As the title says... Chat on...

User avatar
By tma
#46593 Greetings,

I would like to sync to NTP time during startup. I have tried placing an sntp.sync() line at the end of my init.lua file after the TCP WiFi connect but it seems to be ignored, or at least it does not work. Yet it does work OK if I manually enter it after the NodeMCU signon statement.

Is there an alternate way to autorun a script after sign-on?

Has anyone here successfully implemented sntp.sync() within the init.lua file?

Thanks in advance for any help!

tma
User avatar
By dnc40085
#46656 I am assuming that the execution of sntp.sync() in init.lua fails because there is not yet a connection to the internet.

One potential solution is to use the STA_GOT_IP event in the WiFi event monitor to register a callback that will execute when the ESP gets an IP address from the AP.
Code: Select allwifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function() print("YOUR_CODE_HERE") end)
User avatar
By tma
#46808 Greetings,

Thank you for your interest!

I gave "wifi.eventmon.reg(wifi.eventmon.STA_GOT_IP, function() dofile("ntpSync.lua") end)" a try but the init script seem to stop when it hit that statement. I wonder if the event detection doesn't work because it is running in server mode??? I had tried a while loop using wifi.sta.getip() to wait for the ip assignment but I couldn't get it to work either. It makes good logic sense to wait for the IP assignment using a callback.

A factor that added confusion is that even with a long delay after connection is confirmed I still need to send sntp.sync('129.6.15.28') twice to get NTP sync. Since connection to my LAN is very quick the following pair of one shot timer statements at the end of the init file seem to provide a solution:

tmr.alarm(0,5000, tmr.ALARM_SINGLE, function() dofile("ntpSync.lua")end)
tmr.alarm(1,10000, tmr.ALARM_SINGLE, function() dofile("ntpSync.lua")end)

Thanks for your suggestion!

tma
User avatar
By marcelstoer
#46816
tma wrote:I had tried a while loop using wifi.sta.getip() to wait for the ip assignment but I couldn't get it to work either. It makes good logic sense to wait for the IP assignment using a callback.


A skeleton for that old timer-based approach is e.g. here: http://stackoverflow.com/a/36632400/131929