### Install and verify pybricksdev Source: https://context7.com/pybricks/pybricksdev/llms.txt Use pipx or pip to install the package and verify the installation. ```bash # Install pybricksdev using pipx (recommended) pipx install pybricksdev # Or install using pip pip install pybricksdev --pre # Check version pybricksdev --version # Get help for available commands pybricksdev --help ``` -------------------------------- ### Build and install changes Source: https://github.com/pybricks/pybricksdev/blob/master/CONTRIBUTING.md Builds the package and installs it globally using pipx. ```bash poetry build pipx install --force ./dist/pybricksdev-1.0.0a19.tar.gz ``` -------------------------------- ### Start LWP3 REPL Source: https://context7.com/pybricks/pybricksdev/llms.txt Open an interactive session to send LWP3 commands directly to a hub. ```bash # Start LWP3 REPL session pybricksdev lwp3 repl ``` -------------------------------- ### Abstract Virtual Port Setup Message Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/messages.md Abstract base class for messages related to virtual port setup commands. ```APIDOC ## AbstractVirtualPortSetupMessage ### Description Abstract base class for messages related to virtual port setup commands. ### Parameters * **length** (int) - The length of the message. * **command** (VirtualPortSetupCommand) - The virtual port setup command. ### Properties * **command** (VirtualPortSetupCommand) - The virtual port setup command. ``` -------------------------------- ### Install pybricksdev as a library with pip Source: https://github.com/pybricks/pybricksdev/blob/master/README.md Install pybricksdev using pip, typically within a virtual environment. The --pre flag installs pre-release versions. ```bash pip install pybricksdev --pre ``` -------------------------------- ### Install pybricksdev using Python Launcher on Windows Source: https://github.com/pybricks/pybricksdev/blob/master/README.md For Windows users, use 'py -3' with the Python Launcher to install pipx and then pybricksdev. ```bash py -3 -m pip install --upgrade pip py -3 -m pip install pipx pix run pybricksdev ... ``` -------------------------------- ### Clone and setup development environment Source: https://github.com/pybricks/pybricksdev/blob/master/CONTRIBUTING.md Commands to clone the repository, configure the Python environment with Poetry, and open the project in VS Code. ```bash git clone https://github.com/pybricks/pybricksdev cd pybricksdev poetry env use python3.12 poetry install code . ``` -------------------------------- ### Install pybricksdev as a library with Poetry Source: https://github.com/pybricks/pybricksdev/blob/master/README.md Install pybricksdev within a virtual environment managed by Poetry. It's recommended to use a specific Python version. ```bash poetry env use python3.12 poetry add pybricksdev ``` -------------------------------- ### Start Jupyter notebook servers Source: https://github.com/pybricks/pybricksdev/blob/master/README.notebooks.md Commands to launch either the classic notebook server or the modern JupyterLab interface. ```bash jupyter notebook ``` ```bash jupyter lab ``` -------------------------------- ### PortFormatSetupComboMessage Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/messages.md Configures a combo mode setup for a specific port. ```APIDOC ## PortFormatSetupComboMessage ### Description Configures the combo modes and datasets for a given port. ### Parameters #### Request Body - **port** (PortID) - Required - The port identifier. - **modes_and_datasets** (list[tuple[int, int]]) - Required - A list of mode and dataset pairs. ``` -------------------------------- ### Port Input Format Setup Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/messages.md Sets up the input format for a specific port mode, including delta and notification settings. ```APIDOC ## PortInputFormatSetupMessage ### Description Sets up the input format for a specific port mode, including delta and notification settings. ### Parameters #### Path Parameters - **port** (PortID) - Required - The port to configure. - **mode** (int) - Required - The mode to configure. - **delta** (int) - Required - The delta value for notifications. - **notify** (bool) - Required - Whether to enable notifications. ``` -------------------------------- ### Install pybricksdev with pipx Source: https://github.com/pybricks/pybricksdev/blob/master/README.md Use pipx to install pybricksdev for command-line usage. This ensures you are always running the latest version. ```bash pipx install pybricksdev ``` -------------------------------- ### Virtual Port Setup Messages Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/messages.md Messages for connecting and disconnecting virtual ports. ```APIDOC ## VirtualPortSetupConnectMessage - **port_a** (PortID) - Required - **port_b** (PortID) - Required ## VirtualPortSetupDisconnectMessage - **port** (PortID) - Required ``` -------------------------------- ### Run pybricksdev command Source: https://github.com/pybricks/pybricksdev/blob/master/README.md After installing with pipx, you can run pybricksdev commands directly. ```bash pybricksdev run ... ``` -------------------------------- ### Flash Pybricks Firmware to SPIKE Prime Source: https://github.com/pybricks/pybricksdev/blob/master/README_dfu.rst Flash the Pybricks firmware to the SPIKE Prime Hub. Ensure the hub is in DFU mode. Replace the example path with the actual path to your firmware archive. ```bash pybricksdev flash ../pybricks-micropython/bricks/primehub/build/firmware.zip ``` -------------------------------- ### Download Pybricks MicroPython program via Bluetooth without starting Source: https://github.com/pybricks/pybricksdev/blob/master/README.md Download a MicroPython script to a Pybricks device via Bluetooth but do not execute it immediately. ```bash pipx run pybricksdev run ble demo/shortdemo.py --no-start ``` -------------------------------- ### Upgrade pybricksdev with pipx Source: https://github.com/pybricks/pybricksdev/blob/master/README.md Check for and install updates to pybricksdev when installed with pipx. ```bash pipx upgrade pybricksdev ``` -------------------------------- ### Download Programs to Hub Without Running Source: https://context7.com/pybricks/pybricksdev/llms.txt Upload a compiled program to the hub without starting it using the `download` method. Useful for storing programs. ```python import asyncio from pybricksdev.ble import find_device from pybricksdev.connections.pybricks import PybricksHubBLE async def main(): device = await find_device() hub = PybricksHubBLE(device) await hub.connect() try: # Download script to hub without running await hub.download("my_program.py") print("Program downloaded successfully") # Later, start the downloaded program await hub.start_user_program() # Or stop a running program await hub.stop_user_program() finally: await hub.disconnect() asyncio.run(main()) ``` -------------------------------- ### Run Pybricks MicroPython program via Bluetooth Source: https://github.com/pybricks/pybricksdev/blob/master/README.md Compile and run a MicroPython script on a Pybricks device using Bluetooth. This example runs on any available device. ```bash pipx run pybricksdev run ble demo/shortdemo.py ``` -------------------------------- ### Generate Linux udev rules for pybricksdev Source: https://github.com/pybricks/pybricksdev/blob/master/README.md On Linux, generate and install udev rules to allow USB access for pybricksdev. This command requires sudo privileges. ```bash pipx run pybricksdev udev | sudo tee /etc/udev/rules.d/99-pybricksdev.rules ``` -------------------------------- ### Run Pybricks MicroPython program via USB Source: https://github.com/pybricks/pybricksdev/blob/master/README.md Compile and run a MicroPython script on a Pybricks device connected via USB. This example runs on any detected USB device. ```bash pipx run pybricksdev run usb demo/shortdemo.py ``` -------------------------------- ### Inject custom dependency Source: https://github.com/pybricks/pybricksdev/blob/master/CONTRIBUTING.md Adds a custom dependency to the installed pybricksdev package using pipx. ```bash pipx inject pybricksdev https://github.com/hbldh/bleak/archive/refs/heads/develop.zip ``` -------------------------------- ### Construct and parse LWP3 messages Source: https://context7.com/pybricks/pybricksdev/llms.txt Demonstrates how to create property requests, set hub properties, send actions, and parse incoming byte messages using the lwp3 module. ```python from pybricksdev.ble.lwp3.bytecodes import ( HubKind, HubProperty, HubPropertyOperation, HubAction, MessageKind, StatusFlag ) from pybricksdev.ble.lwp3.messages import ( HubPropertyMessage, HubActionMessage, parse_message ) # Create a message to request hub name msg = HubPropertyMessage( HubProperty.NAME, HubPropertyOperation.REQUEST_UPDATE ) print(f"Request name message: {msg.bytes.hex()}") # Create a message to set hub name msg = HubPropertyMessage( HubProperty.NAME, HubPropertyOperation.SET, b"MyHub" ) # Create a power off command msg = HubActionMessage(HubAction.POWER_OFF) # Parse incoming message bytes data = bytes([0x05, 0x00, 0x01, 0x01, 0x06]) # Hub property update parsed = parse_message(data) print(f"Message type: {parsed}") # Hub kinds for identification print(f"SPIKE Prime hub ID: {HubKind.TECHNIC_LARGE}") # 0x81 print(f"SPIKE Essential hub ID: {HubKind.TECHNIC_SMALL}") # 0x83 print(f"BOOST Move Hub ID: {HubKind.BOOST}") # 0x40 ``` -------------------------------- ### Create Firmware Blobs with pybricksdev Source: https://context7.com/pybricks/pybricksdev/llms.txt Generates customized firmware images from a zip file, optionally setting a hub name. ```python import asyncio from pybricksdev.firmware import create_firmware_blob async def main(): # Create firmware blob with default settings firmware, metadata, license_text = await create_firmware_blob( "pybricks-firmware.zip" ) print(f"Firmware size: {len(firmware)} bytes") print(f"Device ID: {metadata['device-id']}") print(f"Firmware version: {metadata['firmware-version']}") # Create firmware with custom hub name firmware, metadata, license_text = await create_firmware_blob( "pybricks-firmware.zip", name="My Robot" ) # Save to file for manual flashing with open("custom_firmware.bin", "wb") as f: f.write(firmware) asyncio.run(main()) ``` -------------------------------- ### Perform DFU operations Source: https://context7.com/pybricks/pybricksdev/llms.txt Manage firmware backups and system configuration for supported hubs. ```bash # Backup current firmware via DFU pybricksdev dfu backup backup.bin # Restore firmware from backup pybricksdev dfu restore backup.bin # Linux: Generate udev rules for USB access pybricksdev udev | sudo tee /etc/udev/rules.d/99-pybricksdev.rules ``` -------------------------------- ### Firmware Management Module Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/index.md Handles firmware metadata and blob creation for Pybricks firmware files. ```APIDOC ## Firmware Module ### Description Provides structures for parsing and creating firmware metadata and blobs for various Pybricks firmware versions. ### Components - **Metadata Classes**: Includes AnyFirmwareMetadata, AnyFirmwareV1Metadata, AnyFirmwareV2Metadata, and specific versions (V100, V110, V200, V210). - **create_firmware_blob()**: Function to generate a firmware blob from metadata. ``` -------------------------------- ### create_firmware_blob Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/firmware.md Creates a firmware blob from a base firmware zip file and an optional custom hub name. ```APIDOC ## create_firmware_blob ### Description Creates a firmware blob from base firmware and an optional custom name. The input must be a zip file containing firmware-base.bin, firmware.metadata.json, and ReadMe_OSS.txt. ### Parameters - **firmware_zip** (str | PathLike | BinaryIO) - Required - Path to the firmware zip file or a file-like object. - **name** (str | None) - Optional - A custom name for the hub. ### Response - **Returns** (tuple[bytes, AnyFirmwareMetadata, str]) - A tuple containing the composite binary blob for flashing, the metadata object, and the license text. ### Errors - **ValueError** - Raised if a name is provided but the firmware does not support it or the name exceeds the allotted space. ``` -------------------------------- ### Run a script on a Hub Source: https://github.com/pybricks/pybricksdev/blob/master/CONTRIBUTING.md Executes a Python script on a connected Hub using the pybricksdev CLI via Poetry. ```bash poetry run pybricksdev run ble test.py ``` -------------------------------- ### Backup Original SPIKE Prime Firmware Source: https://github.com/pybricks/pybricksdev/blob/master/README_dfu.rst Use this command to back up the original firmware before flashing Pybricks. Ensure the hub is in DFU mode. The path specifies where to save the backup file. ```bash pybricksdev dfu backup /path/to/original/firmware.bin ``` -------------------------------- ### Flash firmware to hubs Source: https://context7.com/pybricks/pybricksdev/llms.txt Update hub firmware using the flash command, which handles discovery and bootloader transitions. ```bash # Flash firmware to any discovered hub pybricksdev flash firmware.zip # Flash firmware with custom hub name pybricksdev flash --name "My Robot" firmware.zip ``` -------------------------------- ### Bootloader Commands Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/bootloader.md List of commands that can be sent to the bootloader GATT characteristic to manage firmware flashing. ```APIDOC ## Bootloader Commands ### Description Commands sent to the bootloader GATT characteristic to control the hub's flash memory and firmware state. ### Commands - **DISCONNECT** (136) - Causes the remote device to disconnect from Bluetooth. - **ERASE_FLASH** (17) - Erases the flash memory. - **GET_CHECKSUM** (102) - Gets the current checksum for the data that has been written so far. - **GET_FLASH_STATE** (119) - Gets the STM32 flash memory debug protection state (not supported by all bootloaders). - **GET_INFO** (85) - Gets info about the hub and flash memory layout. - **INIT_LOADER** (68) - Initializes the firmware flasher. - **PROGRAM_FLASH** (34) - Writes to a segment of the flash memory. - **START_APP** (51) - Starts running the firmware (causes Bluetooth to disconnect). ``` -------------------------------- ### Hardware Network Commands Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/bytecodes.md Commands for creating hub-to-hub connections. ```APIDOC ## HwNetCmd ### Description Hardware network commands for creating hub-to-hub connections. ### Enum Values - **CONNECTION_REQUEST** (2): Routes a connection request from a peripheral device to the controlling Central device. - **FAMILY_REQUEST** (3): Requests a new Family and SubFamily from any device in the H/W network. - **FAMILY_SET** (4): Sets the new family from the controlling Central device. - **JOIN_DENIED** (5): Sent to a peripheral when the maximum number of nodes is reached. - **GET_FAMILY** (6): Requests the previously used Family for a specific device. - **FAMILY** (7): The answer returned for `GET_FAMILY` command. - **GET_SUBFAMILY** (8): Requests the previously used SubFamily for a specific device. - **SUBFAMILY** (9): The answer returned for `GET_SUBFAMILY` command. - **SUBFAMILY_SET** (10): Sets the new SubFamily from the controlling Central device. - **GET_EXTENDED_FAMILY** (11): Requests the previously used Family and SubFamily for a specific device. - **EXTENDED_FAMILY** (12): The answer returned for `GET_EXTENDED_FAMILY` command. - **EXTENDED_FAMILY_SET** (13): Sets both the Family and the SubFamily. - **RESET_LONG_PRESS** (14): Resets the timing of the user CONNECTION PRESS. ``` -------------------------------- ### Flash firmware via BLE Bootloader Source: https://context7.com/pybricks/pybricksdev/llms.txt Uses the BootloaderConnection class to flash firmware to a hub in bootloader mode. Requires the hub to be manually placed in bootloader mode before execution. ```python import asyncio from bleak import BleakScanner from pybricksdev.flash import BootloaderConnection from pybricksdev.firmware import create_firmware_blob async def main(): # Find hub in bootloader mode (hold button while inserting batteries) # Bootloader service UUID: 00001626-1212-efde-1623-785feabcd123 device = await BleakScanner.find_device_by_filter( lambda d, ad: "00001626-1212-efde-1623-785feabcd123" in ad.service_uuids ) if not device: print("No hub in bootloader mode found") return # Create firmware blob firmware, metadata, _ = await create_firmware_blob("firmware.zip") # Connect and flash bootloader = BootloaderConnection() await bootloader.connect(device) try: await bootloader.flash(firmware, metadata) print("Firmware flashed successfully!") finally: await bootloader.disconnect() asyncio.run(main()) ``` -------------------------------- ### LWPVersion Class Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/bytecodes.md Represents the LEGO Wireless Protocol version and provides parsing functionality. ```APIDOC ## LWPVersion ### Description The LEGO Wireless Protocol (LWP) version class. ### Properties - **major** (int) - Gets the major version component. - **minor** (int) - Gets the minor version component. ### Methods #### parse(version: str) -> LWPVersion - **version** (str) - Required - Parses a string with the format `XX.XX`. ``` -------------------------------- ### Run programs via USB Source: https://context7.com/pybricks/pybricksdev/llms.txt Execute scripts on compatible hubs connected via USB serial ports. ```bash # Run a script on any available Pybricks hub via USB pybricksdev run usb demo/shortdemo.py # Run with specific serial port pybricksdev run usb --name /dev/ttyACM0 demo/shortdemo.py # Download without starting pybricksdev run usb --no-start demo/shortdemo.py ``` -------------------------------- ### Enable widgets extension Source: https://github.com/pybricks/pybricksdev/blob/master/README.notebooks.md Enables the widgets extension for progress bars in classic Jupyter notebooks. ```bash jupyter nbextension enable --py widgetsnbextension ``` -------------------------------- ### I/O Device Capabilities Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/bytecodes.md Flags for sensor capabilities. ```APIDOC ## IODeviceCapabilities ### Description Sensor capabilities flags. (48-bit) ### Constants - **names** (0) ``` -------------------------------- ### Flash Pybricks MicroPython firmware Source: https://github.com/pybricks/pybricksdev/blob/master/README.md Use the pybricksdev command line tool to flash MicroPython firmware onto a Pybricks device. Replace with the path to your firmware file. ```bash pipx run pybricksdev flash ``` -------------------------------- ### LWP3 Port and System Bytecodes Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/bytecodes.md Definitions for port input/output messages, mode information requests, and system-level enumerations. ```APIDOC ## LWP3 Message Bytecodes ### Description List of message bytecodes used for port configuration, data updates, and output command execution. ### Bytecodes - **PORT_INPUT_FMT_SETUP_COMBO** (66) - Set up input format for a mode combo. - **PORT_MODE_INFO** (68) - Reply to a PORT_MODE_INFO_REQ. - **PORT_MODE_INFO_REQ** (34) - Request mode information. - **PORT_OUTPUT_CMD** (129) - Execute port output commands. - **PORT_OUTPUT_CMD_FEEDBACK** (130) - Indicate port output command completion. - **PORT_VALUE** (69) - Value update from a single mode. - **PORT_VALUE_COMBO** (70) - Value update from a mode combo. - **VIRTUAL_PORT_SETUP** (97) - Set up virtual port for port synchronization. ``` -------------------------------- ### Compile Pybricks MicroPython program to console Source: https://github.com/pybricks/pybricksdev/blob/master/README.md Compile a MicroPython script or string and print the resulting bytecode to the console without flashing or running it on a device. ```bash pipx run pybricksdev compile demo/shortdemo.py ``` ```bash pipx run pybricksdev compile "print('Hello!'); print('world!');" ``` -------------------------------- ### Run programs via Bluetooth Low Energy Source: https://context7.com/pybricks/pybricksdev/llms.txt Execute scripts on hubs over BLE with options for device targeting and connection persistence. ```bash # Run a script on any available Pybricks hub via BLE pybricksdev run ble demo/shortdemo.py # Run on a specific hub by name pybricksdev run ble --name "Pybricks Hub" demo/shortdemo.py # Run on a specific hub by Bluetooth address (Linux/Windows) pybricksdev run ble --name 90:84:2B:4A:2B:75 demo/shortdemo.py # Download script without starting it pybricksdev run ble --no-start demo/shortdemo.py # Stay connected after program ends (interactive menu) pybricksdev run ble --stay-connected demo/shortdemo.py # Don't wait for program to complete pybricksdev run ble --no-wait demo/shortdemo.py # Run from stdin cat demo/shortdemo.py | pybricksdev run ble - ``` -------------------------------- ### Monitor Hub Status and Events Source: https://context7.com/pybricks/pybricksdev/llms.txt Uses PybricksHubBLE to subscribe to connection states, status flags, and stdout data from the hub. ```python import asyncio from pybricksdev.ble import find_device from pybricksdev.connections.pybricks import PybricksHubBLE from pybricksdev.ble.pybricks import StatusFlag from pybricksdev.connections import ConnectionState async def main(): device = await find_device() hub = PybricksHubBLE(device) # Subscribe to connection state changes hub.connection_state_observable.subscribe( lambda state: print(f"Connection state: {state}") ) # Subscribe to hub status updates def on_status(flags: StatusFlag): if flags & StatusFlag.USER_PROGRAM_RUNNING: print("Program is running") if flags & StatusFlag.BATTERY_LOW_VOLTAGE_WARNING: print("Battery low!") if flags & StatusFlag.POWER_BUTTON_PRESSED: print("Button pressed") hub.status_observable.subscribe(on_status) # Subscribe to stdout from hub hub.stdout_observable.subscribe( lambda data: print(f"Hub says: {data.decode()}", end="") ) await hub.connect() try: await hub.run("demo/shortdemo.py", wait=True, print_output=False) finally: await hub.disconnect() asyncio.run(main()) ``` -------------------------------- ### Port Output Commands Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/bytecodes.md Enumeration of available commands for controlling port outputs. ```APIDOC ## PortOutputCommand ### Description Enumeration of commands that can be sent to a port to control motors or other output devices. ### Commands - **START_POWER** (1), **START_POWER_2** (2) - **SET_ACC_TIME** (5), **SET_DEC_TIME** (6) - **START_SPEED** (7), **START_SPEED_2** (8) - **START_SPEED_FOR_TIME** (9), **START_SPEED_FOR_TIME_2** (10) - **START_SPEED_FOR_DEGREES** (11), **START_SPEED_FOR_DEGREES_2** (12) - **GOTO_ABS_POS** (13), **GOTO_ABS_POS_2** (14) - **PRESET_ENCODER** (19), **PRESET_ENCODER_2** (20) - **WRITE_DIRECT** (80), **WRITE_DIRECT_MODE_DATA** (81) ``` -------------------------------- ### Run Pybricks MicroPython program on named Bluetooth device Source: https://github.com/pybricks/pybricksdev/blob/master/README.md Execute a MicroPython script on a specific Pybricks device identified by its name. ```bash pipx run pybricksdev run ble --name "Pybricks Hub" demo/shortdemo.py ``` -------------------------------- ### Manage firmware via USB DFU Source: https://context7.com/pybricks/pybricksdev/llms.txt Provides functions for flashing, backing up, and restoring firmware on SPIKE and MINDSTORMS hubs via USB. The hub must be in DFU mode during the flash operation. ```python from pybricksdev.dfu import flash_dfu, backup_dfu, restore_dfu from pybricksdev.firmware import create_firmware_blob import asyncio async def main(): # Create firmware blob firmware, metadata, _ = await create_firmware_blob("firmware.zip") # Flash via DFU (hub must be in DFU mode - hold button during USB connect) flash_dfu(firmware, metadata) # Backup current firmware def backup_firmware(): with open("backup.bin", "wb") as f: backup_dfu(f) # Restore from backup def restore_firmware(): with open("backup.bin", "rb") as f: restore_dfu(f) asyncio.run(main()) ``` -------------------------------- ### Connect to Pybricks Hub via BLE Source: https://context7.com/pybricks/pybricksdev/llms.txt Connect to a Pybricks hub using the PybricksHubBLE class. Allows running scripts and accessing hub output. ```python import asyncio from pybricksdev.ble import find_device from pybricksdev.connections.pybricks import PybricksHubBLE async def main(): # Find and connect to a hub device = await find_device(name="Pybricks Hub") hub = PybricksHubBLE(device) await hub.connect() print(f"Connected! Firmware version: {hub.fw_version}") try: # Run a script and wait for completion await hub.run("demo/shortdemo.py", wait=True) # Access captured output for line in hub.output: print(f"Hub output: {line.decode()}") finally: await hub.disconnect() asyncio.run(main()) ``` -------------------------------- ### Write to Hub stdin Source: https://context7.com/pybricks/pybricksdev/llms.txt Sends raw bytes, strings, or lines to a running program on the hub via stdin. ```python import asyncio from pybricksdev.ble import find_device from pybricksdev.connections.pybricks import PybricksHubBLE async def main(): device = await find_device() hub = PybricksHubBLE(device) await hub.connect() try: # Start an interactive program await hub.run("interactive_program.py", wait=False, line_handler=True) # Write raw bytes to stdin await hub.write(b"raw data") # Write a string (automatically chunked for BLE) await hub.write_string("Hello from PC") # Write a line with newline appended await hub.write_line("command") # Read a line from hub stdout response = await hub.read_line() print(f"Hub responded: {response}") finally: await hub.disconnect() asyncio.run(main()) ``` -------------------------------- ### PortInputFormatMessage Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/messages.md Sets the input format for a specific port. ```APIDOC ## PortInputFormatMessage ### Description Configures the input format, including mode, delta, and notification settings for a port. ### Parameters #### Request Body - **port** (PortID) - Required - The port identifier. - **mode** (int) - Required - The input mode. - **delta** (int) - Required - The delta value. - **notify** (bool) - Required - Whether to enable notifications. ``` -------------------------------- ### I/O Device Kind Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/bytecodes.md Enumerates the types of attached I/O devices. ```APIDOC ## IODeviceKind ### Description The kind of attached I/O device. ### Enum Values - **BOOST_COLOR_DISTANCE_SENSOR** (37): BOOST Color and Distance Sensor - **BOOST_HUB_ACCEL** (40): BOOST Move Hub built-in accelerometer (tilt sensor). - **BOOST_HUB_MOTOR** (39): BOOST Move Hub built-in motor. ``` -------------------------------- ### Restore Original SPIKE Prime Firmware Source: https://github.com/pybricks/pybricksdev/blob/master/README_dfu.rst Restore the original firmware to the SPIKE Prime Hub using a previously created backup file. Ensure the hub is in DFU mode. The path must point to your backup file. ```bash pybricksdev dfu restore /path/to/original/firmware.bin ``` -------------------------------- ### Pybricks Protocol Version Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/pybricks.md Constant defining the minimum required Pybricks protocol version. ```APIDOC ### PYBRICKS_PROTOCOL_VERSION The minimum required Pybricks protocol version supported by this library. ``` -------------------------------- ### Find BLE Devices with Pybricksdev Source: https://context7.com/pybricks/pybricksdev/llms.txt Discover Pybricks-compatible BLE devices by name, address, or service UUID. Supports custom timeouts. ```python import asyncio from pybricksdev.ble import find_device async def main(): # Find any hub advertising Pybricks service device = await find_device() print(f"Found: {device.name} at {device.address}") # Find a specific hub by name device = await find_device(name="Pybricks Hub") # Find by Bluetooth address (Linux/Windows only) device = await find_device(name="90:84:2B:4A:2B:75") # Custom timeout (default 10 seconds) try: device = await find_device(name="My Robot", timeout=5) except asyncio.TimeoutError: print("Device not found within timeout") asyncio.run(main()) ``` -------------------------------- ### Create a named Jupyter kernel Source: https://github.com/pybricks/pybricksdev/blob/master/README.notebooks.md Registers a new kernel specifically for the pybricksdev environment. ```bash python -m ipykernel install --user --name=pybricksdev ``` -------------------------------- ### Compile MicroPython scripts Source: https://context7.com/pybricks/pybricksdev/llms.txt Convert scripts to MPY bytecode with support for different ABI versions and input sources. ```bash # Compile a MicroPython script (default ABI v6) pybricksdev compile demo/shortdemo.py # Compile with specific ABI version pybricksdev compile --abi 5 demo/shortdemo.py # Compile and output binary data only (useful for pipes) pybricksdev compile --bin demo/shortdemo.py > output.mpy # Compile from stdin echo "print('Hello World')" | pybricksdev compile - ``` -------------------------------- ### Port Output Command Feedback (Dual Port) Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/messages.md Provides feedback for port output commands on two ports. ```APIDOC ## PortOutputCommandFeedbackMessage (Dual Port) ### Description Provides feedback for port output commands on two ports. ### Parameters #### Path Parameters - **port1** (PortID) - Required - The first port. - **feedback1** (Feedback) - Required - The feedback status for the first port. - **port2** (PortID) - Required - The second port. - **feedback2** (Feedback) - Required - The feedback status for the second port. ``` -------------------------------- ### LWP3 Constants and UUIDs Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/index.md Standard constants and UUIDs used for LEGO Wireless Protocol v3 communication. ```APIDOC ## LWP3 Constants ### Constants - **LEGO_CID** (int) - 919 (LEGO System A/S company identifier). - **LWP3_BOOTLOADER_SERVICE_UUID** (str) - '00001625-1212-efde-1623-785feabcd123' - **LWP3_BOOTLOADER_CHARACTERISTIC_UUID** (str) - '00001626-1212-efde-1623-785feabcd123' - **LWP3_HUB_SERVICE_UUID** (str) - '00001623-1212-efde-1623-785feabcd123' - **LWP3_HUB_CHARACTERISTIC_UUID** (str) - '00001624-1212-efde-1623-785feabcd123' ``` -------------------------------- ### Bootloader Advertisement Data Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/bootloader.md Structure of the manufacturer-specific advertisement data sent by a hub in bootloader mode. ```APIDOC ## BootloaderAdvertisementData ### Description Represents the 6-byte manufacturer-specific advertisement data sent when a hub is in bootloader mode. ### Properties - **hub_capabilities** (Capabilities) - Hub capability flags. - **hub_kind** (HubKind) - Hub type identifier. - **version** (Version) - Bootloader software version. ``` -------------------------------- ### Hardware Network Command Messages Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/messages.md Classes for managing hardware network connections and family information. ```APIDOC ## HwNetCmdRequestConnectionMessage ### Description Requests a connection to the hardware network. ### Parameters - **button_pressed** (bool) - Required - Indicates if the button was pressed. ## HwNetCmdFamilyMessage ### Description Message containing hardware network family information. ### Parameters - **family** (HwNetFamily) - Required - The network family. ``` -------------------------------- ### Connect to Pybricks Hub via USB Source: https://context7.com/pybricks/pybricksdev/llms.txt Connect to Pybricks hubs over USB using the PybricksHubUSB class for faster data transfer. Includes a custom match function to find specific hubs. ```python import asyncio from usb.core import find as find_usb from pybricksdev.connections.pybricks import PybricksHubUSB from pybricksdev.usb import LEGO_USB_VID, SPIKE_PRIME_USB_PID async def main(): # Find SPIKE Prime hub with Pybricks firmware via USB def is_pybricks_hub(dev): return (dev.idVendor == LEGO_USB_VID and dev.idProduct == SPIKE_PRIME_USB_PID and dev.product.endswith("Pybricks")) usb_device = find_usb(custom_match=is_pybricks_hub) if usb_device is None: print("No Pybricks USB hub found") return hub = PybricksHubUSB(usb_device) await hub.connect() try: await hub.run("my_program.py", wait=True) finally: await hub.disconnect() asyncio.run(main()) ``` -------------------------------- ### Utility Functions Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/pybricks.md Functions for UUID conversion and unpacking raw BLE characteristic data. ```APIDOC ## Utility Functions ### short_uuid(uuid: str) -> int - **Description**: Gets a 16-bit from a 128-bit UUID. - **Parameters**: uuid (str) - 128-bit UUID string. - **Returns**: (int) 16-bit UUID. ### unpack_hub_capabilities(data: bytes) -> tuple - **Description**: Unpacks the value read from the hub capabilities characteristic. - **Parameters**: data (bytes) - The raw characteristic value. - **Returns**: (tuple) (max_write_size, flags, max_user_program_size, num_slots). ### unpack_hub_capabilities_v15(data: bytes) -> tuple - **Description**: Unpacks the value read from the hub capabilities characteristic (Pybricks protocol v1.5). - **Parameters**: data (bytes) - The raw characteristic value. - **Returns**: (tuple) (max_write_size, flags, max_user_program_size, num_slots). ### unpack_pnp_id(data: bytes) -> tuple - **Description**: Unpacks raw data from the PnP ID characteristic. - **Parameters**: data (bytes) - The raw data. - **Returns**: (tuple) (vendor_id_type, vendor_id, product_id, product_revision). ``` -------------------------------- ### HwNetCmdSetExtendedFamilyMessage Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/messages.md Sets the extended family for the hardware network command. ```APIDOC ## HwNetCmdSetExtendedFamilyMessage ### Description Sets the extended family and subfamily for the hardware network command. ### Parameters #### Request Body - **family** (HwNetFamily) - Required - The network family. - **subfamily** (HwNetSubfamily) - Required - The network subfamily. ``` -------------------------------- ### Bluetooth Low Energy Module Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/index.md Provides interfaces for BLE connections, including LEGO Wireless Protocol, Nordic UART Service, and Pybricks GATT service. ```APIDOC ## BLE Module ### Description Provides classes and functions for managing Bluetooth Low Energy connections with Pybricks devices. ### Components - **BLEConnection**: Base class for BLE connections. - **BLERequestsConnection**: Connection class supporting request-response patterns. - **find_device()**: Utility function to discover available BLE devices. ``` -------------------------------- ### Pybricks BLE Commands Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/pybricks.md Commands sent to a device running Pybricks firmware to control program execution, memory, and system state. ```APIDOC ## Pybricks BLE Commands ### Description Commands are sent to a device running Pybricks firmware to manage user programs, memory, and system operations. ### Commands - **STOP_USER_PROGRAM (0)**: Requests that the user program should be stopped. - **START_USER_PROGRAM (1)**: Requests that the user program should be started. Responds with BUSY if a program is running. - **START_REPL (2)**: Requests that the interactive REPL should be started. Responds with INVALID_COMMAND if not supported or BUSY if a program is running. - **WRITE_USER_PROGRAM_META (3)**: Requests to write user program metadata. Parameters: size (32-bit unsigned integer). - **WRITE_USER_RAM (4)**: Requests to write data to user RAM. Parameters: offset (32-bit unsigned integer), payload (0 to max_char_size - 5 bytes). - **PBIO_PYBRICKS_COMMAND_REBOOT_TO_UPDATE_MODE (5)**: Requests for the hub to reboot in firmware update mode. - **WRITE_STDIN (6)**: Requests to write to stdin on the hub. Parameters: payload (Variable number of bytes). ``` -------------------------------- ### Device Discovery Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/index.md Utility function to find and connect to advertising BLE devices. ```APIDOC ## find_device ### Description Finds a BLE device that is currently advertising that matches the given parameters. ### Parameters - **name** (str | None) - Optional - The device name, address, or UUID. - **service** (str) - Optional - The service UUID that is advertised (default: 'c5f50001-8280-46da-89f4-6d8051e4aeef'). - **timeout** (float) - Optional - How long to search before giving up (default: 10). ``` -------------------------------- ### Utilize Pybricks BLE protocol constants Source: https://context7.com/pybricks/pybricksdev/llms.txt Accesses UUIDs, commands, events, and status flags for the Pybricks BLE protocol. Includes utilities for unpacking hub capabilities. ```python from pybricksdev.ble.pybricks import ( PYBRICKS_SERVICE_UUID, PYBRICKS_COMMAND_EVENT_UUID, PYBRICKS_HUB_CAPABILITIES_UUID, Command, Event, StatusFlag, HubCapabilityFlag, unpack_hub_capabilities, unpack_pnp_id ) # Service UUIDs for device discovery print(f"Pybricks Service: {PYBRICKS_SERVICE_UUID}") # c5f50001-8280-46da-89f4-6d8051e4aeef # Commands that can be sent to hubs print(f"Stop program: {Command.STOP_USER_PROGRAM}") # 0 print(f"Start program: {Command.START_USER_PROGRAM}") # 1 print(f"Write stdin: {Command.WRITE_STDIN}") # 6 # Events received from hubs print(f"Status report event: {Event.STATUS_REPORT}") # 0 print(f"Stdout event: {Event.WRITE_STDOUT}") # 1 # Status flags flags = StatusFlag.USER_PROGRAM_RUNNING | StatusFlag.BLE_ADVERTISING print(f"Program running and advertising: {flags}") # Hub capabilities (from characteristic read) raw_caps = bytes([0x14, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00]) max_write, cap_flags, max_prog_size, num_slots = unpack_hub_capabilities(raw_caps) print(f"Max write size: {max_write} bytes") print(f"Max program size: {max_prog_size} bytes") print(f"Supports MPY v6: {bool(cap_flags & HubCapabilityFlag.USER_PROG_MULTI_FILE_MPY6)}") ``` -------------------------------- ### Port Output Command Feedback Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/messages.md Provides feedback for a port output command. ```APIDOC ## PortOutputCommandFeedbackMessage ### Description Provides feedback for a port output command. ### Parameters #### Path Parameters - **port** (PortID) - Required - The port. - **feedback** (Feedback) - Required - The feedback status. ``` -------------------------------- ### Run Pybricks MicroPython program on specific Bluetooth address Source: https://github.com/pybricks/pybricksdev/blob/master/README.md Run a MicroPython script on a Pybricks device using its Bluetooth address. Note: This may not work on macOS. ```bash pipx run pybricksdev run ble --name 90:84:2B:4A:2B:75 demo/shortdemo.py ``` -------------------------------- ### Hub I/O Messages Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/messages.md Classes for handling virtual device attachments and detachments on the hub. ```APIDOC ## HubIOAttachedVirtualMessage ### Description Represents a message indicating a virtual device has been attached to the hub. ### Parameters - **port** (PortID) - Required - The port ID. - **device** (IODeviceKind) - Required - The kind of device attached. - **port_a** (PortID) - Required - The first port of the virtual device. - **port_b** (PortID) - Required - The second port of the virtual device. ## HubIODetachedMessage ### Description Represents a message indicating a device has been detached from the hub. ### Parameters - **port** (PortID) - Required - The port ID. ``` -------------------------------- ### Capabilities Enum Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/bytecodes.md Describes the capabilities of a hub, used in advertising data. ```APIDOC ## Capabilities Enum ### Description Describes the capabilities of a hub. These flags are used in advertising data. ### Values - **CENTRAL** (1) - The hub supports the central role. - **PERIPHERAL** (2) - The hub supports the peripheral role. - **IO** (4) - The hub has I/O ports for connecting sensors/motors. - **REMOTE** (8) - The hub acts as a remote control. ``` -------------------------------- ### BLE Request-Reply Pattern Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/index.md Specialized connection class for sending messages and awaiting replies of known length. ```APIDOC ## BLERequestsConnection ### Description Sends messages and awaits replies of known length, useful for bootloaders or firmware updates. ### Methods - **prepare_reply()**: Clears existing reply and wait event. - **wait_for_reply(timeout=None)**: Awaits for given number of characters since prepare_reply. ``` -------------------------------- ### Standard UUIDs Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/pybricks.md Standard UUIDs used for firmware revision and PnP ID. ```APIDOC ### FW_REV_UUID Standard Firmware Revision String characteristic UUID [Availability](../../notes.md#availability): Since Pybricks protocol v1.0.0. ### PNP_ID_UUID Standard PnP ID UUID > Vendor ID is [`pybricksdev.ble.lwp3.LEGO_CID`](lwp3/index.md#pybricksdev.ble.lwp3.LEGO_CID). Product ID is one of > [`pybricksdev.ble.lwp3.bytecodes.HubKind`](lwp3/bytecodes.md#pybricksdev.ble.lwp3.bytecodes.HubKind). Revision is `0` for most > hubs or `1` for MINDSTORMS Robot Inventor Hub. [Availability](../../notes.md#availability): Since Pybricks protocol v1.1.0. ### SW_REV_UUID Standard Software Revision String UUID (Pybricks protocol version) [Availability](../../notes.md#availability): Since Pybricks protocol v1.0.0. ``` -------------------------------- ### Pybricks Service and Command UUIDs Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/pybricks.md UUIDs for the main Pybricks GATT service and the command/event characteristic. ```APIDOC ### PYBRICKS_COMMAND_EVENT_UUID The Pybricks command/event GATT characteristic UUID. Commands are written to this characteristic and events are received via notifications. See [`Command`](#pybricksdev.ble.pybricks.Command) and [`Event`](#pybricksdev.ble.pybricks.Event). [Availability](../../notes.md#availability): Since Pybricks protocol v1.0.0. ### PYBRICKS_SERVICE_UUID The Pybricks GATT service UUID. ``` -------------------------------- ### Port Mode Information Capabilities Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/messages.md Provides information about the capabilities of a specific port mode. ```APIDOC ## PortModeInfoCapabilitiesMessage ### Description Provides information about the capabilities of a specific port mode. ### Parameters #### Path Parameters - **port** (PortID) - Required - The port. - **mode** (int) - Required - The mode. - **capabilities** (IODeviceCapabilities) - Required - The capabilities of the mode. ``` -------------------------------- ### Abstract Port Output Command Message Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/messages.md Abstract base class for messages related to port output commands. ```APIDOC ## AbstractPortOutputCommandMessage ### Description Abstract base class for messages related to port output commands. ### Parameters * **length** (int) - The length of the message. * **port** (PortID) - The port associated with the command. * **start** (StartInfo) - Information about the start of the output command. * **end** (EndInfo) - Information about the end of the output command. * **command** (PortOutputCommand) - The specific port output command. ### Properties * **command** (PortOutputCommand) - The specific port output command. * **end** (EndInfo) - Information about the end of the output command. * **port** (PortID) - The port associated with the command. * **start** (StartInfo) - Information about the start of the output command. ``` -------------------------------- ### HubAction Enum Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/bytecodes.md Commands to instruct the hub to perform specific actions. ```APIDOC ## HubAction Enum ### Description Instructs the hub to perform an action. ### Values - **POWER_OFF** (1) - Switches the hub off. - **PORT_VCC_ON** (3) - Turns on 3.3V on I/O port pin 4 for all ports. - **PORT_VCC_OFF** (4) - Turns off 3.3V on I/O port pin 4 for all ports. - **SET_BUSY** (5) - Sets busy indication on status light. - **RESET_BUSY** (6) - Resets busy indication on status light. - **DISCONNECT** (2) - Instructs the hub to disconnect Bluetooth. - **WILL_DISCONNECT** (49) - The hub will disconnect. - **WILL_POWER_OFF** (48) - The hub will switch off. - **WILL_UPDATE** (50) - The hub will restart in firmware update mode. - **FAST_POWER_OFF** (47) - Fast power off (factory use). ``` -------------------------------- ### Compile Python Scripts to MicroPython Bytecode Source: https://context7.com/pybricks/pybricksdev/llms.txt Compile Python scripts to MicroPython bytecode using `compile_file` or `compile_multi_file`. Also includes `print_mpy` to display bytecode. ```python import asyncio from pybricksdev.compile import compile_file, compile_multi_file, print_mpy async def main(): # Compile a single file mpy_data = await compile_file( proj_dir=".", proj_path="my_script.py", abi=6 # MicroPython ABI version (5 or 6) ) print(f"Compiled {len(mpy_data)} bytes") # Compile with dependencies (multi-file project) # Automatically finds and compiles imported local modules mpy_bundle = await compile_multi_file("main.py", abi=6) print(f"Bundle size: {len(mpy_bundle)} bytes") # Print compiled bytecode in C array format print_mpy(mpy_data) # Output: # // MPY file. Size: 47 bytes # const uint8_t script[] = { # 0x4D, 0x06, 0x00, 0x1F, ... # }; asyncio.run(main()) ``` -------------------------------- ### Firmware Update Message Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/messages.md Instructs the hub to reboot into firmware update mode. Requires a safety string for confirmation. ```APIDOC ## FirmwareUpdateMessage ### Description Instructs the hub to reboot in firmware update mode. ### Properties * **key** (bytes) - Safety string. ``` -------------------------------- ### Port Mode Information Mapping Source: https://github.com/pybricks/pybricksdev/blob/master/docs/api/ble/lwp3/messages.md Defines the input and output mappings for a specific port mode. ```APIDOC ## PortModeInfoMappingMessage ### Description Defines the input and output mappings for a specific port mode. ### Parameters #### Path Parameters - **port** (PortID) - Required - The port. - **mode** (int) - Required - The mode. - **input_mapping** (IODeviceMapping) - Required - The input mapping. - **output_mapping** (IODeviceMapping) - Required - The output mapping. ```