Skip to content

Commit

Permalink
Retry properly when device not found or out of range.
Browse files Browse the repository at this point in the history
  • Loading branch information
wscullen committed Mar 24, 2024
1 parent c26f62a commit de0a07e
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/hooks/useWebBluetooth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,20 +73,23 @@ const useWebBluetooth = (incomingDataEventListener: (data: string) => void) => {
};

useEffect(() => {
let reconnect: number;
let reconnect: number | undefined = undefined;
if (previouslyPairedDevices.length > 0) {
reconnect = setInterval(() => {
console.log(isDisconnected);
if (!isDisconnected) {
clearInterval(reconnect);
return;
}
const device = previouslyPairedDevices[0];
connectToExistingDevice(device);
}, 5000);
} else {
if (reconnect !== undefined) clearInterval(reconnect);
}

return () => {
clearInterval(reconnect);
if (reconnect !== undefined) clearInterval(reconnect);
};
}, [previouslyPairedDevices, isDisconnected]);

Expand Down Expand Up @@ -165,7 +168,6 @@ const useWebBluetooth = (incomingDataEventListener: (data: string) => void) => {
const connectToExistingDevice = async (device: BluetoothDevice) => {
try {
console.log("trying to connect to existing device", device);
setIsDisconnected(false);
currentDevice.current = device;

// Add an event listener to detect when a device disconnects
Expand All @@ -187,7 +189,8 @@ const useWebBluetooth = (incomingDataEventListener: (data: string) => void) => {
"characteristicvaluechanged",
handleCharacteristicValueChanged
);
} catch (error) {
setIsDisconnected(false);
} catch (error: unknown) {
console.log(`There was an error: ${error}`);
}
};
Expand Down

0 comments on commit de0a07e

Please sign in to comment.