The lpf2 module

LEGO Powered-Up / LPF2 protocol primitives.

Layout

Submodule

What lives there

lpf2 (top level)

lpf2.port, lpf2.mode, lpf2.version, lpf2.device_descriptor, lpf2.hub (BLE client), lpf2.hub_emulation (BLE server), lpf2.battery, lpf2.motor_setting.

lpf2.local

lpf2.local.port — the concrete port class for on-hub UART sockets.

lpf2.virtual

lpf2.virtual.port and lpf2.virtual.device — emulate a device in Python.

lpf2.devices

Typed device wrappers returned by lpf2.port.device(): basic_motor, encoder_motor, color_sensor, distance_sensor, color_distance_sensor, hub_led, accelerometer, gyroscope, port_expander.

lpf2.port_expander

Port expander helpers (sub-port numbering, virtual device).

Enums

lpf2.color, lpf2.device_type, lpf2.hub_type, lpf2.alerts, lpf2.battery_type, lpf2.button_state, lpf2.hub_property, lpf2.port_num.

Design notes

Every user-visible lpf2 type is a MicroPython wrapper around a C++ object. The wrappers hold mp_obj_t anchors to related Python objects (attached devices, descriptors, port references) so the GC does not collect them while the C++ side still references them.

Automatic polling

Every lpf2 class whose C++ base has an update() method (currently: lpf2.hub, all lpf2.port subclasses, lpf2.virtual.device, lpf2.port_expander.virtual_device) adds itself to a C-side registry at construction time. The firmware main loop calls every registered update() each tick, so you do not need to call ``update()`` from Python — device detection, transport pumping and value parsing all happen in the background. Deleting the Python wrapper (__del__) removes the object from the registry.

Built-in local ports (hub.ports.A/B/C/D and the wrapped built-ins) are constructed on the C++ side and are also pumped by the update() registry — same net effect.

Subclassing

lpf2.virtual.device is designed to be subclassed. Overrides run on the Python side via a C++ trampoline. Default implementations call the C++ default non-virtually so super().startPower(pw) is safe (no infinite recursion).

See Virtual devices for the pattern.