-->
Page 1 of 3

NTP-client, time-sync

PostPosted: Fri Dec 19, 2014 1:15 pm
by ThomasW
Hi,
Attached ntp.lua(.txt) can be used to get the current time from a NTP-Server or to keep a table-structure (hour,minute and second) constantly sync'ed (using a timer-function)

To run the 'realtime-daemon ;)':
Code: Select allTIME=loadfile("ntp.lua")()
TIME:run(1,10,1800,"193.170.62.252")

will start a timer that:
- uses timer 1
- updates the internal 'clock' every 10 seconds
- and adjusts the clock every 30minutes (using an address from 3.at.pool.ntp.org)
(timeserver - ip can be omitted when 'ntpserver' inside the code is set)
Global TIME.hour TIME.minute and TIME.second will constantly be updated then..
Once started, you can save some memory be setting TIME.run=nil

For a one-time call use:
Code: Select allloadfile("ntp.lua")():sync(function(T) end)

The function passed to :sync() will be called with a table as argument (T.hour T.minute T.second) once the NTP-server answered

Important: the program currently needs an internal timer (configurable in the source) for 'guarding' the udp-call against memory leakage.
Maybe this can be changed by setting up a single 'connect' and 'receive-handler' on startup but i haven't tried yet ;)

To be honest, the 'full daemon' probably eats too much ram to be combined with 'real' work but perhaps you can tailor it to your needs...

Thomas

Re: NTP-client, time-sync

PostPosted: Sat Dec 20, 2014 6:22 am
by ThomasW
This is really annoying. Just discovered that the addition of the 'guard' - timerfunction works well in 'daemon'-mode but actually prevents a one-time - call from freeing it's memory :( :(

The problem is that an unanswered udp-query leaks memory permanently as no further event is fired. If the query is answered, I get 'received' and can close the connection and all is well but if not....

Working on a solution but somehow I am getting tired of fighting memory...

Thomas

Re: NTP-client, time-sync

PostPosted: Tue Dec 23, 2014 11:59 am
by hreintke
Thomas,
When you set TIME=nil after having it started with TIME:run the initiated timer is not stopped.
This leads to reboot esp8266 after a while, I presume when the garbage collect hits the TIME table.
I tried to find how to add a destructor to the ntp but (as far as I know now) that is not possible to a table in lua.
Only way I can think of now (but I am unexperienced in lua) is as separate call to be made by the "user" which stops the timer.
Or are there other/better solutions ?
Herman

Re: NTP-client, time-sync

PostPosted: Thu Jan 01, 2015 4:11 am
by pipi61
Hi!
self.sk:on("receive",function(sck,payload)
-- tmr.stop(self.udptimer)
sck:close() << in this line sk or sck close????
--------
Happy New Year
Puzsar