Skip to content

Commit 1a0cc90

Browse files
Merge pull request ParticulaCode#9 from kevin-huff/main
Add auto reconnect if the dice disconnect
2 parents b998bb9 + 9921012 commit 1a0cc90

2 files changed

Lines changed: 26 additions & 9 deletions

File tree

godice.js

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -284,16 +284,21 @@ class GoDice {
284284
/**
285285
* Attempts to reconnect to the device incase of disconnect
286286
*/
287-
async attemptReconnect() {
288-
if (this.bluetoothDevice) {
289-
// This object's device exists
290-
if (this.bluetoothDevice.gatt.connected) {
291-
console.debug(this.GlobalDeviceId + "'s Bluetooth device is already connected")
292-
} else {
293-
await this.connectDeviceAndCacheCharacteristics()
294-
}
287+
async attemptReconnect(diceId, diceInstance) {
288+
while (!this.bluetoothDevice.gatt.connected) {
289+
console.log("Reconnecting to: ", diceId);
290+
try {
291+
await this.connectDeviceAndCacheCharacteristics()
292+
} catch (error) {
293+
console.error("Error while trying to reconnect: ", error)
294+
}
295+
if (!this.bluetoothDevice.gatt.connected) {
296+
await new Promise(resolve => setTimeout(resolve, 1000))
297+
}
295298
}
296-
}
299+
console.log(diceId + " reconnected!")
300+
}
301+
297302

298303
/**
299304
* Turn On/Off RGB LEDs, will turn off if led1 and led2 are null

main.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,18 @@ GoDice.prototype.onRollStart = (diceId) => {
157157
diceIndicatorEl.textContent = "Rollling....";
158158
};
159159

160+
GoDice.prototype.onDiceDisconnected = (diceId, diceInstance) => {
161+
console.log("Roll Start: ", diceId);
162+
163+
// get rolling indicator
164+
const diceIndicatorEl = document.getElementById(diceId + "-die-status");
165+
166+
// show rolling
167+
diceIndicatorEl.textContent = "disconnected";
168+
// Attempt to reconnect
169+
diceInstance.attemptReconnect(diceId, diceInstance);
170+
};
171+
160172
GoDice.prototype.onStable = (diceId, value, xyzArray) => {
161173
console.log("Stable event: ", diceId, value);
162174

0 commit comments

Comments
 (0)