text: /**
    The MIT License (MIT)
    Copyright (c)  2016  Ryotaro Onuki
  
    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
  
  #include "ntp.h"
  
  #include <TimeLib.h>
  #include <WiFiUdp.h>
  #include "config.h"
  #include <Time.h>
  
  // NTP Servers:
  IPAddress timeServer(210, 173, 160, 57); // ntp.jst.mfeed.ad.jp
  
  WiFiUDP Udp;
  unsigned int localPort = 8888;  // local port to listen for UDP packets
  
  void ntp_begin() {
    println_dbg("Starting NTP UDP");
    Udp.begin(localPort);
    print_dbg("Local port: ");
    println_dbg(Udp.localPort());
    println_dbg("waiting for sync");
    setSyncProvider(getNtpTime);
  
    char s[20];
    const char* format = "%04d/%02d/%02d %02d:%02d:%02d";
  
    // JST
    time_t n = now();
    time_t t = localtime(n, 9);
    sprintf(s, format, year(t), month(t), day(t), hour(t), minute(t), second(t));
    print_dbg("JST : ");
    println_dbg(s);
  }
  
  time_t localtime(time_t t, int timeZone) {
    return t + timeZone * SECS_PER_HOUR;
  }
  
  /*-------- NTP code ----------*/
  
  const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
  byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets
  
  time_t getNtpTime() {
    while (Udp.parsePacket() > 0) ; // discard any previously received packets
    println_dbg("Transmit NTP Request");
    sendNTPpacket(timeServer);
    uint32_t beginWait = millis();
    while (millis() - beginWait < 1500) {
      int size = Udp.parsePacket();
      if (size >= NTP_PACKET_SIZE) {
        println_dbg("Receive NTP Response");
        Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
        unsigned long secsSince1900;
        // convert four bytes starting at location 40 to a long integer
        secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
        secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
        secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
        secsSince1900 |= (unsigned long)packetBuffer[43];
        return secsSince1900 - 2208988800UL;
      }
    }
    println_dbg("No NTP Response :-(");
    return 0; // return 0 if unable to get the time
  }
  
  // send an NTP request to the time server at the given address
  void sendNTPpacket(IPAddress &address)
  {
    // set all bytes in the buffer to 0
    memset(packetBuffer, 0, NTP_PACKET_SIZE);
    // Initialize values needed to form NTP request
    // (see URL above for details on the packets)
    packetBuffer[0] = 0b11100011;   // LI, Version, Mode
    packetBuffer[1] = 0;     // Stratum, or type of clock
    packetBuffer[2] = 6;     // Polling Interval
    packetBuffer[3] = 0xEC;  // Peer Clock Precision
    // 8 bytes of zero for Root Delay & Root Dispersion
    packetBuffer[12]  = 49;
    packetBuffer[13]  = 0x4E;
    packetBuffer[14]  = 49;
    packetBuffer[15]  = 52;
    // all NTP fields have been given values, now
    // you can send a packet requesting a timestamp:
    Udp.beginPacket(address, 123); //NTP requests are to port 123
    Udp.write(packetBuffer, NTP_PACKET_SIZE);
    Udp.endPacket();
  }
  
  