does kind of work

This commit is contained in:
2022-04-18 14:16:30 +02:00
parent 8e10db0736
commit a857cb7bb4
2 changed files with 40 additions and 5 deletions

View File

@@ -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<BluetoothDevice>(null);
const [device, setDevice] = useState<{
device: BluetoothDevice;
service: BluetoothRemoteGATTService;
characteristic: BluetoothRemoteGATTCharacteristic;
} | null>(null);
const [doorOpen, setDoorOpen] = useState<boolean | null>(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() {
<>
<span>connected</span>
<button onClick={onDisconnectClick}>Disconnect</button>
<span>{doorOpen ? "open" : "closed"}</span>
</>
)}
</div>

View File

@@ -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()
{