diff --git a/lib/bluetooth-device-wrapper.ts b/lib/bluetooth-device-wrapper.ts index 0e7d07d..5007d8b 100644 --- a/lib/bluetooth-device-wrapper.ts +++ b/lib/bluetooth-device-wrapper.ts @@ -106,7 +106,7 @@ export class BluetoothDeviceWrapper { private disconnectPromise: Promise | undefined; private connecting = false; private isReconnect = false; - private reconnectReadyPromise: Promise | undefined; + private connectReadyPromise: Promise | undefined; private accelerometer = new ServiceInfo(AccelerometerService.createService, [ "accelerometerdatachanged", @@ -176,6 +176,15 @@ export class BluetoothDeviceWrapper { "BluetoothRemoteGATTServer for micro:bit device is undefined", ); } + + if (isWindowsOS) { + // On Windows, the micro:bit can take around 3 seconds to respond to gatt.disconnect(). + // Attempting to connect/reconnect before the micro:bit has responded results in another + // gattserverdisconnected event being fired. We then fail to get primaryService on a + // disconnected GATT server. + await this.connectReadyPromise; + } + try { // A previous connect might have completed in the background as a device was replugged etc. await this.disconnectPromise; @@ -282,7 +291,7 @@ export class BluetoothDeviceWrapper { this.disposeServices(); this.duringExplicitConnectDisconnect--; } - this.reconnectReadyPromise = new Promise((resolve) => + this.connectReadyPromise = new Promise((resolve) => setTimeout(resolve, 3_500), ); } @@ -290,13 +299,6 @@ export class BluetoothDeviceWrapper { async reconnect(): Promise { this.logging.log("Bluetooth reconnect"); this.isReconnect = true; - if (isWindowsOS) { - // On Windows, the micro:bit can take around 3 seconds to respond to gatt.disconnect(). - // Attempting to reconnect before the micro:bit has responded results in another - // gattserverdisconnected event being fired. We then fail to get primaryService on a - // disconnected GATT server. - await this.reconnectReadyPromise; - } await this.connect(); } diff --git a/lib/bluetooth.ts b/lib/bluetooth.ts index 73df12a..65f9b47 100644 --- a/lib/bluetooth.ts +++ b/lib/bluetooth.ts @@ -170,9 +170,6 @@ export class MicrobitWebBluetoothConnection return; } // TODO: timeout unification? - // Connection happens inside createBluetoothDeviceWrapper. - // await this.connection?.connect(); - this.setStatus(ConnectionStatus.CONNECTED); } setNameFilter(name: string) {