-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.js
More file actions
406 lines (363 loc) · 12.7 KB
/
Copy pathcontroller.js
File metadata and controls
406 lines (363 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// =====================================================================
// controller.js - orchestration. The only module that ties the others
// together: handles user actions and bridge messages, updates state,
// then calls view / api / bridge. Holds no DOM code and no raw fetch.
// =====================================================================
// -- Boot ------------------------------------------------------------
(function init() {
var params = new URLSearchParams(window.location.search);
ui.offline = !navigator.onLine;
ui.debug = params.get('debug') === 'true';
Bridge.setHandlers({
autoLogin: onAutoLogin,
scanResult: function (m) { showDevices(m); },
connectResult: onConnectResult,
disconnected: onDisconnected,
reconnected: onReconnected,
ftmsData: function (m) { onFtmsData(m.data); },
saveAck: function () { if (ui.token) showHome(); },
uploadWorkout: onUploadWorkout,
tagCleared: function () {},
goHome: showHome,
rawFtms: function (csv) { ingestData(csv); }
});
bootTimer = setTimeout(finishBoot, 1500);
document.addEventListener('DOMContentLoaded', function () {
render();
if (params.get('offline') === 'true') goOffline();
// Strip stray spaces (common from mobile autocorrect) on blur
['username', 'reg-username'].forEach(function (id) {
var el = document.getElementById(id);
if (el) el.addEventListener('blur', function () { el.value = el.value.trim(); });
});
});
window.addEventListener('online', function () { ui.offline = false; render(); });
window.addEventListener('offline', function () { ui.offline = true; render(); });
document.addEventListener('keydown', function (e) {
if (e.key === 'Enter' && ui.screen === 'login') doLogin();
});
window.addEventListener('message', function (e) {
if (!e.data) return;
if (e.data.type === 'shaderReady') hideLoadingOverlay();
if (e.data.type === 'tokenExpired') {
ui.token = null; ui.username = null;
setUserBadge('');
setLoginStatus('Session expired. Please log in again.');
goScreen('login');
}
});
window.addEventListener('hashchange', function () {
if (window.location.hash.indexOf('#data=') === 0) ingestData(null);
});
})();
var bootTimer = null;
function finishBoot() {
if (bootTimer) { clearTimeout(bootTimer); bootTimer = null; }
hideBootSplash();
}
// -- Login / auth ----------------------------------------------------
function onAutoLogin(msg) {
if (bootTimer) { clearTimeout(bootTimer); bootTimer = null; }
if (!msg.token) { goScreen('login'); hideBootSplash(); return; }
Api.validateToken(msg.token)
.then(function (data) {
if (data && data.status === 'success') {
setSession(msg.token, data.username);
setLoginStatus('');
showHome();
} else {
setLoginStatus('Session expired: ' + ((data && data.error) || 'invalid token'));
clearSession();
goScreen('login');
}
hideBootSplash();
})
.catch(function (e) {
setLoginStatus('Network error: ' + e.message);
hideBootSplash();
goOffline();
});
}
function doLogin() {
var u = document.getElementById('username').value.trim();
var p = document.getElementById('password').value;
if (!u || !p) { setLoginStatus('Username and password required'); return; }
setLoginStatus('');
var btn = document.querySelector('#screen-login .btn');
btn.disabled = true; btn.textContent = 'LOGGING IN...';
Api.login(u, p)
.then(function (data) {
btn.disabled = false; btn.textContent = 'LOGIN';
if (data && data.status === 'success' && data.token) {
setSession(data.token, u);
Bridge.send('loginResult', { success: true, token: data.token, username: u });
showHome();
} else {
var err = (data && data.error) || 'Login failed';
setLoginStatus(err);
Bridge.send('loginResult', { success: false, error: err });
}
})
.catch(function (e) {
btn.disabled = false; btn.textContent = 'LOGIN';
console.error(e);
goOffline();
});
}
function doRegister() {
var u = document.getElementById('reg-username').value.trim();
var e = document.getElementById('reg-email').value.trim();
var p = document.getElementById('reg-password').value;
if (!u || !e || !p) { setRegisterStatus('All fields required'); return; }
if (!document.getElementById('reg-consent').checked) {
setRegisterStatus('You must accept the privacy policy to continue'); return;
}
setRegisterStatus('');
var btn = document.querySelector('#screen-register .btn.primary');
btn.disabled = true; btn.textContent = 'CREATING...';
Api.register(u, e, p)
.then(function (data) {
btn.disabled = false; btn.textContent = 'CREATE';
if (data && data.status === 'success') {
document.getElementById('reg-password').value = '';
openOverlay('registerSuccess');
} else {
setRegisterStatus((data && data.error) || 'Registration failed');
}
})
.catch(function (err) {
btn.disabled = false; btn.textContent = 'CREATE';
setRegisterStatus('Network error: ' + err.message);
});
}
function hideRegisterSuccess() { goScreen('login'); }
function setSession(token, username) {
ui.token = token; ui.username = username;
setUserBadge(username);
}
function clearSession() {
ui.token = null; ui.username = null;
setUserBadge('');
}
// -- Offline ---------------------------------------------------------
function goOffline() {
ui.offline = true;
Bridge.send('loginResult', { success: false, offline: true });
goScreen('scan');
}
// -- Home ------------------------------------------------------------
function showHome() {
var iframe = document.getElementById('home-frame');
var sendToken = function () {
iframe.contentWindow.postMessage({ type: 'token', token: ui.token }, '*');
};
if (iframe.src && iframe.src !== 'about:blank' && iframe.src.indexOf(XESYNC_CONFIG.apexHomeUrl) === 0) {
sendToken();
} else {
iframe.onload = sendToken;
iframe.src = XESYNC_CONFIG.apexHomeUrl;
}
goScreen('home');
}
// -- Exit / logoff ---------------------------------------------------
function doExit() {
if (ui.screen === 'login') { Bridge.send('exit'); return; }
openOverlay('exitConfirm');
}
function hideExitConfirm() { closeOverlay(); }
function doLogoff() {
closeOverlay();
clearSession();
ui.connected = false;
ui.scanning = false;
Debug.stopSim();
document.getElementById('password').value = '';
goScreen('login');
}
function doQuit() {
closeOverlay();
Bridge.send('exit');
}
// -- Scan ------------------------------------------------------------
var scanReturnScreen = null;
function startScan() {
scanReturnScreen = ui.screen;
ui.scanning = true;
renderScanSearching();
goScreen('scan');
if (Debug.isOn()) { Debug.fakeScan(showDevices); return; }
Bridge.send('scan');
}
function stopScan() {
Bridge.send('stopScan');
ui.scanning = false;
if (scanReturnScreen && scanReturnScreen !== 'scan' && scanReturnScreen !== 'connecting') {
if (scanReturnScreen === 'home') showHome(); else goScreen(scanReturnScreen);
} else if (ui.token) {
showHome();
} else {
goScreen('scan');
}
scanReturnScreen = null;
}
function showDevices(msg) {
var seen = {};
var devices = (msg.devices || []).reduce(function (acc, d) {
var parts = (d.id || '').trim().split(/\s+/);
var mac = parts[0];
if (!seen[mac]) { seen[mac] = true; acc.push({ id: mac, name: parts.slice(1).join(' ') || mac }); }
return acc;
}, []);
renderDeviceList(devices, doConnect);
}
// -- Connect ---------------------------------------------------------
function doConnect(device) {
ui.scanning = false;
setConnectingLabel('CONNECTING...');
goScreen('connecting');
if (Debug.isOn()) { Debug.fakeConnect(onConnectResult); return; }
Bridge.send('connect', { deviceId: device.id, deviceName: device.name });
}
function onConnectResult(msg) {
// App Inventor sends connectResult:success even after an unplanned drop
// (its Connected event can't tell first-connect from reconnect). If the
// reconnect overlay is up, this is a reconnection: stop the retry timer
// and just resume the live session.
if (ui.overlay === 'reconnect') {
if (msg.success) {
stopReconnect();
closeOverlay(); // back to the live rowing screen, tracking intact
}
// a failure here is ignored: the retry timer keeps going until RECONNECT_MAX
return;
}
if (msg.success) {
ui.connected = true;
enterRowing();
} else {
setConnectingLabel(msg.error || 'CONNECTION FAILED');
setTimeout(function () { goScreen('scan'); }, 2000);
}
}
function enterRowing() {
showLoadingOverlay();
goScreen('rowing');
initRowing();
initFtmsTracking();
if (Debug.isOn()) Debug.startSim();
}
// --- Reconnect (driven by the web app) ------------------------------
// On an unplanned drop App Inventor sends {"action":"disconnected"}.
// The web app then drives the retries: it shows the RECONNECTING overlay
// and sends {"action":"reconnect"} up to RECONNECT_MAX times, RECONNECT_DELAY
// apart. App Inventor answers each reconnect by calling ConnectWithAddress;
// its Connected event sends {"action":"connectResult","success":true}.
// - success arrives while overlay is up -> cancel timer, close overlay, resume
// - all attempts used up -> give up, close overlay, mark disconnected
var RECONNECT_MAX = 3;
var RECONNECT_DELAY = 5000;
var reconnectTries = 0;
var reconnectTimer = null;
function onDisconnected() {
if (ui.overlay === 'reconnect') return; // already reconnecting
reconnectTries = 0;
openOverlay('reconnect');
attemptReconnect();
}
function attemptReconnect() {
reconnectTries++;
Bridge.send('reconnect');
reconnectTimer = setTimeout(function () {
if (reconnectTries >= RECONNECT_MAX) {
stopReconnect();
ui.connected = false;
closeOverlay();
// No more FTMS packets, so the inactivity watchdog has paused the
// session: the PAUSED dialog (SAVE / EXIT) is waiting for the user.
} else {
attemptReconnect();
}
}, RECONNECT_DELAY);
}
function stopReconnect() {
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
}
function onReconnected() {
stopReconnect();
closeOverlay();
}
function doGiveUp() {
stopReconnect();
closeOverlay();
Bridge.send('disconnect');
ui.connected = false;
ui.scanning = false;
if (ui.token) showHome(); else goScreen('login');
}
function resumeRowing() { enterRowing(); }
function disconnectRower() {
if (Debug.isOn()) Debug.stopSim();
else Bridge.send('disconnect');
ui.connected = false;
ui.scanning = false;
if (ui.token) showHome(); else goScreen('login');
}
function debugMode() {
ui.connected = true;
enterRowing();
}
// -- FTMS raw data ---------------------------------------------------
function onFtmsData(data) {
ingestData(data);
if (XESYNC_CONFIG.logRawData) logRaw(data);
}
function logRaw(data) {
var d = new Date();
var p = function (n, w) { return String(n).padStart(w || 2, '0'); };
var dateStr = p(d.getDate()) + '/' + p(d.getMonth() + 1) + '/' + d.getFullYear() + ' ' +
p(d.getHours()) + ':' + p(d.getMinutes()) + ':' + p(d.getSeconds()) + '.' +
p(d.getMilliseconds(), 3);
Api.logRawData(dateStr, data);
}
function onUploadWorkout(msg) {
Api.saveWorkout(msg.token, msg.workout, msg.data)
.then(function (row) {
if (row && row.status === 'success') Bridge.send('uploadAck', { workout: msg.workout });
})
.catch(function () {});
}
// -- Post workout (called by ftms_integration.js) --------------------
// Called by ftms_integration.js to persist a finished workout.
// Decides online (Api) vs offline (Bridge to App Inventor storage),
// then reports 'online' | 'offline' back through `done`.
window.onWorkoutSave = function (tag, payload, done) {
if (!ui.token) {
Bridge.send('saveData', { workout: tag, data: payload });
setTimeout(function () { done('offline'); }, 1200);
return;
}
var timeout = new Promise(function (_, reject) {
setTimeout(function () { reject(new Error('timeout')); }, 10000);
});
Promise.race([Api.saveWorkout(ui.token, tag, payload), timeout])
.then(function (row) {
done(row && row.status === 'success' ? 'online' : 'offline');
})
.catch(function () { done('offline'); });
};
window.onLeaveRowing = function () {
setConnectingLabel('');
goScreen('connecting');
};
window.onWorkoutComplete = function (savedState) {
renderPostWorkout(savedState, !!ui.token);
openOverlay('postWorkout');
};
function postWorkoutGoWorkouts() {
closeOverlay();
if (ui.token) showHome(); else goScreen('login');
}
function postWorkoutGoLogin() {
closeOverlay();
goScreen('login');
}