time_sntp.cpp 7.3 KB

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