incyclist-services 1.9.21 → 1.9.23

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 (65) hide show
  1. package/lib/cjs/activities/base/repo/db.js +8 -2
  2. package/lib/cjs/activities/base/utils/helpers.js +26 -11
  3. package/lib/cjs/activities/upload/index.js +1 -0
  4. package/lib/cjs/activities/upload/komoot.js +166 -0
  5. package/lib/cjs/apps/base/api/komoot/api.js +35 -0
  6. package/lib/cjs/apps/komoot/KomootAppConnection.js +6 -4
  7. package/lib/cjs/apps/service.js +1 -1
  8. package/lib/cjs/devices/page/base/guidance/guidance.js +277 -16
  9. package/lib/cjs/devices/page/base/service.js +245 -16
  10. package/lib/cjs/devices/page/desktop/matrix.js +2 -1
  11. package/lib/cjs/devices/page/desktop/service.js +4 -11
  12. package/lib/cjs/devices/page/mobile/service.js +1 -0
  13. package/lib/cjs/devices/pairing/conflict.js +47 -0
  14. package/lib/cjs/devices/pairing/guidance.js +40 -4
  15. package/lib/cjs/devices/pairing/helper.js +3 -1
  16. package/lib/cjs/devices/pairing/index.js +1 -0
  17. package/lib/cjs/devices/pairing/service.js +228 -35
  18. package/lib/cjs/devices/pairing/status.js +1 -0
  19. package/lib/cjs/devices/ride/service.js +20 -4
  20. package/lib/cjs/devices/ride/timeouts.js +9 -0
  21. package/lib/cjs/ride/display/service.js +2 -2
  22. package/lib/cjs/routes/base/api/api.js +1 -0
  23. package/lib/esm/activities/base/repo/db.js +8 -2
  24. package/lib/esm/activities/base/utils/helpers.js +24 -10
  25. package/lib/esm/activities/upload/index.js +1 -0
  26. package/lib/esm/activities/upload/komoot.js +163 -0
  27. package/lib/esm/apps/base/api/komoot/api.js +35 -0
  28. package/lib/esm/apps/komoot/KomootAppConnection.js +6 -4
  29. package/lib/esm/apps/service.js +1 -1
  30. package/lib/esm/devices/page/base/guidance/guidance.js +276 -15
  31. package/lib/esm/devices/page/base/service.js +246 -17
  32. package/lib/esm/devices/page/desktop/matrix.js +2 -1
  33. package/lib/esm/devices/page/desktop/service.js +4 -11
  34. package/lib/esm/devices/page/mobile/service.js +1 -0
  35. package/lib/esm/devices/pairing/conflict.js +9 -4
  36. package/lib/esm/devices/pairing/guidance.js +40 -4
  37. package/lib/esm/devices/pairing/helper.js +1 -0
  38. package/lib/esm/devices/pairing/index.js +1 -0
  39. package/lib/esm/devices/pairing/service.js +228 -35
  40. package/lib/esm/devices/pairing/status.js +1 -0
  41. package/lib/esm/devices/ride/service.js +20 -4
  42. package/lib/esm/ride/display/service.js +2 -2
  43. package/lib/esm/routes/base/api/api.js +1 -0
  44. package/lib/types/activities/base/model/index.d.ts +1 -5
  45. package/lib/types/activities/base/repo/db.d.ts +2 -1
  46. package/lib/types/activities/base/utils/helpers.d.ts +2 -1
  47. package/lib/types/activities/upload/index.d.ts +1 -0
  48. package/lib/types/activities/upload/komoot.d.ts +20 -0
  49. package/lib/types/apps/base/api/komoot/api.d.ts +2 -1
  50. package/lib/types/apps/base/api/komoot/types.d.ts +1 -0
  51. package/lib/types/apps/komoot/KomootAppConnection.d.ts +1 -1
  52. package/lib/types/devices/page/base/guidance/guidance.d.ts +49 -2
  53. package/lib/types/devices/page/base/guidance/types.d.ts +20 -2
  54. package/lib/types/devices/page/base/service.d.ts +36 -2
  55. package/lib/types/devices/page/base/types.d.ts +31 -0
  56. package/lib/types/devices/page/desktop/service.d.ts +1 -2
  57. package/lib/types/devices/pairing/conflict.d.ts +4 -1
  58. package/lib/types/devices/pairing/guidance.d.ts +9 -4
  59. package/lib/types/devices/pairing/helper.d.ts +1 -0
  60. package/lib/types/devices/pairing/index.d.ts +1 -0
  61. package/lib/types/devices/pairing/model.d.ts +1 -0
  62. package/lib/types/devices/pairing/service.d.ts +43 -4
  63. package/lib/types/devices/pairing/status.d.ts +2 -1
  64. package/lib/types/devices/ride/service.d.ts +1 -0
  65. package/package.json +2 -2
