experiments with Pylontech/GroWatt PV tech
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.5 KiB

  1. #ifndef ntp_time_h
  2. #define ntp_time_h
  3. #include <WiFiUdp.h>
  4. // NTP Servers:
  5. static const char ntpServerName[] = "0.uk.pool.ntp.org";
  6. const int timeZone = 0;
  7. unsigned int localPort = 8888; // local port to listen for UDP packets
  8. /*-------- NTP code ----------*/
  9. const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
  10. byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets
  11. WiFiUDP udpNtp;
  12. // send an NTP request to the time server at the given address
  13. void sendNTPpacket(IPAddress &address)
  14. {
  15. // set all bytes in the buffer to 0
  16. memset(packetBuffer, 0, NTP_PACKET_SIZE);
  17. // Initialize values needed to form NTP request
  18. // (see URL above for details on the packets)
  19. packetBuffer[0] = 0b11100011; // LI, Version, Mode
  20. packetBuffer[1] = 0; // Stratum, or type of clock
  21. packetBuffer[2] = 6; // Polling Interval
  22. packetBuffer[3] = 0xEC; // Peer Clock Precision
  23. // 8 bytes of zero for Root Delay & Root Dispersion
  24. packetBuffer[12] = 49;
  25. packetBuffer[13] = 0x4E;
  26. packetBuffer[14] = 49;
  27. packetBuffer[15] = 52;
  28. // all NTP fields have been given values, now
  29. // you can send a packet requesting a timestamp:
  30. udpNtp.beginPacket(address, 123); //NTP requests are to port 123
  31. udpNtp.write(packetBuffer, NTP_PACKET_SIZE);
  32. udpNtp.endPacket();
  33. }
  34. time_t getNtpTime()
  35. {
  36. if(WiFi.status() != WL_CONNECTED)
  37. {
  38. return 0;
  39. }
  40. static bool udpStarted = false;
  41. if(udpStarted == false)
  42. {
  43. udpStarted = true;
  44. udpNtp.begin(localPort);
  45. }
  46. IPAddress ntpServerIP; // NTP server's ip address
  47. while (udpNtp.parsePacket() > 0) ; // discard any previously received packets
  48. // get a random server from the pool
  49. WiFi.hostByName(ntpServerName, ntpServerIP);
  50. sendNTPpacket(ntpServerIP);
  51. delay(100);
  52. uint32_t beginWait = millis();
  53. while (millis() - beginWait < 1500) {
  54. int size = udpNtp.parsePacket();
  55. if (size >= NTP_PACKET_SIZE) {
  56. udpNtp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer
  57. unsigned long secsSince1900;
  58. // convert four bytes starting at location 40 to a long integer
  59. secsSince1900 = (unsigned long)packetBuffer[40] << 24;
  60. secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
  61. secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
  62. secsSince1900 |= (unsigned long)packetBuffer[43];
  63. return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
  64. }
  65. delay(10);
  66. }
  67. return 0; // return 0 if unable to get the time
  68. }
  69. #endif //ntp_time_h