/
settings.ino
1526 lines (1372 loc) · 56 KB
/
settings.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
/*
settings.ino - user settings for Tasmota
Copyright (C) 2020 Theo Arends
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*********************************************************************************************\
* RTC memory
\*********************************************************************************************/
const uint16_t RTC_MEM_VALID = 0xA55A;
uint32_t rtc_settings_crc = 0;
uint32_t GetRtcSettingsCrc(void)
{
uint32_t crc = 0;
uint8_t *bytes = (uint8_t*)&RtcSettings;
for (uint32_t i = 0; i < sizeof(RtcSettings); i++) {
crc += bytes[i]*(i+1);
}
return crc;
}
void RtcSettingsSave(void)
{
if (GetRtcSettingsCrc() != rtc_settings_crc) {
RtcSettings.valid = RTC_MEM_VALID;
#ifdef ESP8266
ESP.rtcUserMemoryWrite(100, (uint32_t*)&RtcSettings, sizeof(RtcSettings));
#else
RtcDataSettings = RtcSettings;
#endif
rtc_settings_crc = GetRtcSettingsCrc();
}
}
void RtcSettingsLoad(void)
{
#ifdef ESP8266
ESP.rtcUserMemoryRead(100, (uint32_t*)&RtcSettings, sizeof(RtcSettings)); // 0x290
#else
RtcSettings = RtcDataSettings;
#endif
if (RtcSettings.valid != RTC_MEM_VALID) {
memset(&RtcSettings, 0, sizeof(RtcSettings));
RtcSettings.valid = RTC_MEM_VALID;
RtcSettings.energy_kWhtoday = Settings.energy_kWhtoday;
RtcSettings.energy_kWhtotal = Settings.energy_kWhtotal;
RtcSettings.energy_usage = Settings.energy_usage;
for (uint32_t i = 0; i < MAX_COUNTERS; i++) {
RtcSettings.pulse_counter[i] = Settings.pulse_counter[i];
}
RtcSettings.power = Settings.power;
RtcSettingsSave();
}
rtc_settings_crc = GetRtcSettingsCrc();
}
bool RtcSettingsValid(void)
{
return (RTC_MEM_VALID == RtcSettings.valid);
}
/********************************************************************************************/
uint32_t rtc_reboot_crc = 0;
uint32_t GetRtcRebootCrc(void)
{
uint32_t crc = 0;
uint8_t *bytes = (uint8_t*)&RtcReboot;
for (uint32_t i = 0; i < sizeof(RtcReboot); i++) {
crc += bytes[i]*(i+1);
}
return crc;
}
void RtcRebootSave(void)
{
if (GetRtcRebootCrc() != rtc_reboot_crc) {
RtcReboot.valid = RTC_MEM_VALID;
#ifdef ESP8266
ESP.rtcUserMemoryWrite(100 - sizeof(RtcReboot), (uint32_t*)&RtcReboot, sizeof(RtcReboot));
#else
RtcDataReboot = RtcReboot;
#endif
rtc_reboot_crc = GetRtcRebootCrc();
}
}
void RtcRebootReset(void)
{
RtcReboot.fast_reboot_count = 0;
RtcRebootSave();
}
void RtcRebootLoad(void)
{
#ifdef ESP8266
ESP.rtcUserMemoryRead(100 - sizeof(RtcReboot), (uint32_t*)&RtcReboot, sizeof(RtcReboot)); // 0x280
#else
RtcReboot = RtcDataReboot;
#endif
if (RtcReboot.valid != RTC_MEM_VALID) {
memset(&RtcReboot, 0, sizeof(RtcReboot));
RtcReboot.valid = RTC_MEM_VALID;
// RtcReboot.fast_reboot_count = 0; // Explicit by memset
RtcRebootSave();
}
rtc_reboot_crc = GetRtcRebootCrc();
}
bool RtcRebootValid(void)
{
return (RTC_MEM_VALID == RtcReboot.valid);
}
/*********************************************************************************************\
* Config - Flash
*
* Tasmota 1M flash usage
* 0x00000000 - Unzipped binary bootloader
* 0x00001000 - Unzipped binary code start
* ::::
* 0x000xxxxx - Unzipped binary code end
* 0x000x1000 - First page used by Core OTA
* ::::
* 0x000F3000 - Tasmota Quick Power Cycle counter (SETTINGS_LOCATION - CFG_ROTATES) - First four bytes only
* 0x000F4000 - First Tasmota rotating settings page
* ::::
* 0x000FA000 - Last Tasmota rotating settings page = Last page used by Core OTA
* 0x000FB000 - Core SPIFFS end = Core EEPROM = Tasmota settings page during OTA and when no flash rotation is active (SETTINGS_LOCATION)
* 0x000FC000 - SDK - Uses first 128 bytes for phy init data mirrored by Core in RAM. See core_esp8266_phy.cpp phy_init_data[128] = Core user_rf_cal_sector
* 0x000FD000 - SDK - Uses scattered bytes from 0x340 (iTead use as settings storage from 0x000FD000)
* 0x000FE000 - SDK - Uses scattered bytes from 0x340 (iTead use as mirrored settings storage from 0x000FE000)
* 0x000FF000 - SDK - Uses at least first 32 bytes of this page - Tasmota Zigbee persistence from 0x000FF800 to 0x000FFFFF
\*********************************************************************************************/
extern "C" {
#include "spi_flash.h"
}
#include "eboot_command.h"
#ifdef ESP8266
#if AUTOFLASHSIZE
#include "flash_hal.h"
// From libraries/EEPROM/EEPROM.cpp EEPROMClass
const uint32_t SPIFFS_END = (FS_end - 0x40200000) / SPI_FLASH_SEC_SIZE;
#else
extern "C" uint32_t _FS_end;
// From libraries/EEPROM/EEPROM.cpp EEPROMClass
const uint32_t SPIFFS_END = ((uint32_t)&_FS_end - 0x40200000) / SPI_FLASH_SEC_SIZE;
#endif // AUTOFLASHSIZE
// Version 4.2 config = eeprom area
const uint32_t SETTINGS_LOCATION = SPIFFS_END; // No need for SPIFFS as it uses EEPROM area
#endif // ESP8266
// Version 5.2 allow for more flash space
const uint8_t CFG_ROTATES = 8; // Number of flash sectors used (handles uploads)
uint32_t settings_location = SETTINGS_LOCATION;
uint32_t settings_crc32 = 0;
uint8_t *settings_buffer = nullptr;
/********************************************************************************************/
/*
* Based on cores/esp8266/Updater.cpp
*/
void SetFlashModeDout(void)
{
#ifdef ESP8266
uint8_t *_buffer;
uint32_t address;
eboot_command ebcmd;
eboot_command_read(&ebcmd);
address = ebcmd.args[0];
_buffer = new uint8_t[FLASH_SECTOR_SIZE];
if (ESP.flashRead(address, (uint32_t*)_buffer, FLASH_SECTOR_SIZE)) {
if (_buffer[2] != 3) { // DOUT
_buffer[2] = 3;
if (ESP.flashEraseSector(address / FLASH_SECTOR_SIZE)) {
ESP.flashWrite(address, (uint32_t*)_buffer, FLASH_SECTOR_SIZE);
}
}
}
delete[] _buffer;
#endif // ESP8266
}
bool VersionCompatible(void)
{
#ifdef ESP8266
if (Settings.flag3.compatibility_check) {
return true;
}
eboot_command ebcmd;
eboot_command_read(&ebcmd);
uint32_t start_address = ebcmd.args[0];
uint32_t end_address = start_address + (ebcmd.args[2] & 0xFFFFF000) + FLASH_SECTOR_SIZE;
uint32_t* buffer = new uint32_t[FLASH_SECTOR_SIZE / 4];
uint32_t version[3] = { 0 };
bool found = false;
for (uint32_t address = start_address; address < end_address; address = address + FLASH_SECTOR_SIZE) {
ESP.flashRead(address, (uint32_t*)buffer, FLASH_SECTOR_SIZE);
if ((address == start_address) && (0x1F == (buffer[0] & 0xFF))) {
version[1] = 0xFFFFFFFF; // Ota file is gzipped and can not be checked for compatibility
found = true;
} else {
for (uint32_t i = 0; i < (FLASH_SECTOR_SIZE / 4); i++) {
version[0] = version[1];
version[1] = version[2];
version[2] = buffer[i];
if ((MARKER_START == version[0]) && (MARKER_END == version[2])) {
found = true;
break;
}
}
}
if (found) { break; }
}
delete[] buffer;
if (!found) { version[1] = 0; }
AddLog_P2(LOG_LEVEL_DEBUG, PSTR("OTA: Version 0x%08X, Compatible 0x%08X"), version[1], VERSION_COMPATIBLE);
if (version[1] < VERSION_COMPATIBLE) {
uint32_t eboot_magic = 0; // Abandon OTA result
ESP.rtcUserMemoryWrite(0, (uint32_t*)&eboot_magic, sizeof(eboot_magic));
return false;
}
#endif // ESP8266
return true;
}
void SettingsBufferFree(void)
{
if (settings_buffer != nullptr) {
free(settings_buffer);
settings_buffer = nullptr;
}
}
bool SettingsBufferAlloc(void)
{
SettingsBufferFree();
if (!(settings_buffer = (uint8_t *)malloc(sizeof(Settings)))) {
AddLog_P(LOG_LEVEL_DEBUG, PSTR(D_LOG_APPLICATION D_UPLOAD_ERR_2)); // Not enough (memory) space
return false;
}
return true;
}
uint16_t GetCfgCrc16(uint8_t *bytes, uint32_t size)
{
uint16_t crc = 0;
for (uint32_t i = 0; i < size; i++) {
if ((i < 14) || (i > 15)) { crc += bytes[i]*(i+1); } // Skip crc
}
return crc;
}
uint16_t GetSettingsCrc(void)
{
// Fix miscalculation if previous Settings was 3584 and current Settings is 4096 between 0x06060007 and 0x0606000A
uint32_t size = ((Settings.version < 0x06060007) || (Settings.version > 0x0606000A)) ? 3584 : sizeof(Settings);
return GetCfgCrc16((uint8_t*)&Settings, size);
}
uint32_t GetCfgCrc32(uint8_t *bytes, uint32_t size)
{
// https://create.stephan-brumme.com/crc32/#bitwise
uint32_t crc = 0;
while (size--) {
crc ^= *bytes++;
for (uint32_t j = 0; j < 8; j++) {
crc = (crc >> 1) ^ (-int(crc & 1) & 0xEDB88320);
}
}
return ~crc;
}
uint32_t GetSettingsCrc32(void)
{
return GetCfgCrc32((uint8_t*)&Settings, sizeof(Settings) -4); // Skip crc32
}
void SettingsSaveAll(void)
{
if (Settings.flag.save_state) {
Settings.power = power;
} else {
Settings.power = 0;
}
XsnsCall(FUNC_SAVE_BEFORE_RESTART);
XdrvCall(FUNC_SAVE_BEFORE_RESTART);
SettingsSave(0);
}
/*********************************************************************************************\
* Quick power cycle monitoring
\*********************************************************************************************/
void UpdateQuickPowerCycle(bool update) {
#ifndef FIRMWARE_MINIMAL
if (Settings.flag3.fast_power_cycle_disable) { return; } // SetOption65 - Disable fast power cycle detection for device reset
const uint32_t QPC_COUNT = 7; // Number of Power Cycles before Settings erase
const uint32_t QPC_SIGNATURE = 0xFFA55AFF;
#ifdef ESP8266
const uint32_t qpc_sector = SETTINGS_LOCATION - CFG_ROTATES;
const uint32_t qpc_location = qpc_sector * SPI_FLASH_SEC_SIZE;
uint32_t qpc_buffer[QPC_COUNT +1];
ESP.flashRead(qpc_location, (uint32*)&qpc_buffer, sizeof(qpc_buffer));
if (update && (QPC_SIGNATURE == qpc_buffer[0])) {
uint32_t counter = 1;
while ((0 == qpc_buffer[counter]) && (counter <= QPC_COUNT)) { counter++; }
if (QPC_COUNT == counter) { // 7 power cycles in a row
SettingsErase(3); // Quickly reset all settings including QuickPowerCycle flag
EspRestart(); // And restart
} else {
qpc_buffer[0] = 0;
ESP.flashWrite(qpc_location + (counter * 4), (uint32*)&qpc_buffer, 4);
AddLog_P2(LOG_LEVEL_INFO, PSTR("QPC: Count %d"), counter);
}
}
else if ((qpc_buffer[0] != QPC_SIGNATURE) || (0 == qpc_buffer[1])) {
qpc_buffer[0] = QPC_SIGNATURE;
// Assume flash is default all ones and setting a bit to zero does not need an erase
if (ESP.flashEraseSector(qpc_sector)) {
ESP.flashWrite(qpc_location, (uint32*)&qpc_buffer, 4);
AddLog_P2(LOG_LEVEL_INFO, PSTR("QPC: Reset"));
}
}
#else // ESP32
uint32_t pc_register;
QPCRead(&pc_register, sizeof(pc_register));
if (update && ((pc_register & 0xFFFFFFF0) == 0xFFA55AF0)) {
uint32_t counter = pc_register & 0xF; // Allow up to 15 cycles
if (0xF == counter) { counter = 0; }
counter++;
if (QPC_COUNT == counter) { // 7 power cycles in a row
SettingsErase(3); // Quickly reset all settings including QuickPowerCycle flag
EspRestart(); // And restart
} else {
pc_register = 0xFFA55AF0 | counter;
QPCWrite(&pc_register, sizeof(pc_register));
AddLog_P2(LOG_LEVEL_INFO, PSTR("QPC: Count %d"), counter);
}
}
else if (pc_register != QPC_SIGNATURE) {
pc_register = QPC_SIGNATURE;
QPCWrite(&pc_register, sizeof(pc_register));
AddLog_P2(LOG_LEVEL_INFO, PSTR("QPC: Reset"));
}
#endif // ESP8266 or ESP32
#endif // FIRMWARE_MINIMAL
}
/*********************************************************************************************\
* Config Settings.text char array support
\*********************************************************************************************/
uint32_t GetSettingsTextLen(void) {
char* position = Settings.text_pool;
for (uint32_t size = 0; size < SET_MAX; size++) {
while (*position++ != '\0') { }
}
return position - Settings.text_pool;
}
bool settings_text_mutex = false;
uint32_t settings_text_busy_count = 0;
bool SettingsUpdateFinished(void) {
uint32_t wait_loop = 10;
while (settings_text_mutex && wait_loop) { // Wait for any update to finish
yield();
delayMicroseconds(1);
wait_loop--;
}
return (wait_loop > 0); // true if finished
}
bool SettingsUpdateText(uint32_t index, const char* replace_me) {
if (index >= SET_MAX) {
return false; // Setting not supported - internal error
}
// Make a copy first in case we use source from Settings.text
uint32_t replace_len = strlen_P(replace_me);
char replace[replace_len +1];
memcpy_P(replace, replace_me, sizeof(replace));
uint32_t start_pos = 0;
uint32_t end_pos = 0;
char* position = Settings.text_pool;
for (uint32_t size = 0; size < SET_MAX; size++) {
while (*position++ != '\0') { }
if (1 == index) {
start_pos = position - Settings.text_pool;
}
else if (0 == index) {
end_pos = position - Settings.text_pool -1;
}
index--;
}
uint32_t char_len = position - Settings.text_pool;
uint32_t current_len = end_pos - start_pos;
int diff = replace_len - current_len;
// AddLog_P2(LOG_LEVEL_DEBUG, PSTR("TST: start %d, end %d, len %d, current %d, replace %d, diff %d"),
// start_pos, end_pos, char_len, current_len, replace_len, diff);
int too_long = (char_len + diff) - settings_text_size;
if (too_long > 0) {
AddLog_P2(LOG_LEVEL_INFO, PSTR(D_LOG_CONFIG "Text overflow by %d char(s)"), too_long);
return false; // Replace text too long
}
if (settings_text_mutex && !SettingsUpdateFinished()) {
settings_text_busy_count++;
} else {
settings_text_mutex = true;
if (diff != 0) {
// Shift Settings.text up or down
memmove_P(Settings.text_pool + start_pos + replace_len, Settings.text_pool + end_pos, char_len - end_pos);
}
// Replace text
memmove_P(Settings.text_pool + start_pos, replace, replace_len);
// Fill for future use
memset(Settings.text_pool + char_len + diff, 0x00, settings_text_size - char_len - diff);
settings_text_mutex = false;
}
AddLog_P2(LOG_LEVEL_DEBUG, PSTR(D_LOG_CONFIG "CR %d/%d, Busy %d"), GetSettingsTextLen(), settings_text_size, settings_text_busy_count);
return true;
}
char* SettingsText(uint32_t index)
{
char* position = Settings.text_pool;
if (index >= SET_MAX) {
position += settings_text_size -1; // Setting not supported - internal error - return empty string
} else {
SettingsUpdateFinished();
for (;index > 0; index--) {
while (*position++ != '\0') { }
}
}
return position;
}
/*********************************************************************************************\
* Config Save - Save parameters to Flash ONLY if any parameter has changed
\*********************************************************************************************/
void UpdateBackwardCompatibility(void)
{
// Perform updates for backward compatibility
strlcpy(Settings.user_template_name, SettingsText(SET_TEMPLATE_NAME), sizeof(Settings.user_template_name));
}
uint32_t GetSettingsAddress(void)
{
return settings_location * SPI_FLASH_SEC_SIZE;
}
void SettingsSave(uint8_t rotate)
{
/* Save configuration in eeprom or one of 7 slots below
*
* rotate 0 = Save in next flash slot
* rotate 1 = Save only in eeprom flash slot until SetOption12 0 or restart
* rotate 2 = Save in eeprom flash slot, erase next flash slots and continue depending on stop_flash_rotate
* stop_flash_rotate 0 = Allow flash slot rotation (SetOption12 0)
* stop_flash_rotate 1 = Allow only eeprom flash slot use (SetOption12 1)
*/
#ifndef FIRMWARE_MINIMAL
UpdateBackwardCompatibility();
if ((GetSettingsCrc32() != settings_crc32) || rotate) {
if (1 == rotate) { // Use eeprom flash slot only and disable flash rotate from now on (upgrade)
stop_flash_rotate = 1;
}
if (2 == rotate) { // Use eeprom flash slot and erase next flash slots if stop_flash_rotate is off (default)
settings_location = SETTINGS_LOCATION +1;
}
if (stop_flash_rotate) {
settings_location = SETTINGS_LOCATION;
} else {
settings_location--;
if (settings_location <= (SETTINGS_LOCATION - CFG_ROTATES)) {
settings_location = SETTINGS_LOCATION;
}
}
Settings.save_flag++;
if (UtcTime() > START_VALID_TIME) {
Settings.cfg_timestamp = UtcTime();
} else {
Settings.cfg_timestamp++;
}
Settings.cfg_size = sizeof(Settings);
Settings.cfg_crc = GetSettingsCrc(); // Keep for backward compatibility in case of fall-back just after upgrade
Settings.cfg_crc32 = GetSettingsCrc32();
#ifdef ESP8266
if (ESP.flashEraseSector(settings_location)) {
ESP.flashWrite(settings_location * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(Settings));
}
if (!stop_flash_rotate && rotate) {
for (uint32_t i = 1; i < CFG_ROTATES; i++) {
ESP.flashEraseSector(settings_location -i); // Delete previous configurations by resetting to 0xFF
delay(1);
}
}
AddLog_P2(LOG_LEVEL_DEBUG, PSTR(D_LOG_CONFIG D_SAVED_TO_FLASH_AT " %X, " D_COUNT " %d, " D_BYTES " %d"), settings_location, Settings.save_flag, sizeof(Settings));
#else // ESP32
SettingsWrite(&Settings, sizeof(Settings));
AddLog_P2(LOG_LEVEL_DEBUG, PSTR(D_LOG_CONFIG "Saved, " D_COUNT " %d, " D_BYTES " %d"), Settings.save_flag, sizeof(Settings));
#endif // ESP8266
settings_crc32 = Settings.cfg_crc32;
}
#endif // FIRMWARE_MINIMAL
RtcSettingsSave();
}
void SettingsLoad(void) {
#ifdef ESP8266
// Load configuration from eeprom or one of 7 slots below if first valid load does not stop_flash_rotate
#ifdef CFG_LEGACY_LOAD
// Active until version 8.4.0.2
struct {
uint16_t cfg_holder; // 000
uint16_t cfg_size; // 002
unsigned long save_flag; // 004
} _SettingsH;
unsigned long save_flag = 0;
settings_location = 0;
uint32_t flash_location = SETTINGS_LOCATION +1;
uint16_t cfg_holder = 0;
for (uint32_t i = 0; i < CFG_ROTATES; i++) { // Read all config pages in search of valid and latest
flash_location--;
ESP.flashRead(flash_location * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(Settings));
bool valid = false;
if (Settings.version > 0x06000000) {
bool almost_valid = (Settings.cfg_crc32 == GetSettingsCrc32());
if (Settings.version < 0x0606000B) {
almost_valid = (Settings.cfg_crc == GetSettingsCrc());
}
// Sometimes CRC on pages below FB, overwritten by OTA, is fine but Settings are still invalid. So check cfg_holder too
if (almost_valid && (0 == cfg_holder)) { cfg_holder = Settings.cfg_holder; } // At FB always active cfg_holder
valid = (cfg_holder == Settings.cfg_holder);
} else {
ESP.flashRead((flash_location -1) * SPI_FLASH_SEC_SIZE, (uint32*)&_SettingsH, sizeof(_SettingsH));
valid = (Settings.cfg_holder == _SettingsH.cfg_holder);
}
if (valid) {
if (Settings.save_flag > save_flag) { // Find latest page based on incrementing save_flag
save_flag = Settings.save_flag;
settings_location = flash_location;
if (Settings.flag.stop_flash_rotate && (0 == i)) { // Stop if only eeprom area should be used and it is valid
break;
}
}
}
delay(1);
}
if (settings_location > 0) {
ESP.flashRead(settings_location * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(Settings));
AddLog_P2(LOG_LEVEL_NONE, PSTR(D_LOG_CONFIG D_LOADED_FROM_FLASH_AT " %X, " D_COUNT " %lu"), settings_location, Settings.save_flag);
}
#else // CFG_RESILIENT
// Activated with version 8.4.0.2 - Fails to read any config before version 6.6.0.11
settings_location = 0;
uint32_t save_flag = 0;
uint32_t flash_location = SETTINGS_LOCATION;
for (uint32_t i = 0; i < CFG_ROTATES; i++) { // Read all config pages in search of valid and latest
ESP.flashRead(flash_location * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(Settings));
if ((Settings.cfg_crc32 != 0xFFFFFFFF) && (Settings.cfg_crc32 != 0x00000000) && (Settings.cfg_crc32 == GetSettingsCrc32())) {
if (Settings.save_flag > save_flag) { // Find latest page based on incrementing save_flag
save_flag = Settings.save_flag;
settings_location = flash_location;
if (Settings.flag.stop_flash_rotate && (0 == i)) { // Stop if only eeprom area should be used and it is valid
break;
}
}
}
flash_location--;
delay(1);
}
if (settings_location > 0) {
ESP.flashRead(settings_location * SPI_FLASH_SEC_SIZE, (uint32*)&Settings, sizeof(Settings));
AddLog_P2(LOG_LEVEL_NONE, PSTR(D_LOG_CONFIG D_LOADED_FROM_FLASH_AT " %X, " D_COUNT " %lu"), settings_location, Settings.save_flag);
}
#endif // CFG_RESILIENT
#else // ESP32
SettingsRead(&Settings, sizeof(Settings));
AddLog_P2(LOG_LEVEL_NONE, PSTR(D_LOG_CONFIG "Loaded, " D_COUNT " %lu"), Settings.save_flag);
#endif // ESP8266 - ESP32
#ifndef FIRMWARE_MINIMAL
if ((0 == settings_location) || (Settings.cfg_holder != (uint16_t)CFG_HOLDER)) { // Init defaults if cfg_holder differs from user settings in my_user_config.h
SettingsDefault();
}
settings_crc32 = GetSettingsCrc32();
#endif // FIRMWARE_MINIMAL
RtcSettingsLoad();
}
void EspErase(uint32_t start_sector, uint32_t end_sector)
{
bool serial_output = (LOG_LEVEL_DEBUG_MORE <= seriallog_level);
for (uint32_t sector = start_sector; sector < end_sector; sector++) {
bool result = ESP.flashEraseSector(sector); // Arduino core - erases flash as seen by SDK
// bool result = !SPIEraseSector(sector); // SDK - erases flash as seen by SDK
// bool result = EsptoolEraseSector(sector); // Esptool - erases flash completely (slow)
if (serial_output) {
Serial.printf_P(PSTR(D_LOG_APPLICATION D_ERASED_SECTOR " %d %s\n"), sector, (result) ? D_OK : D_ERROR);
delay(10);
} else {
yield();
}
OsWatchLoop();
}
}
#ifdef ESP8266
void SettingsErase(uint8_t type)
{
/*
For Arduino core and SDK:
Erase only works from flash start address to SDK recognized flash end address (flashchip->chip_size = ESP.getFlashChipSize).
Addresses above SDK recognized size (up to ESP.getFlashChipRealSize) are not accessable.
For Esptool:
The only way to erase whole flash is esptool which uses direct SPI writes to flash.
The default erase function is EspTool (EsptoolErase)
0 = Erase from program end until end of flash as seen by SDK
1 = Erase 16k SDK parameter area near end of flash as seen by SDK (0x0xFCxxx - 0x0xFFFFF) solving possible wifi errors
2 = Erase Tasmota parameter area (0x0xF3xxx - 0x0xFBFFF)
3 = Erase Tasmota and SDK parameter area (0x0F3xxx - 0x0FFFFF)
4 = Erase SDK parameter area used for wifi calibration (0x0FCxxx - 0x0FCFFF)
*/
#ifndef FIRMWARE_MINIMAL
uint32_t _sectorStart = (ESP.getSketchSize() / SPI_FLASH_SEC_SIZE) + 1;
uint32_t _sectorEnd = ESP.getFlashChipRealSize() / SPI_FLASH_SEC_SIZE; // Flash size as reported by hardware
if (1 == type) {
// source Esp.cpp and core_esp8266_phy.cpp
_sectorStart = (ESP.getFlashChipSize() / SPI_FLASH_SEC_SIZE) - 4; // SDK parameter area
}
else if (2 == type) {
_sectorStart = SETTINGS_LOCATION - CFG_ROTATES; // Tasmota parameter area (0x0F3xxx - 0x0FBFFF)
_sectorEnd = SETTINGS_LOCATION +1;
}
else if (3 == type) {
_sectorStart = SETTINGS_LOCATION - CFG_ROTATES; // Tasmota and SDK parameter area (0x0F3xxx - 0x0FFFFF)
_sectorEnd = ESP.getFlashChipSize() / SPI_FLASH_SEC_SIZE; // Flash size as seen by SDK
}
else if (4 == type) {
// _sectorStart = (ESP.getFlashChipSize() / SPI_FLASH_SEC_SIZE) - 4; // SDK phy area and Core calibration sector (0x0FC000)
_sectorStart = SETTINGS_LOCATION +1; // SDK phy area and Core calibration sector (0x0FC000)
_sectorEnd = _sectorStart +1; // SDK end of phy area and Core calibration sector (0x0FCFFF)
}
/*
else if (5 == type) {
_sectorStart = (ESP.getFlashChipRealSize() / SPI_FLASH_SEC_SIZE) -4; // SDK phy area and Core calibration sector (0xxFC000)
_sectorEnd = _sectorStart +1; // SDK end of phy area and Core calibration sector (0xxFCFFF)
}
*/
else {
return;
}
AddLog_P2(LOG_LEVEL_DEBUG, PSTR(D_LOG_APPLICATION D_ERASE " from 0x%08X to 0x%08X"), _sectorStart * SPI_FLASH_SEC_SIZE, (_sectorEnd * SPI_FLASH_SEC_SIZE) -1);
// EspErase(_sectorStart, _sectorEnd); // Arduino core and SDK - erases flash as seen by SDK
EsptoolErase(_sectorStart, _sectorEnd); // Esptool - erases flash completely
#endif // FIRMWARE_MINIMAL
}
#endif // ESP8266
void SettingsSdkErase(void)
{
WiFi.disconnect(false); // Delete SDK wifi config
SettingsErase(1);
delay(1000);
}
/********************************************************************************************/
void SettingsDefault(void)
{
AddLog_P(LOG_LEVEL_NONE, PSTR(D_LOG_CONFIG D_USE_DEFAULTS));
SettingsDefaultSet1();
SettingsDefaultSet2();
SettingsSave(2);
}
void SettingsDefaultSet1(void)
{
memset(&Settings, 0x00, sizeof(Settings));
Settings.cfg_holder = (uint16_t)CFG_HOLDER;
Settings.cfg_size = sizeof(Settings);
// Settings.save_flag = 0;
Settings.version = VERSION;
// Settings.bootcount = 0;
// Settings.cfg_crc = 0;
}
void SettingsDefaultSet2(void)
{
memset((char*)&Settings +16, 0x00, sizeof(Settings) -16);
// this little trick allows GCC to optimize the assignment by grouping values and doing only ORs
SysBitfield flag = { 0 };
SysBitfield2 flag2 = { 0 };
SysBitfield3 flag3 = { 0 };
SysBitfield4 flag4 = { 0 };
SysBitfield5 flag5 = { 0 };
#ifdef ESP8266
// Settings.config_version = 0; // ESP8266 (Has been 0 for long time)
#endif // ESP8266
#ifdef ESP32
Settings.config_version = 1; // ESP32
#endif // ESP32
flag.stop_flash_rotate |= APP_FLASH_CYCLE;
flag.global_state |= APP_ENABLE_LEDLINK;
flag3.sleep_normal |= APP_NORMAL_SLEEP;
flag3.no_power_feedback |= APP_NO_RELAY_SCAN;
flag3.fast_power_cycle_disable |= APP_DISABLE_POWERCYCLE;
flag3.bootcount_update |= DEEPSLEEP_BOOTCOUNT;
flag3.compatibility_check |= OTA_COMPATIBILITY;
Settings.save_data = SAVE_DATA;
Settings.param[P_BACKLOG_DELAY] = MIN_BACKLOG_DELAY;
Settings.param[P_BOOT_LOOP_OFFSET] = BOOT_LOOP_OFFSET; // SetOption36
Settings.param[P_RGB_REMAP] = RGB_REMAP_RGBW;
Settings.sleep = APP_SLEEP;
if (Settings.sleep < 50) {
Settings.sleep = 50; // Default to 50 for sleep, for now
}
// Module
flag.interlock |= APP_INTERLOCK_MODE;
Settings.interlock[0] = APP_INTERLOCK_GROUP_1;
Settings.interlock[1] = APP_INTERLOCK_GROUP_2;
Settings.interlock[2] = APP_INTERLOCK_GROUP_3;
Settings.interlock[3] = APP_INTERLOCK_GROUP_4;
Settings.module = MODULE;
Settings.fallback_module = FALLBACK_MODULE;
ModuleDefault(WEMOS);
// for (uint32_t i = 0; i < ARRAY_SIZE(Settings.my_gp.io); i++) { Settings.my_gp.io[i] = GPIO_NONE; }
SettingsUpdateText(SET_FRIENDLYNAME1, PSTR(FRIENDLY_NAME));
SettingsUpdateText(SET_FRIENDLYNAME2, PSTR(FRIENDLY_NAME"2"));
SettingsUpdateText(SET_FRIENDLYNAME3, PSTR(FRIENDLY_NAME"3"));
SettingsUpdateText(SET_FRIENDLYNAME4, PSTR(FRIENDLY_NAME"4"));
SettingsUpdateText(SET_DEVICENAME, SettingsText(SET_FRIENDLYNAME1));
SettingsUpdateText(SET_OTAURL, PSTR(OTA_URL));
// Power
flag.save_state |= SAVE_STATE;
Settings.power = APP_POWER;
Settings.poweronstate = APP_POWERON_STATE;
Settings.blinktime = APP_BLINKTIME;
Settings.blinkcount = APP_BLINKCOUNT;
Settings.ledstate = APP_LEDSTATE;
Settings.ledmask = APP_LEDMASK;
// Settings.ledpwm_off = 0;
Settings.ledpwm_on = 255;
// Settings.ledpwm_mask = 0;
Settings.pulse_timer[0] = APP_PULSETIME;
// for (uint32_t i = 1; i < MAX_PULSETIMERS; i++) { Settings.pulse_timer[i] = 0; }
// Serial
Settings.serial_config = TS_SERIAL_8N1;
Settings.baudrate = APP_BAUDRATE / 300;
Settings.sbaudrate = SOFT_BAUDRATE / 300;
Settings.serial_delimiter = 0xff;
Settings.seriallog_level = SERIAL_LOG_LEVEL;
// Ethernet
flag4.network_ethernet |= 1;
#ifdef ESP32
Settings.eth_type = ETH_TYPE;
Settings.eth_clk_mode = ETH_CLKMODE;
Settings.eth_address = ETH_ADDR;
#endif
// Wifi
flag4.network_wifi |= 1;
flag3.use_wifi_scan |= WIFI_SCAN_AT_RESTART;
flag3.use_wifi_rescan |= WIFI_SCAN_REGULARLY;
Settings.wifi_output_power = 170;
Settings.param[P_ARP_GRATUITOUS] = WIFI_ARP_INTERVAL;
ParseIp(&Settings.ip_address[0], WIFI_IP_ADDRESS);
ParseIp(&Settings.ip_address[1], WIFI_GATEWAY);
ParseIp(&Settings.ip_address[2], WIFI_SUBNETMASK);
ParseIp(&Settings.ip_address[3], WIFI_DNS);
Settings.sta_config = WIFI_CONFIG_TOOL;
// Settings.sta_active = 0;
SettingsUpdateText(SET_STASSID1, PSTR(STA_SSID1));
SettingsUpdateText(SET_STASSID2, PSTR(STA_SSID2));
SettingsUpdateText(SET_STAPWD1, PSTR(STA_PASS1));
SettingsUpdateText(SET_STAPWD2, PSTR(STA_PASS2));
SettingsUpdateText(SET_HOSTNAME, WIFI_HOSTNAME);
// Syslog
SettingsUpdateText(SET_SYSLOG_HOST, PSTR(SYS_LOG_HOST));
Settings.syslog_port = SYS_LOG_PORT;
Settings.syslog_level = SYS_LOG_LEVEL;
// Webserver
flag2.emulation |= EMULATION;
flag4.alexa_gen_1 |= EMULATION_HUE_1ST_GEN;
flag3.gui_hostname_ip |= GUI_SHOW_HOSTNAME;
flag3.mdns_enabled |= MDNS_ENABLED;
Settings.webserver = WEB_SERVER;
Settings.weblog_level = WEB_LOG_LEVEL;
SettingsUpdateText(SET_WEBPWD, PSTR(WEB_PASSWORD));
SettingsUpdateText(SET_CORS, PSTR(CORS_DOMAIN));
// Button
flag.button_restrict |= KEY_DISABLE_MULTIPRESS;
flag.button_swap |= KEY_SWAP_DOUBLE_PRESS;
flag.button_single |= KEY_ONLY_SINGLE_PRESS;
Settings.param[P_HOLD_TIME] = KEY_HOLD_TIME; // Default 4 seconds hold time
// Switch
for (uint32_t i = 0; i < MAX_SWITCHES; i++) { Settings.switchmode[i] = SWITCH_MODE; }
// MQTT
flag.mqtt_enabled |= MQTT_USE;
flag.mqtt_response |= MQTT_RESULT_COMMAND;
flag.mqtt_offline |= MQTT_LWT_MESSAGE;
flag.mqtt_power_retain |= MQTT_POWER_RETAIN;
flag.mqtt_button_retain |= MQTT_BUTTON_RETAIN;
flag.mqtt_switch_retain |= MQTT_SWITCH_RETAIN;
flag.mqtt_sensor_retain |= MQTT_SENSOR_RETAIN;
// flag.mqtt_serial |= 0;
flag.device_index_enable |= MQTT_POWER_FORMAT;
flag3.time_append_timezone |= MQTT_APPEND_TIMEZONE;
flag3.button_switch_force_local |= MQTT_BUTTON_SWITCH_FORCE_LOCAL;
flag3.no_hold_retain |= MQTT_NO_HOLD_RETAIN;
flag3.use_underscore |= MQTT_INDEX_SEPARATOR;
flag3.grouptopic_mode |= MQTT_GROUPTOPIC_FORMAT;
SettingsUpdateText(SET_MQTT_HOST, MQTT_HOST);
Settings.mqtt_port = MQTT_PORT;
SettingsUpdateText(SET_MQTT_CLIENT, MQTT_CLIENT_ID);
SettingsUpdateText(SET_MQTT_USER, MQTT_USER);
SettingsUpdateText(SET_MQTT_PWD, MQTT_PASS);
SettingsUpdateText(SET_MQTT_TOPIC, MQTT_TOPIC);
SettingsUpdateText(SET_MQTT_BUTTON_TOPIC, MQTT_BUTTON_TOPIC);
SettingsUpdateText(SET_MQTT_SWITCH_TOPIC, MQTT_SWITCH_TOPIC);
SettingsUpdateText(SET_MQTT_GRP_TOPIC, MQTT_GRPTOPIC);
SettingsUpdateText(SET_MQTT_FULLTOPIC, MQTT_FULLTOPIC);
Settings.mqtt_retry = MQTT_RETRY_SECS;
SettingsUpdateText(SET_MQTTPREFIX1, SUB_PREFIX);
SettingsUpdateText(SET_MQTTPREFIX2, PUB_PREFIX);
SettingsUpdateText(SET_MQTTPREFIX3, PUB_PREFIX2);
SettingsUpdateText(SET_STATE_TXT1, MQTT_STATUS_OFF);
SettingsUpdateText(SET_STATE_TXT2, MQTT_STATUS_ON);
SettingsUpdateText(SET_STATE_TXT3, MQTT_CMND_TOGGLE);
SettingsUpdateText(SET_STATE_TXT4, MQTT_CMND_HOLD);
char fingerprint[64];
strncpy_P(fingerprint, PSTR(MQTT_FINGERPRINT1), sizeof(fingerprint));
char *p = fingerprint;
for (uint32_t i = 0; i < 20; i++) {
Settings.mqtt_fingerprint[0][i] = strtol(p, &p, 16);
}
strncpy_P(fingerprint, PSTR(MQTT_FINGERPRINT2), sizeof(fingerprint));
p = fingerprint;
for (uint32_t i = 0; i < 20; i++) {
Settings.mqtt_fingerprint[1][i] = strtol(p, &p, 16);
}
Settings.tele_period = TELE_PERIOD;
Settings.mqttlog_level = MQTT_LOG_LEVEL;
// Energy
flag.no_power_on_check |= ENERGY_VOLTAGE_ALWAYS;
flag2.current_resolution |= 3;
// flag2.voltage_resolution |= 0;
// flag2.wattage_resolution |= 0;
flag2.energy_resolution |= ENERGY_RESOLUTION;
flag3.dds2382_model |= ENERGY_DDS2382_MODE;
flag3.hardware_energy_total |= ENERGY_HARDWARE_TOTALS;
Settings.param[P_MAX_POWER_RETRY] = MAX_POWER_RETRY;
// Settings.energy_power_delta[0] = 0;
// Settings.energy_power_delta[1] = 0;
// Settings.energy_power_delta[2] = 0;
Settings.energy_power_calibration = HLW_PREF_PULSE;
Settings.energy_voltage_calibration = HLW_UREF_PULSE;
Settings.energy_current_calibration = HLW_IREF_PULSE;
// Settings.energy_kWhtoday = 0;
// Settings.energy_kWhyesterday = 0;
// Settings.energy_kWhdoy = 0;
// Settings.energy_min_power = 0;
// Settings.energy_max_power = 0;
// Settings.energy_min_voltage = 0;
// Settings.energy_max_voltage = 0;
// Settings.energy_min_current = 0;
// Settings.energy_max_current = 0;
// Settings.energy_max_power_limit = 0; // MaxPowerLimit
Settings.energy_max_power_limit_hold = MAX_POWER_HOLD;
Settings.energy_max_power_limit_window = MAX_POWER_WINDOW;
// Settings.energy_max_power_safe_limit = 0; // MaxSafePowerLimit
Settings.energy_max_power_safe_limit_hold = SAFE_POWER_HOLD;
Settings.energy_max_power_safe_limit_window = SAFE_POWER_WINDOW;
// Settings.energy_max_energy = 0; // MaxEnergy
// Settings.energy_max_energy_start = 0; // MaxEnergyStart
// Settings.energy_kWhtotal = 0;
RtcSettings.energy_kWhtotal = 0;
// memset((char*)&Settings.energy_usage, 0x00, sizeof(Settings.energy_usage));
memset((char*)&RtcSettings.energy_usage, 0x00, sizeof(RtcSettings.energy_usage));
Settings.param[P_OVER_TEMP] = ENERGY_OVERTEMP;
// IRRemote
flag.ir_receive_decimal |= IR_DATA_RADIX;
flag3.receive_raw |= IR_ADD_RAW_DATA;
Settings.param[P_IR_UNKNOW_THRESHOLD] = IR_RCV_MIN_UNKNOWN_SIZE;
// RF Bridge
flag.rf_receive_decimal |= RF_DATA_RADIX;
// for (uint32_t i = 0; i < 17; i++) { Settings.rf_code[i][0] = 0; }
memcpy_P(Settings.rf_code[0], kDefaultRfCode, 9);
// Domoticz
Settings.domoticz_update_timer = DOMOTICZ_UPDATE_TIMER;
// for (uint32_t i = 0; i < MAX_DOMOTICZ_IDX; i++) {
// Settings.domoticz_relay_idx[i] = 0;
// Settings.domoticz_key_idx[i] = 0;
// Settings.domoticz_switch_idx[i] = 0;
// }
// for (uint32_t i = 0; i < MAX_DOMOTICZ_SNS_IDX; i++) {
// Settings.domoticz_sensor_idx[i] = 0;
// }
// Sensor
flag.temperature_conversion |= TEMP_CONVERSION;
flag.pressure_conversion |= PRESSURE_CONVERSION;
flag2.pressure_resolution |= PRESSURE_RESOLUTION;
flag2.humidity_resolution |= HUMIDITY_RESOLUTION;
flag2.temperature_resolution |= TEMP_RESOLUTION;
flag3.ds18x20_internal_pullup |= DS18X20_PULL_UP;
flag3.counter_reset_on_tele |= COUNTER_RESET;
// Settings.altitude = 0;
// Rules
// Settings.rule_enabled = 0;