incyclist-devices 2.3.0-beta.9 → 2.3.1

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 (71) hide show
  1. package/README.MD +55 -0
  2. package/lib/antv2/base/adapter.d.ts +2 -2
  3. package/lib/base/adpater.d.ts +3 -0
  4. package/lib/base/adpater.js +13 -2
  5. package/lib/ble/adapter-factory.d.ts +24 -20
  6. package/lib/ble/adapter-factory.js +36 -13
  7. package/lib/ble/base/adapter.d.ts +4 -2
  8. package/lib/ble/base/adapter.js +43 -24
  9. package/lib/ble/base/comms.d.ts +74 -2
  10. package/lib/ble/base/comms.js +596 -3
  11. package/lib/ble/base/interface.d.ts +9 -5
  12. package/lib/ble/base/interface.js +77 -40
  13. package/lib/ble/base/peripheral.d.ts +7 -3
  14. package/lib/ble/base/peripheral.js +76 -22
  15. package/lib/ble/base/sensor.d.ts +1 -1
  16. package/lib/ble/base/sensor.js +17 -3
  17. package/lib/ble/ble-interface.d.ts +4 -7
  18. package/lib/ble/ble-interface.js +2 -16
  19. package/lib/ble/ble-peripheral.d.ts +0 -1
  20. package/lib/ble/ble-peripheral.js +11 -7
  21. package/lib/ble/characteristics/csc/features.d.ts +10 -0
  22. package/lib/ble/characteristics/csc/features.js +19 -0
  23. package/lib/ble/characteristics/csc/measurement.d.ts +33 -0
  24. package/lib/ble/characteristics/csc/measurement.js +109 -0
  25. package/lib/ble/characteristics/types.d.ts +6 -0
  26. package/lib/ble/characteristics/types.js +2 -0
  27. package/lib/ble/consts.d.ts +1 -0
  28. package/lib/ble/consts.js +2 -1
  29. package/lib/ble/cp/comm.d.ts +1 -1
  30. package/lib/ble/cp/comm.js +2 -2
  31. package/lib/ble/csc/adapter.d.ts +17 -0
  32. package/lib/ble/csc/adapter.js +66 -0
  33. package/lib/ble/csc/index.d.ts +3 -0
  34. package/lib/ble/csc/index.js +19 -0
  35. package/lib/ble/csc/sensor.d.ts +21 -0
  36. package/lib/ble/csc/sensor.js +64 -0
  37. package/lib/ble/csc/types.d.ts +6 -0
  38. package/lib/ble/csc/types.js +2 -0
  39. package/lib/ble/elite/comms.d.ts +1 -1
  40. package/lib/ble/elite/comms.js +2 -2
  41. package/lib/ble/fm/adapter.d.ts +1 -1
  42. package/lib/ble/fm/adapter.js +32 -23
  43. package/lib/ble/fm/comms.d.ts +1 -1
  44. package/lib/ble/fm/comms.js +3 -3
  45. package/lib/ble/fm/sensor.d.ts +1 -1
  46. package/lib/ble/fm/sensor.js +6 -5
  47. package/lib/ble/hr/comm.d.ts +1 -1
  48. package/lib/ble/hr/comm.js +2 -2
  49. package/lib/ble/index.js +2 -0
  50. package/lib/ble/tacx/adapter.d.ts +1 -1
  51. package/lib/ble/tacx/adapter.js +12 -10
  52. package/lib/ble/tacx/comms.d.ts +1 -1
  53. package/lib/ble/tacx/comms.js +2 -2
  54. package/lib/ble/tacx/sensor.js +9 -3
  55. package/lib/ble/types.d.ts +8 -2
  56. package/lib/ble/utils.d.ts +1 -0
  57. package/lib/ble/utils.js +5 -1
  58. package/lib/ble/wahoo/adapter.d.ts +1 -0
  59. package/lib/ble/wahoo/adapter.js +14 -0
  60. package/lib/ble/wahoo/comms.d.ts +1 -1
  61. package/lib/ble/wahoo/comms.js +2 -2
  62. package/lib/ble/wahoo/sensor.js +3 -6
  63. package/lib/direct-connect/base/interface.d.ts +1 -0
  64. package/lib/direct-connect/base/interface.js +8 -3
  65. package/lib/direct-connect/base/peripheral.d.ts +3 -3
  66. package/lib/direct-connect/base/peripheral.js +11 -7
  67. package/lib/modes/ant-fe-adv-st-mode.d.ts +7 -1
  68. package/lib/modes/ant-fe-adv-st-mode.js +4 -3
  69. package/lib/types/adapter.d.ts +2 -0
  70. package/lib/types/interface.d.ts +1 -0
  71. package/package.json +1 -1
