diff --git a/door-thing-app/src/App.tsx b/door-thing-app/src/App.tsx index 6bdfdde..e9c67bf 100644 --- a/door-thing-app/src/App.tsx +++ b/door-thing-app/src/App.tsx @@ -1,8 +1,16 @@ import { useState } from "preact/hooks"; +const doorServiceUUID: BluetoothServiceUUID = 0x1811; +const doorSwitchUUID: BluetoothCharacteristicUUID = 0x2ae2; + export function App() { const [connecting, setConnecting] = useState(false); - const [device, setDevice] = useState(null); + const [device, setDevice] = useState<{ + device: BluetoothDevice; + service: BluetoothRemoteGATTService; + characteristic: BluetoothRemoteGATTCharacteristic; + } | null>(null); + const [doorOpen, setDoorOpen] = useState(null); const onConnectClick = async () => { try { @@ -13,12 +21,30 @@ export function App() { namePrefix: "Nano", }, ], + optionalServices: [doorServiceUUID], }); console.log("Found device:"); console.log(foundDevice); - setDevice(foundDevice); await foundDevice.gatt.connect(); foundDevice.ongattserverdisconnected = onDisconnect; + + const doorService = await foundDevice.gatt.getPrimaryService( + doorServiceUUID, + ); + + const doorSwitch = await doorService.getCharacteristic(doorSwitchUUID); + setDevice({ + device: foundDevice, + service: doorService, + characteristic: doorSwitch, + }); + + const data = await (await doorSwitch.readValue()).getUint8(0); + + doorSwitch.oncharacteristicvaluechanged = onDoorUpdate; + doorSwitch.startNotifications(); + + setDoorOpen(Boolean(data)); } catch (error) { console.log("Error connecting:"); console.log(error); @@ -27,13 +53,21 @@ export function App() { } }; + const onDoorUpdate = async (ev: Event) => { + const characteristic = ev.target as BluetoothRemoteGATTCharacteristic; + const parsed = Boolean(await characteristic.value.getUint8(0)); + setDoorOpen(parsed); + new Notification("Door update", { body: parsed ? "Open" : "Closed" }); + }; + const onDisconnect = async () => { setDevice(null); }; const onDisconnectClick = async () => { try { - device.gatt.disconnect(); + await device.characteristic.stopNotifications(); + device.device.gatt.disconnect(); } catch (error) { console.log("Error disconnecting:"); console.log(error); @@ -50,6 +84,7 @@ export function App() { <> connected + {doorOpen ? "open" : "closed"} )} diff --git a/door-thing-firmware/src/main.cpp b/door-thing-firmware/src/main.cpp index a3ce3e6..61face8 100644 --- a/door-thing-firmware/src/main.cpp +++ b/door-thing-firmware/src/main.cpp @@ -4,10 +4,10 @@ // Door switch pin #define SWITCH_PIN 2 -BLEService switchService("180A"); // BLE Switch Service +BLEService switchService("1811"); // BLE Switch Service // BLE Switch Characteristic - custom 128-bit UUID, read by central -BLEByteCharacteristic switchCharacteristic("1234", BLERead | BLEIndicate); +BLEByteCharacteristic switchCharacteristic("2AE2", BLERead | BLEIndicate); void setup() {