harp-serial#
Serial transport for harp-device. Provides SerialTransport and the open_device factory, which pairs a device module or a Device class with a serial port. This is the package that pulls in pyserial.
Usage#
Like the builtin open, the returned device is connected and ready. Use it in a with block for guaranteed cleanup:
from harp import serial
from harp.device import behavior, core
# Use "COMx" on Windows, "/dev/ttyUSBx" on Linux.
with serial.open_device(behavior, port="COM3") as device:
print(device.read(core.WhoAmI).payload) # a core register
print(device.read(behavior.AnalogData).payload) # a device register
Passing a device module validates the device identity on open. Pass a Device subclass instead to preserve its own type, or omit the argument entirely for schema-free access, which skips the identity check.
harp-serial is released as open source under the MIT license. Bug reports and contributions are welcome at the GitHub repository.
harp.serial.SerialTransport
#
A serial-port :class:~harp.device.client.ITransport (structural conformance).
harp.serial.open_device(device_or_module=None, *, port, baudrate=DEFAULT_BAUDRATE, raise_on_error=True)
#
open_device(
device_or_module: type[D],
*,
port: str,
baudrate: int = ...,
raise_on_error: bool = ...,
) -> D
Build a :class:~harp.device.client.Device over a serial transport and open it.
Accepts either a device module or a :class:~harp.device.client.Device subclass:
-
Module (preferred): validates identity on open::
from harp.device import behavior, core
with open_device(behavior, port="COM3") as dev: dev.read(core.WhoAmI) # a core register dev.read(behavior.AnalogData) # declared by the schema
-
Device subclass: instantiates the subclass directly, preserving its type::
with open_device(MyBehavior, port="COM3") as dev: dev.arm() # method defined on MyBehavior
Omit the first argument for schema-free access, which skips the identity check.
Like the builtin :func:open, the returned device is already connected; use it
directly or in a with block for guaranteed close.