forked from nygma2004/Wifi_LokRemote
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWifi_LokRemote.ino
1018 lines (892 loc) · 29.9 KB
/
Wifi_LokRemote.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
// Aurduino IDE settings:
// Board: ESP32 Dev Board
// Upload speed: 912600
// CPU Frequency: 240 Mhz
// Flash Frequency 80 Mhz
// Flash Mode: QIO
// Flash Size: 4MB
// Partition: 1MB PROG, 3MB SPIFFS
// PSRAM: Disabled
//--------------------------------
//PINout
// D19: DRV8871 IN1
// D21: DRV8871 IN2
//MAX98357A I2S Amp
// D26: BCLK
// D25: LRC
// D22: DIN
//--------------------------------
#include <WiFi.h>
#include <WebServer.h>
#include "WiFiUdp.h"
#include "SPIFFS.h"
#include <ArduinoJson.h>
#include "AudioFileSourceSPIFFS.h"
#include "AudioFileSourceID3.h"
#include "AudioGeneratorWAV.h"
#include "AudioOutputI2SNoDAC.h"
#include "webpage.h" //Our HTML webpage contents with javascripts
#include "configpage.h" //configuration webpage
#include "settings.h"
#include "globals.h"
// These lines were required for the second task to hit the watchdog timer properly
// https://github.com/espressif/arduino-esp32/issues/595#issuecomment-423796631
#include "soc/timer_group_struct.h"
#include "soc/timer_group_reg.h"
WebServer server(80); // Web server
WiFiUDP udp;
TaskHandle_t AudioTask;
AudioGeneratorWAV *wav;
AudioFileSourceSPIFFS *file;
AudioOutputI2S *out;
// Loads the configuration from SPIFF, also setting the default configuration if JSON does not exist
bool loadConfiguration(const char *filename, Config &config, String localjson) {
// Allocate a temporary JsonDocument
// Don't forget to change the capacity to match your requirements.
// Use arduinojson.org/v6/assistant to compute the capacity.
StaticJsonDocument<1024> doc;
Serial.println("== Config Load ====");
// Open file for reading
File configfile = SPIFFS.open(filename);
if (localjson=="") {
// Set config defaults before anything
Serial.println("== Building object");
strlcpy(config.loconame,"LocoRemote",64);
strlcpy(config.wifimode,"ap",10);
strlcpy(config.ssid,"LocoRemote",30);
strlcpy(config.password,"12345678",30);
config.acceleration = 100;
config.deceleration = 100;
config.minspeed = 135;
config.maxspeed = 255;
config.volume = 2;
strlcpy(config.audio1,"Bell",20);
strlcpy(config.audio2,"Whistle",20);
strlcpy(config.audio3,"Guard",20);
strlcpy(config.audio4,"Horn",20);
strlcpy(config.light3,"Cab",20);
strlcpy(config.light4,"Engine",20);
config.stationwait = 60;
config.blindtime = 30;
strlcpy(config.stationstopsound,"none",6);
strlcpy(config.stationleavesound1,"none",6);
strlcpy(config.stationleavesound2,"none",6);
strlcpy(config.terminusstopsound,"none",6);
strlcpy(config.terminusleavesound1,"none",6);
strlcpy(config.terminusleavesound2,"none",6);
strlcpy(config.input3sound,"none",6);
strlcpy(config.input4sound,"none",6);
if(!configfile){
Serial.println("== Failed to open file for reading");
return false;
}
// Deserialize the JSON document
DeserializationError error = deserializeJson(doc, configfile);
if (error) {
Serial.print(F("== Failed to read the JSON configuration file: "));
Serial.println(error.f_str());
return false;
}
} else {
DeserializationError error = deserializeJson(doc, localjson.c_str());
if (error) {
Serial.print(F("== Failed to read the JSON data: "));
Serial.println(error.f_str());
return false;
}
}
Serial.println("== Reading JSON object");
// Copy values from the JsonDocument to the Config
if (doc.containsKey("acceleration")) {
config.acceleration = doc["acceleration"];
}
if (doc.containsKey("deceleration")) {
config.deceleration = doc["deceleration"];
}
if (doc.containsKey("minspeed")) {
config.minspeed = doc["minspeed"];
}
if (doc.containsKey("maxspeed")) {
config.maxspeed = doc["maxspeed"];
}
if (doc.containsKey("volume")) {
config.volume = doc["volume"];
out->SetGain((float)config.volume/10);
}
if (doc.containsKey("loconame")) {
strlcpy(config.loconame,doc["loconame"],64);
}
if (doc.containsKey("wifimode")) {
strlcpy(config.wifimode,doc["wifimode"],10);
}
if (doc.containsKey("ssid")) {
strlcpy(config.ssid,doc["ssid"],30);
}
if (doc.containsKey("password")) {
strlcpy(config.password,doc["password"],30);
}
if (doc.containsKey("audio1")) {
strlcpy(config.audio1,doc["audio1"],20);
}
if (doc.containsKey("audio2")) {
strlcpy(config.audio2,doc["audio2"],20);
}
if (doc.containsKey("audio3")) {
strlcpy(config.audio3,doc["audio3"],20);
}
if (doc.containsKey("audio4")) {
strlcpy(config.audio4,doc["audio4"],20);
}
if (doc.containsKey("light3")) {
strlcpy(config.light3,doc["light3"],20);
}
if (doc.containsKey("light4")) {
strlcpy(config.light4,doc["light4"],20);
}
if (doc.containsKey("stationwait")) {
config.stationwait = doc["stationwait"];
}
if (doc.containsKey("blindtime")) {
config.blindtime = doc["blindtime"];
}
if (doc.containsKey("stationstopsound")) {
strlcpy(config.stationstopsound,doc["stationstopsound"],6);
}
if (doc.containsKey("stationleavesound1")) {
strlcpy(config.stationleavesound1,doc["stationleavesound1"],6);
}
if (doc.containsKey("stationleavesound2")) {
strlcpy(config.stationleavesound2,doc["stationleavesound2"],6);
}
if (doc.containsKey("terminusstopsound")) {
strlcpy(config.terminusstopsound,doc["terminusstopsound"],6);
}
if (doc.containsKey("terminusleavesound1")) {
strlcpy(config.terminusleavesound1,doc["terminusleavesound1"],6);
}
if (doc.containsKey("terminusleavesound2")) {
strlcpy(config.terminusleavesound2,doc["terminusleavesound2"],6);
}
if (doc.containsKey("input3sound")) {
strlcpy(config.input3sound,doc["input3sound"],6);
}
if (doc.containsKey("input4sound")) {
strlcpy(config.input4sound,doc["input4sound"],6);
}
// Close the file (Curiously, File's destructor doesn't close the file)
configfile.close();
Serial.println("== Config Done =====");
return true;
}
// Conversion of the settings structure to JSON string
String ConfigToString() {
String message = "{";
message += "\"loconame\": \"";
message += config.loconame;
message += "\", \"wifimode\": \"";
message += config.wifimode;
message += "\", \"ssid\": \"";
message += config.ssid;
message += "\", \"password\": \"";
message += config.password;
message += "\", \"acceleration\": ";
message += config.acceleration;
message += ", \"deceleration\": ";
message += config.deceleration;
message += ", \"minspeed\": ";
message += config.minspeed;
message += ", \"maxspeed\": ";
message += config.maxspeed;
message += ", \"volume\": ";
message += config.volume;
message += ", \"audio1\": \"";
message += config.audio1;
message += "\", \"audio2\": \"";
message += config.audio2;
message += "\", \"audio3\": \"";
message += config.audio3;
message += "\", \"audio4\": \"";
message += config.audio4;
message += "\", \"light3\": \"";
message += config.light3;
message += "\", \"light4\": \"";
message += config.light4;
message += "\", \"stationwait\": ";
message += config.stationwait;
message += ", \"blindtime\": ";
message += config.blindtime;
message += ", \"stationstopsound\": \"";
message += config.stationstopsound;
message += "\", \"stationleavesound1\": \"";
message += config.stationleavesound1;
message += "\", \"stationleavesound2\": \"";
message += config.stationleavesound2;
message += "\", \"terminusstopsound\": \"";
message += config.terminusstopsound;
message += "\", \"terminusleavesound1\": \"";
message += config.terminusleavesound1;
message += "\", \"terminusleavesound2\": \"";
message += config.terminusleavesound2;
message += "\", \"input3sound\": \"";
message += config.input3sound;
message += "\", \"input4sound\": \"";
message += config.input4sound;
message += "\"}";
return message;
}
// HTTP request to get the current settings, called when the settings page is loaded
void handleGetSettingsRequest() {
String message;
message = ConfigToString();
Serial.println("Sending config json");
Serial.println(message);
server.send(200, "application/json", message);
}
// Saves the configuration to a file
bool saveConfiguration(const char *filename, const Config &config) {
bool result = false;
// Open file for writing
File configfile = SPIFFS.open(filename, FILE_WRITE);
if (!configfile) {
Serial.println(F("Failed to create file"));
return result;
}
// Allocate a temporary JsonDocument
// Don't forget to change the capacity to match your requirements.
// Use arduinojson.org/assistant to compute the capacity.
StaticJsonDocument<1024> doc;
result = true;
// Set the values in the document
doc["loconame"] = config.loconame;
doc["wifimode"] = config.wifimode;
doc["ssid"] = config.ssid;
doc["password"] = config.password;
doc["acceleration"] = config.acceleration;
doc["deceleration"] = config.deceleration;
doc["minspeed"] = config.minspeed;
doc["maxspeed"] = config.maxspeed;
doc["volume"] = config.volume;
doc["audio1"] = config.audio1;
doc["audio2"] = config.audio2;
doc["audio3"] = config.audio3;
doc["audio4"] = config.audio4;
doc["light3"] = config.light3;
doc["light4"] = config.light4;
doc["stationwait"] = config.stationwait;
doc["blindtime"] = config.blindtime;
doc["stationstopsound"] = config.stationstopsound;
doc["stationleavesound1"] = config.stationleavesound1;
doc["stationleavesound2"] = config.stationleavesound2;
doc["terminusstopsound"] = config.terminusstopsound;
doc["terminusleavesound1"] = config.terminusleavesound1;
doc["terminusleavesound2"] = config.terminusleavesound2;
doc["input3sound"] = config.input3sound;
doc["input4sound"] = config.input4sound;
// Serialize JSON to file
if (serializeJson(doc, configfile) == 0) {
Serial.println(F("Failed to write to file"));
result = false;
}
// Close the file
configfile.close();
return result;
}
// Internal stats, not really used for anything now
void refreshStats() {
char temp[5];
webStat = "RSSI: ";
webStat += WiFi.RSSI();
webStat += "<br/>";
webStat += "Uptime [min]: ";
webStat += uptime;
webStat += "<br/>";
webStat += "Message count: ";
webStat += msgcount;
webStat += "<br/>";
}
// HTTP request to pass the new settings from the settings page back to the ESP to store the new settings
void handleUpdateSettingsRequest() {
if (server.hasArg("plain")== false){ //Check if body received
server.send(200, "text/plain", "Body not received");
return;
}
String message = "";
message += server.arg("plain");
Serial.print("Configuraiton update received: ");
Serial.println(message);
if (loadConfiguration("", config, message)) {
if (saveConfiguration(filename, config)) {
server.send(200, "text/plain", "OK");
} else {
server.send(200, "text/plain", "Saving the configuration failed");
}
} else {
server.send(200, "text/plain", "Processing the update failed");
}
}
// HTTP request to change the target speed (slider or the Stop 1/3, 1/3, Full buttons
void handleSpeedRequest() {
String message = "";
if (server.arg("speed")== "") {
message = "Speed data is missing";
}
if (message=="") {
message = server.arg("speed");
targetspeed = message.toInt();
message = "Speed " + message + " set";
}
// Send dummy response
Serial.println(message);
server.send(200, "text/html", message);
}
// HTTP request to turn the shuttle mode on and off
void handleShuttleRequest() {
String message = "Shuttle mode ";
shuttlemode = !shuttlemode;
message += (shuttlemode) ? "On" : "Off";
// Send dummy response
Serial.println(message);
server.send(200, "text/html", message);
}
// HTTP request to change the direction
void handleDirectionRequest() {
String message = "";
if (server.arg("direction")== "") {
message = "Speed data is missing";
}
if (message=="") {
message = server.arg("direction");
direction = message.toInt();
speed = 0;
targetspeed = 0;
message = "Direction set to " + message + ", speed 0";
ledcWrite(0, 0);
ledcWrite(1, 0);
SetHeadLights();
}
// Send dummy response
Serial.println(message);
server.send(200, "text/html", message);
}
// Setting the PWM signal for the motor driver based on the current speed and direction
void setMotorSpeed() {
if (speed==0) {
motorspeed = 0;
} else {
motorspeed = config.minspeed + (config.maxspeed-config.minspeed)*speed/100;
}
if (direction==0) {
// going forward
ledcWrite(0, motorspeed);
} else {
// going backward
ledcWrite(1, motorspeed);
}
}
// HTTP call from the main webpage every second, which updates the screen controls/labels
void handleStatusRequest() {
String message = "{";
message += "\"direction\": ";
message += direction;
message += ", \"speed\": ";
message += speed;
message += ", \"targetspeed\": ";
message += targetspeed;
message += ", \"motorspeed\": ";
message += motorspeed;
message += ", \"uptime\": ";
message += uptime;
message += ", \"battery\": ";
message += battery;
message += ", \"drivemode\": ";
message += drivemode;
message += ", \"stationwait\": ";
message += stationwait;
message += ", \"shuttlemode\": ";
message += shuttlemode;
message += ", \"sabertooth\": 0";
message += "}";
server.send(200, "text/html", message);
}
// Central audio selection/playing routine
void PlayWAV(const char* filename, bool stop) {
if (strcmp(filename,"slot1")==0) filename = "/01.wav";
if (strcmp(filename,"slot2")==0) filename = "/02.wav";
if (strcmp(filename,"slot3")==0) filename = "/03.wav";
if (strcmp(filename,"slot4")==0) filename = "/04.wav";
if (strcmp(filename,"slot5")==0) filename = "/05.wav";
if (strcmp(filename,"slot6")==0) filename = "/06.wav";
if (strcmp(filename,"slot7")==0) filename = "/07.wav";
if (strcmp(filename,"slot8")==0) filename = "/08.wav";
if (wav->isRunning()) {
if (stop) {
wav->stop();
} else {
return;
}
}
Serial.print("Playing audio: ");
Serial.println(filename);
file = new AudioFileSourceSPIFFS(filename);
wav->begin(file, out);
}
// HTTP request to play and audio
void handleSoundRequest() {
String message = "";
if (server.arg("sound")== "") {
message = "Sound data is missing";
}
if (message=="") {
message = server.arg("sound");
int sound = message.toInt();
switch (sound) {
case 0:
PlayWAV("/01.wav", true);
break;
case 1:
PlayWAV("/02.wav", true);
break;
case 2:
PlayWAV("/03.wav", true);
break;
case 3:
PlayWAV("/04.wav", true);
break;
}
message = "Playing sound " + message;
}
// Send dummy response
Serial.println(message);
server.send(200, "text/html", message);
}
// Turn on lights on outpu1 and output2 based on the direction
void SetHeadLights() {
if (direction==0) {
digitalWrite(LIGHT1, lightState);
digitalWrite(LIGHT2, LOW);
} else {
digitalWrite(LIGHT2, lightState);
digitalWrite(LIGHT1, LOW);
}
}
// HTTP request to turn on/off lights
void handleLightRequest() {
String message = "";
if (server.arg("id")== "") {
message = "Light id is missing";
}
if (message=="") {
message = server.arg("id");
int light = message.toInt();
switch (light) {
case 0:
lightState = !lightState;
SetHeadLights();
break;
case 3:
light3State = !light3State;
digitalWrite(LIGHT3, light3State);
break;
case 4:
light4State = !light4State;
digitalWrite(LIGHT4, light4State);
break;
}
message = "Switching light " + message;
}
// Send dummy response
Serial.println(message);
server.send(200, "text/html", message);
}
// Interrupt Service Routine for input 1 (station magnet)
void IRAM_ATTR Input1Handler() {
if (millis() - lastInput1 >= INPUTDEBOUNCE) {
lastInput1 = millis();
Serial.println("Input 1 triggered");
if ((drivemode==DRIVEMODE_DRIVING)&&(shuttlemode)&&(blindtime==0)) {
// Station magnet detected, slowing down, and set the drivemode to station break
autospeed = targetspeed;
targetspeed = 0;
drivemode=DRIVEMODE_STATIONBREAK;
Serial.println("Stopping at a station...");
}
}
}
// Interrupt Service Routine for input 2 (terminus magnet)
void IRAM_ATTR Input2Handler() {
if (millis() - lastInput2 >= INPUTDEBOUNCE) {
lastInput2 = millis();
Serial.println("Input 2 triggered");
if ((drivemode==DRIVEMODE_DRIVING)&&(shuttlemode)&&(blindtime==0)) {
// Terminus magnet detected, slowing down, and set the drivemode to terminus break
autospeed = targetspeed;
targetspeed = 0;
drivemode=DRIVEMODE_TERMINUSBREAK;
Serial.println("Stopping at a terminus...");
}
}
}
// Interrupt Service Routine for input 3 (audio trigger)
void IRAM_ATTR Input3Handler() {
if (millis() - lastInput3 >= INPUTDEBOUNCE) {
lastInput3 = millis();
Serial.println("Input 3 triggered ");
// Play the sound if configured
if (strcmp(config.input3sound,"none")!=0) {
triggersound = true;
strncpy(startsound,config.input3sound,6);
}
}
}
// Interrupt Service Routine for input 4 (audio trigger)
void IRAM_ATTR Input4Handler() {
if (millis() - lastInput4 >= INPUTDEBOUNCE) {
lastInput4 = millis();
Serial.println("Input 4 triggered ");
// Play the sound if configured
if (strcmp(config.input4sound,"none")!=0) {
triggersound = true;
strncpy(startsound,config.input4sound,6);
}
}
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// SETUP
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
void setup() {
Serial.begin(115200);
Serial.println("LocoRemote");
pinMode(BUILTIN_LED, OUTPUT);
pinMode(MOTORIN1, OUTPUT);
pinMode(MOTORIN2, OUTPUT);
pinMode(LIGHT1, OUTPUT);
pinMode(LIGHT2, OUTPUT);
pinMode(LIGHT3, OUTPUT);
pinMode(LIGHT4, OUTPUT);
pinMode(INPUT1, INPUT_PULLUP);
pinMode(INPUT2, INPUT_PULLUP);
pinMode(INPUT3, INPUT);
pinMode(INPUT4, INPUT);
ledcAttachPin(MOTORIN1,0); // assign the speed control PWM pin to a channel
ledcAttachPin(MOTORIN2,1); // assign the speed control PWM pin to a channel
// initialize channel 0-15, resolution 1-16 bit, frequency limit depend on resolution
ledcSetup(0,PWMFREQ,8); // channel- 0, frequency- 4000, Resolution bit- 8
ledcSetup(1,PWMFREQ,8); // channel- 0, frequency- 4000, Resolution bit- 8
uptime = 0;
msgcount = 0;
// Loading the audio objects
audioLogger = &Serial;
out = new AudioOutputI2S();
wav = new AudioGeneratorWAV();
out->SetGain(0.2);
if(!SPIFFS.begin(true)){
Serial.println("An Error has occurred while mounting SPIFFS");
}
// List all the files in the SPPIFS
Serial.println("===== SPIFFS file list ======");
File root = SPIFFS.open("/");
File filelister = root.openNextFile();
while(filelister){
Serial.print("FILE: ");
Serial.println(filelister.name());
filelister = root.openNextFile();
}
// End of SPIFFS list
loadConfiguration(filename, config,"");
delay(100);
Serial.println();
// Configured for Station Mode
if (strcmp(config.wifimode,"sta")==0) {
Serial.print("Connecting to wifi network");
WiFi.begin(config.ssid, config.password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
digitalWrite(BUILTIN_LED, uptime % 2 == 0);
uptime++;
}
uptime = 0;
digitalWrite(BUILTIN_LED, LOW);
Serial.println("");
Serial.print("Connected to ");
Serial.println(config.ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("Signal [RSSI]: ");
Serial.println(WiFi.RSSI());
}
// Configured for Access Point
if (strcmp(config.wifimode,"ap")==0) {
Serial.println("Setting up Access Point...");
WiFi.softAP(config.ssid, config.password);
Serial.print("Access Point: ");
Serial.println(config.ssid);
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(IP);
server.begin();
}
server.on("/", [](){ // main page
String s = webPage; //Read HTML contents
server.send(200, "text/html", s); //Send web page
});
server.on("/config", [](){ // config page
String s = configPage; //Read HTML contents
server.send(200, "text/html", s); //Send config page
});
server.on("/setspeed", handleSpeedRequest);
server.on("/setdirection", handleDirectionRequest);
server.on("/play", handleSoundRequest);
server.on("/light", handleLightRequest);
server.on("/status", handleStatusRequest);
server.on("/shuttle", handleShuttleRequest);
server.on("/getsettings", handleGetSettingsRequest);
server.on("/updatesettings", handleUpdateSettingsRequest);
server.begin();
Serial.println("HTTP server started");
refreshStats();
//Setup the task for the audio playing
xTaskCreatePinnedToCore(
codeForAudioTask, /* Task function. */
"AudioTask", /* name of task. */
10240, /* Stack size of task - this needed to be enhanced */
NULL, /* parameter of the task */
1, /* priority of the task */
&AudioTask, /* Task handle to keep track of created task */
1); /* Core */
// Configure the input interrupts
attachInterrupt(INPUT1, Input1Handler, FALLING);
attachInterrupt(INPUT2, Input2Handler, FALLING);
attachInterrupt(INPUT3, Input3Handler, FALLING);
attachInterrupt(INPUT4, Input4Handler, FALLING);
if (udp.begin(4444)) {
Serial.print("UDP running at IP: ");
Serial.print(WiFi.localIP());
Serial.println(" port: 4444");
}
}
// Audio thread handler which is responsible for keeping the audio buffer topped up when the audio is playing
void codeForAudioTask( void * parameter ) {
for (;;) {
TIMERG0.wdt_wprotect=TIMG_WDT_WKEY_VALUE;
TIMERG0.wdt_feed=1;
TIMERG0.wdt_wprotect=0;
if (wav->isRunning()) {
if (!wav->loop()) wav->stop();
} else {
//Serial.printf("MP3 done\n");
//delay(1000);
}
//vTaskDelay(1000/portTICK_PERIOD_MS);
}
}
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// LOOP
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
void loop() {
// Handle HTTP server requests
server.handleClient();
// play a sound triggered by the interrupt
// this was required to keep the ISR short and not short dump due to WDT
if (triggersound) {
if (!wav->isRunning()) {
PlayWAV(startsound, true);
}
triggersound = false;
}
// Acceleration and Deceleration
//if ((drivemode==DRIVEMODE_MANUAL)||(drivemode==DRIVEMODE_STATIONBREAK)) {
if (speed!=targetspeed) {
if (speed>targetspeed) {
if (millis()-lastSpeed>config.deceleration) {
speed--;
setMotorSpeed();
lastSpeed = millis();
}
} else {
if (millis()-lastSpeed>config.acceleration) {
speed++;
setMotorSpeed();
lastSpeed = millis();
}
}
}
//}
// Stopped at the station
if (drivemode==DRIVEMODE_STATIONBREAK) {
if (speed==0) {
drivemode=DRIVEMODE_STATIONSTOP;
stationwait = config.stationwait;
Serial.println("Stopped at a station");
if (strcmp(config.stationstopsound,"none")!=0) {
PlayWAV(config.stationstopsound, true);
}
}
}
// At the station
if (drivemode==DRIVEMODE_STATIONSTOP) {
// Time to play the sound 1
if ((stationwait==10)&&(strcmp(config.stationleavesound1,"none")!=0)&&(!wav->isRunning())) {
PlayWAV(config.stationleavesound1, true);
}
// Time to leave the station
if (stationwait==0) {
// Play sound 2
if (strcmp(config.stationleavesound2,"none")!=0) {
PlayWAV(config.stationleavesound2, true);
}
drivemode=DRIVEMODE_DRIVING;
targetspeed = autospeed;
blindtime = config.blindtime;
autospeed = 0;
Serial.println("Leaving the station");
}
}
// Stopped at the terminus
if (drivemode==DRIVEMODE_TERMINUSBREAK) {
if (speed==0) {
drivemode=DRIVEMODE_TERMINUSSTOP;
stationwait = config.stationwait;
Serial.println("Stopped at a terminus");
if (strcmp(config.terminusstopsound,"none")!=0) {
PlayWAV(config.terminusstopsound, true);
}
}
}
// At the terminus
if (drivemode==DRIVEMODE_TERMINUSSTOP) {
// Time to play the sound 1
if ((stationwait==10)&&(strcmp(config.terminusleavesound1,"none")!=0)&&(!wav->isRunning())) {
PlayWAV(config.terminusleavesound1, true);
}
// Time to leave the terminus
if (stationwait==0) {
// Play sound 2
if (strcmp(config.terminusleavesound2,"none")!=0) {
PlayWAV(config.terminusleavesound2, true);
}
if (direction==0) {
direction=1;
} else {
direction=0;
}
SetHeadLights();
drivemode=DRIVEMODE_DRIVING;
targetspeed = autospeed;
blindtime = config.blindtime;
autospeed = 0;
Serial.println("Leaving the terminus");
}
}
// Uptime calculation (every minute)
if (millis() - lastMinute >= 60000) {
lastMinute = millis();
uptime++;
}
// second calculation
if (millis() - lastSecond >= 1000) {
lastSecond = millis();
sec++;
if (sec%10==0) {
refreshStats();
}
// Battery level check
battery = (float)analogRead(BATTERYMONITOR) / 4096 * 33 * 11111 / 11000 * 1.1;
//Battery average calculation - average the last 10 readings
if (battarrcount<BATTARRSIZE-1) {
battarr[battarrcount] = battery;
battarrcount++;
} else {
for(int i=1; i<BATTARRSIZE; i++) {
battarr[i-1]=battarr[i];
}
battarr[BATTARRSIZE-1]=battery;
}
battery = 0;
for(int i=0; i<battarrcount; i++) {
battery += battarr[i];
}
battery = battery / battarrcount;
// If we are waiting at the station, decrement the counter
if (stationwait>0) {
stationwait--;
Serial.print("Wait time left: ");
Serial.println(stationwait);
}
// count down the blindtime
if (blindtime>0) blindtime--;
// reconnect to the wifi network in station mode if connection is lost
if ((config.wifimode=="sta")&&(WiFi.status() != WL_CONNECTED)) {
Serial.println("Reconnecting to wifi...");
WiFi.reconnect();
}
}
// check if data is getting through UDP
int packetSize = udp.parsePacket();
if (packetSize) {
UDPActive = true;
lastUDP = millis();
//Serial.print("UDP received: ");
//Serial.print(" Sender: ");
//Serial.print(udp.remoteIP());
//Serial.print(":");
//Serial.print(udp.remotePort());
int len = udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
}
//Serial.print(", Message lenght: ");
//Serial.print(len);
//Serial.print(", Payload: ");
//Serial.write(packetBuffer, len);
//Serial.println();
if (motorspeed == 0) {
// only change the direction if the motor is stopped
direction = packetBuffer[0];
}
targetspeed = packetBuffer[1];
byte bits = packetBuffer[2];
if (lightState!=((bits & (1 << 7)) == (1 << 7))) {
lightState=((bits & (1 << 7)) == (1 << 7));
SetHeadLights();
}
if (light3State!=((bits & (1 << 6)) == (1 << 6))) {
light3State=((bits & (1 << 6)) == (1 << 6));
digitalWrite(LIGHT3, light3State);
}
if (light4State!=((bits & (1 << 5)) == (1 << 5))) {
light4State=((bits & (1 << 5)) == (1 << 5));
digitalWrite(LIGHT4, light4State);
}
if (packetBuffer[3]>0) {
switch (packetBuffer[3]) {
case 1:
PlayWAV("slot1", false);
break;
case 2:
PlayWAV("slot2", false);
break;
case 3:
PlayWAV("slot3", false);
break;
case 4:
PlayWAV("slot4", false);
break;
case 5:
PlayWAV("slot5", false);
break;
case 6:
PlayWAV("slot6", false);
break;
}
}