@@ -0,0 +1,163 @@
1
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
2
+ var useValue = arguments.length > 2;
3
+ for (var i = 0; i < initializers.length; i++) {
4
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
5
+ }
6
+ return useValue ? value : void 0;
7
+ };
8
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
9
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
10
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
11
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
12
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
13
+ var _, done = false;
14
+ for (var i = decorators.length - 1; i >= 0; i--) {
15
+ var context = {};
16
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
17
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
18
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
19
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
20
+ if (kind === "accessor") {
21
+ if (result === void 0) continue;
22
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
23
+ if (_ = accept(result.get)) descriptor.get = _;
24
+ if (_ = accept(result.set)) descriptor.set = _;
25
+ if (_ = accept(result.init)) initializers.unshift(_);
26
+ }
27
+ else if (_ = accept(result)) {
28
+ if (kind === "field") initializers.unshift(_);
29
+ else descriptor[key] = _;
30
+ }
31
+ }
32
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
33
+ done = true;
34
+ };
35
+ import { IncyclistService } from "../../base/service";
36
+ import { Singleton } from "../../base/types";
37
+ import { Injectable } from "../../base/decorators/Injection";
38
+ import { ActivityUploadFactory } from "./factory";
39
+ import { KomootAppConnection } from "../../apps/komoot";
40
+ import { getBindings } from "../../api";
41
+ let KomootUpload = (() => {
42
+ let _classDecorators = [Singleton];
43
+ let _classDescriptor;
44
+ let _classExtraInitializers = [];
45
+ let _classThis;
46
+ let _classSuper = IncyclistService;
47
+ let _instanceExtraInitializers = [];
48
+ let _getKomootAppConnection_decorators;
49
+ var KomootUpload = class extends _classSuper {
50
+ static { _classThis = this; }
51
+ static {
52
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
53
+ _getKomootAppConnection_decorators = [Injectable];
54
+ __esDecorate(this, null, _getKomootAppConnection_decorators, { kind: "method", name: "getKomootAppConnection", static: false, private: false, access: { has: obj => "getKomootAppConnection" in obj, get: obj => obj.getKomootAppConnection }, metadata: _metadata }, null, _instanceExtraInitializers);
55
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
56
+ KomootUpload = _classThis = _classDescriptor.value;
57
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
58
+ __runInitializers(_classThis, _classExtraInitializers);
59
+ }
60
+ isInitialized = __runInitializers(this, _instanceExtraInitializers);
61
+ connection = new KomootAppConnection();
62
+ constructor() {
63
+ super('KomootUpload');
64
+ this.isInitialized = false;
65
+ this.init();
66
+ }
67
+ init() {
68
+ if (this.isInitialized)
69
+ return true;
70
+ this.isInitialized = this.getKomootAppConnection().init();
71
+ return this.isInitialized;
72
+ }
73
+ isConnected() {
74
+ return this.getKomootAppConnection().isConnected();
75
+ }
76
+ async upload(activity, format = 'FIT') {
77
+ try {
78
+ const ok = this.ensureInitialized();
79
+ if (!ok) {
80
+ this.logEvent({ message: 'Komoot Upload skipped', reason: 'not initialized' });
81
+ return false;
82
+ }
83
+ if (!this.isConnected())
84
+ return false;
85
+ const lcFormat = format.toLowerCase();
86
+ const ucFormat = format.toUpperCase();
87
+ const uploadFormat = this.getKomootFormat(lcFormat);
88
+ const sport = 'racebike';
89
+ this.logEvent({ message: 'Komoot Upload', requestedFormat: ucFormat, uploadFormat });
90
+ if (!activity.links)
91
+ activity.links = {};
92
+ const fileName = activity[`${uploadFormat}FileName`];
93
+ if (!fileName) {
94
+ throw new Error(`data not exported to ${uploadFormat.toUpperCase()}`);
95
+ }
96
+ const data = await this.readFile(fileName);
97
+ if (!data) {
98
+ throw new Error(`file could not be read: ${fileName}`);
99
+ }
100
+ const res = await this.getApi().uploadTour(Buffer.from(data), uploadFormat, sport, activity.title);
101
+ this.logEvent({ message: 'Komoot Upload success', activityId: res.id });
102
+ activity.links.komoot = {
103
+ activity_id: res.id.toString(),
104
+ url: this.getUrl(res.id.toString())
105
+ };
106
+ return true;
107
+ }
108
+ catch (err) {
109
+ this.logEvent({ message: 'Komoot Upload failure', error: err.message });
110
+ activity.links.komoot = {
111
+ error: err.message
112
+ };
113
+ return false;
114
+ }
115
+ }
116
+ getUrl(activityId) {
117
+ return `https://www.komoot.com/tour/${activityId}`;
118
+ }
119
+ getKomootFormat(format) {
120
+ switch (format.toLowerCase()) {
121
+ case 'tcx':
122
+ return 'fit';
123
+ case 'fit':
124
+ return 'fit';
125
+ case 'gpx':
126
+ return 'gpx';
127
+ default:
128
+ return null;
129
+ }
130
+ }
131
+ ensureInitialized() {
132
+ if (!this.isInitialized)
133
+ this.init();
134
+ return this.isInitialized;
135
+ }
136
+ async readFile(fileName) {
137
+ try {
138
+ const fs = this.getFS();
139
+ const exists = await fs.existsFile(fileName);
140
+ if (!exists)
141
+ return null;
142
+ const content = await fs.readFile(fileName);
143
+ return content || null;
144
+ }
145
+ catch (err) {
146
+ this.logError(err, 'readFile');
147
+ }
148
+ }
149
+ getKomootAppConnection() {
150
+ return this.connection;
151
+ }
152
+ getApi() {
153
+ return this.getKomootAppConnection().getApi();
154
+ }
155
+ getFS() {
156
+ return getBindings().fs;
157
+ }
158
+ };
159
+ return KomootUpload = _classThis;
160
+ })();
161
+ export { KomootUpload };
162
+ const factory = new ActivityUploadFactory();
163
+ factory.add('komoot', new KomootUpload());
@@ -107,6 +107,41 @@ export class KomootApi extends AppApiBase {
107
107
  throw (err);
108
108
  }
