incyclist-devices 1.4.100 → 1.5.0

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