@@ -94,6 +94,13 @@ class ServiceInfo<T extends Service> {
94
94
}
95
95
}
96
96
97
+ interface ConnectCallbacks {
98
+ onConnecting : ( ) => void ;
99
+ onReconnecting : ( ) => void ;
100
+ onFail : ( ) => void ;
101
+ onSuccess : ( ) => void ;
102
+ }
103
+
97
104
export class BluetoothDeviceWrapper {
98
105
// Used to avoid automatic reconnection during user triggered connect/disconnect
99
106
// or reconnection itself.
@@ -136,6 +143,7 @@ export class BluetoothDeviceWrapper {
136
143
private dispatchTypedEvent : TypedServiceEventDispatcher ,
137
144
// We recreate this for the same connection and need to re-setup notifications for the old events
138
145
private events : Record < keyof ServiceConnectionEventMap , boolean > ,
146
+ private callbacks : ConnectCallbacks ,
139
147
) {
140
148
device . addEventListener (
141
149
"gattserverdisconnected" ,
@@ -158,6 +166,11 @@ export class BluetoothDeviceWrapper {
158
166
await this . gattConnectPromise ;
159
167
return ;
160
168
}
169
+ if ( this . isReconnect ) {
170
+ this . callbacks . onReconnecting ( ) ;
171
+ } else {
172
+ this . callbacks . onConnecting ( ) ;
173
+ }
161
174
this . duringExplicitConnectDisconnect ++ ;
162
175
if ( this . device . gatt === undefined ) {
163
176
throw new Error (
@@ -233,16 +246,20 @@ export class BluetoothDeviceWrapper {
233
246
type : this . isReconnect ? "Reconnect" : "Connect" ,
234
247
message : "Bluetooth connect success" ,
235
248
} ) ;
249
+ this . callbacks . onSuccess ( ) ;
236
250
} catch ( e ) {
237
251
this . logging . error ( "Bluetooth connect error" , e ) ;
238
252
this . logging . event ( {
239
253
type : this . isReconnect ? "Reconnect" : "Connect" ,
240
254
message : "Bluetooth connect failed" ,
241
255
} ) ;
242
256
await this . disconnectInternal ( false ) ;
257
+ this . callbacks . onFail ( ) ;
243
258
throw new Error ( "Failed to establish a connection!" ) ;
244
259
} finally {
245
260
this . duringExplicitConnectDisconnect -- ;
261
+ // Reset isReconnect for next time
262
+ this . isReconnect = false ;
246
263
}
247
264
}
248
265
@@ -433,6 +450,7 @@ export const createBluetoothDeviceWrapper = async (
433
450
logging : Logging ,
434
451
dispatchTypedEvent : TypedServiceEventDispatcher ,
435
452
addedServiceListeners : Record < keyof ServiceConnectionEventMap , boolean > ,
453
+ callbacks : ConnectCallbacks ,
436
454
) : Promise < BluetoothDeviceWrapper | undefined > => {
437
455
try {
438
456
// Reuse our connection objects for the same device as they
@@ -444,6 +462,7 @@ export const createBluetoothDeviceWrapper = async (
444
462
logging ,
445
463
dispatchTypedEvent ,
446
464
addedServiceListeners ,
465
+ callbacks ,
447
466
) ;
448
467
deviceIdToWrapper . set ( device . id , bluetooth ) ;
449
468
await bluetooth . connect ( ) ;
0 commit comments