@@ -28,6 +28,7 @@ class BleInterface extends events_1.default {
28
28
  if (BleInterface._instance === undefined)
29
29
  BleInterface._instance = new BleInterface(props);
30
30
  else {
31
+ BleInterface._instance.setProps(props);
31
32
  if (props.binding) {
32
33
  BleInterface._instance.setBinding(props.binding);
33
34
  }
@@ -60,9 +61,13 @@ class BleInterface extends events_1.default {
60
61
  }
61
62
  this.internalEvents = new events_1.default();
62
63
  this.onDiscovered = this.onPeripheralFound.bind(this);
63
- if (this.binding)
64
+ const { enabled = true } = props;
65
+ if (this.binding && enabled)
64
66
  this.autoConnect();
65
67
  }
68
+ setProps(props) {
69
+ this.props = props;
70
+ }
66
71
  getLogger() {
67
72
  return this.logger;
68
73
  }
@@ -73,8 +78,9 @@ class BleInterface extends events_1.default {
73
78
  return BleInterface.INTERFACE_NAME;
74
79
  }
75
80
  setBinding(binding) {
81
+ const prev = this.binding;
76
82
  this.binding = binding;
77
- if (!this.isConnected()) {
83
+ if (!prev && !this.isConnected() && this.props.enabled) {
78
84
  this.autoConnect();
79
85
  }
80
86
  }
@@ -110,23 +116,29 @@ class BleInterface extends events_1.default {
110
116
  return success;
111
117
  });
112
118
  }
