diff --git a/relay/bluetooth_handler.py b/relay/bluetooth_handler.py new file mode 100644 index 0000000..91a2644 --- /dev/null +++ b/relay/bluetooth_handler.py @@ -0,0 +1,55 @@ +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("initting 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") + # 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"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") \ No newline at end of file diff --git a/relay/main.py b/relay/main.py index 18e6f11..5a07d77 100644 --- a/relay/main.py +++ b/relay/main.py @@ -2,6 +2,10 @@ from sx1262 import SX1262 from _sx126x import * import time +from bluetooth_handler import BluetoothHandler + +LORA_ENABLED = False + def cb(events): if events & SX1262.RX_DONE: @@ -11,7 +15,7 @@ def cb(events): elif events & SX1262.TX_DONE: print('TX done.') -def main(): +def init_lora(): print("Creating class...") # initialize our radio, im using the HAT SX1262 hat for the pico radio = SX1262(spi_bus=1, clk=10, mosi=11, miso=12, cs=3, irq=20, rst=15, gpio=2) @@ -23,9 +27,21 @@ def main(): radio.begin(freq=915, bw=125, power=22) radio.setBlockingCallback(False, cb) - while True: - print(f"Noise Floor: {radio.getRSSIInst()}") - time.sleep(0.5) +def init_bluetooth(): + bluetooth_handler = BluetoothHandler() + + + +def main(): + if LORA_ENABLED: + init_lora() + + init_bluetooth() + + if LORA_ENABLED: + while True: + print(f"Noise Floor: {radio.getRSSIInst()} | SNR: {radio.getSNR()}") + time.sleep(0.5) if __name__ == "__main__":