incyclist-devices 2.3.9 → 2.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/lib/ble/base/interface.d.ts +6 -3
  2. package/lib/ble/base/interface.js +83 -48
  3. package/lib/ble/fm/adapter.d.ts +2 -1
  4. package/lib/ble/fm/adapter.js +27 -9
  5. package/lib/ble/fm/sensor.js +9 -2
  6. package/lib/ble/wahoo/sensor.d.ts +1 -0
  7. package/lib/ble/wahoo/sensor.js +18 -0
  8. package/package.json +1 -1
  9. package/lib/ble/adapter-factory.d.ts +0 -34
  10. package/lib/ble/adapter-factory.js +0 -110
  11. package/lib/ble/base/comms-utils.d.ts +0 -7
  12. package/lib/ble/base/comms-utils.js +0 -90
  13. package/lib/ble/base/comms.d.ts +0 -75
  14. package/lib/ble/base/comms.js +0 -599
  15. package/lib/ble/ble-interface.d.ts +0 -84
  16. package/lib/ble/ble-interface.js +0 -622
  17. package/lib/ble/ble-peripheral.d.ts +0 -39
  18. package/lib/ble/ble-peripheral.js +0 -252
  19. package/lib/ble/cp/comm.d.ts +0 -30
  20. package/lib/ble/cp/comm.js +0 -126
  21. package/lib/ble/elite/adapter.d.ts +0 -21
  22. package/lib/ble/elite/adapter.js +0 -118
  23. package/lib/ble/elite/comms.d.ts +0 -31
  24. package/lib/ble/elite/comms.js +0 -127
  25. package/lib/ble/elite/index.d.ts +0 -3
  26. package/lib/ble/elite/index.js +0 -10
  27. package/lib/ble/fm/comms.d.ts +0 -49
  28. package/lib/ble/fm/comms.js +0 -506
  29. package/lib/ble/hr/comm.d.ts +0 -19
  30. package/lib/ble/hr/comm.js +0 -65
  31. package/lib/ble/peripheral-cache.d.ts +0 -45
  32. package/lib/ble/peripheral-cache.js +0 -109
  33. package/lib/ble/tacx/comms.d.ts +0 -59
  34. package/lib/ble/tacx/comms.js +0 -634
  35. package/lib/ble/wahoo/comms.d.ts +0 -64
  36. package/lib/ble/wahoo/comms.js +0 -399
  37. package/lib/direct-connect/base/comms.d.ts +0 -3
  38. package/lib/direct-connect/base/comms.js +0 -7
  39. package/lib/direct-connect/base/sensor.d.ts +0 -3
  40. package/lib/direct-connect/base/sensor.js +0 -7
  41. package/lib/direct-connect/utils.d.ts +0 -5
  42. package/lib/direct-connect/utils.js +0 -73
  43. package/lib/factories/index.d.ts +0 -3
  44. package/lib/factories/index.js +0 -10
  45. package/lib/utils/operation.d.ts +0 -17
  46. package/lib/utils/operation.js +0 -20
