incyclist-devices 3.0.42 → 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 (43) hide show
  1. package/lib/cjs/base/adpater.js +3 -0
  2. package/lib/cjs/ble/base/adapter.js +26 -5
  3. package/lib/cjs/ble/base/sensor.js +56 -24
  4. package/lib/cjs/ble/csc/adapter.js +5 -5
  5. package/lib/cjs/ble/fm/adapter.js +4 -0
  6. package/lib/cjs/ble/index.js +2 -0
  7. package/lib/cjs/ble/openbikecontrol/adapter.js +77 -0
  8. package/lib/cjs/ble/openbikecontrol/consts.js +6 -0
  9. package/lib/cjs/ble/openbikecontrol/index.js +18 -0
  10. package/lib/cjs/ble/openbikecontrol/sensor.js +108 -0
  11. package/lib/cjs/ble/zwift/play/adapter.js +3 -0
  12. package/lib/cjs/ble/zwift/play/sensor.js +67 -7
  13. package/lib/cjs/direct-connect/base/interface.js +153 -14
  14. package/lib/cjs/direct-connect/base/peripheral.js +176 -19
  15. package/lib/esm/base/adpater.js +3 -0
  16. package/lib/esm/ble/base/adapter.js +27 -6
  17. package/lib/esm/ble/base/sensor.js +57 -25
  18. package/lib/esm/ble/csc/adapter.js +5 -5
  19. package/lib/esm/ble/fm/adapter.js +4 -0
  20. package/lib/esm/ble/index.js +2 -0
  21. package/lib/esm/ble/openbikecontrol/adapter.js +70 -0
  22. package/lib/esm/ble/openbikecontrol/consts.js +3 -0
  23. package/lib/esm/ble/openbikecontrol/index.js +2 -0
  24. package/lib/esm/ble/openbikecontrol/sensor.js +104 -0
  25. package/lib/esm/ble/zwift/play/adapter.js +3 -0
  26. package/lib/esm/ble/zwift/play/sensor.js +64 -4
  27. package/lib/esm/direct-connect/base/interface.js +155 -16
  28. package/lib/esm/direct-connect/base/peripheral.js +174 -18
  29. package/lib/types/base/adpater.d.ts +1 -0
  30. package/lib/types/ble/base/adapter.d.ts +4 -0
  31. package/lib/types/ble/base/sensor.d.ts +9 -0
  32. package/lib/types/ble/csc/adapter.d.ts +1 -1
  33. package/lib/types/ble/openbikecontrol/adapter.d.ts +23 -0
  34. package/lib/types/ble/openbikecontrol/consts.d.ts +3 -0
  35. package/lib/types/ble/openbikecontrol/index.d.ts +2 -0
  36. package/lib/types/ble/openbikecontrol/sensor.d.ts +25 -0
  37. package/lib/types/ble/types.d.ts +2 -1
  38. package/lib/types/ble/zwift/play/adapter.d.ts +1 -0
  39. package/lib/types/ble/zwift/play/sensor.d.ts +10 -0
  40. package/lib/types/direct-connect/base/interface.d.ts +9 -0
  41. package/lib/types/direct-connect/base/peripheral.d.ts +17 -0
  42. package/lib/types/types/adapter.d.ts +1 -0
  43. package/package.json +2 -2