113
- disconnect() {
119
+ disconnect(connectionLost) {
114
120
  return __awaiter(this, void 0, void 0, function* () {
115
121
  var _a;
116
122
  if (!this.getBinding()) {
117
123
  return false;
118
124
  }
119
- if (!this.isConnected())
125
+ if (!this.isConnected() && !connectionLost)
120
126
  return true;
121
- this.logEvent({ message: 'disconnect request' });
127
+ if (!connectionLost)
128
+ this.logEvent({ message: 'disconnect request' });
129
+ this.emit('disconnect-request');
122
130
  yield this.stopPeripheralScan();
123
- const promises = this.connectedPeripherals.map(p => p.disconnect());
124
- yield Promise.allSettled(promises);
125
- this.connectedPeripherals = [];
131
+ if (connectionLost) {
132
+ this.emitDisconnectAllPeripherals();
133
+ }
134
+ else {
135
+ yield this.disconnectAllPeripherals();
136
+ }
126
137
  if (this.isConnecting())
127
138
  yield ((_a = this.connectTask) === null || _a === void 0 ? void 0 : _a.stop());
128
139
  this.getBinding().removeAllListeners();
129
140
  this.connectAttemptCnt = 0;
141
+ this.emit('disconnect-done');
130
142
  return true;
131
143
  });
132
144
  }
@@ -150,7 +162,7 @@ class BleInterface extends events_1.default {
150
162
  .then(() => { return this.onScanDone(); })
151
163
  .catch(() => []);
152
164
  }
153
- this.logEvent({ message: 'starting scan ..' });
165
+ this.logEvent({ message: 'starting scan ..', interface: 'ble' });
154
166
  this.scanTask = new task_1.InteruptableTask(this.startScan(), {
155
167
  timeout: props.timeout,
156
168
  name: 'scan',
@@ -181,10 +193,14 @@ class BleInterface extends events_1.default {
181
193
  return this.buildDeviceSettings(this.matching);
182
194
  }
183
195
  pauseLogging() {
196
+ this.logEvent({ message: 'pausing logging' });
184
197
  this.logDisabled = true;
198
+ this.getBinding().pauseLogging();
185
199
  }
186
200
  resumeLogging() {
201
+ this.getBinding().resumeLogging();
187
202
  this.logDisabled = false;
203
+ this.logEvent({ message: 'resuming logging' });
188
204
  }
189
205
  isLoggingPaused() {
190
206
  return this.logDisabled;
@@ -203,11 +219,16 @@ class BleInterface extends events_1.default {
203
219
  if (peripheral)
204
220
  return Promise.resolve(peripheral);
205
221
  return new Promise((done) => {
222
+ const wasDiscovering = this.isDiscovering();
223
+ if (!wasDiscovering)
224
+ this.startPeripheralScan();
206
225
  const onDevice = (device) => {
207
226
  if (device.name === settings.name) {
208
227
  const peripheral = this.createPeripheralFromSettings(settings);
209
228
  if (peripheral) {
210
229
  this.off('device', onDevice);
230
+ if (!wasDiscovering)
231
+ this.stopPeripheralScan();
211
232
  done(peripheral);
212
233
  }
213
234
  }
@@ -266,6 +287,20 @@ class BleInterface extends events_1.default {
266
287
  });
267
288
  });
268
289
  }
290
+ emitDisconnectAllPeripherals() {
291
+ this.connectedPeripherals.forEach(p => {
292
+ const peripheral = p.getPeripheral();
293
+ peripheral.emit('disconnect');
294
+ });
295
+ this.connectedPeripherals = [];
296
+ }
297
+ disconnectAllPeripherals() {
298
+ return __awaiter(this, void 0, void 0, function* () {
299
+ const promises = this.connectedPeripherals.map(p => p.disconnect());
300
+ yield Promise.allSettled(promises);
301
+ this.connectedPeripherals = [];
302
+ });
303
+ }
269
304
  isDiscovering() {
270
305
  var _a;
271
306
  return ((_a = this.discoverTask) === null || _a === void 0 ? void 0 : _a.isRunning()) === true;
@@ -289,21 +324,6 @@ class BleInterface extends events_1.default {
289
324
  });
290
325
  });
291
326
  }
292
- pauseDiscovery() {
293
- this.getBinding().off('discover', this.onDiscovered);
294
- return new Promise(done => {
295
- try {
296
- this.getBinding().stopScanning();
297
- done();
298
- }
299
- catch (err) {
300
- done();
301
- }
302
- });
303
- }
304
- resumeDiscovery() {
305
- return this.discoverPeripherals();
306
- }
307
327
  onPeripheralFound(peripheral) {
308
328
  if (!this.isConnected() || !this.isDiscovering())
309
329
  return;
@@ -358,9 +378,10 @@ class BleInterface extends events_1.default {
358
378
  return __awaiter(this, void 0, void 0, function* () {
359
379
  if (!this.isConnected() || !this.isDiscovering())
360
380
  return;
381
+ this.addCompleting(announcement);
382
+ this.logEvent({ message: 'updateWithServices', peripheral: announcement.name });
361
383
  try {
362
- yield this.discoverServices(announcement);
363
- return announcement;
384
+ announcement.serviceUUIDs = yield this.discoverServices(announcement);
364
385
  }
365
386
  catch (err) {
366
387
  this.logError(err, 'updateWithServices');
@@ -373,15 +394,14 @@ class BleInterface extends events_1.default {
373
394
  const device = Object.assign({}, announcement);
374
395
  delete device.peripheral;
375
396
  const { peripheral } = announcement;
376
- let paused = false;
377
397
  try {
378
398
  peripheral.on('error', (err) => {
379
399
  peripheral.removeAllListeners();
380
- this.logEvent({ message: 'Device error', error: err.message });
400
+ this.logEvent({ message: 'peripheral error', error: err.message });
381
401
  });
382
402
  peripheral.on('disconnect', () => {
383
403
  peripheral.removeAllListeners();
384
- this.logEvent({ message: 'Device disconnected' });
404
+ this.logEvent({ message: 'peripheral disconnected' });
385
405
  });
386
406
  yield peripheral.connectAsync();
387
407
  if (peripheral.discoverServicesAsync !== undefined) {
@@ -397,10 +417,7 @@ class BleInterface extends events_1.default {
397
417
  this.logEvent({ message: 'discover services failed', reason: err.message, device });
398
418
  }
399
419
  peripheral === null || peripheral === void 0 ? void 0 : peripheral.removeAllListeners();
400
- if (paused) {
401
- yield this.resumeDiscovery();
402
- }
403
- return device.serviceUUIDs;
420
+ return announcement.serviceUUIDs;
404
421
  });
405
422
  }
406
423
  isScanning() {
@@ -495,7 +512,7 @@ class BleInterface extends events_1.default {
495
512
  const expected = this.expectedServices.map(utils_1.parseUUID);
496
513
  const supported = (_b = found.filter(uuid => expected.includes(uuid))) !== null && _b !== void 0 ? _b : [];
497
514
  if (!supported.length) {
498
- this.logEvent({ message: 'service not supported', name: service.name, uuids: service.serviceUUIDs });
515
+ this.logEvent({ message: 'peripheral not supported', name: service.name, uuids: service.serviceUUIDs });
499
516
  this.addUnsupported(service);
500
517
  }
501
518
  return supported.length > 0;
@@ -529,10 +546,7 @@ class BleInterface extends events_1.default {
529
546
  });
530
547
  this.getBinding().on('stateChange', (state) => {
531
548
  if (state === 'poweredOn') {
532
- this.logEvent({ message: 'BLE connected' });
533
- this.getBinding().removeAllListeners('stateChange');
534
- this.getBinding().on('stateChange', this.onBleStateChange.bind(this));
535
- this.getBinding().on('error', console.log);
549
+ this.onConnected();
536
550
  return done(true);
537
551
  }
538
552
  else {
@@ -541,7 +555,30 @@ class BleInterface extends events_1.default {
541
555
  });
542
556
  });
543
557
  }
558
+ onError(err) {
559
+ this.logError(err, 'BLE connect');
560
+ }
561
+ onConnected() {
562
+ this.logEvent({ message: 'BLE connected' });
563
+ this.getBinding().removeAllListeners('error');
564
+ this.getBinding().removeAllListeners('stateChange');
565
+ this.getBinding().on('stateChange', this.onBleStateChange.bind(this));
566
+ this.getBinding().on('error', this.onError.bind(this));
567
+ }
568
+ onDisconnected() {
569
+ return __awaiter(this, void 0, void 0, function* () {
570
+ this.logEvent({ message: 'BLE Disconnected' });
571
+ yield this.disconnect(true);
572
+ this.getBinding().on('stateChange', this.onBleStateChange.bind(this));
573
+ this.getBinding().on('error', this.onError.bind(this));
574
+ });
575
+ }
544
576
  onBleStateChange(state) {
577
+ if (state !== 'poweredOn') {
578
+ this.onDisconnected();
579
+ }
580
+ else
581
+ this.onConnected();
545
582
  }
546
583
  getAdapterFactory() {
547
584
  return factories_1.BleAdapterFactory.getInstance('ble');
@@ -555,13 +592,13 @@ class BleInterface extends events_1.default {
555
592
  logEvent(event) {
556
593
  if (this.logDisabled && event.message !== 'Error')
557
594
  return;
558
- this.getLogger().logEvent(event);
595
+ this.getLogger().logEvent(Object.assign(Object.assign({}, event), { interface: 'ble' }));
559
596
  const emitPayload = Object.assign({}, event);
560
597
  delete emitPayload.ts;
561
598
  this.emit('log', emitPayload);
562
599
  const w = global.window;
563
600
  if (this.debug || (w === null || w === void 0 ? void 0 : w.SERVICE_DEBUG) || process.env.DEBUG)
564
- console.log(`~~~ ${this.logger.getName().toUpperCase()}-SVC`, event);
601
+ console.log(`~~~ ${this.logger.getName().toUpperCase()}-SVC`, Object.assign(Object.assign({}, event), { interface: 'ble' }));
565
602
  }
566
603
  logError(err, fn, args) {
567
604
  const logInfo = args || {};
@@ -11,22 +11,26 @@ export declare class BlePeripheral implements IBlePeripheral {
11
11
  callback: (data: Buffer) => void;
12
12
  }>;
13
13
  protected disconnecting: boolean;
14
+ protected onErrorHandler: any;
14
15
  constructor(announcement: BlePeripheralAnnouncement);
15
16
  get services(): BleService[];
16
- protected getPeripheral(): BleRawPeripheral;
17
+ getPeripheral(): BleRawPeripheral;
17
18
  connect(): Promise<boolean>;
18
- disconnect(): Promise<boolean>;
19
+ disconnect(connectionLost?: boolean): Promise<boolean>;
19
20
  isConnected(): boolean;
20
21
  isConnecting(): boolean;
21
22
  onDisconnect(callback: () => void): void;
23
+ protected onPeripheralDisconnect(): Promise<void>;
24
+ protected onPeripheralError(err: Error): void;
22
25
  discoverServices(): Promise<string[]>;
23
26
  discoverCharacteristics(serviceUUID: string): Promise<BleCharacteristic[]>;
24
27
  subscribe(characteristicUUID: string, callback: (characteristicUuid: string, data: Buffer) => void): Promise<boolean>;
25
28
  unsubscribe(characteristicUUID: string): Promise<boolean>;
26
29
  subscribeSelected(characteristics: string[], callback: (characteristicUuid: string, data: Buffer) => void): Promise<boolean>;
27
30
  discoverAllCharacteristics(): Promise<string[]>;
31
+ discoverSomeCharacteristics(characteristics: string[]): Promise<string[]>;
28
32
  subscribeAll(callback: (characteristicUuid: string, data: Buffer) => void): Promise<boolean>;
29
- unsubscribeAll(): Promise<boolean>;
33
+ unsubscribeAll(connectionLost?: boolean): Promise<void>;
30
34
  read(characteristicUUID: string): Promise<Buffer>;
31
35
  write(characteristicUUID: string, data: Buffer, options?: BleWriteProps): Promise<Buffer>;
32
36
  protected getRawCharacteristic(uuid: string): BleRawCharacteristic;
@@ -19,6 +19,7 @@ class BlePeripheral {
19
19
  this.characteristics = {};
20
20
  this.subscribed = [];
21
21
  this.disconnecting = false;
22
+ this.onErrorHandler = this.onPeripheralError.bind(this);
22
23
  this.ble = interface_1.BleInterface.getInstance();
23
24
  }
24
25
  get services() {
@@ -29,31 +30,42 @@ class BlePeripheral {
29
30
  }
30
31
  connect() {
31
32
  return __awaiter(this, void 0, void 0, function* () {
32
- yield this.getPeripheral().connectAsync();
33
+ if (this.isConnected())
34
+ return true;
35
+ const peripheral = this.getPeripheral();
36
+ yield peripheral.connectAsync();
33
37
  this.ble.registerConnected(this);
38
+ peripheral.once('disconnect', () => { this.onPeripheralDisconnect(); });
39
+ peripheral.on('error', this.onErrorHandler);
34
40
  this.connected = true;
35
- return true;
41
+ return this.connected;
36
42
  });
37
43
  }
38
44
  disconnect() {
39
- return __awaiter(this, void 0, void 0, function* () {
45
+ return __awaiter(this, arguments, void 0, function* (connectionLost = false) {
40
46
  this.disconnecting = true;
41
47
  if (!this.isConnected())
42
48
  return true;
43
- yield this.unsubscribeAll();
49
+ yield this.unsubscribeAll(connectionLost);
44
50
  Object.keys(this.characteristics).forEach(uuid => {
45
51
  const c = this.characteristics[uuid];
46
52
  c.removeAllListeners();
47
53
  });
48
- if (!this.getPeripheral().disconnectAsync) {
49
- this.getPeripheral().disconnectAsync = () => {
50
- return new Promise((done) => { this.getPeripheral().disconnect(() => { done(); }); });
51
- };
54
+ const peripheral = this.getPeripheral();
55
+ if (peripheral) {
56
+ if (!connectionLost) {
57
+ if (!peripheral.disconnectAsync) {
58
+ peripheral.disconnectAsync = () => {
59
+ return new Promise((done) => { this.getPeripheral().disconnect(() => { done(); }); });
60
+ };
61
+ }
62
+ yield this.getPeripheral().disconnectAsync();
63
+ }
64
+ peripheral.removeAllListeners();
52
65
  }
53
- yield this.getPeripheral().disconnectAsync();
54
66
  this.connected = false;
55
67
  this.disconnecting = false;
56
- return true;
68
+ return !this.connected;
57
69
  });
58
70
  }
59
71
  isConnected() {
@@ -65,13 +77,29 @@ class BlePeripheral {
65
77
  onDisconnect(callback) {
66
78
  this.onDisconnectHandler = callback;
67
79
  }
80
+ onPeripheralDisconnect() {
81
+ return __awaiter(this, void 0, void 0, function* () {
82
+ this.logEvent({ message: 'disconnect' });
83
+ try {
84
+ yield this.disconnect(true);
85
+ }
86
+ catch (_a) { }
87
+ if (this.onDisconnectHandler)
88
+ this.onDisconnectHandler();
89
+ });
90
+ }
91
+ onPeripheralError(err) {
92
+ this.logEvent({ message: 'peripheral error', error: err.message });
93
+ }
68
94
  discoverServices() {
69
95
  return __awaiter(this, void 0, void 0, function* () {
70
96
  if (this.getPeripheral().discoverServicesAsync) {
97
+ this.logEvent({ message: 'discover services' });
71
98
  const services = yield this.getPeripheral().discoverServicesAsync([]);
72
99
  return services.map(s => s.uuid);
73
100
  }
74
101
  else {
102
+ this.logEvent({ message: 'discover services and characteristics' });
75
103
  const res = yield this.getPeripheral().discoverSomeServicesAndCharacteristicsAsync([], []);
76
104
  return res.services.map(s => s.uuid);
77
105
  }
@@ -92,8 +120,17 @@ class BlePeripheral {
92
120
  try {
93
121
  if (this.disconnecting || !this.connected)
94
122
  return false;
123
+ const onData = (data) => {
124
+ try {
125
+ callback(characteristicUUID, data);
126
+ }
127
+ catch (_a) { }
128
+ };
95
129
  const subscription = this.subscribed.find(s => s.uuid === characteristicUUID);
96
130
  if (subscription) {
131
+ const c = this.getRawCharacteristic(characteristicUUID);
132
+ if (c)
133
+ c.on('data', onData);
97
134
  return true;
98
135
  }
99
136
  const c = this.getRawCharacteristic(characteristicUUID);
@@ -114,12 +151,6 @@ class BlePeripheral {
114
151
  }
115
152
  else {
116
153
  if (callback) {
117
- const onData = (data) => {
118
- try {
119
- callback(characteristicUUID, data);
120
- }
121
- catch (_a) { }
122
- };
123
154
  this.subscribed.push({ uuid: characteristicUUID, callback: onData });
124
155
  c.on('data', onData);
125
156
  }
@@ -177,16 +208,16 @@ class BlePeripheral {
177
208
  yield this.discoverAllCharacteristics();
178
209
  }
179
210
  const retry = [];
180
- for (let i = 0; i < characteristics.length; i++) {
181
- const c = this.getRawCharacteristic(characteristics[i]);
211
+ for (const element of characteristics) {
212
+ const c = this.getRawCharacteristic(element);
182
213
  if (c === null || c === void 0 ? void 0 : c.properties.includes('notify')) {
183
214
  const success = yield this.subscribe(c.uuid, callback);
184
215
  if (!success)
185
216
  retry.push(c);
186
217
  }
187
218
  }
188
- for (let i = 0; i < retry.length; i++) {
189
- const c = retry[i];
219
+ for (const element of retry) {
220
+ const c = element;
190
221
  yield this.subscribe(c.uuid, callback);
191
222
  }
192
223
  return true;
@@ -214,6 +245,24 @@ class BlePeripheral {
214
245
  }
215
246
  });
216
247
  }
248
+ discoverSomeCharacteristics(characteristics) {
249
+ return __awaiter(this, void 0, void 0, function* () {
250
+ try {
251
+ const target = characteristics.map(c => (0, utils_1.fullUUID)(c));
252
+ const res = yield this.getPeripheral().discoverSomeServicesAndCharacteristicsAsync([], target);
253
+ const found = [];
254
+ res.characteristics.forEach(c => {
255
+ this.characteristics[(0, utils_1.beautifyUUID)(c.uuid)] = c;
256
+ found.push(c.uuid);
257
+ });
258
+ return found;
259
+ }
260
+ catch (err) {
261
+ this.logEvent({ message: 'Error', fn: 'discoverAllCharacteristics', error: err.message, stack: err.stack });
262
+ return [];
263
+ }
264
+ });
265
+ }
217
266
  subscribeAll(callback) {
218
267
  return __awaiter(this, void 0, void 0, function* () {
219
268
  const characteristics = yield this.discoverAllCharacteristics();
@@ -222,13 +271,16 @@ class BlePeripheral {
222
271
  });
223
272
  }
224
273
  unsubscribeAll() {
225
- return __awaiter(this, void 0, void 0, function* () {
274
+ return __awaiter(this, arguments, void 0, function* (connectionLost = false) {
275
+ if (connectionLost) {
276
+ this.subscribed = [];
277
+ return;
278
+ }
226
279
  const promises = [];
227
280
  this.subscribed.forEach(d => {
228
281
  promises.push(this.unsubscribe(d.uuid));
229
282
  });
230
283
  yield Promise.allSettled(promises);
231
- return true;
232
284
  });
233
285
  }
234
286
  read(characteristicUUID) {
@@ -280,6 +332,8 @@ class BlePeripheral {
280
332
  return this.characteristics[(0, utils_1.beautifyUUID)(uuid)];
281
333
  }
282
334
  logEvent(event) {
335
+ var _a;
336
+ event.peripheral = (_a = this.announcement) === null || _a === void 0 ? void 0 : _a.name;
283
337
  this.ble.logEvent(event);
284
338
  }
285
339
  }
@@ -20,7 +20,7 @@ export declare class TBleSensor extends EventEmitter implements IBleSensor {
20
20
  hasPeripheral(): boolean;
21
21
  startSensor(reconnect?: boolean): Promise<boolean>;
22
22
  protected getRequiredCharacteristics(): Array<string>;
23
- protected subscribe(): Promise<boolean>;
23
+ subscribe(): Promise<boolean>;
24
24
  stopSensor(): Promise<boolean>;
25
25
  reconnectSensor(): Promise<void>;
26
26
  reset(): void;
@@ -74,7 +74,7 @@ class TBleSensor extends events_1.default {
74
74
  return false;
75
75
  if (!reconnect)
76
76
  this.peripheral.onDisconnect(this.reconnectSensor.bind(this));
77
- return yield this.subscribe();
77
+ return true;
78
78
  });
79
79
  }
80
80
  getRequiredCharacteristics() {
@@ -101,11 +101,19 @@ class TBleSensor extends events_1.default {
101
101
  }
102
102
  reconnectSensor() {
103
103
  return __awaiter(this, void 0, void 0, function* () {
104
+ let connected = false;
105
+ let subscribed = false;
104
106
  let success = false;
105
107
  do {
106
- success = yield this.startSensor(true);
108
+ if (!connected) {
109
+ connected = yield this.startSensor(true);
110
+ }
111
+ if (connected && !subscribed) {
112
+ subscribed = yield this.subscribe();
113
+ }
114
+ success = connected && subscribed;
107
115
  if (!success) {
108
- yield (0, utils_1.sleep)(5000);
116
+ yield (0, utils_1.sleep)(1000);
109
117
  }
110
118
  } while (!success || this.stopRequested);
111
119
  });
@@ -119,10 +127,16 @@ class TBleSensor extends events_1.default {
119
127
  }
120
128
  read(characteristicUUID) {
121
129
  var _a;
130
+ if (!this.isConnected()) {
131
+ return Promise.reject(new Error('not connected'));
132
+ }
122
133
  return (_a = this.peripheral) === null || _a === void 0 ? void 0 : _a.read(characteristicUUID);
123
134
  }
124
135
  write(characteristicUUID, data, options) {
125
136
  var _a;
137
+ if (!this.isConnected()) {
138
+ return Promise.reject(new Error('not connected'));
139
+ }
126
140
  return (_a = this.peripheral) === null || _a === void 0 ? void 0 : _a.write(characteristicUUID, data, options);
127
141
  }
128
142
  onData(characteristic, data) {
@@ -1,8 +1,8 @@
1
1
  import { EventLogger } from 'gd-eventlog';
2
2
  import BleAdapterFactory from './adapter-factory';
3
- import { BleInterfaceProps, BlePeripheral, BleDeviceSettings, BleProtocol, BleBinding, BleInterfaceState, BleScanProps, BleCharacteristic, IBleInterface } from './types';
3
+ import { BleInterfaceProps, BlePeripheral, BleDeviceSettings, BleProtocol, BleBinding, BleInterfaceState, BleScanProps, BleCharacteristic } from './types';
4
4
  import { BleComms } from './base/comms';
5
- import { IncyclistScanProps } from '../types';
5
+ import { IncyclistInterface, IncyclistScanProps } from '../types';
6
6
  import BlePeripheralCache from './peripheral-cache';
7
7
  import EventEmitter from 'events';
8
8
  export interface ScanState {
@@ -31,7 +31,7 @@ export interface BleDeviceClassInfo {
31
31
  services: string[];
32
32
  id: string;
33
33
  }
34
- export default class BleInterface extends EventEmitter implements IBleInterface {
34
+ export default class BleInterface extends EventEmitter implements IncyclistInterface {
35
35
  scanState: ScanState;
36
36
  connectState: ConnectState;
37
37
  peripheralCache: BlePeripheralCache;
@@ -62,8 +62,7 @@ export default class BleInterface extends EventEmitter implements IBleInterface
62
62
  pauseLogging(debugOnly?: boolean): void;
63
63
  resumeLogging(): void;
64
64
  protected isDebugEnabled(): boolean;
65
- logEvent(event: any): void;
66
- logError(err: Error, fn: string, args?: any): void;
65
+ protected logEvent(event: any): void;
67
66
  protected onStateChange(state: BleInterfaceState): void;
68
67
  protected onError(err: any): void;
69
68
  connect(to?: number): Promise<boolean>;
@@ -80,8 +79,6 @@ export default class BleInterface extends EventEmitter implements IBleInterface
80
79
  }): Promise<any>;
81
80
  scanForDevice(comms: BleComms, props: IncyclistScanProps): Promise<BlePeripheral>;
82
81
  scan(props?: BleScanProps): Promise<BleDeviceSettings[]>;
83
- protected legacyScan(props?: BleScanProps): Promise<BleDeviceSettings[]>;
84
82
  stopScan(): Promise<boolean>;
85
83
  isScanning(): boolean;
86
- getLogger(): EventLogger;
87
84
  }
@@ -118,10 +118,6 @@ class BleInterface extends events_1.default {
118
118
  console.log('~~~ BLE', event);
119
119
  }
120
120
  }
121
- logError(err, fn, args) {
122
- const logInfo = args || {};
123
- this.logEvent(Object.assign(Object.assign({ message: 'Error', fn }, logInfo), { error: err.message, stack: err.stack }));
124
- }
125
121
  onStateChange(state) {
126
122
  if (state !== 'poweredOn') {
127
123
  this.logEvent({ message: 'Ble disconnected', });
@@ -146,12 +142,10 @@ class BleInterface extends events_1.default {
146
142
  this.resumeLogging();
147
143
  const timeout = this.props.timeout || to || 2000;
148
144
  const connect = new Promise((resolve, reject) => {
149
- this.logEvent({ message: 'Ble connect request', timeout });
145
+ this.logEvent({ message: 'Ble connect request' });
150
146
  if (!this.getBinding())
151
147
  return reject(new Error('no binding defined'));
152
- this.connectState.isConnecting = true;
153
148
  this.connectState.timeout = setTimeout(() => {
154
- console.log('connect timeout');
155
149
  this.connectState.isConnected = false;
156
150
  this.connectState.isConnecting = false;
157
151
  this.connectState.timeout = null;
@@ -500,13 +494,8 @@ class BleInterface extends events_1.default {
500
494
  }
501
495
  scan() {
502
496
  return __awaiter(this, arguments, void 0, function* (props = {}) {
503
- return yield this.legacyScan(props);
504
- });
505
- }
506
- legacyScan() {
507
- return __awaiter(this, arguments, void 0, function* (props = {}) {
508
- this.resumeLogging();
509
497
  this.logEvent({ message: 'starting scan ..' });
498
+ this.resumeLogging();
510
499
  const { timeout, protocol, protocols } = props;
511
500
  const requestedProtocols = protocols || [];
512
501
  if (protocol && !requestedProtocols.find(p => p === protocol))
@@ -629,8 +618,5 @@ class BleInterface extends events_1.default {
629
618
  isScanning() {
630
619
  return this.scanState.isScanning === true;
631
620
  }
632
- getLogger() {
633
- return this.logger;
634
- }
635
621
  }
636
622
  exports.default = BleInterface;
@@ -18,7 +18,6 @@ export default class BlePeripheralConnector implements IBlePeripheralConnector {
18
18
  private emitter;
19
19
  constructor(peripheral: BlePeripheral);
20
20
  logEvent(event: any): void;
21
- logError(err: Error, fn: string, args?: any): void;
22
21
  connect(): Promise<void>;
23
22
  reconnect(): Promise<void>;
24
23
  onDisconnect(): void;
@@ -12,12 +12,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
+ const ble_interface_1 = __importDefault(require("./ble-interface"));
16
+ const gd_eventlog_1 = require("gd-eventlog");
15
17
  const events_1 = __importDefault(require("events"));
16
18
  const utils_1 = require("./utils");
17
- const interface_1 = require("./base/interface");
18
19
  class BlePeripheralConnector {
19
20
  constructor(peripheral) {
20
- this.ble = interface_1.BleInterface.getInstance();
21
+ this.ble = ble_interface_1.default.getInstance();
21
22
  this.peripheral = peripheral;
22
23
  this.emitter = new events_1.default();
23
24
  if (!this.peripheral || !this.ble)
@@ -25,13 +26,16 @@ class BlePeripheralConnector {
25
26
  this.state = { subscribed: [], isConnected: false, isConnecting: false, isInitialized: false, isInitializing: false, isSubscribing: false };
26
27
  this.services = [];
27
28
  this.characteristics = [];
28
- this.logger = this.ble.getLogger();
29
+ this.logger = new gd_eventlog_1.EventLogger('BLE');
29
30
  }
30
31
  logEvent(event) {
31
- this.ble.logEvent(event);
32
- }
33
- logError(err, fn, args) {
34
- this.ble.logError(err, fn, args);
32
+ if (this.logger) {
33
+ this.logger.logEvent(event);
34
+ }
35
+ const w = global.window;
36
+ if ((w === null || w === void 0 ? void 0 : w.DEVICE_DEBUG) || process.env.BLE_DEBUG) {
37
+ console.log('~~~ BLE', event);
38
+ }
35
39
  }
36
40
  connect() {
37
41
  return __awaiter(this, void 0, void 0, function* () {