55 lines
1.9 KiB
Python
55 lines
1.9 KiB
Python
import bluetooth
|
|
from micropython import const
|
|
|
|
|
|
# i just made a UUID up and changed the last number to change what protocol you're using
|
|
SERVICE_UUID = bluetooth.UUID("E1898FF7-5063-4441-a6eb-526073B00001")
|
|
TX_UUID = bluetooth.UUID("E1898FF7-5063-4441-a6eb-526073B00002")
|
|
RX_UUID = bluetooth.UUID("E1898FF7-5063-4441-a6eb-526073B00003")
|
|
|
|
TX_CHAR = (TX_UUID, bluetooth.FLAG_NOTIFY)
|
|
RX_CHAR = (RX_UUID, bluetooth.FLAG_WRITE)
|
|
|
|
SERVICE = (SERVICE_UUID, (TX_CHAR, RX_CHAR))
|
|
|
|
IRQ_CONNECT = const(1)
|
|
IRQ_DISCONNECT = const(2)
|
|
IRQ_GATTS_WRITE = const(3)
|
|
|
|
|
|
class BluetoothHandler:
|
|
def __init__(self):
|
|
print("Initializing Bluetooth...")
|
|
self.ble = bluetooth.BLE()
|
|
self.ble.active(True)
|
|
self.ble.irq(self.irq)
|
|
|
|
((self.tx_handle, self.rx_handle),) = self.ble.gatts_register_services((SERVICE,))
|
|
|
|
self.connections = set()
|
|
|
|
self.advertise()
|
|
|
|
def advertise(self):
|
|
print("Advertising Bluetooth...")
|
|
# note: \x02\x01\x06\x0C\x09 is the BLE header that tells other devices we're BLE only and discoverable
|
|
self.ble.gap_advertise(100_000, b"\x02\x01\x06\x0C\x09MeshConnectorNode")
|
|
|
|
def irq(self, event, data):
|
|
print(f"BLUETOOTH IRQ | EVENT: {event}, DATA: {data}")
|
|
if event == IRQ_CONNECT:
|
|
conn_handle, _, _ = data
|
|
self.connections.add(conn_handle)
|
|
elif event == IRQ_DISCONNECT:
|
|
conn_handle, _, _ = data
|
|
self.connections.remove(conn_handle)
|
|
self.advertise()
|
|
elif event == IRQ_GATTS_WRITE:
|
|
conn_handle, value_handle = data
|
|
|
|
if value_handle == self.tx_handle:
|
|
msg = self.ble.gatts_read(self.tx_handle)
|
|
|
|
if msg == b"ping":
|
|
for conn in self.connections:
|
|
self.ble.gatts_notify(conn, self.rx_handle, b"pong") |