forked from ropg/ezTime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathezTime.cpp
1512 lines (1324 loc) · 48 KB
/
ezTime.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 <Arduino.h>
#include <ezTime.h>
#ifdef EZTIME_NETWORK_ENABLE
#ifdef EZTIME_CACHE_NVS
#include <Preferences.h> // For timezone lookup cache
#endif
#ifdef EZTIME_CACHE_EEPROM
#include <EEPROM.h>
#endif
#if defined(ESP8266)
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#elif defined(ARDUINO_SAMD_MKR1000)
#include <SPI.h>
#include <WiFi101.h>
#include <WiFiUdp.h>
#elif defined(EZTIME_ETHERNET)
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#elif defined(EZTIME_WIFIESP)
#include <WifiEsp.h>
#include <WifiEspUdp.h>
#else
#include <WiFi.h>
#include <WiFiUdp.h>
#endif
#endif
#if defined(EZTIME_MAX_DEBUGLEVEL_NONE)
#define err(args...) ""
#define errln(args...) ""
#define info(args...) ""
#define infoln(args...) ""
#define debug(args...) ""
#define debugln(args...) ""
#elif defined(EZTIME_MAX_DEBUGLEVEL_ERROR)
#define err(args...) if (_debug_level >= ERROR) _debug_device->print(args)
#define errln(args...) if (_debug_level >= ERROR) _debug_device->println(args)
#define info(args...) ""
#define infoln(args...) ""
#define debug(args...) ""
#define debugln(args...) ""
#elif defined(EZTIME_MAX_DEBUGLEVEL_INFO)
#define err(args...) if (_debug_level >= ERROR) _debug_device->print(args)
#define errln(args...) if (_debug_level >= ERROR) _debug_device->println(args)
#define info(args...) if (_debug_level >= INFO) _debug_device->print(args)
#define infoln(args...) if (_debug_level >= INFO) _debug_device->println(args)
#define debug(args...) ""
#define debugln(args...) ""
#else // nothing specified compiles everything in.
#define err(args...) if (_debug_level >= ERROR) _debug_device->print(args)
#define errln(args...) if (_debug_level >= ERROR) _debug_device->println(args)
#define info(args...) if (_debug_level >= INFO) _debug_device->print(args)
#define infoln(args...) if (_debug_level >= INFO) _debug_device->println(args)
#define debug(args...) if (_debug_level >= DEBUG) _debug_device->print(args)
#define debugln(args...) if (_debug_level >= DEBUG) _debug_device->println(args)
#endif
const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31}; // API starts months from 1, this array starts from 0
// The private things go in an anonymous namespace
namespace {
ezError_t _last_error = NO_ERROR;
String _server_error = "";
ezDebugLevel_t _debug_level = NONE;
Print *_debug_device = (Print *)&Serial;
ezEvent_t _events[MAX_EVENTS];
time_t _last_sync_time = 0;
time_t _last_read_t = 0;
uint32_t _last_sync_millis = 0;
uint16_t _last_read_ms;
timeStatus_t _time_status;
bool _initialised = false;
#ifdef EZTIME_NETWORK_ENABLE
uint16_t _ntp_interval = NTP_INTERVAL;
String _ntp_server = NTP_SERVER;
#endif
void triggerError(const ezError_t err) {
_last_error = err;
if (_last_error) {
err(F("ERROR: "));
errln(ezt::errorString(err));
}
}
String debugLevelString(const ezDebugLevel_t level) {
switch (level) {
case NONE: return F("NONE");
case ERROR: return F("ERROR");
case INFO: return F("INFO");
default: return F("DEBUG");
}
}
time_t nowUTC(const bool update_last_read = true) {
time_t t;
uint32_t m = millis();
t = _last_sync_time + ((m - _last_sync_millis) / 1000);
if (update_last_read) {
_last_read_t = t;
_last_read_ms = (m - _last_sync_millis) % 1000;
}
return t;
}
}
namespace ezt {
////////// Error handing
String errorString(const ezError_t err /* = LAST_ERROR */) {
switch (err) {
case NO_ERROR: return F("OK");
case LAST_ERROR: return errorString(_last_error);
case NO_NETWORK: return F("No network");
case TIMEOUT: return F("Timeout");
case CONNECT_FAILED: return F("Connect Failed");
case DATA_NOT_FOUND: return F("Data not found");
case LOCKED_TO_UTC: return F("Locked to UTC");
case NO_CACHE_SET: return F("No cache set");
case CACHE_TOO_SMALL: return F("Cache too small");
case TOO_MANY_EVENTS: return F("Too many events");
case INVALID_DATA: return F("Invalid data received from NTP server");
case SERVER_ERROR: return _server_error;
default: return F("Unkown error");
}
}
ezError_t error(const bool reset /* = false */) {
ezError_t tmp = _last_error;
if (reset) _last_error = NO_ERROR;
return tmp;
}
void setDebug(const ezDebugLevel_t level) {
setDebug(level, *_debug_device);
}
void setDebug(const ezDebugLevel_t level, Print &device) {
_debug_level = level;
_debug_device = &device;
info(F("\r\nezTime debug level set to "));
infoln(debugLevelString(level));
}
// The include below includes the dayStr, dayShortStr, monthStr and monthShortStr from the appropriate language file
// in the /src/lang subdirectory.
#ifdef EZTIME_LANGUAGE
#define XSTR(x) #x
#define STR(x) XSTR(x)
#include STR(lang/EZTIME_LANGUAGE)
#else
#include "lang/EN"
#endif
//
timeStatus_t timeStatus() { return _time_status; }
void events() {
if (!_initialised) {
for (uint8_t n = 0; n < MAX_EVENTS; n++) _events[n] = { 0, NULL };
#ifdef EZTIME_NETWORK_ENABLE
if (_ntp_interval) updateNTP(); // Start the cycle of updateNTP running and then setting an event for its next run
#endif
_initialised = true;
}
// See if any events are due
for (uint8_t n = 0; n < MAX_EVENTS; n++) {
if (_events[n].function && nowUTC(false) >= _events[n].time) {
debug(F("Running event (#")); debug(n + 1); debug(F(") set for ")); debugln(UTC.dateTime(_events[n].time));
void (*tmp)() = _events[n].function;
_events[n] = { 0, NULL }; // reset the event
(tmp)(); // execute the function
}
}
yield();
}
void deleteEvent(const uint8_t event_handle) {
if (event_handle && event_handle <= MAX_EVENTS) {
debug(F("Deleted event (#")); debug(event_handle); debug(F("), set for ")); debugln(UTC.dateTime(_events[event_handle - 1].time));
_events[event_handle - 1] = { 0, NULL };
}
}
void deleteEvent(void (*function)()) {
for (uint8_t n = 0; n< MAX_EVENTS; n++) {
if (_events[n].function == function) {
debug(F("Deleted event (#")); debug(n + 1); debug(F("), set for ")); debugln(UTC.dateTime(_events[n].time));
_events[n] = { 0, NULL };
}
}
}
void breakTime(const time_t timeInput, tmElements_t &tm){
// break the given time_t into time components
// this is a more compact version of the C library localtime function
// note that year is offset from 1970 !!!
uint8_t year;
uint8_t month, monthLength;
uint32_t time;
unsigned long days;
time = (uint32_t)timeInput;
tm.Second = time % 60;
time /= 60; // now it is minutes
tm.Minute = time % 60;
time /= 60; // now it is hours
tm.Hour = time % 24;
time /= 24; // now it is days
tm.Wday = ((time + 4) % 7) + 1; // Sunday is day 1
year = 0;
days = 0;
while((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= time) {
year++;
}
tm.Year = year; // year is offset from 1970
days -= LEAP_YEAR(year) ? 366 : 365;
time -= days; // now it is days in this year, starting at 0
days=0;
month=0;
monthLength=0;
for (month=0; month<12; month++) {
if (month==1) { // february
if (LEAP_YEAR(year)) {
monthLength=29;
} else {
monthLength=28;
}
} else {
monthLength = monthDays[month];
}
if (time >= monthLength) {
time -= monthLength;
} else {
break;
}
}
tm.Month = month + 1; // jan is month 1
tm.Day = time + 1; // day of month
}
time_t makeTime(const uint8_t hour, const uint8_t minute, const uint8_t second, const uint8_t day, const uint8_t month, const uint16_t year) {
tmElements_t tm;
tm.Hour = hour;
tm.Minute = minute;
tm.Second = second;
tm.Day = day;
tm.Month = month;
if (year > 68) { // time_t cannot reach beyond 68 + 1970 anyway, so if bigger user means actual years
tm.Year = year - 1970;
} else {
tm.Year = year;
}
return makeTime(tm);
}
time_t makeTime(tmElements_t &tm){
// assemble time elements into time_t
// note year argument is offset from 1970 (see macros in time.h to convert to other formats)
// previous version used full four digit year (or digits since 2000),i.e. 2009 was 2009 or 9
int i;
uint32_t seconds;
// seconds from 1970 till 1 jan 00:00:00 of the given year
seconds= tm.Year * SECS_PER_DAY * 365UL;
for (i = 0; i < tm.Year; i++) {
if (LEAP_YEAR(i)) {
seconds += SECS_PER_DAY; // add extra days for leap years
}
}
// add days for this year, months start from 1
for (i = 1; i < tm.Month; i++) {
if ( (i == 2) && LEAP_YEAR(tm.Year)) {
seconds += SECS_PER_DAY * 29UL;
} else {
seconds += SECS_PER_DAY * (uint32_t)monthDays[i-1]; //monthDay array starts from 0
}
}
seconds+= (tm.Day-1) * SECS_PER_DAY;
seconds+= tm.Hour * 3600UL;
seconds+= tm.Minute * 60UL;
seconds+= tm.Second;
return (time_t)seconds;
}
// makeOrdinalTime allows you to resolve "second thursday in September in 2018" into a number of seconds since 1970
// (Very useful for the timezone calculations that ezTime does internally)
// If ordinal is 0 or 5 it is taken to mean "the last $wday in $month"
time_t makeOrdinalTime(const uint8_t hour, const uint8_t minute, uint8_t const second, uint8_t ordinal, const uint8_t wday, const uint8_t month, uint16_t year) {
if (year <= 68 ) year = 1970 + year; // fix user intent
uint8_t m = month;
uint8_t w = ordinal;
if (w == 5) {
ordinal = 0;
w = 0;
}
if (w == 0) { // is this a "Last week" rule?
if (++m > 12) { // yes, for "Last", go to the next month
m = 1;
++year;
}
w = 1; // and treat as first week of next month, subtract 7 days later
}
time_t t = makeTime(hour, minute, second, 1, m, year);
// add offset from the first of the month to weekday, and offset for the given week
t += ( (wday - UTC.weekday(t) + 7) % 7 + (w - 1) * 7 ) * SECS_PER_DAY;
// back up a week if this is a "Last" rule
if (ordinal == 0) t -= 7 * SECS_PER_DAY;
return t;
}
String zeropad(const uint32_t number, const uint8_t length) {
String out;
out.reserve(length);
out = String(number);
while (out.length() < length) out = "0" + out;
return out;
}
time_t compileTime(const String compile_date /* = __DATE__ */, const String compile_time /* = __TIME__ */) {
uint8_t hrs = compile_time.substring(0,2).toInt();
uint8_t min = compile_time.substring(3,5).toInt();
uint8_t sec = compile_time.substring(6).toInt();
uint8_t day = compile_date.substring(4,6).toInt();
int16_t year = compile_date.substring(7).toInt();
String iterate_month;
for (uint8_t month = 1; month < 13; month++) {
iterate_month = monthStr(month);
if ( iterate_month.substring(0,3) == compile_date.substring(0,3) ) {
return makeTime(hrs, min, sec, day, month, year);
}
}
return 0;
}
bool secondChanged() {
time_t t = nowUTC(false);
if (_last_read_t != t) return true;
return false;
}
bool minuteChanged() {
time_t t = nowUTC(false);
if (_last_read_t / 60 != t / 60) return true;
return false;
}
#ifdef EZTIME_NETWORK_ENABLE
void updateNTP() {
deleteEvent(updateNTP); // Delete any events pointing here, in case called manually
time_t t;
unsigned long measured_at;
if (queryNTP(_ntp_server, t, measured_at)) {
int32_t correction = ( (t - _last_sync_time) * 1000 ) - ( measured_at - _last_sync_millis );
_last_sync_time = t;
_last_sync_millis = measured_at;
_last_read_ms = ( millis() - measured_at) % 1000;
info(F("Received time: "));
info(UTC.dateTime(t, F("l, d-M-y H:i:s.v T")));
if (_time_status != timeNotSet) {
info(F(" (internal clock was "));
if (!correction) {
infoln(F("spot on)"));
} else {
info(String(abs(correction)));
if (correction > 0) {
infoln(F(" ms fast)"));
} else {
infoln(F(" ms slow)"));
}
}
} else {
infoln("");
}
if (_ntp_interval) UTC.setEvent(updateNTP, t + _ntp_interval);
_time_status = timeSet;
} else {
if ( nowUTC(false) > _last_sync_time + _ntp_interval + NTP_STALE_AFTER ) {
_time_status = timeNeedsSync;
}
UTC.setEvent(updateNTP, nowUTC(false) + NTP_RETRY);
}
}
// This is a nice self-contained NTP routine if you need one: feel free to use it.
// It gives you the seconds since 1970 (unix epoch) and the millis() on your system when
// that happened (by deducting fractional seconds and estimated network latency).
bool queryNTP(const String server, time_t &t, unsigned long &measured_at) {
info(F("Querying "));
info(server);
info(F(" ... "));
#ifndef EZTIME_ETHERNET
if (WiFi.status() != WL_CONNECTED) { triggerError(NO_NETWORK); return false; }
#ifndef EZTIME_WIFIESP
WiFiUDP udp;
#else
WiFiEspUDP udp;
#endif
#else
EthernetUDP udp;
#endif
// Send NTP packet
byte buffer[NTP_PACKET_SIZE];
memset(buffer, 0, NTP_PACKET_SIZE);
buffer[0] = 0b11100011; // LI, Version, Mode
buffer[1] = 0; // Stratum, or type of clock
buffer[2] = 9; // Polling Interval (9 = 2^9 secs = ~9 mins, close to our 10 min default)
buffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
buffer[12] = 'X'; // "kiss code", see RFC5905
buffer[13] = 'E'; // (codes starting with 'X' are not interpreted)
buffer[14] = 'Z';
buffer[15] = 'T';
udp.flush();
udp.begin(NTP_LOCAL_PORT);
unsigned long started = millis();
udp.beginPacket(server.c_str(), 123); //NTP requests are to port 123
udp.write(buffer, NTP_PACKET_SIZE);
udp.endPacket();
// Wait for packet or return false with timed out
while (!udp.parsePacket()) {
delay (1);
if (millis() - started > NTP_TIMEOUT) {
udp.stop();
triggerError(TIMEOUT);
return false;
}
}
udp.read(buffer, NTP_PACKET_SIZE);
udp.stop(); // On AVR there's only very limited sockets, we want to free them when done.
//print out received packet for debug
int i;
debug(F("Received data:"));
for (i = 0; i < NTP_PACKET_SIZE; i++) {
if ((i % 4) == 0) {
debugln();
debug(String(i) + ": ");
}
debug(buffer[i], HEX);
debug(F(", "));
}
debugln();
//prepare timestamps
uint32_t highWord, lowWord;
highWord = ( buffer[16] << 8 | buffer[17] ) & 0x0000FFFF;
lowWord = ( buffer[18] << 8 | buffer[19] ) & 0x0000FFFF;
uint32_t reftsSec = highWord << 16 | lowWord; // reference timestamp seconds
highWord = ( buffer[32] << 8 | buffer[33] ) & 0x0000FFFF;
lowWord = ( buffer[34] << 8 | buffer[35] ) & 0x0000FFFF;
uint32_t rcvtsSec = highWord << 16 | lowWord; // receive timestamp seconds
highWord = ( buffer[40] << 8 | buffer[41] ) & 0x0000FFFF;
lowWord = ( buffer[42] << 8 | buffer[43] ) & 0x0000FFFF;
uint32_t secsSince1900 = highWord << 16 | lowWord; // transmit timestamp seconds
highWord = ( buffer[44] << 8 | buffer[45] ) & 0x0000FFFF;
lowWord = ( buffer[46] << 8 | buffer[47] ) & 0x0000FFFF;
uint32_t fraction = highWord << 16 | lowWord; // transmit timestamp fractions
//check if received data makes sense
//buffer[1] = stratum - should be 1..15 for valid reply
//also checking that all timestamps are non-zero and receive timestamp seconds are <= transmit timestamp seconds
if ((buffer[1] < 1) or (buffer[1] > 15) or (reftsSec == 0) or (rcvtsSec == 0) or (rcvtsSec > secsSince1900)) {
// we got invalid packet
triggerError(INVALID_DATA);
return false;
}
// Set the t and measured_at variables that were passed by reference
uint32_t done = millis();
info(F("success (round trip ")); info(done - started); infoln(F(" ms)"));
t = secsSince1900 - 2208988800UL; // Subtract 70 years to get seconds since 1970
uint16_t ms = fraction / 4294967UL; // Turn 32 bit fraction into ms by dividing by 2^32 / 1000
measured_at = done - ((done - started) / 2) - ms; // Assume symmetric network latency and return when we think the whole second was.
return true;
}
void setInterval(const uint16_t seconds /* = 0 */) {
deleteEvent(updateNTP);
_ntp_interval = seconds;
if (seconds) UTC.setEvent(updateNTP, nowUTC(false) + _ntp_interval);
}
void setServer(const String ntp_server /* = NTP_SERVER */) { _ntp_server = ntp_server; }
bool waitForSync(const uint16_t timeout /* = 0 */) {
unsigned long start = millis();
#if !defined(EZTIME_ETHERNET)
if (WiFi.status() != WL_CONNECTED) {
info(F("Waiting for WiFi ... "));
while (WiFi.status() != WL_CONNECTED) {
if ( timeout && (millis() - start) / 1000 > timeout ) { triggerError(TIMEOUT); return false;};
events();
delay(25);
}
infoln(F("connected"));
}
#endif
if (_time_status != timeSet) {
infoln(F("Waiting for time sync"));
while (_time_status != timeSet) {
if ( timeout && (millis() - start) / 1000 > timeout ) { triggerError(TIMEOUT); return false;};
delay(250);
events();
}
infoln(F("Time is in sync"));
}
return true;
}
time_t lastNtpUpdateTime() { return _last_sync_time; }
#endif // EZTIME_NETWORK_ENABLE
}
//
// Timezone class
//
Timezone::Timezone(const bool locked_to_UTC /* = false */) {
_locked_to_UTC = locked_to_UTC;
_posix = "UTC";
#ifdef EZTIME_NETWORK_ENABLE
#ifdef EZTIME_CACHE_EEPROM
_cache_month = 0;
_eeprom_address = -1;
#endif
#ifdef EZTIME_CACHE_NVS
_cache_month = 0;
_nvs_name = "";
_nvs_key = "";
#endif
_olson = "";
#endif
}
bool Timezone::setPosix(const String posix) {
if (_locked_to_UTC) { triggerError(LOCKED_TO_UTC); return false; }
_posix = posix;
#ifdef EZTIME_NETWORK_ENABLE
_olson = "";
#endif
return true;
}
time_t Timezone::now() { return tzTime(); }
time_t Timezone::tzTime(time_t t /* = TIME_NOW */, ezLocalOrUTC_t local_or_utc /* = LOCAL_TIME */) {
if (_locked_to_UTC) return nowUTC(); // just saving some time and memory
String tzname;
bool is_dst;
int16_t offset;
return tzTime(t, local_or_utc, tzname, is_dst, offset);
}
time_t Timezone::tzTime(time_t t, ezLocalOrUTC_t local_or_utc, String &tzname, bool &is_dst, int16_t &offset) {
if (t == TIME_NOW) {
t = nowUTC();
local_or_utc = UTC_TIME;
} else if (t == LAST_READ) {
t = _last_read_t;
local_or_utc = UTC_TIME;
}
int8_t offset_hr = 0;
uint8_t offset_min = 0;
int8_t dst_shift_hr = 1;
uint8_t dst_shift_min = 0;
uint8_t start_month = 0, start_week = 0, start_dow = 0, start_time_hr = 2, start_time_min = 0;
uint8_t end_month = 0, end_week = 0, end_dow = 0, end_time_hr = 2, end_time_min = 0;
enum posix_state_e {STD_NAME, OFFSET_HR, OFFSET_MIN, DST_NAME, DST_SHIFT_HR, DST_SHIFT_MIN, START_MONTH, START_WEEK, START_DOW, START_TIME_HR, START_TIME_MIN, END_MONTH, END_WEEK, END_DOW, END_TIME_HR, END_TIME_MIN};
posix_state_e state = STD_NAME;
bool ignore_nums = false;
char c = 1; // Dummy value to get while(newchar) started
uint8_t strpos = 0;
uint8_t stdname_end = _posix.length() - 1;
uint8_t dstname_begin = _posix.length();
uint8_t dstname_end = _posix.length();
while (strpos < _posix.length()) {
c = (char)_posix[strpos];
// Do not replace the code below with switch statement: evaluation of state that
// changes while this runs. (Only works because this state can only go forward.)
if (c && state == STD_NAME) {
if (c == '<') ignore_nums = true;
if (c == '>') ignore_nums = false;
if (!ignore_nums && (isDigit(c) || c == '-' || c == '+')) {
state = OFFSET_HR;
stdname_end = strpos - 1;
}
}
if (c && state == OFFSET_HR) {
if (c == '+') {
// Ignore the plus
} else if (c == ':') {
state = OFFSET_MIN;
c = 0;
} else if (c != '-' && !isDigit(c)) {
state = DST_NAME;
dstname_begin = strpos;
} else {
if (!offset_hr) offset_hr = atoi(_posix.c_str() + strpos);
}
}
if (c && state == OFFSET_MIN) {
if (!isDigit(c)) {
state = DST_NAME;
dstname_begin = strpos;
ignore_nums = false;
} else {
if (!offset_min) offset_min = atoi(_posix.c_str() + strpos);
}
}
if (c && state == DST_NAME) {
if (c == '<') ignore_nums = true;
if (c == '>') ignore_nums = false;
if (c == ',') {
state = START_MONTH;
c = 0;
dstname_end = strpos - 1;
} else if (!ignore_nums && (c == '-' || isDigit(c))) {
state = DST_SHIFT_HR;
dstname_end = strpos - 1;
}
}
if (c && state == DST_SHIFT_HR) {
if (c == ':') {
state = DST_SHIFT_MIN;
c = 0;
} else if (c == ',') {
state = START_MONTH;
c = 0;
} else if (dst_shift_hr == 1) dst_shift_hr = atoi(_posix.c_str() + strpos);
}
if (c && state == DST_SHIFT_MIN) {
if (c == ',') {
state = START_MONTH;
c = 0;
} else if (!dst_shift_min) dst_shift_min = atoi(_posix.c_str() + strpos);
}
if (c && state == START_MONTH) {
if (c == '.') {
state = START_WEEK;
c = 0;
} else if (c != 'M' && !start_month) start_month = atoi(_posix.c_str() + strpos);
}
if (c && state == START_WEEK) {
if (c == '.') {
state = START_DOW;
c = 0;
} else start_week = c - '0';
}
if (c && state == START_DOW) {
if (c == '/') {
state = START_TIME_HR;
c = 0;
} else if (c == ',') {
state = END_MONTH;
c = 0;
} else start_dow = c - '0';
}
if (c && state == START_TIME_HR) {
if (c == ':') {
state = START_TIME_MIN;
c = 0;
} else if (c == ',') {
state = END_MONTH;
c = 0;
} else if (start_time_hr == 2) start_time_hr = atoi(_posix.c_str() + strpos);
}
if (c && state == START_TIME_MIN) {
if (c == ',') {
state = END_MONTH;
c = 0;
} else if (!start_time_min) start_time_min = atoi(_posix.c_str() + strpos);
}
if (c && state == END_MONTH) {
if (c == '.') {
state = END_WEEK;
c = 0;
} else if (c != 'M') if (!end_month) end_month = atoi(_posix.c_str() + strpos);
}
if (c && state == END_WEEK) {
if (c == '.') {
state = END_DOW;
c = 0;
} else end_week = c - '0';
}
if (c && state == END_DOW) {
if (c == '/') {
state = END_TIME_HR;
c = 0;
} else end_dow = c - '0';
}
if (c && state == END_TIME_HR) {
if (c == ':') {
state = END_TIME_MIN;
c = 0;
} else if (end_time_hr == 2) end_time_hr = atoi(_posix.c_str() + strpos);
}
if (c && state == END_TIME_MIN) {
if (!end_time_min) end_time_min = atoi(_posix.c_str() + strpos);
}
strpos++;
}
int16_t std_offset = (offset_hr < 0) ? offset_hr * 60 - offset_min : offset_hr * 60 + offset_min;
tzname = _posix.substring(0, stdname_end + 1); // Overwritten with dstname later if needed
if (!start_month) {
if (tzname == "UTC" && std_offset) tzname = "???";
is_dst = false;
offset = std_offset;
} else {
int16_t dst_offset = std_offset - dst_shift_hr * 60 - dst_shift_min;
// to find the year
tmElements_t tm;
ezt::breakTime(t, tm);
// in local time
time_t dst_start = ezt::makeOrdinalTime(start_time_hr, start_time_min, 0, start_week, start_dow + 1, start_month, tm.Year + 1970);
time_t dst_end = ezt::makeOrdinalTime(end_time_hr, end_time_min, 0, end_week, end_dow + 1, end_month, tm.Year + 1970);
if (local_or_utc == UTC_TIME) {
dst_start += std_offset * 60LL;
dst_end += dst_offset * 60LL;
}
if (dst_end > dst_start) {
is_dst = (t >= dst_start && t < dst_end); // northern hemisphere
} else {
is_dst = !(t >= dst_end && t < dst_start); // southern hemisphere
}
if (is_dst) {
offset = dst_offset;
tzname = _posix.substring(dstname_begin, dstname_end + 1);
} else {
offset = std_offset;
}
}
if (local_or_utc == LOCAL_TIME) {
return t + offset * 60LL;
} else {
return t - offset * 60LL;
}
}
String Timezone::getPosix() { return _posix; }
#ifdef EZTIME_NETWORK_ENABLE
bool Timezone::setLocation(const String location /* = "GeoIP" */) {
info(F("Timezone lookup for: "));
info(location);
info(F(" ... "));
if (_locked_to_UTC) { triggerError(LOCKED_TO_UTC); return false; }
#ifndef EZTIME_ETHERNET
if (WiFi.status() != WL_CONNECTED) { triggerError(NO_NETWORK); return false; }
#ifndef EZTIME_WIFIESP
WiFiUDP udp;
#else
WiFiEspUDP udp;
#endif
#else
EthernetUDP udp;
#endif
udp.flush();
udp.begin(TIMEZONED_LOCAL_PORT);
unsigned long started = millis();
udp.beginPacket(TIMEZONED_REMOTE_HOST, TIMEZONED_REMOTE_PORT);
udp.write((const uint8_t*)location.c_str(), location.length());
udp.endPacket();
// Wait for packet or return false with timed out
while (!udp.parsePacket()) {
delay (1);
if (millis() - started > TIMEZONED_TIMEOUT) {
udp.stop();
triggerError(TIMEOUT);
return false;
}
}
// Stick result in String recv
String recv;
recv.reserve(60);
while (udp.available()) recv += (char)udp.read();
udp.stop();
info(F("(round-trip "));
info(millis() - started);
info(F(" ms) "));
if (recv.substring(0,6) == "ERROR ") {
_server_error = recv.substring(6);
error (SERVER_ERROR);
return false;
}
if (recv.substring(0,3) == "OK ") {
_olson = recv.substring(3, recv.indexOf(" ", 4));
_posix = recv.substring(recv.indexOf(" ", 4) + 1);
infoln(F("success."));
info(F(" Olson: ")); infoln(_olson);
info(F(" Posix: ")); infoln(_posix);
#if defined(EZTIME_CACHE_EEPROM) || defined(EZTIME_CACHE_NVS)
String tzinfo = _olson + " " + _posix;
writeCache(tzinfo); // caution, byref to save memory, tzinfo mangled afterwards
#endif
return true;
}
error (DATA_NOT_FOUND);
return false;
}
String Timezone::getOlson() {
return _olson;
}
String Timezone::getOlsen() {
return _olson;
}
#if defined(EZTIME_CACHE_EEPROM) || defined(EZTIME_CACHE_NVS)
#if defined(ESP32) || defined(ESP8266)
#define eepromBegin() EEPROM.begin(4096)
#define eepromEnd() EEPROM.end()
#define eepromLength() (4096)
#else
#define eepromBegin() ""
#define eepromEnd() ""
#define eepromLength() EEPROM.length()
#endif
#ifdef EZTIME_CACHE_EEPROM
bool Timezone::setCache(const int16_t address) {
eepromBegin();
if (address + EEPROM_CACHE_LEN > eepromLength()) { triggerError(CACHE_TOO_SMALL); return false; }
_eeprom_address = address;
eepromEnd();
return setCache();
}
#endif
#ifdef EZTIME_CACHE_NVS
bool Timezone::setCache(const String name, const String key) {
_nvs_name = name;
_nvs_key = key;
return setCache();
}
#endif
bool Timezone::setCache() {
String olson, posix;
uint8_t months_since_jan_2018;
if (readCache(olson, posix, months_since_jan_2018)) {
setPosix(posix);
_olson = olson;
_cache_month = months_since_jan_2018;
if ( (year() - 2018) * 12 + month(LAST_READ) - months_since_jan_2018 > MAX_CACHE_AGE_MONTHS) {
infoln(F("Cache stale, getting fresh"));
setLocation(olson);
}
return true;
}
return false;
}
void Timezone::clearCache(const bool delete_section /* = false */) {
#ifdef EZTIME_CACHE_EEPROM
eepromBegin();
if (_eeprom_address < 0) { triggerError(NO_CACHE_SET); return; }
for (int16_t n = _eeprom_address; n < _eeprom_address + EEPROM_CACHE_LEN; n++) EEPROM.write(n, 0);
eepromEnd();
#endif
#ifdef EZTIME_CACHE_NVS
if (_nvs_name == "" || _nvs_key == "") { triggerError(NO_CACHE_SET); return; }
Preferences prefs;
prefs.begin(_nvs_name.c_str(), false);
if (delete_section) {
prefs.clear();
} else {
prefs.remove(_nvs_key.c_str());
}
prefs.end();
#endif
}
bool Timezone::writeCache(String &str) {
uint8_t months_since_jan_2018 = 0;
if (year() >= 2018) months_since_jan_2018 = (year(LAST_READ) - 2018) * 12 + month(LAST_READ) - 1;
#ifdef EZTIME_CACHE_EEPROM
if (_eeprom_address < 0) return false;
info(F("Caching timezone data "));
if (str.length() > MAX_CACHE_PAYLOAD) { triggerError(CACHE_TOO_SMALL); return false; }
uint16_t last_byte = _eeprom_address + EEPROM_CACHE_LEN - 1;
uint16_t addr = _eeprom_address;
eepromBegin();
// First byte is cache age, in months since 2018
EEPROM.write(addr++, months_since_jan_2018);
// Second byte is length of payload
EEPROM.write(addr++, str.length());
// Followed by payload, compressed. Every 4 bytes to three by encoding only 6 bits, ASCII all-caps
str.toUpperCase();
uint8_t store = 0;
for (uint8_t n = 0; n < str.length(); n++) {
unsigned char c = str.charAt(n) - 32;
if ( c > 63) c = 0;
switch (n % 4) {
case 0:
store = c << 2; //all of 1st
break;
case 1:
store |= c >> 4; //high two of 2nd
EEPROM.write(addr++, store);
store = c << 4; //low four of 2nd
break;
case 2:
store |= c >> 2; //high four of 3rd
EEPROM.write(addr++, store);
store = c << 6; //low two of third
break;
case 3:
store |= c; //all of 4th
EEPROM.write(addr++, store);
store = 0;
}
}
if (store) EEPROM.write(addr++, store);
// Fill rest of cache (except last byte) with zeroes
for (; addr < last_byte; addr++) EEPROM.write(addr, 0);
// Add all bytes in cache % 256 and add 42, that is the checksum written to last byte.
// The 42 is because then checksum of all zeroes then isn't zero.
uint8_t checksum = 0;
for (uint16_t n = _eeprom_address; n < last_byte; n++) checksum += EEPROM.read(n);
checksum += 42;
EEPROM.write(last_byte, checksum);
eepromEnd();
infoln();