Advertisement
honey_the_codewitch

partial NTP

Apr 3rd, 2022
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.33 KB | None | 0 0
  1. uint32_t g_networkClockSyncTS = 0;
  2. time_t networkReceiveNTPTime() {
  3.   // if we got a packet from NTP, read it
  4.   if (0 < g_networkUDP.parsePacket()) {
  5.     g_networkUDP.read(g_networkNTPPacketBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
  6.  
  7.     //the timestamp starts at byte 40 of the received packet and is four bytes,
  8.     // or two words, long. First, extract the two words:
  9.  
  10.     unsigned long highWord = word(g_networkNTPPacketBuffer[40], g_networkNTPPacketBuffer[41]);
  11.     unsigned long lowWord = word(g_networkNTPPacketBuffer[42], g_networkNTPPacketBuffer[43]);
  12.     // combine the four bytes (two words) into a long integer
  13.     // this is NTP time (seconds since Jan 1 1900):
  14.     unsigned long secsSince1900 = highWord << 16 | lowWord;
  15.     // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
  16.     const unsigned long seventyYears = 2208988800UL;
  17.     // subtract seventy years:
  18.     return secsSince1900 - seventyYears;
  19.   }
  20.   return 0;
  21. }
  22. // send an NTP request to the time server
  23. void networkSendNTPPacket() {
  24.   IPAddress ntpIP;
  25.   WiFi.hostByName(NTP_SERVER, ntpIP);
  26.   // set all bytes in the buffer to 0
  27.   memset(g_networkNTPPacketBuffer, 0, NTP_PACKET_SIZE);
  28.   // Initialize values needed to form NTP request
  29.   g_networkNTPPacketBuffer[0] = 0b11100011;   // LI, Version, Mode
  30.   g_networkNTPPacketBuffer[1] = 0;     // Stratum, or type of clock
  31.   g_networkNTPPacketBuffer[2] = 6;     // Polling Interval
  32.   g_networkNTPPacketBuffer[3] = 0xEC;  // Peer Clock Precision
  33.   // 8 bytes of zero for Root Delay & Root Dispersion
  34.   g_networkNTPPacketBuffer[12]  = 49;
  35.   g_networkNTPPacketBuffer[13]  = 0x4E;
  36.   g_networkNTPPacketBuffer[14]  = 49;
  37.   g_networkNTPPacketBuffer[15]  = 52;
  38.  
  39.   // all NTP fields have been given values, now
  40.   // you can send a packet requesting a timestamp:
  41.   g_networkUDP.beginPacket(ntpIP, 123); //NTP requests are to port 123
  42.   g_networkUDP.write(g_networkNTPPacketBuffer, NTP_PACKET_SIZE);
  43.   g_networkUDP.endPacket();
  44. }
  45. void beginNetworkClock() {
  46.   beginNetworkUDP();
  47. }
  48. void networkSyncClock() {
  49.   if (WL_CONNECTED == WiFi.status()) {
  50.     uint32_t ms = millis();
  51.     if (ms - g_networkClockSyncTS > (1000 * NTP_SYNC_FREQUENCY)) {
  52.       g_networkClockSyncTS = ms;
  53.       networkSendNTPPacket();
  54.     }
  55.     time_t t = networkReceiveNTPTime();
  56.     if (0 != t)
  57.       clockSet(t);
  58.   }
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement