Advertisement
ZNZNCOOP

ntp

Feb 22nd, 2016
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.74 KB | None | 0 0
  1. return({
  2.     hour=0,
  3.     minute=0,
  4.     second=0,
  5.     lastsync=0,
  6.     ustamp=0,
  7.     tz=1,
  8.     udptimer=2,
  9.     udptimeout=1000,
  10.     ntpserver="194.109.22.18",
  11.     sk=nil,
  12.     sync=function(self,callback)
  13.         local request=string.char( 227, 0, 6, 236, 0,0,0,0,0,0,0,0, 49, 78, 49, 52,
  14.         0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
  15.         )
  16.         self.sk=net.createConnection(net.UDP, 0)
  17.         self.sk:on("receive",function(sck,payload)
  18.             sck:close()
  19.             self.lastsync=self:calc_stamp(payload:sub(41,44))
  20.             self:set_time()
  21.             if callback and type(callback) == "function" then
  22.                 callback(self)
  23.             end
  24.             collectgarbage() collectgarbage()
  25.         end)
  26.         self.sk:connect(123,self.ntpserver)
  27.         tmr.alarm(self.udptimer,self.udptimeout,0,function() self.sk:close() end)
  28.         self.sk:send(request)
  29.     end,
  30.     calc_stamp=function(self,bytes)
  31.         local highw,loww,ntpstamp
  32.         highw = bytes:byte(1) * 256 + bytes:byte(2)
  33.         loww = bytes:byte(3) * 256 + bytes:byte(4)
  34.         ntpstamp=( highw * 65536 + loww ) + ( self.tz * 3600)   -- NTP-stamp, seconds since 1.1.1900
  35.         self.ustamp=ntpstamp - 1104494400 - 1104494400      -- UNIX-timestamp, seconds since 1.1.1970
  36.         return(self.ustamp)
  37.     end,
  38.     set_time=function(self)
  39.         self.hour = self.ustamp % 86400 / 3600
  40.         self.minute = self.ustamp % 3600 / 60
  41.         self.second = self.ustamp % 60
  42.     end,
  43.     show_time=function(self)
  44.         return(string.format("%02u:%02u:%02u",self.hour,self.minute,self.second))
  45.     end,
  46.     run=function(self,t,uinterval,sinterval,server)
  47.         if server then self.ntpserver = server end
  48.         self.lastsync = sinterval * 2 * -1  -- force sync on first run
  49.         tmr.alarm(t,uinterval * 1000,1,function()
  50.             self.ustamp = self.ustamp + uinterval
  51.             self:set_time()
  52.             if self.lastsync + sinterval < self.ustamp then
  53.                 self:sync()
  54.             end
  55.         end)
  56.     end
  57. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement