22# Copyright (c) 2020 Henrik Blidh
33# Copyright (c) 2022-2023 The Pybricks Authors
44
5+ """
6+ Example program for computer-to-hub communication.
7+
8+ Requires Pybricks firmware >= 3.3.0.
9+ """
10+
511import asyncio
612from contextlib import suppress
713from bleak import BleakScanner , BleakClient
814
9- UART_SERVICE_UUID = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
10- UART_RX_CHAR_UUID = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
11- UART_TX_CHAR_UUID = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
15+ PYBRICKS_COMMAND_EVENT_CHAR_UUID = "c5f50002-8280-46da-89f4-6d8051e4aeef"
1216
1317# Replace this with the name of your hub if you changed
1418# it when installing the Pybricks firmware.
@@ -30,10 +34,13 @@ def handle_disconnect(_):
3034 ready_event = asyncio .Event ()
3135
3236 def handle_rx (_ , data : bytearray ):
33- if data == b"rdy" :
34- ready_event .set ()
35- else :
36- print ("Received:" , data )
37+ if data [0 ] == 0x01 : # "write stdout" event (0x01)
38+ payload = data [1 :]
39+
40+ if payload == b"rdy" :
41+ ready_event .set ()
42+ else :
43+ print ("Received:" , payload )
3744
3845 # Do a Bluetooth scan to find the hub.
3946 device = await BleakScanner .find_device_by_name (HUB_NAME )
@@ -46,7 +53,7 @@ def handle_rx(_, data: bytearray):
4653 async with BleakClient (device , handle_disconnect ) as client :
4754
4855 # Subscribe to notifications from the hub.
49- await client .start_notify (UART_TX_CHAR_UUID , handle_rx )
56+ await client .start_notify (PYBRICKS_COMMAND_EVENT_CHAR_UUID , handle_rx )
5057
5158 # Shorthand for sending some data to the hub.
5259 async def send (data ):
@@ -55,7 +62,11 @@ async def send(data):
5562 # Prepare for the next ready event.
5663 ready_event .clear ()
5764 # Send the data to the hub.
58- await client .write_gatt_char (UART_RX_CHAR_UUID , data )
65+ await client .write_gatt_char (
66+ PYBRICKS_COMMAND_EVENT_CHAR_UUID ,
67+ b"\x06 " + data , # prepend "write stdin" command (0x06)
68+ response = True
69+ )
5970
6071 # Tell user to start program on the hub.
6172 print ("Start the program on the hub now with the button." )
0 commit comments