time_sntp.cpp 6.6 KB

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