-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
536 lines (469 loc) · 14.6 KB
/
index.html
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Carrera 2.0</title>
<meta name="version" content="dd.mm_hh:mm">
</head>
<body>
<div id="speedInput">
<div id="speedValueDisplay">
00
</div>
</div>
<div id="ledPanel">
<div id="ledDurationDisplay"></div>
<div id="ledButton"></div>
</div>
<div id="parameterPanel" class="closed">
<button id="parameterPanelToggle" onclick="toggleParameterPanel()"></button>
<form id="paramForm">
<input id="paramRoll" type="number" min="0" max="1" step="0.001" title="Slowing of the vehicle if no power is applied">
<input id="paramDeceleration" type="number" min="0" max="1" step="0.001" title="Deceleration power of the break">
<input id="paramAcceleration" type="number" min="0" max="1" step="0.001" title="Acceleration power of the gas pedal">
<span title="Check if you want to use the JoyCon horizontally">
<input id="paramHorizontal" type="checkbox">
<label for="paramHorizontal">Horizontal JoyCon</label>
</span>
<span title="Check if you have the left Joycon in use">
<input id="paramLeftJoycon" type="checkbox">
<label for="paramLeftJoycon">Left JoyCon</label>
</span>
<button type="submit">Apply</button>
</form>
</div>
<div id="stopButton" class="stop" hidden></div>
<span id="versionDisplay"></span>
<div id="paramNotification">Parameters have been saved.</div>
</body>
<script>
function displayVersion() {
const version = document.querySelector("meta[name='version']").content;
document.getElementById("versionDisplay").innerHTML = version;
}
displayVersion();
// Variables and constants
const min = 0;
const max = 130;
var currentSpeed = 0;
var speedInput = 0.0;
// Gamepad Variables
var rollSlow = 0.001;
var decelerationPower = 0.03;
var accelerationPower = 0.05;
var horizontalMode = 0; // Set to 1 if you want to use the JoyCon horizontally.
var isLeftJoycon = 0; // Instead of true and false we use 0 and 1 (because of localStorage)
const buttonMap = new Map([
[0, {"function": activateLed}],
[5, {"function": boost}],
[8, {"function": boost}],
[16, {"function": emergencyStop}],
]);
// Websocket overload protection
var lastMessageSent = null;
// This handles the input Slider.
setupClickEvents();
function setupClickEvents() {
document.getElementById("speedInput").addEventListener("mousedown", handleMouseClick);
document.getElementById("speedInput").addEventListener("mousemove", handleMouseClick);
document.getElementById("speedInput").addEventListener("touchmove", handleTouchEvent);
document.getElementById("ledButton").addEventListener("click", clickLedButton);
document.getElementById("ledButton").addEventListener("touchstart", clickLedButton);
document.getElementById("stopButton").addEventListener("click", clickStopButton);
document.getElementById("stopButton").addEventListener("touchstart", clickStopButton);
document.getElementById('paramForm').addEventListener('submit', changeParams);
}
loadDefaultParams();
function loadDefaultParams() {
if (localStorage.getItem("rollSlow"))
rollSlow = localStorage.getItem("rollSlow");
document.getElementById("paramRoll").value = rollSlow;
if (localStorage.getItem("decelerationPower"))
decelerationPower = localStorage.getItem("decelerationPower");
document.getElementById("paramDeceleration").value = decelerationPower;
if (localStorage.getItem("accelerationPower"))
accelerationPower = localStorage.getItem("accelerationPower");
document.getElementById("paramAcceleration").value = accelerationPower;
if (localStorage.getItem("horizontalMode"))
horizontalMode = parseInt(localStorage.getItem("horizontalMode"));
document.getElementById("paramHorizontal").checked = horizontalMode == 1;
if (localStorage.getItem("isLeftJoycon"))
isLeftJoycon = parseInt(localStorage.getItem("isLeftJoycon"));
document.getElementById("paramLeftJoycon").checked = isLeftJoycon == 1;
}
function changeParams(e) {
e.preventDefault();
rollSlow = document.getElementById("paramRoll").value;
decelerationPower = document.getElementById("paramDeceleration").value;
accelerationPower = document.getElementById("paramAcceleration").value;
horizontalMode = document.getElementById("paramHorizontal").checked ? 1 : 0;
isLeftJoycon = document.getElementById("paramLeftJoycon").checked ? 1 : 0;
localStorage.setItem("rollSlow", rollSlow);
localStorage.setItem("decelerationPower", decelerationPower);
localStorage.setItem("accelerationPower", accelerationPower);
localStorage.setItem("horizontalMode", horizontalMode);
localStorage.setItem("isLeftJoycon", isLeftJoycon);
// Visual confirmation of save:
const notification = document.getElementById("paramNotification");
notification.className = "show";
setTimeout(function(){ notification.className = notification.className.replace("show", ""); }, 3000);
}
function toggleParameterPanel() {
const panel = document.getElementById("parameterPanel");
const toggle = document.getElementById("parameterPanelToggle");
if (panel.classList.contains("closed")) {
panel.classList.replace("closed", "opened");
toggle.innerHTML = "<";
toggle.title = "Hide parameter panel";
} else {
panel.classList.replace("opened", "closed");
toggle.innerHTML = ">";
toggle.title = "Show parameter panel";
}
}
function handleMouseClick(event) {
if (!event.buttons || event.buttons != 1) return;
const value = calculateClickValue(event.y);
handleUserInput(value);
}
function calculateClickValue(yCoordinate) {
const inputFieldBounds = document.getElementById("speedInput").getBoundingClientRect();
const yPos = yCoordinate - inputFieldBounds.top;
const height = inputFieldBounds.height;
return clampPctValue(1-(yPos/height));
}
function handleTouchEvent(touchEvent) {
const touch = touchEvent.touches[0];
const value = calculateClickValue(touch.clientY);
handleUserInput(value);
}
function handleUserInput(pctValue) {
pctValue = clampPctValue(pctValue);
if (speedInput == pctValue) return; // No change happened, we can ignore this
speedInput = pctValue;
const absolute = convertPctToAbsoluteSpeed(pctValue);
updateSpeedInputDisplay();
updateSpeed(absolute);
}
function handleAbsoluteInput(absoluteValue) {
handleUserInput(absoluteToPctSpeed(absoluteValue));
}
function clickLedButton(event) {
if (event.pointerId && event.pointerId != 1) // Prevent action to execute twice on touch click
return;
activateLed();
}
function clickStopButton(event) {
if (event.pointerId && event.pointerId != 1) // Prevent action to execute twice on touch click
return;
emergencyStop();
}
function updateSpeedInputDisplay() {
const input = document.getElementById("speedInput");
const inputValue = 100 * speedInput;
const actualValue = 100 * absoluteToPctSpeed(currentSpeed);
document.getElementById("speedValueDisplay").innerHTML = currentSpeed;
if (actualValue < inputValue) {
input.style.background = `linear-gradient(0deg, var(--darkColor) 0%, var(--darkColor) ${actualValue}%, var(--changeColor) ${actualValue}%, var(--changeColor) ${inputValue}%, var(--lightColor) ${inputValue}%, var(--lightColor) 100%)`;
} else {
input.style.background = `linear-gradient(0deg, var(--darkColor) 0%, var(--darkColor) ${inputValue}%, var(--changeColor) ${inputValue}%, var(--changeColor) ${actualValue}%, var(--lightColor) ${actualValue}%, var(--lightColor) 100%)`;
}
}
function clampPctValue(pctValue) {
return Math.min(Math.max(0, pctValue), 1);
}
function convertPctToAbsoluteSpeed(pctValue) {
const value = min + Math.round(pctValue * (max - min));
return value;
}
function absoluteToPctSpeed(absoluteValue) {
return (absoluteValue - min) / max;
}
//Websockets:
var gateway = `ws://${window.location.hostname}/ws`;
var websocket;
var connected = false;
window.addEventListener("load", onLoad);
function initWebSocket() {
console.log("Trying to open a WebSocket connection...");
websocket = new WebSocket(gateway);
websocket.onopen = onOpen;
websocket.onclose = onClose;
websocket.onmessage = onMessage;
}
function onOpen(event) {
connected = true;
document.getElementById("speedInput").classList.add("connected");
console.log("Connection opened");
}
function onClose(event) {
connected = false;
document.getElementById("speedInput").classList.remove("connected");
console.log("Connection closed");
setTimeout(initWebSocket, 2000);
}
function onMessage(event) {
console.log("Recieving: ", event);
currentSpeed = event.data;
updateSpeedInputDisplay();
}
function onLoad(event) {
initWebSocket();
}
function updateSpeed(value) {
sendViaWebsocket(value.toString());
}
function activateLed() {
if (!connected) return;
sendViaWebsocket("L");
const display = document.getElementById("ledDurationDisplay");
display.classList.remove("animate");
setTimeout(() => {display.classList.add("animate")}, 1);
}
function boost() {
sendViaWebsocket("B");
}
function emergencyStop() {
sendViaWebsocket("S");
}
function sendViaWebsocket(message) {
if (!connected || lastMessageSent == message) return;
console.log("Sending:", message);
websocket.send(message);
if (!isNaN(message)) // Prevent the system from sending the same speed message several times
lastMessageSent = message;
}
// Gamepad support:
const haveEvents = 'ongamepadconnected' in window;
var controller = null;
window.addEventListener("gamepadconnected", connecthandler);
function connecthandler(e) {
// Show parameter panel when controller is connected:
toggleParameterPanel();
document.getElementById("parameterPanel").style.visibility = "visible";
addgamepad(e.gamepad);
}
function addgamepad(gamepad) {
controller = gamepad;
console.log("New gamepad connected:", gamepad);
requestAnimationFrame(updateStatus); // Activate recursive call for updates
}
function updateStatus() {
if (!haveEvents) {
scangamepad();
}
handlePressedButtons();
handleJoystickInput();
requestAnimationFrame(updateStatus); // Basically a recursive call of this function
}
function handlePressedButtons() {
buttonMap.forEach((value, key) => {
if (controller.buttons.length < key)
return;
if (controller.buttons[key].pressed)
value.function();
});
}
function handleJoystickInput() {
let maxSpeedInput = controller.buttons[7].value;
let maxBreakInput = 0.0;
if (isLeftJoycon) {
maxSpeedInput = Math.max(maxSpeedInput, controller.buttons[6].value);
} else {
maxBreakInput = controller.buttons[6].value;
}
for(let i = 0; i < controller.axes.length; i += 2) {
let input = controller.axes[i + horizontalMode];
if (horizontalMode || isLeftJoycon) // Since left joycon is inverted
input *= -1;
maxSpeedInput = Math.max(maxSpeedInput, input, 0);
maxBreakInput = Math.max(maxBreakInput, -Math.min(0, input));
}
handleControllerInput(maxSpeedInput, maxBreakInput);
}
function handleControllerInput(speedInputValue, breakInputValue) {
if (breakInputValue > 0.0) { // active breaking
const decleration = breakInputValue;
handleUserInput(speedInput - decleration * decelerationPower);
} else if (speedInputValue > 0.0 && (speedInput < speedInputValue)) { // active powering
handleUserInput(speedInput + (speedInputValue - speedInput) * accelerationPower);
} else { // decelerate slowly
handleUserInput(speedInput - rollSlow);
}
}
function scangamepad() {
const gamepads = navigator.getGamepads();
for (const gamepad of gamepads) {
if (gamepad) { // Can be null if disconnected during the session
if (gamepad.index == controller.index) {
controller = gamepad;
}
}
}
}
</script>
<style>
:root {
--buttonColor: #3D7EAA;
--stopButtonColor: rgb(187, 57, 57);
--goButtonColor: rgb(32, 107, 32);
--shadow: 0 0 10px 1px rgba(23, 23, 23, 0.2);
}
body {
background: linear-gradient(135deg, #283048, #859398);
color: white;
}
#speedInput {
opacity: 0.8;
--lightColor: lightGray;
--darkColor: gray;
--changeColor: rgb(225, 199, 93);
position: fixed;
left: 10%;
top: 50%;
transform: translateY(-50%);
width: 50%;
height: 90%;
border-radius: 10px;
background: var(--lightColor);
box-shadow: 0 0 10px 1px;
color: red;
}
#speedInput.connected {
color: green;
}
#speedValueDisplay {
position: absolute;
left: 50%;
top: 50%;
font-size: 10rem;
transform: translate(-50%, -50%);
color: black;
-webkit-user-select: none; /* Safari */
-ms-user-select: none; /* IE 10 and IE 11 */
user-select: none; /* Standard syntax */
}
#ledPanel {
position: fixed;
right: 0px;
top: 0px;
height: 100vh;
width: 30vw;
}
#ledButton {
position: absolute;
bottom: 5%;
left: 50%;
border-radius: 50%;
box-shadow: 0 0 10px 1px rgba(23, 23, 23, 0.2);
transform: translate(-50%);
width: 80%;
max-width: 10rem;
aspect-ratio: 1;
background-color: var(--buttonColor);
box-shadow: var(--shadow);
}
#ledDurationDisplay {
--activeColor: var(--buttonColor);
--inactiveColor: rgba(211, 211, 211, 0);
position: absolute;
background: linear-gradient(to top, var(--activeColor) 0%, var(--activeColor) 50%, var(--inactiveColor) 50%, var(--inactiveColor) 100%);
background-size: 100% 200%; /* For animating the background */
border-radius: 5px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 3rem;
height: 80%;
}
#ledDurationDisplay.animate {
animation-name: durationDisplay;
animation-timing-function: linear;
animation-duration: 1s;
}
/* This moves the display for the duration of the led */
@keyframes durationDisplay {
0% {
background-position: 0% 100%;
}
100% {
background-position: 0% 0%;
}
}
#stopButton {
position: absolute;
top: 0px;
right: 0px;
margin: 1rem;
border-radius: 40%;
box-shadow: 0 0 10px 1px rgba(23, 23, 23, 0.2);
width: 10%;
aspect-ratio: 1;
background-color: var(--goButtonColor);
box-shadow: var(--shadow);
}
.stop {
background-color: var(--stopButtonColor) !important;
}
#versionDisplay{
position: fixed;
bottom: 0px;
left: 0px;
margin: 2px;
color: lightgray;
opacity: 0.25;
}
#parameterPanel {
visibility: hidden;
}
#parameterPanel.closed form {
visibility: hidden;
}
#parameterPanel.opened form {
visibility: visible;
}
#parameterPanel form {
display: inline;
}
#paramNotification {
visibility: hidden;
min-width: 250px;
margin-left: -125px;
background-color: #333;
color: #fff;
text-align: center;
border-radius: 5px;
padding: 16px;
position: fixed;
z-index: 1;
left: 50%;
bottom: 30px;
font-size: 17px;
}
#paramNotification.show {
visibility: visible;
-webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s;
animation: fadein 0.5s, fadeout 0.5s 2.5s;
}
button {
border-radius: 5px;
border-style: none;
}
@-webkit-keyframes fadein {
from {bottom: 0; opacity: 0;}
to {bottom: 30px; opacity: 1;}
}
@keyframes fadein {
from {bottom: 0; opacity: 0;}
to {bottom: 30px; opacity: 1;}
}
@-webkit-keyframes fadeout {
from {bottom: 30px; opacity: 1;}
to {bottom: 0; opacity: 0;}
}
@keyframes fadeout {
from {bottom: 30px; opacity: 1;}
to {bottom: 0; opacity: 0;}
}
</style>
</html>