109
109
  }
110
+ async uploadTour(data, format, sport, name) {
111
+ const tsStart = Date.now();
112
+ try {
113
+ const auth = this.getBasicAuthCredentials();
114
+ if (!this.userid) {
115
+ this.logger.logEvent({ message: 'uploadTour failed', reason: 'invalid credentials' });
116
+ throw new Error('invalid credentials');
117
+ }
118
+ const contentType = format === 'gpx' ? 'application/gpx+xml' : 'application/octet-stream';
119
+ const params = new URLSearchParams({ data_type: format, sport, name });
120
+ const response = await this.getApi().request({
121
+ method: 'post',
122
+ url: `${this.getBaseUrl()}/tours/?${params.toString()}`,
123
+ auth,
124
+ headers: { 'Content-Type': contentType },
125
+ data,
126
+ validateStatus: () => true
127
+ });
128
+ if (response.status >= 400) {
129
+ this.logger.logEvent({
130
+ message: 'uploadTour failed',
131
+ status: response.status,
132
+ body: JSON.stringify(response.data),
133
+ duration: Date.now() - tsStart
134
+ });
135
+ throw new Error(`HTTP ${response.status}: ${JSON.stringify(response.data)}`);
136
+ }
137
+ this.logger.logEvent({ message: 'uploadTour success', id: response.data?.id, duration: Date.now() - tsStart });
138
+ return response.data;
139
+ }
140
+ catch (err) {
141
+ this.logger.logEvent({ message: 'uploadTour failed', reason: err.message, duration: Date.now() - tsStart });
142
+ throw err;
143
+ }
144
+ }
110
145
  applyFilter(tours, filters) {
111
146
  if (!filters)
112
147
  return tours;
@@ -62,7 +62,6 @@ let KomootAppConnection = (() => {
62
62
  constructor() {
63
63
  super('KomootAppConnection', 'komoot');
64
64
  this.api = new KomootApi();
65
- this.iniAuth();
66
65
  }
67
66
  async connect(credentials) {
68
67
  this.ensureInitialized();
@@ -107,9 +106,9 @@ let KomootAppConnection = (() => {
107
106
  getApi() {
108
107
  return this.api;
109
108
  }
110
- iniAuth() {
109
+ initAuth() {
111
110
  const api = this.getApi();
112
- if (this.credentials) {
111
+ if (this.credentials && api) {
113
112
  api.setAuth(this.credentials);
114
113
  return true;
115
114
  }
@@ -139,7 +138,10 @@ let KomootAppConnection = (() => {
139
138
  isInitialized = false;
140
139
  }
141
140
  this.setupEventListeners();
142
- this.credentials = { ...credentials };
141
+ if (isInitialized) {
142
+ this.credentials = { ...credentials };
143
+ this.initAuth();
144
+ }
143
145
  return isInitialized;
144
146
  }
145
147
  getAuthConfig() {
@@ -63,7 +63,7 @@ let AppsService = (() => {
63
63
  __runInitializers(_classThis, _classExtraInitializers);
64
64
  }
65
65
  services = (__runInitializers(this, _instanceExtraInitializers), {
66
- ActivityUpload: ['strava', 'intervals'],
66
+ ActivityUpload: ['strava', 'intervals', 'komoot'],
67
67
  WorkoutUpload: [],
68
68
  WorkoutDownload: ['intervals'],
69
69
  ActivityDownload: [],
@@ -10,6 +10,12 @@ export const HELPER_REASON_EVENT = 'pairing helper reason selected';
10
10
  export const HELPER_ACTION_EVENT = 'pairing helper action';
11
11
  export const HELPER_RESOLVED_EVENT = 'pairing helper resolved';
12
12
  export const HELPER_CLOSED_EVENT = 'pairing helper closed';
13
+ export const FALLBACK_CHOSEN_EVENT = 'pairing fallback chosen';
14
+ export const FALLBACK_CANCELLED_EVENT = 'pairing fallback cancelled';
15
+ export const RIDER_RETRY_EVENT = 'pairing trainer retry';
16
+ export const RIDER_RETRY_ENDED_EVENT = 'pairing trainer retry ended';
17
+ export const FALLBACK_REVERTED_DISPLAY_MS = 3000;
18
+ const NOT_AVAILABLE = { reason: 'not-available', scope: 'until-next-pairing' };
13
19
  export const HELPER_THRESHOLD_MS = {
14
20
  mobile: 30000,
15
21
  desktop: 45000,
@@ -54,6 +60,19 @@ export class PairingGuidance {
54
60
  attemptElapsedMs = 0;
55
61
  attemptResumedAt;
56
62
  attemptTimer;
63
+ unavailableSince;
64
+ trainerRetry;
65
+ retryIndex = 0;
66
+ retryCase;
67
+ retrySawConnecting = false;
68
+ retryStartFields;
69
+ retryTimeoutMs;
70
+ retryElapsedMs = 0;
71
+ retryResumedAt;
72
+ retryTimer;
73
+ fallback;
74
+ fallbackReverted = false;
75
+ fallbackRevertedTimer;
57
76
  visitId;
58
77
  openedAt = 0;
59
78
  partialOutageSince;
@@ -97,6 +116,8 @@ export class PairingGuidance {
97
116
  closeVisit() {
98
117
  if (this.visitOpen && this.helperPhase === 'open')
99
118
  this.logHelperClosed('page_left');
119
+ if (this.visitOpen && this.trainerRetry === 'running')
120
+ this.endRiderRetry('left_page');
100
121
  this.reset();
101
122
  }
102
123
  pauseVisit() {
@@ -105,6 +126,8 @@ export class PairingGuidance {
105
126
  this.paused = true;
106
127
  this.stopAttemptClock();
107
128
  this.clearAttemptTimer();
129
+ this.stopRetryClock();
130
+ this.clearRetryTimer();
108
131
  this.stopHelperClock();
109
132
  this.clearHelperTimer();
110
133
  if (this.helperPhase === 'resolved')
@@ -118,40 +141,130 @@ export class PairingGuidance {
118
141
  if (this.attemptTimeoutMs !== undefined)
119
142
  this.attemptResumedAt = Date.now();
120
143
  this.armAttemptTimer();
144
+ if (this.retryTimeoutMs !== undefined)
145
+ this.retryResumedAt = Date.now();
146
+ this.armRetryTimer();
121
147
  this.helperResumedAt = Date.now();
122
148
  this.armHelperTimer();
123
149
  }
124
150
  onPairingState(state) {
125
151
  if (!this.visitOpen || this.paused)
126
152
  return;
127
- const control = state?.capabilities?.find(c => c.capability === IncyclistCapability.Control);
128
- this.trainerConfigured = isCapabilityActive(control);
129
- if (!this.trainerConfigured) {
130
- this.endTrainer();
131
- return;
132
- }
133
- if (this.phase === undefined || control.selected !== this.trainerUdid) {
134
- this.startTrainer(control);
135
- return;
136
- }
137
- this.trainerInterface = control.interface ?? this.trainerInterface;
138
- this.onTrainerConnectState(control.connectState);
153
+ const previousConnectState = this.lastConnectState;
154
+ this.followTrainer(state);
155
+ this.followRiderRetry(previousConnectState);
139
156
  }
140
157
  onTrainerUnavailable() {
141
158
  if (this.visitOpen && this.phase === 'connecting')
142
159
  this.moveTo('unavailable', 'rider');
143
160
  }
161
+ getResistanceUnselectAction() {
162
+ const { trainerPhase } = this.getState();
163
+ const waitingForTrainer = trainerPhase === 'connecting' || trainerPhase === 'unavailable';
164
+ return this.visitOpen && !this.fallback && waitingForTrainer ? 'open-helper' : 'unselect';
165
+ }
166
+ openHelperForUnavailableTrainer(trigger) {
167
+ if (!this.visitOpen)
168
+ return;
169
+ this.onTrainerUnavailable();
170
+ if (this.helperPhase !== 'open')
171
+ this.showHelper(trigger);
172
+ this.preselectReason('trainer_unavailable');
173
+ }
144
174
  getState() {
145
- const trainerPhase = this.trainerConfigured ? this.phase : undefined;
175
+ const trainerPhase = this.trainerConfigured || this.fallback ? this.phase : undefined;
146
176
  const pairingCase = trainerPhase ? CASE_BY_PHASE[trainerPhase] : 'no-trainer';
147
- return { trainerConfigured: this.trainerConfigured, trainerPhase, pairingCase };
177
+ const state = { trainerConfigured: this.trainerConfigured, trainerPhase, pairingCase };
178
+ if (this.trainerRetry)
179
+ state.trainerRetry = this.trainerRetry;
180
+ if (this.fallback)
181
+ state.fallback = { capability: this.fallback.capability };
182
+ return state;
183
+ }
184
+ getFallbackCandidate() {
185
+ if (!this.visitOpen || this.fallback || this.getState().trainerPhase !== 'unavailable')
186
+ return undefined;
187
+ return this.separateSensor;
188
+ }
189
+ chooseFallback() {
190
+ const capability = this.getFallbackCandidate();
191
+ const configuration = this.deps.configuration?.();
192
+ const trainerUdid = this.trainerUdid;
193
+ if (!capability || !configuration || !trainerUdid)
194
+ return false;
195
+ const now = Date.now();
196
+ this.fallback = { capability, trainerUdid, since: now };
197
+ try {
198
+ configuration.excludeDevice(trainerUdid, NOT_AVAILABLE);
199
+ }
200
+ catch {
201
+ delete this.fallback;
202
+ return false;
203
+ }
204
+ this.closeHelperForFallback(capability);
205
+ this.safeLog(FALLBACK_CHOSEN_EVENT, { capability, msSinceOpen: now - this.openedAt });
206
+ return true;
207
+ }
208
+ cancelFallback() {
209
+ const fallback = this.fallback;
210
+ const configuration = this.deps.configuration?.();
211
+ if (!this.visitOpen || !fallback || !configuration)
212
+ return false;
213
+ delete this.fallback;
214
+ this.trainerConfigured = true;
215
+ const excluded = configuration.getExclusions()
216
+ .filter(e => e.reason === NOT_AVAILABLE.reason && e.udid === fallback.trainerUdid);
217
+ const isControl = (e) => Number(e.capability === IncyclistCapability.Control);
218
+ excluded.sort((a, b) => isControl(b) - isControl(a));
219
+ excluded.forEach(e => { configuration.includeCapability(e.capability); });
220
+ const now = Date.now();
221
+ this.safeLog(FALLBACK_CANCELLED_EVENT, { capability: fallback.capability, msSinceOpen: now - this.openedAt, msSinceFallback: now - fallback.since });
222
+ return true;
223
+ }
224
+ onFallbackReverted(udid) {
225
+ const trainerUdid = this.fallback?.trainerUdid ?? this.trainerUdid;
226
+ if (!this.visitOpen || udid !== trainerUdid)
227
+ return;
228
+ delete this.fallback;
229
+ this.fallbackReverted = true;
230
+ this.clearFallbackRevertedTimer();
231
+ this.fallbackRevertedTimer = setTimeout(() => { this.onFallbackRevertedShown(); }, FALLBACK_REVERTED_DISPLAY_MS);
232
+ }
233
+ startRiderRetry({ trigger }) {
234
+ if (!this.visitOpen || this.paused || this.fallback || this.trainerRetry === 'running')
235
+ return false;
236
+ const { pairingCase, trainerPhase } = this.getState();
237
+ if (trainerPhase !== 'unavailable')
238
+ return false;
239
+ this.retryIndex++;
240
+ this.trainerRetry = 'running';
241
+ this.retryCase = pairingCase;
242
+ this.retrySawConnecting = false;
243
+ this.retryStartFields = this.getRiderRetryStartFields(trigger);
244
+ this.retryTimeoutMs = this.getAttemptTimeoutMs();
245
+ this.retryElapsedMs = 0;
246
+ this.retryResumedAt = Date.now();
247
+ this.armRetryTimer();
248
+ return true;
249
+ }
250
+ logRiderRetry(retryCapabilities) {
251
+ if (!this.retryStartFields)
252
+ return;
253
+ const fields = { retryCapabilities: retryCapabilities.join(','), ...this.retryStartFields };
254
+ delete this.retryStartFields;
255
+ this.safeLog(RIDER_RETRY_EVENT, fields);
148
256
  }
149
257
  getStatus(src) {
150
258
  const hint = this.visitOpen && !this.paused ? getPartialOutageHint(src) : undefined;
151
259
  this.trackPartialOutage(hint);
260
+ const { trainerPhase, trainerRetry } = this.getState();
152
261
  const status = getPairingStatusDisplay({
153
262
  ...src,
154
- trainerPhase: this.getState().trainerPhase,
263
+ trainerPhase,
264
+ trainerRetry,
265
+ fallbackActive: this.fallback !== undefined,
266
+ fallbackCapability: this.fallback?.capability,
267
+ fallbackReverted: this.fallbackReverted,
155
268
  partialOutageSince: this.partialOutageSince,
156
269
  helperThresholdReached: this.visitOpen && this.thresholdReached,
157
270
  now: Date.now(),
@@ -172,6 +285,8 @@ export class PairingGuidance {
172
285
  partialOutageShown: this.partialOutageShown !== undefined,
173
286
  switchedOffRequired: this.lastStatusId === 'S8',
174
287
  helperShown: this.helperShown,
288
+ fallbackActive: this.fallback !== undefined,
289
+ trainerRetries: this.retryIndex,
175
290
  };
176
291
  if (trainerPhase)
177
292
  fields.trainerPhase = trainerPhase;
@@ -193,6 +308,7 @@ export class PairingGuidance {
193
308
  reasons,
194
309
  selectedReason,
195
310
  separateSensor: trainerPhase ? this.separateSensor : undefined,
311
+ fallbackCandidate: this.getFallbackCandidate(),
196
312
  continueTarget: this.getContinueWithoutDeviceAction().target,
197
313
  platform: this.platform,
198
314
  forRide: this.forRide,
@@ -226,6 +342,12 @@ export class PairingGuidance {
226
342
  interfaceStates: this.interfaceStates,
227
343
  }));
228
344
  }
345
+ preselectReason(reason) {
346
+ if (!this.getHelper().reasons.includes(reason))
347
+ return;
348
+ this.selectedReason = reason;
349
+ this.lastReason = reason;
350
+ }
229
351
  setDeviceListOpen(open) {
230
352
  this.deviceListOpen = open;
231
353
  }
@@ -424,8 +546,134 @@ export class PairingGuidance {
424
546
  catch {
425
547
  }
426
548
  }
549
+ followTrainer(state) {
550
+ const control = state?.capabilities?.find(c => c.capability === IncyclistCapability.Control);
551
+ this.trainerConfigured = isCapabilityActive(control);
552
+ if (this.fallback && !this.isOnFallback(control))
553
+ delete this.fallback;
554
+ if (!this.trainerConfigured) {
555
+ if (!this.fallback)
556
+ this.endTrainer();
557
+ return;
558
+ }
559
+ if (this.phase === undefined || control.selected !== this.trainerUdid) {
560
+ this.startTrainer(control);
561
+ return;
562
+ }
563
+ this.trainerInterface = control.interface ?? this.trainerInterface;
564
+ this.onTrainerConnectState(control.connectState);
565
+ }
566
+ isOnFallback(control) {
567
+ return control?.selected === this.fallback?.trainerUdid && control?.excluded?.reason === NOT_AVAILABLE.reason && !control?.disabled;
568
+ }
569
+ closeHelperForFallback(capability) {
570
+ if (this.helperPhase !== 'open') {
571
+ this.hideHelper();
572
+ return;
573
+ }
574
+ const fields = { action: 'fallback_without_trainer' };
575
+ if (this.selectedReason)
576
+ fields.reason = this.selectedReason;
577
+ fields.fallbackCapability = capability;
578
+ this.safeLog(HELPER_ACTION_EVENT, this.getHelperEventFields(fields));
579
+ this.logHelperClosed('fallback');
580
+ this.hideHelper();
581
+ }
582
+ onFallbackRevertedShown() {
583
+ delete this.fallbackRevertedTimer;
584
+ try {
585
+ this.fallbackReverted = false;
586
+ this.deps.onChange();
587
+ }
588
+ catch {
589
+ }
590
+ }
591
+ clearFallbackRevertedTimer() {
592
+ if (this.fallbackRevertedTimer)
593
+ clearTimeout(this.fallbackRevertedTimer);
594
+ delete this.fallbackRevertedTimer;
595
+ }
596
+ followRiderRetry(previousConnectState) {
597
+ if (this.trainerRetry !== 'running')
598
+ return;
599
+ if (this.phase === 'connected') {
600
+ this.endRiderRetry('connected');
601
+ return;
602
+ }
603
+ const connectState = this.lastConnectState;
604
+ if (connectState === 'connecting' && previousConnectState !== 'connecting')
605
+ this.retrySawConnecting = true;
606
+ else if (connectState === 'failed' && previousConnectState !== 'failed' && this.retrySawConnecting)
607
+ this.endRiderRetry('failed');
608
+ }
609
+ endRiderRetry(retryResult) {
610
+ const durationMs = this.getRetryElapsedMs();
611
+ const lasting = retryResult === 'failed' || retryResult === 'timeout';
612
+ this.clearRiderRetry();
613
+ if (lasting)
614
+ this.trainerRetry = 'failed';
615
+ this.safeLog(RIDER_RETRY_ENDED_EVENT, {
616
+ retryResult,
617
+ durationMs,
618
+ retryIndex: this.retryIndex,
619
+ pairingCase: this.retryCase,
620
+ platform: this.platform,
621
+ });
622
+ }
623
+ clearRiderRetry() {
624
+ this.clearRetryTimer();
625
+ delete this.trainerRetry;
626
+ delete this.retryTimeoutMs;
627
+ delete this.retryResumedAt;
628
+ delete this.retryStartFields;
629
+ this.retryElapsedMs = 0;
630
+ this.retrySawConnecting = false;
631
+ }
632
+ getRiderRetryStartFields(trigger) {
633
+ const fields = { trigger, retryIndex: this.retryIndex };
634
+ if (this.unavailableSince !== undefined)
635
+ fields.msSinceUnavailable = Date.now() - this.unavailableSince;
636
+ fields.separateDeviceConnected = this.separateSensor !== undefined;
637
+ fields.helperOpen = this.helperPhase === 'open';
638
+ fields.pairingCase = this.retryCase;
639
+ fields.platform = this.platform;
640
+ return fields;
641
+ }
642
+ getRetryElapsedMs() {
643
+ const running = this.retryResumedAt === undefined ? 0 : Date.now() - this.retryResumedAt;
644
+ return this.retryElapsedMs + running;
645
+ }
646
+ stopRetryClock() {
647
+ this.retryElapsedMs = this.getRetryElapsedMs();
648
+ delete this.retryResumedAt;
649
+ }
650
+ armRetryTimer() {
651
+ this.clearRetryTimer();
652
+ if (this.paused || this.trainerRetry !== 'running' || this.retryTimeoutMs === undefined)
653
+ return;
654
+ const remaining = Math.max(0, this.retryTimeoutMs - this.getRetryElapsedMs());
655
+ this.retryTimer = setTimeout(() => { this.onRetryTimeout(); }, remaining);
656
+ }
657
+ clearRetryTimer() {
658
+ if (this.retryTimer)
659
+ clearTimeout(this.retryTimer);
660
+ delete this.retryTimer;
661
+ }
662
+ onRetryTimeout() {
663
+ delete this.retryTimer;
664
+ try {
665
+ if (this.trainerRetry !== 'running')
666
+ return;
667
+ this.endRiderRetry('timeout');
668
+ this.deps.onChange();
669
+ }
670
+ catch {
671
+ }
672
+ }
427
673
  startTrainer(control) {
428
674
  this.stopAttempt();
675
+ this.clearRiderRetry();
676
+ delete this.unavailableSince;
429
677
  this.trainerUdid = control.selected;
430
678
  this.trainerInterface = control.interface;
431
679
  this.lastConnectState = control.connectState;
@@ -438,6 +686,8 @@ export class PairingGuidance {
438
686
  }
439
687
  endTrainer() {
440
688
  this.stopAttempt();
689
+ this.clearRiderRetry();
690
+ delete this.unavailableSince;
441
691
  delete this.phase;
442
692
  delete this.trainerUdid;
443
693
  delete this.trainerInterface;
@@ -463,6 +713,12 @@ export class PairingGuidance {
463
713
  const fromPhase = this.phase;
464
714
  const attemptMs = this.attemptTimeoutMs === undefined ? undefined : this.getAttemptElapsedMs();
465
715
  this.phase = toPhase;
716
+ if (toPhase === 'unavailable')
717
+ this.unavailableSince = Date.now();
718
+ else
719
+ delete this.unavailableSince;
720
+ if (toPhase === 'connected' && this.trainerRetry === 'failed')
721
+ this.clearRiderRetry();
466
722
  if (toPhase === 'connected')
467
723
  this.stopAttempt();
468
724
  else if (toPhase === 'connecting')
@@ -527,6 +783,11 @@ export class PairingGuidance {
527
783
  }
528
784
  reset() {
529
785
  this.endTrainer();
786
+ this.retryIndex = 0;
787
+ delete this.retryCase;
788
+ delete this.fallback;
789
+ this.fallbackReverted = false;
790
+ this.clearFallbackRevertedTimer();
530
791
  this.clearPartialOutage();
531
792
  this.resetHelper();
532
793
  this.visitOpen = false;