-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTankRobot.ino
2011 lines (1535 loc) · 42.8 KB
/
TankRobot.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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>
#include <AsyncJson.h>
#include <VL53L1X.h>
#include <MPU6050_6Axis_MotionApps_V6_12.h>
#include <Ticker.h>
#include <Wire.h>
#include <FS.h>
#define SERIAL_BAUD 9600
#define BEEPER_PIN D7
#define BEEP_DURATION 100
#define BEEP_DELAY 30
#define AP_SSID "TankRobot"
#define AP_PASSWORD "KeepSummerSafe"
#define AP_CHANNEL 1
#define AP_MAX_CONNECTIONS 2
#define AP_HIDDEN 0
#define HTTP_PORT 80
#define HTTP_OK 200
#define HTTP_NOT_FOUND 404
#define HTTP_UNPROCESSABLE_ENTITY 422
#define BATTERY_PIN A0
#define BATTERY_SAMPLE_RATE 1000
#define VOLTMETER_RESOLUTION 1024.0
#define MIN_VOLTAGE 6.0
#define MAX_VOLTAGE 8.4
#define MOTOR_A_DIRECTION_PIN 0
#define MOTOR_A_THROTTLE_PIN 5
#define MOTOR_B_DIRECTION_PIN 2
#define MOTOR_B_THROTTLE_PIN 4
#define MIN_THROTTLE 800
#define MAX_THROTTLE 1000
#define FORWARD 1
#define REVERSE 0
#define LEFT 2
#define RIGHT 3
#define I2C_SDA_PIN D5
#define I2C_SCL_PIN D6
#define I2C_CLOCK 400000
#define MPU_ADDRESS 0x68
#define MPU_INTERRUPT_PIN 10
#define MPU_MAX_FIFO_COUNT 1024
#define LOW_PASS_FILTER_MODE 3
#define GYRO_CALIBRATION_LOOPS 8
#define QUATERNION_SAMPLE_RATE 20
#define GRAVITY_SAMPLE_RATE QUATERNION_SAMPLE_RATE
#define ORIENTATION_SAMPLE_RATE GRAVITY_SAMPLE_RATE
#define ACCEL_CALIBRATION_LOOPS 8
#define ACCEL_LSB_PER_G 16384.0
#define ACCELERATION_SAMPLE_RATE 50
#define IS_MOVING_SAMPLE_RATE ACCELERATION_SAMPLE_RATE
#define ZERO_MOVEMENT_THRESHOLD 0.13
#define ZERO_MOVEMENT_WINDOW 2
#define TEMPERATURE_SAMPLE_RATE 3000
#define TEMPERATURE_SENSITIVITY 340.0
#define TEMPERATURE_CONSTANT 36.53
#define ROTATOR_SAMPLE_RATE ORIENTATION_SAMPLE_RATE
#define ROTATOR_THRESHOLD 1.5 * DEG_TO_RAD
#define STABILIZER_SAMPLE_RATE ORIENTATION_SAMPLE_RATE
#define LIDAR_ADDRESS 0x52
#define LIDAR_TIMEOUT 500
#define LIDAR_SENSOR_OFFSET -10
#define LIDAR_TIMING_BUDGET 100000
#define LIDAR_SAMPLE_RATE 100
#define LIDAR_MAX_RANGE 3600
#define LIDAR_RANGE_VALID 0
#define LIDAR_NOISY_SIGNAL 1
#define LIDAR_SIGNAL_FAILURE 2
#define LIDAR_PHASE_OUT_OF_BOUNDS 4
#define VISIBILITY_SAMPLE_RATE 1000
#define EXPLORE_SAMPLE_RATE 250
#define SCAN_SAMPLE_RATE LIDAR_SAMPLE_RATE
#define SCAN_WINDOW 0.75 * PI
#define NUM_SCANS 5
#define MOVER_SAMPLE_RATE LIDAR_SAMPLE_RATE
#define MOVER_MAX_ACTIVATION 5000.0
#define COLLISION_SAMPLE_RATE LIDAR_SAMPLE_RATE
#define COLLISION_THRESHOLD 350
#define ROLLOVER_SAMPLE_RATE 500
#define ROLLOVER_THRESHOLD HALF_PI
#define MAX_RAND_INT 2147483647
Ticker beep_timer;
const IPAddress _ip(192, 168, 4, 1);
const IPAddress _gateway(192, 168, 4, 1);
const IPAddress _subnet(255, 255, 255, 0);
AsyncWebServer server(HTTP_PORT);
AsyncEventSource sensor_emitter("/events/robot/sensors");
AsyncEventSource training_emitter("/events/robot/training");
AsyncEventSource malfunction_emitter("/events/robot/malfunctions");
float _battery_voltage;
Ticker battery_timer;
uint8_t _direction = FORWARD;
unsigned int _throttle = 900;
bool _stopped = true;
Ticker brake_timer;
MPU6050 mpu(MPU_ADDRESS);
Quaternion _q;
VectorFloat _gravity;
VectorFloat _acceleration;
float _heading, _pitch, _roll;
float _heading_lock;
float _temperature;
bool _is_moving;
uint8_t _zero_movement_count;
uint8_t _dmp_fifo_buffer[64];
uint16_t _dmp_packet_size;
volatile bool _dmp_ready = false;
void IRAM_ATTR dmpDataReady();
Ticker quaternion_timer, gravity_timer, orientation_timer;
Ticker acceleration_timer, is_moving_timer;
Ticker temperature_timer;
float _rotator_p_gain = 2.0;
float _rotator_i_gain = 0.7;
float _rotator_d_gain = 1.4;
float _stabilizer_p_gain = 0.4;
float _stabilizer_i_gain = 0.8;
float _stabilizer_d_gain = 0.3;
float _rotator_prev_delta, _rotator_delta_integral;
float _stabilizer_prev_delta, _stabilizer_delta_integral;
Ticker rotator_timer, stabilizer_timer;
Ticker rollover_timer;
VL53L1X lidar;
float _scan_angles[NUM_SCANS];
float _angle_visibilities[NUM_SCANS];
unsigned int _distances_to_object[NUM_SCANS];
uint8_t _scan_direction = LEFT;
uint8_t _scan_count;
Ticker scan_timer, collision_timer, visibility_timer;
float _path_affinity = 2.0;
float _mover_learning_rate = 0.1;
float _mover_momentum = 0.9;
float _mover_alpha = 1e-4;
float _mover_max_overshoot = 0.2;
float _mover_features[4];
float _mover_weights[4];
float _mover_weight_velocities[4];
float _mover_bias;
float _mover_bias_velocity;
float _mover_prediction;
unsigned long _mover_start_timestamp;
unsigned long _mover_end_timestamp;
unsigned int _mover_epoch = 1;
Ticker mover_timer;
uint8_t _explorer_step;
Ticker explore_timer;
void forward(unsigned int duration = 0);
void reverse(unsigned int duration = 0);
/**
* Set up the serial interface.
*/
void setupSerial()
{
Serial.begin(SERIAL_BAUD);
Serial.println("Serial port enabled");
}
/**
* Setup the beeper.
*/
void setupBeeper()
{
pinMode(BEEPER_PIN, OUTPUT);
Serial.println("Beeper enabled");
}
/**
* Set up the central processing unit.
*/
void setupCPU()
{
Serial.print("CPU speed: ");
Serial.print(ESP.getCpuFreqMHz());
Serial.println("mhz");
}
/**
* Setup the flash ROM.
*/
void setupROM()
{
if (!ESP.checkFlashCRC()) {
Serial.println("Flash ROM CRC mismatch");
panicNow();
}
Serial.print("ROM speed: ");
Serial.print(ESP.getFlashChipSpeed() / 1000000);
Serial.println("mhz");
Serial.print("ROM size: ");
Serial.print(ESP.getFlashChipRealSize() / 1024);
Serial.println("kb");
Serial.print("Free space: ");
Serial.print(ESP.getFreeSketchSpace() / 1024.0, 1);
Serial.println("kb");
}
/**
* Set up the SPI Flash Filesystem.
*/
void setupSPIFFS()
{
if (SPIFFS.begin()) {
Serial.println("SPIFFS mounted");
} else {
Serial.println("Failed to mount SPIFFS");
panicNow();
}
}
/**
* Set up the wireless access point.
*/
void setupAccessPoint()
{
WiFi.softAPConfig(_ip, _gateway, _subnet);
WiFi.softAP(AP_SSID, AP_PASSWORD, AP_CHANNEL, AP_HIDDEN, AP_MAX_CONNECTIONS);
Serial.println("Access point ready");
Serial.print("SSID: ");
Serial.println(AP_SSID);
Serial.print("IP Address: ");
Serial.println(WiFi.softAPIP());
Serial.print("MAC Address: ");
Serial.println(WiFi.softAPmacAddress());
}
/**
* Set up the HTTP server.
*/
void setupHttpServer()
{
setupStaticRoutes();
setupApiRoutes();
setupEventEmitters();
server.onNotFound(handleNotFound);
server.begin();
Serial.print("HTTP server listening on port ");
Serial.println(HTTP_PORT);
}
/**
* Set up the HTTP static routes.
*/
void setupStaticRoutes()
{
server.serveStatic("/ui", SPIFFS, "/app.html");
server.serveStatic("/ui/control", SPIFFS, "/app.html");
server.serveStatic("/ui/dynamics", SPIFFS, "/app.html");
server.serveStatic("/ui/autonomy", SPIFFS, "/app.html");
server.serveStatic("/ui/training", SPIFFS, "/app.html");
server.serveStatic("/manifest.json", SPIFFS, "/manifest.json");
server.serveStatic("/app.js", SPIFFS, "/app.js");
server.serveStatic("/sw.js", SPIFFS, "/sw.js");
server.serveStatic("/app.css", SPIFFS, "/app.css");
server.serveStatic("/images/app-icon-small.png", SPIFFS, "/images/app-icon-small.png");
server.serveStatic("/images/app-icon-large.png", SPIFFS, "/images/app-icon-large.png");
server.serveStatic("/fonts/Roboto-300.woff2", SPIFFS, "/fonts/Roboto-300.woff2");
server.serveStatic("/fonts/Roboto-regular.woff2", SPIFFS, "/fonts/Roboto-regular.woff2");
server.serveStatic("/fonts/Roboto-500.woff2", SPIFFS, "/fonts/Roboto-500.woff2");
server.serveStatic("/fonts/fa-solid-900.woff2", SPIFFS, "/fonts/fa-solid-900.woff2");
server.serveStatic("/sounds/plucky.ogg", SPIFFS, "/sounds/plucky.ogg");
}
/**
* Set up the HTTP API routes.
*/
void setupApiRoutes()
{
server.addHandler(new AsyncCallbackJsonWebHandler("/robot/motors/direction", handleChangeDirection));
server.addHandler(new AsyncCallbackJsonWebHandler("/robot/motors/throttle", handleSetThrottlePercentage));
server.addHandler(new AsyncCallbackJsonWebHandler("/robot/rotator/left", handleRotateLeft));
server.addHandler(new AsyncCallbackJsonWebHandler("/robot/rotator/right", handleRotateRight));
server.addHandler(new AsyncCallbackJsonWebHandler("/robot/rotator/p", handleSetRotatorPGain));
server.addHandler(new AsyncCallbackJsonWebHandler("/robot/rotator/i", handleSetRotatorIGain));
server.addHandler(new AsyncCallbackJsonWebHandler("/robot/rotator/d", handleSetRotatorDGain));
server.addHandler(new AsyncCallbackJsonWebHandler("/robot/autonomy/path-affinity", handleSetPathAffinity));
server.addHandler(new AsyncCallbackJsonWebHandler("/robot/autonomy/mover/max-overshoot", handleSetMoverMaxOvershoot));
server.addHandler(new AsyncCallbackJsonWebHandler("/robot/autonomy/mover/learning-rate", handleSetMoverLearningRate));
server.addHandler(new AsyncCallbackJsonWebHandler("/robot/autonomy/mover/momentum", handleSetMoverMomentum));
server.addHandler(new AsyncCallbackJsonWebHandler("/robot/autonomy/mover/alpha", handleSetMoverAlpha));
server.addHandler(new AsyncCallbackJsonWebHandler("/robot/stabilizer/p", handleSetStabilizerPGain));
server.addHandler(new AsyncCallbackJsonWebHandler("/robot/stabilizer/i", handleSetStabilizerIGain));
server.addHandler(new AsyncCallbackJsonWebHandler("/robot/stabilizer/d", handleSetStabilizerDGain));
server.on("/robot", HTTP_GET, handleGetRobot);
server.on("/robot/motors", HTTP_DELETE, handleStop);
server.on("/robot/features/beeper", HTTP_PUT, handleBeep);
server.on("/robot/autonomy/enabled", HTTP_PUT, handleExplore);
server.on("/robot/autonomy", HTTP_DELETE, handleStop);
}
/**
* Set up the HTTP event emitters.
*/
void setupEventEmitters()
{
server.addHandler(&sensor_emitter);
server.addHandler(&training_emitter);
server.addHandler(&malfunction_emitter);
}
/**
* Set up the battery voltmeter.
*/
void setupBattery()
{
pinMode(BATTERY_PIN, INPUT);
battery_timer.attach_ms(BATTERY_SAMPLE_RATE, updateBattery);
Serial.println("Battery voltmeter enabled");
}
/**
* Set up the motors.
*/
void setupMotors()
{
pinMode(MOTOR_A_DIRECTION_PIN, OUTPUT);
pinMode(MOTOR_A_THROTTLE_PIN, OUTPUT);
pinMode(MOTOR_B_DIRECTION_PIN, OUTPUT);
pinMode(MOTOR_B_THROTTLE_PIN, OUTPUT);
analogWriteFreq(MAX_THROTTLE);
Serial.println("Motors enabled");
}
/**
* Set up the I2C bus.
*/
void setupI2C()
{
Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN);
Wire.setClock(I2C_CLOCK);
Serial.println("I2C bus initialized");
}
/**
* Set up and calibrate the MPU accelerometer, gyroscope, and temperature sensor.
*/
void setupMPU()
{
mpu.initialize();
if (mpu.testConnection()) {
Serial.println("MPU initialized");
} else {
Serial.println("MPU failure");
panicNow();
}
pinMode(MPU_INTERRUPT_PIN, INPUT);
attachInterrupt(digitalPinToInterrupt(MPU_INTERRUPT_PIN), dmpDataReady, RISING);
mpu.setFullScaleGyroRange(MPU6050_GYRO_FS_250);
mpu.setFullScaleAccelRange(MPU6050_ACCEL_FS_2);
mpu.setDLPFMode(LOW_PASS_FILTER_MODE);
Serial.print("Calibrating gyroscope ");
mpu.CalibrateGyro(GYRO_CALIBRATION_LOOPS);
Serial.println(" done");
Serial.print("Calibrating accelerometer ");
mpu.CalibrateAccel(ACCEL_CALIBRATION_LOOPS);
Serial.println(" done");
mpu.setSleepEnabled(false);
mpu.dmpInitialize();
mpu.setDMPEnabled(true);
_dmp_packet_size = mpu.dmpGetFIFOPacketSize();
quaternion_timer.attach_ms(QUATERNION_SAMPLE_RATE, updateQuaternion);
gravity_timer.attach_ms(GRAVITY_SAMPLE_RATE, updateGravity);
orientation_timer.attach_ms(ORIENTATION_SAMPLE_RATE, updateOrientation);
acceleration_timer.attach_ms(ACCELERATION_SAMPLE_RATE, updateAcceleration);
is_moving_timer.attach_ms(IS_MOVING_SAMPLE_RATE, updateIsMoving);
temperature_timer.attach_ms(TEMPERATURE_SAMPLE_RATE, updateTemperature);
Serial.println("DMP initialized");
}
/**
* Set up the lidar distance sensor.
*/
void setupLidar()
{
lidar.setTimeout(LIDAR_TIMEOUT);
if (lidar.init()) {
Serial.println("Lidar initialized");
} else {
Serial.println("Lidar failure");
panicNow();
}
lidar.setDistanceMode(VL53L1X::Long);
lidar.setMeasurementTimingBudget(LIDAR_TIMING_BUDGET);
lidar.startContinuous(LIDAR_SAMPLE_RATE);
visibility_timer.attach_ms(VISIBILITY_SAMPLE_RATE, updateVisibility);
}
/**
* Set up the random number generator.
*/
void setupRandom()
{
randomSeed(RANDOM_REG32);
Serial.println("Seeded random number generator");
}
/**
* Set up the mover model.
*/
void setupMover()
{
for (uint8_t i = 0; i < 5; ++i) {
_mover_weights[i] = random(-MAX_RAND_INT, MAX_RAND_INT) / (float)MAX_RAND_INT;
}
Serial.println("Mover model initialized");
}
/**
* Bootstrap the robot.
*/
void setup()
{
setupSerial();
setupBeeper();
setupCPU();
setupROM();
setupSPIFFS();
setupAccessPoint();
setupHttpServer();
setupBattery();
setupMotors();
setupI2C();
setupMPU();
setupLidar();
setupRandom();
setupMover();
Serial.println("Ready");
}
/**
* The main event loop.
*/
void loop()
{
if (lidar.dataReady()) {
lidar.read(false);
}
yield();
if (_dmp_ready) {
uint8_t mpu_int_status = mpu.getIntStatus();
uint16_t fifo_count = mpu.getFIFOCount();
if (mpu_int_status & 0x10 || fifo_count >= MPU_MAX_FIFO_COUNT) {
mpu.resetFIFO();
} else if (fifo_count % _dmp_packet_size != 0) {
mpu.resetFIFO();
} else if (mpu_int_status & 0x02) {
while (fifo_count >= _dmp_packet_size) {
mpu.getFIFOBytes(_dmp_fifo_buffer, _dmp_packet_size);
fifo_count -= _dmp_packet_size;
}
}
_dmp_ready = false;
}
}
/**
* Handle a get robot info request.
*/
void handleGetRobot(AsyncWebServerRequest *request)
{
StaticJsonDocument<768> doc;
char buffer[768];
JsonObject robot = doc.createNestedObject("robot");
JsonObject motors = robot.createNestedObject("motors");
motors["direction"] = _direction;
motors["throttle"] = throttlePercentage();
motors["stopped"] = _stopped;
JsonObject sensors = robot.createNestedObject("sensors");
JsonObject battery = sensors.createNestedObject("battery");
battery["voltage"] = _battery_voltage;
battery["capacity"] = batteryCapacity();
JsonObject lidar = sensors.createNestedObject("lidar");
lidar["visibility"] = visibility();
sensors["temperature"] = _temperature;
JsonObject rotator = robot.createNestedObject("rotator");
rotator["p"] = _rotator_p_gain;
rotator["i"] = _rotator_i_gain;
rotator["d"] = _rotator_d_gain;
JsonObject autonomy = robot.createNestedObject("autonomy");
autonomy["enabled"] = isAutonomous();
autonomy["pathAffinity"] = _path_affinity;
JsonObject mover = autonomy.createNestedObject("mover");
mover["learningRate"] = _mover_learning_rate;
mover["momentum"] = _mover_momentum;
mover["alpha"] = _mover_alpha;
mover["maxOvershoot"] = _mover_max_overshoot;
JsonObject importances = mover.createNestedObject("importances");
importances["throttle"] = moverThrottleImportance();
importances["battery"] = moverBatteryImportance();
importances["pitch"] = moverPitchImportance();
importances["distance"] = moverDistanceImportance();
JsonObject stabilizer = robot.createNestedObject("stabilizer");
stabilizer["p"] = _stabilizer_p_gain;
stabilizer["i"] = _stabilizer_i_gain;
stabilizer["d"] = _stabilizer_d_gain;
serializeJson(doc, buffer);
request->send(HTTP_OK, "application/json", buffer);
}
/**
* Handle a change direction request.
*/
void handleChangeDirection(AsyncWebServerRequest *request, JsonVariant &json)
{
const JsonObject &doc = json.as<JsonObject>();
if (!doc.containsKey("direction")) {
request->send(HTTP_UNPROCESSABLE_ENTITY);
return;
}
uint8_t direction = doc["direction"];
switch (direction) {
case FORWARD:
forward();
break;
case LEFT:
left();
break;
case RIGHT:
right();
break;
case REVERSE:
reverse();
break;
}
request->send(HTTP_OK);
}
/**
* Handle the stop movement request.
*/
void handleStop(AsyncWebServerRequest *request)
{
stop();
request->send(HTTP_OK);
}
/**
* Handle a beep request.
*/
void handleBeep(AsyncWebServerRequest *request)
{
beep(2);
request->send(HTTP_OK);
}
/**
* Handle the explore request.
*/
void handleExplore(AsyncWebServerRequest *request)
{
explore();
request->send(HTTP_OK);
}
/**
* Handle a set throttle position request.
*/
void handleSetThrottlePercentage(AsyncWebServerRequest *request, JsonVariant &json)
{
const JsonObject &doc = json.as<JsonObject>();
if (!doc.containsKey("throttle")) {
request->send(HTTP_UNPROCESSABLE_ENTITY);
return;
}
setThrottlePercentage(doc["throttle"]);
request->send(HTTP_OK);
}
/**
* Handle the rotate left request.
*/
void handleRotateLeft(AsyncWebServerRequest *request, JsonVariant &json)
{
const JsonObject &doc = json.as<JsonObject>();
if (!doc.containsKey("radians")) {
request->send(HTTP_UNPROCESSABLE_ENTITY);
return;
}
rotateLeft(doc["radians"]);
request->send(HTTP_OK);
}
/**
* Handle the rotate right request.
*/
void handleRotateRight(AsyncWebServerRequest *request, JsonVariant &json)
{
const JsonObject &doc = json.as<JsonObject>();
if (!doc.containsKey("radians")) {
request->send(HTTP_UNPROCESSABLE_ENTITY);
return;
}
rotateRight(doc["radians"]);
request->send(HTTP_OK);
}
/**
* Handle the set rotator proportional control gain.
*/
void handleSetRotatorPGain(AsyncWebServerRequest *request, JsonVariant &json)
{
const JsonObject &doc = json.as<JsonObject>();
if (!doc.containsKey("gain")) {
request->send(HTTP_UNPROCESSABLE_ENTITY);
return;
}
setRotatorPGain(doc["gain"]);
request->send(HTTP_OK);
}
/**
* Handle the set rotator integral control gain.
*/
void handleSetRotatorIGain(AsyncWebServerRequest *request, JsonVariant &json)
{
const JsonObject &doc = json.as<JsonObject>();
if (!doc.containsKey("gain")) {
request->send(HTTP_UNPROCESSABLE_ENTITY);
return;
}
setRotatorIGain(doc["gain"]);
request->send(HTTP_OK);
}
/**
* Handle the set rotator derivative control gain.
*/
void handleSetRotatorDGain(AsyncWebServerRequest *request, JsonVariant &json)
{
const JsonObject &doc = json.as<JsonObject>();
if (!doc.containsKey("gain")) {
request->send(HTTP_UNPROCESSABLE_ENTITY);
return;
}
setRotatorDGain(doc["gain"]);
request->send(HTTP_OK);
}
/**
* Handle the set path affinity request.
*/
void handleSetPathAffinity(AsyncWebServerRequest *request, JsonVariant &json)
{
const JsonObject &doc = json.as<JsonObject>();
if (!doc.containsKey("pathAffinity")) {
request->send(HTTP_UNPROCESSABLE_ENTITY);
return;
}
setPathAffinity(doc["pathAffinity"]);
request->send(HTTP_OK);
}
/**
* Handle the set mover max overshoot request.
*/
void handleSetMoverMaxOvershoot(AsyncWebServerRequest *request, JsonVariant &json)
{
const JsonObject &doc = json.as<JsonObject>();
if (!doc.containsKey("maxOvershoot")) {
request->send(HTTP_UNPROCESSABLE_ENTITY);
return;
}
setMoverMaxOvershoot(doc["maxOvershoot"]);
request->send(HTTP_OK);
}
/**
* Handle the set mover learning rate request.
*/
void handleSetMoverLearningRate(AsyncWebServerRequest *request, JsonVariant &json)
{
const JsonObject &doc = json.as<JsonObject>();
if (!doc.containsKey("learningRate")) {
request->send(HTTP_UNPROCESSABLE_ENTITY);
return;
}
setMoverLearningRate(doc["learningRate"]);
request->send(HTTP_OK);
}
/**
* Handle the set mover momentum request.
*/
void handleSetMoverMomentum(AsyncWebServerRequest *request, JsonVariant &json)
{
const JsonObject &doc = json.as<JsonObject>();
if (!doc.containsKey("momentum")) {
request->send(HTTP_UNPROCESSABLE_ENTITY);
return;
}
setMoverMomentum(doc["momentum"]);
request->send(HTTP_OK);
}
/**
* Handle the set mover L2 regularization parameter.
*/
void handleSetMoverAlpha(AsyncWebServerRequest *request, JsonVariant &json)
{
const JsonObject &doc = json.as<JsonObject>();
if (!doc.containsKey("alpha")) {
request->send(HTTP_UNPROCESSABLE_ENTITY);
return;
}
setMoverAlpha(doc["alpha"]);
request->send(HTTP_OK);
}
/**
* Handle the set stabilizer proportional control gain.
*/
void handleSetStabilizerPGain(AsyncWebServerRequest *request, JsonVariant &json)
{
const JsonObject &doc = json.as<JsonObject>();
if (!doc.containsKey("gain")) {
request->send(HTTP_UNPROCESSABLE_ENTITY);
return;
}
setStabilizerPGain(doc["gain"]);
request->send(HTTP_OK);
}
/**
* Handle the set stabilizer integral control gain.
*/
void handleSetStabilizerIGain(AsyncWebServerRequest *request, JsonVariant &json)
{
const JsonObject &doc = json.as<JsonObject>();
if (!doc.containsKey("gain")) {
request->send(HTTP_UNPROCESSABLE_ENTITY);
return;
}
setStabilizerIGain(doc["gain"]);
request->send(HTTP_OK);
}
/**
* Handle the set stabilizer derivative control gain.
*/
void handleSetStabilizerDGain(AsyncWebServerRequest *request, JsonVariant &json)
{
const JsonObject &doc = json.as<JsonObject>();
if (!doc.containsKey("gain")) {
request->send(HTTP_UNPROCESSABLE_ENTITY);
return;
}
setStabilizerDGain(doc["gain"]);
request->send(HTTP_OK);
}
/**
* Catch all route responds with 404.
*/
void handleNotFound(AsyncWebServerRequest *request)
{
request->send(HTTP_NOT_FOUND);
}
/**
* Move forward for an amount of milliseconds.
*/
void forward(unsigned int duration)
{
_direction = FORWARD;
enableCollisionPrevention();
enableStabilizer();
digitalWrite(MOTOR_A_DIRECTION_PIN, FORWARD);
digitalWrite(MOTOR_B_DIRECTION_PIN, FORWARD);
if (duration > 0) {
brake_timer.once_ms(duration, brake);
}
go();
}
/**
* Turn left.
*/
void left()
{
_direction = LEFT;
digitalWrite(MOTOR_A_DIRECTION_PIN, FORWARD);
digitalWrite(MOTOR_B_DIRECTION_PIN, REVERSE);
go();
}
/**
* Turn right.
*/
void right()
{
_direction = RIGHT;
digitalWrite(MOTOR_A_DIRECTION_PIN, REVERSE);
digitalWrite(MOTOR_B_DIRECTION_PIN, FORWARD);
go();
}
/**
* Move in reverse for a given number of milliseconds.
*/