44 lines
1.1 KiB
Python
44 lines
1.1 KiB
Python
|
import time
|
||
|
|
||
|
import bleak
|
||
|
from adafruit_ble import BLERadio
|
||
|
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
|
||
|
from adafruit_ble.services.nordic import UARTService
|
||
|
|
||
|
ble = BLERadio()
|
||
|
|
||
|
def scan():
|
||
|
print("disconnected, scanning")
|
||
|
for advertisement in ble.start_scan(ProvideServicesAdvertisement, timeout=1):
|
||
|
if not advertisement.complete_name.startswith('Feather'):
|
||
|
continue
|
||
|
|
||
|
ble.connect(advertisement)
|
||
|
print("connected to", advertisement.complete_name)
|
||
|
break
|
||
|
ble.stop_scan()
|
||
|
|
||
|
def read(connection):
|
||
|
uart = connection[UARTService]
|
||
|
if uart.in_waiting:
|
||
|
res = uart.read(uart.in_waiting)
|
||
|
print(res)
|
||
|
|
||
|
def loop():
|
||
|
while True:
|
||
|
while ble.connected:
|
||
|
for connection in ble.connections:
|
||
|
try:
|
||
|
read(connection)
|
||
|
except bleak.exc.BleakError:
|
||
|
print('Disconnected, waiting 3 seconds and trying to reconnect...')
|
||
|
connection.disconnect()
|
||
|
time.sleep(3)
|
||
|
|
||
|
time.sleep(0.1)
|
||
|
|
||
|
scan()
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
loop()
|