luat_sntp_idf5.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include "luat_base.h"
  2. #include "luat_msgbus.h"
  3. #include "luat_wlan.h"
  4. #include "esp_attr.h"
  5. #include "esp_netif.h"
  6. #include "esp_event.h"
  7. #include "esp_system.h"
  8. #include "esp_wifi.h"
  9. #include "esp_wifi_types.h"
  10. #include "esp_smartconfig.h"
  11. #include "esp_mac.h"
  12. #include <time.h>
  13. #include <sys/time.h>
  14. #define LUAT_LOG_TAG "sntp"
  15. #include "luat_log.h"
  16. static uint8_t ntp_auto_sync_started = 0;
  17. static uint8_t ntp_first_ntp = 0;
  18. static int l_ntp_sync_cb(lua_State *L, void* ptr) {
  19. lua_getglobal(L, "sys_pub");
  20. if (!lua_isnil(L, -1)) {
  21. lua_pushstring(L, "NTP_UPDATE");
  22. lua_call(L, 1, 0);
  23. }
  24. return 0;
  25. }
  26. static void my_ntp_cb (struct timeval *tv) {
  27. if (ntp_first_ntp == 0) {
  28. ntp_first_ntp = 1;
  29. LLOGD("time sync done");
  30. }
  31. rtos_msg_t msg = {0};
  32. msg.handler = l_ntp_sync_cb;
  33. luat_msgbus_put(&msg, 0);
  34. }
  35. // 自动进行NTP同步
  36. #include "esp_sntp.h"
  37. void luat_ntp_autosync(void) {
  38. if (ntp_auto_sync_started != 0) {
  39. return;
  40. }
  41. ntp_auto_sync_started = 1;
  42. sntp_setoperatingmode(SNTP_OPMODE_POLL);
  43. sntp_setservername(0, "ntp.aliyun.com");
  44. sntp_setservername(1, "pool.ntp.org");
  45. #ifdef CONFIG_SNTP_TIME_SYNC_METHOD_SMOOTH
  46. sntp_set_sync_mode(SNTP_SYNC_MODE_SMOOTH);
  47. #endif
  48. sntp_set_sync_interval(900*1000); // every 60s
  49. sntp_set_time_sync_notification_cb(my_ntp_cb);
  50. sntp_init();
  51. }