incyclist-devices 3.0.45 → 3.0.47

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.
@@ -167,7 +167,7 @@ class IncyclistDevice extends node_events_1.EventEmitter {
167
167
  }
168
168
  createOrGetMode(mode, useCurrent = true) {
169
169
  if (typeof mode === 'string') {
170
- if (useCurrent && this.cyclingMode && mode === this.cyclingMode?.getName()) {
170
+ if (useCurrent && this.cyclingMode && mode === this.cyclingMode?.getName() && this.isModeSupported(mode)) {
171
171
  return this.cyclingMode;
172
172
  }
173
173
  const supported = this.getSupportedCyclingModes();
@@ -185,6 +185,9 @@ class IncyclistDevice extends node_events_1.EventEmitter {
185
185
  }
186
186
  return mode;
187
187
  }
188
+ isModeSupported(_modeName) {
189
+ return true;
190
+ }
188
191
  getSupportedCyclingModes() {
189
192
  if (!this.isControllable())
190
193
  return [];
@@ -35,7 +35,7 @@ class BleAdapter extends adpater_js_1.default {
35
35
  if (this.getName().match(/\d/g) || settings.address === undefined)
36
36
  return this.getName();
37
37
  else {
38
- const id = (settings.id ?? settings.address ?? '').replace(/[:\-]/g, '');
38
+ const id = (settings.id ?? settings.address ?? '').replace(/[:\-.]/g, '');
39
39
  const addressHash = id.length > 4 ? id.slice(-4).toUpperCase() : id.toUpperCase();
40
40
  return `${this.getName()} ${addressHash}`;
41
41
  }
@@ -131,6 +131,8 @@ class BleAdapter extends adpater_js_1.default {
131
131
  }
132
132
  getName() {
133
133
  const settings = this.settings;
134
+ const id = (settings.id ?? settings.address ?? '').replace(/[:\-]/g, '');
135
+ const addressHash = id.length > 4 ? id.slice(-4).toUpperCase() : id.toUpperCase();
134
136
  return settings.name || settings.id || settings.address;
135
137
  }
136
138
  refreshDeviceData() {
@@ -26,6 +26,7 @@ class BleFmAdapter extends adapter_js_1.default {
26
26
  promiseSendUpdate;
27
27
  zwiftPlay;
28
28
  isHubInitialized = false;
29
+ setSlopeSkippedLogged = false;
29
30
  constructor(settings, props) {
30
31
  super(settings, props);
31
32
  this.logger = new gd_eventlog_1.EventLogger('BLE-FM');
@@ -176,6 +177,7 @@ class BleFmAdapter extends adapter_js_1.default {
176
177
  return;
177
178
  await this.establishControl();
178
179
  await this.attemptStartRequest();
180
+ this.getResistanceMode()?.resetSession();
179
181
  await this.sendInitialRequest();
180
182
  }
181
183
  async initControlBestEffort(_startProps) {
@@ -289,6 +291,20 @@ class BleFmAdapter extends adapter_js_1.default {
289
291
  mode.resetConfig();
290
292
  mode.getConfig();
291
293
  });
294
+ const autoDefault = this.getSensor()?.features?.setSlope === false;
295
+ const resistanceModes = [...Object.values(this.modes), this.cyclingMode];
296
+ resistanceModes.forEach(mode => {
297
+ if (mode instanceof fm_resistance_js_1.default)
298
+ mode.setAutoResistanceDefault(autoDefault);
299
+ });
300
+ }
301
+ getResistanceMode() {
302
+ const mode = this.getCyclingMode();
303
+ return mode instanceof fm_resistance_js_1.default ? mode : undefined;
304
+ }
305
+ async stop() {
306
+ this.getResistanceMode()?.logSummary();
307
+ return await super.stop();
292
308
  }
293
309
  async checkCapabilities() {
294
310
  const before = this.capabilities.join(',');
@@ -304,12 +320,42 @@ class BleFmAdapter extends adapter_js_1.default {
304
320
  if (sensor.features) {
305
321
  this.updateCapabilitiesFromFeatures(sensor.features);
306
322
  }
323
+ this.setSlopeSkippedLogged = false;
324
+ this.checkCyclingModeSupported();
325
+ if (sensor.features)
326
+ this.updateCyclingModeConfig();
307
327
  const after = this.capabilities.join(',');
308
328
  if (before !== after) {
309
329
  this.logEvent({ message: 'device capabilities updated', name: this.getSettings().name, interface: this.getSettings().interface, capabilities: this.capabilities });
310
330
  this.emit('device-info', this.getSettings(), { capabilities: this.capabilities });
311
331
  }
312
332
  }
333
+ isModeSupported(modeName) {
334
+ if (!this.getSensor()?.features)
335
+ return true;
336
+ return this.getSupportedCyclingModes().some(M => new M(null).getName() === modeName);
337
+ }
338
+ checkCyclingModeSupported() {
339
+ const sensor = this.getSensor();
340
+ const features = sensor?.features;
341
+ if (!features)
342
+ return;
343
+ const current = this.getCyclingMode();
344
+ const requestedMode = current?.getName();
345
+ if (!requestedMode || this.isModeSupported(requestedMode))
346
+ return;
347
+ const newMode = this.getDefaultCyclingMode();
348
+ if (!newMode)
349
+ return;
350
+ this.cyclingMode = newMode;
351
+ this.logEvent({
352
+ message: 'cycling mode not supported',
353
+ requestedMode, newMode: newMode.getName(),
354
+ setSlope: features.setSlope === true, setPower: features.setPower === true, setResistance: features.setResistance === true,
355
+ device: this.getName()
356
+ });
357
+ this.emit('mode-replaced', { requestedMode, newMode: newMode.getName() });
358
+ }
313
359
  updateCapabilitiesFromFeatures(features) {
314
360
  if (features.heartrate && !this.hasCapability(index_js_1.IncyclistCapability.HeartRate)) {
315
361
  this.capabilities.push(index_js_1.IncyclistCapability.HeartRate);
@@ -352,7 +398,14 @@ class BleFmAdapter extends adapter_js_1.default {
352
398
  const send = async () => {
353
399
  const res = {};
354
400
  if (update.slope !== undefined) {
355
- if (update.isHub) {
401
+ const skipSlope = !update.isHub && device.features?.setSlope === false;
402
+ if (skipSlope) {
403
+ if (!this.setSlopeSkippedLogged) {
404
+ this.setSlopeSkippedLogged = true;
405
+ this.logEvent({ message: 'setSlope skipped', reason: 'not supported', device: this.getName() });
406
+ }
407
+ }
408
+ else if (update.isHub) {
356
409
  await this.initVirtualShifting(true);
357
410
  if (this.zwiftPlay) {
358
411
  await this.zwiftPlay.setIncline(update.slope);
@@ -361,7 +414,8 @@ class BleFmAdapter extends adapter_js_1.default {
361
414
  else {
362
415
  await device.setSlope(update.slope);
363
416
  }
364
- res.slope = update.slope;
417
+ if (!skipSlope)
418
+ res.slope = update.slope;
365
419
  }
366
420
  if (update.targetPower !== undefined && !update.isHub) {
367
421
  const tp = update.targetPower > 0 ? update.targetPower : 0;
@@ -369,7 +423,9 @@ class BleFmAdapter extends adapter_js_1.default {
369
423
  res.targetPower = tp;
370
424
  }
371
425
  if (update.targetResistance !== undefined && !update.isHub) {
372
- await device.setTargetResistanceLevel(update.targetResistance);
426
+ const success = await device.setTargetResistanceLevel(update.targetResistance);
427
+ if (success === false)
428
+ this.getResistanceMode()?.registerFailedUpdate();
373
429
  res.targetResistance = update.targetResistance;
374
430
  }
375
431
  if (update.gearRatio !== undefined) {
@@ -167,6 +167,9 @@ class BleFitnessMachineDevice extends sensor_js_1.TBleSensor {
167
167
  if (res === 5) {
168
168
  this.hasControl = false;
169
169
  }
170
+ if (res !== 1) {
171
+ this.logEvent({ message: 'setTargetResistanceLevel failed', device: this.getName(), resistanceLevel, result: String(res) });
172
+ }
170
173
  return (res === 1);
171
174
  }
172
175
  async setSlope(slope) {
@@ -701,7 +704,7 @@ class BleFitnessMachineDevice extends sensor_js_1.TBleSensor {
701
704
  return (res === 1);
702
705
  }
703
706
  async setIndoorBikeSimulation(windSpeed, gradient, crr, cw) {
704
- if (this.features?.setPower === false)
707
+ if (this.features?.setSlope === false)
705
708
  return true;
706
709
  this.logEvent({ message: 'setIndoorBikeSimulation', device: this.getName(), windSpeed, gradient, crr, cw });
707
710
  const hasControl = await this.requestControl();
@@ -76,7 +76,7 @@ class ZwiftPlayAdapter extends adapter_js_1.default {
76
76
  if (this.device.getDeviceType() === 'ride-right')
77
77
  name = name + '-R';
78
78
  }
79
- const id = (settings.id ?? settings.address ?? '').replace(/[:\-]/g, '');
79
+ const id = (settings.id ?? settings.address ?? '').replace(/[:\-.]/g, '');
80
80
  const addressHash = id.length > 4 ? id.slice(-4).toUpperCase() : id.toUpperCase();
81
81
  return `${name} ${addressHash}`;
82
82
  }
@@ -5,6 +5,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const power_base_js_1 = __importDefault(require("./power-base.js"));
7
7
  const types_js_1 = require("./types.js");
8
+ const MIN_GEAR = 1;
9
+ const MAX_GEAR = 26;
10
+ const LEVELS_PER_GEAR = 4;
11
+ const DEFAULT_MAX_SLOPE = 10;
12
+ const DOWNHILL_FACTOR = 0.5;
13
+ const UPDATE_THROTTLE_MS = 1000;
8
14
  class FMResistanceMode extends power_base_js_1.default {
9
15
  static config = {
10
16
  isERG: false,
@@ -12,20 +18,61 @@ class FMResistanceMode extends power_base_js_1.default {
12
18
  isResistance: true,
13
19
  name: "Resistance",
14
20
  description: "Resistance levels are set by the app based on selected gear. Calculates speed based on power and slope.",
15
- properties: [
16
- { key: 'startGear', name: 'Initial Gear', description: 'Initial Gear', type: types_js_1.CyclingModeProperyType.Integer, default: 5, min: 1, max: 26 }
17
- ]
21
+ properties: FMResistanceMode.buildProperties(false)
18
22
  };
23
+ static buildProperties(autoDefault) {
24
+ const isAuto = (s) => (s?.autoResistance ?? autoDefault) !== false && s?.autoResistance !== 'false';
25
+ return [
26
+ { key: 'startGear', name: 'Initial Gear', description: 'Initial Gear', type: types_js_1.CyclingModeProperyType.Integer, default: 5, min: 1, max: 26 },
27
+ { key: 'autoResistance', name: 'Auto Resistance', description: 'Adjusts the resistance automatically to the slope of the route. Gear shifts will increase/decrease the resistance on top of that', type: types_js_1.CyclingModeProperyType.Boolean, default: autoDefault },
28
+ { key: 'maxSlope', name: 'Max Slope', description: 'Slope (in %) at which the maximum resistance is reached. Downhill sections reduce the resistance at half of that rate', type: types_js_1.CyclingModeProperyType.Integer, default: DEFAULT_MAX_SLOPE, min: 1, max: 30, condition: isAuto }
29
+ ];
30
+ }
19
31
  confirmedResistance;
20
32
  requestedResistance;
33
+ gearOffset = 0;
34
+ lastAutoSendTs = 0;
35
+ autoStats = { updatesSent: 0, updatesFailed: 0, gearChanges: 0 };
21
36
  constructor(adapter, props) {
22
37
  super(adapter, props);
23
38
  this.initLogger('FMResistanceMode');
24
39
  this.data.slope = 0;
25
40
  }
41
+ setAutoResistanceDefault(autoDefault) {
42
+ const base = this.constructor.config;
43
+ this.setConfig({ ...base, properties: FMResistanceMode.buildProperties(autoDefault) });
44
+ }
45
+ isAutoResistance() {
46
+ const value = this.getSetting('autoResistance');
47
+ return value === true || value === 'true';
48
+ }
26
49
  getBikeInitRequest() {
50
+ if (this.isAutoResistance()) {
51
+ return { targetResistance: this.calculateAutoResistance(this.data.slope ?? 0) };
52
+ }
27
53
  return { targetResistance: this.calculateTargetResistance(this.getInitialGear()) };
28
54
  }
55
+ resetSession() {
56
+ this.gearOffset = 0;
57
+ this.lastAutoSendTs = 0;
58
+ this.autoStats = { updatesSent: 0, updatesFailed: 0, gearChanges: 0 };
59
+ }
60
+ registerFailedUpdate() {
61
+ if (this.isAutoResistance())
62
+ this.autoStats.updatesFailed++;
63
+ }
64
+ logSummary() {
65
+ const stats = this.autoStats;
66
+ if (stats.updatesSent === 0)
67
+ return;
68
+ const durationSec = stats.tsStart ? Math.round((Date.now() - stats.tsStart) / 1000) : 0;
69
+ this.logEvent({
70
+ message: 'auto resistance summary',
71
+ updatesSent: stats.updatesSent, updatesFailed: stats.updatesFailed, gearChanges: stats.gearChanges,
72
+ targetMin: stats.targetMin ?? 0, targetMax: stats.targetMax ?? 0, durationSec
73
+ });
74
+ this.autoStats = { updatesSent: 0, updatesFailed: 0, gearChanges: 0 };
75
+ }
29
76
  sendBikeUpdate(incoming) {
30
77
  if (this.logger)
31
78
  this.logEvent({ message: "processing update request", request: incoming, prev: this.prevRequest, data: this.getData() });
@@ -38,8 +85,16 @@ class FMResistanceMode extends power_base_js_1.default {
38
85
  return req;
39
86
  }
40
87
  this.checkSlope(request);
41
- this.checkGearDeltaSet(request, newRequest);
88
+ if (this.isAutoResistance()) {
89
+ this.checkAutoGearDeltaSet(request, newRequest);
90
+ }
91
+ else {
92
+ this.checkGearDeltaSet(request, newRequest);
93
+ }
42
94
  this.checkTargetResistanceSet(request, newRequest);
95
+ if (this.isAutoResistance()) {
96
+ this.checkAutoResistanceSet(newRequest);
97
+ }
43
98
  this.checkRefresh(request, newRequest);
44
99
  this.checkEmptyRequest(newRequest);
45
100
  this.prevRequest = JSON.parse(JSON.stringify(newRequest));
@@ -50,6 +105,9 @@ class FMResistanceMode extends power_base_js_1.default {
50
105
  }
51
106
  if (newRequest.targetResistance !== undefined) {
52
107
  this.requestedResistance = newRequest.targetResistance;
108
+ if (this.isAutoResistance()) {
109
+ this.recordAutoUpdate(newRequest.targetResistance);
110
+ }
53
111
  }
54
112
  return newRequest;
55
113
  }
@@ -89,8 +147,68 @@ class FMResistanceMode extends power_base_js_1.default {
89
147
  delete request.gearDelta;
90
148
  }
91
149
  }
150
+ getStartGear() {
151
+ const gear = Math.round(this.getInitialGear());
152
+ if (Number.isNaN(gear))
153
+ return MIN_GEAR;
154
+ return Math.min(Math.max(gear, MIN_GEAR), MAX_GEAR);
155
+ }
156
+ getMaxSlope() {
157
+ const maxSlope = Number(this.getSetting('maxSlope'));
158
+ return (Number.isNaN(maxSlope) || maxSlope <= 0) ? DEFAULT_MAX_SLOPE : maxSlope;
159
+ }
160
+ getGearOffset() {
161
+ const startGear = this.getStartGear();
162
+ return Math.min(Math.max(this.gearOffset, MIN_GEAR - startGear), MAX_GEAR - startGear);
163
+ }
164
+ getVirtualGear() {
165
+ return this.getStartGear() + this.getGearOffset();
166
+ }
167
+ calculateAutoResistance(slope) {
168
+ const base = this.calculateTargetResistance(this.getStartGear());
169
+ const maxSlope = this.getMaxSlope();
170
+ const s = Number.isFinite(slope) ? slope : 0;
171
+ const effective = s < 0 ? s * DOWNHILL_FACTOR : s;
172
+ const resistance = base + (100 - base) * effective / maxSlope + LEVELS_PER_GEAR * this.getGearOffset();
173
+ return Math.round(Math.min(Math.max(resistance, 0), 100));
174
+ }
175
+ checkAutoGearDeltaSet(request, newRequest) {
176
+ if (request.gearDelta === undefined)
177
+ return;
178
+ const startGear = this.getStartGear();
179
+ const prevOffset = this.getGearOffset();
180
+ const offset = Math.min(Math.max(prevOffset + request.gearDelta, MIN_GEAR - startGear), MAX_GEAR - startGear);
181
+ delete request.gearDelta;
182
+ if (offset !== prevOffset)
183
+ this.autoStats.gearChanges++;
184
+ this.gearOffset = offset;
185
+ newRequest.targetResistance = this.calculateAutoResistance(this.data.slope ?? 0);
186
+ }
187
+ checkAutoResistanceSet(newRequest) {
188
+ if (newRequest.targetResistance !== undefined)
189
+ return;
190
+ if (Date.now() - this.lastAutoSendTs < UPDATE_THROTTLE_MS)
191
+ return;
192
+ const target = this.calculateAutoResistance(this.data.slope ?? 0);
193
+ if (target !== this.requestedResistance)
194
+ newRequest.targetResistance = target;
195
+ }
196
+ recordAutoUpdate(target) {
197
+ const now = Date.now();
198
+ const stats = this.autoStats;
199
+ this.lastAutoSendTs = now;
200
+ stats.tsStart = stats.tsStart ?? now;
201
+ stats.updatesSent++;
202
+ stats.targetMin = stats.targetMin === undefined ? target : Math.min(stats.targetMin, target);
203
+ stats.targetMax = stats.targetMax === undefined ? target : Math.max(stats.targetMax, target);
204
+ }
92
205
  updateData(bikeData, log) {
93
206
  const data = super.updateData(bikeData, log);
207
+ if (this.isAutoResistance()) {
208
+ data.gear = this.getVirtualGear();
209
+ data.gearStr = `${data.gear}`;
210
+ return data;
211
+ }
94
212
  if (data.resistance !== undefined) {
95
213
  data.gear = this.getGear(data.resistance);
96
214
  data.gearStr = `${data.gear}`;
@@ -412,6 +412,10 @@ class KettlerRacerAdapter extends adapter_js_1.SerialIncyclistDevice {
412
412
  }
413
413
  catch (err) {
414
414
  this.requestBusy = false;
415
+ if (err.message === 'connection error') {
416
+ this.logEvent({ message: 'send failed', reason: 'not connected' });
417
+ return;
418
+ }
415
419
  this.logEvent({ message: 'error', fn: 'sendRequest()', error: err.message || err });
416
420
  return;
417
421
  }
@@ -165,7 +165,7 @@ export default class IncyclistDevice extends EventEmitter {
165
165
  }
166
166
  createOrGetMode(mode, useCurrent = true) {
167
167
  if (typeof mode === 'string') {
168
- if (useCurrent && this.cyclingMode && mode === this.cyclingMode?.getName()) {
168
+ if (useCurrent && this.cyclingMode && mode === this.cyclingMode?.getName() && this.isModeSupported(mode)) {
169
169
  return this.cyclingMode;
170
170
  }
171
171
  const supported = this.getSupportedCyclingModes();
@@ -183,6 +183,9 @@ export default class IncyclistDevice extends EventEmitter {
183
183
  }
184
184
  return mode;
185
185
  }
186
+ isModeSupported(_modeName) {
187
+ return true;
188
+ }
186
189
  getSupportedCyclingModes() {
187
190
  if (!this.isControllable())
188
191
  return [];
@@ -30,7 +30,7 @@ export default class BleAdapter extends IncyclistDevice {
30
30
  if (this.getName().match(/\d/g) || settings.address === undefined)
31
31
  return this.getName();
32
32
  else {
33
- const id = (settings.id ?? settings.address ?? '').replace(/[:\-]/g, '');
33
+ const id = (settings.id ?? settings.address ?? '').replace(/[:\-.]/g, '');
34
34
  const addressHash = id.length > 4 ? id.slice(-4).toUpperCase() : id.toUpperCase();
35
35
  return `${this.getName()} ${addressHash}`;
36
36
  }
@@ -126,6 +126,8 @@ export default class BleAdapter extends IncyclistDevice {
126
126
  }
127
127
  getName() {
128
128
  const settings = this.settings;
129
+ const id = (settings.id ?? settings.address ?? '').replace(/[:\-]/g, '');
130
+ const addressHash = id.length > 4 ? id.slice(-4).toUpperCase() : id.toUpperCase();
129
131
  return settings.name || settings.id || settings.address;
130
132
  }
131
133
  refreshDeviceData() {
@@ -21,6 +21,7 @@ export default class BleFmAdapter extends BleAdapter {
21
21
  promiseSendUpdate;
22
22
  zwiftPlay;
23
23
  isHubInitialized = false;
24
+ setSlopeSkippedLogged = false;
24
25
  constructor(settings, props) {
25
26
  super(settings, props);
26
27
  this.logger = new EventLogger('BLE-FM');
@@ -171,6 +172,7 @@ export default class BleFmAdapter extends BleAdapter {
171
172
  return;
172
173
  await this.establishControl();
173
174
  await this.attemptStartRequest();
175
+ this.getResistanceMode()?.resetSession();
174
176
  await this.sendInitialRequest();
175
177
  }
176
178
  async initControlBestEffort(_startProps) {
@@ -284,6 +286,20 @@ export default class BleFmAdapter extends BleAdapter {
284
286
  mode.resetConfig();
285
287
  mode.getConfig();
286
288
  });
289
+ const autoDefault = this.getSensor()?.features?.setSlope === false;
290
+ const resistanceModes = [...Object.values(this.modes), this.cyclingMode];
291
+ resistanceModes.forEach(mode => {
292
+ if (mode instanceof FMResistanceMode)
293
+ mode.setAutoResistanceDefault(autoDefault);
294
+ });
295
+ }
296
+ getResistanceMode() {
297
+ const mode = this.getCyclingMode();
298
+ return mode instanceof FMResistanceMode ? mode : undefined;
299
+ }
300
+ async stop() {
301
+ this.getResistanceMode()?.logSummary();
302
+ return await super.stop();
287
303
  }
288
304
  async checkCapabilities() {
289
305
  const before = this.capabilities.join(',');
@@ -299,12 +315,42 @@ export default class BleFmAdapter extends BleAdapter {
299
315
  if (sensor.features) {
300
316
  this.updateCapabilitiesFromFeatures(sensor.features);
301
317
  }
318
+ this.setSlopeSkippedLogged = false;
319
+ this.checkCyclingModeSupported();
320
+ if (sensor.features)
321
+ this.updateCyclingModeConfig();
302
322
  const after = this.capabilities.join(',');
303
323
  if (before !== after) {
304
324
  this.logEvent({ message: 'device capabilities updated', name: this.getSettings().name, interface: this.getSettings().interface, capabilities: this.capabilities });
305
325
  this.emit('device-info', this.getSettings(), { capabilities: this.capabilities });
306
326
  }
307
327
  }
328
+ isModeSupported(modeName) {
329
+ if (!this.getSensor()?.features)
330
+ return true;
331
+ return this.getSupportedCyclingModes().some(M => new M(null).getName() === modeName);
332
+ }
333
+ checkCyclingModeSupported() {
334
+ const sensor = this.getSensor();
335
+ const features = sensor?.features;
336
+ if (!features)
337
+ return;
338
+ const current = this.getCyclingMode();
339
+ const requestedMode = current?.getName();
340
+ if (!requestedMode || this.isModeSupported(requestedMode))
341
+ return;
342
+ const newMode = this.getDefaultCyclingMode();
343
+ if (!newMode)
344
+ return;
345
+ this.cyclingMode = newMode;
346
+ this.logEvent({
347
+ message: 'cycling mode not supported',
348
+ requestedMode, newMode: newMode.getName(),
349
+ setSlope: features.setSlope === true, setPower: features.setPower === true, setResistance: features.setResistance === true,
350
+ device: this.getName()
351
+ });
352
+ this.emit('mode-replaced', { requestedMode, newMode: newMode.getName() });
353
+ }
308
354
  updateCapabilitiesFromFeatures(features) {
309
355
  if (features.heartrate && !this.hasCapability(IncyclistCapability.HeartRate)) {
310
356
  this.capabilities.push(IncyclistCapability.HeartRate);
@@ -347,7 +393,14 @@ export default class BleFmAdapter extends BleAdapter {
347
393
  const send = async () => {
348
394
  const res = {};
349
395
  if (update.slope !== undefined) {
350
- if (update.isHub) {
396
+ const skipSlope = !update.isHub && device.features?.setSlope === false;
397
+ if (skipSlope) {
398
+ if (!this.setSlopeSkippedLogged) {
399
+ this.setSlopeSkippedLogged = true;
400
+ this.logEvent({ message: 'setSlope skipped', reason: 'not supported', device: this.getName() });
401
+ }
402
+ }
403
+ else if (update.isHub) {
351
404
  await this.initVirtualShifting(true);
352
405
  if (this.zwiftPlay) {
353
406
  await this.zwiftPlay.setIncline(update.slope);
@@ -356,7 +409,8 @@ export default class BleFmAdapter extends BleAdapter {
356
409
  else {
357
410
  await device.setSlope(update.slope);
358
411
  }
359
- res.slope = update.slope;
412
+ if (!skipSlope)
413
+ res.slope = update.slope;
360
414
  }
361
415
  if (update.targetPower !== undefined && !update.isHub) {
362
416
  const tp = update.targetPower > 0 ? update.targetPower : 0;
@@ -364,7 +418,9 @@ export default class BleFmAdapter extends BleAdapter {
364
418
  res.targetPower = tp;
365
419
  }
366
420
  if (update.targetResistance !== undefined && !update.isHub) {
367
- await device.setTargetResistanceLevel(update.targetResistance);
421
+ const success = await device.setTargetResistanceLevel(update.targetResistance);
422
+ if (success === false)
423
+ this.getResistanceMode()?.registerFailedUpdate();
368
424
  res.targetResistance = update.targetResistance;
369
425
  }
370
426
  if (update.gearRatio !== undefined) {
@@ -165,6 +165,9 @@ export default class BleFitnessMachineDevice extends TBleSensor {
165
165
  if (res === 5) {
166
166
  this.hasControl = false;
167
167
  }
168
+ if (res !== 1) {
169
+ this.logEvent({ message: 'setTargetResistanceLevel failed', device: this.getName(), resistanceLevel, result: String(res) });
170
+ }
168
171
  return (res === 1);
169
172
  }
170
173
  async setSlope(slope) {
@@ -699,7 +702,7 @@ export default class BleFitnessMachineDevice extends TBleSensor {
699
702
  return (res === 1);
700
703
  }
701
704
  async setIndoorBikeSimulation(windSpeed, gradient, crr, cw) {
702
- if (this.features?.setPower === false)
705
+ if (this.features?.setSlope === false)
703
706
  return true;
704
707
  this.logEvent({ message: 'setIndoorBikeSimulation', device: this.getName(), windSpeed, gradient, crr, cw });
705
708
  const hasControl = await this.requestControl();
@@ -70,7 +70,7 @@ export class ZwiftPlayAdapter extends BleAdapter {
70
70
  if (this.device.getDeviceType() === 'ride-right')
71
71
  name = name + '-R';
72
72
  }
73
- const id = (settings.id ?? settings.address ?? '').replace(/[:\-]/g, '');
73
+ const id = (settings.id ?? settings.address ?? '').replace(/[:\-.]/g, '');
74
74
  const addressHash = id.length > 4 ? id.slice(-4).toUpperCase() : id.toUpperCase();
75
75
  return `${name} ${addressHash}`;
76
76
  }
@@ -1,5 +1,11 @@
1
1
  import PowerBasedCyclingModeBase from "./power-base.js";
2
2
  import { CyclingModeProperyType } from "./types.js";
3
+ const MIN_GEAR = 1;
4
+ const MAX_GEAR = 26;
5
+ const LEVELS_PER_GEAR = 4;
6
+ const DEFAULT_MAX_SLOPE = 10;
7
+ const DOWNHILL_FACTOR = 0.5;
8
+ const UPDATE_THROTTLE_MS = 1000;
3
9
  export default class FMResistanceMode extends PowerBasedCyclingModeBase {
4
10
  static config = {
5
11
  isERG: false,
@@ -7,20 +13,61 @@ export default class FMResistanceMode extends PowerBasedCyclingModeBase {
7
13
  isResistance: true,
8
14
  name: "Resistance",
9
15
  description: "Resistance levels are set by the app based on selected gear. Calculates speed based on power and slope.",
10
- properties: [
11
- { key: 'startGear', name: 'Initial Gear', description: 'Initial Gear', type: CyclingModeProperyType.Integer, default: 5, min: 1, max: 26 }
12
- ]
16
+ properties: FMResistanceMode.buildProperties(false)
13
17
  };
18
+ static buildProperties(autoDefault) {
19
+ const isAuto = (s) => (s?.autoResistance ?? autoDefault) !== false && s?.autoResistance !== 'false';
20
+ return [
21
+ { key: 'startGear', name: 'Initial Gear', description: 'Initial Gear', type: CyclingModeProperyType.Integer, default: 5, min: 1, max: 26 },
22
+ { key: 'autoResistance', name: 'Auto Resistance', description: 'Adjusts the resistance automatically to the slope of the route. Gear shifts will increase/decrease the resistance on top of that', type: CyclingModeProperyType.Boolean, default: autoDefault },
23
+ { key: 'maxSlope', name: 'Max Slope', description: 'Slope (in %) at which the maximum resistance is reached. Downhill sections reduce the resistance at half of that rate', type: CyclingModeProperyType.Integer, default: DEFAULT_MAX_SLOPE, min: 1, max: 30, condition: isAuto }
24
+ ];
25
+ }
14
26
  confirmedResistance;
15
27
  requestedResistance;
28
+ gearOffset = 0;
29
+ lastAutoSendTs = 0;
30
+ autoStats = { updatesSent: 0, updatesFailed: 0, gearChanges: 0 };
16
31
  constructor(adapter, props) {
17
32
  super(adapter, props);
18
33
  this.initLogger('FMResistanceMode');
19
34
  this.data.slope = 0;
20
35
  }
36
+ setAutoResistanceDefault(autoDefault) {
37
+ const base = this.constructor.config;
38
+ this.setConfig({ ...base, properties: FMResistanceMode.buildProperties(autoDefault) });
39
+ }
40
+ isAutoResistance() {
41
+ const value = this.getSetting('autoResistance');
42
+ return value === true || value === 'true';
43
+ }
21
44
  getBikeInitRequest() {
45
+ if (this.isAutoResistance()) {
46
+ return { targetResistance: this.calculateAutoResistance(this.data.slope ?? 0) };
47
+ }
22
48
  return { targetResistance: this.calculateTargetResistance(this.getInitialGear()) };
23
49
  }
50
+ resetSession() {
51
+ this.gearOffset = 0;
52
+ this.lastAutoSendTs = 0;
53
+ this.autoStats = { updatesSent: 0, updatesFailed: 0, gearChanges: 0 };
54
+ }
55
+ registerFailedUpdate() {
56
+ if (this.isAutoResistance())
57
+ this.autoStats.updatesFailed++;
58
+ }
59
+ logSummary() {
60
+ const stats = this.autoStats;
61
+ if (stats.updatesSent === 0)
62
+ return;
63
+ const durationSec = stats.tsStart ? Math.round((Date.now() - stats.tsStart) / 1000) : 0;
64
+ this.logEvent({
65
+ message: 'auto resistance summary',
66
+ updatesSent: stats.updatesSent, updatesFailed: stats.updatesFailed, gearChanges: stats.gearChanges,
67
+ targetMin: stats.targetMin ?? 0, targetMax: stats.targetMax ?? 0, durationSec
68
+ });
69
+ this.autoStats = { updatesSent: 0, updatesFailed: 0, gearChanges: 0 };
70
+ }
24
71
  sendBikeUpdate(incoming) {
25
72
  if (this.logger)
26
73
  this.logEvent({ message: "processing update request", request: incoming, prev: this.prevRequest, data: this.getData() });
@@ -33,8 +80,16 @@ export default class FMResistanceMode extends PowerBasedCyclingModeBase {
33
80
  return req;
34
81
  }
35
82
  this.checkSlope(request);
36
- this.checkGearDeltaSet(request, newRequest);
83
+ if (this.isAutoResistance()) {
84
+ this.checkAutoGearDeltaSet(request, newRequest);
85
+ }
86
+ else {
87
+ this.checkGearDeltaSet(request, newRequest);
88
+ }
37
89
  this.checkTargetResistanceSet(request, newRequest);
90
+ if (this.isAutoResistance()) {
91
+ this.checkAutoResistanceSet(newRequest);
92
+ }
38
93
  this.checkRefresh(request, newRequest);
39
94
  this.checkEmptyRequest(newRequest);
40
95
  this.prevRequest = JSON.parse(JSON.stringify(newRequest));
@@ -45,6 +100,9 @@ export default class FMResistanceMode extends PowerBasedCyclingModeBase {
45
100
  }
46
101
  if (newRequest.targetResistance !== undefined) {
47
102
  this.requestedResistance = newRequest.targetResistance;
103
+ if (this.isAutoResistance()) {
104
+ this.recordAutoUpdate(newRequest.targetResistance);
105
+ }
48
106
  }
49
107
  return newRequest;
50
108
  }
@@ -84,8 +142,68 @@ export default class FMResistanceMode extends PowerBasedCyclingModeBase {
84
142
  delete request.gearDelta;
85
143
  }
86
144
  }
145
+ getStartGear() {
146
+ const gear = Math.round(this.getInitialGear());
147
+ if (Number.isNaN(gear))
148
+ return MIN_GEAR;
149
+ return Math.min(Math.max(gear, MIN_GEAR), MAX_GEAR);
150
+ }
151
+ getMaxSlope() {
152
+ const maxSlope = Number(this.getSetting('maxSlope'));
153
+ return (Number.isNaN(maxSlope) || maxSlope <= 0) ? DEFAULT_MAX_SLOPE : maxSlope;
154
+ }
155
+ getGearOffset() {
156
+ const startGear = this.getStartGear();
157
+ return Math.min(Math.max(this.gearOffset, MIN_GEAR - startGear), MAX_GEAR - startGear);
158
+ }
159
+ getVirtualGear() {
160
+ return this.getStartGear() + this.getGearOffset();
161
+ }
162
+ calculateAutoResistance(slope) {
163
+ const base = this.calculateTargetResistance(this.getStartGear());
164
+ const maxSlope = this.getMaxSlope();
165
+ const s = Number.isFinite(slope) ? slope : 0;
166
+ const effective = s < 0 ? s * DOWNHILL_FACTOR : s;
167
+ const resistance = base + (100 - base) * effective / maxSlope + LEVELS_PER_GEAR * this.getGearOffset();
168
+ return Math.round(Math.min(Math.max(resistance, 0), 100));
169
+ }
170
+ checkAutoGearDeltaSet(request, newRequest) {
171
+ if (request.gearDelta === undefined)
172
+ return;
173
+ const startGear = this.getStartGear();
174
+ const prevOffset = this.getGearOffset();
175
+ const offset = Math.min(Math.max(prevOffset + request.gearDelta, MIN_GEAR - startGear), MAX_GEAR - startGear);
176
+ delete request.gearDelta;
177
+ if (offset !== prevOffset)
178
+ this.autoStats.gearChanges++;
179
+ this.gearOffset = offset;
180
+ newRequest.targetResistance = this.calculateAutoResistance(this.data.slope ?? 0);
181
+ }
182
+ checkAutoResistanceSet(newRequest) {
183
+ if (newRequest.targetResistance !== undefined)
184
+ return;
185
+ if (Date.now() - this.lastAutoSendTs < UPDATE_THROTTLE_MS)
186
+ return;
187
+ const target = this.calculateAutoResistance(this.data.slope ?? 0);
188
+ if (target !== this.requestedResistance)
189
+ newRequest.targetResistance = target;
190
+ }
191
+ recordAutoUpdate(target) {
192
+ const now = Date.now();
193
+ const stats = this.autoStats;
194
+ this.lastAutoSendTs = now;
195
+ stats.tsStart = stats.tsStart ?? now;
196
+ stats.updatesSent++;
197
+ stats.targetMin = stats.targetMin === undefined ? target : Math.min(stats.targetMin, target);
198
+ stats.targetMax = stats.targetMax === undefined ? target : Math.max(stats.targetMax, target);
199
+ }
87
200
  updateData(bikeData, log) {
88
201
  const data = super.updateData(bikeData, log);
202
+ if (this.isAutoResistance()) {
203
+ data.gear = this.getVirtualGear();
204
+ data.gearStr = `${data.gear}`;
205
+ return data;
206
+ }
89
207
  if (data.resistance !== undefined) {
90
208
  data.gear = this.getGear(data.resistance);
91
209
  data.gearStr = `${data.gear}`;
@@ -407,6 +407,10 @@ export default class KettlerRacerAdapter extends SerialIncyclistDevice {
407
407
  }
408
408
  catch (err) {
409
409
  this.requestBusy = false;
410
+ if (err.message === 'connection error') {
411
+ this.logEvent({ message: 'send failed', reason: 'not connected' });
412
+ return;
413
+ }
410
414
  this.logEvent({ message: 'error', fn: 'sendRequest()', error: err.message || err });
411
415
  return;
412
416
  }
@@ -58,6 +58,7 @@ export default class IncyclistDevice<P extends DeviceProperties> extends EventEm
58
58
  setCyclingMode(mode: string | ICyclingMode, settings?: any, sendInitCommands?: boolean): void;
59
59
  createMode(ModeClass: typeof CyclingMode): ICyclingMode;
60
60
  protected createOrGetMode(mode: string | ICyclingMode, useCurrent?: boolean): ICyclingMode;
61
+ protected isModeSupported(_modeName: string): boolean;
61
62
  getSupportedCyclingModes(): Array<typeof CyclingMode>;
62
63
  getCyclingMode(): ICyclingMode;
63
64
  getDefaultCyclingMode(): ICyclingMode;
@@ -6,6 +6,7 @@ import { BleDeviceProperties, BleDeviceSettings, BleStartProperties, IBlePeriphe
6
6
  import { IAdapter, IncyclistAdapterData, IncyclistBikeData, ITrainer } from '../../types/index.js';
7
7
  import { LegacyProfile } from '../../antv2/types.js';
8
8
  import { BleZwiftPlaySensor } from '../zwift/play/index.js';
9
+ import FMResistanceMode from '../../modes/fm-resistance.js';
9
10
  import { Sport } from '../../types/sport.js';
10
11
  export default class BleFmAdapter extends BleAdapter<IndoorBikeData, BleFitnessMachineDevice> implements ITrainer {
11
12
  protected static INCYCLIST_PROFILE_NAME: LegacyProfile;
@@ -16,6 +17,7 @@ export default class BleFmAdapter extends BleAdapter<IndoorBikeData, BleFitnessM
16
17
  protected promiseSendUpdate: Promise<UpdateRequest | void> | undefined;
17
18
  protected zwiftPlay: BleZwiftPlaySensor | undefined;
18
19
  protected isHubInitialized: boolean;
20
+ protected setSlopeSkippedLogged: boolean;
19
21
  constructor(settings: BleDeviceSettings, props?: BleDeviceProperties);
20
22
  getSupportedSports(): Array<Sport>;
21
23
  updateSensor(peripheral: IBlePeripheral): void;
@@ -36,7 +38,11 @@ export default class BleFmAdapter extends BleAdapter<IndoorBikeData, BleFitnessM
36
38
  protected establishControl(): Promise<boolean>;
37
39
  protected sendInitialRequest(): Promise<void>;
38
40
  protected updateCyclingModeConfig(): void;
41
+ protected getResistanceMode(): FMResistanceMode | undefined;
42
+ stop(): Promise<boolean>;
39
43
  protected checkCapabilities(): Promise<void>;
44
+ protected isModeSupported(modeName: string): boolean;
45
+ protected checkCyclingModeSupported(): void;
40
46
  protected updateCapabilitiesFromFeatures(features: IndoorBikeFeatures): void;
41
47
  sendUpdate(request: UpdateRequest, enforced?: boolean): Promise<UpdateRequest | void>;
42
48
  sendInitCommands(): Promise<boolean>;
@@ -1,33 +1,43 @@
1
1
  import { IncyclistDeviceAdapter } from "../base/adpater.js";
2
2
  import { IncyclistBikeData } from "../types/index.js";
3
3
  import PowerBasedCyclingModeBase from "./power-base.js";
4
- import ICyclingMode, { CyclingModeProperyType, UpdateRequest } from "./types.js";
4
+ import ICyclingMode, { CyclingModeConfig, UpdateRequest } from "./types.js";
5
+ type AutoResistanceStats = {
6
+ updatesSent: number;
7
+ updatesFailed: number;
8
+ gearChanges: number;
9
+ targetMin?: number;
10
+ targetMax?: number;
11
+ tsStart?: number;
12
+ };
5
13
  export default class FMResistanceMode extends PowerBasedCyclingModeBase implements ICyclingMode {
6
- protected static config: {
7
- isERG: boolean;
8
- isSIM: boolean;
9
- isResistance: boolean;
10
- name: string;
11
- description: string;
12
- properties: {
13
- key: string;
14
- name: string;
15
- description: string;
16
- type: CyclingModeProperyType;
17
- default: number;
18
- min: number;
19
- max: number;
20
- }[];
21
- };
14
+ protected static config: CyclingModeConfig;
15
+ protected static buildProperties(autoDefault: boolean): CyclingModeConfig['properties'];
22
16
  protected confirmedResistance?: number;
23
17
  protected requestedResistance?: number;
18
+ protected gearOffset: number;
19
+ protected lastAutoSendTs: number;
20
+ protected autoStats: AutoResistanceStats;
24
21
  constructor(adapter: IncyclistDeviceAdapter, props?: any);
22
+ setAutoResistanceDefault(autoDefault: boolean): void;
23
+ isAutoResistance(): boolean;
25
24
  getBikeInitRequest(): UpdateRequest;
25
+ resetSession(): void;
26
+ registerFailedUpdate(): void;
27
+ logSummary(): void;
26
28
  sendBikeUpdate(incoming: UpdateRequest): UpdateRequest;
27
29
  checkForResetOrEmpty(request: UpdateRequest): UpdateRequest | undefined;
28
30
  protected checkSlope(request: UpdateRequest): void;
29
31
  protected checkTargetResistanceSet(request: UpdateRequest, newRequest: UpdateRequest): void;
30
32
  protected checkGearDeltaSet(request: UpdateRequest, newRequest: UpdateRequest): void;
33
+ protected getStartGear(): number;
34
+ protected getMaxSlope(): number;
35
+ protected getGearOffset(): number;
36
+ protected getVirtualGear(): number;
37
+ protected calculateAutoResistance(slope: number): number;
38
+ protected checkAutoGearDeltaSet(request: UpdateRequest, newRequest: UpdateRequest): void;
39
+ protected checkAutoResistanceSet(newRequest: UpdateRequest): void;
40
+ protected recordAutoUpdate(target: number): void;
31
41
  updateData(bikeData: IncyclistBikeData, log?: boolean): IncyclistBikeData;
32
42
  confirmed(request: UpdateRequest): void;
33
43
  protected getCurrentResistanceTarget(): number;
@@ -37,3 +47,4 @@ export default class FMResistanceMode extends PowerBasedCyclingModeBase implemen
37
47
  protected getGear(resistance: number): number;
38
48
  protected calculateTargetResistance(gear: number): number;
39
49
  }
50
+ export {};
@@ -13,6 +13,13 @@ export type ControllerConfig = {
13
13
  export type UpdateRequestInput = UpdateRequest & {
14
14
  enforced?: boolean;
15
15
  };
16
+ export type ModeReplacedInfo = {
17
+ requestedMode: string;
18
+ newMode: string;
19
+ };
20
+ export interface AdapterEvents {
21
+ 'mode-replaced': (info: ModeReplacedInfo) => void;
22
+ }
16
23
  export interface ITrainer {
17
24
  setCyclingMode(mode: ICyclingMode | string, settings?: any, sendInitCommands?: boolean): void;
18
25
  getSupportedCyclingModes(): Array<typeof CyclingMode>;
@@ -36,6 +43,10 @@ export interface ISensor {
36
43
  update(): void;
37
44
  }
38
45
  export interface IAdapter extends EventEmitter, ITrainer, ISensor {
46
+ on<E extends keyof AdapterEvents>(event: E, listener: AdapterEvents[E]): this;
47
+ on(event: string | symbol, listener: (...args: any[]) => void): this;
48
+ emit<E extends keyof AdapterEvents>(event: E, ...args: Parameters<AdapterEvents[E]>): boolean;
49
+ emit(event: string | symbol, ...args: any[]): boolean;
39
50
  getName(): string;
40
51
  getID(): string;
41
52
  getUniqueName(): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "incyclist-devices",
3
- "version": "3.0.45",
3
+ "version": "3.0.47",
4
4
  "scripts": {
5
5
  "lint": "eslint . --ext .ts",
6
6
  "build": "npm run build:esm && npm run build:cjs",