|
| 1 | + |
| 2 | +#include <time.h> // time() ctime() |
| 3 | +#include <sys/time.h> // struct timeval |
| 4 | +#include <ESP8266WiFi.h> |
| 5 | + |
| 6 | +//////////////////////////////////////////////////////// |
| 7 | + |
| 8 | +#define SSID "open" |
| 9 | +#define SSIDPWD "" |
| 10 | +#define TZ 1 // utc+TZ in hours |
| 11 | +#define DST_MN 60 // use 60 for summer time in some countries |
| 12 | + |
| 13 | +#define NTP0_OR_LOCAL1 1 // 0:use NTP 1:fake external RTC |
| 14 | +#define RTC_TEST 1510592825 // 1510592825 = Monday 13 November 2017 17:07:05 UTC |
| 15 | + |
| 16 | +//////////////////////////////////////////////////////// |
| 17 | + |
| 18 | +#define TZ_MN ((TZ)*60) |
| 19 | +#define TZ_SEC ((TZ)*3600) |
| 20 | +#define DST_SEC ((DST_MN)*60) |
| 21 | + |
| 22 | +void setup() { |
| 23 | + Serial.begin(115200); |
| 24 | + |
| 25 | +#if NTP0_OR_LOCAL1 |
| 26 | + |
| 27 | + // local |
| 28 | + ESP.eraseConfig(); |
| 29 | + time_t rtc = RTC_TEST; |
| 30 | + timeval tv = { rtc, 0 }; |
| 31 | + timezone tz = { TZ_MN + DST_MN, 0 }; |
| 32 | + settimeofday(&tv, &tz); |
| 33 | + |
| 34 | +#else |
| 35 | + |
| 36 | + // NTP |
| 37 | + configTime(TZ_SEC, DST_SEC, "pool.ntp.org"); |
| 38 | + WiFi.mode(WIFI_STA); |
| 39 | + WiFi.begin(SSID, SSIDPWD); |
| 40 | + // don't wait |
| 41 | + |
| 42 | +#endif |
| 43 | +} |
| 44 | + |
| 45 | +// for testing purpose: |
| 46 | +extern "C" int clock_gettime(clockid_t unused, struct timespec *tp); |
| 47 | + |
| 48 | +void loop() { |
| 49 | + |
| 50 | + // same result as with time() |
| 51 | + // but wrong with NTP |
| 52 | + timeval tv; |
| 53 | + gettimeofday(&tv, NULL); |
| 54 | + Serial.print("gtod:"); |
| 55 | + Serial.print((uint32_t)tv.tv_sec); |
| 56 | +#if 0 |
| 57 | + // but usec is wrong |
| 58 | + Serial.print("/"); |
| 59 | + Serial.print((uint32_t)tv.tv_usec); |
| 60 | +#endif |
| 61 | + |
| 62 | + // same result as with millis()/1000 |
| 63 | + timespec tp; |
| 64 | + clock_gettime(0, &tp); |
| 65 | + Serial.print(" -- clock:"); |
| 66 | + Serial.print((uint32_t)tp.tv_sec); |
| 67 | +#if 0 |
| 68 | + // nsec is wrong |
| 69 | + Serial.print("/"); |
| 70 | + Serial.print((uint32_t)tp.tv_nsec/1000000); |
| 71 | + Serial.print("ms"); |
| 72 | +#endif |
| 73 | + |
| 74 | + // gives EPOCH+tz+dst |
| 75 | + time_t now = time(nullptr); |
| 76 | + Serial.print(" -- time:"); |
| 77 | + Serial.print((uint32_t)now); |
| 78 | + |
| 79 | + // from boot: |
| 80 | + Serial.print(" -- millis:"); |
| 81 | + Serial.print((uint32_t)millis()); |
| 82 | + Serial.print(" -- micros:"); |
| 83 | + Serial.print((uint32_t)micros()); |
| 84 | + |
| 85 | + // human readable |
| 86 | + Serial.print(" -- ctime:(UTC+"); |
| 87 | + Serial.print((uint32_t)(TZ*60 + DST_MN)); |
| 88 | + Serial.print("mn)"); |
| 89 | + Serial.print(ctime(&now)); |
| 90 | + |
| 91 | + // simple drifting loop |
| 92 | + delay(1000); |
| 93 | +} |
| 94 | + |
0 commit comments