JustinCase2020

ESP8266 SNTP Quick & Dirty

Jul 3rd, 2021 (edited)
504
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.01 KB | None | 0 0
  1. #include "osapi.h"
  2. #include "user_interface.h"
  3.  
  4. #define INFO( format, ... ) os_printf( format, ## __VA_ARGS__ )
  5.  
  6. LOCAL os_timer_t ntp_timer;
  7.  
  8. LOCAL char hostname[16] = "xxx-01";
  9. LOCAL char ssid[32] = "The Promised LAN";
  10. LOCAL char password[64] = "xxx";
  11. LOCAL char bssid[6] = { 0x74, 0xD0, 0x2B, 0x67, 0x9E, 0x86 };
  12.  
  13. uint32 ICACHE_FLASH_ATTR user_rf_cal_sector_set(void)
  14. {
  15.     return 1019;
  16. }
  17.  
  18. void NTPTimer(void* arg)
  19. {
  20.     static uint8_t cnt = 50;
  21.  
  22.     uint32 current_stamp;
  23.     current_stamp = sntp_get_current_timestamp();
  24.     if (current_stamp == 0 && cnt > 0)
  25.     {
  26.         cnt--;
  27.         os_timer_arm(&ntp_timer, 100, 0);
  28.     }
  29.     else
  30.     {
  31.         INFO("Current timestamp (%d): %d - %s", cnt, current_stamp, sntp_get_real_time(current_stamp));
  32.     }
  33. }
  34.  
  35. void ICACHE_FLASH_ATTR mywifi_handle_events(System_Event_t *evt)
  36. {
  37.     switch (evt->event)
  38.     {
  39.         case EVENT_STAMODE_CONNECTED:
  40.         {
  41.             break;
  42.         }
  43.         case EVENT_STAMODE_DISCONNECTED:
  44.         {
  45.             break;
  46.         }
  47.         case EVENT_STAMODE_GOT_IP:
  48.         {
  49.             sntp_init();
  50.             os_timer_arm(&ntp_timer, 100, 0);
  51.         }
  52.     }
  53. }
  54.  
  55. void ICACHE_FLASH_ATTR user_init(void)
  56. {
  57.     gpio_init();
  58.  
  59.     uart_init(74880, 74880);
  60.  
  61.     struct station_config stConf;
  62.     stConf.bssid_set = 1;
  63.     os_memcpy(&stConf.bssid, bssid, 6);
  64.     os_memcpy(&stConf.ssid, ssid, 32);
  65.     os_memcpy(&stConf.password, password, 64);
  66.  
  67.     wifi_set_event_handler_cb(mywifi_handle_events);
  68.     wifi_set_opmode_current(STATION_MODE);
  69.     wifi_station_set_hostname(hostname);
  70.     wifi_station_set_config(&stConf);
  71.     wifi_set_sleep_type(NONE_SLEEP_T);
  72.  
  73.     os_timer_disarm(&ntp_timer);
  74.     os_timer_setfn(&ntp_timer, (os_timer_func_t *)NTPTimer, NULL);
  75.  
  76.     sntp_setservername(0, "0.ca.pool.ntp.org"); // set server 0 by domain name
  77.     sntp_setservername(1, "1.ca.pool.ntp.org"); // set server 1 by domain name
  78.     sntp_setservername(2, "2.ca.pool.ntp.org"); // set server 2 by domain name
  79. }
  80.  
Add Comment
Please, Sign In to add comment