Browse Source

add: wlan启动时把ntp也启动起来,同步完成后马上通知,并设置为中国时区

Wendal Chen 3 years ago
parent
commit
221b29f74a

+ 62 - 0
luatos/components/luat/port/luat_sntp_idf5.c

@@ -0,0 +1,62 @@
+#include "luat_base.h"
+#include "luat_msgbus.h"
+#include "luat_wlan.h"
+
+
+#include "esp_attr.h"
+#include "esp_netif.h"
+#include "esp_event.h"
+#include "esp_system.h"
+#include "esp_wifi.h"
+#include "esp_wifi_types.h"
+#include "esp_smartconfig.h"
+#include "esp_mac.h"
+
+#include <time.h>
+#include <sys/time.h>
+
+#define LUAT_LOG_TAG "sntp"
+#include "luat_log.h"
+
+static uint8_t ntp_auto_sync_started = 0; 
+static uint8_t ntp_first_ntp = 0; 
+
+static int l_ntp_sync_cb(lua_State *L, void* ptr) {
+    lua_getglobal(L, "sys_pub");
+    if (!lua_isnil(L, -1)) {
+        lua_pushstring(L, "NTP_UPDATE");
+        lua_call(L, 1, 0);
+    }
+    return 0;
+}
+    
+static void my_ntp_cb (struct timeval *tv) {
+    if (ntp_first_ntp == 0) {
+        ntp_first_ntp = 1;
+        LLOGD("time sync done");
+    }
+
+    rtos_msg_t msg = {0};
+    msg.handler = l_ntp_sync_cb;
+    luat_msgbus_put(&msg, 0);
+}
+
+// 自动进行NTP同步
+#include "esp_sntp.h"
+void luat_ntp_autosync(void) {
+    if (ntp_auto_sync_started != 0) {
+        return;
+    }
+
+    ntp_auto_sync_started = 1;
+
+    sntp_setoperatingmode(SNTP_OPMODE_POLL);
+    sntp_setservername(0, "ntp.aliyun.com");
+    sntp_setservername(1, "pool.ntp.org");
+#ifdef CONFIG_SNTP_TIME_SYNC_METHOD_SMOOTH
+    sntp_set_sync_mode(SNTP_SYNC_MODE_SMOOTH);
+#endif
+    sntp_set_sync_interval(60*1000); // every 60s
+    sntp_set_time_sync_notification_cb(my_ntp_cb);
+    sntp_init();
+}

+ 5 - 0
luatos/components/luat/port/luat_wlan_idf5.c

@@ -195,6 +195,7 @@ static void sc_event_handler(void *arg, esp_event_base_t event_base,
     luat_msgbus_put(&msg, 0);
 }
 
+extern void luat_ntp_autosync(void);
 int luat_wlan_init(luat_wlan_config_t *conf) {
     if (wlan_inited != 0) {
         LLOGI("wlan is ready!!");
@@ -218,6 +219,10 @@ int luat_wlan_init(luat_wlan_config_t *conf) {
     ret = esp_wifi_start();
     LLOGD("esp_wifi_start ret %d", ret);
     wlan_inited = 1;
+
+    // 自动开启ntp
+    luat_ntp_autosync();
+
     return 0;
 }
 

+ 6 - 0
luatos/main/idf5_main.c

@@ -11,6 +11,8 @@
 #include "freertos/FreeRTOS.h"
 #include "freertos/timers.h"
 
+#include <time.h>
+#include <sys/time.h>
 
 #ifdef LUAT_USE_LVGL
 #include "lvgl.h"
@@ -38,6 +40,10 @@ void app_main(void){
         nvs_flash_erase();
         r = nvs_flash_init();
     }
+
+    setenv("TZ", "CST-8", 1);
+    tzset();
+
     luat_heap_init();
     esp_event_loop_create_default();
 #ifdef LUAT_USE_LVGL