@@ -83,6 +83,9 @@ class IncyclistDevice extends node_events_1.EventEmitter {
83
83
  getInterface() {
84
84
  return typeof this.settings.interface === 'string' ? this.settings.interface : this.settings.interface.getName();
85
85
  }
86
+ isReconnecting() {
87
+ return false;
88
+ }
86
89
  async restart(pause) {
87
90
  this.logger.logEvent({ message: 'restarting device', device: this.getName() });
88
91
  const stopped = await this.stop();
@@ -9,6 +9,10 @@ const interface_factory_js_1 = require("../factories/interface-factory.js");
9
9
  const task_js_1 = require("../../utils/task.js");
10
10
  const utils_js_1 = require("../../utils/utils.js");
11
11
  class BleAdapter extends adpater_js_1.default {
12
+ static STOP_WAIT_BOUND_MS = 10000;
13
+ getStopWaitBound() {
14
+ return BleAdapter.STOP_WAIT_BOUND_MS;
15
+ }
12
16
  deviceData;
13
17
  dataMsgCount;
14
18
  lastDataTS;
@@ -94,6 +98,9 @@ class BleAdapter extends adpater_js_1.default {
94
98
  isConnected() {
95
99
  return this.device?.isConnected();
96
100
  }
101
+ isReconnecting() {
102
+ return this.getSensor()?.isReconnectBusy() ?? false;
103
+ }
97
104
  resetData() {
98
105
  super.resetData();
99
106
  this.dataMsgCount = 0;
@@ -213,7 +220,8 @@ class BleAdapter extends adpater_js_1.default {
213
220
  timeout: startProps?.timeout ?? this.getDefaultStartupTimeout(),
214
221
  name: 'start',
215
222
  errorOnTimeout: false,
216
- log: this.logEvent.bind(this)
223
+ log: this.logEvent.bind(this),
224
+ onCancel: () => { ble.cancelWait?.(this.settings); }
217
225
  });
218
226
  this.startPromise = this.runStartTask(ble);
219
227
  return this.startPromise;
@@ -236,6 +244,9 @@ class BleAdapter extends adpater_js_1.default {
236
244
  hasData() {
237
245
  return this.dataMsgCount > 0;
238
246
  }
247
+ shouldWaitForData() {
248
+ return true;
249
+ }
239
250
  async waitForInitialData(startupTimeout) {
240
251
  let waitTask;
241
252
  let iv;
@@ -314,7 +325,9 @@ class BleAdapter extends adpater_js_1.default {
314
325
  else {
315
326
  await this.initControlBestEffort(startProps);
316
327
  }
317
- await this.waitForInitialData(timeout);
328
+ if (this.shouldWaitForData()) {
329
+ await this.waitForInitialData(timeout);
330
+ }
318
331
  this.stopped = false;
319
332
  this.started = true;
320
333
  if (wasPaused)
@@ -329,7 +342,7 @@ class BleAdapter extends adpater_js_1.default {
329
342
  return true;
330
343
  }
331
344
  catch (err) {
332
- this.logEvent({ message: 'start result: error', error: err.message, stack: err.stack, device: this.getName(), interface: this.getInterface(), protocol: this.getProtocolName() });
345
+ this.logEvent({ message: 'start result: error', error: err.message, device: this.getName(), interface: this.getInterface(), protocol: this.getProtocolName() });
333
346
  this.started = false;
334
347
  this.stopped = true;
335
348
  const ble = this.getBle();
@@ -346,7 +359,7 @@ class BleAdapter extends adpater_js_1.default {
346
359
  }
347
360
  const sensor = this.getSensor();
348
361
  let connected = await sensor.startSensor();
349
- const subscribed = await sensor.subscribe();
362
+ const subscribed = connected ? await sensor.subscribe() : false;
350
363
  if (connected && !subscribed) {
351
364
  connected = false;
352
365
  }
@@ -413,7 +426,15 @@ class BleAdapter extends adpater_js_1.default {
413
426
  if (this.isStarting()) {
414
427
  const task = this.startTask;
415
428
  await task.stop();
416
- await task.getUnderlyingPromise()?.catch(() => { });
429
+ const underlying = task.getUnderlyingPromise();
430
+ if (underlying !== undefined) {
431
+ const settled = await Promise.race([
432
+ underlying.then(() => true).catch(() => true),
433
+ (0, utils_js_1.sleep)(this.getStopWaitBound()).then(() => false),
434
+ ]);
435
+ if (!settled)
436
+ this.logEvent({ message: 'stop(): the previous start is still running past its bound, proceeding anyway', device: this.getName(), interface: this.getInterface() });
437
+ }
417
438
  }
418
439
  this.started = false;
419
440
  this.resetData();
@@ -8,11 +8,14 @@ const utils_js_2 = require("../utils.js");
8
8
  class TBleSensor extends node_events_1.EventEmitter {
9
9
  peripheral;
10
10
  static protocol;
11
+ static RECONNECT_ATTEMPT_TIMEOUT = 20000;
11
12
  logger;
12
13
  stopRequested = false;
13
14
  subscribeSuccess = false;
14
15
  reconnectPromise;
15
16
  connectPromise;
17
+ reconnectAttemptTimeout = TBleSensor.RECONNECT_ATTEMPT_TIMEOUT;
18
+ reconnectCount = 0;
16
19
  onDataHandler;
17
20
  logEvent(event, ...args) {
18
21
  try {
@@ -93,16 +96,22 @@ class TBleSensor extends node_events_1.EventEmitter {
93
96
  const selected = this.getRequiredCharacteristics();
94
97
  if (selected === null) {
95
98
  const res = this.peripheral?.subscribeAll ? await this.peripheral.subscribeAll(this.onDataHandler) : false;
96
- this.subscribeSuccess = res;
97
- return res;
99
+ return this.onSubscribeResult(res);
98
100
  }
99
101
  if (selected.length === 0) {
100
102
  this.subscribeSuccess = true;
101
103
  return true;
102
104
  }
103
105
  const res = await this.peripheral.subscribeSelected(selected, this.onDataHandler);
104
- this.subscribeSuccess = res;
105
- return res;
106
+ return this.onSubscribeResult(res);
107
+ }
108
+ onSubscribeResult(res) {
109
+ const success = res && this.isConnected();
110
+ if (res && !success) {
111
+ this.logEvent({ message: 'subscribe failed', reason: 'not connected' });
112
+ }
113
+ this.subscribeSuccess = success;
114
+ return success;
106
115
  }
107
116
  async stopSensor() {
108
117
  this.stopRequested = true;
@@ -124,41 +133,64 @@ class TBleSensor extends node_events_1.EventEmitter {
124
133
  delete this.reconnectPromise;
125
134
  return res;
126
135
  }
136
+ getReconnectCount() {
137
+ return this.reconnectCount;
138
+ }
127
139
  async doReconnectSensor(connectionLost = true) {
128
140
  this.onDisconnect();
141
+ this.reconnectCount++;
129
142
  const { name, address } = this.peripheral?.getInfo() ?? {};
130
143
  this.logEvent({ message: 'reconnect sensor', name, address, connectionLost });
131
- let connected = false;
132
- let subscribed = false;
133
144
  let success = false;
134
145
  if (connectionLost) {
135
146
  this.emit('connctionLost');
136
147
  }
137
148
  await (0, utils_js_1.sleep)(500);
138
- do {
139
- try {
140
- if (!connected) {
141
- connected = await this.startSensor(true);
142
- }
143
- if (connected && !subscribed) {
144
- subscribed = await this.subscribe();
145
- }
146
- }
147
- catch {
148
- }
149
- success = connected && subscribed;
150
- if (!success) {
151
- await (0, utils_js_1.sleep)(1000);
152
- }
153
- if (!this.stopRequested && !success)
154
- this.logEvent({ message: 'reconnect sensor retry', name, address });
155
- } while (!success || this.stopRequested);
149
+ success = await this.reconnectUntilDone(name, address);
156
150
  if (connectionLost && success) {
157
151
  this.emit('connctionRecovered');
158
152
  }
159
153
  this.logEvent({ message: 'reconnect sensor completed', success, stopRequested: this.stopRequested });
160
154
  return success;
161
155
  }
156
+ async reconnectUntilDone(name, address) {
157
+ const success = await this.reconnectAttempt(name, address);
158
+ if (success || this.stopRequested)
159
+ return success;
160
+ await (0, utils_js_1.sleep)(1000);
161
+ if (this.stopRequested)
162
+ return false;
163
+ this.logEvent({ message: 'reconnect sensor retry', name, address });
164
+ return this.reconnectUntilDone(name, address);
165
+ }
166
+ async reconnectAttempt(name, address) {
167
+ try {
168
+ return await (0, utils_js_1.runWithTimeout)(this.connectAndSubscribe(), this.reconnectAttemptTimeout);
169
+ }
170
+ catch (err) {
171
+ if (err?.message === 'Timeout') {
172
+ await this.abortReconnectAttempt(name, address);
173
+ }
174
+ return false;
175
+ }
176
+ }
177
+ async connectAndSubscribe() {
178
+ const connected = await this.startSensor(true);
179
+ if (!connected)
180
+ return false;
181
+ const subscribed = await this.subscribe();
182
+ return subscribed && this.isConnected();
183
+ }
184
+ async abortReconnectAttempt(name, address) {
185
+ this.logEvent({ message: 'reconnect sensor attempt timeout', name, address, timeout: this.reconnectAttemptTimeout });
186
+ delete this.connectPromise;
187
+ this.onDisconnect();
188
+ try {
189
+ await (0, utils_js_1.runWithTimeout)(this.peripheral.disconnect(), this.reconnectAttemptTimeout);
190
+ }
191
+ catch {
192
+ }
193
+ }
162
194
  reset() {
163
195
  throw new Error("Method not implemented.");
164
196
  }
@@ -28,10 +28,10 @@ class BleCSCAdapter extends adapter_js_1.default {
28
28
  if (!sensor)
29
29
  return;
30
30
  const features = await sensor.getFeatures();
31
- if (!features?.wheelRevolutionData)
32
- this.capabilities = this.capabilities.filter(c => c !== index_js_1.IncyclistCapability.Speed);
33
- if (!features?.crankRevolutionData)
34
- this.capabilities = this.capabilities.filter(c => c !== index_js_1.IncyclistCapability.Cadence);
31
+ if (!features || (features.wheelRevolutionData === undefined && features.crankRevolutionData === undefined))
32
+ return;
33
+ this.capabilities = BleCSCAdapter.CAPABILITIES.filter(c => (c !== index_js_1.IncyclistCapability.Speed || features.wheelRevolutionData) &&
34
+ (c !== index_js_1.IncyclistCapability.Cadence || features.crankRevolutionData));
35
35
  const after = this.capabilities.join(',');
36
36
  if (before !== after) {
37
37
  this.logEvent({ message: 'device capabilities updated', name: this.getSettings().name, interface: this.getSettings().interface, capabilities: this.capabilities });
@@ -54,7 +54,7 @@ class BleCSCAdapter extends adapter_js_1.default {
54
54
  }
55
55
  mapData(deviceData) {
56
56
  const { cadence, speed = 0 } = deviceData;
57
- return { cadence, speed };
57
+ return { cadence, pedalRpm: cadence, speed };
58
58
  }
59
59
  transformData(bikeData) {
60
60
  if (bikeData === undefined)
@@ -342,6 +342,10 @@ class BleFmAdapter extends adapter_js_1.default {
342
342
  return;
343
343
  try {
344
344
  const update = this.getCyclingMode().buildUpdate(request);
345
+ if (this.isReconnecting()) {
346
+ this.logEvent({ message: 'send bike update skipped', reason: 'reconnect in progress', update, request });
347
+ return;
348
+ }
345
349
  this.logEvent({ message: 'send bike update requested', profile: this.getProfile(), mode: this.getCyclingMode()?.getName(), update, request });
346
350
  const device = this.getSensor();
347
351
  if (this.hasCapability(index_js_1.IncyclistCapability.Control)) {
@@ -34,6 +34,7 @@ Object.defineProperty(exports, "BleInterfaceFactory", { enumerable: true, get: f
34
34
  Object.defineProperty(exports, "BleAdapterFactory", { enumerable: true, get: function () { return index_js_7.BleAdapterFactory; } });
35
35
  const index_js_8 = require("./csc/index.js");
36
36
  const index_js_9 = require("./zwift/play/index.js");
37
+ const index_js_10 = require("./openbikecontrol/index.js");
37
38
  ['ble', 'wifi'].forEach(i => {
38
39
  const af = index_js_7.BleAdapterFactory.getInstance(i);
39
40
  af.register('hr', index_js_1.BleHrmAdapter, index_js_1.BleHrmComms);
@@ -44,6 +45,7 @@ const index_js_9 = require("./zwift/play/index.js");
44
45
  af.register('bkool', index_js_6.BleBkoolAdapter, index_js_6.BleBkoolComms);
45
46
  af.register('csc', index_js_8.BleCSCAdapter, index_js_8.BleCyclingSpeedCadenceDevice);
46
47
  af.register('zwift-play', index_js_9.ZwiftPlayAdapter, index_js_9.BleZwiftPlaySensor);
48
+ af.register('openbikecontrol', index_js_10.OpenBikeControlAdapter, index_js_10.BleOpenBikeControlSensor);
47
49
  });
48
50
  index_js_7.BleMultiTransportInterfaceFactory.register('ble', interface_js_1.BleInterfaceFactory);
49
51
  __exportStar(require("./utils.js"), exports);
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.OpenBikeControlAdapter = void 0;
7
+ const gd_eventlog_1 = require("gd-eventlog");
8
+ const adapter_js_1 = __importDefault(require("../base/adapter.js"));
9
+ const sensor_js_1 = require("./sensor.js");
10
+ const index_js_1 = require("../../types/index.js");
11
+ class OpenBikeControlAdapter extends adapter_js_1.default {
12
+ static INCYCLIST_PROFILE_NAME = 'Controller';
13
+ static CAPABILITIES = [index_js_1.IncyclistCapability.AppControl];
14
+ keyPressedHandler;
15
+ constructor(settings, props) {
16
+ super(settings, props);
17
+ this.logger = new gd_eventlog_1.EventLogger('OpenBikeControl');
18
+ this.device = new sensor_js_1.BleOpenBikeControlSensor(this.getPeripheral(), { logger: this.logger });
19
+ this.capabilities = OpenBikeControlAdapter.CAPABILITIES;
20
+ }
21
+ async checkCapabilities() {
22
+ return;
23
+ }
24
+ async startSensor() {
25
+ try {
26
+ let connected = await super.startSensor();
27
+ if (connected) {
28
+ const sensor = this.getSensor();
29
+ if (this.keyPressedHandler) {
30
+ sensor.off('key-pressed', this.keyPressedHandler);
31
+ }
32
+ else {
33
+ this.keyPressedHandler = this.onKeyPressed.bind(this);
34
+ }
35
+ sensor.on('key-pressed', this.keyPressedHandler);
36
+ }
37
+ return connected;
38
+ }
39
+ catch (err) {
40
+ this.logEvent({ message: 'error', fn: 'startSensor', error: err.message, stack: err.stack });
41
+ return false;
42
+ }
43
+ }
44
+ onKeyPressed(event) {
45
+ this.emit('key-pressed', this.getSettings(), event);
46
+ }
47
+ isEqual(settings) {
48
+ return super.isEqual(settings) && settings.address == this.settings.address;
49
+ }
50
+ isSame(adapter) {
51
+ if (!(adapter instanceof OpenBikeControlAdapter))
52
+ return false;
53
+ return this.isEqual(adapter.settings);
54
+ }
55
+ updateSensor(peripheral) {
56
+ this.device = new sensor_js_1.BleOpenBikeControlSensor(peripheral, { logger: this.logger });
57
+ }
58
+ getProfile() {
59
+ return OpenBikeControlAdapter.INCYCLIST_PROFILE_NAME;
60
+ }
61
+ getName() {
62
+ const settings = this.settings;
63
+ const id = (settings.id ?? settings.address ?? '').replace(/[:\-.]/g, '');
64
+ const addressHash = id.length > 4 ? id.slice(-4).toUpperCase() : id.toUpperCase();
65
+ return addressHash ? `${settings.name} ${addressHash}` : settings.name;
66
+ }
67
+ getDisplayName() {
68
+ return this.getName();
69
+ }
70
+ mapData(deviceData) {
71
+ return {};
72
+ }
73
+ shouldWaitForData() {
74
+ return false;
75
+ }
76
+ }
77
+ exports.OpenBikeControlAdapter = OpenBikeControlAdapter;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OBC_APP_INFO = exports.OBC_BUTTON_STATE = exports.OBC_SERVICE = void 0;
4
+ exports.OBC_SERVICE = 'd273f680-d548-419d-b9d1-fa0472345229';
5
+ exports.OBC_BUTTON_STATE = 'd273f681-d548-419d-b9d1-fa0472345229';
6
+ exports.OBC_APP_INFO = 'd273f683-d548-419d-b9d1-fa0472345229';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./sensor.js"), exports);
18
+ __exportStar(require("./adapter.js"), exports);
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BleOpenBikeControlSensor = void 0;
4
+ const sensor_js_1 = require("../base/sensor.js");
5
+ const utils_js_1 = require("../utils.js");
6
+ const consts_js_1 = require("./consts.js");
7
+ const MSG_BUTTON_STATE = 0x01;
8
+ const MSG_APP_INFO = 0x04;
9
+ const BUTTON_SHIFT_UP = 0x01;
10
+ const BUTTON_SHIFT_DOWN = 0x02;
11
+ const BUTTON_INCREASE_DIFFICULTY = 0x30;
12
+ const BUTTON_DECREASE_DIFFICULTY = 0x31;
13
+ const BUTTON_SKIP_INTERVAL = 0x32;
14
+ const BUTTON_PREVIOUS_INTERVAL = 0x36;
15
+ const BUTTON_KEYS = new Map([
16
+ [BUTTON_SHIFT_UP, 'r-shift-up'],
17
+ [BUTTON_SHIFT_DOWN, 'r-shift-down'],
18
+ [BUTTON_INCREASE_DIFFICULTY, 'y'],
19
+ [BUTTON_DECREASE_DIFFICULTY, 'b'],
20
+ [BUTTON_SKIP_INTERVAL, 'a'],
21
+ [BUTTON_PREVIOUS_INTERVAL, 'z'],
22
+ ]);
23
+ class BleOpenBikeControlSensor extends sensor_js_1.TBleSensor {
24
+ static profile = 'Controller';
25
+ static protocol = 'openbikecontrol';
26
+ static services = [consts_js_1.OBC_SERVICE];
27
+ static characteristics = [];
28
+ static detectionPriority = 0;
29
+ buttonStates = new Map();
30
+ onDisconnect() {
31
+ super.onDisconnect();
32
+ this.reset();
33
+ }
34
+ async subscribe() {
35
+ const subscribed = await super.subscribe();
36
+ if (subscribed)
37
+ await this.sendAppInfo();
38
+ return subscribed;
39
+ }
40
+ getRequiredCharacteristics() {
41
+ return [consts_js_1.OBC_BUTTON_STATE];
42
+ }
43
+ onData(characteristic, data) {
44
+ if ((0, utils_js_1.matches)(characteristic, consts_js_1.OBC_BUTTON_STATE)) {
45
+ this.onButtonState(Buffer.from(data));
46
+ }
47
+ return true;
48
+ }
49
+ onButtonState(data) {
50
+ try {
51
+ if (data.length < 3 || data[0] !== MSG_BUTTON_STATE)
52
+ return;
53
+ const press = { buttons: [], pressed: [], timestamp: Date.now() };
54
+ const released = [];
55
+ for (let i = 1; i + 1 < data.length; i += 2) {
56
+ const buttonId = data[i];
57
+ if (!BUTTON_KEYS.has(buttonId))
58
+ continue;
59
+ const pressed = data[i + 1] !== 0x00;
60
+ const prev = this.buttonStates.get(buttonId);
61
+ if (pressed && !prev) {
62
+ press.buttons.push(buttonId);
63
+ press.pressed.push(buttonId);
64
+ this.buttonStates.set(buttonId, press);
65
+ }
66
+ else if (!pressed && prev) {
67
+ this.buttonStates.delete(buttonId);
68
+ prev.pressed = prev.pressed.filter(id => id !== buttonId);
69
+ if (prev.pressed.length === 0)
70
+ released.push(prev);
71
+ }
72
+ }
73
+ released.forEach(p => {
74
+ const key = this.getKey(p.buttons);
75
+ const duration = Date.now() - p.timestamp;
76
+ const { name, address } = this.peripheral?.getInfo() ?? {};
77
+ this.logEvent({ message: 'key pressed', key, name, address, duration });
78
+ this.emit('key-pressed', { key, duration });
79
+ });
80
+ }
81
+ catch (err) {
82
+ this.logEvent({ message: 'error', fn: 'onButtonState', error: err.message, stack: err.stack });
83
+ }
84
+ }
85
+ getKey(buttons) {
86
+ if (buttons.includes(BUTTON_SHIFT_UP) && buttons.includes(BUTTON_INCREASE_DIFFICULTY))
87
+ return 'up';
88
+ if (buttons.includes(BUTTON_SHIFT_DOWN) && buttons.includes(BUTTON_DECREASE_DIFFICULTY))
89
+ return 'down';
90
+ const buttonId = Array.from(BUTTON_KEYS.keys()).find(id => buttons.includes(id));
91
+ return BUTTON_KEYS.get(buttonId);
92
+ }
93
+ async sendAppInfo() {
94
+ try {
95
+ const appId = Buffer.from('incyclist');
96
+ const buttons = Array.from(BUTTON_KEYS.keys());
97
+ const message = Buffer.from([MSG_APP_INFO, 0x01, appId.length, ...appId, 0x00, buttons.length, ...buttons]);
98
+ await this.write(consts_js_1.OBC_APP_INFO, message, { withoutResponse: true });
99
+ }
100
+ catch (err) {
101
+ this.logEvent({ message: 'warning', fn: 'sendAppInfo', error: err.message });
102
+ }
103
+ }
104
+ reset() {
105
+ this.buttonStates = new Map();
106
+ }
107
+ }
108
+ exports.BleOpenBikeControlSensor = BleOpenBikeControlSensor;
@@ -82,5 +82,8 @@ class ZwiftPlayAdapter extends adapter_js_1.default {
82
82
  mapData(deviceData) {
83
83
  return {};
84
84
  }
85
+ shouldWaitForData() {
86
+ return false;
87
+ }
85
88
  }
86
89
  exports.ZwiftPlayAdapter = ZwiftPlayAdapter;
@@ -3,7 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BleZwiftPlaySensor = void 0;
4
4
  const zwift_hub_js_1 = require("../../../proto/zwift_hub.js");
5
5
  const sensor_js_1 = require("../../base/sensor.js");
6
- const utils_js_1 = require("../../utils.js");
6
+ const utils_js_1 = require("../../../utils/utils.js");
7
+ const utils_js_2 = require("../../utils.js");
7
8
  const node_events_1 = require("node:events");
8
9
  const index_js_1 = require("../../../bindings/index.js");
9
10
  class BleZwiftPlaySensor extends sensor_js_1.TBleSensor {
@@ -36,31 +37,84 @@ class BleZwiftPlaySensor extends sensor_js_1.TBleSensor {
36
37
  prevcWax10000;
37
38
  pendingMeasurement;
38
39
  measurementReassemblyErrorLogged = false;
40
+ static RECONNECT_PAIR_ATTEMPTS = 3;
41
+ static RECONNECT_PAIR_RETRY_DELAY = 1000;
42
+ owner;
43
+ ownerReconnectCount = 0;
44
+ reconnectAndPairPromise;
39
45
  constructor(peripheral, props) {
40
46
  if (props?.isTrainer && peripheral) {
41
47
  const sensor = peripheral;
42
48
  super(sensor.getPeripheral(), props);
43
49
  this.isFM = true;
50
+ this.owner = sensor;
44
51
  }
45
52
  else if (peripheral &&
46
53
  'startSensor' in peripheral && typeof peripheral.startSensor === 'function' &&
47
54
  'getPeripheral' in peripheral && typeof peripheral.getPeripheral === 'function') {
48
55
  super(peripheral.getPeripheral(), props);
49
56
  this.isFM = true;
57
+ this.owner = peripheral;
50
58
  }
51
59
  else {
52
60
  super(peripheral, props);
53
61
  this.isFM = false;
54
62
  }
63
+ this.ownerReconnectCount = this.owner?.getReconnectCount?.() ?? 0;
55
64
  this.emitter = new node_events_1.EventEmitter();
56
65
  this.setInitialState();
57
66
  }
58
67
  async reconnectSensor() {
59
- this.setInitialState();
60
- let reconnected = await super.reconnectSensor();
61
- this.pair();
68
+ this.reconnectAndPairPromise = this.reconnectAndPairPromise ?? this.reconnectAndPair();
69
+ const promise = this.reconnectAndPairPromise;
70
+ const reconnected = await promise;
71
+ if (this.reconnectAndPairPromise === promise)
72
+ delete this.reconnectAndPairPromise;
62
73
  return reconnected;
63
74
  }
75
+ isReconnectBusy() {
76
+ return super.isReconnectBusy() || this.reconnectAndPairPromise !== undefined || this.isOwnerReconnecting();
77
+ }
78
+ isOwnerReconnecting() {
79
+ return this.owner?.isReconnectBusy?.() ?? false;
80
+ }
81
+ async reconnectAndPair() {
82
+ this.setInitialState();
83
+ const reconnected = await super.reconnectSensor();
84
+ if (!reconnected)
85
+ return false;
86
+ const paired = await this.pairWithRetry(1);
87
+ if (paired === undefined) {
88
+ const { name, address } = this.peripheral?.getInfo() ?? {};
89
+ this.logEvent({ message: 'reconnect sensor pairing failed', name, address, attempts: BleZwiftPlaySensor.RECONNECT_PAIR_ATTEMPTS });
90
+ return false;
91
+ }
92
+ return paired;
93
+ }
94
+ async pairWithRetry(attempt) {
95
+ if (this.stopRequested)
96
+ return false;
97
+ if (await this.pair())
98
+ return true;
99
+ if (attempt >= BleZwiftPlaySensor.RECONNECT_PAIR_ATTEMPTS)
100
+ return undefined;
101
+ await (0, utils_js_1.sleep)(BleZwiftPlaySensor.RECONNECT_PAIR_RETRY_DELAY);
102
+ return this.pairWithRetry(attempt + 1);
103
+ }
104
+ canSendHubCommand(fn) {
105
+ if (!this.owner)
106
+ return true;
107
+ const reconnectCount = this.owner.getReconnectCount?.() ?? 0;
108
+ if (reconnectCount !== this.ownerReconnectCount) {
109
+ this.ownerReconnectCount = reconnectCount;
110
+ this.setInitialState();
111
+ }
112
+ if (this.isOwnerReconnecting()) {
113
+ this.logger.logEvent({ message: 'warning', fn, reason: 'reconnect in progress', skipped: true });
114
+ return false;
115
+ }
116
+ return true;
117
+ }
64
118
  stopSensor() {
65
119
  this.emitter.removeAllListeners();
66
120
  this.setInitialState();
@@ -107,7 +161,7 @@ class BleZwiftPlaySensor extends sensor_js_1.TBleSensor {
107
161
  return this.deviceType;
108
162
  }
109
163
  onData(characteristic, data, isNotify) {
110
- const uuid = (0, utils_js_1.beautifyUUID)(characteristic).toLowerCase();
164
+ const uuid = (0, utils_js_2.beautifyUUID)(characteristic).toLowerCase();
111
165
  if (uuid === '00000002-19ca-4651-86e5-fa29dcdd09d1') {
112
166
  this.onMeasurement(data);
113
167
  }
@@ -123,6 +177,8 @@ class BleZwiftPlaySensor extends sensor_js_1.TBleSensor {
123
177
  }
124
178
  async setSimulationData(data) {
125
179
  try {
180
+ if (!this.canSendHubCommand('setSimulationData'))
181
+ return;
126
182
  if (!this.isHubServiceActive) {
127
183
  await this.initHubService(false);
128
184
  }
@@ -161,6 +217,8 @@ class BleZwiftPlaySensor extends sensor_js_1.TBleSensor {
161
217
  }
162
218
  async setGearRatio(gearRatio) {
163
219
  try {
220
+ if (!this.canSendHubCommand('setGearRatio'))
221
+ return;
164
222
  if (!this.isHubServiceActive) {
165
223
  await this.initHubService();
166
224
  }
@@ -270,6 +328,8 @@ class BleZwiftPlaySensor extends sensor_js_1.TBleSensor {
270
328
  }
271
329
  }
272
330
  async initHubService(setSimulation = true) {
331
+ if (!this.canSendHubCommand('initHubService'))
332
+ return false;
273
333
  if (!this.isHubServiceActive && this.initHubServicePromise !== undefined) {
274
334
  await this.initHubServicePromise;
275
335
  }
@@ -574,7 +634,7 @@ class BleZwiftPlaySensor extends sensor_js_1.TBleSensor {
574
634
  const paired = await this.pairPromise;
575
635
  this.pairPromise = undefined;
576
636
  if (paired)
577
- return;
637
+ return true;
578
638
  }
579
639
  let manufacturerData;
580
640
  try {
@@ -624,7 +684,7 @@ class BleZwiftPlaySensor extends sensor_js_1.TBleSensor {
624
684
  message = Buffer.from('RideOn');
625
685
  }
626
686
  this.logEvent({ message: `send rideOn` });
627
- await this.write((0, utils_js_1.fullUUID)('00000003-19ca-4651-86e5-fa29dcdd09d1'), message, { withoutResponse: true });
687
+ await this.write((0, utils_js_2.fullUUID)('00000003-19ca-4651-86e5-fa29dcdd09d1'), message, { withoutResponse: true });
628
688
  this.isHubServicePaired = true;
629
689
  this.logEvent({ message: 'pairing done', deviceType: this.deviceType, encrypted: this.encrypted, manufacturerData: this.getManufacturerData() });
630
690
  return true;