Skip to content

Commit 990051d

Browse files
Update exceptions handling in BluetoothManager.Device methods. Add a timeout for the connection to server.
1 parent 4446212 commit 990051d

2 files changed

Lines changed: 96 additions & 57 deletions

File tree

src/bluetooth/BluetoothManager.ts

Lines changed: 83 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,6 @@ export class BluetoothManager implements IBluetoothManager {
7171

7272
// Method to remove a device from the list
7373
removeDeviceFromList(device: BluetoothManager.Device): void {
74-
console.warn('removeDeviceFromList is called!', device);
7574
const index = this._deviceList.indexOf(device);
7675
if (index > -1) {
7776
this._deviceList.splice(index, 1);
@@ -119,14 +118,10 @@ export class BluetoothManager implements IBluetoothManager {
119118
): Promise<BluetoothDevice | undefined> {
120119
const isWebBluetoothSupported = await this.checkWebBluetoothSupport()
121120
if (isWebBluetoothSupported) {
122-
try {
123-
const native = await navigator.bluetooth.requestDevice(
124-
registryItem.options
125-
);
126-
return native;
127-
} catch (error) {
128-
console.error(error);
129-
}
121+
const native = await navigator.bluetooth.requestDevice(
122+
registryItem.options
123+
);
124+
return native;
130125
}
131126
else {
132127
return;
@@ -169,19 +164,70 @@ export namespace BluetoothManager {
169164
this.isConnected = false;
170165
this.disconnected.emit(true);
171166
});
167+
const server = this.native.gatt
168+
if (server) {
169+
const timeout = 5000;
170+
const connectWithTimeout = new Promise<void>((resolve, reject) => {
171+
const timeoutId = setTimeout(() => {
172+
reject(
173+
new Error('Connection to GATT server timed out'));
174+
server.disconnect();
175+
this.dispose();
176+
}, timeout);
172177

173-
await this.native.gatt?.connect();
174-
this.isConnected = true;
175-
this.connected.emit(true);
176-
this.isDisposed = false;
177-
const services = await this.native.gatt?.getPrimaryServices();
178-
if (!services || services.length === 0) {
179-
throw new Error('No services found on the device.');
180-
} else {
181-
return services;
178+
server.connect().then(async () => {
179+
clearTimeout(timeoutId);
180+
resolve();
181+
this.isConnected = true;
182+
this.connected.emit(true);
183+
})
184+
.catch((error) => {
185+
server.disconnect();
186+
reject(error);
187+
});
188+
});
189+
await connectWithTimeout
190+
if (server.connected === true) {
191+
const services = await server.getPrimaryServices();
192+
if (!services || services.length === 0) {
193+
throw new Error('Server exists but no service found on the device.');
194+
} else { return services; }
195+
}
196+
else {
197+
throw new Error('There is no connection to server. No attempt to get a service.')
198+
}
199+
}
200+
else {
201+
throw new Error('Server is not defined.');
182202
}
183203
}
184204

205+
/*async connectAndGetAllServices(): Promise<
206+
Array<BluetoothRemoteGATTService> | undefined
207+
> {
208+
this.native.addEventListener('gattserverdisconnected', event => {
209+
this.isConnected = false;
210+
this.disconnected.emit(true);
211+
});
212+
const server = this.native.gatt
213+
if (server) {
214+
server.connect();
215+
if (server.connected === true) {
216+
const services = await server.getPrimaryServices();
217+
this.isConnected = true;
218+
if (!services || services.length === 0) {
219+
throw new Error('Server exists but no service found on the device.');
220+
} else { return services; }
221+
}
222+
else {
223+
throw new Error('There is no connection to server. No attempt to get a service.')
224+
}
225+
}
226+
else {
227+
throw new Error('Server is not defined.');
228+
}
229+
}*/
230+
185231
async disconnect(): Promise<void> {
186232
if (this.native) {
187233
this.native.gatt?.disconnect();
@@ -192,52 +238,38 @@ export namespace BluetoothManager {
192238
async getService(
193239
selectedServiceUUID: string
194240
): Promise<BluetoothRemoteGATTService | undefined> {
195-
try {
196-
const services = await this.connectAndGetAllServices();
197-
if (services) {
198-
const selectedService = services.find(
199-
service => service.uuid === selectedServiceUUID
200-
);
201-
return selectedService;
202-
} else {
203-
console.error('Services could not be reached.');
204-
}
205-
} catch (error) {
206-
console.error('The selected service could not be found', error);
241+
const services = await this.connectAndGetAllServices();
242+
if (services) {
243+
const selectedService = services.find(
244+
service => service.uuid === selectedServiceUUID
245+
);
246+
return selectedService;
247+
} else {
248+
throw new Error('Services could not be reached.');
207249
}
208250
}
209251

210252
async getAllCharacteristics(
211253
serviceUUID: string
212254
): Promise<Array<BluetoothRemoteGATTCharacteristic> | undefined> {
213-
try {
214-
const service = await this.getService(serviceUUID);
215-
if (service) {
216-
return service.getCharacteristics();
217-
} else {
218-
console.error('The requested service is not available.');
219-
}
220-
} catch (error) {
221-
console.error(
222-
'There is no available characteristics on the requested service.',
223-
error
224-
);
255+
const service = await this.getService(serviceUUID);
256+
if (service) {
257+
return service.getCharacteristics();
258+
} else {
259+
throw new Error('The requested service is not available.')
225260
}
226261
}
227262

228263
async getCharacteristic(
229264
serviceUUID: string,
230265
characteristicUUID: string
231266
): Promise<BluetoothRemoteGATTCharacteristic | undefined> {
232-
try {
233-
const service = await this.getService(serviceUUID);
234-
if (service) {
235-
return service.getCharacteristic(characteristicUUID);
236-
} else {
237-
console.error('The requested service is not available.');
238-
}
239-
} catch (error) {
240-
console.error('The requested characteristic is not available.', error);
267+
const service = await this.getService(serviceUUID);
268+
if (service) {
269+
return service.getCharacteristic(characteristicUUID);
270+
271+
} else {
272+
throw new Error('The requested service is not available.');
241273
}
242274
}
243275

src/movehub-extension/moveHub.ts

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ export class MoveHub extends BluetoothManager.Device {
8080
turnSpeed: DEFAULT_CONFIG.TURN_SPEED
8181
};
8282
this.contextCommands = ['bluetooth-manager:disconnect-device','bluetooth-manager:add-lego-movehub-control-panel']
83+
this.isConnected = false;
8384
}
8485
logDebug(message?: any, ...optionalParams: any[]): void {
8586
if (message) {
@@ -98,20 +99,24 @@ export class MoveHub extends BluetoothManager.Device {
9899

99100
async initDevice(): Promise<void> {
100101
this.connected.connect(async (sender, connected: boolean) => {
101-
this.deviceInfo.connected = connected;
102+
if (connected) {
103+
this.deviceInfo.connected = connected;
104+
this.isConnected = connected;
105+
}
102106
console.warn(
103-
'The connection state has changed and is now',
104-
this.deviceInfo.connected
107+
'The connection state is',
108+
this.isConnected
105109
);
106110
this.deviceInfo.identifier = buildShortIdentifier(this.native);
107111
});
108112
this.disconnected.connect(async (sender, disconnected: boolean) => {
109113
if (disconnected) {
110114
this.deviceInfo.connected = false;
115+
this.isConnected = false;
111116
}
112117
console.warn(
113-
'The connection state has changed and is now',
114-
this.deviceInfo.connected
118+
'The connection state is',
119+
this.isConnected
115120
);
116121
});
117122

@@ -122,6 +127,7 @@ export class MoveHub extends BluetoothManager.Device {
122127

123128
// Initialize hub
124129
if (characteristic !== undefined) {
130+
console.log('Initialize the hub new HubAsync')
125131
this.hub = new HubAsync(characteristic, defaultConfiguration);
126132
this.hub.logDebug = this.logDebug;
127133

@@ -135,13 +141,14 @@ export class MoveHub extends BluetoothManager.Device {
135141
defaultConfiguration
136142
);
137143
this.hubControl.start(this.hub);
144+
console.log('Start hubControl')
138145

139146
setInterval(() => {
140147
this.hubControl.update();
141148
}, 100);
142149
});
143150
} else {
144-
console.warn('There is no characteristic available on this service.');
151+
throw new Error('There is no characteristic available on this service.');
145152
}
146153
}
147154
// Methods from Hub

0 commit comments

Comments
 (0)