incyclist-devices 1.4.98 → 1.4.100

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 (128) hide show
  1. package/LICENSE +0 -0
  2. package/lib/CyclingMode.d.ts +76 -76
  3. package/lib/CyclingMode.js +79 -79
  4. package/lib/Device.d.ts +92 -92
  5. package/lib/Device.js +71 -71
  6. package/lib/DeviceProtocol.d.ts +74 -74
  7. package/lib/DeviceProtocol.js +41 -41
  8. package/lib/DeviceRegistry.d.ts +8 -8
  9. package/lib/DeviceRegistry.js +33 -33
  10. package/lib/DeviceSupport.d.ts +34 -34
  11. package/lib/DeviceSupport.js +78 -78
  12. package/lib/ant/AntAdapter.d.ts +50 -50
  13. package/lib/ant/AntAdapter.js +109 -109
  14. package/lib/ant/AntScanner.d.ts +60 -60
  15. package/lib/ant/AntScanner.js +651 -651
  16. package/lib/ant/antfe/AntFEAdapter.d.ts +83 -83
  17. package/lib/ant/antfe/AntFEAdapter.js +652 -652
  18. package/lib/ant/antfe/ant-fe-adv-st-mode.d.ts +9 -9
  19. package/lib/ant/antfe/ant-fe-adv-st-mode.js +51 -51
  20. package/lib/ant/antfe/ant-fe-erg-mode.d.ts +6 -6
  21. package/lib/ant/antfe/ant-fe-erg-mode.js +14 -14
  22. package/lib/ant/antfe/ant-fe-st-mode.d.ts +5 -5
  23. package/lib/ant/antfe/ant-fe-st-mode.js +13 -13
  24. package/lib/ant/anthrm/AntHrmAdapter.d.ts +16 -16
  25. package/lib/ant/anthrm/AntHrmAdapter.js +130 -130
  26. package/lib/ant/antpwr/pwr-adapter.d.ts +49 -49
  27. package/lib/ant/antpwr/pwr-adapter.js +251 -251
  28. package/lib/ant/utils.d.ts +1 -1
  29. package/lib/ant/utils.js +23 -23
  30. package/lib/ble/ble-device.d.ts +63 -63
  31. package/lib/ble/ble-device.js +442 -442
  32. package/lib/ble/ble-erg-mode.d.ts +18 -18
  33. package/lib/ble/ble-erg-mode.js +132 -127
  34. package/lib/ble/ble-interface.d.ts +100 -99
  35. package/lib/ble/ble-interface.js +717 -712
  36. package/lib/ble/ble-peripheral.d.ts +36 -36
  37. package/lib/ble/ble-peripheral.js +200 -200
  38. package/lib/ble/ble-st-mode.d.ts +15 -15
  39. package/lib/ble/ble-st-mode.js +102 -102
  40. package/lib/ble/ble.d.ts +129 -129
  41. package/lib/ble/ble.js +86 -86
  42. package/lib/ble/consts.d.ts +14 -14
  43. package/lib/ble/consts.js +17 -17
  44. package/lib/ble/fm.d.ts +125 -125
  45. package/lib/ble/fm.js +739 -739
  46. package/lib/ble/hrm.d.ts +48 -48
  47. package/lib/ble/hrm.js +134 -134
  48. package/lib/ble/incyclist-protocol.d.ts +31 -31
  49. package/lib/ble/incyclist-protocol.js +147 -147
  50. package/lib/ble/pwr.d.ts +89 -89
  51. package/lib/ble/pwr.js +321 -321
  52. package/lib/ble/tacx.d.ts +90 -90
  53. package/lib/ble/tacx.js +731 -730
  54. package/lib/ble/wahoo-kickr.d.ts +98 -98
  55. package/lib/ble/wahoo-kickr.js +496 -496
  56. package/lib/calculations.d.ts +13 -13
  57. package/lib/calculations.js +150 -150
  58. package/lib/daum/DaumAdapter.d.ts +66 -66
  59. package/lib/daum/DaumAdapter.js +396 -396
  60. package/lib/daum/DaumPowerMeterCyclingMode.d.ts +8 -8
  61. package/lib/daum/DaumPowerMeterCyclingMode.js +21 -21
  62. package/lib/daum/ERGCyclingMode.d.ts +26 -26
  63. package/lib/daum/ERGCyclingMode.js +201 -201
  64. package/lib/daum/SmartTrainerCyclingMode.d.ts +41 -41
  65. package/lib/daum/SmartTrainerCyclingMode.js +344 -344
  66. package/lib/daum/classic/DaumClassicAdapter.d.ts +18 -18
  67. package/lib/daum/classic/DaumClassicAdapter.js +146 -146
  68. package/lib/daum/classic/DaumClassicCyclingMode.d.ts +13 -13
  69. package/lib/daum/classic/DaumClassicCyclingMode.js +97 -97
  70. package/lib/daum/classic/DaumClassicProtocol.d.ts +27 -27
  71. package/lib/daum/classic/DaumClassicProtocol.js +185 -185
  72. package/lib/daum/classic/bike.d.ts +64 -64
  73. package/lib/daum/classic/bike.js +456 -456
  74. package/lib/daum/classic/utils.d.ts +13 -13
  75. package/lib/daum/classic/utils.js +143 -143
  76. package/lib/daum/constants.d.ts +19 -19
  77. package/lib/daum/constants.js +22 -22
  78. package/lib/daum/premium/DaumClassicCyclingMode.d.ts +14 -14
  79. package/lib/daum/premium/DaumClassicCyclingMode.js +86 -86
  80. package/lib/daum/premium/DaumPremiumAdapter.d.ts +12 -12
  81. package/lib/daum/premium/DaumPremiumAdapter.js +131 -131
  82. package/lib/daum/premium/DaumPremiumProtocol.d.ts +32 -32
  83. package/lib/daum/premium/DaumPremiumProtocol.js +207 -207
  84. package/lib/daum/premium/bike.d.ts +123 -123
  85. package/lib/daum/premium/bike.js +894 -894
  86. package/lib/daum/premium/tcpserial.d.ts +33 -33
  87. package/lib/daum/premium/tcpserial.js +123 -123
  88. package/lib/daum/premium/utils.d.ts +62 -62
  89. package/lib/daum/premium/utils.js +376 -376
  90. package/lib/kettler/comms.d.ts +59 -59
  91. package/lib/kettler/comms.js +242 -242
  92. package/lib/kettler/ergo-racer/ERGCyclingMode.d.ts +25 -25
  93. package/lib/kettler/ergo-racer/ERGCyclingMode.js +144 -145
  94. package/lib/kettler/ergo-racer/adapter.d.ts +101 -101
  95. package/lib/kettler/ergo-racer/adapter.js +639 -639
  96. package/lib/kettler/ergo-racer/protocol.d.ts +41 -41
  97. package/lib/kettler/ergo-racer/protocol.js +203 -203
  98. package/lib/modes/power-base.d.ts +20 -20
  99. package/lib/modes/power-base.js +70 -70
  100. package/lib/modes/power-meter.d.ts +20 -20
  101. package/lib/modes/power-meter.js +78 -78
  102. package/lib/modes/simulator.d.ts +29 -29
  103. package/lib/modes/simulator.js +140 -140
  104. package/lib/simulator/Simulator.d.ts +69 -69
  105. package/lib/simulator/Simulator.js +288 -288
  106. package/lib/types/command.d.ts +8 -8
  107. package/lib/types/command.js +2 -2
  108. package/lib/types/route.d.ts +24 -24
  109. package/lib/types/route.js +9 -9
  110. package/lib/types/user.d.ts +11 -11
  111. package/lib/types/user.js +9 -9
  112. package/lib/utils.d.ts +14 -14
  113. package/lib/utils.js +114 -114
  114. package/package.json +46 -46
  115. package/lib/ant/antfe/ant-fe-st-mode copy.d.ts +0 -7
  116. package/lib/ant/antfe/ant-fe-st-mode copy.js +0 -54
  117. package/lib/ant/antpwr/AntPWRAdapter.d.ts +0 -24
  118. package/lib/ant/antpwr/AntPWRAdapter.js +0 -252
  119. package/lib/daum/PowerMeterCyclingMode.d.ts +0 -18
  120. package/lib/daum/PowerMeterCyclingMode.js +0 -78
  121. package/lib/daum/classic/ERGCyclingMode.d.ts +0 -23
  122. package/lib/daum/classic/ERGCyclingMode.js +0 -171
  123. package/lib/daum/indoorbike.d.ts +0 -24
  124. package/lib/daum/indoorbike.js +0 -178
  125. package/lib/kettler/ergo-racer/modes/power-meter.d.ts +0 -18
  126. package/lib/kettler/ergo-racer/modes/power-meter.js +0 -86
  127. package/lib/simulator/simulator-mode.d.ts +0 -28
  128. package/lib/simulator/simulator-mode.js +0 -120
