1+ #include " NTPUtils.h"
2+ #include " Arduino.h"
3+
4+ // could be a constexpr in C++14
5+ static time_t cvt_TIME (char const *time) {
6+ char s_month[5 ];
7+ int month, day, year;
8+ struct tm t = {0 };
9+ static const char month_names[] = " JanFebMarAprMayJunJulAugSepOctNovDec" ;
10+
11+ sscanf (time, " %s %d %d" , s_month, &day, &year);
12+
13+ month = (strstr (month_names, s_month)-month_names)/3 ;
14+
15+ t.tm_mon = month;
16+ t.tm_mday = day;
17+ t.tm_year = year - 1900 ;
18+ t.tm_isdst = -1 ;
19+
20+ return mktime (&t);
21+ }
22+
23+
24+ NTPUtils::NTPUtils (UDP& Udp) : Udp(Udp) {}
25+
26+ bool NTPUtils::isTimeValid (unsigned long time) {
27+ Serial.println (" Compile time: " + String (cvt_TIME (__DATE__)));
28+ return (time > cvt_TIME (__DATE__));
29+ }
30+
31+ void NTPUtils::sendNTPpacket (uint8_t * packetBuffer) {
32+ memset (packetBuffer, 0 , NTP_PACKET_SIZE);
33+ packetBuffer[0 ] = 0b11100011 ;
34+ packetBuffer[1 ] = 0 ;
35+ packetBuffer[2 ] = 6 ;
36+ packetBuffer[3 ] = 0xEC ;
37+ packetBuffer[12 ] = 49 ;
38+ packetBuffer[13 ] = 0x4E ;
39+ packetBuffer[14 ] = 49 ;
40+ packetBuffer[15 ] = 52 ;
41+ Udp.beginPacket (timeServer, 123 );
42+ Udp.write (packetBuffer, NTP_PACKET_SIZE);
43+ Udp.endPacket ();
44+ }
45+
46+ unsigned long NTPUtils::getTime () {
47+
48+ unsigned int localPort = 8888 ;
49+ uint8_t packetBuffer[NTP_PACKET_SIZE];
50+
51+ Udp.begin (localPort);
52+ sendNTPpacket (packetBuffer);
53+ long start = millis ();
54+ while (!Udp.parsePacket () && (millis () - start < 10000 )) {
55+
56+ }
57+ if (millis () - start >= 1000 ) {
58+ // timeout reached
59+ return 0 ;
60+ }
61+ Udp.read (packetBuffer, NTP_PACKET_SIZE);
62+
63+ unsigned long highWord = word (packetBuffer[40 ], packetBuffer[41 ]);
64+ unsigned long lowWord = word (packetBuffer[42 ], packetBuffer[43 ]);
65+ unsigned long secsSince1900 = highWord << 16 | lowWord;
66+ const unsigned long seventyYears = 2208988800UL ;
67+ unsigned long epoch = secsSince1900 - seventyYears;
68+
69+ Udp.stop ();
70+
71+ return epoch;
72+ }
0 commit comments