-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
377 lines (328 loc) · 11.7 KB
/
Copy pathapp.js
File metadata and controls
377 lines (328 loc) · 11.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
/*
* app.js
* Omni-wheel Robot Controller Engine (Ultra-Low Latency Local HTTP)
*
* Architecture:
* - PRIMARY: Mac Local HTTP Server (http://192.168.10.140:8000/api/cmd)
* - BACKUP: USB Web Serial API (Chrome only, cable connection)
* - NO MQTT, NO Cloud. Pure local network for instant response.
*
* Continuous Hold-To-Drive Pulse System (100ms):
* - While button or key is held down, sends heartbeat pulse every 100ms.
* - Release -> Clears interval & sends instant STOP 'x'.
*/
// ==========================================
// 1. WEB SERIAL API CONTROLLER (USB DIRECT)
// ==========================================
class SerialController {
constructor(onData, onStatus) {
this.onData = onData;
this.onStatus = onStatus;
this.port = null;
this.reader = null;
this.writer = null;
this.keepReading = false;
}
async connect() {
if (!('serial' in navigator)) {
alert('Web Serial API is not supported in this browser. Please use Google Chrome or Edge.');
return false;
}
try {
this.port = await navigator.serial.requestPort();
await this.port.open({ baudRate: 115200 });
const textEncoder = new TextEncoderStream();
this.writableStreamClosed = textEncoder.readable.pipeTo(this.port.writable);
this.writer = textEncoder.writable.getWriter();
this.keepReading = true;
this.readLoop();
if (this.onStatus) this.onStatus(true, 'USB SERIAL CONNECTED');
return true;
} catch (error) {
console.error('[Web Serial Error]', error);
if (this.onStatus) this.onStatus(false, 'SERIAL ERROR');
this.disconnect();
return false;
}
}
async readLoop() {
const textDecoder = new TextDecoderStream();
this.readableStreamClosed = this.port.readable.pipeTo(textDecoder.writable);
const reader = textDecoder.readable.getReader();
this.reader = reader;
let buffer = '';
try {
while (this.keepReading) {
const { value, done } = await reader.read();
if (done) break;
if (value) {
buffer += value;
const lines = buffer.split('\n');
buffer = lines.pop();
}
}
} catch (error) {
console.warn('[Web Serial Read Error]', error);
} finally {
reader.releaseLock();
}
}
async send(data) {
if (this.writer) {
try {
await this.writer.write(data);
} catch (err) {
console.error('[Web Serial Send Error]', err);
}
}
}
async disconnect() {
this.keepReading = false;
if (this.reader) await this.reader.cancel().catch(() => {});
if (this.writer) await this.writer.close().catch(() => {});
if (this.port) await this.port.close().catch(() => {});
this.port = null;
this.reader = null;
this.writer = null;
if (this.onStatus) this.onStatus(false, 'DISCONNECTED');
}
}
// ==========================================
// 2. LOCAL HTTP API CONTROLLER (PRIMARY)
// ==========================================
class LocalHttpController {
constructor(onStatusChange) {
this.onStatusChange = onStatusChange;
this.isConnected = false;
this.checkConnection();
}
checkConnection() {
fetch('/api/status')
.then(resp => resp.json())
.then(data => {
this.isConnected = true;
if (this.onStatusChange) {
this.onStatusChange(true, 'LOCAL HTTP ACTIVE');
}
})
.catch(err => {
this.isConnected = false;
if (this.onStatusChange) {
this.onStatusChange(false, 'SERVER OFFLINE');
}
// Retry in 3 seconds
setTimeout(() => this.checkConnection(), 3000);
});
}
send(cmd) {
fetch('/api/cmd?set=' + cmd).catch(() => {
this.isConnected = false;
if (this.onStatusChange) {
this.onStatusChange(false, 'SERVER OFFLINE');
}
});
}
}
// ==========================================
// 3. MULTI-CHANNEL CONTROL DISPATCHER
// ==========================================
class RobotControlDispatcher {
constructor(serialController, localHttpController, statusBadge, statusText) {
this.serialController = serialController;
this.localHttpController = localHttpController;
this.statusBadge = statusBadge;
this.statusText = statusText;
this.lastCmd = null;
}
updateStatus(isConnected, text) {
if (this.statusBadge && this.statusText) {
if (isConnected) {
this.statusBadge.classList.add('connected');
this.statusText.textContent = text;
} else {
this.statusBadge.classList.remove('connected');
this.statusText.textContent = text;
}
}
}
send(cmd) {
this.lastCmd = cmd;
// Path 1: Local HTTP API (Primary, <5ms)
if (this.localHttpController) {
this.localHttpController.send(cmd);
}
// Path 2: USB Web Serial (Backup, cable only)
if (this.serialController && this.serialController.port) {
this.serialController.send(cmd);
}
}
}
// ==========================================
// 4. MAIN APPLICATION & CONTINUOUS HOLD PULSE BINDINGS
// ==========================================
document.addEventListener('DOMContentLoaded', () => {
// DOM Elements
const btnConnect = document.getElementById('btn-connect');
const statusBadge = document.getElementById('status-badge');
const statusText = document.getElementById('status-text');
const btnUp = document.getElementById('btn-up');
const btnDown = document.getElementById('btn-down');
const btnLeft = document.getElementById('btn-left');
const btnRight = document.getElementById('btn-right');
const btnStop = document.getElementById('btn-stop');
const btnAuto = document.getElementById('btn-auto');
const btnStopAll = document.getElementById('btn-stop-all');
const speedPills = document.querySelectorAll('.speed-pill');
// Instantiate Controllers & Dispatcher
const serialController = new SerialController(null, (isConnected, label) => {
dispatcher.updateStatus(isConnected, label);
});
const localHttpController = new LocalHttpController((isConnected, label) => {
dispatcher.updateStatus(isConnected, label);
});
const dispatcher = new RobotControlDispatcher(serialController, localHttpController, statusBadge, statusText);
// Speed Pill Click Handler
speedPills.forEach(pill => {
pill.addEventListener('click', (e) => {
e.preventDefault();
speedPills.forEach(p => p.classList.remove('active'));
pill.classList.add('active');
const level = pill.getAttribute('data-speed');
dispatcher.send(level);
});
});
// USB Serial Connect Button
if (btnConnect) {
btnConnect.addEventListener('click', async () => {
if (serialController.port) {
await serialController.disconnect();
} else {
await serialController.connect();
}
});
}
// Active Hold Pulse Timer Storage
let holdPulseTimer = null;
let currentHoldingCmd = null;
function startHoldPulse(cmd, element) {
if (currentHoldingCmd === cmd) return;
currentHoldingCmd = cmd;
if (element) element.classList.add('active');
// Immediate first pulse
dispatcher.send(cmd);
// Continuous 100ms heartbeat pulses while held down
if (holdPulseTimer) clearInterval(holdPulseTimer);
holdPulseTimer = setInterval(() => {
if (currentHoldingCmd) {
dispatcher.send(currentHoldingCmd);
}
}, 100);
}
function stopHoldPulse(element) {
currentHoldingCmd = null;
if (holdPulseTimer) {
clearInterval(holdPulseTimer);
holdPulseTimer = null;
}
if (element) element.classList.remove('active');
dispatcher.send('x');
}
function bindHoldToDrive(element, moveCmd) {
if (!element) return;
// Mouse Events
element.addEventListener('mousedown', (e) => {
e.preventDefault();
startHoldPulse(moveCmd, element);
});
element.addEventListener('mouseup', (e) => {
e.preventDefault();
stopHoldPulse(element);
});
element.addEventListener('mouseleave', (e) => {
e.preventDefault();
if (currentHoldingCmd === moveCmd) {
stopHoldPulse(element);
}
});
// Touch Events (Mobile Touchscreen)
element.addEventListener('touchstart', (e) => {
e.preventDefault();
startHoldPulse(moveCmd, element);
}, { passive: false });
element.addEventListener('touchend', (e) => {
e.preventDefault();
stopHoldPulse(element);
}, { passive: false });
element.addEventListener('touchcancel', (e) => {
e.preventDefault();
stopHoldPulse(element);
}, { passive: false });
}
// Bind D-Pad Direction Buttons
bindHoldToDrive(btnUp, 'w');
bindHoldToDrive(btnDown, 's');
bindHoldToDrive(btnLeft, 'a');
bindHoldToDrive(btnRight, 'd');
// Tap Action Buttons (Stop & Auto Roam)
if (btnStop) {
btnStop.addEventListener('click', (e) => {
e.preventDefault();
stopHoldPulse(null);
});
}
if (btnAuto) {
btnAuto.addEventListener('click', (e) => {
e.preventDefault();
stopHoldPulse(null);
dispatcher.send('i');
});
}
if (btnStopAll) {
btnStopAll.addEventListener('click', (e) => {
e.preventDefault();
stopHoldPulse(null);
dispatcher.send('o');
});
}
// Keyboard WASD & Arrow Key Hold-To-Drive Handler
const keyMap = {
'w': { cmd: 'w', btn: btnUp },
'arrowup': { cmd: 'w', btn: btnUp },
's': { cmd: 's', btn: btnDown },
'arrowdown': { cmd: 's', btn: btnDown },
'a': { cmd: 'a', btn: btnLeft },
'arrowleft': { cmd: 'a', btn: btnLeft },
'd': { cmd: 'd', btn: btnRight },
'arrowright': { cmd: 'd', btn: btnRight }
};
const activeKeys = new Set();
window.addEventListener('keydown', (e) => {
const k = e.key.toLowerCase();
if (keyMap[k] && !activeKeys.has(k)) {
e.preventDefault();
activeKeys.add(k);
startHoldPulse(keyMap[k].cmd, keyMap[k].btn);
} else if (k === 'x' || k === ' ') {
e.preventDefault();
stopHoldPulse(null);
} else if (k === 'i') {
e.preventDefault();
stopHoldPulse(null);
dispatcher.send('i');
} else if (k >= '1' && k <= '9') {
e.preventDefault();
dispatcher.send(k);
}
});
window.addEventListener('keyup', (e) => {
const k = e.key.toLowerCase();
if (keyMap[k]) {
e.preventDefault();
activeKeys.delete(k);
if (keyMap[k].btn) keyMap[k].btn.classList.remove('active');
if (activeKeys.size === 0) {
stopHoldPulse(keyMap[k].btn);
}
}
});
});