incyclist-devices 3.0.43 → 3.0.44

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 (31) hide show
  1. package/lib/cjs/ble/base/adapter.js +23 -5
  2. package/lib/cjs/ble/csc/adapter.js +5 -5
  3. package/lib/cjs/ble/index.js +2 -0
  4. package/lib/cjs/ble/openbikecontrol/adapter.js +77 -0
  5. package/lib/cjs/ble/openbikecontrol/consts.js +6 -0
  6. package/lib/cjs/ble/openbikecontrol/index.js +18 -0
  7. package/lib/cjs/ble/openbikecontrol/sensor.js +108 -0
  8. package/lib/cjs/ble/zwift/play/adapter.js +3 -0
  9. package/lib/cjs/direct-connect/base/interface.js +153 -14
  10. package/lib/cjs/direct-connect/base/peripheral.js +176 -19
  11. package/lib/esm/ble/base/adapter.js +24 -6
  12. package/lib/esm/ble/csc/adapter.js +5 -5
  13. package/lib/esm/ble/index.js +2 -0
  14. package/lib/esm/ble/openbikecontrol/adapter.js +70 -0
  15. package/lib/esm/ble/openbikecontrol/consts.js +3 -0
  16. package/lib/esm/ble/openbikecontrol/index.js +2 -0
  17. package/lib/esm/ble/openbikecontrol/sensor.js +104 -0
  18. package/lib/esm/ble/zwift/play/adapter.js +3 -0
  19. package/lib/esm/direct-connect/base/interface.js +155 -16
  20. package/lib/esm/direct-connect/base/peripheral.js +174 -18
  21. package/lib/types/ble/base/adapter.d.ts +3 -0
  22. package/lib/types/ble/csc/adapter.d.ts +1 -1
  23. package/lib/types/ble/openbikecontrol/adapter.d.ts +23 -0
  24. package/lib/types/ble/openbikecontrol/consts.d.ts +3 -0
  25. package/lib/types/ble/openbikecontrol/index.d.ts +2 -0
  26. package/lib/types/ble/openbikecontrol/sensor.d.ts +25 -0
  27. package/lib/types/ble/types.d.ts +2 -1
  28. package/lib/types/ble/zwift/play/adapter.d.ts +1 -0
  29. package/lib/types/direct-connect/base/interface.d.ts +9 -0
  30. package/lib/types/direct-connect/base/peripheral.d.ts +17 -0
  31. package/package.json +2 -2
@@ -1,14 +1,19 @@
1
1
  import { EventEmitter } from "node:events";
2
2
  import { EventLogger } from "gd-eventlog";
3
3
  import { InteruptableTask } from "../../utils/task.js";
4
- import { DirectConnectPeripheral } from "./peripheral.js";
5
- import { beautifyUUID, BleAdapterFactory } from "../../ble/index.js";
4
+ import { DirectConnectPeripheral, OpenBikeControlPeripheral } from "./peripheral.js";
5
+ import { beautifyUUID, BleAdapterFactory, matches } from "../../ble/index.js";
6
6
  import { InterfaceFactory } from "../../ble/base/types.js";
7
7
  import { CSC, CSP } from "../../ble/consts.js";
8
8
  import { WAHOO_ADVANCED_FTMS } from "../../ble/wahoo/consts.js";
9
+ import { OBC_SERVICE } from "../../ble/openbikecontrol/consts.js";
9
10
  const DC_TYPE = 'wahoo-fitness-tnp';
10
11
  const DC_PORT = 36866;
11
12
  const DC_EXPIRATION_TIMEOUT = 10 * 1000 * 60;
13
+ const DC_PROBE_TIMEOUT = 2000;
14
+ const DC_REPROBE_INTERVAL = 5000;
15
+ const DC_WAIT_LIFETIME = 5 * 60 * 1000;
16
+ const OBC_TYPE = 'openbikecontrol';
12
17
  let instanceId = 0;
