messaging – Send and receive messages

Classes to send and receive messages from another device.

radiobroadcast channel0observe channel1
class BLERadio(broadcast_channel=None, observe_channels=[])

Send and receive messages without a connection using Bluetooth Low Energy.

New in version 4.0: This used to be part of each hub class.

Parameters:
  • broadcast_channel – Channel number (0 to 255) used to broadcast data. Choose None when not using broadcasting.

  • observe_channels – A list of channels to listen to when hub.ble.observe() is called. Listening to more channels requires more memory. Default is an empty list (no channels).

radio000list withbroadcast
awaitbroadcast(data)

Starts broadcasting the given data on the previously selected broadcast_channel.

Data may be of type int, float, str, bytes, True, or False. It can also be a list or tuple of these.

Choose None to stop broadcasting. This helps improve performance when you don’t need the broadcast feature, especially when observing at the same time.

The total data size is quite limited (26 bytes). True and False take 1 byte each. float takes 5 bytes. int takes 2 to 5 bytes depending on how big the number is. str and bytes take the number of bytes in the object plus one extra byte.

When multitasking, only one task can broadcast at a time. To broadcast information from multiple tasks (or block stacks), you could use a dedicated separate task that broadcast new values when one or more variables change.

Parameters:

data – The value or values to be broadcast.

Raises:
  • RuntimeError – If no broadcast_channel was configured.

  • ValueError – If the encoded data exceeds 26 bytes.

  • TypeError – If data contains a value that is not bool, int, float, str, or bytes.

radioobserve0
observe(channel) bool | int | float | str | bytes | tuple | None

Retrieves the last observed data for a given channel.

Receiving data is more reliable when the hub is not connected to a computer or other devices at the same time.

Parameters:

channel (int) – The channel to observe. Must be one of the channels given to observe_channels when creating this object.

Returns:

The received data in the same format as it was sent, or None if no data has been received within the last second.

Raises:

ValueError – If channel was not in observe_channels.

signal_strength(channel) int: dBm

Gets the average signal strength in dBm for the given channel.

This indicates how near the broadcasting device is. Nearby devices may have a signal strength around -40 dBm, while far away devices might have a signal strength around -70 dBm.

Parameters:

channel (int) – The channel number. Must be one of the channels given to observe_channels when creating this object.

Returns:

The signal strength, or -128 if no data has been received within the last second.

Raises:

ValueError – If channel was not in observe_channels.

version() str

Gets the firmware version from the Bluetooth chip.

redsmartcolor tracker
0zj3KVdmjsmartclassificationmodel
smartobject detectiondetectpersonpotted plantnothingnothing
smartline followerdark line
0bbbbsmartcustommodeformat
class AppData(modes)

Exchange raw data with the Pybricks Code host application over USB or Bluetooth. This is used by the smart sensor features like the vision processors.

Each processor has on emode and produces a fixed amount of data. These are continuously sent to the hub as they change. The user code can read these buffered values at any time without blocking. All values are initially zero.

From the hub’s perspective, writing back to the host is an awaitable operation. Can be used to configure modes and mode settings.

Only one instance may exist at a time. Must be created during program initialization. After that, all methods may be used while multi-tasking.

Parameters:

modes – A list of (mode, size) tuples, where mode is a mode number (0 to 255) and size is the number of bytes to allocate for that mode’s receive buffer. Mode numbers must be unique. The list is sorted by mode number automatically.

Raises:
  • RuntimeError – If an AppData instance already exists.

  • TypeError – If modes is not a list, or if any element is not a (mode, size) tuple with a mode value of 0 to 255.

  • ValueError – If any mode number appears more than once.

get_bytes(mode, index=None) bytes | int

Gets data received from the host for the given mode.

Parameters:
  • mode (int) – The mode number to read.

  • index (int) – If given, returns the single byte at this position within the mode’s buffer as an integer. Otherwise returns the entire mode buffer as bytes.

Returns:

All received bytes for the mode, or a single byte as an integer if index is given.

Raises:

ValueError – If mode was not configured, or if index is out of range.

0smartvalue
awaitwrite_bytes(data)

Sends raw bytes to the host application.

Parameters:

data (bytes) – The data to send.

awaitconfigure(mode, parameter, value)

Sends a configuration command to the host for the given mode.

This is a wrapper around write_bytes(). It prepends a [0x01, mode, parameter] header to configure mode settings.

Parameters:
  • mode (int) – The mode number to configure.

  • parameter (int) – The parameter identifier within the mode.

  • value (bytes) – The configuration value to send.

close()

Deactivates the data callback and releases the receive buffer.

This is also called automatically when the object is garbage collected.

BLERadio examples

Broadcasting data to other hubs

from pybricks.pupdevices import Motor
from pybricks.parameters import Port
from pybricks.tools import wait
from pybricks.messaging import BLERadio

# Initialize the hub.
radio = BLERadio(broadcast_channel=1)

# Initialize the motors.
left_motor = Motor(Port.A)
right_motor = Motor(Port.B)

while True:
    # Read the motor angles to be sent to the other hub.
    left_angle = left_motor.angle()
    right_angle = right_motor.angle()

    # Set the broadcast data and start broadcasting if not already doing so.
    data = (left_angle, right_angle)
    radio.broadcast(data)

    # Broadcasts are only sent every 100 milliseconds, so there is no reason
    # to call the broadcast() method more often than that.
    wait(100)

Observing data from other hubs

from pybricks.pupdevices import Motor
from pybricks.parameters import Port
from pybricks.tools import wait
from pybricks.messaging import BLERadio

# Initialize the hub.
radio = BLERadio(observe_channels=[1])

# Initialize the motors.
left_motor = Motor(Port.A)
right_motor = Motor(Port.B)

while True:
    # Receive broadcast from the other hub.

    data = radio.observe(1)

    if data is not None:
        # Data was received and is less that one second old.
        # It contains the same values in the same order
        # that were passed to radio.broadcast() on the
        # other hub.
        left_angle, right_angle = data

        # Make the motors on this hub mirror the position of the
        # motors on the other hub.
        left_motor.track_target(left_angle)
        right_motor.track_target(right_angle)

    # Broadcasts are only sent every 100 milliseconds, so there is
    # no reason to call the observe() method more often than that.
    wait(100)