@@ -1,442 +1,442 @@
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
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.BleDevice = void 0;
13
- const gd_eventlog_1 = require("gd-eventlog");
14
- const ble_1 = require("./ble");
15
- const ble_2 = require("./ble");
16
- const CONNECT_WAIT_TIMEOUT = 10000;
17
- const BLE_TIMEOUT = 1000;
18
- class BleDevice extends ble_1.BleDeviceClass {
19
- constructor(props) {
20
- super();
21
- this.characteristics = [];
22
- this.deviceInfo = {};
23
- this.id = props.id;
24
- this.address = props.address;
25
- this.name = props.name;
26
- this.services = props.services;
27
- this.ble = props.ble;
28
- this.characteristics = [];
29
- this.subscribedCharacteristics = [];
30
- this.isInitialized = false;
31
- this.writeQueue = [];
32
- this.workerIv = null;
33
- this.prevMessages = [];
34
- if (props.peripheral) {
35
- const { id, address, advertisement, state } = props.peripheral;
36
- this.peripheral = props.peripheral;
37
- this.id = id;
38
- this.address = address;
39
- this.name = advertisement.localName;
40
- this.services = advertisement.serviceUuids;
41
- this.state = state;
42
- }
43
- if (props.logger) {
44
- this.logger = props.logger;
45
- }
46
- else if (props.log !== false) {
47
- this.logger = new gd_eventlog_1.EventLogger('BleDevice');
48
- }
49
- }
50
- getServices() {
51
- return this.services;
52
- }
53
- logEvent(event) {
54
- if (this.logger) {
55
- this.logger.logEvent(event);
56
- }
57
- console.log('~~~BLE:', event);
58
- }
59
- setLogger(logger) {
60
- this.logger = logger;
61
- }
62
- setInterface(ble) {
63
- this.ble = ble;
64
- }
65
- isMatching(characteristics) {
66
- return true;
67
- }
68
- cleanupListeners() {
69
- if (this.characteristics === undefined) {
70
- this.characteristics = [];
71
- }
72
- else {
73
- const connector = this.ble.getConnector(this.peripheral);
74
- this.characteristics.forEach(c => {
75
- connector.removeAllListeners((0, ble_1.uuid)(c.uuid));
76
- });
77
- }
78
- }
79
- onDisconnect() {
80
- this.logEvent({ message: 'device disconnected', address: this.address, profile: this.getProfile() });
81
- this.state = "disconnected";
82
- if (!this.connectState.isDisconnecting) {
83
- this.peripheral.state = 'disconnected';
84
- this.connectState.isConnecting = false;
85
- this.connectState.isConnected = false;
86
- this.cleanupListeners();
87
- this.subscribedCharacteristics = [];
88
- this.ble.onDisconnect(this.peripheral);
89
- this.connect({ reconnect: true });
90
- }
91
- this.emit('disconnected');
92
- }
93
- waitForConnectFinished(timeout) {
94
- const waitStart = Date.now();
95
- const waitTimeout = waitStart + timeout;
96
- return new Promise((resolve, reject) => {
97
- const waitIv = setInterval(() => {
98
- try {
99
- if (this.connectState.isConnecting && Date.now() > waitTimeout) {
100
- clearInterval(waitIv);
101
- return reject(new Error('connection already in progress'));
102
- }
103
- if (!this.connectState.isConnecting) {
104
- clearInterval(waitIv);
105
- return resolve(true);
106
- }
107
- }
108
- catch (err) {
109
- console.log('~~~ error', err);
110
- }
111
- }, 100);
112
- });
113
- }
114
- hasService(serviceUuid) {
115
- return this.services && this.services.find(s => s === serviceUuid || (0, ble_1.uuid)(serviceUuid)) !== undefined;
116
- }
117
- init() {
118
- return __awaiter(this, void 0, void 0, function* () {
119
- return yield this.initDevice();
120
- });
121
- }
122
- initDevice() {
123
- this.logEvent({ message: 'get device info' });
124
- return this.getDeviceInfo().then(() => {
125
- this.emit('deviceInfo', this.deviceInfo);
126
- this.logEvent(Object.assign({ message: 'device init done' }, this.deviceInfo));
127
- this.isInitialized = true;
128
- return true;
129
- });
130
- }
131
- connectPeripheral(peripheral) {
132
- return __awaiter(this, void 0, void 0, function* () {
133
- this.connectState.isConnecting = true;
134
- try {
135
- const connector = this.ble.getConnector(peripheral);
136
- connector.on('disconnect', () => { this.onDisconnect(); });
137
- yield connector.connect();
138
- yield connector.initialize();
139
- yield this.subscribeAll(connector);
140
- this.connectState.isConnected = true;
141
- this.state = "connected";
142
- this.emit('connected');
143
- yield this.init();
144
- }
145
- catch (err) {
146
- this.logEvent({ message: 'Error', fn: 'connectPeripheral()', error: err.message, stack: err.stack });
147
- }
148
- this.connectState.isConnecting = false;
149
- });
150
- }
151
- subscribeAll(conn) {
152
- return __awaiter(this, void 0, void 0, function* () {
153
- try {
154
- const connector = conn || this.ble.getConnector(this.peripheral);
155
- const subscribed = yield connector.subscribeAll((uuid, data) => { this.onData(uuid, data); });
156
- subscribed.forEach(c => this.subscribedCharacteristics.push(c));
157
- }
158
- catch (err) {
159
- this.logEvent({ message: 'Error', fn: 'subscribeAll()', error: err.message, stack: err.stack });
160
- }
161
- });
162
- }
163
- connect(props) {
164
- return __awaiter(this, void 0, void 0, function* () {
165
- const { reconnect } = props || {};
166
- try {
167
- this.logEvent({ message: reconnect ? 'reconnect' : 'connect', address: this.peripheral ? this.peripheral.address : this.address, state: this.connectState });
168
- if (!reconnect && this.connectState.isConnecting) {
169
- yield this.waitForConnectFinished(CONNECT_WAIT_TIMEOUT);
170
- }
171
- if (this.connectState.isConnected) {
172
- try {
173
- yield this.subscribeAll();
174
- yield this.init();
175
- }
176
- catch (err) {
177
- this.logEvent({ message: 'cannot reconnect', error: err.message || err });
178
- return false;
179
- }
180
- return true;
181
- }
182
- this.connectState.isConnecting = true;
183
- if (!this.peripheral) {
184
- const { id, name, address } = this;
185
- try {
186
- this.peripheral = this.ble.findPeripheral({ id, name, address });
187
- }
188
- catch (err) {
189
- console.log('~~~ error', err);
190
- }
191
- }
192
- if (this.peripheral) {
193
- const { id, address, advertisement } = this.peripheral;
194
- const name = advertisement === null || advertisement === void 0 ? void 0 : advertisement.localName;
195
- this.logEvent({ message: 'connect requested', mode: 'peripheral', device: { id, name, address: address } });
196
- yield this.connectPeripheral(this.peripheral);
197
- this.logEvent({ message: 'connect result: success', mode: 'peripheral', device: { id, name, address } });
198
- return true;
199
- }
200
- else {
201
- const { id, name, address } = this;
202
- let error;
203
- if (this.address || this.id || this.name) {
204
- this.logEvent({ message: 'connect requested', mode: 'device', device: { id, name, address } });
205
- try {
206
- if (this.ble.isScanning()) {
207
- yield this.ble.stopScan();
208
- }
209
- const devices = yield this.ble.scan({ requested: this });
210
- if (devices && devices.length > 0) {
211
- this.peripheral = devices[0].peripheral;
212
- yield this.connectPeripheral(this.peripheral);
213
- this.logEvent({ message: 'connect result: success', mode: 'device', device: { id, name, address } });
214
- this.connectState.isConnecting = false;
215
- this.connectState.isConnected = true;
216
- return true;
217
- }
218
- }
219
- catch (err) {
220
- console.log('~~~ error', err);
221
- error = err;
222
- }
223
- }
224
- this.logEvent({ message: 'connect result: failure', mode: 'device', device: { id, name, address }, error: error.message, stack: error.stack });
225
- this.connectState.isConnecting = false;
226
- this.connectState.isConnected = false;
227
- return false;
228
- }
229
- }
230
- catch (err) {
231
- this.connectState.isConnecting = false;
232
- this.connectState.isConnected = false;
233
- this.logEvent({ message: 'connect result: error', error: err.message });
234
- return false;
235
- }
236
- });
237
- }
238
- disconnect() {
239
- return __awaiter(this, void 0, void 0, function* () {
240
- const { id, name, address } = this;
241
- this.logEvent({ message: 'disconnect requested', device: { id, name, address } });
242
- this.connectState.isDisconnecting = true;
243
- if (this.workerIv) {
244
- this.stopWorker();
245
- }
246
- if (!this.connectState.isConnecting && !this.connectState.isConnected) {
247
- this.connectState.isDisconnecting = false;
248
- this.connectState.isConnecting = false;
249
- this.connectState.isConnected = false;
250
- this.logEvent({ message: 'disconnect result: success', device: { id, name, address } });
251
- return true;
252
- }
253
- if (this.connectState.isConnecting) {
254
- this.cleanupListeners();
255
- setTimeout(() => { this.connectState.isDisconnecting = false; }, 1000);
256
- this.logEvent({ message: 'disconnect result: unclear - connect ongoing', device: { id, name, address } });
257
- this.connectState.isConnecting = false;
258
- this.connectState.isConnected = false;
259
- return true;
260
- }
261
- if (this.connectState.isConnected) {
262
- this.ble.removeConnectedDevice(this);
263
- this.cleanupListeners();
264
- this.logEvent({ message: 'disconnect result: success', device: { id, name, address } });
265
- this.connectState.isDisconnecting = false;
266
- this.connectState.isConnecting = false;
267
- this.connectState.isConnected = false;
268
- return true;
269
- }
270
- });
271
- }
272
- checkForDuplicate(characteristic, data) {
273
- const prev = this.prevMessages.find(i => i.uuid === characteristic);
274
- if (prev) {
275
- if (prev.data === data.toString('hex') && prev.timestamp > Date.now() - 500) {
276
- prev.timestamp = Date.now();
277
- return true;
278
- }
279
- else {
280
- prev.data = data.toString('hex');
281
- prev.timestamp = Date.now();
282
- }
283
- }
284
- else {
285
- this.prevMessages.push({ uuid: characteristic, timestamp: Date.now(), data: data.toString('hex') });
286
- }
287
- return false;
288
- }
289
- onData(characteristic, _data) {
290
- const data = Buffer.from(_data);
291
- const isDuplicate = this.checkForDuplicate(characteristic, data);
292
- if (isDuplicate) {
293
- return false;
294
- }
295
- this.logEvent({ message: 'got data', characteristic, data: data.toString('hex'), writeQueue: this.writeQueue.length });
296
- if (this.writeQueue.length > 0) {
297
- const writeIdx = this.writeQueue.findIndex(i => (0, ble_2.matches)(i.uuid, characteristic));
298
- if (writeIdx !== -1) {
299
- const writeItem = this.writeQueue[writeIdx];
300
- this.writeQueue.splice(writeIdx, 1);
301
- if (writeItem.resolve)
302
- writeItem.resolve(data);
303
- return false;
304
- }
305
- }
306
- return true;
307
- }
308
- timeoutCheck() {
309
- const now = Date.now();
310
- const updatedQueue = [];
311
- let hasTimeout = false;
312
- this.writeQueue.forEach(writeItem => {
313
- if (writeItem.timeout && writeItem.timeout < now) {
314
- if (writeItem.reject) {
315
- hasTimeout = true;
316
- writeItem.reject(new Error('timeout'));
317
- }
318
- }
319
- else {
320
- updatedQueue.push(writeItem);
321
- }
322
- });
323
- if (hasTimeout)
324
- this.writeQueue = updatedQueue;
325
- }
326
- startWorker() {
327
- if (this.workerIv)
328
- return;
329
- this.workerIv = setInterval(() => { this.timeoutCheck(); }, 100);
330
- }
331
- stopWorker() {
332
- if (!this.workerIv)
333
- return;
334
- clearInterval(this.workerIv);
335
- this.workerIv = null;
336
- }
337
- write(characteristicUuid, data, props) {
338
- return __awaiter(this, void 0, void 0, function* () {
339
- try {
340
- if (!this.isConnected())
341
- throw new Error('not connected');
342
- const { withoutResponse, timeout } = props || {};
343
- const connector = this.ble.getConnector(this.peripheral);
344
- const isAlreadySubscribed = connector.isSubscribed(characteristicUuid);
345
- if (!withoutResponse && !this.workerIv) {
346
- this.startWorker();
347
- }
348
- if (!withoutResponse && !isAlreadySubscribed) {
349
- const connector = this.ble.getConnector(this.peripheral);
350
- connector.removeAllListeners(characteristicUuid);
351
- connector.on(characteristicUuid, (uuid, data) => {
352
- this.onData(uuid, data);
353
- });
354
- this.logEvent({ message: 'write:subscribing ', characteristic: characteristicUuid });
355
- yield connector.subscribe(characteristicUuid);
356
- this.subscribedCharacteristics.push(characteristicUuid);
357
- }
358
- return new Promise((resolve, reject) => {
359
- const characteristic = this.characteristics.find(c => c.uuid === characteristicUuid || (0, ble_1.uuid)(c.uuid) === characteristicUuid);
360
- if (!characteristic) {
361
- reject(new Error('Characteristic not found'));
362
- return;
363
- }
364
- if (withoutResponse) {
365
- this.logEvent({ message: 'writing', data: data.toString('hex'), withoutResponse });
366
- characteristic.write(data, withoutResponse);
367
- resolve(new ArrayBuffer(0));
368
- return;
369
- }
370
- else {
371
- const writeId = this.writeQueue.length;
372
- let messageDeleted = false;
373
- const writeTimeout = timeout !== undefined ? timeout : BLE_TIMEOUT;
374
- this.writeQueue.push({ uuid: characteristicUuid.toLocaleLowerCase(), data, timeout: Date.now() + writeTimeout, resolve, reject });
375
- const to = setTimeout(() => {
376
- if (this.writeQueue.length > writeId && !messageDeleted)
377
- this.writeQueue.splice(writeId, 1);
378
- this.logEvent({ message: 'writing response', err: 'timeout' });
379
- reject(new Error('timeout'));
380
- }, 5000);
381
- this.logEvent({ message: 'writing' });
382
- characteristic.write(data, withoutResponse, (err) => {
383
- clearTimeout(to);
384
- this.logEvent({ message: 'writing response', err });
385
- if (err) {
386
- this.writeQueue.splice(writeId, 1);
387
- messageDeleted = true;
388
- reject(err);
389
- }
390
- });
391
- }
392
- });
393
- }
394
- catch (err) {
395
- this.logEvent({ message: 'error', fn: '', error: err.message || err, stack: err.stack });
396
- }
397
- });
398
- }
399
- read(characteristicUuid) {
400
- return new Promise((resolve, reject) => {
401
- if (!this.isConnected())
402
- return reject(new Error('not connected'));
403
- const characteristic = this.characteristics.find(c => c.uuid === characteristicUuid || (0, ble_1.uuid)(c.uuid) === characteristicUuid);
404
- if (!characteristic) {
405
- reject(new Error('Characteristic not found'));
406
- return;
407
- }
408
- characteristic.read((err, data) => {
409
- if (err && data instanceof Error)
410
- reject(err);
411
- else if (data instanceof Error)
412
- reject(data);
413
- else
414
- resolve(data);
415
- });
416
- });
417
- }
418
- getDeviceInfo() {
419
- return __awaiter(this, void 0, void 0, function* () {
420
- const info = this.deviceInfo;
421
- const readValue = (c) => __awaiter(this, void 0, void 0, function* () {
422
- try {
423
- const b = yield this.read(c);
424
- const buffer = b ? Buffer.from(b) : undefined;
425
- return buffer ? buffer.toString() : undefined;
426
- }
427
- catch (_a) {
428
- return undefined;
429
- }
430
- });
431
- info.model = info.model || (yield readValue('2a24'));
432
- info.serialNo = info.serialNo || (yield readValue('2a25'));
433
- info.fwRevision = info.fwRevision || (yield readValue('2a26'));
434
- info.hwRevision = info.hwRevision || (yield readValue('2a27'));
435
- info.swRevision = info.swRevision || (yield readValue('2a28'));
436
- info.manufacturer = info.manufacturer || (yield readValue('2a29'));
437
- this.deviceInfo = info;
438
- return info;
439
- });
440
- }
441
- }
442
- exports.BleDevice = BleDevice;
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.BleDevice = void 0;
13
+ const gd_eventlog_1 = require("gd-eventlog");
14
+ const ble_1 = require("./ble");
15
+ const ble_2 = require("./ble");
16
+ const CONNECT_WAIT_TIMEOUT = 10000;
17
+ const BLE_TIMEOUT = 1000;
18
+ class BleDevice extends ble_1.BleDeviceClass {
19
+ constructor(props) {
20
+ super();
21
+ this.characteristics = [];
22
+ this.deviceInfo = {};
23
+ this.id = props.id;
24
+ this.address = props.address;
25
+ this.name = props.name;
26
+ this.services = props.services;
27
+ this.ble = props.ble;
28
+ this.characteristics = [];
29
+ this.subscribedCharacteristics = [];
30
+ this.isInitialized = false;
31
+ this.writeQueue = [];
32
+ this.workerIv = null;
33
+ this.prevMessages = [];
34
+ if (props.peripheral) {
35
+ const { id, address, advertisement, state } = props.peripheral;
36
+ this.peripheral = props.peripheral;
37
+ this.id = id;
38
+ this.address = address;
39
+ this.name = advertisement.localName;
40
+ this.services = advertisement.serviceUuids;
41
+ this.state = state;
42
+ }
43
+ if (props.logger) {
44
+ this.logger = props.logger;
45
+ }
46
+ else if (props.log !== false) {
47
+ this.logger = new gd_eventlog_1.EventLogger('BleDevice');
48
+ }
49
+ }
50
+ getServices() {
51
+ return this.services;
52
+ }
53
+ logEvent(event) {
54
+ if (this.logger) {
55
+ this.logger.logEvent(event);
56
+ }
57
+ console.log('~~~BLE:', event);
58
+ }
59
+ setLogger(logger) {
60
+ this.logger = logger;
61
+ }
62
+ setInterface(ble) {
63
+ this.ble = ble;
64
+ }
65
+ isMatching(characteristics) {
66
+ return true;
67
+ }
68
+ cleanupListeners() {
69
+ if (this.characteristics === undefined) {
70
+ this.characteristics = [];
71
+ }
72
+ else {
73
+ const connector = this.ble.getConnector(this.peripheral);
74
+ this.characteristics.forEach(c => {
75
+ connector.removeAllListeners((0, ble_1.uuid)(c.uuid));
76
+ });
77
+ }
78
+ }
79
+ onDisconnect() {
80
+ this.logEvent({ message: 'device disconnected', address: this.address, profile: this.getProfile() });
81
+ this.state = "disconnected";
82
+ if (!this.connectState.isDisconnecting) {
83
+ this.peripheral.state = 'disconnected';
84
+ this.connectState.isConnecting = false;
85
+ this.connectState.isConnected = false;
86
+ this.cleanupListeners();
87
+ this.subscribedCharacteristics = [];
88
+ this.ble.onDisconnect(this.peripheral);
89
+ this.connect({ reconnect: true });
90
+ }
91
+ this.emit('disconnected');
92
+ }
93
+ waitForConnectFinished(timeout) {
94
+ const waitStart = Date.now();
95
+ const waitTimeout = waitStart + timeout;
96
+ return new Promise((resolve, reject) => {
97
+ const waitIv = setInterval(() => {
98
+ try {
99
+ if (this.connectState.isConnecting && Date.now() > waitTimeout) {
100
+ clearInterval(waitIv);
101
+ return reject(new Error('connection already in progress'));
102
+ }
103
+ if (!this.connectState.isConnecting) {
104
+ clearInterval(waitIv);
105
+ return resolve(true);
106
+ }
107
+ }
108
+ catch (err) {
109
+ console.log('~~~ error', err);
110
+ }
111
+ }, 100);
112
+ });
113
+ }
114
+ hasService(serviceUuid) {
115
+ return this.services && this.services.find(s => s === serviceUuid || (0, ble_1.uuid)(serviceUuid)) !== undefined;
116
+ }
117
+ init() {
118
+ return __awaiter(this, void 0, void 0, function* () {
119
+ return yield this.initDevice();
120
+ });
121
+ }
122
+ initDevice() {
123
+ this.logEvent({ message: 'get device info' });
124
+ return this.getDeviceInfo().then(() => {
125
+ this.emit('deviceInfo', this.deviceInfo);
126
+ this.logEvent(Object.assign({ message: 'device init done' }, this.deviceInfo));
127
+ this.isInitialized = true;
128
+ return true;
129
+ });
130
+ }
131
+ connectPeripheral(peripheral) {
132
+ return __awaiter(this, void 0, void 0, function* () {
133
+ this.connectState.isConnecting = true;
134
+ try {
135
+ const connector = this.ble.getConnector(peripheral);
136
+ connector.on('disconnect', () => { this.onDisconnect(); });
137
+ yield connector.connect();
138
+ yield connector.initialize();
139
+ yield this.subscribeAll(connector);
140
+ this.connectState.isConnected = true;
141
+ this.state = "connected";
142
+ this.emit('connected');
143
+ yield this.init();
144
+ }
145
+ catch (err) {
146
+ this.logEvent({ message: 'Error', fn: 'connectPeripheral()', error: err.message, stack: err.stack });
147
+ }
148
+ this.connectState.isConnecting = false;
149
+ });
150
+ }
151
+ subscribeAll(conn) {
152
+ return __awaiter(this, void 0, void 0, function* () {
153
+ try {
154
+ const connector = conn || this.ble.getConnector(this.peripheral);
155
+ const subscribed = yield connector.subscribeAll((uuid, data) => { this.onData(uuid, data); });
156
+ subscribed.forEach(c => this.subscribedCharacteristics.push(c));
157
+ }
158
+ catch (err) {
159
+ this.logEvent({ message: 'Error', fn: 'subscribeAll()', error: err.message, stack: err.stack });
160
+ }
161
+ });
162
+ }
163
+ connect(props) {
164
+ return __awaiter(this, void 0, void 0, function* () {
165
+ const { reconnect } = props || {};
166
+ try {
167
+ this.logEvent({ message: reconnect ? 'reconnect' : 'connect', address: this.peripheral ? this.peripheral.address : this.address, state: this.connectState });
168
+ if (!reconnect && this.connectState.isConnecting) {
169
+ yield this.waitForConnectFinished(CONNECT_WAIT_TIMEOUT);
170
+ }
171
+ if (this.connectState.isConnected) {
172
+ try {
173
+ yield this.subscribeAll();
174
+ yield this.init();
175
+ }
176
+ catch (err) {
177
+ this.logEvent({ message: 'cannot reconnect', error: err.message || err });
178
+ return false;
179
+ }
180
+ return true;
181
+ }
182
+ this.connectState.isConnecting = true;
183
+ if (!this.peripheral) {
184
+ const { id, name, address } = this;
185
+ try {
186
+ this.peripheral = this.ble.findPeripheral({ id, name, address });
187
+ }
188
+ catch (err) {
189
+ console.log('~~~ error', err);
190
+ }
191
+ }
192
+ if (this.peripheral) {
193
+ const { id, address, advertisement } = this.peripheral;
194
+ const name = advertisement === null || advertisement === void 0 ? void 0 : advertisement.localName;
195
+ this.logEvent({ message: 'connect requested', mode: 'peripheral', device: { id, name, address: address } });
196
+ yield this.connectPeripheral(this.peripheral);
197
+ this.logEvent({ message: 'connect result: success', mode: 'peripheral', device: { id, name, address } });
198
+ return true;
199
+ }
200
+ else {
201
+ const { id, name, address } = this;
202
+ let error;
203
+ if (this.address || this.id || this.name) {
204
+ this.logEvent({ message: 'connect requested', mode: 'device', device: { id, name, address } });
205
+ try {
206
+ if (this.ble.isScanning()) {
207
+ yield this.ble.stopScan();
208
+ }
209
+ const devices = yield this.ble.scan({ requested: this });
210
+ if (devices && devices.length > 0) {
211
+ this.peripheral = devices[0].peripheral;
212
+ yield this.connectPeripheral(this.peripheral);
213
+ this.logEvent({ message: 'connect result: success', mode: 'device', device: { id, name, address } });
214
+ this.connectState.isConnecting = false;
215
+ this.connectState.isConnected = true;
216
+ return true;
217
+ }
218
+ }
219
+ catch (err) {
220
+ console.log('~~~ error', err);
221
+ error = err;
222
+ }
223
+ }
224
+ this.logEvent({ message: 'connect result: failure', mode: 'device', device: { id, name, address }, error: error.message, stack: error.stack });
225
+ this.connectState.isConnecting = false;
226
+ this.connectState.isConnected = false;
227
+ return false;
228
+ }
229
+ }
230
+ catch (err) {
231
+ this.connectState.isConnecting = false;
232
+ this.connectState.isConnected = false;
233
+ this.logEvent({ message: 'connect result: error', error: err.message });
234
+ return false;
235
+ }
236
+ });
237
+ }
238
+ disconnect() {
239
+ return __awaiter(this, void 0, void 0, function* () {
240
+ const { id, name, address } = this;
241
+ this.logEvent({ message: 'disconnect requested', device: { id, name, address } });
242
+ this.connectState.isDisconnecting = true;
243
+ if (this.workerIv) {
244
+ this.stopWorker();
245
+ }
246
+ if (!this.connectState.isConnecting && !this.connectState.isConnected) {
247
+ this.connectState.isDisconnecting = false;
248
+ this.connectState.isConnecting = false;
249
+ this.connectState.isConnected = false;
250
+ this.logEvent({ message: 'disconnect result: success', device: { id, name, address } });
251
+ return true;
252
+ }
253
+ if (this.connectState.isConnecting) {
254
+ this.cleanupListeners();
255
+ setTimeout(() => { this.connectState.isDisconnecting = false; }, 1000);
256
+ this.logEvent({ message: 'disconnect result: unclear - connect ongoing', device: { id, name, address } });
257
+ this.connectState.isConnecting = false;
258
+ this.connectState.isConnected = false;
259
+ return true;
260
+ }
261
+ if (this.connectState.isConnected) {
262
+ this.ble.removeConnectedDevice(this);
263
+ this.cleanupListeners();
264
+ this.logEvent({ message: 'disconnect result: success', device: { id, name, address } });
265
+ this.connectState.isDisconnecting = false;
266
+ this.connectState.isConnecting = false;
267
+ this.connectState.isConnected = false;
268
+ return true;
269
+ }
270
+ });
271
+ }
272
+ checkForDuplicate(characteristic, data) {
273
+ const prev = this.prevMessages.find(i => i.uuid === characteristic);
274
+ if (prev) {
275
+ if (prev.data === data.toString('hex') && prev.timestamp > Date.now() - 500) {
276
+ prev.timestamp = Date.now();
277
+ return true;
278
+ }
279
+ else {
280
+ prev.data = data.toString('hex');
281
+ prev.timestamp = Date.now();
282
+ }
283
+ }
284
+ else {
285
+ this.prevMessages.push({ uuid: characteristic, timestamp: Date.now(), data: data.toString('hex') });
286
+ }
287
+ return false;
288
+ }
289
+ onData(characteristic, _data) {
290
+ const data = Buffer.from(_data);
291
+ const isDuplicate = this.checkForDuplicate(characteristic, data);
292
+ if (isDuplicate) {
293
+ return false;
294
+ }
295
+ this.logEvent({ message: 'got data', characteristic, data: data.toString('hex'), writeQueue: this.writeQueue.length });
296
+ if (this.writeQueue.length > 0) {
297
+ const writeIdx = this.writeQueue.findIndex(i => (0, ble_2.matches)(i.uuid, characteristic));
298
+ if (writeIdx !== -1) {
299
+ const writeItem = this.writeQueue[writeIdx];
300
+ this.writeQueue.splice(writeIdx, 1);
301
+ if (writeItem.resolve)
302
+ writeItem.resolve(data);
303
+ return false;
304
+ }
305
+ }
306
+ return true;
307
+ }
308
+ timeoutCheck() {
309
+ const now = Date.now();
310
+ const updatedQueue = [];
311
+ let hasTimeout = false;
312
+ this.writeQueue.forEach(writeItem => {
313
+ if (writeItem.timeout && writeItem.timeout < now) {
314
+ if (writeItem.reject) {
315
+ hasTimeout = true;
316
+ writeItem.reject(new Error('timeout'));
317
+ }
318
+ }
319
+ else {
320
+ updatedQueue.push(writeItem);
321
+ }
322
+ });
323
+ if (hasTimeout)
324
+ this.writeQueue = updatedQueue;
325
+ }
326
+ startWorker() {
327
+ if (this.workerIv)
328
+ return;
329
+ this.workerIv = setInterval(() => { this.timeoutCheck(); }, 100);
330
+ }
331
+ stopWorker() {
332
+ if (!this.workerIv)
333
+ return;
334
+ clearInterval(this.workerIv);
335
+ this.workerIv = null;
336
+ }
337
+ write(characteristicUuid, data, props) {
338
+ return __awaiter(this, void 0, void 0, function* () {
339
+ try {
340
+ if (!this.isConnected())
341
+ throw new Error('not connected');
342
+ const { withoutResponse, timeout } = props || {};
343
+ const connector = this.ble.getConnector(this.peripheral);
344
+ const isAlreadySubscribed = connector.isSubscribed(characteristicUuid);
345
+ if (!withoutResponse && !this.workerIv) {
346
+ this.startWorker();
347
+ }
348
+ if (!withoutResponse && !isAlreadySubscribed) {
349
+ const connector = this.ble.getConnector(this.peripheral);
350
+ connector.removeAllListeners(characteristicUuid);
351
+ connector.on(characteristicUuid, (uuid, data) => {
352
+ this.onData(uuid, data);
353
+ });
354
+ this.logEvent({ message: 'write:subscribing ', characteristic: characteristicUuid });
355
+ yield connector.subscribe(characteristicUuid);
356
+ this.subscribedCharacteristics.push(characteristicUuid);
357
+ }
358
+ return new Promise((resolve, reject) => {
359
+ const characteristic = this.characteristics.find(c => c.uuid === characteristicUuid || (0, ble_1.uuid)(c.uuid) === characteristicUuid);
360
+ if (!characteristic) {
361
+ reject(new Error('Characteristic not found'));
362
+ return;
363
+ }
364
+ if (withoutResponse) {
365
+ this.logEvent({ message: 'writing', data: data.toString('hex'), withoutResponse });
366
+ characteristic.write(data, withoutResponse);
367
+ resolve(new ArrayBuffer(0));
368
+ return;
369
+ }
370
+ else {
371
+ const writeId = this.writeQueue.length;
372
+ let messageDeleted = false;
373
+ const writeTimeout = timeout !== undefined ? timeout : BLE_TIMEOUT;
374
+ this.writeQueue.push({ uuid: characteristicUuid.toLocaleLowerCase(), data, timeout: Date.now() + writeTimeout, resolve, reject });
375
+ const to = setTimeout(() => {
376
+ if (this.writeQueue.length > writeId && !messageDeleted)
377
+ this.writeQueue.splice(writeId, 1);
378
+ this.logEvent({ message: 'writing response', err: 'timeout' });
379
+ reject(new Error('timeout'));
380
+ }, 5000);
381
+ this.logEvent({ message: 'writing' });
382
+ characteristic.write(data, withoutResponse, (err) => {
383
+ clearTimeout(to);
384
+ this.logEvent({ message: 'writing response', err });
385
+ if (err) {
386
+ this.writeQueue.splice(writeId, 1);
387
+ messageDeleted = true;
388
+ reject(err);
389
+ }
390
+ });
391
+ }
392
+ });
393
+ }
394
+ catch (err) {
395
+ this.logEvent({ message: 'error', fn: '', error: err.message || err, stack: err.stack });
396
+ }
397
+ });
398
+ }
399
+ read(characteristicUuid) {
400
+ return new Promise((resolve, reject) => {
401
+ if (!this.isConnected())
402
+ return reject(new Error('not connected'));
403
+ const characteristic = this.characteristics.find(c => c.uuid === characteristicUuid || (0, ble_1.uuid)(c.uuid) === characteristicUuid);
404
+ if (!characteristic) {
405
+ reject(new Error('Characteristic not found'));
406
+ return;
407
+ }
408
+ characteristic.read((err, data) => {
409
+ if (err && data instanceof Error)
410
+ reject(err);
411
+ else if (data instanceof Error)
412
+ reject(data);
413
+ else
414
+ resolve(data);
415
+ });
416
+ });
417
+ }
418
+ getDeviceInfo() {
419
+ return __awaiter(this, void 0, void 0, function* () {
420
+ const info = this.deviceInfo;
421
+ const readValue = (c) => __awaiter(this, void 0, void 0, function* () {
422
+ try {
423
+ const b = yield this.read(c);
424
+ const buffer = b ? Buffer.from(b) : undefined;
425
+ return buffer ? buffer.toString() : undefined;
426
+ }
427
+ catch (_a) {
428
+ return undefined;
429
+ }
430
+ });
431
+ info.model = info.model || (yield readValue('2a24'));
432
+ info.serialNo = info.serialNo || (yield readValue('2a25'));
433
+ info.fwRevision = info.fwRevision || (yield readValue('2a26'));
434
+ info.hwRevision = info.hwRevision || (yield readValue('2a27'));
435
+ info.swRevision = info.swRevision || (yield readValue('2a28'));
436
+ info.manufacturer = info.manufacturer || (yield readValue('2a29'));
437
+ this.deviceInfo = info;
438
+ return info;
439
+ });
440
+ }
441
+ }
442
+ exports.BleDevice = BleDevice;