13
18
  export default class DirectConnectInterface extends EventEmitter {
14
19
  static _instance;
@@ -25,6 +30,7 @@ export default class DirectConnectInterface extends EventEmitter {
25
30
  matching = [];
26
31
  instance;
27
32
  connected = false;
33
+ pendingWaits = new Map();
28
34
  backgroundPaused = false;
29
35
  static getInstance(props = {}) {
30
36
  if (DirectConnectInterface._instance === undefined)
@@ -62,6 +68,8 @@ export default class DirectConnectInterface extends EventEmitter {
62
68
  this.props = props;
63
69
  }
64
70
  createPeripheral(announcement) {
71
+ if (announcement.type === OBC_TYPE)
72
+ return OpenBikeControlPeripheral.create(announcement);
65
73
  return DirectConnectPeripheral.create(announcement);
66
74
  }
67
75
  getSupportedServices() {
@@ -148,12 +156,20 @@ export default class DirectConnectInterface extends EventEmitter {
148
156
  this.getBinding().mdns.find({ type: DC_TYPE }, (service) => {
149
157
  this.addService(service, DC_TYPE);
150
158
  });
159
+ this.getBinding().mdns.find({ type: OBC_TYPE }, (service) => {
160
+ if (service.type && service.type !== OBC_TYPE)
161
+ return;
162
+ if (service.serviceUUIDs?.length && !service.serviceUUIDs.some(uuid => matches(uuid, OBC_SERVICE)))
163
+ return;
164
+ this.addService({ ...service, type: OBC_TYPE }, OBC_TYPE);
165
+ });
151
166
  }
152
167
  async pauseBackgroundActivity() {
153
168
  if (this.backgroundPaused)
154
169
  return;
155
170
  this.backgroundPaused = true;
156
171
  this.logEvent({ message: 'pausing background activity' });
172
+ this.cancelWaits();
157
173
  try {
158
174
  this.getBinding()?.mdns?.disconnect();
159
175
  }
@@ -235,22 +251,134 @@ export default class DirectConnectInterface extends EventEmitter {
235
251
  return this.logDisabled;
236
252
  }
237
253
  waitForPeripheral(settings) {
238
- const peripheral = this.createPeripheralFromSettings(settings);
239
- if (peripheral)
240
- return Promise.resolve(peripheral);
241
- return new Promise((done) => {
242
- const onDevice = (device) => {
243
- if (device.name === settings.name) {
254
+ const key = `${settings.name}|${settings.address ?? ''}`;
255
+ const pending = this.pendingWaits.get(key);
256
+ if (pending)
257
+ return pending.promise;
258
+ let cancel = () => { };
259
+ const promise = new Promise((resolve, reject) => {
260
+ cancel = this.runWait(key, settings, resolve, reject);
261
+ });
262
+ this.pendingWaits.set(key, { promise, cancel });
263
+ return promise;
264
+ }
265
+ cancelWait(settings) {
266
+ const key = `${settings.name}|${settings.address ?? ''}`;
267
+ this.pendingWaits.get(key)?.cancel();
268
+ }
269
+ runWait(key, settings, resolve, reject) {
270
+ const start = Date.now();
271
+ let probes = 0;
272
+ let lastResult;
273
+ let finished = false;
274
+ let timer;
275
+ const cleanup = () => {
276
+ finished = true;
277
+ if (timer)
278
+ clearTimeout(timer);
279
+ this.off('device', onDevice);
280
+ this.pendingWaits.delete(key);
281
+ };
282
+ const succeed = (peripheral, source) => {
283
+ if (finished)
284
+ return;
285
+ cleanup();
286
+ this.logEvent({ message: 'wifi device reachable', device: settings.name, address: settings.address ?? '', source, waitedMs: Date.now() - start, probes });
287
+ resolve(peripheral);
288
+ };
289
+ const fail = (reason) => {
290
+ if (finished)
291
+ return;
292
+ cleanup();
293
+ reject(new Error(`wifi device wait ${reason}`));
294
+ };
295
+ const onDevice = (device) => {
296
+ if (finished || device.name !== settings.name)
297
+ return;
298
+ const peripheral = this.createPeripheralFromSettings(settings);
299
+ if (peripheral)
300
+ succeed(peripheral, 'mdns');
301
+ };
302
+ const attempt = async (trigger) => {
303
+ if (finished)
304
+ return;
305
+ const entry = this.findEntry(settings);
306
+ if (entry) {
307
+ const { address, port } = entry.service;
308
+ const t0 = Date.now();
309
+ const result = await this.probePort(address, port);
310
+ if (finished)
311
+ return;
312
+ probes++;
313
+ if (result !== lastResult) {
314
+ lastResult = result;
315
+ this.logEvent({ message: 'wifi device probe', device: settings.name, address, port, result, durationMs: Date.now() - t0, trigger });
316
+ }
317
+ if (result === 'open' || result === 'skipped') {
318
+ entry.ts = Date.now();
244
319
  const peripheral = this.createPeripheralFromSettings(settings);
245
- if (peripheral) {
246
- this.off('device', onDevice);
247
- done(peripheral);
248
- }
320
+ if (peripheral)
321
+ return succeed(peripheral, 'probe');
322
+ }
323
+ }
324
+ if (Date.now() - start >= DC_WAIT_LIFETIME) {
325
+ this.logEvent({ message: 'wifi device wait abandoned', device: settings.name, address: settings.address ?? '', waitedMs: Date.now() - start, probes });
326
+ fail('abandoned');
327
+ return;
328
+ }
329
+ timer = setTimeout(() => { void attempt('reprobe'); }, DC_REPROBE_INTERVAL);
330
+ };
331
+ this.on('device', onDevice);
332
+ void attempt('start');
333
+ return () => fail('cancelled');
334
+ }
335
+ probePort(address, port, timeout = DC_PROBE_TIMEOUT) {
336
+ const net = this.getBinding()?.net;
337
+ if (!net?.createSocket || !address)
338
+ return Promise.resolve('skipped');
339
+ return new Promise(resolve => {
340
+ let socket;
341
+ let timer;
342
+ let settled = false;
343
+ const done = (result) => {
344
+ if (settled)
345
+ return;
346
+ settled = true;
347
+ if (timer)
348
+ clearTimeout(timer);
349
+ try {
350
+ socket?.removeAllListeners();
351
+ socket?.on('error', () => { });
352
+ socket?.destroy();
249
353
  }
354
+ catch { }
355
+ resolve(result);
250
356
  };
251
- this.on('device', onDevice);
357
+ try {
358
+ socket = net.createSocket();
359
+ socket.once('connect', () => done('open'));
360
+ socket.once('error', (err) => done(err?.code === 'ETIMEDOUT' ? 'timeout' : 'closed'));
361
+ socket.once('timeout', () => done('timeout'));
362
+ timer = setTimeout(() => done('timeout'), timeout);
363
+ socket.connect(port, address);
364
+ }
365
+ catch (err) {
366
+ this.logError(err, 'probePort');
367
+ done('error');
368
+ }
252
369
  });
253
370
  }
371
+ findEntry(settings) {
372
+ const bleSettings = settings;
373
+ const all = this.getAll();
374
+ return (bleSettings.address && all.find(a => a.service.name === settings.name && a.service.address === bleSettings.address))
375
+ || all.find(a => a.service.name === settings.name);
376
+ }
377
+ cancelWaits() {
378
+ const waits = Array.from(this.pendingWaits.values());
379
+ waits.forEach(w => w.cancel());
380
+ this.pendingWaits.clear();
381
+ }
254
382
  async reconnect() {
255
383
  await this.disconnect();
256
384
  await this.connect(true);
@@ -267,7 +395,7 @@ export default class DirectConnectInterface extends EventEmitter {
267
395
  emitCachedDevices() {
268
396
  const announced = this.getAll();
269
397
  this.matching = announced.map(a => a.service.name);
270
- announced.forEach(a => {
398
+ announced.filter(a => a.source !== 'known-device').forEach(a => {
271
399
  this.emitDevice(a.service);
272
400
  });
273
401
  }
@@ -284,6 +412,8 @@ export default class DirectConnectInterface extends EventEmitter {
284
412
  const src = source === 'known-device' ? 'known-device' : 'mdns';
285
413
  try {
286
414
  service.transport = this.getName();
415
+ if (service.type === OBC_TYPE && !service.serviceUUIDs?.length)
416
+ service.serviceUUIDs = [OBC_SERVICE];
287
417
  const sameAddress = this.findByNameAndAddress(service.name, service.address);
288
418
  if (sameAddress) {
289
419
  this.refreshSameAddressEntry(sameAddress, service, src, source);
@@ -312,16 +442,25 @@ export default class DirectConnectInterface extends EventEmitter {
312
442
  const idx = this.services.indexOf(sameAddress);
313
443
  const wasKnownDevicePlaceholder = sameAddress.source === 'known-device';
314
444
  const nextSource = (wasKnownDevicePlaceholder && src !== 'known-device') ? src : sameAddress.source;
315
- this.services[idx] = { ts: Date.now(), service, source: nextSource };
445
+ const hadServices = sameAddress.service.serviceUUIDs?.length > 0;
446
+ const hasServices = service.serviceUUIDs?.length > 0;
447
+ this.services[idx] = { ts: Date.now(), service: (hadServices && !hasServices) ? sameAddress.service : service, source: nextSource };
316
448
  if (src !== 'known-device' && wasKnownDevicePlaceholder) {
317
449
  this.logEvent({ message: 'device re-announced', device: service.name, announcement: service, source });
318
450
  this.emitDevice(service);
319
451
  }
452
+ else if (!hadServices && hasServices) {
453
+ this.logEvent({ message: 'device announced', device: service.name, announcement: service, source });
454
+ this.emitDevice(service);
455
+ this.matching?.push(service.name);
456
+ }
320
457
  }
321
458
  announceNewEntry(service, src, source, message) {
322
459
  this.services.push({ ts: Date.now(), service, source: src });
323
460
  if (!service.serviceUUIDs?.length)
324
461
  return;
462
+ if (src === 'known-device')
463
+ return;
325
464
  this.logEvent({ message, device: service.name, announcement: service, source });
326
465
  this.emitDevice(service);
327
466
  this.matching?.push(service.name);
@@ -383,7 +522,7 @@ export default class DirectConnectInterface extends EventEmitter {
383
522
  return details[0].class;
384
523
  }
385
524
  createAnnouncementFromSettings(settings) {
386
- if (settings.protocol && settings.address) {
525
+ if (settings.protocol && settings.address && settings.protocol !== 'openbikecontrol') {
387
526
  const announcement = {
388
527
  name: settings.name,
389
528
  address: settings.address,
@@ -4,7 +4,10 @@ import { CharacteristicNotificationMessage, DiscoverCharacteristicsMessage, Disc
4
4
  import { EventEmitter } from "node:events";
5
5
  import { DC_MESSAGE_CHARACTERISTIC_NOTIFICATION, DC_RC_REQUEST_COMPLETED_SUCCESSFULLY } from "../consts.js";
6
6
  import { beautifyUUID, parseUUID } from "../../ble/utils.js";
7
+ import { OBC_BUTTON_STATE, OBC_SERVICE } from "../../ble/openbikecontrol/consts.js";
7
8
  let IDS = 0;
9
+ const DC_CONNECT_TIMEOUT = 2000;
10
+ const DC_RESPONSE_TIMEOUT = 5000;
8
11
  export class DirectConnectPeripheral {
9
12
  announcement;
10
13
  static instances = {};
@@ -16,6 +19,7 @@ export class DirectConnectPeripheral {
16
19
  return this.instances[key];
17
20
  }
18
21
  socket;
22
+ socketConnected = false;
19
23
  connectTask;
20
24
  msgSeqNo = 0;
21
25
  onDataHandler = this.onData.bind(this);
@@ -52,22 +56,36 @@ export class DirectConnectPeripheral {
52
56
  async connect() {
53
57
  if (this.isConnected())
54
58
  return true;
55
- if (this.isConnecting())
56
- await this.connectTask.getPromise();
57
- const keys = Object.keys(DirectConnectPeripheral.instances);
58
- const instances = [];
59
- for (const key of keys)
60
- instances.push(DirectConnectPeripheral.instances[key]);
59
+ if (this.isConnecting()) {
60
+ try {
61
+ await this.connectTask.getPromise();
62
+ }
63
+ catch { }
64
+ if (this.isConnected())
65
+ return true;
66
+ }
61
67
  this.connectTask = new InteruptableTask(this.startConnection(), {
62
- timeout: 1000,
68
+ timeout: DC_CONNECT_TIMEOUT,
63
69
  });
64
- return await this.connectTask.run();
70
+ let connected = false;
71
+ try {
72
+ connected = await this.connectTask.run();
73
+ }
74
+ catch {
75
+ connected = false;
76
+ }
77
+ if (!connected || !this.isConnected()) {
78
+ this.discardSocket();
79
+ return false;
80
+ }
81
+ return true;
65
82
  }
66
83
  async disconnect(connectionLost = false) {
67
84
  try {
68
- await this.connectTask.stop();
85
+ await this.connectTask?.stop();
69
86
  await this.stopConnection(connectionLost);
70
87
  delete this.socket;
88
+ this.socketConnected = false;
71
89
  }
72
90
  catch (err) {
73
91
  return false;
@@ -75,7 +93,20 @@ export class DirectConnectPeripheral {
75
93
  return true;
76
94
  }
77
95
  isConnected() {
78
- return this.socket !== undefined;
96
+ return this.socket !== undefined && this.socketConnected;
97
+ }
98
+ discardSocket() {
99
+ const socket = this.socket;
100
+ delete this.socket;
101
+ this.socketConnected = false;
102
+ if (!socket)
103
+ return;
104
+ try {
105
+ socket.removeAllListeners();
106
+ socket.on('error', () => { });
107
+ socket.destroy();
108
+ }
109
+ catch { }
79
110
  }
80
111
  isConnecting() {
81
112
  return this.connectTask?.isRunning();
@@ -362,6 +393,7 @@ export class DirectConnectPeripheral {
362
393
  this.stopConnection().then(() => resolve(false));
363
394
  });
364
395
  this.socket.once('connect', () => {
396
+ this.socketConnected = true;
365
397
  this.socket.on('data', this.onDataHandler);
366
398
  this.socket.on('error', this.onPortErrorHandler);
367
399
  this.socket.on('close', this.onPortCloseHandler);
@@ -400,9 +432,7 @@ export class DirectConnectPeripheral {
400
432
  async stopConnection(connectionLost = false) {
401
433
  this.eventEmitter.removeAllListeners();
402
434
  if (!this.isConnected()) {
403
- this.socket.removeAllListeners();
404
- this.socket.destroy();
405
- delete this.socket;
435
+ this.discardSocket();
406
436
  return true;
407
437
  }
408
438
  await this.unsubscribeAll(connectionLost);
@@ -430,12 +460,28 @@ export class DirectConnectPeripheral {
430
460
  return this.msgSeqNo;
431
461
  }
432
462
  async send(seqNo, data) {
433
- await this.connect();
434
- this.socket.write(data);
435
- return new Promise(done => {
436
- this.eventEmitter.once(`response-${seqNo}`, (response) => {
463
+ const connected = await this.connect();
464
+ if (!connected || !this.isConnected())
465
+ throw new Error('not connected');
466
+ const event = `response-${seqNo}`;
467
+ return new Promise((done, reject) => {
468
+ const timer = setTimeout(() => {
469
+ this.eventEmitter.off(event, onResponse);
470
+ reject(new Error('response timeout'));
471
+ }, DC_RESPONSE_TIMEOUT);
472
+ const onResponse = (response) => {
473
+ clearTimeout(timer);
437
474
  done(response);
438
- });
475
+ };
476
+ this.eventEmitter.once(event, onResponse);
477
+ try {
478
+ this.socket.write(data);
479
+ }
480
+ catch (err) {
481
+ clearTimeout(timer);
482
+ this.eventEmitter.off(event, onResponse);
483
+ reject(err);
484
+ }
439
485
  });
440
486
  }
441
487
  getNextMessage(data) {
@@ -503,3 +549,113 @@ export class DirectConnectPeripheral {
503
549
  return this.getInterface().getBinding();
504
550
  }
505
551
  }
552
+ const OBC_MSG_BUTTON_STATE = 0x01;
553
+ const OBC_MSG_DEVICE_STATUS = 0x02;
554
+ const OBC_DEVICE_STATUS_LENGTH = 3;
555
+ export class OpenBikeControlPeripheral extends DirectConnectPeripheral {
556
+ static instances = {};
557
+ static create(announcement) {
558
+ const { address, port } = announcement;
559
+ const key = `${address}:${port}`;
560
+ if (!this.instances[key])
561
+ this.instances[key] = new OpenBikeControlPeripheral(announcement);
562
+ return this.instances[key];
563
+ }
564
+ async discoverServices() {
565
+ this.discoveredServiceUUIds = [beautifyUUID(OBC_SERVICE)];
566
+ return [OBC_SERVICE];
567
+ }
568
+ async discoverCharacteristics(_serviceUUID) {
569
+ return [{ uuid: OBC_BUTTON_STATE, properties: ['read', 'notify'] }];
570
+ }
571
+ async subscribe(characteristicUUID, callback) {
572
+ const uuid = parseUUID(characteristicUUID);
573
+ if (this.subscribed.includes(uuid))
574
+ return true;
575
+ this.subscribed.push(uuid);
576
+ if (callback) {
577
+ this.eventEmitter.on(uuid, (data) => {
578
+ callback(characteristicUUID, data);
579
+ });
580
+ }
581
+ return true;
582
+ }
583
+ async unsubscribe(characteristicUUID) {
584
+ const uuid = parseUUID(characteristicUUID);
585
+ if (this.subscribed.includes(uuid))
586
+ this.subscribed.splice(this.subscribed.indexOf(uuid), 1);
587
+ this.eventEmitter.removeAllListeners(uuid);
588
+ return true;
589
+ }
590
+ async read(_characteristicUUID) {
591
+ return Buffer.from([]);
592
+ }
593
+ async write(characteristicUUID, data, _options) {
594
+ await this.connect();
595
+ this.logEvent({ message: 'write', path: this.getPath(), characteristic: beautifyUUID(characteristicUUID), raw: data.toString('hex') });
596
+ this.socket.write(data);
597
+ return Buffer.from([]);
598
+ }
599
+ pending;
600
+ async disconnect(connectionLost) {
601
+ delete this.pending;
602
+ return super.disconnect(connectionLost);
603
+ }
604
+ async onData(data) {
605
+ const buffer = this.pending ? Buffer.concat([this.pending, data]) : data;
606
+ delete this.pending;
607
+ try {
608
+ let offset = 0;
609
+ while (offset < buffer.length) {
610
+ const msgType = buffer[offset];
611
+ if (msgType === OBC_MSG_DEVICE_STATUS) {
612
+ if (offset + OBC_DEVICE_STATUS_LENGTH > buffer.length) {
613
+ this.pending = Buffer.from(buffer.subarray(offset));
614
+ return;
615
+ }
616
+ const status = buffer.subarray(offset, offset + OBC_DEVICE_STATUS_LENGTH);
617
+ this.logEvent({ message: 'device status', path: this.getPath(), battery: status[1], connected: status[2] === 1, raw: status.toString('hex') });
618
+ offset += OBC_DEVICE_STATUS_LENGTH;
619
+ }
620
+ else if (msgType === OBC_MSG_BUTTON_STATE) {
621
+ const end = this.getButtonStateEnd(buffer, offset);
622
+ if (end < 0) {
623
+ this.pending = Buffer.from(buffer.subarray(offset));
624
+ return;
625
+ }
626
+ const message = Buffer.from(buffer.subarray(offset, end));
627
+ this.logEvent({ message: 'button state', path: this.getPath(), raw: message.toString('hex') });
628
+ this.eventEmitter.emit(parseUUID(OBC_BUTTON_STATE), message);
629
+ offset = end;
630
+ }
631
+ else {
632
+ this.logEvent({ message: 'unknown message', path: this.getPath(), raw: buffer.subarray(offset).toString('hex') });
633
+ return;
634
+ }
635
+ }
636
+ }
637
+ catch (err) {
638
+ this.logEvent({ message: 'error', fn: 'onData', error: err.message, stack: err.stack, path: this.getPath(), raw: buffer?.toString('hex') });
639
+ }
640
+ }
641
+ getButtonStateEnd(buffer, offset) {
642
+ const buttons = new Set();
643
+ let pos = offset + 1;
644
+ while (pos < buffer.length) {
645
+ const id = buffer[pos];
646
+ if (buttons.has(id))
647
+ return pos;
648
+ if (pos + 1 >= buffer.length)
649
+ return buttons.size > 0 && this.isMessageType(id) ? pos : -1;
650
+ const next = buffer[pos + 1];
651
+ if (buttons.size > 0 && this.isMessageType(id) && next > 0x01)
652
+ return pos;
653
+ buttons.add(id);
654
+ pos += 2;
655
+ }
656
+ return buttons.size > 0 ? pos : -1;
657
+ }
658
+ isMessageType(byte) {
659
+ return byte === OBC_MSG_BUTTON_STATE || byte === OBC_MSG_DEVICE_STATUS;
660
+ }
661
+ }
@@ -7,6 +7,8 @@ import ICyclingMode from "../../modes/types.js";
7
7
  import { InteruptableTask, TaskState } from "../../utils/task.js";
8
8
  import { TBleSensor } from "./sensor.js";
9
9
  export default class BleAdapter<TDeviceData extends BleDeviceData, TDevice extends TBleSensor> extends IncyclistDevice<BleDeviceProperties> {
10
+ protected static readonly STOP_WAIT_BOUND_MS = 10000;
11
+ protected getStopWaitBound(): number;
10
12
  protected deviceData: TDeviceData;
11
13
  protected dataMsgCount: number;
12
14
  protected lastDataTS: number;
@@ -49,6 +51,7 @@ export default class BleAdapter<TDeviceData extends BleDeviceData, TDevice exten
49
51
  protected runStartTask(ble: IBleInterface<any>): Promise<boolean>;
50
52
  protected isStarting(): boolean;
51
53
  protected hasData(): boolean;
54
+ protected shouldWaitForData(): boolean;
52
55
  protected waitForInitialData(startupTimeout: any): Promise<void>;
53
56
  protected checkCapabilities(): Promise<void>;
54
57
  protected initControl(_props?: BleStartProperties): Promise<void>;
@@ -15,7 +15,7 @@ export declare class BleCSCAdapter extends BleAdapter<CSCData, BleCyclingSpeedCa
15
15
  updateSensor(peripheral: IBlePeripheral): void;
16
16
  getProfile(): LegacyProfile;
17
17
  getDisplayName(): string;
18
- mapData(deviceData: CSCData): IncyclistAdapterData;
18
+ mapData(deviceData: CSCData): IncyclistAdapterData & Partial<IncyclistBikeData>;
19
19
  transformData(bikeData: IncyclistBikeData): IncyclistAdapterData;
20
20
  setCyclingMode(mode: string | ICyclingMode, settings?: any, sendInitCommands?: boolean): void;
21
21
  }
@@ -0,0 +1,23 @@
1
+ import { BleDeviceData } from '../base/types.js';
2
+ import { LegacyProfile } from '../../antv2/types.js';
3
+ import BleAdapter from '../base/adapter.js';
4
+ import { BleOpenBikeControlSensor } from './sensor.js';
5
+ import { DeviceProperties, IAdapter, IncyclistAdapterData, IncyclistCapability } from '../../types/index.js';
6
+ import { BleDeviceSettings, IBlePeripheral } from '../types.js';
7
+ export declare class OpenBikeControlAdapter extends BleAdapter<BleDeviceData, BleOpenBikeControlSensor> {
8
+ protected static INCYCLIST_PROFILE_NAME: LegacyProfile;
9
+ protected static CAPABILITIES: IncyclistCapability[];
10
+ protected keyPressedHandler?: (event: any) => void;
11
+ constructor(settings: BleDeviceSettings, props?: DeviceProperties);
12
+ protected checkCapabilities(): Promise<void>;
13
+ startSensor(): Promise<boolean>;
14
+ protected onKeyPressed(event: any): void;
15
+ isEqual(settings: BleDeviceSettings): boolean;
16
+ isSame(adapter: IAdapter): boolean;
17
+ updateSensor(peripheral: IBlePeripheral): void;
18
+ getProfile(): LegacyProfile;
19
+ getName(): string;
20
+ getDisplayName(): string;
21
+ mapData(deviceData: BleDeviceData): IncyclistAdapterData;
22
+ protected shouldWaitForData(): boolean;
23
+ }
@@ -0,0 +1,3 @@
1
+ export declare const OBC_SERVICE = "d273f680-d548-419d-b9d1-fa0472345229";
2
+ export declare const OBC_BUTTON_STATE = "d273f681-d548-419d-b9d1-fa0472345229";
3
+ export declare const OBC_APP_INFO = "d273f683-d548-419d-b9d1-fa0472345229";
@@ -0,0 +1,2 @@
1
+ export * from './sensor.js';
2
+ export * from './adapter.js';
@@ -0,0 +1,25 @@
1
+ import { LegacyProfile } from "../../antv2/types.js";
2
+ import { TBleSensor } from "../base/sensor.js";
3
+ import { BleProtocol } from "../types.js";
4
+ type ButtonPress = {
5
+ buttons: number[];
6
+ pressed: number[];
7
+ timestamp: number;
8
+ };
9
+ export declare class BleOpenBikeControlSensor extends TBleSensor {
10
+ static readonly profile: LegacyProfile;
11
+ static readonly protocol: BleProtocol;
12
+ static readonly services: string[];
13
+ static readonly characteristics: any[];
14
+ static readonly detectionPriority = 0;
15
+ protected buttonStates: Map<number, ButtonPress>;
16
+ protected onDisconnect(): void;
17
+ subscribe(): Promise<boolean>;
18
+ protected getRequiredCharacteristics(): Array<string>;
19
+ onData(characteristic: string, data: Buffer): boolean;
20
+ protected onButtonState(data: Buffer): void;
21
+ protected getKey(buttons: number[]): string;
22
+ protected sendAppInfo(): Promise<void>;
23
+ reset(): void;
24
+ }
25
+ export {};
@@ -1,7 +1,7 @@
1
1
  import { EventEmitter } from "events";
2
2
  import { EventLogger } from "gd-eventlog";
3
3
  import { DeviceProperties, DeviceSettings, DeviceStartProperties, IncyclistInterface, IncyclistScanProps, InterfaceProps } from "../types/index.js";
4
- export type BleProtocol = 'hr' | 'fm' | 'cp' | 'tacx' | 'wahoo' | 'bkool' | 'elite' | 'csc' | 'zwift-play';
4
+ export type BleProtocol = 'hr' | 'fm' | 'cp' | 'tacx' | 'wahoo' | 'bkool' | 'elite' | 'csc' | 'zwift-play' | 'openbikecontrol';
5
5
  export type BleInterfaceState = 'unknown' | 'resetting' | 'unsupported' | 'unauthorized' | 'poweredOff' | 'poweredOn';
6
6
  export interface BleBinding extends EventEmitter {
7
7
  startScanning(serviceUUIDs?: string[], allowDuplicates?: boolean, callback?: (error?: Error) => void): void;
@@ -148,6 +148,7 @@ export interface IBleInterface<T extends PeripheralAnnouncement> extends Incycli
148
148
  createPeripheralFromSettings(settings: DeviceSettings): IBlePeripheral;
149
149
  createDeviceSetting(announcement: T): DeviceSettings;
150
150
  waitForPeripheral(settings: DeviceSettings): Promise<IBlePeripheral>;
151
+ cancelWait?(settings: DeviceSettings): void;
151
152
  pauseDiscovery?(): Promise<void>;
152
153
  resumeDiscovery?(): Promise<void>;
153
154
  getSupportedServices(): string[];
@@ -20,4 +20,5 @@ export declare class ZwiftPlayAdapter extends BleAdapter<BleDeviceData, BleZwift
20
20
  getName(): string;
21
21
  getDisplayName(): string;
22
22
  mapData(deviceData: BleDeviceData): IncyclistAdapterData;
23
+ protected shouldWaitForData(): boolean;
23
24
  }
@@ -28,6 +28,10 @@ export default class DirectConnectInterface extends EventEmitter implements IBle
28
28
  protected matching?: Array<string>;
29
29
  protected instance: number;
30
30
  protected connected: boolean;
31
+ protected pendingWaits: Map<string, {
32
+ promise: Promise<IBlePeripheral>;
33
+ cancel: () => void;
34
+ }>;
31
35
  protected backgroundPaused: boolean;
32
36
  static getInstance(props?: InterfaceProps): DirectConnectInterface;
33
37
  constructor(props: InterfaceProps);
@@ -57,6 +61,11 @@ export default class DirectConnectInterface extends EventEmitter implements IBle
57
61
  resumeLogging(): void;
58
62
  isLoggingPaused(): boolean;
59
63
  waitForPeripheral(settings: DeviceSettings): Promise<IBlePeripheral>;
64
+ cancelWait(settings: DeviceSettings): void;
65
+ protected runWait(key: string, settings: DeviceSettings, resolve: (p: IBlePeripheral) => void, reject: (err: Error) => void): () => void;
66
+ protected probePort(address: string, port: number, timeout?: number): Promise<'open' | 'closed' | 'timeout' | 'error' | 'skipped'>;
67
+ protected findEntry(settings: DeviceSettings): Announcement | undefined;
68
+ protected cancelWaits(): void;
60
69
  protected reconnect(): Promise<void>;
61
70
  protected isScanning(): boolean;
62
71
  protected startScan(): Promise<void>;