MicroPython API
Repository: luxai-qtrobot/magpie-upy · Runtime: MicroPython with asyncio
Language references: Python · C++ · TypeScript / JavaScript · MicroPython
MAGPIE for MicroPython brings the same streaming, request/reply, frame, schema, and MCP concepts to constrained devices. It uses asynchronous APIs and MessagePack by default. The included ZMQ transport communicates directly with Python or C++ MAGPIE peers; optional MQTT also connects boards to brokered systems and browser applications.
Runtime and platform scope
The implementation is transport-independent at its core and has no dependency on a board family. It runs on all MicroPython devices. ZMQ is included in the default package, while MQTT and mqtt_as are installed through a separate manifest; individual features use the runtime capabilities and peripherals exposed by the device.
| Included | Not included in this device package |
|---|---|
| Async streams and RPC over ZMQ | WebRTC transport |
Optional MQTT networking through mqtt_as | Audio frame family |
| Primitive and raw/JPEG image frames | Desktop CLI tools and discovery helpers |
| JSON-RPC and MCP tool server behavior | HTTP MCP server or FastMCP runtime on the board |
The board can serve MCP tools to a desktop FastMCP client through MAGPIE's desktop McpTransport adapter.
Installation
Install mpremote on the development computer, then install the default ZMQ package on the board. Replace COM13 with the board's serial port.
python -m pip install mpremote
mpremote connect COM13 mip install github:luxai-qtrobot/magpie-upy
The default manifest installs the MAGPIE core, ZMQ adapter, and umsgpack. Install the MQTT manifest as well when the board needs MQTT:
mpremote connect COM13 mip install github:luxai-qtrobot/magpie-upy/package-mqtt.json
See Installation for source-checkout installation and platform requirements.
Core asynchronous API
All network operations are asynchronous. The four base operations mirror desktop MAGPIE but must be awaited.
| Class and method | Parameters and return | Behavior |
|---|---|---|
StreamWriter.write(data, topic) | Value and non-empty topic → None | Serializes and publishes one value. Raises RuntimeError after close. |
StreamWriter.close() | → None | Releases writer resources. |
StreamReader.read(timeout=None) | Seconds or None → (value, topic) | Reads and deserializes one value. Raises asyncio.TimeoutError on timeout. |
StreamReader.close() | → None | Releases subscriptions and receive state. |
RpcRequester.call(request, timeout=None) | Raw request → decoded reply | Waits for an ACK and final reply. |
RpcRequester.call(method, _timeout=None, **params) | Method name with a schema → unwrapped result | Builds and unwraps JSON-RPC automatically. |
RpcResponder.respond(handler=None, timeout=None) | Sync/async handler → True; timeout → False | Handles exactly one request. A schema can replace the explicit handler. |
RpcRequester.close() / RpcResponder.close() | → None | Releases component resources and pending state. |
respond() handles one request at a time. Keep calling it from the service loop; use a short timeout when the loop also performs other work.
ZMQ transport
The MicroPython adapter implements the ZMTP 3.0/3.1 wire protocol directly over TCP. It interoperates with desktop MAGPIE's ZeroMQ classes without requiring libzmq on the board.
ZMQ streams
| Class | Public constructor |
|---|---|
ZmqStreamWriter | (endpoint, serializer=None, queue_size=0, bind=True, delivery="reliable", max_message_size=8192, max_peers=4, max_subscriptions=16, max_subscription_bytes=512) |
ZmqStreamReader | (endpoint, topic="", serializer=None, queue_size=4, bind=False, delivery="reliable", max_message_size=8192, max_peers=4) |
topic may be one string or a non-empty list of prefix subscriptions. Call await start() to begin listening or connecting, and await wait_connected(timeout) when startup ordering matters. Both classes reconnect their TCP connection, but the application remains responsible for establishing and restoring Wi-Fi.
from luxai.magpie.transport.zmq import ZmqStreamWriter
writer = ZmqStreamWriter(
"tcp://*:5555",
queue_size=0,
delivery="latest",
)
await writer.start()
await writer.write(
{"temperature": 22.5, "unit": "C"},
"robot/sensors/temperature",
)
await writer.close()
delivery="latest" favors fresh buffered values. delivery="reliable" retains ordinary ZeroMQ PUB/SUB best-effort behavior; it does not guarantee delivery. Inspect dropped when monitoring bounded buffers.
ZMQ RPC
| Class | Public constructor |
|---|---|
ZmqRpcRequester | (endpoint, serializer=None, schema=None, identity=None, ack_timeout=2, reply_timeout=10, max_pending=4, max_message_size=8192) |
ZmqRpcResponder | (endpoint, serializer=None, schema=None, bind=True, queue_size=4, max_peers=4, max_message_size=8192) |
The requester connects as a DEALER. The responder binds as a ROUTER by default and can serve up to max_peers simultaneous TCP peers. Call await start() before traffic, then await close() during shutdown.
from luxai.magpie.transport.zmq import ZmqRpcResponder
server = ZmqRpcResponder("tcp://*:5556")
await server.start()
while True:
await server.respond(
handler=lambda request: {"accepted": True, "request": request},
timeout=1,
)
AckTimeoutError means no responder accepted a request. ReplyTimeoutError means it was acknowledged but did not complete in time. Inspect responder dropped and malformed counters when diagnosing constrained-device traffic.
:::warning Plain ZMQ is for trusted networks
The device adapter uses ZMTP NULL security and does not implement encrypted ZeroMQ mechanisms. Keep its ports on a trusted LAN, behind firewall rules, or inside a protected tunnel.
:::
Optional MQTT transport
MQTT requires the package-mqtt.json manifest and a board supported by mqtt_as.
from luxai.magpie.transport.mqtt import MqttConnection
config = {
"ssid": "YOUR_WIFI",
"wifi_pw": "YOUR_WIFI_PASSWORD",
"server": "broker.example.com",
"port": 1883,
"client_id": b"sensor-01",
}
connection = MqttConnection(config)
await connection.connect()
MqttConnection
MqttConnection(config)
The config dictionary accepts mqtt_as settings, including Wi-Fi, server, port, credentials, TLS, client ID, and reconnect options.
| Method | Purpose |
|---|---|
await connect() | Connects and restores registered subscriptions after reconnect. Returns the connection. |
close() | Closes the client and clears subscriptions. This method is synchronous. |
Create one connection and share it across MQTT streams and RPC components. The application owns it; closing a component never closes the connection.
MQTT streams
| Class | Public constructor and behavior |
|---|---|
MqttStreamWriter | (connection, serializer=None, qos=1, retain=False); publishes immediately without a worker queue. |
MqttStreamReader | (connection, topic, serializer=None, queue_size=4, qos=1); supports exact topics and MQTT wildcards. |
Call await reader.start() before publishers begin when early messages must not be missed. read() starts the subscription lazily as a convenience. A full reader queue drops the oldest item so the consumer receives recent data; inspect reader.dropped to monitor this.
MQTT RPC
| Class | Public constructor |
|---|---|
MqttRpcRequester | (connection, service_name, serializer=None, schema=None, ack_timeout=2, reply_timeout=10, max_pending=4, qos=1) |
MqttRpcResponder | (connection, service_name, serializer=None, schema=None, queue_size=4, qos=1, recent_limit=4, recent_payload_limit=1024) |
The requester publishes to <service>/rpc/req and uses a unique reply topic. The responder sends an immediate ACK, processes one request at a time, and keeps a bounded cache of recent replies for common QoS 1 redeliveries. Handlers should still be idempotent.
Frames
Every frame carries gid, id, name, and timestamp. Available primitive and collection frames are:
BoolFrame, IntFrame, FloatFrame, StringFrame, BytesFrame, DictFrame, and ListFrame.
from luxai.magpie.frames import Frame, IntFrame
first = IntFrame(20)
second = IntFrame(21, gid=first.gid, id=1)
wire_value = second.to_dict()
restored = Frame.from_dict(wire_value)
print(restored.value)
Image frames use the same wire fields as desktop MAGPIE:
| Class | Public constructor |
|---|---|
ImageFrameRaw | (data=b"", format="raw", width=0, height=0, channels=0, pixel_format="", gid=None, id=0, timestamp=None) |
ImageFrameJpeg | (data=b"", format="jpeg", width=0, height=0, channels=0, pixel_format="", gid=None, id=0, timestamp=None) |
from luxai.magpie.frames import ImageFrameJpeg
frame = ImageFrameJpeg(
data=jpeg_bytes,
width=640,
height=480,
channels=3,
pixel_format="RGB",
)
await writer.write(frame, "camera/jpeg")
These classes preserve the supplied bytes and metadata; they do not encode or decode images on the board. Set the transport's max_message_size high enough for the largest expected frame.
| Method | Purpose |
|---|---|
frame.to_dict() | Produces the shared wire-format dictionary. |
Frame.from_dict(data) | Reconstructs a registered frame class by its name. |
Frame.register_type(frame_type) | Registers a custom payload frame class. |
When the board clock is not set, a generated timestamp is "0" rather than a misleading wall-clock value. Plain values can be streamed without a frame wrapper.
Serialization
MsgpackSerializer is the default and implements:
serialize(data) -> bytes
deserialize(data) -> value
To use another wire format, subclass BaseSerializer, implement those methods, and pass the same serializer to every endpoint on that communication path. MessagePack is an interoperable default, not an enforced requirement.
JSON-RPC schema
JsonRpcSchema supplies method registration, request wrapping, dispatch, and response unwrapping.
| Method | Purpose |
|---|---|
register(name, func=None, description=None, input_schema=None, output_schema=None) | Registers metadata and an optional sync/async handler. |
method(...) | Decorator form of register(). |
handler(name) | Attaches a handler to a previously loaded method. |
from_json(definitions) | Creates a schema from a list of shared method definitions. |
wrap(method, params=None) | Builds a JSON-RPC 2.0 request. |
await dispatch(request) | Dispatches a request or batch and returns JSON-RPC replies. |
unwrap(response) | Extracts the result or raises JsonRpcError. |
The compact implementation dispatches schemas but does not run a JSON Schema validation engine. Handlers must still validate device-specific ranges and safety constraints.
MCP tool server
McpSchema(name="magpie", version="1.0.0") extends JsonRpcSchema with initialize, notifications, ping, tools/list, and tools/call.
import gc
from luxai.magpie.schema import McpSchema
from luxai.magpie.transport.zmq import ZmqRpcResponder
schema = McpSchema(name="sensor-01")
schema.register(
"free_memory",
lambda: {"bytes": gc.mem_free()},
description="Return free heap in bytes.",
input_schema={"type": "object", "properties": {}},
output_schema={
"type": "object",
"properties": {"bytes": {"type": "integer"}},
"required": ["bytes"],
},
)
server = ZmqRpcResponder("tcp://*:5556", schema=schema)
await server.start()
while True:
await server.respond(timeout=1)
This exposes MCP tool discovery and calls directly from the board. It does not run an HTTP MCP endpoint; a desktop or agent-side MAGPIE MCP adapter connects the standard MCP client to the ZMQ or MQTT RPC service.
Logging
Logger provides set_level(), set_color(), debug(), info(), warning(), error(), and pretty_print(). Disable color when logs are consumed by a machine or a terminal without ANSI support.
Lifecycle and resource guidance
For ZMQ:
- Construct the reader, writer, requester, or responder with a
tcp://endpoint. - Call
await component.start(). - Await application operations and keep handlers short and cooperative.
- Call
await component.close().
For MQTT:
- Construct one
MqttConnectionand pass it to MQTT components. - Call
await connection.connect(). - Start readers, requesters, and responders before traffic begins.
- Close every component with
await component.close(). - Call the synchronous
connection.close()last.
Defaults are intentionally bounded. ZMQ messages default to 8192 bytes and bound endpoints accept up to four peers. MQTT payloads default to 4096 bytes, reader and responder queues default to four items, and requester concurrency defaults to four calls. Tune these values carefully against available heap rather than copying desktop settings.
The MicroPython source is the canonical signature reference. Continue with the embedded examples for complete device-to-desktop programs.