-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathESPHomer.cpp
1219 lines (1062 loc) · 34.4 KB
/
ESPHomer.cpp
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 <stdlib.h> // for free()
#include <string.h> // for strlen, strcpy, strcat
#include <pgmspace.h> // for PSTR, strcpy_P
#include <inttypes.h> // frintf PRIu32, PRIu16, PRIu8
//#include <HashMap.h> // for Associative Arrays (__topics)
#include "Arduino.h"
extern "C" {
#include <user_interface.h>
}
#include "ESPHomer.h"
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
//#include <WINSResponder.h>
#include <ArduinoOTA.h>
/*
- Need increase the size of MQTT_MAX_PACKET_SIZE in w:\User\Documents\Arduino\libraries\PubSubClient\src\PubSubClient.h
from 128 to 512 to get MQTT working properly. This is an issue in the library
which has not been fixed yet.
*/
#include <PubSubClient.h>
#include <EEPROM.h>
#include <CRC32.h>
String resetReason(uint8_t which) {
switch (which) {
case REASON_DEFAULT_RST:
return F("normal startup by power on");
break;
case REASON_WDT_RST:
return F("hardware watch dog reset");
break;
case REASON_EXCEPTION_RST:
return F("exception reset, GPIO status won't change");
break;
case REASON_SOFT_WDT_RST:
return F("software watch dog reset, GPIO status won't change");
break;
case REASON_SOFT_RESTART:
return F("software restart ,system_restart , GPIO status won't change");
break;
case REASON_DEEP_SLEEP_AWAKE:
return F("wake up from deep-sleep");
break;
case REASON_EXT_SYS_RST:
return F("external system reset");
break;
default:
return F("Unknown");
break;
}
}
String connectionStatus(int which) {
switch ( which )
{
case WL_CONNECTED:
return F("Connected");
break;
case WL_NO_SSID_AVAIL:
return F("Network not availible");
break;
case WL_CONNECT_FAILED:
return F("Wrong password");
break;
case WL_IDLE_STATUS:
return F("Idle status");
break;
case WL_DISCONNECTED:
return F("Disconnected");
break;
default:
return F("Unknown");
break;
}
}
String disconnectReason(int which) {
switch ( which )
{
case WIFI_DISCONNECT_REASON_UNSPECIFIED:
return F("UNSPECIFIED");
break;
case WIFI_DISCONNECT_REASON_AUTH_EXPIRE:
return F("AUTH_EXPIRE");
break;
case WIFI_DISCONNECT_REASON_AUTH_LEAVE:
return F("AUTH_LEAVE");
break;
case WIFI_DISCONNECT_REASON_ASSOC_EXPIRE:
return F("ASSOC_EXPIRE");
break;
case WIFI_DISCONNECT_REASON_ASSOC_TOOMANY:
return F("ASSOC_TOOMANY");
break;
case WIFI_DISCONNECT_REASON_NOT_AUTHED:
return F("NOT_AUTHED");
break;
case WIFI_DISCONNECT_REASON_NOT_ASSOCED:
return F("NOT_ASSOCED");
break;
case WIFI_DISCONNECT_REASON_ASSOC_LEAVE:
return F("ASSOC_LEAVE");
break;
case WIFI_DISCONNECT_REASON_ASSOC_NOT_AUTHED:
return F("ASSOC_NOT_AUTHED");
break;
case WIFI_DISCONNECT_REASON_DISASSOC_PWRCAP_BAD:
return F("DISASSOC_PWRCAP_BAD");
break;
case WIFI_DISCONNECT_REASON_DISASSOC_SUPCHAN_BAD:
return F("DISASSOC_SUPCHAN_BAD");
break;
case WIFI_DISCONNECT_REASON_IE_INVALID:
return F("IE_INVALID");
break;
case WIFI_DISCONNECT_REASON_MIC_FAILURE:
return F("MIC_FAILURE");
break;
case WIFI_DISCONNECT_REASON_4WAY_HANDSHAKE_TIMEOUT:
return F("4WAY_HANDSHAKE_TIMEOUT");
break;
case WIFI_DISCONNECT_REASON_GROUP_KEY_UPDATE_TIMEOUT:
return F("GROUP_KEY_UPDATE_TIMEOUT");
break;
case WIFI_DISCONNECT_REASON_IE_IN_4WAY_DIFFERS:
return F("IE_IN_4WAY_DIFFERS");
break;
case WIFI_DISCONNECT_REASON_GROUP_CIPHER_INVALID:
return F("GROUP_CIPHER_INVALID");
break;
case WIFI_DISCONNECT_REASON_AKMP_INVALID:
return F("AKMP_INVALID");
break;
case WIFI_DISCONNECT_REASON_UNSUPP_RSN_IE_VERSION:
return F("UNSUPP_RSN_IE_VERSION");
break;
case WIFI_DISCONNECT_REASON_INVALID_RSN_IE_CAP:
return F("INVALID_RSN_IE_CAP");
break;
case WIFI_DISCONNECT_REASON_802_1X_AUTH_FAILED:
return F("802_1X_AUTH_FAILED");
break;
case WIFI_DISCONNECT_REASON_CIPHER_SUITE_REJECTED:
return F("CIPHER_SUITE_REJECTED");
break;
case WIFI_DISCONNECT_REASON_BEACON_TIMEOUT:
return F("BEACON_TIMEOUT");
break;
case WIFI_DISCONNECT_REASON_NO_AP_FOUND:
return F("NO_AP_FOUND");
break;
case WIFI_DISCONNECT_REASON_AUTH_FAIL:
return F("AUTH_FAIL");
break;
case WIFI_DISCONNECT_REASON_ASSOC_FAIL:
return F("ASSOC_FAIL");
break;
case WIFI_DISCONNECT_REASON_HANDSHAKE_TIMEOUT:
return F("HANDSHAKE_TIMEOUT");
break;
default:
return F("-=Unknown=-");
break;
}
}
ESPHomer::ESPHomer(const char *espname)
: timeClient(ntpUDP, HOMER_NTP_SERVER, 0, 3600000),
// You can specify the time server pool and the offset (in seconds, can be
// changed later with setTimeOffset() ). Additionaly you can specify the
// update interval (in milliseconds, can be changed using setUpdateInterval() ).
//initNTPClient(ntpUDP, HOMER_NTP_SERVER, 0, 3600000);
client(espClient)
//: s_winsResponder(&ntpUDP);
{
_espname = espname;
topic_count = (sizeof(base_topics)/sizeof(char *));
setCallback(NULL);
onCommand(NULL);
onShutdown(NULL);
}
ESPHomer::~ESPHomer() {
free(_ssid);
free(_pass);
}
char* ESPHomer::getSSID() {
return _ssid;
}
char* ESPHomer::getPASS() {
return _pass;
}
void ESPHomer::setAppVer(const char* ver) {
appver = ver;
}
void ESPHomer::setVccAdj(int16_t adj) {
_VCC_ADJ = adj;
}
void ESPHomer::setSSID(const char *ssid, const char *pass) {
_ssid = (char *)ssid;
_pass = (char *)pass;
}
void ESPHomer::setOTA(const char *pass) {
_ota_pass = (char *)pass;
}
void ESPHomer::setMQTT(const char *host, uint16_t port) {
_mqtt_server = (char *)host;
_mqtt_port = port;
}
void ESPHomer::setNTP(const char *host) {
_ntp_server = (char *)host;
}
void ESPHomer::setStatusPeriod(uint32_t ms) {
_statusPeriod = ms;
}
void ESPHomer::pinLed(int8_t pin, uint8_t lvlLedOn) {
_pinLed = (int8_t) pin;
_lvlLedOn= lvlLedOn;
if (_pinLed >= 0) {
pinMode(_pinLed, OUTPUT);
}
}
uint8_t ESPHomer::addTopic(const char* name) {
uint8_t pl = strlen(_topic_prefix);
uint8_t nl = strlen(_espname);
uint8_t tl = strlen(name);
uint8_t memcount = sizeof(char) * (pl + nl + tl + 2);
_topics[topic_count] = (char *)malloc(memcount);
strncpy(_topics[topic_count], _topic_prefix, pl);
strncpy(_topics[topic_count]+pl, _espname, nl);
strncpy(_topics[topic_count]+pl+nl, "/", 1);
strncpy(_topics[topic_count]+pl+nl+1, name, tl+1);
topic_count++;
return topic_count-1;
}
uint8_t ESPHomer::publish(uint8_t topic_idx, const char* msg) {
return client.publish(_topics[topic_idx], msg);
}
void ESPHomer::setupSerial() {
setupSerial(115200);
}
void ESPHomer::setupSerial(int32_t speed) {
#ifdef SERIAL_DEBUG
uint32_t time1 = millis();
_serial_speed = speed;
Serial.begin(_serial_speed);
Serial.setTimeout(2000);
// Wait for serial to initialize.
while(!Serial) { }
uint32_t time2 = millis() - time1;
Serial.println("");
Serial.print("Serial: ");
Serial.print(time2);
Serial.println("ms");
#endif
}
void ESPHomer::setup_Reset() {
rst_info *resetInfo;
resetInfo = ESP.getResetInfoPtr();
_reset_reason = resetInfo->reason;
#ifdef SERIAL_DEBUG
Serial.print("[");
Serial.print(millis());
Serial.print("] Reset reason[");
Serial.print(_reset_reason);
Serial.print("]: ");
Serial.println(resetReason(_reset_reason));
#endif
}
void ESPHomer::setup() {
initTime = millis();
#ifdef SERIAL_DEBUG
Serial.print("[");
Serial.print(millis());
Serial.print("] Boot done in ");
Serial.print(initTime);
Serial.println("ms");
#endif
//setup_Serial();
setup_Reset();
setup_EEPROM();
setup_wifi();
setup_OTA();
emergency_OTA();
setup_NTP();
setup_MQTT();
#ifdef SERIAL_DEBUG
//возвращает ESP8266 chip ID, int 32bit
Serial.printf(" ESP8266 ChipId: %08X\r\n", ESP.getChipId());
//возвращает flash chip ID, int 32bit
Serial.printf(" Flash ChipId: %08X\r\n", ESP.getFlashChipId());
// возвращает размер флеш памяти в байтах, так, как его определяет SDK (может быть меньше реального размера).
Serial.printf(" Flash ChipSize: %d\r\n", ESP.getFlashChipSize());
Serial.printf(" Flash realSize: %d\r\n", ESP.getFlashChipRealSize());
// возвращает частоту флеш памяти, в Гц.
Serial.printf(" FlashChipSpeed: %d\r\n", ESP.getFlashChipSpeed());
FlashMode_t ideMode = ESP.getFlashChipMode();
Serial.printf(" Flash ide mode: %s\r\n", (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT" : ideMode == FM_DIO ? "DIO" : ideMode == FM_DOUT ? "DOUT" : "UNKNOWN"));
Serial.printf(" SDK version: "); Serial.println(ESP.getSdkVersion());
Serial.print("[");
Serial.print(millis());
Serial.print("] Ready [");
Serial.print(_espname);
Serial.println("]");
#endif
}
/*void ESPHomer::setup_Serial() {
#ifdef SERIAL_DEBUG
time1 = millis();
Serial.begin(115200);
Serial.setTimeout(2000);
// Wait for serial to initialize.
while(!Serial) { }
time2 = millis() - time1;
Serial.print("Serial: ");
Serial.print(time2);
Serial.println("ms");
#endif
}
*/
//TODO
//WiFi.onSoftAPModeStationConnected(onSoftAPModeStationConnected);
//WiFi.onSoftAPModeStationDisconnected(onSoftAPModeStationDisconnected);
//WiFi.onSoftAPModeProbeRequestReceived(onSoftAPModeProbeRequestReceived);
void ESPHomer::setup_EEPROM() {
#ifdef SERIAL_DEBUG
time1 = millis();
#endif
word i;
uint8_t eeprom_data_tmp[sizeof(eeprom_data)];
uint32_t memcrc; uint8_t *p_memcrc = (uint8_t*)&memcrc;
uint8_t format; uint8_t *p_format = (uint8_t*)&format;
uint32_t datacrc;
EEPROM.begin(sizeof(eeprom_data) + sizeof(memcrc));
for (i = EEPROM_START; i < EEPROM_START+sizeof(eeprom_data); i++) {
eeprom_data_tmp[i] = EEPROM.read(i);
}
p_format[0] = eeprom_data_tmp[0];
if (format == EEPROM_FORMAT_VERSION) {
p_memcrc[0] = EEPROM.read(i++);
p_memcrc[1] = EEPROM.read(i++);
p_memcrc[2] = EEPROM.read(i++);
p_memcrc[3] = EEPROM.read(i++);
datacrc = CRC32::calculate(eeprom_data_tmp, sizeof(eeprom_data_tmp));
if (memcrc == datacrc) {
setEEPROM = true;
memcpy(&eeprom_data, eeprom_data_tmp, sizeof(eeprom_data));
}
} else {
// format UPGRADE/DOWNGRADE
if (format == 1) {
unsigned long date; uint8_t *p_date = (uint8_t*)&date;
p_date[0] = eeprom_data_tmp[1];
p_date[1] = eeprom_data_tmp[2];
p_date[2] = eeprom_data_tmp[3];
p_date[3] = eeprom_data_tmp[4];
setEEPROM = true;
// FIXME HERE - EEPROM_FORMAT_VERSION UPGRADE
eeprom_data.format = EEPROM_FORMAT_VERSION;
eeprom_data.updateTime = date;
} else
// DOWNGRADE
if (format == 2) {
unsigned long date; uint8_t *p_date = (uint8_t*)&date;
p_date[0] = eeprom_data_tmp[1];
p_date[1] = eeprom_data_tmp[2];
p_date[2] = eeprom_data_tmp[3];
p_date[3] = eeprom_data_tmp[4];
setEEPROM = true;
// FIXME HERE - EEPROM_FORMAT_VERSION UPGRADE
eeprom_data.format = EEPROM_FORMAT_VERSION;
eeprom_data.updateTime = date;
}
}
#ifdef SERIAL_DEBUG
time2 = millis() - time1;
Serial.print("[");
Serial.print(millis());
Serial.print("] EEPROM: ");
Serial.print(time2);
Serial.println("ms");
Serial.printf(" format: %u\r\n updateTime: %" PRIu32 "\r\n", eeprom_data.format, eeprom_data.updateTime);
#endif
}
void ESPHomer::setup_wifi() {
// We start by connecting to a WiFi network
#ifdef SERIAL_DEBUG
time1 = millis();
Serial.print("[");
Serial.print(millis());
Serial.print("] Start wifi for connecting to ");
Serial.println(_ssid);
#endif
//WiFi.disconnect(true);
WiFi.mode(WIFI_STA);
WiFi.persistent(false);
WiFi.setPhyMode(WIFI_PHY_MODE_11N); //WIFI_PHY_MODE_11G
WiFi.hostname(_espname);
//WiFi.setAutoConnect(true);
WiFi.setAutoReconnect(true);
//WiFi.onEvent(WiFiEvent); // depricated
stationModeConnected = WiFi.onStationModeConnected([this](const WiFiEventStationModeConnected& event) {
isTimeouted = false;
#ifdef SERIAL_DEBUG
unsigned long now = millis();
Serial.printf("[%lu] [WiFi] Connected. SSID=%s BSSID=%s ch=%u\r\n", now, event.ssid.c_str(), initMAC(event.bssid), event.channel);
#endif
});
stationModeDisconnected = WiFi.onStationModeDisconnected([this](const WiFiEventStationModeDisconnected& event) {
#ifdef SERIAL_DEBUG
unsigned long now = millis();
Serial.printf("[%lu] [WiFi] Disconnected [%d:%s] Status %d, %s\r\n", now, event.reason, disconnectReason(event.reason).c_str(), WiFi.status(), connectionStatus( WiFi.status() ).c_str() );
#endif
});
stationModeAuthModeChanged = WiFi.onStationModeAuthModeChanged([this](const WiFiEventStationModeAuthModeChanged& event) {
#ifdef SERIAL_DEBUG
unsigned long now = millis();
Serial.printf("[%lu] [WiFi] AuthMode Change %u -> %u\r\n", now, event.oldMode, event.newMode);
#endif
});
stationModeGotIP = WiFi.onStationModeGotIP([this](const WiFiEventStationModeGotIP& event) {
#ifdef SERIAL_DEBUG
unsigned long now = millis();
Serial.printf("[%lu] [WiFi] Got IP: %s, gw: %s, host=%s in %lums\r\n", now, event.ip.toString().c_str(), event.gw.toString().c_str(), WiFi.hostname().c_str(), (now - timeStartWifiConnection));
#endif
//s_winsResponder.begin(WiFi.hostname().c_str(), event.ip);
if (MDNS.begin(WiFi.hostname().c_str(), event.ip)) {
MDNS.addService("homer", "tcp", 28066);
}
#ifdef SERIAL_DEBUG
Serial.print("[");
Serial.print(millis());
Serial.println("] WINS??? and mDNS responder started");
#endif
});
stationModeDHCPTimeout = WiFi.onStationModeDHCPTimeout([this]() {
#ifdef SERIAL_DEBUG
unsigned long now = millis();
Serial.printf("[%lu] [WiFi] DHCP timeout\r\n", now);
#endif
});
//TODO
//WiFi.onSoftAPModeStationConnected(onSoftAPModeStationConnected);
//WiFi.onSoftAPModeStationDisconnected(onSoftAPModeStationDisconnected);
//WiFi.onSoftAPModeProbeRequestReceived(onSoftAPModeProbeRequestReceived);
/*
void WiFiEvent(WiFiEvent_t event) {
unsigned long now = millis();
#ifdef SERIAL_DEBUG
Serial.printf("[%d] [WiFi-event] event: %d\r\n", now, event);
#endif
case WIFI_EVENT_SOFTAPMODE_STACONNECTED:
#ifdef SERIAL_DEBUG
Serial.printf("[AP] %d, Client Connected\r\n", event);
#endif
break;
case WIFI_EVENT_SOFTAPMODE_STADISCONNECTED:
#ifdef SERIAL_DEBUG
Serial.printf("[AP] %d, Client Disconnected\r\n", event);
#endif
break;
case WIFI_EVENT_SOFTAPMODE_PROBEREQRECVED:
#ifdef SERIAL_DEBUG
Serial.printf("[AP] %d, Probe Request Recieved\r\n", event);
#endif
break;
}
}
*/
if (WiFi.status() != WL_CONNECTED) {
timeStartWifiConnection = millis();
lastWifiAttempt = timeStartWifiConnection;
isTimeouted = true;
WiFi.begin(_ssid, _pass);
/*
while (WiFi.status() != WL_CONNECTED) {
delay(500);
#ifdef SERIAL_DEBUG
Serial.print(".");
#endif
time2 = millis();
if (time2 - time1 > WIFI_CONNECT_TIMEOUT_MS) // wifi connection lasts too ling, retry
{
#ifdef SERIAL_DEBUG
Serial.println("Connection Failed! Rebooting...");
#endif
delay(1000);
ESP.restart();
yield();
}
}
*/
} else {
#ifdef SERIAL_DEBUG
Serial.println("");
Serial.println("!!! WiFi ALREADY connected !!!");
#endif
}
#ifdef SERIAL_DEBUG
time2 = millis() - time1;
Serial.print("[");
Serial.print(millis());
Serial.print("] Wifi: ");
Serial.print(time2);
Serial.println("ms");
#endif
}
void ESPHomer::setup_OTA() {
#ifdef SERIAL_DEBUG
time1 = millis();
#endif
// Port defaults to 8266
ArduinoOTA.setPort(8266);
// Hostname defaults to esp8266-[ChipID]
ArduinoOTA.setHostname(_espname);
// No authentication by default
ArduinoOTA.setPassword(_ota_pass);
/*
#ifdef SERIAL_DEBUG
Serial.print("OTA: [");
Serial.print(_ota_pass
);
Serial.println("]");
#endif
*/
ArduinoOTA.onStart([this]() {
#ifdef SERIAL_DEBUG
Serial.print("[");
Serial.print(millis());
Serial.println("] Start OTA update");
#endif
});
ArduinoOTA.onEnd([this]() {
#ifdef SERIAL_DEBUG
Serial.print("\n[");
Serial.print(millis());
Serial.println("] End OTA update");
#endif
//EPPROM set
eeprom_data.updateTime = timeClient.getEpochTime();
writeEEPROM(true);
if (shutdownHandler) {
shutdownHandler(SHUTDOWN_REASON_UPDATE);
yield();
delay(200);
}
// Dont delete this, this need for end all network job before reboot
delay(500);
});
ArduinoOTA.onProgress([this](unsigned int progress, unsigned int total) {
#ifdef SERIAL_DEBUG
Serial.printf("[%lu] OTA Progress: %u%%\r", millis(), (progress / (total / 100)));
#endif
});
ArduinoOTA.onError([this](ota_error_t error) {
#ifdef SERIAL_DEBUG
Serial.print("\n[");
Serial.print(millis());
Serial.printf("] OTA Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
#endif
});
ArduinoOTA.begin();
#ifdef SERIAL_DEBUG
time2 = millis() - time1;
Serial.print("[");
Serial.print(millis());
Serial.print("] OTA: ");
Serial.print(time2);
Serial.println("ms");
#endif
}
void ESPHomer::emergency_OTA() {
time1 = millis();
if (HOMER_EMERGENCY_OTA_MS > 0 && (_reset_reason == REASON_EXCEPTION_RST)) {
#ifdef SERIAL_DEBUG
Serial.print("[");
Serial.print(millis());
Serial.println("] emergency_OTA start");
#endif
int32_t emerg_start = millis();
while (millis() - emerg_start < 5000) {
delay(10);
if (WiFi.status() == WL_CONNECTED) {
break;
}
yield();
}
emerg_start = millis();
while (millis() - emerg_start < HOMER_EMERGENCY_OTA_MS) {
yield();
if (WiFi.status() == WL_CONNECTED) {
ArduinoOTA.handle();
}
}
#ifdef SERIAL_DEBUG
time2 = millis() - time1;
Serial.print("[");
Serial.print(millis());
Serial.print("] emergency_OTA: ");
Serial.print(time2);
Serial.println("ms");
#endif
}
}
void ESPHomer::setup_NTP() {
#ifdef SERIAL_DEBUG
time1 = millis();
#endif
timeClient.setPoolServerName(_ntp_server);
timeClient.begin();
#ifdef SERIAL_DEBUG
time2 = millis() - time1;
Serial.print("[");
Serial.print(millis());
Serial.print("] NTP: ");
Serial.print(time2);
Serial.println("ms");
#endif
}
void ESPHomer::setup_MQTT() {
#ifdef SERIAL_DEBUG
time1 = millis();
#endif
uint8_t pl = strlen(_topic_prefix);
uint8_t nl = strlen(_espname);
uint8_t i = 0;
uint8_t base_topic_count = (sizeof(base_topics)/sizeof(char *));
while(i < base_topic_count && base_topics[i]) {
uint8_t tl = strlen(base_topics[i]);
if (tl == 0) {
break;
}
/*
#ifdef SERIAL_DEBUG
Serial.print(base_topics[i]);
#endif
*/
// если ещё не было замены
if (_topics[i] == nullptr || strlen(_topics[i]) < pl || strncmp(_topic_prefix, _topics[i], pl)) {
uint8_t memcount = sizeof(char) * (pl + nl + tl + 2);
/*
#ifdef SERIAL_DEBUG
Serial.print(" ");
Serial.print(pl);
Serial.print("+");
Serial.print(nl);
Serial.print("+");
Serial.print(tl);
Serial.print("+2 = ");
Serial.println(memcount);
#endif
*/
_topics[i] = (char *)malloc(memcount);
strncpy(_topics[i], _topic_prefix, pl);
strncpy(_topics[i]+pl, _espname, nl);
strncpy(_topics[i]+pl+nl, "/", 1);
strncpy(_topics[i]+pl+nl+1, base_topics[i], tl+1);
}
i++;
}
client.setServer(_mqtt_server, _mqtt_port);
client.setCallback([this] (char* topic, byte* payload, unsigned int length) { this->_callback(topic, payload, length); });
#ifdef SERIAL_DEBUG
time2 = millis() - time1;
Serial.print("[");
Serial.print(millis());
Serial.print("] MQTT: ");
Serial.print(time2);
Serial.println("ms");
#endif
}
uint8_t ESPHomer::loop(boolean isCanReboot) {
loopState = 255; // Unknown error
#ifdef SERIAL_DEBUG
if (inited == 0) {
inited = millis();
Serial.print("[");
Serial.print(inited);
Serial.print("] INITED in ");
Serial.print(millis() - initTime);
Serial.println("ms");
}
#endif
if (millis() - lastNTPUpdate >= 1000) {
lastNTPUpdate = millis();
nowtime = timeClient.getEpochTime();
}
if (WiFi.status() == WL_CONNECTED) {
ArduinoOTA.handle();
timeClient.update();
if (!client.connected()) {
loopState = 1; // MQTT NOT connected
long now = millis();
if (now - lastReconnectAttempt > 5000) {
lastReconnectAttempt = now;
if (reconnect()) {
lastReconnectAttempt = 0;
}
}
} else {
client.loop();
StatusSend();
loopState = 0; // All OK
}
} else {
loopState = 2; // Wifi NOT connected
uint32_t now = millis();
// wifi connection lasts too ling, retry
if (isTimeouted && now - timeStartWifiConnection > WIFI_CONNECT_TIMEOUT_MS) {
loopState = 254; // REBOOTING
#ifdef SERIAL_DEBUG
Serial.println("Connection Failed! Rebooting...");
#endif
if (shutdownHandler) {
shutdownHandler(SHUTDOWN_REASON_CONN_FAIL);
yield();
delay(200);
}
delay(1000);
ESP.restart();
yield();
}
#ifdef SERIAL_DEBUG
if (now - lastWifiAttempt > 5000) {
lastWifiAttempt = now;
Serial.printf("WiFi NOT connected: [%d] %s\r\n", WiFi.status(), connectionStatus( WiFi.status() ).c_str());
}
#endif
}
// max 4294967.296 sec So - 3600296
if (millis() > 4291367000 && isCanReboot) {
loopState = 253; // RESET MILIS
if (shutdownHandler) {
shutdownHandler(SHUTDOWN_REASON_TIMER_OVERFLOW);
yield();
delay(200);
}
delay(500);
ESP.restart();
yield();
delay(500);
ESP.reset();
}
return loopState;
}
boolean ESPHomer::reconnect() {
#ifdef SERIAL_DEBUG
Serial.print("[");
Serial.print(millis());
Serial.println(F("] Attempting MQTT connection... "));
time1 = millis();
#endif
if (client.connect(_espname)) {
#ifdef SERIAL_DEBUG
time2 = millis() - time1;
time1 = millis();
Serial.print("[");
Serial.print(time1);
Serial.print("] ");
Serial.printf("mqtt.connect: %lu\r\n", time2);
#endif
unsigned long t = timeClient.getEpochTime();
String name = WiFi.SSID();
long rssi = WiFi.RSSI();
uint32_t freemem = ESP.getFreeHeap();
float vcc = ((float)ESP.getVcc())/_VCC_ADJ;
//String msg = "connected "+name+" ("+String(_espname)+") {"+getMAC()+"} ["+WiFi.localIP().toString()+"] h"+String(ESP_HOMER_VERSION)+" v"+appver+" #"+eeprom_data.updateTime+" TI:"+inited+" T:"+String(t)+" R:"+String(rssi)+" M:"+String(freemem)+" V:"+String(vcc);
char msg[MQTT_MAX_PACKET_SIZE];
const char * init_format = PSTR(R"({"act":"connected","ap":"%s","name":"%s","mac":"%s","ip":"%s","rssi":%d,"vcc":%.2f,"h":"%s","v":"%s","upd":%u,"time":%u,"inited":%u,"free":%u})");
snprintf_P(msg, sizeof(msg), init_format, name.c_str(), _espname, getMAC(), WiFi.localIP().toString().c_str(), rssi, vcc, ESP_HOMER_VERSION, appver, eeprom_data.updateTime, t, inited, freemem);
#ifdef SERIAL_DEBUG
Serial.print("[");
Serial.print(millis());
Serial.print("] ");
Serial.println(msg);
//Serial.print("size: ");
//Serial.println(msg.length());
#endif
if (!client.connected()) {
serialln(F("NOT CONNECTED !!!"));
}
client.publish(_topic_init, msg); // init
// ... and resubscribe
client.subscribe(_topics[C_LED]); // 1 - led
client.subscribe(_topics[C_CMD]); // 3 - cmd
#ifdef SERIAL_DEBUG
time2 = millis() - time1;
Serial.print("[");
Serial.print(millis());
Serial.print("] ");
Serial.printf_P(PSTR("mqtt.subscribe: %lu\r\n"), time2);
if (_firstConnect) {
_firstConnect = 0;
Serial.print("[");
Serial.print(millis());
Serial.print("] Full READY in ");
Serial.print(millis() - initTime);
Serial.println("ms");
}
#endif
return client.connected();
}
#ifdef SERIAL_DEBUG
time2 = millis() - time1;
Serial.print("[");
Serial.print(millis());
Serial.print("] failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5s");
Serial.printf("\tmqtt.connecting: %lu\r\n", time2);
#endif
return 0;
}
void ESPHomer::writeEEPROM(boolean isCommit) {
word i;
uint8_t eeprom_data_tmp[sizeof(eeprom_data)];
uint32_t memcrc; uint8_t *p_memcrc = (uint8_t*)&memcrc;
EEPROM.begin(sizeof(eeprom_data) + sizeof(memcrc));
eeprom_data.format = EEPROM_FORMAT_VERSION;
memcpy(eeprom_data_tmp, &eeprom_data, sizeof(eeprom_data));
for (i = EEPROM_START; i < EEPROM_START+sizeof(eeprom_data); i++) {
EEPROM.write(i, eeprom_data_tmp[i]);
}
memcrc = CRC32::calculate(eeprom_data_tmp, sizeof(eeprom_data_tmp));
EEPROM.write(i++, p_memcrc[0]);
EEPROM.write(i++, p_memcrc[1]);
EEPROM.write(i++, p_memcrc[2]);
EEPROM.write(i++, p_memcrc[3]);
if (isCommit) {
EEPROM.commit();
}
}
char* ESPHomer::initMAC(const uint8_t mac[WL_MAC_ADDR_LENGTH]) {
snprintf(__mac, sizeof(__mac)
, "%02X:%02X:%02X:%02X:%02X:%02X"
, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return __mac;
}
/*
String ESPHomer::showMAC(const uint8_t mac[WL_MAC_ADDR_LENGTH]) {
String resukt = String(mac[WL_MAC_ADDR_LENGTH - 6], HEX) + ":" +
String(mac[WL_MAC_ADDR_LENGTH - 5], HEX) + ":" +
String(mac[WL_MAC_ADDR_LENGTH - 4], HEX) + ":" +
String(mac[WL_MAC_ADDR_LENGTH - 3], HEX) + ":" +
String(mac[WL_MAC_ADDR_LENGTH - 2], HEX) + ":" +
String(mac[WL_MAC_ADDR_LENGTH - 1], HEX);
resukt.toUpperCase();
return resukt;
}
String ESPHomer::getMAC() {
uint8_t mac[WL_MAC_ADDR_LENGTH];
WiFi.macAddress(mac);
return showMAC(mac);
}
*/
char* ESPHomer::getMAC() {
uint8_t mac[WL_MAC_ADDR_LENGTH];
WiFi.macAddress(mac);
return initMAC(mac);
}
void ESPHomer::serialln(const char* msg) {
#ifdef SERIAL_DEBUG
Serial.println(msg);
#endif
}