Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- uint32_t g_networkClockSyncTS = 0;
- time_t networkReceiveNTPTime() {
- // if we got a packet from NTP, read it
- if (0 < g_networkUDP.parsePacket()) {
- g_networkUDP.read(g_networkNTPPacketBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
- //the timestamp starts at byte 40 of the received packet and is four bytes,
- // or two words, long. First, extract the two words:
- unsigned long highWord = word(g_networkNTPPacketBuffer[40], g_networkNTPPacketBuffer[41]);
- unsigned long lowWord = word(g_networkNTPPacketBuffer[42], g_networkNTPPacketBuffer[43]);
- // combine the four bytes (two words) into a long integer
- // this is NTP time (seconds since Jan 1 1900):
- unsigned long secsSince1900 = highWord << 16 | lowWord;
- // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
- const unsigned long seventyYears = 2208988800UL;
- // subtract seventy years:
- return secsSince1900 - seventyYears;
- }
- return 0;
- }
- // send an NTP request to the time server
- void networkSendNTPPacket() {
- IPAddress ntpIP;
- WiFi.hostByName(NTP_SERVER, ntpIP);
- // set all bytes in the buffer to 0
- memset(g_networkNTPPacketBuffer, 0, NTP_PACKET_SIZE);
- // Initialize values needed to form NTP request
- g_networkNTPPacketBuffer[0] = 0b11100011; // LI, Version, Mode
- g_networkNTPPacketBuffer[1] = 0; // Stratum, or type of clock
- g_networkNTPPacketBuffer[2] = 6; // Polling Interval
- g_networkNTPPacketBuffer[3] = 0xEC; // Peer Clock Precision
- // 8 bytes of zero for Root Delay & Root Dispersion
- g_networkNTPPacketBuffer[12] = 49;
- g_networkNTPPacketBuffer[13] = 0x4E;
- g_networkNTPPacketBuffer[14] = 49;
- g_networkNTPPacketBuffer[15] = 52;
- // all NTP fields have been given values, now
- // you can send a packet requesting a timestamp:
- g_networkUDP.beginPacket(ntpIP, 123); //NTP requests are to port 123
- g_networkUDP.write(g_networkNTPPacketBuffer, NTP_PACKET_SIZE);
- g_networkUDP.endPacket();
- }
- void beginNetworkClock() {
- beginNetworkUDP();
- }
- void networkSyncClock() {
- if (WL_CONNECTED == WiFi.status()) {
- uint32_t ms = millis();
- if (ms - g_networkClockSyncTS > (1000 * NTP_SYNC_FREQUENCY)) {
- g_networkClockSyncTS = ms;
- networkSendNTPPacket();
- }
- time_t t = networkReceiveNTPTime();
- if (0 != t)
- clockSet(t);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement