Skip to content

Commit

Permalink
pybricksdev.connections.pybricks: make line handler optional
Browse files Browse the repository at this point in the history
Long running programs may want to ignore stdout from the hub instead of
maintaining an infinite log. We also plan on adding an optional stdout
subscription that is an alternative to the line handler. So in these
cases, it is desireable to disable the default line handler.
  • Loading branch information
dlech committed Apr 21, 2023
1 parent dd50822 commit 33056f4
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions pybricksdev/connections/pybricks.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ def __init__(self):
self._capability_flags = HubCapabilityFlag(0)
self._max_user_program_size = 0

# whether to enable line handler features or not
self._enable_line_handler = False

# buffered stdout from the hub for splitting into lines
self._stdout_buf = bytearray()

Expand Down Expand Up @@ -198,15 +201,19 @@ def _nus_handler(self, sender, data: bytearray) -> None:
# support legacy firmware where the Nordic UART service
# was used for stdio
if self._legacy_stdio:
self._handle_line_data(data)
if self._enable_line_handler:
self._handle_line_data(data)

def _pybricks_service_handler(self, _: int, data: bytes) -> None:
if data[0] == Event.STATUS_REPORT:
# decode the payload
(flags,) = struct.unpack_from("<I", data, 1)
self.status_observable.on_next(StatusFlag(flags))
elif data[0] == Event.WRITE_STDOUT:
self._handle_line_data(data[1:])
payload = data[1:]

if self._enable_line_handler:
self._handle_line_data(payload)

async def connect(self, device: BLEDevice):
"""Connects to a device that was discovered with :meth:`pybricksdev.ble.find_device`
Expand Down Expand Up @@ -422,7 +429,11 @@ async def stop_user_program(self) -> None:
)

async def run(
self, py_path: str, wait: bool = True, print_output: bool = True
self,
py_path: str,
wait: bool = True,
print_output: bool = True,
line_handler: bool = True,
) -> None:
"""
Compiles and runs a user program.
Expand All @@ -431,6 +442,7 @@ async def run(
py_path: The path to the .py file to compile.
wait: If true, wait for the user program to stop before returning.
print_output: If true, echo stdout of the hub to ``sys.stdout``.
line_handler: If true enable hub stdout line handler features.
"""
if self.connection_state_observable.value != ConnectionState.CONNECTED:
raise RuntimeError("not connected")
Expand All @@ -442,6 +454,7 @@ async def run(
self._stdout_line_queue = asyncio.Queue()
self.print_output = print_output
self.script_dir, _ = os.path.split(py_path)
self._enable_line_handler = line_handler

# maintain compatibility with older firmware (Pybricks profile < 1.2.0).
if self._mpy_abi_version:
Expand Down

0 comments on commit 33056f4

Please sign in to comment.