-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFF_WebServer.cpp
More file actions
2743 lines (2357 loc) · 89.1 KB
/
FF_WebServer.cpp
File metadata and controls
2743 lines (2357 loc) · 89.1 KB
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
/*!
FF_WebServer
This library implements on ESP8266 a fully asynchronous Web server with:
- MQTT connection
- Arduino and Web OTA
- local file system to host user and server files
- file and/or browser based settings
- full file editor/upload/download
- optional telnet or serial or MQTT debug commands
- optional serial and/or syslog trace
- optional external hardware watchdog
- optional Domoticz connectivity
This code is based on a highly modified version of https://github.com/FordPrfkt/FSBrowserNG,
itself a fork of https://github.com/gmag11/FSBrowserNG, not anymore maintained.
Written and maintained by Flying Domotic (https://github.com/FlyingDomotic/FF_WebServer)
*/
#include "FF_WebServer.hpp"
#include <StreamString.h>
#define XQUOTE(x) #x
#define QUOTE(x) XQUOTE(x)
const char Page_WaitAndReload[] PROGMEM = R"=====(
<meta http-equiv="refresh" content="10; URL=/config.html">
Please Wait....Configuring and Restarting.
)=====";
const char Page_Restart[] PROGMEM = R"=====(
<meta http-equiv="refresh" content="10; URL=/general.html">
Please Wait....Configuring and Restarting.
)=====";
// ----- Trace -----
extern trace_declare();
char deviceName[33];
// ----- Remote debug -----
#ifdef REMOTE_DEBUG
extern RemoteDebug Debug;
#endif
#if defined(ESP8266)
extern "C" {bool system_update_cpu_freq(uint8_t freq);} // ESP8266 SDK
#endif
// ----- Web server -----
void AsyncFFWebServer::error404(AsyncWebServerRequest *request) {
if (this->error404Callback) {
if (this->error404Callback(request)) {
return;
}
}
request->send(404, "text/plain", "FileNotFound");
}
/*
Perform URL percent decoding.
Decoding is done in-place and will modify the parameter.
*/
void AsyncFFWebServer::percentDecode(char *src) {
char *dst = src;
while (*src) {
if (*src == '+') {
src++;
*dst++ = ' ';
} else if (*src == '%') {
// handle percent escape
*dst = '\0';
src++;
if (*src >= '0' && *src <= '9') {*dst = *src++ - '0';}
else if (*src >= 'A' && *src <= 'F') {*dst = 10 + *src++ - 'A';}
else if (*src >= 'a' && *src <= 'f') {*dst = 10 + *src++ - 'a';}
*dst <<= 4;
if (*src >= '0' && *src <= '9') {*dst |= *src++ - '0';}
else if (*src >= 'A' && *src <= 'F') {*dst |= 10 + *src++ - 'A';}
else if (*src >= 'a' && *src <= 'f') {*dst |= 10 + *src++ - 'a';}
dst++;
} else {
*dst++ = *src++;
}
}
*dst = '\0';
}
/*!
Parse an URL parameters list and return each parameter and value in a given table.
\note WARNING! This function overwrites the content of this string. Pass this function a copy if you need the value preserved.
\param[in,out] queryString: parameters string which is to be parsed (will be overwritten)
\param[out] results: place to put the pairs of parameter name/value (will be overwritten)
\param[in] resultsMaxCt: maximum number of results, = sizeof(results)/sizeof(*results)
\param[in] decodeUrl: if this is true, then url escapes will be decoded as per RFC 2616
\return Number of parameters returned in results
*/
int AsyncFFWebServer::parseUrlParams (char *queryString, char *results[][2], const int resultsMaxCt, const boolean decodeUrl) {
int ct = 0;
while (queryString && *queryString && ct < resultsMaxCt) {
results[ct][0] = strsep(&queryString, "&");
results[ct][1] = strchr(results[ct][0], '=');
if (*results[ct][1]) *results[ct][1]++ = '\0';
if (decodeUrl) {
percentDecode(results[ct][0]);
percentDecode(results[ct][1]);
}
ct++;
}
return ct;
}
// ---- MQTT ----
// Test MQTT configuration
boolean AsyncFFWebServer::mqttTest() {
if (configMQTT_Host == "" || configMQTT_Port == 0 || configMQTT_Interval == 0 ||configMQTT_Topic == "") {
return false;
} else {
return true;
}
}
// Connect to MQTT
void AsyncFFWebServer::connectToMqtt(void) {
// (Re)connect only if MQTT initialized, not connected to MQTT and network connected
if (mqttInitialized && !mqttClient.connected() && WiFi.status() == WL_CONNECTED) {
// Wait for 30 seconds between connection tries
if (((millis() - lastMqttConnectTime) >= 30000) || !lastMqttConnectTime) {
lastMqttConnectTime = millis();
if (FF_WebServer.debugFlag) trace_debug_P("Connecting to MQTT...", NULL);
mqttClient.connect();
}
}
}
// Called on MQTT connection
void AsyncFFWebServer::onMqttConnect(bool sessionPresent) {
if (FF_WebServer.debugFlag) trace_debug_P("Connected to MQTT, session present: %d", sessionPresent);
// Send a "we're up" message
char tempBuffer[100];
snprintf_P(tempBuffer, sizeof(tempBuffer), PSTR("{\"state\":\"up\",\"version\":\"%s/%s\"}"), FF_WebServer.userVersion.c_str(), FF_WebServer.serverVersion.c_str());
FF_WebServer.mqttPublishRaw(FF_WebServer.mqttWillTopic.c_str(), tempBuffer, true);
if (FF_WebServer.debugFlag) trace_debug_P("LWT = %s", tempBuffer);
if (FF_WebServer.mqttConnectCallback) {
FF_WebServer.mqttConnectCallback();
}
if (FF_WebServer.configMQTT_CommandTopic != "") {
FF_WebServer.mqttSubscribeRaw(FF_WebServer.configMQTT_CommandTopic.c_str());
}
}
// Called on MQTT disconnection
void AsyncFFWebServer::onMqttDisconnect(AsyncMqttClientDisconnectReason disconnectReason) {
if (FF_WebServer.debugFlag) trace_debug_P("Disconnected from MQTT, reason %d", disconnectReason);
if (FF_WebServer.mqttDisconnectCallback) {
FF_WebServer.mqttDisconnectCallback(disconnectReason);
}
}
// Called after MQTT subscription acknowledgment
void AsyncFFWebServer::onMqttSubscribe(uint16_t packetId, uint8_t qos) {
if (FF_WebServer.debugFlag) trace_debug_P("Subscribe done, packetId %d, qos %d", packetId, qos);
}
// Called after MQTT unsubscription acknowledgment
void AsyncFFWebServer::onMqttUnsubscribe(uint16_t packetId) {
if (FF_WebServer.debugFlag) trace_debug_P("Unsubscribe done, packetId %d", packetId);
}
// Called when an MQTT subscribed message is received
void AsyncFFWebServer::onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
// Take care of (very) long payload that comes in multiple messages
char localPayload[len+1];
strncpy(localPayload, payload, len);
localPayload[len] = 0;
if (FF_WebServer.traceFlag) trace_info_P("Received: topic %s, payload %s, len %d, index %d, total %d", topic, localPayload, len, index, total);
// Do we have a MQTT command topic defined?
if (FF_WebServer.configMQTT_CommandTopic != "") {
// Is this topic the same?
if (strcmp(topic, FF_WebServer.configMQTT_CommandTopic.c_str()) == 0) {
// Yes, execute (debug) command
FF_WebServer.executeCommand(String(localPayload));
return;
}
}
if (FF_WebServer.mqttMessageCallback) {
FF_WebServer.mqttMessageCallback(topic, payload, properties, len, index, total);
}
}
// Called after full MQTT message sending
void AsyncFFWebServer::onMqttPublish(uint16_t packetId) {
if (FF_WebServer.debugFlag) trace_debug_P("Publish done, packetId %d", packetId);
}
/*!
Subscribe to one MQTT subtopic (main topic will be prepended)
\param[in] subTopic: subTopic to send message to (main topic will be prepended)
\param[in] qos: quality of service associated with subscription (default to 0)
\return true if subscription if successful, false else
*/
bool AsyncFFWebServer::mqttSubscribe (const char *subTopic, const int qos) {
char topic[80];
snprintf_P(topic, sizeof(topic), PSTR("%s/%s"), configMQTT_Topic.c_str(), subTopic);
return mqttSubscribeRaw(topic, qos);
}
/*!
Subscribe to one MQTT subtopic (main topic will NOT be prepended)
\param[in] topic: topic to send message to (main topic will be prepended)
\param[in] qos: quality of service associated with subscription (default to 0)
\return true if subscription if successful, false else
*/
bool AsyncFFWebServer::mqttSubscribeRaw (const char *topic, const int qos) {
bool status = mqttClient.subscribe(topic, qos);
if (FF_WebServer.debugFlag) trace_debug_P("subscribed to %s, qos=%d, status=%d", topic, qos, status);
return status;
}
/*!
Publish one MQTT subtopic (main topic will be prepended)
\param[in] subTopic: subTopic to send message to (main topic will be prepended)
\param[in] value: value to send to subTopic
\return none
*/
void AsyncFFWebServer::mqttPublish (const char *subTopic, const char *value, bool retain) {
char topic[80];
snprintf_P(topic, sizeof(topic), PSTR("%s/%s"), configMQTT_Topic.c_str(), subTopic);
mqttPublishRaw(topic, value, retain);
}
/*!
Publish one MQTT topic (main topic will NOT be prepended)
\param[in] topic: topic to send message to (main topic will NOT be prepended)
\param[in] value: value to send to topic
\return none
*/
void AsyncFFWebServer::mqttPublishRaw (const char *topic, const char *value, bool retain) {
uint16_t packetId = mqttClient.publish(topic, 1, retain, value);
if (debugFlag) trace_debug_P("publish %s = %s, retain=%d, packedId %d", topic, value, retain, packetId);
}
// ----- Domoticz -----
#ifdef INCLUDE_DOMOTICZ
// Domoticz is supported on (asynchronous) MQTT
/*!
Send a message to Domoticz for an Energy meter
\param idx: Domoticz device's IDX to send message to
\param power: instant power value
\param energy: total energy value
\return none
*/
void AsyncFFWebServer::sendDomoticzPower (const int idx, const float power, const float energy) {
char url[150];
snprintf_P(url, sizeof(url), PSTR("%.3f;%.3f;0;0;0;0"), power, energy * 1000.0);
this->sendDomoticzValues(idx, url);
}
/*!
Send a message to Domoticz for a switch
\param[in] idx: Domoticz device's IDX to send message to
\param[in] isOn: if true, sends device on, else device off
\return none
*/
void AsyncFFWebServer::sendDomoticzSwitch (const int idx, const bool isOn) {
char url[150];
snprintf_P(url, sizeof(url), PSTR("\"switchlight\", \"idx\": %d, \"switchcmd\": \"%s\""), idx, isOn ? "On" : "Off");
this->sendDomoticz(url);
}
/*!
Send a message to Domoticz for a dimmer
\param[in] idx: Domoticz device's IDX to send message to
\param[in] level: level value to send
\return none
*/
// Send a message to Domoticz for a dimmer
void AsyncFFWebServer::sendDomoticzDimmer (const int idx, const uint8_t level) {
char url[150];
snprintf_P(url, sizeof(url), PSTR("\"switchlight\", \"idx\": %d, \"switchcmd\":\"Set Level\", \"level\": %d"), idx, level);
this->sendDomoticz(url);
}
/*!
Send a message to Domoticz with nValue and sValue
\param[in] idx: Domoticz device's IDX to send message to
\param[in] values: comma separated values to send to Domoticz as sValue
\param[in] integer: numeric value to send to Domoticz as nValue
\return none
*/
void AsyncFFWebServer::sendDomoticzValues (const int idx, const char *values, const int integer) {
char url[250];
snprintf_P(url, sizeof(url), PSTR("\"udevice\", \"idx\": %d, \"nvalue\": %d, \"svalue\": \"%s\""), idx, integer, values);
this->sendDomoticz(url);
}
// Compute Domoticz signal level
uint8_t AsyncFFWebServer::mapRSSItoDomoticz(void) {
long rssi = WiFi.RSSI();
if (-50 < rssi) {return 10;}
if (rssi <= -98) {return 0;}
rssi = rssi + 97; // Range 0..97 => 1..9
return (rssi / 5) + 1;
}
// Compute Domoticz battery level
uint8_t AsyncFFWebServer::mapVccToDomoticz(void) {
#if FEATURE_ADC_VCC
// Voltage range from 2.6V .. 3.6V => 0..100%
if (vcc < 2.6) {return 0;}
return (vcc - 2.6) * 100;
#else // if FEATURE_ADC_VCC
return 255;
#endif // if FEATURE_ADC_VCC
}
// Send a message to Domoticz
void AsyncFFWebServer::sendDomoticz(const char* url){
// load full URL
char fullUrl[200];
snprintf_P(fullUrl, sizeof(fullUrl), PSTR("{\"command\": %s, \"rssi\": %d, \"battery\": %d}"), url, this->mapRSSItoDomoticz(), this->mapVccToDomoticz());
mqttPublishRaw("domoticz/in", fullUrl, true);
}
#endif
/*!
Reset trace keep alive timer
Automatically called by default trace callback.
To be called by user's callback if automatic trace callback is disabled (FF_DISABLE_DEFAULT_TRACE defined).
\param None
\return None
*/
#ifdef FF_TRACE_KEEP_ALIVE
void AsyncFFWebServer::resetTraceKeepAlive(void) {
lastTraceMessage = millis();
}
#endif
// Called each time system or user config is changed
void AsyncFFWebServer::loadConfig(void) {
if (FF_WebServer.traceFlag) trace_info_P("Load config", NULL);
load_user_config("MQTTHost", configMQTT_Host);
load_user_config("MQTTPass", configMQTT_Pass);
load_user_config("MQTTPort", configMQTT_Port);
load_user_config("MQTTTopic", configMQTT_Topic);
load_user_config("MQTTCommandTopic", configMQTT_CommandTopic);
load_user_config("MQTTUser", configMQTT_User);
load_user_config("MQTTClientID", configMQTT_ClientID);
load_user_config("MQTTInterval", configMQTT_Interval);
#ifdef FF_TRACE_USE_SYSLOG
load_user_config("SyslogServer", syslogServer);
load_user_config("SyslogPort", syslogPort);
#endif
}
// Called each time system or user config is changed
void AsyncFFWebServer::loadUserConfig(void) {
if (FF_WebServer.traceFlag) trace_info_P("Load user config", NULL);
if (configChangedCallback) {
configChangedCallback();
}
}
// Class definition
AsyncFFWebServer::AsyncFFWebServer(uint16_t port) : AsyncWebServer(port) {
#if defined(SERIAL_COMMAND_PREFIX) || !defined(NO_SERIAL_COMMAND_CALLBACK)
// Clear serialBuffer
memset(serialCommand, 0, sizeof(serialCommand));
#endif
}
// Called each second
void AsyncFFWebServer::s_secondTick(void* arg) {
AsyncFFWebServer* self = reinterpret_cast<AsyncFFWebServer*>(arg);
if (self->_evs.count() > 0) {
self->sendTimeData();
}
//Check WiFi connection timeout if enabled
#if (AP_ENABLE_TIMEOUT > 0)
if (self->wifiStatus == FS_STAT_CONNECTING) {
if (++self->connectionTimout >= AP_ENABLE_TIMEOUT){
DEBUG_ERROR_P("Connection Timeout, switching to AP Mode", NULL);
self->configureWifiAP();
}
}
#endif //AP_ENABLE_TIMEOUT
}
// Send time data
void AsyncFFWebServer::sendTimeData() {
String timeData = PSTR("{\"time\":\"") + NTP.getTimeStr() + PSTR("\",")
+ PSTR("\"date\":\"") + NTP.getDateStr() + PSTR("\",")
+ PSTR("\"lastSync\":\"") + NTP.getTimeDateString(NTP.getLastNTPSync()) + PSTR("\",")
+ PSTR("\"uptime\":\"") + NTP.getUptimeString() + PSTR("\",")
+ PSTR("\"lastBoot\":\"") + NTP.getTimeDateString(NTP.getLastBootTime()) + PSTR("\"")
+ PSTR("}\r\n");
DEBUG_VERBOSE(timeData.c_str());
_evs.send(timeData.c_str(), "timeDate");
timeData = String();
}
// Format a size in B(ytes), KB, MB or GB
String AsyncFFWebServer::formatBytes(size_t bytes) {
if (bytes < 1024) {
return String(bytes) + "B";
} else if (bytes < (1024 * 1024)) {
return String(bytes / 1024.0) + "KB";
} else if (bytes < (1024 * 1024 * 1024)) {
return String(bytes / 1024.0 / 1024.0) + "MB";
} else {
return String(bytes / 1024.0 / 1024.0 / 1024.0) + "GB";
}
}
#if (CONNECTION_LED >= 0)
// Flash LED
// *** Warning *** Not asynchronous, will block CPU for delayTime * times * 2 milliseconds
void AsyncFFWebServer::flashLED(const int pin, const int times, int delayTime) {
int oldState = digitalRead(pin);
DEBUG_VERBOSE_P("---Flash LED during %d ms %d times. Old state = %d", delayTime, times, oldState);
for (int i = 0; i < times; i++) {
digitalWrite(pin, LOW); // Turn on LED
delay(delayTime);
digitalWrite(pin, HIGH); // Turn on LED
delay(delayTime);
}
digitalWrite(pin, oldState); // Turn on LED
}
#endif
// Return standard help message
String AsyncFFWebServer::standardHelpCmd() {
return String(PSTR("vars -> dump standard variables\r\n"
"user -> dump user variables\r\n"
"debug -> toggle debug flag\r\n"
"trace -> toggle trace flag\r\n"
"wdt -> toggle watchdog flag\r\n"));
}
/*!
Initialize FF_WebServer class
To be called in setup()
Will try to connect to WiFi only during the first 10 seconds of life.
\param[in] fs: (Little) file system to use
\param[in] version: user's code version (used in trace)
\return None
*/
void AsyncFFWebServer::begin(FS* fs, const char *version) {
_fs = fs;
userVersion = String(version);
connectionTimout = 0;
// ----- Global trace ----
// Register Serial trace callback
#ifndef FF_DISABLE_DEFAULT_TRACE
trace_register((void (*)(traceLevel_t, const char*, uint16_t, const char*, const char*))&AsyncFFWebServer::defaultTraceCallback);
#endif
loadConfig();
if (!load_config()) { // Try to load configuration from file system
defaultConfig(); // Load defaults if any error
_apConfig.APenable = true;
}
loadHTTPAuth();
// Register Wifi Events
onStationModeConnectedHandler = WiFi.onStationModeConnected([this](WiFiEventStationModeConnected data) {
this->onWiFiConnected(data);
});
onStationModeDisconnectedHandler = WiFi.onStationModeDisconnected([this](WiFiEventStationModeDisconnected data) {
this->onWiFiDisconnected(data);
});
onStationModeGotIPHandler = WiFi.onStationModeGotIP([this](WiFiEventStationModeGotIP data) {
this->onWiFiConnectedGotIP(data);
});
#ifdef FF_TRACE_USE_SYSLOG
#undef __FILENAME__ // Deactivate standard macro, only supporting "/" as separator
#define __FILENAME__ (strrchr(__FILE__, '\\')? strrchr(__FILE__, '\\') + 1 : (strrchr(__FILE__, '/')? strrchr(__FILE__, '/') + 1 : __FILE__))
if (syslogServer != "") {
syslog.server(syslogServer.c_str(), syslogPort);
syslog.deviceHostname(deviceName);
syslog.defaultPriority(LOG_LOCAL0 + LOG_DEBUG);
syslog.appName(__FILENAME__);
}
#endif
uint32_t chipId = 0;
// Force client id if empty or starts with "ESP_" and not right chip id
char tempBuffer[16];
chipId = ESP.getChipId();
snprintf_P(tempBuffer, sizeof(tempBuffer), PSTR("ESP_%x"), chipId);
if ((configMQTT_ClientID == "") || (configMQTT_ClientID.startsWith("ESP_") && strcmp(configMQTT_ClientID.c_str(), tempBuffer))) {
configMQTT_ClientID = tempBuffer;
FF_WebServer.save_user_config("MQTTClientID", configMQTT_ClientID);
}
WiFi.hostname(_config.deviceName.c_str());
////WiFi.forceSleepWake();
////WiFi.setSleepMode(WIFI_NONE_SLEEP);
#if (AP_ENABLE_BUTTON >= 0)
if (_apConfig.APenable) {
configureWifiAP(); // Set AP mode if AP button was pressed
} else {
configureWifi(); // Set WiFi config
}
#else
configureWifi(); // Set WiFi config
#endif
// Wait for Wifi up in first 10 seconds of life
#if (WIFI_MAX_WAIT_SECS >=1)
unsigned long startWait = millis();
while ((WiFi.status() != WL_CONNECTED) && ((millis() - startWait) <= (WIFI_MAX_WAIT_SECS * 1000))) {
yield();
}
#endif
// The following let time for WiFi to properly initialize and stabilize, allowing then syslog to work immediatly
delay(1000);
trace_debug_P("WiFi status = %d (%sconnected)", WiFi.status(), (WiFi.status() != WL_CONNECTED) ? "NOT ":"");
if (_config.updateNTPTimeEvery > 0) { // Enable NTP sync
NTP.begin(_config.ntpServerName, _config.timezone / 10, _config.daylight);
NTP.setInterval(15, _config.updateNTPTimeEvery * 60);
}
#ifdef REMOTE_DEBUG
// Initialize RemoteDebug
Debug.begin(FF_WebServer.getDeviceName().c_str()); // Initialize the WiFi server
if (_httpAuth.wwwPassword != "") {
Debug.setPassword(_httpAuth.wwwPassword.c_str()); // Password on telnet connection
}
Debug.setResetCmdEnabled(true); // Enable the reset command
Debug.showProfiler(true); // Profiler (Good to measure times, to optimize codes)
Debug.showColors(true); // Colors
//Debug.setSerialEnabled(true); // if you wants serial echo - only recommended if ESP is plugged in USB
// Set help message
Debug.setHelpProjectsCmds(PSTR("help -> display full help message"));
Debug.setCallBackProjectCmds((void(*)())&AsyncFFWebServer::executeDebugCommand);
#endif
#ifdef SERIAL_DEBUG
extern boolean _debugActive; // Debug is only active after receive first data from Serial
extern uint8_t _debugLevel; // Current level of debug (init as disabled)
extern bool _debugShowProfiler; // Show profiler time ?
_debugActive = true;
_debugLevel = DEBUG_LEVEL_VERBOSE;
_debugShowProfiler = false;
#endif
struct rst_info *rtc_info = system_get_rst_info();
// Send reset reason
trace_info_P("%s V%s/%s starting, reset reason: %x - %s", FF_WebServer.getDeviceName().c_str(), FF_WebServer.userVersion.c_str(), FF_WebServer.serverVersion.c_str(), rtc_info->reason, ESP.getResetReason().c_str());
// In case of software restart, send additional info
if (rtc_info->reason == REASON_WDT_RST || rtc_info->reason == REASON_EXCEPTION_RST || rtc_info->reason == REASON_SOFT_WDT_RST) {
// If crashed, print exception
if (rtc_info->reason == REASON_EXCEPTION_RST) {
trace_error_P("Fatal exception (%d):", rtc_info->exccause);
}
trace_error_P("epc1=0x%08x, epc2=0x%08x, epc3=0x%08x, excvaddr=0x%08x, depc=0x%08x", rtc_info->epc1, rtc_info->epc2, rtc_info->epc3, rtc_info->excvaddr, rtc_info->depc);
}
if (mqttTest()) {
mqttClient.onConnect((void(*)(bool))&AsyncFFWebServer::onMqttConnect);
mqttClient.onDisconnect((void (*)(AsyncMqttClientDisconnectReason))&AsyncFFWebServer::onMqttDisconnect);
mqttClient.onSubscribe((void (*)(uint16_t, uint8_t))&AsyncFFWebServer::onMqttSubscribe);
mqttClient.onUnsubscribe((void (*)(uint16_t))&AsyncFFWebServer::onMqttUnsubscribe);
mqttClient.onMessage((void (*)(char*, char*, AsyncMqttClientMessageProperties, size_t, size_t, size_t)) &AsyncFFWebServer::onMqttMessage);
mqttClient.onPublish((void (*)(uint16_t))&AsyncFFWebServer::onMqttPublish);
if (configMQTT_ClientID != "") {
mqttClient.setClientId(configMQTT_ClientID.c_str());
}
if (configMQTT_User != "") {
mqttClient.setCredentials(configMQTT_User.c_str(), configMQTT_Pass.c_str());
}
mqttWillTopic = configMQTT_Topic + "/LWT";
mqttClient.setWill(mqttWillTopic.c_str(), 1, true, "{\"state\":\"down\"}");
mqttClient.setServer(configMQTT_Host.c_str(), configMQTT_Port);
} else {
trace_error_P("MQTT config error: Host %s Port %d User %s Pass %s Id %s Topic %s Interval %d",
configMQTT_Host.c_str(), configMQTT_Port, configMQTT_User.c_str(), configMQTT_Pass.c_str(),
configMQTT_ClientID.c_str(), configMQTT_Topic.c_str(), configMQTT_Interval);
}
#ifdef HARDWARE_WATCHDOG_PIN
pinMode(HARDWARE_WATCHDOG_PIN, OUTPUT);
hardwareWatchdogState = HARDWARE_WATCHDOG_INITIAL_STATE;
digitalWrite(HARDWARE_WATCHDOG_PIN, hardwareWatchdogState ? HIGH : LOW);
hardwareWatchdogDelay = hardwareWatchdogState ? HARDWARE_WATCHDOG_ON_DELAY : HARDWARE_WATCHDOG_OFF_DELAY;
#endif
#ifdef DEBUG_FF_WEBSERVER
#ifdef FF_TRACE_USE_SERIAL
Serial.setDebugOutput(true);
#endif
#ifdef FF_TRACE_USE_SERIAL1
Serial1.setDebugOutput(true);
#endif
#endif // DEBUG_FF_WEBSERVER
// NTP client setup
#if (CONNECTION_LED >= 0)
pinMode(CONNECTION_LED, OUTPUT); // CONNECTION_LED pin defined as output
digitalWrite(CONNECTION_LED, HIGH); // Turn LED off
#endif
#if (AP_ENABLE_BUTTON >= 0)
pinMode(AP_ENABLE_BUTTON, INPUT_PULLUP); // If this pin is HIGH during startup ESP will run in AP_ONLY mode. Backdoor to change WiFi settings when configured WiFi is not available.
_apConfig.APenable = !digitalRead(AP_ENABLE_BUTTON); // Read AP button. If button is pressed activate AP
DEBUG_VERBOSE_P("AP Enable = %d", _apConfig.APenable);
#endif
if (!_fs) // If LitleFS is not started
_fs->begin();
#ifdef DEBUG_FF_WEBSERVER
// List files
Dir dir = _fs->openDir("/");
while (dir.next()) {
String fileName = dir.fileName();
size_t fileSize = dir.fileSize();
DEBUG_VERBOSE_P("FS File: %s, size: %s", fileName.c_str(), formatBytes(fileSize).c_str());
}
#endif // DEBUG_FF_WEBSERVER
_secondTk.attach(1.0f, (void (*) (void*)) &AsyncFFWebServer::s_secondTick, static_cast<void*>(this)); // Task to run periodic things every second
AsyncWebServer::begin(); // Start underlying AsyncWebServer class
serverInit(); // Configure and start Web server
#ifndef DISABLE_MDNS
MDNS.begin(_config.deviceName.c_str());
MDNS.addService("http", "tcp", 80);
#endif
ConfigureOTA(_httpAuth.wwwPassword.c_str());
serverStarted = true;
loadUserConfig();
if (mqttTest()) {
mqttInitialized = true;
}
FF_WebServer.lastTraceLevel = trace_getLevel(); // Save current trace level
DEBUG_VERBOSE_P("END Setup");
}
// Load config.json file
bool AsyncFFWebServer::load_config() {
File configFile = _fs->open(CONFIG_FILE, "r");
if (!configFile) {
DEBUG_ERROR_P("Failed to open %s", CONFIG_FILE);
return false;
}
size_t size = configFile.size();
/*if (size > 1024) {
DEBUG_VERBOSE_P("Config file size is too large");
configFile.close();
return false;
}*/
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
// We don't use String here because ArduinoJson library requires the input
// buffer to be mutable. If you don't use ArduinoJson, you may as well
// use configFile.readString instead.
configFile.readBytes(buf.get(), size);
configFile.close();
DEBUG_VERBOSE_P("JSON file size: %d bytes", size);
JsonDocument jsonDoc;
auto error = deserializeJson(jsonDoc, buf.get());
if (error) {
DEBUG_ERROR_P("Failed to parse %s. Error: %s", CONFIG_FILE, error.c_str());
return false;
}
#ifdef DEBUG_FF_WEBSERVER
String temp;
serializeJsonPretty(jsonDoc, temp);
DEBUG_VERBOSE_P("Config: %s", temp.c_str());
#endif
_config.ssid = jsonDoc["ssid"].as<const char *>();
_config.password = jsonDoc["pass"].as<const char *>();
_config.ip = IPAddress(jsonDoc["ip"][0], jsonDoc["ip"][1], jsonDoc["ip"][2], jsonDoc["ip"][3]);
_config.netmask = IPAddress(jsonDoc["netmask"][0], jsonDoc["netmask"][1], jsonDoc["netmask"][2], jsonDoc["netmask"][3]);
_config.gateway = IPAddress(jsonDoc["gateway"][0], jsonDoc["gateway"][1], jsonDoc["gateway"][2], jsonDoc["gateway"][3]);
_config.dns = IPAddress(jsonDoc["dns"][0], jsonDoc["dns"][1], jsonDoc["dns"][2], jsonDoc["dns"][3]);
_config.dhcp = jsonDoc["dhcp"].as<bool>();
_config.ntpServerName = jsonDoc["ntp"].as<const char *>();
_config.updateNTPTimeEvery = jsonDoc["NTPperiod"].as<long>();
_config.timezone = jsonDoc["timeZone"].as<long>();
_config.daylight = jsonDoc["daylight"].as<long>();
_config.deviceName = jsonDoc["deviceName"].as<const char *>();
strncpy(deviceName, _config.deviceName.c_str(), sizeof(deviceName));
//config.connectionLed = jsonDoc["led"];
DEBUG_VERBOSE_P("Data initialized, SSID: %s, PASS %s, NTP Server: %s", _config.ssid.c_str(), _config.password.c_str(), _config.ntpServerName.c_str());
return true;
}
// Save default config
void AsyncFFWebServer::defaultConfig() {
// DEFAULT CONFIG
_config.ssid = "WIFI_SSID";
_config.password = "WIFI_PASSWD";
_config.dhcp = 1;
_config.ip = IPAddress(192, 168, 1, 4);
_config.netmask = IPAddress(255, 255, 255, 0);
_config.gateway = IPAddress(192, 168, 1, 1);
_config.dns = IPAddress(192, 168, 1, 1);
_config.ntpServerName = "pool.ntp.org";
_config.updateNTPTimeEvery = 15;
_config.timezone = 10;
_config.daylight = 1;
_config.deviceName = "FF_WebServer";
//config.connectionLed = CONNECTION_LED;
save_config();
}
// Save current config to file
bool AsyncFFWebServer::save_config() {
//flag_config = false;
DEBUG_VERBOSE_P("Save config");
JsonDocument jsonDoc;
jsonDoc["ssid"] = _config.ssid;
jsonDoc["pass"] = _config.password;
JsonArray jsonip = jsonDoc["ip"].to<JsonArray>();
jsonip.add(_config.ip[0]);
jsonip.add(_config.ip[1]);
jsonip.add(_config.ip[2]);
jsonip.add(_config.ip[3]);
JsonArray jsonNM = jsonDoc["netmask"].to<JsonArray>();
jsonNM.add(_config.netmask[0]);
jsonNM.add(_config.netmask[1]);
jsonNM.add(_config.netmask[2]);
jsonNM.add(_config.netmask[3]);
JsonArray jsonGateway = jsonDoc["gateway"].to<JsonArray>();
jsonGateway.add(_config.gateway[0]);
jsonGateway.add(_config.gateway[1]);
jsonGateway.add(_config.gateway[2]);
jsonGateway.add(_config.gateway[3]);
JsonArray jsondns = jsonDoc["dns"].to<JsonArray>();
jsondns.add(_config.dns[0]);
jsondns.add(_config.dns[1]);
jsondns.add(_config.dns[2]);
jsondns.add(_config.dns[3]);
jsonDoc["dhcp"] = _config.dhcp;
jsonDoc["ntp"] = _config.ntpServerName;
jsonDoc["NTPperiod"] = _config.updateNTPTimeEvery;
jsonDoc["timeZone"] = _config.timezone;
jsonDoc["daylight"] = _config.daylight;
jsonDoc["deviceName"] = _config.deviceName;
File configFile = _fs->open(CONFIG_FILE, "w");
if (!configFile) {
DEBUG_ERROR_P("Failed to open %s for writing", CONFIG_FILE);
configFile.close();
return false;
}
#ifdef DEBUG_FF_WEBSERVER
String temp;
serializeJsonPretty(jsonDoc, temp);
DEBUG_VERBOSE_P("Saved config: %s", temp.c_str());
#endif
serializeJson(jsonDoc, configFile);
configFile.flush();
configFile.close();
return true;
}
/*!
Clear system configuration
\param[in] reset: reset ESP if true
\return None
*/
void AsyncFFWebServer::clearConfig(bool reset)
{
if (_fs->exists(CONFIG_FILE)) {
_fs->remove(CONFIG_FILE);
}
if (_fs->exists(SECRET_FILE)) {
_fs->remove(SECRET_FILE);
}
if (reset) {
_fs->end();
ESP.restart();
}
}
/*!
Load an user's configuration String
\param[in] name: item name to return
\param[out] value: returned (String) value
\return false if error detected, true else
*/
bool AsyncFFWebServer::load_user_config(String name, String &value) {
File configFile = _fs->open(USER_CONFIG_FILE, "r");
if (!configFile) {
DEBUG_ERROR_P("Failed to open %s", USER_CONFIG_FILE);
return false;
}
size_t size = configFile.size();
/*if (size > 1024) {
DEBUG_ERROR_P("Config file size is too large");
configFile.close();
return false;
}*/
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
// We don't use String here because ArduinoJson library requires the input
// buffer to be mutable. If you don't use ArduinoJson, you may as well
// use configFile.readString instead.
configFile.readBytes(buf.get(), size);
configFile.close();
DEBUG_VERBOSE_P("JSON file size: %d bytes", size);
JsonDocument jsonDoc;
auto error = deserializeJson(jsonDoc, buf.get());
if (error) {
DEBUG_ERROR_P("Failed to parse %s. Error: %s", USER_CONFIG_FILE, error.c_str());
return false;
}
value = jsonDoc[name].as<const char*>();
#ifdef DEBUG_FF_WEBSERVER
DEBUG_VERBOSE_P("User config: %s=%s", name.c_str(), value.c_str());
#endif
return true;
}
// Save one user config item (String)
bool AsyncFFWebServer::save_user_config(String name, String value) {
//add logic to test and create if non
DEBUG_VERBOSE_P("%s: %s", name.c_str(), value.c_str());
File configFile;
if (!_fs->exists(USER_CONFIG_FILE)) {
configFile = _fs->open(USER_CONFIG_FILE, "w");
if (!configFile) {
DEBUG_ERROR_P("Failed to open %s for writing", USER_CONFIG_FILE);
configFile.close();
return false;
}
//create blank json file
DEBUG_VERBOSE_P("Creating user %s for writing", USER_CONFIG_FILE);
configFile.print("{}");
configFile.close();
}
//get existing json file
configFile = _fs->open(USER_CONFIG_FILE, "r");
if (!configFile) {
DEBUG_ERROR_P("Failed to open %s", USER_CONFIG_FILE);
return false;
}
size_t size = configFile.size();
/*if (size > 1024) {
DEBUG_VERBOSE_P("Config file size is too large");
configFile.close();
return false;
}*/
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
// We don't use String here because ArduinoJson library requires the input
// buffer to be mutable. If you don't use ArduinoJson, you may as well
// use configFile.readString instead.
configFile.readBytes(buf.get(), size);
configFile.close();
DEBUG_VERBOSE_P("Read JSON file size: %d bytes", size);
JsonDocument jsonDoc;
auto error = deserializeJson(jsonDoc, buf.get());
if (error) {
DEBUG_ERROR_P("Failed to parse %s. Error: %s", USER_CONFIG_FILE, error.c_str());
return false;
} else {
DEBUG_VERBOSE_P("Parse User config file");
}
jsonDoc[name] = value;
configFile = _fs->open(USER_CONFIG_FILE, "w");
if (!configFile) {
DEBUG_ERROR_P("Failed to open %s for writing", USER_CONFIG_FILE);
configFile.close();
return false;
}
#ifdef DEBUG_FF_WEBSERVER
String temp;
serializeJsonPretty(jsonDoc, temp);
DEBUG_VERBOSE_P("Save user config %s", temp.c_str());
#endif
serializeJson(jsonDoc, configFile);
configFile.flush();
configFile.close();
return true;
}
/*!
Clear user configuration
\param[in] reset: reset ESP if true
\return None
*/
void AsyncFFWebServer::clearUserConfig(bool reset) {
if (_fs->exists(USER_CONFIG_FILE)) {
_fs->remove(USER_CONFIG_FILE);
}