incyclist-devices 2.0.5 → 2.0.7

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.
@@ -194,8 +194,8 @@ class AntFEAdapter extends adapter_1.ControllableAntAdapter {
194
194
  const opts = props || {};
195
195
  const { args = {}, user = {} } = opts;
196
196
  return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
197
- const { timeout = 20000 } = props || {};
198
- const totalTimeout = timeout + 10000;
197
+ const { startupTimeout = 20000, reconnectTimeout = 2000 } = props || {};
198
+ const totalTimeout = Math.min(startupTimeout + 10000, startupTimeout * 2);
199
199
  let to;
200
200
  const stopTimeoutCheck = () => {
201
201
  if (to) {
@@ -224,7 +224,7 @@ class AntFEAdapter extends adapter_1.ControllableAntAdapter {
224
224
  }
225
225
  if (this.sensorConnected && !hasData) {
226
226
  try {
227
- yield this.waitForData(timeout);
227
+ yield this.waitForData(startupTimeout);
228
228
  hasData = true;
229
229
  }
230
230
  catch (err) {
@@ -235,12 +235,12 @@ class AntFEAdapter extends adapter_1.ControllableAntAdapter {
235
235
  }
236
236
  catch (_a) { }
237
237
  this.started = false;
238
- return reject(new Error('could not start device, reason: no data received'));
238
+ return reject(new Error('could not start device, reason:no data received'));
239
239
  }
240
240
  }
241
241
  status = { userSent: false, slopeSent: false };
242
242
  if (!hasData) {
243
- yield (0, utils_2.sleep)(2000);
243
+ yield (0, utils_2.sleep)(reconnectTimeout);
244
244
  continue;
245
245
  }
246
246
  if (!this.isReconnecting) {
@@ -65,8 +65,11 @@ class IncyclistDevice extends events_1.default {
65
65
  if (!this.logger || this.paused)
66
66
  return;
67
67
  this.logger.logEvent(event);
68
- const logText = '~~~' + this.getInterface().toUpperCase();
69
- console.log(logText, event);
68
+ const w = global.window;
69
+ if ((w === null || w === void 0 ? void 0 : w.DEVICE_DEBUG) || process.env.BLE_DEBUG || process.env.ANT_DEBUG) {
70
+ const logText = '~~~ ' + this.getInterface().toUpperCase();
71
+ console.log(logText, event);
72
+ }
70
73
  }
71
74
  getMaxUpdateFrequency() {
72
75
  return this.updateFrequency;
@@ -88,7 +88,10 @@ class BleComms extends events_1.default {
88
88
  if (this.logger) {
89
89
  this.logger.logEvent(event);
90
90
  }
91
- console.log('~~~BLE:', event);
91
+ const w = global.window;
92
+ if ((w === null || w === void 0 ? void 0 : w.DEVICE_DEBUG) || process.env.BLE_DEBUG) {
93
+ console.log('~~~ BLE', event);
94
+ }
92
95
  }
93
96
  setLogger(logger) {
94
97
  this.logger = logger;
@@ -201,12 +204,12 @@ class BleComms extends events_1.default {
201
204
  yield connector.connect();
202
205
  if (disconnectSignalled)
203
206
  return;
204
- yield connector.initialize();
205
- if (disconnectSignalled)
206
- return;
207
+ const initialized = yield connector.initialize();
208
+ if (!initialized || disconnectSignalled)
209
+ return done(false);
207
210
  yield this.subscribeAll(connector);
208
211
  if (disconnectSignalled)
209
- return;
212
+ return done(false);
210
213
  this.connectState.isConnected = true;
211
214
  this.state = "connected";
212
215
  this.emit('connected');
@@ -227,6 +230,7 @@ class BleComms extends events_1.default {
227
230
  });
228
231
  }
229
232
  subscribeMultiple(characteristics, conn) {
233
+ this.logEvent({ message: 'subscribe', characteristics });
230
234
  return new Promise(resolve => {
231
235
  try {
232
236
  const connector = conn || this.ble.peripheralCache.getConnector(this.peripheral);
@@ -315,6 +319,9 @@ class BleComms extends events_1.default {
315
319
  const { id, name, address } = this;
316
320
  try {
317
321
  this.peripheral = this.ble.peripheralCache.getPeripheral({ id, name, address });
322
+ const connector = this.ble.peripheralCache.getConnector(this.peripheral);
323
+ if (!connector) {
324
+ }
318
325
  }
319
326
  catch (err) {
320
327
  this.logEvent({ message: 'error', fn: 'connect()', error: err.message, stack: err.stack });
@@ -340,7 +347,7 @@ class BleComms extends events_1.default {
340
347
  if (this.ble.isScanning()) {
341
348
  yield this.ble.stopScan();
342
349
  }
343
- const peripheral = yield this.ble.scanForDevice(this, {}).catch(() => null);
350
+ const peripheral = yield this.ble.scanForDevice(this, {});
344
351
  if (peripheral) {
345
352
  this.peripheral = peripheral;
346
353
  const connected = yield this.connectPeripheral(this.peripheral);
@@ -352,11 +359,10 @@ class BleComms extends events_1.default {
352
359
  }
353
360
  }
354
361
  catch (err) {
355
- console.log('~~~ ERROR', err);
356
362
  error = err;
357
363
  }
358
364
  }
359
- this.logEvent({ message: 'connect result: failure', mode: 'device', device: { id, name, address }, error: error.message, stack: error.stack });
365
+ this.logEvent({ message: 'connect result: failure', mode: 'device', device: { id, name, address }, error: error.message });
360
366
  this.connectState.isConnecting = false;
361
367
  this.connectState.isConnected = false;
362
368
  this.ble.stopConnectSensor();
@@ -366,7 +372,7 @@ class BleComms extends events_1.default {
366
372
  catch (err) {
367
373
  this.connectState.isConnecting = false;
368
374
  this.connectState.isConnected = false;
369
- this.logEvent({ message: 'connect result: error', error: err.message });
375
+ this.logEvent({ message: 'connect result: error', error: err.message, stack: err.stack });
370
376
  this.ble.stopConnectSensor();
371
377
  return false;
372
378
  }
@@ -15,6 +15,7 @@ export interface ScanState {
15
15
  isBackgroundScan: boolean;
16
16
  timeout?: NodeJS.Timeout;
17
17
  peripherals?: Map<string, BlePeripheral>;
18
+ detected?: string[];
18
19
  }
19
20
  export interface ConnectState {
20
21
  isConnecting: boolean;
@@ -80,11 +80,16 @@ class BleInterface extends events_1.default {
80
80
  if (this.logger) {
81
81
  this.logger.logEvent(event);
82
82
  }
83
- console.log('~~BLE:', event);
83
+ const w = global.window;
84
+ if ((w === null || w === void 0 ? void 0 : w.DEVICE_DEBUG) || process.env.BLE_DEBUG) {
85
+ console.log('~~~ BLE', event);
86
+ }
84
87
  }
85
88
  onStateChange(state) {
86
89
  if (state !== 'poweredOn') {
90
+ this.logEvent({ message: 'Ble disconnected', });
87
91
  this.connectState.isConnected = false;
92
+ this.stopConnectSensor();
88
93
  }
89
94
  else {
90
95
  this.connectState.isConnected = true;
@@ -223,7 +228,9 @@ class BleInterface extends events_1.default {
223
228
  chachedPeripheralInfo.state = { isConfigured: false, isLoading: true, isInterrupted: false };
224
229
  yield connector.connect();
225
230
  peripheral.state = connector.getState();
226
- yield connector.initialize();
231
+ const initialized = yield connector.initialize();
232
+ if (!initialized)
233
+ return null;
227
234
  characteristics = connector.getCharachteristics();
228
235
  this.logEvent({ message: 'characteristic info (+):', address: peripheral.address, info: characteristics.map(utils_1.getCharachteristicsInfo) });
229
236
  chachedPeripheralInfo.characteristics = characteristics;
@@ -259,6 +266,7 @@ class BleInterface extends events_1.default {
259
266
  });
260
267
  }
261
268
  onPeripheralFound(p, callback, props = {}) {
269
+ var _a;
262
270
  return __awaiter(this, void 0, void 0, function* () {
263
271
  let peripheral = p;
264
272
  if (!peripheral || !peripheral.advertisement || !peripheral.advertisement.localName) {
@@ -277,18 +285,30 @@ class BleInterface extends events_1.default {
277
285
  if (isPeripheralProcessed) {
278
286
  return;
279
287
  }
288
+ if (scanForDevice) {
289
+ const alreadyDetected = ((_a = this.scanState.detected) === null || _a === void 0 ? void 0 : _a.find(p => p === peripheral.address)) !== undefined;
290
+ if (alreadyDetected)
291
+ return;
292
+ this.scanState.detected.push(peripheral.address);
293
+ }
280
294
  if (scanForDevice) {
281
295
  let found = false;
282
296
  found =
283
- (request.name && peripheral.advertisement && request.name === peripheral.advertisement.localName) ||
284
- (request.address && request.address === peripheral.address);
297
+ (request.name !== undefined && peripheral.advertisement && request.name === peripheral.advertisement.localName) ||
298
+ (request.address !== undefined && request.address === peripheral.address);
299
+ this.logEvent({ message: 'search device: found device', peripheral: (0, utils_1.getPeripheralInfo)(peripheral), scanForDevice, matching: found });
285
300
  if (!found) {
286
301
  return;
287
302
  }
288
- this.logEvent({ message: 'search device: found device', peripheral: (0, utils_1.getPeripheralInfo)(peripheral), scanForDevice, callback: callback !== undefined });
289
303
  this.scanState.peripherals.set(peripheral.address, peripheral);
290
304
  const characteristics = yield this.getCharacteristics(peripheral);
291
- callback(peripheral, characteristics);
305
+ if (characteristics) {
306
+ callback(peripheral, characteristics);
307
+ }
308
+ else {
309
+ callback(null);
310
+ }
311
+ this.stopScan();
292
312
  return;
293
313
  }
294
314
  else {
@@ -297,13 +317,16 @@ class BleInterface extends events_1.default {
297
317
  const { protocolFilter } = props;
298
318
  const connector = this.peripheralCache.getConnector(p);
299
319
  const characteristics = yield this.getCharacteristics(p);
320
+ if (!characteristics) {
321
+ return callback(null);
322
+ }
300
323
  const announcedServices = connector.getServices();
301
324
  const services = announcedServices ? announcedServices.map(utils_1.uuid) : undefined;
302
325
  peripheral = connector.getPeripheral();
303
326
  const DeviceClasses = this.getAdapterFactory().getDeviceClasses(peripheral, { services }) || [];
304
327
  const MatchingClasses = protocolFilter && DeviceClasses ? DeviceClasses.filter(C => protocolFilter.includes(C.protocol)) : DeviceClasses;
305
328
  const DeviceClass = (0, comms_utils_1.getBestDeviceMatch)(MatchingClasses.filter(C => C.isMatching(characteristics.map(c => c.uuid))));
306
- this.logEvent({ message: 'BLE scan: device connected', peripheral: (0, utils_1.getPeripheralInfo)(peripheral), services, protocols: DeviceClasses.map(c => c.protocol) });
329
+ this.logEvent({ message: 'BLE scan: device connected', peripheral: (0, utils_1.getPeripheralInfo)(peripheral), services, protocols: DeviceClasses.map(c => c.protocol), found: DeviceClass !== undefined });
307
330
  if (!DeviceClass)
308
331
  return callback(null);
309
332
  const { id, name, address } = (0, utils_1.getPeripheralInfo)(peripheral);
@@ -340,6 +363,7 @@ class BleInterface extends events_1.default {
340
363
  return new Promise((resolve, reject) => {
341
364
  this.scanState.isScanning = true;
342
365
  this.scanState.peripherals = new Map();
366
+ this.scanState.detected = [];
343
367
  const onTimeout = () => {
344
368
  if (!this.scanState.isScanning || !this.scanState.timeout)
345
369
  return;
@@ -358,7 +382,7 @@ class BleInterface extends events_1.default {
358
382
  if (protocol !== 'tacx') {
359
383
  services = (device.getComms().getServices()) || [];
360
384
  }
361
- ble.startScanning(services, false, (err) => {
385
+ ble.startScanning(services, true, (err) => {
362
386
  if (err) {
363
387
  this.logEvent({ message: `${opStr} result: error`, request, error: err.message });
364
388
  this.scanState.isScanning = false;
@@ -366,6 +390,8 @@ class BleInterface extends events_1.default {
366
390
  }
367
391
  ble.on('discover', (p) => {
368
392
  this.onPeripheralFound(p, (peripheral, characteristics) => {
393
+ if (!peripheral)
394
+ return reject(new Error('could not connect'));
369
395
  device.getComms().characteristics = characteristics;
370
396
  process.nextTick(() => {
371
397
  if (this.scanState.timeout) {
@@ -6,6 +6,7 @@ export type ConnectorState = {
6
6
  isInitializing: boolean;
7
7
  isSubscribing: boolean;
8
8
  subscribed?: string[];
9
+ connectPromise?: Promise<void>;
9
10
  };
10
11
  export default class BlePeripheralConnector implements IBlePeripheralConnector {
11
12
  private state;
@@ -20,7 +21,7 @@ export default class BlePeripheralConnector implements IBlePeripheralConnector {
20
21
  connect(): Promise<void>;
21
22
  reconnect(): Promise<void>;
22
23
  onDisconnect(): void;
23
- initialize(enforce?: boolean): Promise<void>;
24
+ initialize(enforce?: boolean): Promise<boolean>;
24
25
  isSubscribed(characteristicUuid: string): boolean;
25
26
  subscribeAll(callback: (characteristicUuid: string, data: any) => void): Promise<string[]>;
26
27
  subscribe(characteristicUuid: string, timeout?: number): Promise<boolean>;
@@ -32,25 +32,35 @@ class BlePeripheralConnector {
32
32
  if (this.logger) {
33
33
  this.logger.logEvent(event);
34
34
  }
35
- console.log('~~~BLE:', event);
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
+ }
36
39
  }
37
40
  connect() {
38
41
  return __awaiter(this, void 0, void 0, function* () {
39
42
  if (this.state.isConnected)
40
43
  return;
41
44
  this.logEvent({ message: 'connect peripheral', peripheral: this.peripheral.address, state: this.state, peripheralState: this.peripheral.state });
45
+ const wasConnecting = this.state.isConnecting;
42
46
  this.state.isConnecting = true;
43
47
  try {
44
- this.peripheral.on('disconnect', () => { this.onDisconnect(); });
45
- if (!this.state.isConnected || (this.peripheral && this.peripheral.state !== 'connected')) {
46
- yield this.peripheral.connectAsync();
48
+ if (!wasConnecting) {
49
+ this.peripheral.once('disconnect', () => { this.onDisconnect(); });
50
+ if (!this.state.isConnected || (this.peripheral && this.peripheral.state !== 'connected')) {
51
+ this.state.connectPromise = this.peripheral.connectAsync();
52
+ }
47
53
  }
54
+ if (this.state.connectPromise)
55
+ yield this.state.connectPromise;
48
56
  this.state.isConnected = this.peripheral.state === 'connected';
57
+ this.state.connectPromise = undefined;
49
58
  return;
50
59
  }
51
60
  catch (err) {
52
61
  this.logEvent({ message: 'Error', fn: 'connect()', error: err.message });
53
62
  }
63
+ this.state.connectPromise = undefined;
54
64
  this.state.isConnecting = false;
55
65
  });
56
66
  }
@@ -67,43 +77,55 @@ class BlePeripheralConnector {
67
77
  this.state.isConnecting = false;
68
78
  this.state.isInitialized = false;
69
79
  this.state.isInitializing = false;
80
+ this.state.connectPromise = undefined;
81
+ this.state.isSubscribing = false;
82
+ this.state.subscribed = [];
70
83
  this.emitter.emit('disconnect');
71
84
  }
72
85
  initialize(enforce = false) {
73
86
  return __awaiter(this, void 0, void 0, function* () {
74
- if (this.state.isInitialized && !enforce)
75
- return;
76
87
  this.logEvent({ message: 'initialize', peripheral: this.peripheral.address, state: this.state, enforce });
88
+ if (this.state.isInitialized && !enforce)
89
+ return true;
77
90
  if (this.state.isInitialized && enforce) {
78
91
  this.state.isInitialized = false;
79
92
  }
80
- this.state.isInitializing = true;
81
- this.characteristics = undefined;
82
- this.services = undefined;
83
- try {
84
- const res = yield this.peripheral.discoverSomeServicesAndCharacteristicsAsync([], []);
85
- if (this.state.isInitializing) {
86
- this.characteristics = res.characteristics;
87
- this.services = res.services.map(s => typeof (s) === 'string' ? s : s.uuid);
88
- this.state.isInitializing = false;
89
- this.state.isInitialized = this.characteristics !== undefined && this.services !== undefined;
90
- this.logEvent({ message: 'initialize done', peripheral: this.peripheral.address, state: this.state });
93
+ return new Promise((done) => __awaiter(this, void 0, void 0, function* () {
94
+ this.state.isInitializing = true;
95
+ this.characteristics = undefined;
96
+ this.services = undefined;
97
+ try {
98
+ this.emitter.once('disconnect', () => {
99
+ done(false);
100
+ });
101
+ const res = yield this.peripheral.discoverSomeServicesAndCharacteristicsAsync([], []);
102
+ if (this.state.isInitializing) {
103
+ this.characteristics = res.characteristics;
104
+ this.services = res.services.map(s => typeof (s) === 'string' ? s : s.uuid);
105
+ this.state.isInitializing = false;
106
+ this.state.isInitialized = this.characteristics !== undefined && this.services !== undefined;
107
+ this.logEvent({ message: 'initialize done', peripheral: this.peripheral.address, state: this.state });
108
+ return done(true);
109
+ }
110
+ else {
111
+ this.logEvent({ message: 'initialize interrupted', peripheral: this.peripheral.address });
112
+ }
91
113
  }
92
- else {
93
- this.logEvent({ message: 'initialize interrupted', peripheral: this.peripheral.address });
114
+ catch (err) {
115
+ this.logEvent({ message: 'error', fn: 'initialize', error: err.message, stack: err.stack });
116
+ this.state.isInitializing = false;
117
+ this.state.isInitialized = false;
118
+ done(false);
94
119
  }
95
- }
96
- catch (err) {
97
- this.logEvent({ message: 'error', fn: 'initialize', error: err.message, stack: err.stack });
98
- this.state.isInitializing = false;
99
- this.state.isInitialized = false;
100
- }
120
+ }));
101
121
  });
102
122
  }
103
123
  isSubscribed(characteristicUuid) {
104
- return this.state.subscribed.find(c => c === characteristicUuid || (0, utils_1.uuid)(c) === characteristicUuid || c === (0, utils_1.uuid)(characteristicUuid)) !== undefined;
124
+ var _a;
125
+ return ((_a = this.state.subscribed) === null || _a === void 0 ? void 0 : _a.find(c => c === characteristicUuid || (0, utils_1.uuid)(c) === characteristicUuid || c === (0, utils_1.uuid)(characteristicUuid))) !== undefined;
105
126
  }
106
127
  subscribeAll(callback) {
128
+ var _a;
107
129
  return __awaiter(this, void 0, void 0, function* () {
108
130
  const cnt = this.characteristics.length;
109
131
  this.state.isSubscribing = true;
@@ -122,7 +144,7 @@ class BlePeripheralConnector {
122
144
  this.on((0, utils_1.uuid)(c.uuid), callback);
123
145
  }
124
146
  this.logEvent({ message: 'subscribe', peripheral: this.peripheral.address, characteristic: c.uuid, uuid: (0, utils_1.uuid)(c.uuid) });
125
- if (this.state.subscribed.find(uuid => uuid === c.uuid) === undefined) {
147
+ if (((_a = this.state.subscribed) === null || _a === void 0 ? void 0 : _a.find(uuid => uuid === c.uuid)) === undefined) {
126
148
  try {
127
149
  yield this.subscribe(c.uuid, 3000);
128
150
  subscribed.push(c.uuid);
@@ -117,7 +117,7 @@ class BleFmAdapter extends adapter_1.BleControllableAdapter {
117
117
  this.resume();
118
118
  if (this.started && !wasPaused)
119
119
  return true;
120
- this.logEvent(Object.assign(Object.assign({ message: 'starting device' }, this.getSettings()), { protocol: this.getProtocolName(), props, isStarted: this.started }));
120
+ this.logEvent(Object.assign(Object.assign({ message: 'starting device' }, this.getSettings()), { protocol: this.getProtocolName(), props, isStarted: this.started, isConnected: this.getComms().isConnected() }));
121
121
  const { restart = wasPaused } = props;
122
122
  if (!restart && this.ble.isScanning() && !this.getComms().isConnected()) {
123
123
  }
@@ -131,11 +131,11 @@ class BleFmAdapter extends adapter_1.BleControllableAdapter {
131
131
  this.connectPromise = this.connect();
132
132
  const res = yield Promise.race([
133
133
  this.connectPromise.then((connected) => {
134
- this.connectPromise = undefined;
135
134
  return { connected, reason: connected ? null : 'could not connect' };
136
135
  }),
137
136
  (0, utils_1.sleep)(timeout).then(() => ({ connected: false, reason: 'timeout' }))
138
137
  ]);
138
+ this.connectPromise = undefined;
139
139
  const connected = res.connected;
140
140
  if (!connected) {
141
141
  throw new Error(`could not start device, reason:${res.reason}`);
@@ -12,6 +12,8 @@ class BlePeripheralCache {
12
12
  return this.find(adapter.getSettings());
13
13
  }
14
14
  getConnector(peripheral) {
15
+ if (!peripheral)
16
+ return;
15
17
  const info = this.find({ address: peripheral.address });
16
18
  if (!info) {
17
19
  const item = this.add({ address: peripheral.address, ts: Date.now(), peripheral });
@@ -99,7 +101,7 @@ class BlePeripheralCache {
99
101
  const { address } = peripheral;
100
102
  cachedItemIdx = this._findIndex({ address });
101
103
  }
102
- if (cachedItemIdx == -1)
104
+ if (cachedItemIdx === -1)
103
105
  return;
104
106
  this.peripherals.splice(cachedItemIdx);
105
107
  }
@@ -66,7 +66,7 @@ export interface BlePeripheral extends EventEmitter, BlePeripheralIdentifier {
66
66
  export interface IBlePeripheralConnector {
67
67
  connect(): Promise<void>;
68
68
  reconnect(): Promise<void>;
69
- initialize(enforce: boolean): Promise<void>;
69
+ initialize(enforce: boolean): Promise<boolean>;
70
70
  isSubscribed(characteristicUuid: string): boolean;
71
71
  subscribeAll(callback: (characteristicUuid: string, data: any) => void): Promise<string[]>;
72
72
  subscribe(characteristicUuid: string, timeout?: number): Promise<boolean>;
@@ -68,7 +68,7 @@ export declare class DaumClassicSimulator {
68
68
  simulateTimeout(ms: number): void;
69
69
  simulateNoResponse(cnt?: number): void;
70
70
  simulateIllegalResponse(cnt?: number): void;
71
- isPedalling(): 1 | 0;
71
+ isPedalling(): 0 | 1;
72
72
  }
73
73
  export declare class DaumClassicMockBinding extends MockPortBinding {
74
74
  prevCommand: Buffer;
@@ -2,7 +2,7 @@ export declare const DEFAULT_AGE = 30;
2
2
  export declare const DEFAULT_USER_WEIGHT = 75;
3
3
  export declare const DEFAULT_BIKE_WEIGHT = 10;
4
4
  export declare function getCockpit(c: any): "Cardio" | "Fitness" | "Vita De Luxe" | "8008" | "8008 TRS" | "8080" | "Therapie" | "8008 TRS Pro" | "8008 TRS3" | "ergo_lyps Cardio Pro" | "Unknown";
5
- export declare function getBikeType(type: any): 1 | 0;
5
+ export declare function getBikeType(type: any): 0 | 1;
6
6
  export declare function getGender(sex: any): 1 | 2;
7
7
  export declare function getLength(length: any): number;
8
8
  export declare function getWeight(weight?: any): number;
@@ -8,6 +8,7 @@ export default class DaumPremiumAdapter extends DaumAdapter {
8
8
  commProps: SerialCommProps;
9
9
  _startRetryTimeout: number;
10
10
  constructor(settings: SerialDeviceSettings, props?: DeviceProperties);
11
+ logEvent(event: any): void;
11
12
  getName(): string;
12
13
  getUniqueName(): string;
13
14
  getPort(): any;
@@ -60,6 +60,15 @@ class DaumPremiumAdapter extends DaumAdapter_1.default {
60
60
  this.distanceInternal = undefined;
61
61
  this.initData();
62
62
  }
63
+ logEvent(event) {
64
+ if (this.logger) {
65
+ this.logger.logEvent(event);
66
+ }
67
+ const w = global.window;
68
+ if ((w === null || w === void 0 ? void 0 : w.DEVICE_DEBUG) || process.env.BLE_DEBUG) {
69
+ console.log('~~~ DaumPremium', event);
70
+ }
71
+ }
63
72
  getName() {
64
73
  return 'Daum8i';
65
74
  }
@@ -102,19 +111,19 @@ class DaumPremiumAdapter extends DaumAdapter_1.default {
102
111
  return __awaiter(this, void 0, void 0, function* () {
103
112
  var info = {};
104
113
  return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
105
- this.logger.logEvent({ message: "checking device", port: this.getPort() });
114
+ this.logEvent({ message: "checking device", port: this.getPort() });
106
115
  try {
116
+ yield this.bike.close();
107
117
  const connected = yield this.connect();
108
118
  if (!connected)
109
119
  resolve(false);
110
120
  info.deviceType = yield this.bike.getDeviceType();
111
121
  info.version = yield this.bike.getProtocolVersion();
112
- yield this.bike.close();
113
- this.logger.logEvent({ message: "checking device success", port: this.getPort(), info });
122
+ this.logEvent({ message: "checking device success", port: this.getPort(), info });
114
123
  resolve(true);
115
124
  }
116
125
  catch (err) {
117
- this.logger.logEvent({ message: "checking device failed", port: this.getPort(), reason: err.message || err });
126
+ this.logEvent({ message: "checking device failed", port: this.getPort(), reason: err.message || err });
118
127
  resolve(false);
119
128
  }
120
129
  }));
@@ -142,26 +151,26 @@ class DaumPremiumAdapter extends DaumAdapter_1.default {
142
151
  }
143
152
  startRide(props = {}) {
144
153
  return __awaiter(this, void 0, void 0, function* () {
145
- this.logger.logEvent({ message: 'relaunch of device' });
154
+ this.logEvent({ message: 'relaunch of device' });
146
155
  try {
147
156
  yield this.launch(props, true);
148
157
  return true;
149
158
  }
150
159
  catch (err) {
151
- this.logger.logEvent({ message: 'start result: error', error: err.message });
160
+ this.logEvent({ message: 'start result: error', error: err.message });
152
161
  throw new Error(`could not start device, reason:${err.message}`);
153
162
  }
154
163
  });
155
164
  }
156
165
  start(props = {}) {
157
166
  return __awaiter(this, void 0, void 0, function* () {
158
- this.logger.logEvent({ message: 'initial start of device' });
167
+ this.logEvent({ message: 'initial start of device' });
159
168
  try {
160
169
  yield this.launch(props, false);
161
170
  return true;
162
171
  }
163
172
  catch (err) {
164
- this.logger.logEvent({ message: 'start result: error', error: err.message });
173
+ this.logEvent({ message: 'start result: error', error: err.message });
165
174
  throw new Error(`could not start device, reason:${err.message}`);
166
175
  }
167
176
  });
@@ -185,7 +194,6 @@ class DaumPremiumAdapter extends DaumAdapter_1.default {
185
194
  if (!info.version) {
186
195
  info.version = yield this.bike.getProtocolVersion();
187
196
  }
188
- console.log('~~~~ starting Daum8i', this.getCyclingMode().getName(), this.getCyclingMode().getModeProperty('eppSupport'));
189
197
  if (this.getCyclingMode().getModeProperty('eppSupport')) {
190
198
  const bikeType = this.getCyclingMode().getSetting('bikeType');
191
199
  if (!info.upload) {
@@ -41,7 +41,8 @@ class Daum8i {
41
41
  const { logger, serial, path } = props;
42
42
  this.serial = serial;
43
43
  this.path = validatePath(path);
44
- this.logger = logger || (process.env.DEBUG ? DEBUG_LOGGER : new gd_eventlog_1.EventLogger('DaumPremium'));
44
+ const w = global.window;
45
+ this.logger = logger || ((w === null || w === void 0 ? void 0 : w.DEVICE_DEBUG) || process.env.DEBUG ? DEBUG_LOGGER : new gd_eventlog_1.EventLogger('DaumPremium'));
45
46
  this.isLoggingPaused = false;
46
47
  this.connected = false;
47
48
  this.blocked = false;
@@ -75,6 +76,10 @@ class Daum8i {
75
76
  logEvent(e) {
76
77
  if (!this.isLoggingPaused)
77
78
  this.logger.logEvent(e);
79
+ const w = global.window;
80
+ if (w === null || w === void 0 ? void 0 : w.DEVICE_DEBUG) {
81
+ console.log('~~~ DaumPremium', e);
82
+ }
78
83
  }
79
84
  connect() {
80
85
  return __awaiter(this, void 0, void 0, function* () {
@@ -114,6 +119,7 @@ class Daum8i {
114
119
  }
115
120
  this.connected = false;
116
121
  if (this.sp) {
122
+ console.log('~~~ removing all listeners');
117
123
  this.sp.removeAllListeners();
118
124
  this.sp = null;
119
125
  }
@@ -149,6 +155,7 @@ class Daum8i {
149
155
  return __awaiter(this, void 0, void 0, function* () {
150
156
  this.connected = false;
151
157
  if (this.sp) {
158
+ console.log('~~~ removing all listeners');
152
159
  this.sp.removeAllListeners();
153
160
  this.sp = null;
154
161
  }
@@ -421,19 +428,18 @@ class Daum8i {
421
428
  }
422
429
  write(buffer) {
423
430
  return __awaiter(this, void 0, void 0, function* () {
424
- return new Promise(done => {
431
+ return new Promise((done) => __awaiter(this, void 0, void 0, function* () {
425
432
  this.state.writeBusy = true;
426
433
  try {
427
- this.sp.write(buffer, () => {
428
- this.state.writeBusy = false;
429
- done();
430
- });
434
+ yield this.sp.write(buffer);
435
+ this.state.writeBusy = false;
436
+ done();
431
437
  }
432
438
  catch (err) {
433
439
  this.state.writeBusy = false;
434
440
  done();
435
441
  }
436
- });
442
+ }));
437
443
  });
438
444
  }
439
445
  sendACK() {
@@ -143,9 +143,6 @@ class Daum8iMockBinding extends binding_mock_1.MockPortBinding {
143
143
  }
144
144
  this.writeOperation = (() => __awaiter(this, void 0, void 0, function* () {
145
145
  yield (0, utils_1.resolveNextTick)();
146
- if (!this.isOpen || !this.port) {
147
- throw new Error('Write canceled');
148
- }
149
146
  if (this.simulator._isSimulateACKTimeout) {
150
147
  this.simulator._isSimulateACKTimeout = false;
151
148
  }
@@ -164,7 +164,7 @@ class KettlerRacerMockBinding extends binding_mock_1.MockPortBinding {
164
164
  handler(payload);
165
165
  }
166
166
  else {
167
- this, this.emitData('ERROR' + CRLF);
167
+ this.emitData('ERROR' + CRLF);
168
168
  }
169
169
  });
170
170
  });
@@ -31,6 +31,7 @@ export declare class SinglePathScanner {
31
31
  props: SerialScannerProps;
32
32
  logger: EventLogger;
33
33
  constructor(path: string, serial: SerialInterface, props: SerialScannerProps);
34
+ logEvent(event: any): void;
34
35
  onStopRequest(resolve: any): Promise<void>;
35
36
  scan(): Promise<SerialDeviceSettings | undefined>;
36
37
  }
@@ -48,6 +49,7 @@ export default class SerialInterface extends EventEmitter implements IncyclistIn
48
49
  static getInstance(props: SerialInterfaceProps): SerialInterface;
49
50
  static _add(instance: SerialInterface): void;
50
51
  constructor(props: SerialInterfaceProps);
52
+ logEvent(event: any): void;
51
53
  setBinding(binding: BindingInterface): void;
52
54
  getName(): string;
53
55
  isConnected(): boolean;
@@ -32,9 +32,18 @@ class SinglePathScanner {
32
32
  this.props = props;
33
33
  this.logger = props.logger || new gd_eventlog_1.EventLogger('SerialScanner');
34
34
  }
35
+ logEvent(event) {
36
+ if (this.logger) {
37
+ this.logger.logEvent(event);
38
+ }
39
+ const w = global.window;
40
+ if ((w === null || w === void 0 ? void 0 : w.DEVICE_DEBUG) || process.env.BLE_DEBUG) {
41
+ console.log('~~~ SerialScanner', event);
42
+ }
43
+ }
35
44
  onStopRequest(resolve) {
36
45
  return __awaiter(this, void 0, void 0, function* () {
37
- this.logger.logEvent({ message: 'stopping scan', path: this.path });
46
+ this.logEvent({ message: 'stopping scan', path: this.path });
38
47
  yield this.serial.closePort(this.path);
39
48
  this.isScanning = false;
40
49
  resolve(this.result);
@@ -46,7 +55,7 @@ class SinglePathScanner {
46
55
  return;
47
56
  this.isScanning = true;
48
57
  return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
49
- this.logger.logEvent({ message: 'starting scan', path: this.path });
58
+ this.logEvent({ message: 'starting scan', path: this.path });
50
59
  this.serial.scanEvents.on('timeout', () => this.onStopRequest(resolve));
51
60
  this.serial.scanEvents.on('stop', () => this.onStopRequest(resolve));
52
61
  let found = false;
@@ -65,12 +74,13 @@ class SinglePathScanner {
65
74
  found = yield adapter.check();
66
75
  if (found) {
67
76
  const name = adapter.getName();
77
+ yield this.serial.closePort(this.path).catch();
68
78
  resolve(Object.assign(Object.assign({}, adapterSettings), { name }));
69
79
  }
70
80
  yield (0, utils_1.sleep)(100);
71
81
  }
72
82
  catch (err) {
73
- this.logger.logEvent({ message: 'error', fn: 'scan()', error: err.message || err, stack: err.stack });
83
+ this.logEvent({ message: 'error', fn: 'scan()', error: err.message || err, stack: err.stack });
74
84
  yield (0, utils_1.sleep)(100);
75
85
  }
76
86
  }
@@ -113,12 +123,21 @@ class SerialInterface extends events_1.default {
113
123
  this.scanEvents.setMaxListeners(100);
114
124
  this.logger = props.logger || new gd_eventlog_1.EventLogger(`Serial:${ifaceName}`);
115
125
  this.connected = false;
116
- this.logger.logEvent({ message: 'new serial interface', ifaceName });
126
+ this.logEvent({ message: 'new serial interface', ifaceName });
117
127
  if (binding) {
118
128
  this.setBinding(binding);
119
129
  }
120
130
  SerialInterface._add(this);
121
131
  }
132
+ logEvent(event) {
133
+ if (this.logger) {
134
+ this.logger.logEvent(event);
135
+ }
136
+ const w = global.window;
137
+ if ((w === null || w === void 0 ? void 0 : w.DEVICE_DEBUG) || process.env.BLE_DEBUG) {
138
+ console.log('~~~ Serial', event);
139
+ }
140
+ }
122
141
  setBinding(binding) {
123
142
  this.binding = binding;
124
143
  serialport_1.default.getInstance().setBinding(this.ifaceName, binding);
@@ -138,7 +157,7 @@ class SerialInterface extends events_1.default {
138
157
  }
139
158
  try {
140
159
  const SerialPort = this.binding;
141
- const res = yield SerialPort.list();
160
+ yield SerialPort.list();
142
161
  this.connected = true;
143
162
  return true;
144
163
  }
@@ -156,7 +175,7 @@ class SerialInterface extends events_1.default {
156
175
  }
157
176
  openPort(path) {
158
177
  return __awaiter(this, void 0, void 0, function* () {
159
- this.logger.logEvent({ message: 'opening port', path });
178
+ this.logEvent({ message: 'opening port', path });
160
179
  const port = serialport_1.default.getInstance().getSerialPort(this.ifaceName, { path });
161
180
  if (!port) {
162
181
  return null;
@@ -164,20 +183,21 @@ class SerialInterface extends events_1.default {
164
183
  const existing = this.ports.findIndex(p => p.path === path);
165
184
  if (existing !== -1) {
166
185
  const port = this.ports[existing].port;
167
- if (port.isOpen)
186
+ if (port.isOpen) {
168
187
  return port;
188
+ }
169
189
  else {
170
190
  this.ports.splice(existing, 1);
171
191
  }
172
192
  }
173
193
  return new Promise((resolve) => {
174
194
  port.once('error', (err) => {
175
- this.logger.logEvent({ message: 'error', path, error: err || err.message });
195
+ this.logEvent({ message: 'error', path, error: err || err.message });
176
196
  port.removeAllListeners();
177
197
  resolve(null);
178
198
  });
179
199
  port.once('open', () => {
180
- this.logger.logEvent({ message: 'port opened', path });
200
+ this.logEvent({ message: 'port opened', path });
181
201
  port.removeAllListeners();
182
202
  this.ports.push({ path, port });
183
203
  resolve(port);
@@ -188,6 +208,7 @@ class SerialInterface extends events_1.default {
188
208
  }
189
209
  closePort(path) {
190
210
  return __awaiter(this, void 0, void 0, function* () {
211
+ this.logEvent({ message: 'closing port' });
191
212
  const existing = this.ports.findIndex(p => p.path === path);
192
213
  if (existing === -1)
193
214
  return true;
@@ -229,7 +250,7 @@ class SerialInterface extends events_1.default {
229
250
  this.scanEvents.emit('timeout');
230
251
  }, timeout);
231
252
  }
232
- this.logger.logEvent({ message: 'checking for ports ' });
253
+ this.logEvent({ message: 'checking for ports' });
233
254
  this.isScanning = true;
234
255
  do {
235
256
  try {
@@ -245,21 +266,21 @@ class SerialInterface extends events_1.default {
245
266
  console.log('~~~ERROR', err);
246
267
  }
247
268
  if (!paths || paths.length === 0) {
248
- this.logger.logEvent({ message: 'scanning: no ports detected', interface: this.ifaceName, paths: paths.map(p => p.path), timeout });
269
+ this.logEvent({ message: 'scanning: no ports detected', interface: this.ifaceName, paths: paths.map(p => p.path), timeout });
249
270
  yield (0, utils_1.sleep)(1000);
250
271
  }
251
272
  if (Date.now() > toExpiresAt)
252
273
  timeOutExpired = true;
253
274
  } while (this.isScanning && !timeOutExpired && paths.length === 0);
254
275
  if (paths.length === 0) {
255
- this.logger.logEvent({ message: 'nothing to scan ' });
276
+ this.logEvent({ message: 'nothing to scan ' });
256
277
  if (this.toScan) {
257
278
  clearTimeout(this.toScan);
258
279
  this.toScan = null;
259
280
  }
260
281
  return [];
261
282
  }
262
- this.logger.logEvent({ message: 'scanning on ', paths: paths.map(p => p.path), timeout });
283
+ this.logEvent({ message: 'scanning on ', paths: paths.map(p => p.path), timeout });
263
284
  const scanners = paths.map(p => new SinglePathScanner(p.path, this, Object.assign(Object.assign({}, props), { logger: this.logger })));
264
285
  try {
265
286
  yield Promise.all(scanners.map(s => s.scan()
@@ -272,14 +293,14 @@ class SerialInterface extends events_1.default {
272
293
  .catch()));
273
294
  }
274
295
  catch (err) {
275
- this.logger.logEvent({ message: 'error', fn: 'scan()', error: err.message || err, stack: err.stack });
296
+ this.logEvent({ message: 'error', fn: 'scan()', error: err.message || err, stack: err.stack });
276
297
  }
277
298
  if (this.toScan) {
278
299
  clearTimeout(this.toScan);
279
300
  this.toScan = null;
280
301
  }
281
302
  this.isScanning = false;
282
- this.logger.logEvent({ message: 'scan finished on', interface: this.ifaceName, paths: paths.map(p => p.path), devices: detected.map(d => {
303
+ this.logEvent({ message: 'scan finished on', interface: this.ifaceName, paths: paths.map(p => p.path), devices: detected.map(d => {
283
304
  const res = Object.assign({}, d);
284
305
  res.interface = this.ifaceName;
285
306
  return res;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "incyclist-devices",
3
- "version": "2.0.5",
3
+ "version": "2.0.7",
4
4
  "dependencies": {
5
5
  "@serialport/bindings-interface": "^1.2.2",
6
6
  "@serialport/parser-byte-length": "^9.0.1",