messaging – Send and receive messages¶
Classes to send and receive messages from another device.
| ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|---|
- 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
Nonewhen 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).
- awaitbroadcast(data)¶
Starts broadcasting the given data on the previously selected
broadcast_channel.Data may be of type
int,float,str,bytes,True, orFalse. It can also be a list or tuple of these.Choose
Noneto 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).
TrueandFalsetake 1 byte each.floattakes 5 bytes.inttakes 2 to 5 bytes depending on how big the number is.strandbytestake 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_channelwas configured.ValueError – If the encoded data exceeds 26 bytes.
TypeError – If
datacontains a value that is notbool,int,float,str, orbytes.
- 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_channelswhen creating this object.- Returns:
The received data in the same format as it was sent, or
Noneif no data has been received within the last second.- Raises:
ValueError – If
channelwas not inobserve_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_channelswhen creating this object.- Returns:
The signal strength, or
-128if no data has been received within the last second.- Raises:
ValueError – If
channelwas not inobserve_channels.
- 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, wheremodeis a mode number (0 to 255) andsizeis 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
AppDatainstance already exists.TypeError – If
modesis 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:
- Returns:
All received bytes for the mode, or a single byte as an integer if
indexis given.- Raises:
ValueError – If
modewas not configured, or ifindexis out of range.
- 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.
- 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)