protocol — OpenMV Protocol Channels
The protocol module exposes the OpenMV host protocol to Python. It allows
the firmware-side protocol stack to be initialized and configured, and lets
user code register custom logical channels backed by a Python object that
implements the channel interface (read, write, size, poll,
etc.).
Example:
import protocol
from protocol import CBORChannel
protocol.init()
def on_read(ch):
ch["temp"] = read_temp()
def on_write(ch, name, value):
if name == "mirror":
set_mirror(value)
ch = CBORChannel(on_read=on_read, on_write=on_write)
ch.add("temp", type="label", unit="Cel")
ch.add("mirror", type="toggle")
handle = protocol.register(name="sensors", backend=ch)
Functions
- protocol.init(crc: bool = True, seq: bool = True, ack: bool = True, events: bool = True, max_payload: int = OMV_PROTOCOL_MAX_PAYLOAD_SIZE, rtx_retries: int = OMV_PROTOCOL_DEF_RTX_RETRIES, rtx_timeout_ms: int = OMV_PROTOCOL_DEF_RTX_TIMEOUT_MS, lock_interval_ms: int = OMV_PROTOCOL_MIN_LOCK_INTERVAL_MS, poll_ms: int = 0) None
Initialize the protocol stack and register the default logical data channels (
stdin,stdout,streamand, if compiled in,profile). RaisesRuntimeErrorif initialization fails.crcenables CRC validation on protocol frames.seqenables sequence number tracking.ackenables per-frame acknowledgements.eventsenables channel event notifications.max_payloadis the maximum payload size in bytes.rtx_retriesis the number of retransmission attempts.rtx_timeout_msis the retransmission timeout in milliseconds.lock_interval_msis the minimum lock interval in milliseconds.poll_msis the polling interval in milliseconds (0disables timer polling).
- protocol.is_active() bool
Return
Trueif a host is currently connected and the protocol stack is active, otherwiseFalse.
- protocol.register(name: str, backend: object, flags: int = 0) ProtocolChannel
Register a Python
backendobject as a new logical channel and return aProtocolChannelhandle. Thebackendobject’s available methods (see Backend Interface below) determine the channel’s capabilities;protocol.CHANNEL_FLAG_READ,protocol.CHANNEL_FLAG_WRITEandprotocol.CHANNEL_FLAG_LOCKare added toflagsautomatically when the corresponding methods are implemented.nameis the channel name as a string. Truncated to the firmware’s channel-name buffer size.backendis the Python object implementing the backend interface.flagsis additional channel flag bits (see theCHANNEL_FLAG_*constants).Raises
RuntimeErrorif the channel cannot be registered (e.g. no free channel slots).
Classes
- class protocol.ProtocolChannel
Handle returned by
protocol.register. Instances are not constructed directly.
Backend Interface
A backend object passed to protocol.register may implement any subset of
the following methods. Only the methods present on the object are wired to
the C protocol layer; missing methods leave the corresponding capability
disabled.
- class protocol.backend
Channel backend object passed to
protocol.register. The methods below describe the optional interface a Python backend may implement.- init() object
Called once when the channel is initialized. Return any non-
Nonevalue on success; an exception or missing return is treated as an error.
- poll() bool
Return
Trueif the channel has data ready to be read by the host.
- lock() bool
Acquire the channel for a transfer. Return
Trueon success.
- unlock() bool
Release the channel after a transfer. Return
Trueon success.
- size() int
Return the number of bytes currently readable from the channel.
- shape() tuple
Return a tuple of up to four integers describing the data shape (e.g. image dimensions). Up to four elements are consumed by the protocol layer.
- flush() object
Flush any pending data. Return any non-
Nonevalue on success.
- read(offset: int, size: int) bytes
Return up to
sizebytes starting atoffsetas abytes-like object that supports the buffer protocol.
- readp(offset: int, size: int) bytes
Zero-copy variant of
read. Returns a buffer whose underlying memory is read directly by the protocol layer; the buffer must remain valid for the duration of the transfer.
- write(offset: int, data: bytearray) int
Write
dataatoffset.datais abytearrayreferencing the C buffer directly. Return the number of bytes written, or0on default success.
- ioctl(cmd: int, length: int, arg: bytearray | None) int
Handle an ioctl.
argisNoneiflengthis zero, otherwise abytearrayreferencing the C buffer. Return0orNoneon success, or a negative integer on error.
- is_active() bool
For transport channels, return
Trueif the underlying transport is currently connected.
- class protocol.CBORChannel(on_read: Callable | None = None, on_write: Callable | None = None)
A higher-level Python backend (provided by the frozen
protocolpackage) that serializes named fields to CBOR using SenML-compatible integer keys. Supports display widgets (label,depth) and interactive controls (toggle,slider,select) withon_read/on_writecallbacks.on_readis an optional callableon_read(channel)invoked before the channel is serialized for the host. Use it to refresh field values.on_writeis an optional callableon_write(channel, name, value)invoked when the host writes a new value for a named field.- add(name: str, type: str, value: Any = None, unit: str | None = None, min: int | float | None = None, max: int | float | None = None, step: int | float | None = None, options: list | None = None, width: int | None = None, height: int | None = None) None
Add a named field to the channel.
nameis the display name; must be unique within this channel.typeis the widget type:"label","toggle","slider","select", or"depth".valueis the initial value. The default depends ontype.unitis the unit string forlabel/slider(e.g."Cel","%RH").minis the minimum value (slider range or depth range).maxis the maximum value (slider range or depth range).stepis the step size (slider).optionsis the list of option strings (select).widthis the pixel width (depth).heightis the pixel height (depth).
- __getitem__(name: str) object
Return the current value of the named field. For
depthfields the binary data buffer is returned, otherwise the scalar value.
- __setitem__(name: str, value: Any) None
Set the value of the named field. For
sliderfields, a(min, max, value)tuple updates the range and current value simultaneously. Fordepthfields,valueis the binary data buffer.
- size() int
Backend interface method. Invokes
on_read(if set) and returns the size of the serialized buffer.
Constants
Channel flag bits (combined bitwise; passed to protocol.register via
flags or set automatically based on the backend’s methods).
- protocol.CHANNEL_FLAG_PHYSICAL: int
The channel represents a physical transport (as opposed to a logical data channel).
Built-in channel identifiers.