time_sntp.cpp 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. #include "time_sntp.h"
  2. #include <string>
  3. #include <time.h>
  4. #include <sys/time.h>
  5. #include "freertos/FreeRTOS.h"
  6. #include "freertos/task.h"
  7. #include "freertos/event_groups.h"
  8. #include "esp_system.h"
  9. #include "esp_event.h"
  10. #include "esp_log.h"
  11. #include "esp_attr.h"
  12. #include "esp_sleep.h"
  13. #include "esp_sntp.h"
  14. #include "../../include/defines.h"
  15. #include "ClassLogFile.h"
  16. #include "configFile.h"
  17. #include "Helper.h"
  18. static const char *TAG = "SNTP";
  19. static std::string timeZone = "";
  20. static std::string timeServer = "undefined";
  21. static bool useNtp = true;
  22. std::string getNtpStatusText(sntp_sync_status_t status);
  23. static void setTimeZone(std::string _tzstring);
  24. static std::string getServerName(void);
  25. std::string ConvertTimeToString(time_t _time, const char * frm)
  26. {
  27. struct tm timeinfo;
  28. char strftime_buf[64];
  29. localtime_r(&_time, &timeinfo);
  30. strftime(strftime_buf, sizeof(strftime_buf), frm, &timeinfo);
  31. std::string result(strftime_buf);
  32. return result;
  33. }
  34. std::string getCurrentTimeString(const char * frm)
  35. {
  36. time_t now;
  37. struct tm timeinfo;
  38. time(&now);
  39. char strftime_buf[64];
  40. localtime_r(&now, &timeinfo);
  41. strftime(strftime_buf, sizeof(strftime_buf), frm, &timeinfo);
  42. std::string result(strftime_buf);
  43. return result;
  44. }
  45. void time_sync_notification_cb(struct timeval *tv)
  46. {
  47. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Time is now successfully synced with NTP Server " +
  48. getServerName() + ": " + getCurrentTimeString("%Y-%m-%d %H:%M:%S"));
  49. }
  50. void setTimeZone(std::string _tzstring)
  51. {
  52. setenv("TZ", _tzstring.c_str(), 1);
  53. tzset();
  54. _tzstring = "Time zone set to " + _tzstring;
  55. LogFile.WriteToFile(ESP_LOG_INFO, TAG, _tzstring);
  56. }
  57. std::string getNtpStatusText(sntp_sync_status_t status) {
  58. if (status == SNTP_SYNC_STATUS_COMPLETED) {
  59. return "Synchronized";
  60. }
  61. else if (status == SNTP_SYNC_STATUS_IN_PROGRESS) {
  62. return "In Progress";
  63. }
  64. else { // SNTP_SYNC_STATUS_RESET
  65. return "Reset";
  66. }
  67. }
  68. bool getTimeIsSet(void) {
  69. time_t now;
  70. struct tm timeinfo;
  71. time(&now);
  72. localtime_r(&now, &timeinfo);
  73. // Is time set? If not, tm_year will be (1970 - 1900).
  74. if ((timeinfo.tm_year < (2022 - 1900))) {
  75. return false;
  76. }
  77. else {
  78. return true;
  79. }
  80. }
  81. /*void restartNtpClient(void) {
  82. // sntp_restart();
  83. // obtain_time();
  84. }*/
  85. bool getUseNtp(void) {
  86. return useNtp;
  87. }
  88. std::string getServerName(void) {
  89. char buf[100];
  90. if (sntp_getservername(0)){
  91. snprintf(buf, sizeof(buf), "%s", sntp_getservername(0));
  92. return std::string(buf);
  93. }
  94. else { // we have either IPv4 or IPv6 address
  95. ip_addr_t const *ip = sntp_getserver(0);
  96. if (ipaddr_ntoa_r(ip, buf, sizeof(buf)) != NULL) {
  97. return std::string(buf);
  98. }
  99. }
  100. return "";
  101. }
  102. /**
  103. * Load the TimeZone and TimeServer from the config file and initialize the NTP client
  104. */
  105. bool setupTime() {
  106. time_t now;
  107. struct tm timeinfo;
  108. char strftime_buf[64];
  109. ConfigFile configFile = ConfigFile(CONFIG_FILE);
  110. if (!configFile.ConfigFileExists()){
  111. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "No ConfigFile defined - exit setupTime() ");
  112. return false;
  113. }
  114. std::vector<std::string> splitted;
  115. std::string line = "";
  116. bool disabledLine = false;
  117. bool eof = false;
  118. /* Load config from config file */
  119. while ((!configFile.GetNextParagraph(line, disabledLine, eof) ||
  120. (line.compare("[System]") != 0)) && !eof) {}
  121. if (eof) {
  122. return false;
  123. }
  124. if (disabledLine) {
  125. return false;
  126. }
  127. while (configFile.getNextLine(&line, disabledLine, eof) &&
  128. !configFile.isNewParagraph(line)) {
  129. splitted = ZerlegeZeile(line);
  130. if (toUpper(splitted[0]) == "TIMEZONE") {
  131. timeZone = splitted[1];
  132. }
  133. if (toUpper(splitted[0]) == "TIMESERVER") {
  134. if (splitted.size() <= 1) { // Key has no value => we use this to show it as disabled
  135. timeServer = "";
  136. }
  137. else {
  138. timeServer = splitted[1];
  139. }
  140. }
  141. }
  142. /* Setup NTP Server and Timezone */
  143. if (timeServer == "undefined") {
  144. timeServer = "pool.ntp.org";
  145. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "TimeServer not defined, using default: " + timeServer);
  146. }
  147. else if (timeServer == "") {
  148. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "TimeServer config empty, disabling NTP");
  149. useNtp = false;
  150. }
  151. else {
  152. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "TimeServer: " + timeServer);
  153. }
  154. if (timeZone == "") {
  155. timeZone = "CET-1CEST,M3.5.0,M10.5.0/3";
  156. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "TimeZone not set, using default: " + timeZone);
  157. }
  158. if (useNtp) {
  159. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Configuring NTP Client...");
  160. sntp_setoperatingmode(SNTP_OPMODE_POLL);
  161. sntp_setservername(0, timeServer.c_str());
  162. sntp_init();
  163. sntp_set_time_sync_notification_cb(time_sync_notification_cb);
  164. setTimeZone(timeZone);
  165. }
  166. /* The RTC keeps the time after a restart (Except on Power On or Pin Reset)
  167. * There should only be a minor correction through NTP */
  168. // Get current time from RTC
  169. time(&now);
  170. localtime_r(&now, &timeinfo);
  171. strftime(strftime_buf, sizeof(strftime_buf), "%Y-%m-%d %H:%M:%S", &timeinfo);
  172. if (getTimeIsSet()) {
  173. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Time is already set: " + std::string(strftime_buf));
  174. }
  175. else {
  176. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "The local time is unknown, starting with " + std::string(strftime_buf));
  177. if (useNtp) {
  178. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Once the NTP server provides a time, we will switch to that one");
  179. }
  180. }
  181. return true;
  182. }