Skip to content

Commit

Permalink
prevent crash when no BLE device isc connected
Browse files Browse the repository at this point in the history
  • Loading branch information
Apollon77 committed Oct 31, 2024
1 parent b6bd185 commit 5570317
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,7 @@ For Issues please consider to directly provide debug loggins (see above).

### __WORK IN PROGRESS__
* (dnicolson/Apollon77) Change noble to @stoprocent fork
* (Apollon77) prevent crash when no BLE device isc connected

### 0.10.1 (2023-11-23)
* (Apollon77) Remove duplicate entries in characteristic list
Expand Down
22 changes: 16 additions & 6 deletions src/transport/ble/ble-discovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,16 @@ import { Peripheral } from '@stoprocent/noble';
import GattClient from './gatt-client';
import Debug from 'debug';

let noble: typeof import('@stoprocent/noble');
noble = require('@stoprocent/noble');
if (typeof noble.on !== 'function') {
// The following commit broke the default exported instance of noble:
// https://github.com/abandonware/noble/commit/b67eea246f719947fc45b1b52b856e61637a8a8e
noble = (noble as any)({ extended: false });
let noble: typeof import('@stoprocent/noble') | null = null;
try {
noble = require('@stoprocent/noble');
if (typeof noble?.on !== 'function') {
// The following commit broke the default exported instance of noble:
// https://github.com/abandonware/noble/commit/b67eea246f719947fc45b1b52b856e61637a8a8e
noble = (noble as any)({ extended: false });
}
} catch (error) {
console.error('Cannot start noble. Make sure it is installed and BLE device is connected.');
}
const debug = Debug('hap-controller:gatt-client');

Expand Down Expand Up @@ -168,6 +172,9 @@ export default class BLEDiscovery extends EventEmitter {
* updated in the advertisement.
*/
start(allowDuplicates = false): void {
if (!noble) {
throw new Error('BLE not enabled');
}
this.scanEnabled = true;
this.allowDuplicates = allowDuplicates;

Expand Down Expand Up @@ -207,6 +214,9 @@ export default class BLEDiscovery extends EventEmitter {
* Stop an ongoing discovery process.
*/
stop(): void {
if (!noble) {
throw new Error('BLE not enabled');
}
this.scanEnabled = false;
noble.stopScanning();
noble.removeListener('stateChange', this.handleStateChange);
Expand Down

0 comments on commit 5570317

Please sign in to comment.