forked from bskari/pi-rc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.html
642 lines (611 loc) · 22.8 KB
/
watch.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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
<!doctype html>
<html lang="en">
<head>
<title>Webcam monitor</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
box-sizing: border-box;
}
body {
font-family: sans-serif;
line-height: 1.15;
margin: 0;
}
header {
font-size: 200%;
margin: 10px;
}
.content {
display: table;
text-align: left;
}
.center {
text-align: center;
margin: 0 auto;
}
.label {
float: left;
padding: .25rem;
text-align: right;
width: 50%;
}
.value {
float: left;
padding: .25rem;
text-align: left;
width: 50%;
}
.button {
opacity: 1;
font-size: .875rem;
margin-bottom: .5rem;
padding-left: 1rem;
padding-right: 1rem;
padding-top: .5rem;
padding-bottom: .5rem;
background-color: #000;
color: #fff;
text-decoration: none;
display: inline-block;
border-radius: .25rem;
}
.hidden {
display: none;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0); /* Fallback if alpha not supported */
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
background-color: white;
text-align: center;
margin: 15% auto;
padding: 20px;
border: 1px solid black;
width: 20%;
}
#help {
width: 600px;
display: none;
}
</style>
<script>
(function() {
'use strict';
var width = 320;
var height = 0; // This will be computed based on the input stream
var streaming = false;
var video = null;
var canvas = null;
var photo = null;
var countDownDiv = null;
var monitorButton = null;
var previewButton = null;
var imageChange = null;
var pictureIntervalId = null;
var countDownIntervalId = null;
var countDown = 0;
var sendSignals = false;
var referenceImage = null;
var differenceThreshold = 5;
function startUp() {
video = document.getElementById('video');
canvas = document.getElementById('canvas');
photo = document.getElementById('photo');
monitorButton = document.getElementById('toggle-monitoring');
previewButton = document.getElementById('start-preview');
countDownDiv = document.getElementById('count-down');
imageChange = document.getElementById('image-change');
if (window.location.protocol == 'file:') {
var infoP = document.getElementById('info');
infoP.appendChild(
document.createTextNode(
'This file needs to be served over HTTPS to access the webcam.'));
infoP.appendChild(document.createElement('br'));
infoP.appendChild(
document.createTextNode(
'Please run `python host_files.py` and visit '));
var linkElement = document.createElement('a');
var url = 'https://localhost:4443/watch.html';
linkElement.appendChild(document.createTextNode(url));
linkElement.title = url;
linkElement.href = url;
infoP.appendChild(linkElement);
infoP.appendChild(document.createElement('br'));
var certificateInstructions = 'You will need to accept the self-signed certificate by '
// If Firefox
if (typeof InstallTrigger !== 'undefined') {
certificateInstructions += 'clicking "Advanced", "Add Exception", and "Confirm Security Exception".';
} else {
certificateInstructions += 'clicking "Advanced" and "Proceed to localhost (unsafe)".';
}
infoP.appendChild(document.createTextNode(certificateInstructions));
infoP.classList.remove('hidden');
return;
}
video.addEventListener('canplay', function(event) {
if (!streaming) {
height = video.videoHeight / (video.videoWidth / width);
// Work around Firefox bug
if (isNaN(height)) {
height = width / (4 / 3);
}
video.setAttribute('width', width);
video.setAttribute('height', height);
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
streaming = true;
}
}, false);
enumerateDevices();
monitorButton.addEventListener('click', function(event) {
event.preventDefault();
toggleMonitoring();
}, false);
previewButton.addEventListener('click', function(event) {
event.preventDefault();
startPreview();
}, false);
document.getElementById('help-header').addEventListener('click', function(event) {
document.getElementById('help').style.display = 'block';
});
clearPhoto();
}
function alertError(error) {
alert('An error occurred: ' + error);
}
function toggleMonitoring() {
sendSignals = !sendSignals;
if (sendSignals) {
monitorButton.text = 'Stop monitoring';
countDown = 5;
countDownDiv.children[0].children[0].textContent = countDown + '...';
countDownDiv.style.display = 'block';
countDownIntervalId = setInterval(updateCountDown, 1000);
var infoP = document.querySelector('#info');
while (infoP.hasChildNodes()) {
infoP.removeChild(infoP.lastChild);
}
} else {
monitorButton.text = 'Start monitoring';
countDown = 0;
countDownDiv.style.display = 'none';
if (countDownIntervalId) {
clearInterval(countDownIntervalId);
}
}
referenceImage = null;
}
function clearPhoto() {
var context = canvas.getContext('2d');
context.fillStyle = '#AAA';
context.fillRect(0, 0, canvas.width, canvas.height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
}
function takePicture() {
var context = canvas.getContext('2d');
var rawData;
if (width && height) {
canvas.width = width;
canvas.height = height;
context.drawImage(video, 0, 0, width, height);
rawData = context.getImageData(0, 0, width, height);
context.putImageData(rawData, 0, 0);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
} else {
clearPhoto();
}
}
function nextCommand() {
var useconds = document.getElementById('useconds').value | 0;
var syncRepeats = document.getElementById('sync-repeats').value | 0;
var syncMultiplier = document.getElementById('sync-multiplier').value | 0;
var signalRepeats = document.getElementById('signal-repeats').value | 0;
if (useconds < 100 || useconds > 1201) {
useconds = 100;
}
if (syncRepeats < 2 || syncRepeats > 7) {
syncRepeats = 2;
}
if (syncMultiplier < 2 || syncMultiplier > 7) {
syncMultiplier = 2;
}
if (signalRepeats < 5 || signalRepeats > 50) {
signalRepeats = 5;
}
signalRepeats += 1;
if (signalRepeats > 50) {
signalRepeats = 5;
syncRepeats += 1;
}
if (syncRepeats > 7) {
syncRepeats = 2;
syncMultiplier += 1;
}
if (syncMultiplier > 7) {
syncMultiplier = 2;
useconds += 100;
}
if (useconds > 1201) {
// Nothing more to do, reset everything
useconds = 100;
syncMultiplier = 2;
syncRepeats = 2;
signalRepeats = 5;
toggleMonitoring();
}
document.getElementById('useconds').value = useconds;
document.getElementById('sync-multiplier').value = syncMultiplier;
document.getElementById('sync-repeats').value = syncRepeats;
document.getElementById('signal-repeats').value = signalRepeats;
}
function sendCommand() {
var command = [];
var frequency = parseFloat(document.getElementById('frequency').value);
var deadFrequency = frequency < 28 ? 49.860 : 27.095;
var useconds = parseInt(document.getElementById('useconds').value);
var syncMultiplier = parseInt(document.getElementById('sync-multiplier').value);
var syncRepeats = parseInt(document.getElementById('sync-repeats').value);
var signalRepeats = parseInt(document.getElementById('signal-repeats').value);
var command = [
{
frequency: frequency,
dead_frequency: deadFrequency,
burst_us: useconds * syncMultiplier,
spacing_us: useconds,
repeats: syncRepeats,
},
{
frequency: frequency,
dead_frequency: deadFrequency,
burst_us: useconds,
spacing_us: useconds,
repeats: signalRepeats,
}
];
var request = new XMLHttpRequest();
request.onerror = function() {
alert('Unable to contact the Python server: is host_files.py running?');
};
request.onreadystatechange = createReadyStateChangeCallback(request);
request.open('POST', window.location.origin + '/command/');
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(command));
}
function createReadyStateChangeCallback(request) {
return function() {
if (request.readyState === XMLHttpRequest.DONE) {
// Any success status code is fine
if (!('' + request.status).startsWith('2')) {
var message;
if (request.status === 500) {
message = 'Unable to contact the server: is pi_pcm running?';
} else {
message = request.statusText || 'Unknown error';
}
alert('Error sending command: ' + message);
if (pictureIntervalId) {
toggleMonitoring();
clearInterval(pictureIntervalId);
pictureIntervalId = null;
}
}
}
}
};
// This function should only be called once
function enumerateDevices() {
function removeCameraSelect() {
var container = document.getElementById('camera-container');
while (container.firstChild) {
container.removeChild(container.firstChild);
}
}
if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
navigator.mediaDevices.enumerateDevices().then(function(devices) {
devices = devices.filter(function(device) {
return device.kind === 'videoinput';
});
// If there's only one camera, just use it
if (devices.length <= 1) {
removeCameraSelect();
startPreview();
return;
}
var cameraSelect = document.getElementById('camera-select');
devices.forEach(function(device, index) {
var option = document.createElement('option');
// Testing on Firefox on a laptop didn't have any labels
if (device.label) {
option.text = device.label;
} else {
option.text = 'Camera ' + (index + 1);
}
option.value = device.deviceId;
cameraSelect.appendChild(option);
});
});
} else {
// Just hide the camera options
removeCameraSelect();
startPreview();
}
}
function getVideoDeviceSelector() {
var cameraSelect = document.getElementById('camera-select');
var defaultOptions = {
width: {
max: 1280,
ideal: 640
},
height: {
max: 960,
ideal: 480
}
};
if (cameraSelect) {
defaultOptions.deviceId = cameraSelect.value;
return defaultOptions;
}
// Otherwise just grab any device
return defaultOptions;
}
function startPreview() {
// I'd prefer to always use the environment facing camera. Firefox
// honors facingMode, iOS Safari doesn't support WebRTC at all, Android
// Chrome claims to but doesn't. Not sure about Opera. We'll just let
// the user choose an enumerated device, or use the only one.
var videoOptions = {
video: getVideoDeviceSelector(),
audio: false
};
function setVideoSource(stream) {
if (navigator.mozGetUserMedia) {
video.mozSrcObject = stream;
} else {
var vendorUrl = window.URL || window.webkitURL;
video.src = vendorUrl.createObjectURL(stream);
}
video.play();
}
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(videoOptions).then(setVideoSource).catch(alertError);
} else {
var getUserMedia = (
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
if (getUserMedia === undefined) {
alert('This browser does not support video');
} else {
getUserMedia(videoOptions, setVideoSource, alertError);
}
}
pictureIntervalId = setInterval(takePicture, 1000);
}
function updateCountDown() {
countDown -= 1;
if (countDown <= 0) {
countDownDiv.style.display = 'none';
if (countDownIntervalId) {
clearInterval(countDownIntervalId);
countDownIntervalId = null;
}
if (pictureIntervalId) {
clearInterval(pictureIntervalId);
pictureIntervalId = null;
}
// Save the reference image
takePicture();
var context = canvas.getContext('2d');
var pixels = context.getImageData(0, 0, canvas.width, canvas.height);
referenceImage = pixels;
imageChange.value = 0.0;
// Use a recursive function with setTimeout instead of setInterval
// to work around slow devices calculating diff
(function loop() {
takePicture();
var context = canvas.getContext('2d');
var rawData = context.getImageData(0, 0, width, height);
var difference = percentDifference(rawData, referenceImage);
imageChange.value = (difference + '').substring(0, 6);
nextCommand();
sendCommand();
pictureIntervalId = setTimeout(
function() {
if (imageChange.value < differenceThreshold) {
loop();
} else {
toggleMonitoring();
saveConfigToWebStorage();
var infoP = document.getElementById('info');
while (infoP.childNodes.length > 0) {
infoP.removeChild(infoP.childNodes[0]);
}
infoP.appendChild(
document.createTextNode(
'Movement detected, parameters saved. Visit '));
var linkElement = document.createElement('a');
var url = '/control.html';
linkElement.appendChild(document.createTextNode('control.html'));
linkElement.title = url;
linkElement.href = url;
infoP.appendChild(linkElement);
infoP.appendChild(
document.createTextNode(
' to set the individual commands.'));
infoP.classList.remove('hidden');
}
},
1000
);
})();
} else {
countDownDiv.children[0].children[0].textContent = countDown + '...';
}
}
function percentDifference(pixels1, pixels2) {
// This happens when we stop monitoring, just ignore it
if (pixels2 === null) {
return 0.0;
}
// On mobile, it looks like the preview is cutting off some pixels, and
// for some reason, the reference image is different sized from the
// actual photo, so be careful when iterating
var pixelCount = Math.min(pixels1.width * pixels1.height, pixels2.width * pixels2.height);
var limit = pixelCount * 4;
var sumDifference = 0.0;
for (var i = 0; i < limit; i += 4) {
sumDifference += Math.abs(pixels1.data[i] - pixels2.data[i]);
sumDifference += Math.abs(pixels1.data[i + 1] - pixels2.data[i + 1]);
sumDifference += Math.abs(pixels1.data[i + 2] - pixels2.data[i + 2]);
// Skip alpha
}
return sumDifference / (pixelCount * 256 * 3) * 100;
}
function saveConfigToWebStorage() {
var frequency = parseFloat(document.getElementById('frequency').value);
var useconds = parseInt(document.getElementById('useconds').value);
var syncMultiplier = parseInt(document.getElementById('sync-multiplier').value);
var syncRepeats = parseInt(document.getElementById('sync-repeats').value);
var signalRepeats = parseInt(document.getElementById('signal-repeats').value);
var config = JSON.stringify({
'frequency': frequency,
'synchronization_burst_us': useconds * syncMultiplier,
'synchronization_spacing_us': useconds,
'total_synchronizations': syncRepeats,
'signal_burst_us': useconds,
'signal_spacing_us': useconds,
});
window.localStorage.setItem('piRcConfig', config);
}
window.addEventListener('load', startUp, false);
})();
</script>
</head>
<body>
<div id="count-down" class="modal">
<div class="modal-content">
<p>5...</p>
</div>
</div>
<div class="content center">
<header>RC monitor</header>
<div class="hidden">
<video id="video">Sorry, no video stream is available</video>
<canvas id="canvas"></canvas>
</div>
<div class="center">
<img id="photo" alt="The screen capture that will appear in this box.">
</div>
<p id="info" class="hidden"></p>
</div>
<div>
<div id="camera-container">
<div class="label">
<label for="camera-select">Camera</label>
</div>
<div class="value">
<select id="camera-select">
</select>
</div>
<div class="content center">
<a id="start-preview" class="button">Start camera preview</a>
</div>
</div>
<div class="label">
<label for="frequency">Frequency MHz</label>
</div>
<div class="value">
<select id="frequency">
<option value="26.995">26.995</option>
<option value="27.045">27.045</option>
<option value="27.095">27.095</option>
<option value="27.145">27.145</option>
<option value="27.195">27.195</option>
<option value="27.255">27.255</option>
<option value="49.830">49.830</option>
<option value="49.845">49.845</option>
<option value="49.860">49.860</option>
<option value="49.875">49.875</option>
<option value="49.890">49.890</option>
</select>
</div>
<div class="label">
<label for="useconds">Useconds</label>
</div>
<div class="value">
<input id="useconds" class="parameter" value="100" type="number" step="1">
</div>
<div class="label">
<label for="sync-repeats">Sync repeats</label>
</div>
<div class="value">
<input id="sync-repeats" class="parameter" value="2" type="number" step="1">
</div>
<div class="label">
<label for="sync-multiplier">Sync multiplier</label>
</div>
<div class="value">
<input id="sync-multiplier" class="parameter" value="2" type="number" step="1">
</div>
<div class="label">
<label for="signal-repeats">Signal repeats</label>
</div>
<div class="value">
<input id="signal-repeats" class="parameter" value="5" type="number" step="1">
</div>
<div class="label">
<label for="image-change">Image change %</label>
</div>
<div class="value">
<input id="image-change" class="parameter" disabled="disabled" value="0.0">
</div>
</div>
<div class="content center">
<a id="toggle-monitoring" class="button">Start monitoring</a>
</div>
<p id="help-header" class="center">Help ▼</p>
<div id="help" class="center">
<p>
This page will help you search for command codes for your RC car. It does so by
repeatedly broadcasting RC commands and using a webcam to see if the car moves.
Once the car does move, the parameters will be saved and you will be redirected
to the control page where you can test and drive the car interactively.
</p>
<p>
pi-rc only works with simple cars, such as those that can only move forward and
reverse and left and right. More complicated controls, such as ones that have
proportional steering or throttle, will likely not work.
</p>
<p>
To start, run <code>pi_pcm</code> on the Raspberry Pi. Set the frequency of the
in the above "Frequency MHz" selector. In the United States, most cheap RC cars
run in either the 27 MHz or the 49 MHz band. This should be labelled on the car
itself. If you the car doesn't list the exact frequency (such as 26.995 MHz),
then select the middle frequency in that band (e.g. 27.095 for 27 MHz). Then,
place the car in front of the webcam in a location with consistent lighting,
i.e. away from sunlight. Then click "Start Monitoring". Once the car moves, the
parameters will be saved and you will be directed to the control page.
</p>
<p>
This page should work in Firefox and Chrome on the desktop computers, and on
Firefox, Chrome, and the Android browser on Android phones. Safari doesn't
support the webcam API on desktop or phone, so it will not work.
</p>
</div>
</body>
</html>