@@ -1,622 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const gd_eventlog_1 = require("gd-eventlog");
16
- const adapter_factory_1 = __importDefault(require("./adapter-factory"));
17
- const utils_1 = require("./utils");
18
- const comms_utils_1 = require("./base/comms-utils");
19
- const peripheral_cache_1 = __importDefault(require("./peripheral-cache"));
20
- const events_1 = __importDefault(require("events"));
21
- const utils_2 = require("../utils/utils");
22
- const DEFAULT_SCAN_TIMEOUT = 20000;
23
- class BleInterface extends events_1.default {
24
- static getInstance(props = {}) {
25
- if (!BleInterface._instance) {
26
- BleInterface._instance = new BleInterface(props);
27
- }
28
- else {
29
- if (props.binding) {
30
- BleInterface._instance.setBinding(props.binding);
31
- }
32
- if (props.logger) {
33
- BleInterface._instance.logger = props.logger;
34
- }
35
- if (props.log && !BleInterface._instance.logger) {
36
- BleInterface._instance.logger = new gd_eventlog_1.EventLogger('BLE');
37
- }
38
- }
39
- return BleInterface._instance;
40
- }
41
- constructor(props = {}) {
42
- super();
43
- this.scanState = { isScanning: false, isConnecting: false, timeout: undefined, isBackgroundScan: false };
44
- this.connectState = { isConnecting: false, isConnected: false, isInitSuccess: false };
45
- this.emittingAdapters = [];
46
- this.props = props;
47
- if (props.binding)
48
- this.setBinding(props.binding);
49
- this.peripheralCache = new peripheral_cache_1.default();
50
- if (props.logger)
51
- this.logger = props.logger;
52
- else
53
- this.logger = new gd_eventlog_1.EventLogger('BLE');
54
- this.loggingPaused = false;
55
- }
56
- getBinding() { return this.binding; }
57
- setBinding(binding) { if (binding)
58
- this.binding = binding; }
59
- getName() {
60
- return 'ble';
61
- }
62
- getReconnectPause() {
63
- return 1000;
64
- }
65
- startConnectSensor() {
66
- this.sensorIsConnecting = true;
67
- }
68
- stopConnectSensor() {
69
- this.sensorIsConnecting = false;
70
- }
71
- waitForSensorConnectionFinish() {
72
- return __awaiter(this, void 0, void 0, function* () {
73
- while (this.sensorIsConnecting && this.connectState.isConnected) {
74
- yield (0, utils_2.sleep)(100);
75
- }
76
- return;
77
- });
78
- }
79
- getAdapterFactory() {
80
- return adapter_factory_1.default.getInstance();
81
- }
82
- pauseLogging(debugOnly = false) {
83
- if (this.loggingPaused)
84
- return;
85
- this.logEvent({ message: 'pause logging on BLE Interface', debugOnly });
86
- this.loggingPaused = debugOnly;
87
- try {
88
- this.getBinding().pauseLogging();
89
- }
90
- catch (_a) { }
91
- }
92
- resumeLogging() {
93
- if (!this.loggingPaused)
94
- return;
95
- const event = { message: 'resume logging on BLE Interface' };
96
- this.logger.logEvent(event);
97
- if (this.isDebugEnabled()) {
98
- console.log('~~~ BLE', event);
99
- }
100
- this.loggingPaused = false;
101
- try {
102
- this.getBinding().resumeLogging();
103
- }
104
- catch (_a) { }
105
- }
106
- isDebugEnabled() {
107
- const w = global.window;
108
- if ((w === null || w === void 0 ? void 0 : w.DEVICE_DEBUG) || process.env.BLE_DEBUG) {
109
- return true;
110
- }
111
- return false;
112
- }
113
- logEvent(event) {
114
- if (this.logger && !this.loggingPaused) {
115
- this.logger.logEvent(event);
116
- }
117
- if (this.isDebugEnabled()) {
118
- console.log('~~~ BLE', event);
119
- }
120
- }
121
- onStateChange(state) {
122
- if (state !== 'poweredOn') {
123
- this.logEvent({ message: 'Ble disconnected', });
124
- this.connectState.isConnected = false;
125
- this.stopConnectSensor();
126
- }
127
- else {
128
- this.connectState.isConnected = true;
129
- }
130
- }
131
- onError(err) {
132
- this.logEvent({ message: 'error', error: err.message, stack: err.stack });
133
- }
134
- connect(to) {
135
- return __awaiter(this, void 0, void 0, function* () {
136
- if (this.connectState.isConnected) {
137
- return true;
138
- }
139
- if (this.connectState.isConnecting) {
140
- return yield this.connectState.connectPromise;
141
- }
142
- this.resumeLogging();
143
- const timeout = this.props.timeout || to || 2000;
144
- const connect = new Promise((resolve, reject) => {
145
- this.logEvent({ message: 'Ble connect request' });
146
- if (!this.getBinding())
147
- return reject(new Error('no binding defined'));
148
- this.connectState.timeout = setTimeout(() => {
149
- this.connectState.isConnected = false;
150
- this.connectState.isConnecting = false;
151
- this.connectState.timeout = null;
152
- this.logEvent({ message: 'Ble connect result: timeout' });
153
- resolve(false);
154
- }, timeout);
155
- try {
156
- const state = this.getBinding().state;
157
- if (state === 'poweredOn') {
158
- clearTimeout(this.connectState.timeout);
159
- this.connectState.timeout = null;
160
- this.getBinding().removeAllListeners('stateChange');
161
- this.getBinding().on('stateChange', this.onStateChange.bind(this));
162
- this.connectState.isConnected = true;
163
- this.connectState.isConnecting = false;
164
- this.logEvent({ message: 'connect result: already connected' });
165
- resolve(true);
166
- return;
167
- }
168
- else {
169
- this.getBinding().once('error', (err) => {
170
- this.connectState.isConnected = true;
171
- this.connectState.isConnecting = false;
172
- this.logEvent({ message: 'connect result: error', error: err.message });
173
- this.getBinding().on('error', this.onError.bind(this));
174
- return reject(err);
175
- });
176
- this.getBinding().on('stateChange', (state) => {
177
- if (state === 'poweredOn') {
178
- clearTimeout(this.connectState.timeout);
179
- this.connectState.timeout = null;
180
- this.getBinding().removeAllListeners('stateChange');
181
- this.getBinding().on('stateChange', this.onStateChange.bind(this));
182
- this.connectState.isConnected = true;
183
- this.connectState.isConnecting = false;
184
- this.logEvent({ message: 'Ble connect result: success' });
185
- return resolve(true);
186
- }
187
- else {
188
- this.logEvent({ message: 'BLE state change', state });
189
- }
190
- });
191
- }
192
- }
193
- catch (err) {
194
- this.connectState.isConnected = false;
195
- this.connectState.isConnecting = false;
196
- if (this.connectState.timeout)
197
- clearTimeout(this.connectState.timeout);
198
- this.connectState.timeout = null;
199
- this.logEvent({ message: 'Ble connect result: error', error: err.message });
200
- return reject(new Error('bluetooth unavailable, cause: ' + err.message));
201
- }
202
- });
203
- const cleanup = () => {
204
- if (this.connectState.timeout) {
205
- clearTimeout(this.connectState.timeout);
206
- this.connectState.timeout = null;
207
- }
208
- this.connectState.isConnecting = false;
209
- delete this.connectState.connectPromise;
210
- };
211
- this.connectState.isConnecting = true;
212
- this.connectState.connectPromise = connect;
213
- try {
214
- const connected = yield connect;
215
- cleanup();
216
- return connected;
217
- }
218
- catch (err) {
219
- cleanup();
220
- throw err;
221
- }
222
- });
223
- }
224
- disconnect() {
225
- return __awaiter(this, void 0, void 0, function* () {
226
- if (!this.connectState.isConnected) {
227
- return Promise.resolve(true);
228
- }
229
- if (!this.getBinding())
230
- return Promise.reject(new Error('no binding defined'));
231
- this.logEvent({ message: 'disconnect request' });
232
- if (this.scanState.isScanning) {
233
- yield this.stopScan();
234
- }
235
- const devices = this.getAdapterFactory().getAllInstances();
236
- const connectedDevices = devices.filter(d => d.isConnected());
237
- for (let i = 0; i < connectedDevices.length; i++) {
238
- const d = connectedDevices[i];
239
- yield d.close();
240
- }
241
- this.connectState.isConnected = false;
242
- this.connectState.isConnecting = false;
243
- if (this.connectState.timeout) {
244
- clearTimeout(this.connectState.timeout);
245
- this.connectState.timeout = null;
246
- }
247
- this.logEvent({ message: 'disconnect result: success' });
248
- this.pauseLogging();
249
- return true;
250
- });
251
- }
252
- isConnected() {
253
- return this.connectState.isConnected;
254
- }
255
- onDisconnect(peripheral) {
256
- this.peripheralCache.remove(peripheral);
257
- }
258
- scannerWaitForConnection(tsTimeoutExpired) {
259
- return __awaiter(this, void 0, void 0, function* () {
260
- const timeoutExpired = () => {
261
- if (!tsTimeoutExpired)
262
- return false;
263
- return Date.now() >= tsTimeoutExpired;
264
- };
265
- while (!this.isConnected() && this.scanState.isScanning && !timeoutExpired()) {
266
- const connected = yield this.connect();
267
- if (!connected)
268
- yield (0, utils_2.sleep)(this.getReconnectPause());
269
- }
270
- });
271
- }
272
- getCharacteristics(peripheral) {
273
- return __awaiter(this, void 0, void 0, function* () {
274
- let characteristics = undefined;
275
- let chachedPeripheralInfo = this.peripheralCache.find({ peripheral });
276
- if (chachedPeripheralInfo && Date.now() - chachedPeripheralInfo.ts > 600000) {
277
- chachedPeripheralInfo.ts = Date.now();
278
- }
279
- if (!chachedPeripheralInfo) {
280
- chachedPeripheralInfo = this.peripheralCache.add({ address: peripheral.address, ts: Date.now(), peripheral });
281
- }
282
- const connector = chachedPeripheralInfo.connector;
283
- if (!chachedPeripheralInfo.characteristics) {
284
- try {
285
- chachedPeripheralInfo.state = { isConfigured: false, isLoading: true, isInterrupted: false };
286
- yield connector.connect();
287
- peripheral.state = connector.getState();
288
- const initialized = yield connector.initialize();
289
- if (!initialized)
290
- return null;
291
- characteristics = connector.getCharachteristics();
292
- this.logEvent({ message: 'characteristic info (+):', address: peripheral.address, info: characteristics.map(utils_1.getCharachteristicsInfo) });
293
- chachedPeripheralInfo.characteristics = characteristics;
294
- chachedPeripheralInfo.state = { isConfigured: true, isLoading: false, isInterrupted: false };
295
- }
296
- catch (err) {
297
- console.log('~~ ERROR', err);
298
- }
299
- }
300
- else {
301
- characteristics = chachedPeripheralInfo.characteristics;
302
- this.logEvent({ message: 'characteristic info (*):', address: peripheral.address, info: characteristics.map(utils_1.getCharachteristicsInfo) });
303
- }
304
- if (!characteristics)
305
- this.logEvent({ message: 'characteristic info:', info: 'none' });
306
- return characteristics;
307
- });
308
- }
309
- waitForScanFinished(timeout) {
310
- const waitStart = Date.now();
311
- const waitTimeout = waitStart + timeout;
312
- return new Promise((resolve, reject) => {
313
- const waitIv = setInterval(() => {
314
- if (this.scanState.isScanning && Date.now() > waitTimeout) {
315
- clearInterval(waitIv);
316
- return reject(new Error('scanning already in progress'));
317
- }
318
- if (!this.scanState.isScanning) {
319
- clearInterval(waitIv);
320
- return resolve(true);
321
- }
322
- }, 100);
323
- });
324
- }
325
- onPeripheralFound(p_1, callback_1) {
326
- return __awaiter(this, arguments, void 0, function* (p, callback, props = {}) {
327
- var _a;
328
- let peripheral = p;
329
- if (!peripheral || !peripheral.advertisement || !peripheral.advertisement.localName) {
330
- return;
331
- }
332
- const scanForDevice = (props.comms !== undefined) || (props.request !== undefined && props.request !== null);
333
- const request = props.comms ? props.comms.getSettings() : props.request;
334
- if (scanForDevice && this.scanState.peripherals.size > 0) {
335
- return;
336
- }
337
- if (!this.scanState.peripherals)
338
- this.scanState.peripherals = new Map();
339
- if (peripheral.address === undefined || peripheral.address === '')
340
- peripheral.address = peripheral.id || peripheral.name;
341
- const isPeripheralProcessed = this.scanState.peripherals.get(peripheral.address) !== undefined;
342
- if (isPeripheralProcessed) {
343
- return;
344
- }
345
- if (scanForDevice) {
346
- const alreadyDetected = ((_a = this.scanState.detected) === null || _a === void 0 ? void 0 : _a.find(p => p === peripheral.address)) !== undefined;
347
- if (alreadyDetected)
348
- return;
349
- this.scanState.detected.push(peripheral.address);
350
- }
351
- if (scanForDevice) {
352
- let found = false;
353
- found =
354
- (request.name !== undefined && peripheral.advertisement && request.name === peripheral.advertisement.localName) ||
355
- (request.address !== undefined && request.address === peripheral.address);
356
- this.logEvent({ message: 'search device: found device', peripheral: (0, utils_1.getPeripheralInfo)(peripheral), scanForDevice, matching: found });
357
- if (!found) {
358
- return;
359
- }
360
- this.scanState.peripherals.set(peripheral.address, peripheral);
361
- const characteristics = yield this.getCharacteristics(peripheral);
362
- if (characteristics) {
363
- callback(peripheral, characteristics);
364
- }
365
- else {
366
- callback(null);
367
- }
368
- this.stopScan();
369
- return;
370
- }
371
- else {
372
- this.logEvent({ message: 'BLE scan: found device', peripheral: (0, utils_1.getPeripheralInfo)(peripheral), scanForDevice, callback: callback !== undefined });
373
- this.scanState.peripherals.set(peripheral.address, peripheral);
374
- const { protocolFilter } = props;
375
- const connector = this.peripheralCache.getConnector(p);
376
- const characteristics = yield this.getCharacteristics(p);
377
- if (!characteristics) {
378
- return callback(null);
379
- }
380
- const announcedServices = connector.getServices();
381
- const services = announcedServices ? announcedServices.map(utils_1.uuid) : undefined;
382
- peripheral = connector.getPeripheral();
383
- const DeviceClasses = this.getAdapterFactory().getDeviceClasses(peripheral, { services }) || [];
384
- const MatchingClasses = protocolFilter && DeviceClasses ? DeviceClasses.filter(C => protocolFilter.includes(C.protocol)) : DeviceClasses;
385
- const DeviceClass = (0, comms_utils_1.getBestDeviceMatch)(MatchingClasses.filter(C => C.isMatching(characteristics.map(c => c.uuid))));
386
- this.logEvent({ message: 'BLE scan: device connected', peripheral: (0, utils_1.getPeripheralInfo)(peripheral), services, protocols: DeviceClasses.map(c => c.protocol), found: DeviceClass !== undefined });
387
- if (!DeviceClass)
388
- return callback(null);
389
- const { id, name, address } = (0, utils_1.getPeripheralInfo)(peripheral);
390
- const settings = { protocol: DeviceClass.protocol, interface: 'ble', id, name: peripheral.name || name, address: peripheral.address || address };
391
- callback(settings, characteristics, peripheral);
392
- }
393
- });
394
- }
395
- scanForDevice(comms, props) {
396
- return __awaiter(this, void 0, void 0, function* () {
397
- const { timeout = DEFAULT_SCAN_TIMEOUT } = props;
398
- const request = comms.getSettings();
399
- const { protocol } = request;
400
- const ble = this.getBinding();
401
- try {
402
- this.getBinding().setServerDebug(true);
403
- }
404
- catch (_a) { }
405
- if (!this.isConnected()) {
406
- yield this.connect();
407
- }
408
- const device = adapter_factory_1.default.getInstance().createInstance(request);
409
- if (device.isConnected())
410
- return device.getComms().peripheral;
411
- let opStr;
412
- opStr = 'search device';
413
- this.logEvent({ message: 'search device request', request });
414
- const wasLoggingPaused = this.loggingPaused;
415
- this.resumeLogging();
416
- if (this.scanState.isScanning) {
417
- try {
418
- this.logEvent({ message: `${opStr}: waiting for previous scan to finish` });
419
- yield this.waitForScanFinished(timeout);
420
- }
421
- catch (err) {
422
- this.logEvent({ message: `${opStr} result: already scanning`, error: err.message });
423
- throw (err);
424
- }
425
- }
426
- return new Promise((resolve, reject) => {
427
- this.scanState.isScanning = true;
428
- this.scanState.peripherals = new Map();
429
- this.scanState.detected = [];
430
- const onTimeout = () => {
431
- if (!this.scanState.isScanning || !this.scanState.timeout)
432
- return;
433
- this.scanState.timeout = null;
434
- this.logEvent({ message: `${opStr} result: timeout`, request });
435
- ble.removeAllListeners('discover');
436
- this.logEvent({ message: `${opStr}: stop scanning`, request });
437
- if (wasLoggingPaused)
438
- this.pauseLogging();
439
- ble.stopScanning(() => {
440
- this.scanState.isScanning = false;
441
- try {
442
- this.getBinding().setServerDebug(false);
443
- }
444
- catch (_a) { }
445
- reject(new Error('device not found'));
446
- return;
447
- });
448
- };
449
- this.logEvent({ message: `${opStr}: start scanning`, request, timeout });
450
- let services = [];
451
- if (protocol !== 'tacx') {
452
- services = (device.getComms().getServices()) || [];
453
- }
454
- ble.startScanning(services, true, (err) => {
455
- if (err) {
456
- this.logEvent({ message: `${opStr} result: error`, request, error: err.message });
457
- this.scanState.isScanning = false;
458
- return reject(err);
459
- }
460
- ble.on('discover', (p) => {
461
- this.onPeripheralFound(p, (peripheral, characteristics) => {
462
- if (!peripheral)
463
- return reject(new Error('could not connect'));
464
- device.getComms().characteristics = characteristics;
465
- process.nextTick(() => {
466
- if (this.scanState.timeout) {
467
- clearTimeout(this.scanState.timeout);
468
- this.scanState.timeout = null;
469
- }
470
- this.logEvent({ message: `${opStr}: stop scanning`, request });
471
- if (wasLoggingPaused)
472
- this.pauseLogging();
473
- ble.stopScanning(() => {
474
- ble.removeAllListeners('discover');
475
- this.scanState.isScanning = false;
476
- try {
477
- this.getBinding().setServerDebug(false);
478
- }
479
- catch (_a) { }
480
- resolve(peripheral);
481
- });
482
- });
483
- }, { comms });
484
- });
485
- const cachedItem = this.peripheralCache.find(request);
486
- if (cachedItem) {
487
- this.logEvent({ message: `${opStr}: adding peripheral from cache `, peripheral: (0, utils_1.getPeripheralInfo)(cachedItem.peripheral) });
488
- ble.emit('discover', cachedItem.peripheral);
489
- }
490
- });
491
- this.scanState.timeout = setTimeout(onTimeout, timeout);
492
- });
493
- });
494
- }
495
- scan() {
496
- return __awaiter(this, arguments, void 0, function* (props = {}) {
497
- this.logEvent({ message: 'starting scan ..' });
498
- this.resumeLogging();
499
- const { timeout, protocol, protocols } = props;
500
- const requestedProtocols = protocols || [];
501
- if (protocol && !requestedProtocols.find(p => p === protocol))
502
- requestedProtocols.push(protocol);
503
- const protocolFilter = requestedProtocols.length > 0 ? requestedProtocols : null;
504
- const services = protocolFilter === null ? this.getAdapterFactory().getAllSupportedServices() : (0, comms_utils_1.getServicesFromProtocols)(protocolFilter);
505
- const ble = this.getBinding();
506
- if (!ble)
507
- throw new Error('no binding defined');
508
- const opStr = 'scan';
509
- if (this.scanState.isScanning) {
510
- try {
511
- this.logEvent({ message: `${opStr}: waiting for previous scan to finish` });
512
- yield this.waitForScanFinished(timeout);
513
- }
514
- catch (err) {
515
- this.logEvent({ message: `${opStr} result: already scanning` });
516
- throw (err);
517
- }
518
- }
519
- this.scanState.isScanning = true;
520
- this.scanState.emitter = new events_1.default();
521
- const tsStart = Date.now();
522
- const tsTimeoutExpired = timeout ? tsStart + timeout : undefined;
523
- yield this.scannerWaitForConnection(tsTimeoutExpired);
524
- if (Date.now() > tsTimeoutExpired || !this.scanState.isScanning) {
525
- return [];
526
- }
527
- const adjustedScanTimeout = timeout;
528
- const supported = adapter_factory_1.default.getInstance().getAll().map(i => i.protocol);
529
- this.logEvent({ message: 'scan start', services, supported });
530
- return new Promise((resolve, reject) => {
531
- this.scanState.peripherals = new Map();
532
- const detected = [];
533
- const requested = protocolFilter;
534
- const onTimeoutOrStopped = (...args_1) => __awaiter(this, [...args_1], void 0, function* (wasTimeout = false) {
535
- if (!this.scanState.isScanning || !this.scanState.timeout)
536
- return;
537
- if (this.scanState.timeout) {
538
- clearTimeout(this.scanState.timeout);
539
- this.scanState.timeout = null;
540
- }
541
- const devices = detected.map(d => {
542
- const { id, name, address, protocol } = d;
543
- return { id, name, address, protocol };
544
- });
545
- if (wasTimeout)
546
- this.logEvent({ message: `${opStr} result: timeout, devices found`, requested, devices });
547
- ble.removeAllListeners('discover');
548
- yield ble.stopScanning();
549
- resolve(detected);
550
- this.emittingAdapters.forEach(a => {
551
- a.comms.off('data', a.cb);
552
- a.comms.unsubscribeAll();
553
- });
554
- this.emittingAdapters = [];
555
- this.emit('scan stopped', true);
556
- });
557
- if (timeout)
558
- this.scanState.timeout = setTimeout(onTimeoutOrStopped, adjustedScanTimeout);
559
- this.scanState.emitter.on('stop', () => {
560
- this.emit('stop-scan');
561
- onTimeoutOrStopped();
562
- });
563
- ble.startScanning(protocolFilter ? services : [], false, (err) => {
564
- if (err) {
565
- this.logEvent({ message: `${opStr} result: error`, requested, error: err.message });
566
- this.scanState.isScanning = false;
567
- return reject(err);
568
- }
569
- ble.on('discover', (p) => {
570
- this.onPeripheralFound(p, (deviceSettings, characteristics, peripheral) => __awaiter(this, void 0, void 0, function* () {
571
- if (deviceSettings) {
572
- detected.push(deviceSettings);
573
- const device = this.getAdapterFactory().createInstance(deviceSettings);
574
- device.getComms().characteristics = characteristics;
575
- device.getComms().peripheral = peripheral;
576
- try {
577
- yield device.getComms().subscribeAll();
578
- const cb = (deviceData) => { this.emit('data', deviceSettings, deviceData); };
579
- device.getComms().on('data', cb);
580
- this.emittingAdapters.push({ comms: device.getComms(), cb });
581
- }
582
- catch (_a) { }
583
- this.emit('device', deviceSettings);
584
- }
585
- }), { protocolFilter });
586
- });
587
- const cachedItems = this.peripheralCache.filter(protocolFilter ? services : []);
588
- if (cachedItems && cachedItems.length > 0) {
589
- cachedItems.map(c => c.peripheral).forEach(peripheral => {
590
- this.logEvent({ message: `${opStr}: adding peripheral from cache `, peripheral: (0, utils_1.getPeripheralInfo)(peripheral) });
591
- ble.emit('discover', peripheral);
592
- });
593
- }
594
- });
595
- });
596
- });
597
- }
598
- stopScan() {
599
- return __awaiter(this, void 0, void 0, function* () {
600
- this.logEvent({ message: 'stopping scan ..' });
601
- this.pauseLogging(true);
602
- if (!this.isScanning()) {
603
- this.logEvent({ message: 'stopping scan done ..' });
604
- return true;
605
- }
606
- yield new Promise(done => {
607
- var _a;
608
- (_a = this.scanState.emitter) === null || _a === void 0 ? void 0 : _a.emit('stop');
609
- this.once('scan stopped', (res) => {
610
- done(res);
611
- });
612
- });
613
- this.scanState.isScanning = false;
614
- this.logEvent({ message: 'stopping scan done ..' });
615
- return true;
616
- });
617
- }
618
- isScanning() {
619
- return this.scanState.isScanning === true;
620
- }
621
- }
622
- exports.default = BleInterface;
@@ -1,39 +0,0 @@
1
- import { BleCharacteristic, BlePeripheral, IBlePeripheralConnector } from './types';
2
- export type ConnectorState = {
3
- isConnected: boolean;
4
- isConnecting: boolean;
5
- isInitialized: boolean;
6
- isInitializing: boolean;
7
- isSubscribing: boolean;
8
- subscribed?: string[];
9
- connectPromise?: Promise<void>;
10
- };
11
- export default class BlePeripheralConnector implements IBlePeripheralConnector {
12
- private state;
13
- private services;
14
- private characteristics;
15
- private ble;
16
- private peripheral;
17
- private logger?;
18
- private emitter;
19
- constructor(peripheral: BlePeripheral);
20
- logEvent(event: any): void;
21
- connect(): Promise<void>;
22
- reconnect(): Promise<void>;
23
- onDisconnect(): void;
24
- initialize(enforce?: boolean): Promise<boolean>;
25
- isSubscribed(characteristicUuid: string): boolean;
26
- subscribeAll(callback: (characteristicUuid: string, data: any) => void): Promise<string[]>;
27
- subscribe(characteristicUuid: string, timeout?: number): Promise<boolean>;
28
- unsubscribeAll(): void;
29
- unubscribe(c: BleCharacteristic): void;
30
- onData(characteristicUuid: string, data: any): void;
31
- on(characteristicUuid: string, callback: (characteristicUuid: string, data: any) => void): void;
32
- once(characteristicUuid: string, callback: (characteristicUuid: string, data: any) => void): void;
33
- off(characteristicUuid: string, callback: (characteristicUuid: string, data: any) => void): void;
34
- removeAllListeners(characteristicUuid: string): void;
35
- getState(): string;
36
- getCharachteristics(): BleCharacteristic[];
37
- getServices(): string[];
38
- getPeripheral(): BlePeripheral;
39
- }