forked from letscontrolit/ESPEasy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Misc.ino
2215 lines (1946 loc) · 61.4 KB
/
Misc.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
/*********************************************************************************************\
Get value count from sensor type
\*********************************************************************************************/
byte getValueCountFromSensorType(byte sensorType)
{
byte valueCount = 0;
switch (sensorType)
{
case SENSOR_TYPE_SINGLE: // single value sensor, used for Dallas, BH1750, etc
case SENSOR_TYPE_SWITCH:
case SENSOR_TYPE_DIMMER:
valueCount = 1;
break;
case SENSOR_TYPE_LONG: // single LONG value, stored in two floats (rfid tags)
valueCount = 1;
break;
case SENSOR_TYPE_TEMP_HUM:
case SENSOR_TYPE_TEMP_BARO:
case SENSOR_TYPE_DUAL:
valueCount = 2;
break;
case SENSOR_TYPE_TEMP_HUM_BARO:
case SENSOR_TYPE_TRIPLE:
valueCount = 3;
break;
case SENSOR_TYPE_QUAD:
valueCount = 4;
break;
}
return valueCount;
}
/*********************************************************************************************\
Workaround for removing trailing white space when String() converts a float with 0 decimals
\*********************************************************************************************/
String toString(float value, byte decimals)
{
String sValue = String(value, decimals);
sValue.trim();
return sValue;
}
/*********************************************************************************************\
Parse a string and get the xth command or parameter
\*********************************************************************************************/
String parseString(String& string, byte indexFind)
{
String tmpString = string;
tmpString += ",";
tmpString.replace(" ", ",");
String locateString = "";
byte count = 0;
int index = tmpString.indexOf(',');
while (index > 0)
{
count++;
locateString = tmpString.substring(0, index);
tmpString = tmpString.substring(index + 1);
index = tmpString.indexOf(',');
if (count == indexFind)
{
locateString.toLowerCase();
return locateString;
}
}
return "";
}
/*********************************************************************************************\
Parse a string and get the xth command or parameter
\*********************************************************************************************/
int getParamStartPos(String& string, byte indexFind)
{
String tmpString = string;
byte count = 0;
tmpString.replace(" ", ",");
for (int x = 0; x < tmpString.length(); x++)
{
if (tmpString.charAt(x) == ',')
{
count++;
if (count == (indexFind - 1))
return x + 1;
}
}
return -1;
}
/*********************************************************************************************\
set pin mode & state (info table)
\*********************************************************************************************/
boolean setPinState(byte plugin, byte index, byte mode, uint16_t value)
{
// plugin number and index form a unique key
// first check if this pin is already known
boolean reUse = false;
for (byte x = 0; x < PINSTATE_TABLE_MAX; x++)
if ((pinStates[x].plugin == plugin) && (pinStates[x].index == index))
{
pinStates[x].mode = mode;
pinStates[x].value = value;
reUse = true;
break;
}
if (!reUse)
{
for (byte x = 0; x < PINSTATE_TABLE_MAX; x++)
if (pinStates[x].plugin == 0)
{
pinStates[x].plugin = plugin;
pinStates[x].index = index;
pinStates[x].mode = mode;
pinStates[x].value = value;
break;
}
}
}
/*********************************************************************************************\
get pin mode & state (info table)
\*********************************************************************************************/
boolean getPinState(byte plugin, byte index, byte *mode, uint16_t *value)
{
for (byte x = 0; x < PINSTATE_TABLE_MAX; x++)
if ((pinStates[x].plugin == plugin) && (pinStates[x].index == index))
{
*mode = pinStates[x].mode;
*value = pinStates[x].value;
return true;
}
return false;
}
/*********************************************************************************************\
check if pin mode & state is known (info table)
\*********************************************************************************************/
boolean hasPinState(byte plugin, byte index)
{
for (byte x = 0; x < PINSTATE_TABLE_MAX; x++)
if ((pinStates[x].plugin == plugin) && (pinStates[x].index == index))
{
return true;
}
return false;
}
/*********************************************************************************************\
report pin mode & state (info table) using json
\*********************************************************************************************/
String getPinStateJSON(boolean search, byte plugin, byte index, String& log, uint16_t noSearchValue)
{
printToWebJSON = true;
byte mode = PIN_MODE_INPUT;
uint16_t value = noSearchValue;
String reply = "";
boolean found = false;
if (search)
{
for (byte x = 0; x < PINSTATE_TABLE_MAX; x++)
if ((pinStates[x].plugin == plugin) && (pinStates[x].index == index))
{
mode = pinStates[x].mode;
value = pinStates[x].value;
found = true;
break;
}
}
if (!search || (search && found))
{
reply += F("{\n\"log\": \"");
reply += log.substring(7, 32); // truncate to 25 chars, max MQTT message size = 128 including header...
reply += F("\",\n\"plugin\": ");
reply += plugin;
reply += F(",\n\"pin\": ");
reply += index;
reply += F(",\n\"mode\": \"");
switch (mode)
{
case PIN_MODE_UNDEFINED:
reply += F("undefined");
break;
case PIN_MODE_INPUT:
reply += F("input");
break;
case PIN_MODE_OUTPUT:
reply += F("output");
break;
case PIN_MODE_PWM:
reply += F("PWM");
break;
case PIN_MODE_SERVO:
reply += F("servo");
break;
}
reply += F("\",\n\"state\": ");
reply += value;
reply += F("\n}\n");
return reply;
}
return "?";
}
/********************************************************************************************\
Unsigned long Timer timeOut check
\*********************************************************************************************/
boolean timeOut(unsigned long timer)
{
// This routine solves the 49 day bug without the need for separate start time and duration
// that would need two 32 bit variables if duration is not static
// It limits the maximum delay to 24.9 days.
unsigned long now = millis();
if (((now >= timer) && ((now - timer) < 1 << 31)) || ((timer >= now) && (timer - now > 1 << 31)))
return true;
return false;
}
/********************************************************************************************\
Status LED
\*********************************************************************************************/
void statusLED(boolean traffic)
{
if (Settings.Pin_status_led == -1)
return;
static unsigned long timer = 0;
static byte currentState = 0;
if (traffic)
{
currentState = HIGH;
digitalWrite(Settings.Pin_status_led, currentState); // blink off
timer = millis() + 100;
}
if (timer == 0 || millis() > timer)
{
timer = 0;
byte state = HIGH;
if (WiFi.status() == WL_CONNECTED)
state = LOW;
if (currentState != state)
{
currentState = state;
pinMode(Settings.Pin_status_led, OUTPUT);
digitalWrite(Settings.Pin_status_led, state);
}
}
}
/********************************************************************************************\
delay in milliseconds with background processing
\*********************************************************************************************/
void delayMillis(unsigned long delay)
{
unsigned long timer = millis() + delay;
while (millis() < timer)
backgroundtasks();
}
/********************************************************************************************\
Parse a command string to event struct
\*********************************************************************************************/
void parseCommandString(struct EventStruct *event, String& string)
{
char command[80];
command[0] = 0;
char TmpStr1[80];
TmpStr1[0] = 0;
string.toCharArray(command, 80);
event->Par1 = 0;
event->Par2 = 0;
event->Par3 = 0;
if (GetArgv(command, TmpStr1, 2)) event->Par1 = str2int(TmpStr1);
if (GetArgv(command, TmpStr1, 3)) event->Par2 = str2int(TmpStr1);
if (GetArgv(command, TmpStr1, 4)) event->Par3 = str2int(TmpStr1);
}
/********************************************************************************************\
Clear task settings for given task
\*********************************************************************************************/
void taskClear(byte taskIndex, boolean save)
{
Settings.TaskDeviceNumber[taskIndex] = 0;
ExtraTaskSettings.TaskDeviceName[0] = 0;
Settings.TaskDeviceID[taskIndex] = 0;
Settings.TaskDeviceDataFeed[taskIndex] = 0;
Settings.TaskDevicePin1[taskIndex] = -1;
Settings.TaskDevicePin2[taskIndex] = -1;
Settings.TaskDevicePin3[taskIndex] = -1;
Settings.TaskDevicePort[taskIndex] = 0;
Settings.TaskDeviceSendData[taskIndex] = true;
Settings.TaskDeviceGlobalSync[taskIndex] = false;
Settings.TaskDeviceTimer[taskIndex] = 0;
for (byte x = 0; x < PLUGIN_CONFIGVAR_MAX; x++)
Settings.TaskDevicePluginConfig[taskIndex][x] = 0;
for (byte varNr = 0; varNr < VARS_PER_TASK; varNr++)
{
ExtraTaskSettings.TaskDeviceFormula[varNr][0] = 0;
ExtraTaskSettings.TaskDeviceValueNames[varNr][0] = 0;
ExtraTaskSettings.TaskDeviceValueDecimals[varNr] = 2;
}
for (byte varNr = 0; varNr < PLUGIN_EXTRACONFIGVAR_MAX; varNr++)
ExtraTaskSettings.TaskDevicePluginConfigLong[varNr] = 0;
if (save)
{
SaveTaskSettings(taskIndex);
SaveSettings();
}
}
/********************************************************************************************\
Use DNS to resolve hostname to ip address
\*********************************************************************************************/
void getIPfromHostName()
{
IPAddress IP;
if (Settings.ControllerHostName[0] != 0)
{
WiFi.hostByName(Settings.ControllerHostName, IP);
for (byte x = 0; x < 4; x++)
Settings.Controller_IP[x] = IP[x];
}
}
/********************************************************************************************\
Fix stuff to clear out differences between releases
\*********************************************************************************************/
void BuildFixes()
{
Serial.println(F("\nBuild changed!"));
// fix default send data on active tasks, new to R52
if (Settings.Build < 52)
{
Serial.println(F("Fix SendData"));
for (byte x = 0; x < TASKS_MAX; x++)
{
Settings.TaskDeviceSendData[x] = true;
}
}
if (Settings.Build < 64)
{
Serial.println(F("Fix Pin3"));
for (byte x = 0; x < TASKS_MAX; x++)
{
Settings.TaskDevicePin3[x] = -1;
}
}
if (Settings.Build < 79)
{
Serial.println(F("Fix status LED Pin"));
Settings.Pin_status_led = -1;
Settings.UseSerial = true;
for (byte x = 0; x < TASKS_MAX; x++)
Settings.TaskDeviceTimer[x] = Settings.Delay;
}
if (Settings.Build < 83)
{
Serial.println(F("Fix taskindex"));
for (byte x = 0; x < TASKS_MAX; x++)
{
LoadTaskSettings(x);
SaveTaskSettings(x);
}
}
if (Settings.Build < 88)
{
struct ExtraTaskSettingsStruct_old
{
byte TaskIndex;
char TaskDeviceName[26];
char TaskDeviceFormula[VARS_PER_TASK][41];
char TaskDeviceValueNames[VARS_PER_TASK][26];
long TaskDevicePluginConfigLong[PLUGIN_EXTRACONFIGVAR_MAX];
byte TaskDeviceValueDecimals[VARS_PER_TASK];
} ExtraTaskSettings_old;
Serial.println(F("Fix extratasksettings"));
for (byte TaskIndex = 0; TaskIndex < TASKS_MAX; TaskIndex++)
{
LoadFromFlash(4096 + (TaskIndex * 1024), (byte*)&ExtraTaskSettings_old, sizeof(struct ExtraTaskSettingsStruct_old));
ExtraTaskSettings.TaskIndex = ExtraTaskSettings_old.TaskIndex;
strcpy(ExtraTaskSettings.TaskDeviceName, ExtraTaskSettings_old.TaskDeviceName);
for (byte x = 0; x < VARS_PER_TASK; x++)
{
strcpy(ExtraTaskSettings.TaskDeviceFormula[x], ExtraTaskSettings_old.TaskDeviceFormula[x]);
strcpy(ExtraTaskSettings.TaskDeviceValueNames[x], ExtraTaskSettings_old.TaskDeviceValueNames[x]);
ExtraTaskSettings.TaskDeviceValueDecimals[x] = 2;
}
for (byte x = 0; x < PLUGIN_EXTRACONFIGVAR_MAX; x++)
{
ExtraTaskSettings.TaskDevicePluginConfigLong[x] = ExtraTaskSettings_old.TaskDevicePluginConfigLong[x];
}
SaveToFlash(4096 + (TaskIndex * 1024), (byte*)&ExtraTaskSettings, sizeof(struct ExtraTaskSettingsStruct));
}
}
if (Settings.Build < 112)
{
Serial.println(F("Fix timezone"));
Settings.TimeZone = Settings.TimeZone_OLD * 60;
}
Settings.Build = BUILD;
SaveSettings();
}
#if FEATURE_SPIFFS
void fileSystemCheck()
{
if (SPIFFS.begin())
{
String log = F("SPIFFS Mount successful");
addLog(LOG_LEVEL_INFO, log);
File f = SPIFFS.open("config.txt", "r");
if (!f)
{
log = F("formatting...");
addLog(LOG_LEVEL_INFO, log);
SPIFFS.format();
log = F("format done!");
addLog(LOG_LEVEL_INFO, log);
File f = SPIFFS.open("config.txt", "w");
if (f)
{
for (int x = 0; x < 32768; x++)
f.write(0);
f.close();
}
f = SPIFFS.open("security.txt", "w");
if (f)
{
for (int x = 0; x < 512; x++)
f.write(0);
f.close();
}
f = SPIFFS.open("rules.txt", "w");
f.close();
}
}
else
{
String log = F("SPIFFS Mount failed");
addLog(LOG_LEVEL_INFO, log);
}
}
#endif
/********************************************************************************************\
Find device index corresponding to task number setting
\*********************************************************************************************/
byte getDeviceIndex(byte Number)
{
byte DeviceIndex = 0;
for (byte x = 0; x <= deviceCount ; x++)
if (Device[x].Number == Number)
DeviceIndex = x;
return DeviceIndex;
}
/********************************************************************************************\
Find protocol index corresponding to protocol setting
\*********************************************************************************************/
byte getProtocolIndex(byte Number)
{
byte ProtocolIndex = 0;
for (byte x = 0; x <= protocolCount ; x++)
if (Protocol[x].Number == Number)
ProtocolIndex = x;
return ProtocolIndex;
}
/********************************************************************************************\
Find positional parameter in a char string
\*********************************************************************************************/
boolean GetArgv(const char *string, char *argv, int argc)
{
int string_pos = 0, argv_pos = 0, argc_pos = 0;
char c, d;
while (string_pos < strlen(string))
{
c = string[string_pos];
d = string[string_pos + 1];
if (c == ' ' && d == ' ') {}
else if (c == ' ' && d == ',') {}
else if (c == ',' && d == ' ') {}
else if (c == ' ' && d >= 33 && d <= 126) {}
else if (c == ',' && d >= 33 && d <= 126) {}
else
{
argv[argv_pos++] = c;
argv[argv_pos] = 0;
if (d == ' ' || d == ',' || d == 0)
{
argv[argv_pos] = 0;
argc_pos++;
if (argc_pos == argc)
{
return true;
}
argv[0] = 0;
argv_pos = 0;
string_pos++;
}
}
string_pos++;
}
return false;
}
/********************************************************************************************\
Convert a char string to integer
\*********************************************************************************************/
unsigned long str2int(char *string)
{
unsigned long temp = atof(string);
return temp;
}
/********************************************************************************************\
Convert a char string to IP byte array
\*********************************************************************************************/
boolean str2ip(char *string, byte* IP)
{
byte c;
byte part = 0;
int value = 0;
for (int x = 0; x <= strlen(string); x++)
{
c = string[x];
if (isdigit(c))
{
value *= 10;
value += c - '0';
}
else if (c == '.' || c == 0) // next octet from IP address
{
if (value <= 255)
IP[part++] = value;
else
return false;
value = 0;
}
else if (c == ' ') // ignore these
;
else // invalid token
return false;
}
if (part == 4) // correct number of octets
return true;
return false;
}
/********************************************************************************************\
Save settings to SPIFFS
\*********************************************************************************************/
void SaveSettings(void)
{
#if FEATURE_SPIFFS
SaveToFile((char*)"config.txt", 0, (byte*)&Settings, sizeof(struct SettingsStruct));
SaveToFile((char*)"security.txt", 0, (byte*)&SecuritySettings, sizeof(struct SecurityStruct));
#else
SaveToFlash(0, (byte*)&Settings, sizeof(struct SettingsStruct));
SaveToFlash(32768, (byte*)&SecuritySettings, sizeof(struct SecurityStruct));
#endif
}
/********************************************************************************************\
Load settings from SPIFFS
\*********************************************************************************************/
boolean LoadSettings()
{
#if FEATURE_SPIFFS
LoadFromFile((char*)"config.txt", 0, (byte*)&Settings, sizeof(struct SettingsStruct));
LoadFromFile((char*)"security.txt", 0, (byte*)&SecuritySettings, sizeof(struct SecurityStruct));
#else
LoadFromFlash(0, (byte*)&Settings, sizeof(struct SettingsStruct));
LoadFromFlash(32768, (byte*)&SecuritySettings, sizeof(struct SecurityStruct));
#endif
}
/********************************************************************************************\
Save Task settings to SPIFFS
\*********************************************************************************************/
void SaveTaskSettings(byte TaskIndex)
{
ExtraTaskSettings.TaskIndex = TaskIndex;
#if FEATURE_SPIFFS
SaveToFile((char*)"config.txt", 4096 + (TaskIndex * 1024), (byte*)&ExtraTaskSettings, sizeof(struct ExtraTaskSettingsStruct));
#else
SaveToFlash(4096 + (TaskIndex * 1024), (byte*)&ExtraTaskSettings, sizeof(struct ExtraTaskSettingsStruct));
#endif
}
/********************************************************************************************\
Load Task settings from SPIFFS
\*********************************************************************************************/
void LoadTaskSettings(byte TaskIndex)
{
if (ExtraTaskSettings.TaskIndex == TaskIndex)
return;
#if FEATURE_SPIFFS
LoadFromFile((char*)"config.txt", 4096 + (TaskIndex * 1024), (byte*)&ExtraTaskSettings, sizeof(struct ExtraTaskSettingsStruct));
#else
LoadFromFlash(4096 + (TaskIndex * 1024), (byte*)&ExtraTaskSettings, sizeof(struct ExtraTaskSettingsStruct));
#endif
ExtraTaskSettings.TaskIndex = TaskIndex; // Needed when an empty task was requested
}
/********************************************************************************************\
Save Custom Task settings to SPIFFS
\*********************************************************************************************/
void SaveCustomTaskSettings(int TaskIndex, byte* memAddress, int datasize)
{
if (datasize > 512)
return;
#if FEATURE_SPIFFS
SaveToFile((char*)"config.txt", 4096 + (TaskIndex * 1024) + 512, memAddress, datasize);
#else
SaveToFlash(4096 + (TaskIndex * 1024) + 512, memAddress, datasize);
#endif
}
/********************************************************************************************\
Save Custom Task settings to SPIFFS
\*********************************************************************************************/
void LoadCustomTaskSettings(int TaskIndex, byte* memAddress, int datasize)
{
if (datasize > 512)
return;
#if FEATURE_SPIFFS
LoadFromFile((char*)"config.txt", 4096 + (TaskIndex * 1024) + 512, memAddress, datasize);
#else
LoadFromFlash(4096 + (TaskIndex * 1024) + 512, memAddress, datasize);
#endif
}
/********************************************************************************************\
Save Custom Controller settings to SPIFFS
\*********************************************************************************************/
void SaveCustomControllerSettings(byte* memAddress, int datasize)
{
if (datasize > 4096)
return;
#if FEATURE_SPIFFS
SaveToFile((char*)"config.txt", 28672, memAddress, datasize);
#else
SaveToFlash(28672, memAddress, datasize);
#endif
}
/********************************************************************************************\
Save Custom Controller settings to SPIFFS
\*********************************************************************************************/
void LoadCustomControllerSettings(byte* memAddress, int datasize)
{
if (datasize > 4096)
return;
#if FEATURE_SPIFFS
LoadFromFile((char*)"config.txt", 28672, memAddress, datasize);
#else
LoadFromFlash(28672, memAddress, datasize);
#endif
}
#if FEATURE_SPIFFS
/********************************************************************************************\
Save data into config file on SPIFFS
\*********************************************************************************************/
void SaveToFile(char* fname, int index, byte* memAddress, int datasize)
{
File f = SPIFFS.open(fname, "r+");
if (f)
{
f.seek(index, SeekSet);
byte *pointerToByteToSave = memAddress;
for (int x = 0; x < datasize ; x++)
{
f.write(*pointerToByteToSave);
pointerToByteToSave++;
}
f.close();
String log = F("FILE : File saved");
addLog(LOG_LEVEL_INFO, log);
}
}
/********************************************************************************************\
Load data from config file on SPIFFS
\*********************************************************************************************/
void LoadFromFile(char* fname, int index, byte* memAddress, int datasize)
{
File f = SPIFFS.open(fname, "r+");
if (f)
{
f.seek(index, SeekSet);
byte *pointerToByteToRead = memAddress;
for (int x = 0; x < datasize; x++)
{
*pointerToByteToRead = f.read();
pointerToByteToRead++;// next byte
}
f.close();
}
}
#endif
/********************************************************************************************\
Save data to flash
\*********************************************************************************************/
void SaveToFlash(int index, byte* memAddress, int datasize)
{
if (index > 33791) // Limit usable flash area to 32+1k size
{
return;
}
uint32_t _sector = ((uint32_t)&_SPIFFS_start - 0x40200000) / SPI_FLASH_SEC_SIZE;
uint8_t* data = new uint8_t[FLASH_EEPROM_SIZE];
int sectorOffset = index / SPI_FLASH_SEC_SIZE;
int sectorIndex = index % SPI_FLASH_SEC_SIZE;
uint8_t* dataIndex = data + sectorIndex;
_sector += sectorOffset;
// load entire sector from flash into memory
noInterrupts();
spi_flash_read(_sector * SPI_FLASH_SEC_SIZE, reinterpret_cast<uint32_t*>(data), FLASH_EEPROM_SIZE);
interrupts();
// store struct into this block
memcpy(dataIndex, memAddress, datasize);
noInterrupts();
// write sector back to flash
if (spi_flash_erase_sector(_sector) == SPI_FLASH_RESULT_OK)
if (spi_flash_write(_sector * SPI_FLASH_SEC_SIZE, reinterpret_cast<uint32_t*>(data), FLASH_EEPROM_SIZE) == SPI_FLASH_RESULT_OK)
{
//Serial.println("flash save ok");
}
interrupts();
delete [] data;
String log = F("FLASH: Settings saved");
addLog(LOG_LEVEL_INFO, log);
flashWrites++;
}
/********************************************************************************************\
Load data from flash
\*********************************************************************************************/
void LoadFromFlash(int index, byte* memAddress, int datasize)
{
uint32_t _sector = ((uint32_t)&_SPIFFS_start - 0x40200000) / SPI_FLASH_SEC_SIZE;
uint8_t* data = new uint8_t[FLASH_EEPROM_SIZE];
int sectorOffset = index / SPI_FLASH_SEC_SIZE;
int sectorIndex = index % SPI_FLASH_SEC_SIZE;
uint8_t* dataIndex = data + sectorIndex;
_sector += sectorOffset;
// load entire sector from flash into memory
noInterrupts();
spi_flash_read(_sector * SPI_FLASH_SEC_SIZE, reinterpret_cast<uint32_t*>(data), FLASH_EEPROM_SIZE);
interrupts();
// load struct from this block
memcpy(memAddress, dataIndex, datasize);
delete [] data;
}
/********************************************************************************************\
Erase data on flash
\*********************************************************************************************/
void ZeroFillFlash()
{
// this will fill the SPIFFS area with a 64k block of all zeroes.
uint32_t _sectorStart = ((uint32_t)&_SPIFFS_start - 0x40200000) / SPI_FLASH_SEC_SIZE;
uint32_t _sectorEnd = _sectorStart + 16 ; //((uint32_t)&_SPIFFS_end - 0x40200000) / SPI_FLASH_SEC_SIZE;
uint8_t* data = new uint8_t[FLASH_EEPROM_SIZE];
uint8_t* tmpdata = data;
for (int x = 0; x < FLASH_EEPROM_SIZE; x++)
{
*tmpdata = 0;
tmpdata++;
}
for (uint32_t _sector = _sectorStart; _sector < _sectorEnd; _sector++)
{
// write sector to flash
noInterrupts();
if (spi_flash_erase_sector(_sector) == SPI_FLASH_RESULT_OK)
if (spi_flash_write(_sector * SPI_FLASH_SEC_SIZE, reinterpret_cast<uint32_t*>(data), FLASH_EEPROM_SIZE) == SPI_FLASH_RESULT_OK)
{
interrupts();
Serial.print(F("FLASH: Zero Fill Sector: "));
Serial.println(_sector);
delay(10);
}
}
interrupts();
delete [] data;
}
/********************************************************************************************\
Erase all content on flash (except sketch)
\*********************************************************************************************/
void EraseFlash()
{
uint32_t _sectorStart = (ESP.getSketchSize() / SPI_FLASH_SEC_SIZE) + 1;
uint32_t _sectorEnd = _sectorStart + (ESP.getFlashChipRealSize() / SPI_FLASH_SEC_SIZE);
for (uint32_t _sector = _sectorStart; _sector < _sectorEnd; _sector++)
{
noInterrupts();
if (spi_flash_erase_sector(_sector) == SPI_FLASH_RESULT_OK)
{
interrupts();
Serial.print(F("FLASH: Erase Sector: "));
Serial.println(_sector);
delay(10);
}
interrupts();
}
}
/********************************************************************************************\
Check SPIFFS area settings
\*********************************************************************************************/
int SpiffsSectors()
{
uint32_t _sectorStart = ((uint32_t)&_SPIFFS_start - 0x40200000) / SPI_FLASH_SEC_SIZE;
uint32_t _sectorEnd = ((uint32_t)&_SPIFFS_end - 0x40200000) / SPI_FLASH_SEC_SIZE;
return _sectorEnd - _sectorStart;
}
/********************************************************************************************\
Reset all settings to factory defaults
\*********************************************************************************************/
void ResetFactory(void)
{
// Direct Serial is allowed here, since this is only an emergency task.
byte bootCount = 0;
if (readFromRTC(&bootCount))
{
Serial.print(F("RESET: Reboot count: "));
Serial.println(bootCount);
if (bootCount > 3)
{
Serial.println(F("RESET: To many reset attempts"));
return;
}
}
else
Serial.println(F("RESET: Cold boot"));
bootCount++;
saveToRTC(bootCount);
#if FEATURE_SPIFFS
File f = SPIFFS.open("config.txt", "w");
if (f)
{
for (int x = 0; x < 32768; x++)
f.write(0);
f.close();
}
f = SPIFFS.open("security.txt", "w");
if (f)
{
for (int x = 0; x < 512; x++)
f.write(0);
f.close();
}
f = SPIFFS.open("rules.txt", "w");
f.close();
#else
EraseFlash();
ZeroFillFlash();
#endif
LoadSettings();
// now we set all parameters that need to be non-zero as default value
#if DEFAULT_USE_STATIC_IP
str2ip((char*)DEFAULT_IP, Settings.IP);
str2ip((char*)DEFAULT_DNS, Settings.DNS);
str2ip((char*)DEFAULT_GW, Settings.Gateway);
str2ip((char*)DEFAULT_SUBNET, Settings.Subnet);
#endif
#if DEFAULT_MQTT_TEMPLATE
strcpy_P(Settings.MQTTsubscribe, PSTR(DEFAULT_MQTT_SUB));
strcpy_P(Settings.MQTTpublish, PSTR(DEFAULT_MQTT_PUB));
#endif
Settings.PID = ESP_PROJECT_PID;
Settings.Version = VERSION;
Settings.Unit = UNIT;
strcpy_P(SecuritySettings.WifiSSID, PSTR(DEFAULT_SSID));
strcpy_P(SecuritySettings.WifiKey, PSTR(DEFAULT_KEY));
strcpy_P(SecuritySettings.WifiAPKey, PSTR(DEFAULT_AP_KEY));
SecuritySettings.Password[0] = 0;
str2ip((char*)DEFAULT_SERVER, Settings.Controller_IP);
Settings.ControllerPort = DEFAULT_PORT;
Settings.Delay = DEFAULT_DELAY;
Settings.Pin_i2c_sda = 4;
Settings.Pin_i2c_scl = 5;
Settings.Pin_status_led = -1;
Settings.Protocol = DEFAULT_PROTOCOL;
strcpy_P(Settings.Name, PSTR(DEFAULT_NAME));
Settings.SerialLogLevel = 2;
Settings.WebLogLevel = 2;
Settings.BaudRate = 115200;
Settings.MessageDelay = 1000;
Settings.deepSleep = false;
Settings.CustomCSS = false;
for (byte x = 0; x < TASKS_MAX; x++)
{
Settings.TaskDevicePin1[x] = -1;
Settings.TaskDevicePin2[x] = -1;
Settings.TaskDevicePin3[x] = -1;
Settings.TaskDevicePin1PullUp[x] = true;
Settings.TaskDevicePin1Inversed[x] = false;
Settings.TaskDeviceSendData[x] = true;
Settings.TaskDeviceTimer[x] = Settings.Delay;
}
Settings.Build = BUILD;
Settings.UseSerial = true;
SaveSettings();
delay(1000);
WiFi.persistent(true); // use SDK storage of SSID/WPA parameters
WiFi.disconnect(); // this will store empty ssid/wpa into sdk storage
WiFi.persistent(false); // Do not use SDK storage of SSID/WPA parameters
ESP.reset();
}
/********************************************************************************************\