-
Notifications
You must be signed in to change notification settings - Fork 0
/
mow_remotecontrol.ino
833 lines (763 loc) · 35.9 KB
/
mow_remotecontrol.ino
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
#include <ESP8266WiFi.h>
#include <ESPAsyncWebServer.h>
#include <ESPAsyncTCP.h>
#include <ArduinoJson.h>
// Define the WiFi username and password, and PARAM_dir parameter.
const char *ssid = "Mowwifi";
const char *password = "123456789";
const char *PARAM_dir = "dir";
// Create an AsyncWebServer on port 80 to access the server.
AsyncWebServer server(80);
// Define an HTML page that contains the controls for car control.
// Here, HTML is used to create the UI interface and JavaScript is used to establish the function calls.
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="#" />
<title>WiFi Control</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
background-color: rgb(255, 255, 255);
color: rgb(254, 174, 0);
font-family: Arial;
text-align: center;
overflow: hidden;
}
.parent {
display: flex;
justify-content: center;
align-items: center;
}
.joystick-container {
margin: 3rem;
display: inline-block;
}
.coordiv {
border: 2px solid #ffbb00;
border-radius: 0.9375rem;
}
#coordiv-left{
position: absolute;
left: 1%;
top: 10%;
}
#coordiv-right{
position: absolute;
right: 1%;
top: 20%;
}
#coordiv-all{
margin-top: 140px;
margin-left: 20px;
}
.slider-container {
text-align: center;
}
.button-container {
text-align: center;
}
.button {
font-size: 1rem;
border: none;
border-radius: 0.5rem;
background-color: #ffbb00;
color: white;
cursor: pointer;
}
.button.active {
background-color: #ff3c00;
</style>
</head>
<body>
<div class="button-container">
<button id="slowSpeed" class="button">slow</button>
<button id="normalSpeed" class="button active">normal</button>
<button id="fastSpeed" class="button">fast</button>
</div>
<div class="slider-container">
<label for="speedSlider">Speed Controller: </label>
<input type="range" min="0" max="20" value="0" class="slider" id="speedSlider">
</div>
<div class="joystick-container">
<canvas id="coordiv-left" class="coordiv" width="100" height="200">do not support canvas</canvas>
<div id="point-loc-left"></div>
</div>
<div class="joystick-container">
<canvas id="coordiv-right" class="coordiv" width="200" height="100">do not support canvas</canvas>
</div>
<div class="joystick-container">
<canvas id="coordiv-all" class="coordiv" width="200" height="200">do not support canvas</canvas>
</div>
<script>
var VirtualJoystick = function(opts)
{
opts = opts || {};
this._container = opts.container || document.body;
this._strokeStyle = opts.strokeStyle || 'cyan';
this._stickEl = opts.stickElement || this._buildJoystickStick();
this._baseEl = opts.baseElement || this._buildJoystickBase();
this._mouseSupport = opts.mouseSupport !== undefined ? opts.mouseSupport : false;
this._stationaryBase = opts.stationaryBase || false;
this._baseX = this._stickX = opts.baseX || 0
this._baseY = this._stickY = opts.baseY || 0
this._limitStickTravel = opts.limitStickTravel || false
this._stickRadius = opts.stickRadius !== undefined ? opts.stickRadius : 100
this._useCssTransform = opts.useCssTransform !== undefined ? opts.useCssTransform : false
this._direction = opts.direction || 'all'; // 'all', 'vertical', 'horizontal'
this._region = opts.region || null; // Added region option
this._container.style.position = "relative"
this._container.appendChild(this._baseEl)
this._baseEl.style.position = "absolute"
this._baseEl.style.display = "none"
this._container.appendChild(this._stickEl)
this._stickEl.style.position = "absolute"
this._stickEl.style.display = "none"
this._pressed = false;
this._touchIdx = null;
if(this._stationaryBase === true){
this._baseEl.style.display = "";
this._baseEl.style.left = (this._baseX - this._baseEl.width /2)+"px";
this._baseEl.style.top = (this._baseY - this._baseEl.height/2)+"px";
}
this._transform = this._useCssTransform ? this._getTransformProperty() : false;
this._has3d = this._check3D();
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
this._$onTouchStart = __bind(this._onTouchStart , this);
this._$onTouchEnd = __bind(this._onTouchEnd , this);
this._$onTouchMove = __bind(this._onTouchMove , this);
this._container.addEventListener( 'touchstart' , this._$onTouchStart , false );
this._container.addEventListener( 'touchend' , this._$onTouchEnd , false );
this._container.addEventListener( 'touchmove' , this._$onTouchMove , false );
if( this._mouseSupport ){
this._$onMouseDown = __bind(this._onMouseDown , this);
this._$onMouseUp = __bind(this._onMouseUp , this);
this._$onMouseMove = __bind(this._onMouseMove , this);
this._container.addEventListener( 'mousedown' , this._$onMouseDown , false );
this._container.addEventListener( 'mouseup' , this._$onMouseUp , false );
this._container.addEventListener( 'mousemove' , this._$onMouseMove , false );
}
}
VirtualJoystick.prototype.destroy = function()
{
this._container.removeChild(this._baseEl);
this._container.removeChild(this._stickEl);
this._container.removeEventListener( 'touchstart' , this._$onTouchStart , false );
this._container.removeEventListener( 'touchend' , this._$onTouchEnd , false );
this._container.removeEventListener( 'touchmove' , this._$onTouchMove , false );
if( this._mouseSupport ){
this._container.removeEventListener( 'mouseup' , this._$onMouseUp , false );
this._container.removeEventListener( 'mousedown' , this._$onMouseDown , false );
this._container.removeEventListener( 'mousemove' , this._$onMouseMove , false );
}
}
/**
* @returns {Boolean} true if touchscreen is currently available, false otherwise
*/
VirtualJoystick.touchScreenAvailable = function()
{
return 'createTouch' in document ? true : false;
}
/**
* microevents.js - https://github.com/jeromeetienne/microevent.js
*/
;(function(destObj){
destObj.addEventListener = function(event, fct){
if(this._events === undefined) this._events = {};
this._events[event] = this._events[event] || [];
this._events[event].push(fct);
return fct;
};
destObj.removeEventListener = function(event, fct){
if(this._events === undefined) this._events = {};
if( event in this._events === false ) return;
this._events[event].splice(this._events[event].indexOf(fct), 1);
};
destObj.dispatchEvent = function(event /* , args... */){
if(this._events === undefined) this._events = {};
if( this._events[event] === undefined ) return;
var tmpArray = this._events[event].slice();
for(var i = 0; i < tmpArray.length; i++){
var result = tmpArray[i].apply(this, Array.prototype.slice.call(arguments, 1))
if( result !== undefined ) return result;
}
return undefined
};
})(VirtualJoystick.prototype);
VirtualJoystick.prototype.deltaX = function(){ return this._stickX - this._baseX; }
VirtualJoystick.prototype.deltaY = function(){ return this._stickY - this._baseY; }
VirtualJoystick.prototype.up = function(){
if( this._pressed === false ) return false;
var deltaX = this.deltaX();
var deltaY = this.deltaY();
if( deltaY >= 0 ) return false;
if( Math.abs(deltaX) > 2*Math.abs(deltaY) ) return false;
return true;
}
VirtualJoystick.prototype.down = function(){
if( this._pressed === false ) return false;
var deltaX = this.deltaX();
var deltaY = this.deltaY();
if( deltaY <= 0 ) return false;
if( Math.abs(deltaX) > 2*Math.abs(deltaY) ) return false;
return true;
}
VirtualJoystick.prototype.right = function(){
if( this._pressed === false ) return false;
var deltaX = this.deltaX();
var deltaY = this.deltaY();
if( deltaX <= 0 ) return false;
if( Math.abs(deltaY) > 2*Math.abs(deltaX) ) return false;
return true;
}
VirtualJoystick.prototype.left = function(){
if( this._pressed === false ) return false;
var deltaX = this.deltaX();
var deltaY = this.deltaY();
if( deltaX >= 0 ) return false;
if( Math.abs(deltaY) > 2*Math.abs(deltaX) ) return false;
return true;
}
VirtualJoystick.prototype._onUp = function()
{
this._pressed = false;
this._stickEl.style.display = "none";
if(this._stationaryBase == false){
this._baseEl.style.display = "none";
this._baseX = this._baseY = 0;
this._stickX = this._stickY = 0;
}
}
VirtualJoystick.prototype._onDown = function(x, y)
{
this._pressed = true;
if(this._stationaryBase == false){
this._baseX = x;
this._baseY = y;
this._baseEl.style.display = "";
this._move(this._baseEl.style, (this._baseX - this._baseEl.width /2), (this._baseY - this._baseEl.height/2));
}
this._stickX = x;
this._stickY = y;
if(this._limitStickTravel === true){
var deltaX = this.deltaX();
var deltaY = this.deltaY();
var stickDistance = Math.sqrt( (deltaX * deltaX) + (deltaY * deltaY) );
if(stickDistance > this._stickRadius){
var stickNormalizedX = deltaX / stickDistance;
var stickNormalizedY = deltaY / stickDistance;
this._stickX = stickNormalizedX * this._stickRadius + this._baseX;
this._stickY = stickNormalizedY * this._stickRadius + this._baseY;
}
}
this._stickEl.style.display = "";
this._move(this._stickEl.style, (this._stickX - this._stickEl.width /2), (this._stickY - this._stickEl.height/2));
}
VirtualJoystick.prototype._onMove = function(x, y)
{
if( this._pressed === true ){
if(this._direction === 'vertical') {
this._stickY = y;
} else if(this._direction === 'horizontal') {
this._stickX = x;
} else {
this._stickX = x;
this._stickY = y;
}
if(this._limitStickTravel === true){
var deltaX = this.deltaX();
var deltaY = this.deltaY();
var stickDistance = Math.sqrt( (deltaX * deltaX) + (deltaY * deltaY) );
if(stickDistance > this._stickRadius){
var stickNormalizedX = deltaX / stickDistance;
var stickNormalizedY = deltaY / stickDistance;
if(this._direction === 'vertical') {
this._stickY = stickNormalizedY * this._stickRadius + this._baseY;
} else if(this._direction === 'horizontal') {
this._stickX = stickNormalizedX * this._stickRadius + this._baseX;
} else {
this._stickX = stickNormalizedX * this._stickRadius + this._baseX;
this._stickY = stickNormalizedY * this._stickRadius + this._baseY;
}
}
}
this._move(this._stickEl.style, (this._stickX - this._stickEl.width /2), (this._stickY - this._stickEl.height/2));
}
}
VirtualJoystick.prototype._onMouseUp = function(event)
{
return this._onUp();
}
VirtualJoystick.prototype._onMouseDown = function(event)
{
if (this._region && !this._region.contains(event.clientX, event.clientY)) return;
var x = event.clientX;
var y = event.clientY;
return this._onDown(x, y);
}
VirtualJoystick.prototype._onMouseMove = function(event)
{
var x = event.clientX;
var y = event.clientY;
return this._onMove(x, y);
}
VirtualJoystick.prototype._onTouchStart = function(event)
{
// if there is already a touch inprogress do nothing
if( this._touchIdx !== null ) return;
// notify event for validation
var isValid = this.dispatchEvent('touchStartValidation', event);
if( isValid === false ) return;
if (this._region && !this._region.contains(event.changedTouches[0].pageX, event.changedTouches[0].pageY)) return;
// dispatch touchStart
this.dispatchEvent('touchStart', event);
// get the first who changed
var touch = event.changedTouches[0];
// set the touchIdx of this joystick
this._touchIdx = touch.identifier;
// forward the action
var x = touch.pageX;
var y = touch.pageY;
return this._onDown(x, y)
}
VirtualJoystick.prototype._onTouchEnd = function(event)
{
// if there is no touch in progress, do nothing
if( this._touchIdx === null ) return;
// dispatch touchEnd
this.dispatchEvent('touchEnd', event);
// try to find our touch event
var touchList = event.changedTouches;
for(var i = 0; i < touchList.length && touchList[i].identifier !== this._touchIdx; i++);
// if touch event isnt found,
if( i === touchList.length) return;
// reset touchIdx - mark it as no-touch-in-progress
this._touchIdx = null;
event.preventDefault();
return this._onUp()
}
VirtualJoystick.prototype._onTouchMove = function(event)
{
// if there is no touch in progress, do nothing
if( this._touchIdx === null ) return;
// dispatch touchMove
this.dispatchEvent('touchMove', event);
// try to find our touch event
var touchList = event.changedTouches;
/* if (this._region && !this._region.contains(event.changedTouches[0].pageX, event.changedTouches[0].pageY)) return; */
for(var i = 0; i < touchList.length && touchList[i].identifier !== this._touchIdx; i++ );
// if touch event with the proper identifier isnt found, do nothing
if( i === touchList.length) return;
var touch = touchList[i];
var x = touch.pageX;
var y = touch.pageY;
return this._onMove(x, y)
}
/**
* build the canvas for joystick base
*/
VirtualJoystick.prototype._buildJoystickBase = function()
{
var canvas = document.createElement( 'canvas' );
canvas.width = 126;
canvas.height = 126;
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.strokeStyle = this._strokeStyle;
ctx.lineWidth = 6;
ctx.arc( canvas.width/2, canvas.width/2, 40, 0, Math.PI*2, true);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = this._strokeStyle;
ctx.lineWidth = 2;
ctx.arc( canvas.width/2, canvas.width/2, 60, 0, Math.PI*2, true);
ctx.stroke();
return canvas;
}
/**
* build the canvas for joystick stick
*/
VirtualJoystick.prototype._buildJoystickStick = function()
{
var canvas = document.createElement( 'canvas' );
canvas.width = 86;
canvas.height = 86;
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.strokeStyle = this._strokeStyle;
ctx.lineWidth = 6;
ctx.arc( canvas.width/2, canvas.width/2, 40, 0, Math.PI*2, true);
ctx.stroke();
return canvas;
}
VirtualJoystick.prototype._move = function(style, x, y)
{
if (this._transform) {
if (this._has3d) {
style[this._transform] = 'translate3d(' + x + 'px,' + y + 'px, 0)';
} else {
style[this._transform] = 'translate(' + x + 'px,' + y + 'px)';
}
} else {
style.left = x + 'px';
style.top = y + 'px';
}
}
VirtualJoystick.prototype._getTransformProperty = function()
{
var styles = [
'webkitTransform',
'MozTransform',
'msTransform',
'OTransform',
'transform'
];
var el = document.createElement('p');
var style;
for (var i = 0; i < styles.length; i++) {
style = styles[i];
if (null != el.style[style]) {
return style;
}
}
}
VirtualJoystick.prototype._check3D = function()
{
var prop = this._getTransformProperty();
// IE8<= doesn't have `getComputedStyle`
if (!prop || !window.getComputedStyle) return module.exports = false;
var map = {
webkitTransform: '-webkit-transform',
OTransform: '-o-transform',
msTransform: '-ms-transform',
MozTransform: '-moz-transform',
transform: 'transform'
};
var el = document.createElement('div');
el.style[prop] = 'translate3d(1px,1px,1px)';
document.body.insertBefore(el, null);
var val = getComputedStyle(el).getPropertyValue(map[prop]);
document.body.removeChild(el);
var exports = null != val && val.length && 'none' != val;
return exports;
}
class Region {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
contains(x, y) {
return x >= this.x && x <= this.x + this.width &&
y >= this.y && y <= this.y + this.height;
}
}
document.body.style.overflow = 'hidden';
window.addEventListener('wheel', function(e) {
e.preventDefault();
}, { passive: false });
window.addEventListener('touchmove', function(e) {
e.preventDefault();
}, { passive: false });
let speedCar = 0;
let rotation = 0;
let direction = 'S';
let middleJoystick = { x: 150 , y: 150 };
const leftCanvas = document.getElementById('coordiv-left');
const rightCanvas = document.getElementById('coordiv-right');
const middleCanvas = document.getElementById('coordiv-all')
const leftCtx = leftCanvas.getContext('2d');
const rightCtx = rightCanvas.getContext('2d');
const middleCtx = middleCanvas.getContext('2d');
const leftCenter = { x: leftCanvas.width / 2, y: leftCanvas.height / 2 };
const rightCenter = { x: rightCanvas.width / 2, y: rightCanvas.height / 2 };
const middleCenter = { x: middleCanvas.width / 2, y: middleCanvas.height / 2 }
const speedSlider = document.getElementById('speedSlider');
const slowSpeedBtn = document.getElementById('slowSpeed');
const normalSpeedBtn = document.getElementById('normalSpeed');
const fastSpeedBtn = document.getElementById('fastSpeed');
let speedMode = 1;
const setSpeedMode = (mode) => {
if (speedMode === mode) {
speedMode = 0; // Reset to zero if the same button is pressed again
slowSpeedBtn.classList.remove('active');
normalSpeedBtn.classList.remove('active');
fastSpeedBtn.classList.remove('active');
} else {
speedMode = mode;
slowSpeedBtn.classList.remove('active');
normalSpeedBtn.classList.remove('active');
fastSpeedBtn.classList.remove('active');
if (mode === 0.5) {
slowSpeedBtn.classList.add('active');
} else if (mode === 1) {
normalSpeedBtn.classList.add('active');
} else if (mode === 2) {
fastSpeedBtn.classList.add('active');
}
}
};
slowSpeedBtn.addEventListener('click', () => setSpeedMode(0.5));
normalSpeedBtn.addEventListener('click', () => setSpeedMode(1));
fastSpeedBtn.addEventListener('click', () => setSpeedMode(2));
function getCanvasCenter(canvas) {
const rect = canvas.getBoundingClientRect();
const centerX = rect.left + rect.width/2
const centerY = rect.top + rect.height/2
return { x: centerX, y: centerY };
}
function updateJoystickRegions() {
var leftRegion = new Region(0, 0, leftCanvas.width, leftCanvas.height);
var rightRegion = new Region(getCanvasCenter(rightCanvas).x - rightCanvas.width/2, 80, rightCanvas.width, rightCanvas.height);
var leftjoystick = new VirtualJoystick({
container : document.body,
strokeStyle : 'orange',
limitStickTravel: true,
stickRadius : 100,
direction: 'vertical',
region:leftRegion,
});
leftjoystick.addEventListener('touchStartValidation', function(event){
var touch = event.changedTouches[0];
if( touch.pageX >= window.innerWidth/2 ) return false;
return true
});
leftjoystick.addEventListener('touchMove', function(){
let position = -leftjoystick.deltaY()
// Normalize position to range 0-20 for speedSlider
let sliderValue = Math.abs(position/100 * 20);
speedSlider.value = sliderValue;
speedCar = sliderValue*speedMode;
if (position > 0) {
direction = 'F';
speedCar = position/100*speedMode;
} else if (position < 0) {
direction = 'B';
speedCar = position/100*speedMode;
} else {
direction = 'S';
speedCar = 0;
}
})
leftjoystick.addEventListener('touchEnd', function(){
let sliderValue = 0;
direction = 'S';
speedSlider.value = sliderValue;
speedCar = sliderValue*speedMode;
})
var rightjoystick = new VirtualJoystick({
container : document.body,
strokeStyle : 'cyan',
limitStickTravel: true,
stickRadius : 100,
direction: 'horizontal',
region: rightRegion,
});
rightjoystick.addEventListener('touchStartValidation', function(event){
var touch = event.changedTouches[0];
if( touch.pageX < window.innerWidth/2 ) return false;
return true
});
rightjoystick.addEventListener('touchMove', function(){
let position = rightjoystick.deltaX();
if (position < 0) {
direction = 'L';
rotation = position/100;
} else if (position > 0) {
direction = 'R';
rotation = position/100;
} else {
direction = 'S';
rotation = 0;
}
});
rightjoystick.addEventListener('touchEnd', function(){
direction = 'S';
rotation = 0;
})
}
const updateJoystick = function(canvas, ctx, center, joystick, locId, isLeft){
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.beginPath();
ctx.arc(center.x, center.y, 100, 0, 2 * Math.PI, false);
ctx.fillStyle = "#CCCCCC";
ctx.fill();
ctx.shadowBlur = 10;
ctx.shadowColor = "#ff9900";
ctx.strokeStyle = "#333333";
ctx.stroke();
// Constrain joystick within base circle
let dx = joystick.x - center.x;
let dy = joystick.y - center.y;
let distance = Math.sqrt(dx * dx + dy * dy);
if (distance > 100) {
dx *= 100 / distance;
dy *= 100 / distance;
joystick.x = center.x + dx;
joystick.y = center.y + dy;
}
ctx.beginPath();
ctx.arc(joystick.x, joystick.y, 200 / 4, 0, 2 * Math.PI, false);
ctx.fillStyle = "#21242d";
ctx.fill();
ctx.stroke();
ctx.closePath();
ctx.restore();
//const loc = `current position ${isLeft ? 'y' : 'x'}: ${parseInt((isLeft ? joystick.y : joystick.x) / (center.x / 5))}`;
//document.getElementById(locId).innerHTML = loc;
if (isLeft) {
let speedValue = -parseInt((joystick.y - center.y));
if (speedValue < -0.1) {
direction = 'B';
speedCar = speedValue/100*speedMode;
} else if (speedValue > 0.1) {
direction = 'F';
speedCar = speedValue/100*speedMode;
} else {
direction = 'S';
speedCar = 0;
}
speedSlider.value = Math.abs(speedValue/100 *20);
let steeringValue = (joystick.x - center.x) / 100;
if (steeringValue < 0) {
direction = 'L';
rotation = steeringValue;
} else if (steeringValue > 0) {
direction = 'R';
rotation = steeringValue;
} else {
direction = 'S';
rotation = 0;
}
}
}
let initJoystick = function(canvas, ctx, center, joystick, locId, isLeft) {
const activeTouches = {};
const getTouch = (e) => e.touches.length ? e.touches[0] : e.changedTouches[0];
const handleMovement = (e, touch) => {
const x = canvas.offsetLeft;
const y = canvas.offsetTop;
let NowX = touch ? touch.clientX - x : e.clientX - x;
let NowY = touch ? touch.clientY - y : e.clientY - y;
NowX = Math.max(0, Math.min(NowX, canvas.width));
NowY = Math.max(0, Math.min(NowY, canvas.height));
joystick.x = NowX;
joystick.y = NowY;
updateJoystick(canvas, ctx, center, joystick, locId, isLeft);
};
canvas.addEventListener('mousedown', function(e) {
handleMovement(e);
const mouseMoveHandler = (e) => handleMovement(e);
const mouseUpHandler = () => {
joystick.x = center.x;
joystick.y = center.y;
updateJoystick(canvas, ctx, center, joystick, locId, isLeft);
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
};
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
});
canvas.addEventListener('touchstart', function(e) {
const touch = getTouch(e);
handleMovement(e, touch);
activeTouches[touch.identifier] = touch;
const touchMoveHandler = (e) => {
for (let touch of e.touches) {
if (activeTouches[touch.identifier]) {
handleMovement(e, touch);
}
}
};
const touchEndHandler = (e) => {
for (let touch of e.changedTouches) {
if (activeTouches[touch.identifier]) {
joystick.x = center.x;
joystick.y = center.y;
updateJoystick(canvas, ctx, center, joystick, locId, isLeft);
delete activeTouches[touch.identifier];
}
}
};
canvas.addEventListener('touchmove', touchMoveHandler);
canvas.addEventListener('touchend', touchEndHandler);
});
};
initJoystick(middleCanvas, middleCtx, middleCenter, middleJoystick, 'point-loc-left', true);
window.onload = updateJoystickRegions;
window.onresize = updateJoystickRegions;
let loop = setInterval(function(){
SentCommand(rotation,speedCar);
}, 100);
let SentCommand = function(angle, speed){
let xhr = new XMLHttpRequest();
xhr.open("GET", "/direction?rotation=" + angle + "&speedCar=" + speed, true);
xhr.send();
}
</script>
</body>
</html>
)rawliteral";
// Next, WiFi.begin is used to connect to the WiFi network and wait for a successful connection.
// Finally, the server route is set up to respond to HTTP GET requests to the root path "/" and return an HTML page.
void setup(){
Serial.begin(115200);
bool ssid_hidden = false; // Set to true to hide the SSID
int channel = 1; // Set the WiFi channel
int max_connection = 4; // Set the maximum number of connections
// Set the ESP8266 to AP mode using the defined SSID and password
bool result = WiFi.softAP(ssid, password, channel, ssid_hidden, max_connection);
Serial.println("ESP8266 is set as a WiFi Access Point with SSID: " + String(ssid));
if (result)
{
Serial.println("Access Point Started");
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(IP);
}
else
{
Serial.println("Access Point Failed to Start");
}
// Set up the server route to respond to HTTP GET requests to the root path "/" and return an HTML page.
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send_P(200, "text/html", index_html);
Serial.print("get success!");
});
// On the server object, set up an HTTP GET route named "direction" that uses the getParam function of the request object to get the values of speedCar and dir parameters,
// which represent the speed and direction of the car, respectively.
server.on("/direction", HTTP_GET, [](AsyncWebServerRequest *request) {
float speedCar =0;
float rotation = 0;
if(request->hasParam("speedCar")){
speedCar = request->getParam("speedCar")->value().toFloat();
}
if(request->hasParam("rotation")){
rotation = request->getParam("rotation")->value().toFloat();
}
handleDirection(rotation,speedCar);
request->send(200, "text/html","receive rotation:" + String(rotation) + "receive linear speed:" + String(speedCar)) ;
});
server.begin();
}
void handleDirection(float rotation, float speedCar){
byte data[sizeof(float) * 2 + 1];
memcpy(data, &rotation, sizeof(float));
data[sizeof(float)] = 0xFF;
memcpy(data + sizeof(float) + 1, &speedCar, sizeof(float));
Serial.write(data, sizeof(data));
// Print data in a readable format
Serial.print("Data: ");
for (int i = 0; i < sizeof(data); i++) {
Serial.print(data[i], HEX); // Print each byte in hexadecimal format
Serial.print(" ");
}
Serial.println();
}
void loop(){
}