|
1 | 1 | from time import sleep
|
2 |
| -from adafruit_ble.uart_client import UARTClient |
3 |
| -from adafruit_ble.scanner import Scanner |
| 2 | +from adafruit_ble import BLERadio |
| 3 | +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement |
| 4 | +from adafruit_ble.services.nordic import UARTService |
4 | 5 | from adafruit_bluefruit_connect.packet import Packet
|
5 | 6 | from adafruit_bluefruit_connect.button_packet import ButtonPacket
|
6 | 7 | from adafruit_bluefruit_connect.color_packet import ColorPacket
|
|
35 | 36 |
|
36 | 37 | button_packet = ButtonPacket("1", True) # Transmits pressed button 1
|
37 | 38 |
|
38 |
| -scanner = Scanner() # BLE Scanner |
39 |
| -uart_client = UARTClient() # BLE Client |
| 39 | +ble = BLERadio() |
40 | 40 |
|
41 |
| -while True: |
42 |
| - uart_addresses = [] |
43 |
| - pixels[0] = BLUE # Blue LED indicates disconnected status |
44 |
| - pixels.show() |
| 41 | +uart_connection = None |
| 42 | +# See if any existing connections are providing UARTService. |
| 43 | +if ble.connected: |
| 44 | + for connection in ble.connections: |
| 45 | + if UARTService in connection: |
| 46 | + uart_connection = connection |
| 47 | + break |
45 | 48 |
|
46 |
| - # Keep trying to find target UART peripheral |
47 |
| - while not uart_addresses: |
48 |
| - uart_addresses = uart_client.scan(scanner) |
49 |
| - for address in uart_addresses: |
50 |
| - if TARGET in str(address): |
51 |
| - uart_client.connect(address, 5) # Connect to target |
| 49 | +while True: |
| 50 | + if not uart_connection: |
| 51 | + pixels[0] = BLUE # Blue LED indicates disconnected status |
| 52 | + pixels.show() |
| 53 | + for adv in ble.start_scan(ProvideServicesAdvertisement, timeout=5): |
| 54 | + if UARTService in adv.services: |
| 55 | + uart_connection = ble.connect(adv) |
| 56 | + break |
| 57 | + # Stop scanning whether or not we are connected. |
| 58 | + ble.stop_scan() |
52 | 59 |
|
53 |
| - while uart_client.connected: # Connected |
| 60 | + while uart_connection and uart_connection.connected: |
54 | 61 | switch.update()
|
55 | 62 | if switch.fell: # Check for button press
|
56 | 63 | try:
|
57 |
| - uart_client.write(button_packet.to_bytes()) # Transmit press |
| 64 | + uart_connection.write(button_packet.to_bytes()) # Transmit press |
58 | 65 | except OSError:
|
59 |
| - pass |
| 66 | + uart_connection = None |
| 67 | + continue |
60 | 68 | # Check for LED status receipt
|
61 |
| - if uart_client.in_waiting: |
62 |
| - packet = Packet.from_stream(uart_client) |
| 69 | + if uart_connection.in_waiting: |
| 70 | + packet = Packet.from_stream(uart_connection) |
63 | 71 | if isinstance(packet, ColorPacket):
|
64 | 72 | if fancy.CRGB(*packet.color).pack() == GREEN: # Color match
|
65 | 73 | # Green indicates on state
|
|
79 | 87 | color_index += fade_direction
|
80 | 88 |
|
81 | 89 | sleep(0.02)
|
| 90 | + |
| 91 | + uart_connection = None |
0 commit comments