Skip to content

Commit

Permalink
fix(bluetooth-low-energy): add timeout for app discovery
Browse files Browse the repository at this point in the history
If peripherals are slow to respond when querying services and
characteristics we should drop the connection at some point, otherwise
we end up blocking the scanning for too long.
  • Loading branch information
mKeRix committed Dec 6, 2020
1 parent f8bfaf2 commit 16922ac
Showing 1 changed file with 31 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { Sensor } from '../../entities/sensor';
import { RoomPresenceProxyHandler } from '../room-presence/room-presence.proxy';
import { BluetoothLowEnergyPresenceSensor } from './bluetooth-low-energy-presence.sensor';
import { BluetoothService } from '../bluetooth/bluetooth.service';
import { promiseWithTimeout } from '../../util/promises';

export const NEW_DISTANCE_CHANNEL = 'bluetooth-low-energy.new-distance';
export const APP_DISCOVERY_CHANNEL = 'bluetooth-low-energy.app-discovery';
Expand Down Expand Up @@ -151,22 +152,10 @@ export class BluetoothLowEnergyService
);

try {
const services = await peripheral.discoverServicesAsync([
'5403c8a75c9647e99ab859e373d875a7',
]);

if (services.length > 0) {
const characteristics = await services[0].discoverCharacteristicsAsync([
'21c46f33e813440786012ad281030052',
]);

if (characteristics.length > 0) {
const data = await characteristics[0].readAsync();
return data.toString('utf-8');
}
}

return null;
return await promiseWithTimeout<string>(
BluetoothLowEnergyService.readCompanionAppId(peripheral),
15 * 1000
);
} catch (e) {
this.logger.error(
`Failed to search for companion app at tag ${tag.id}: ${e.message}`,
Expand Down Expand Up @@ -528,4 +517,30 @@ export class BluetoothLowEnergyService
this.companionAppBlacklist.delete(event.tagId);
}
}

/**
* Read companion app ID from a peripheral by looking at the relevant characteristic.
*
* @param peripheral - peripheral to read from
*/
private static async readCompanionAppId(
peripheral: Peripheral
): Promise<string> {
const services = await peripheral.discoverServicesAsync([
'5403c8a75c9647e99ab859e373d875a7',
]);

if (services.length > 0) {
const characteristics = await services[0].discoverCharacteristicsAsync([
'21c46f33e813440786012ad281030052',
]);

if (characteristics.length > 0) {
const data = await characteristics[0].readAsync();
return data.toString('utf-8');
}
}

return null;
}
}

0 comments on commit 16922ac

Please sign in to comment.