I'm a newbie to LUA and ESP8266. I've written below code to create a socket, read the date & time from a server, convert format and store in a global variable dateRcv. The code ran ok to get date and time. However, it can never return from the function gettime() that created the socket. If I add timer loop after gettime() is called, the program seemed to have crashed and exit.
Can someone helped me and pointed me to the right direction? Many thanks!
portno = 13
tcpserverip = "ptbtime2.ptb.de" -- "ptbtime1.ptb.de"
SSID = "TEST"
pwd = "1234abcd"
dateRcv = ""
starttime = tmr.time()
wifi.setmode(wifi.STATION)
wifi.sta.config(SSID,pwd)
wifi.sta.connect()
repeat
tmr.alarm(0, 1000, 0, function() end)
print("Get IP address status: ", wifi.sta.status())
until wifi.sta.status() >= 2
if wifi.sta.status() >=2 then
net.dns.setdnsserver("58.176.125.223",0)
print("DNS server: ", net.dns.getdnsserver(0))
end
function gettime(port, TSip)
local mt = {JAN=1,FEB=2,MAR=3,APR=4,MAY=5,JUN=6,JUL=7,AUG=8,SEP=9,OCT=10,NOV=11,DEC=12}
local time = ""
local gotdate = false
if (wifi.sta.getip() ~= nil) then
sk = net.createConnection(net.TCP, 0)
sk:on("receive", function(sk, payload)
print("Received data "..payload)
m = (mt[string.sub(payload, 4, 6)])
dateRcv = string.sub(payload, 10,11) .. "-"..m .."-".. string.sub(payload, 1, 2)
time = string.sub(payload, 13, 20)
print("Date, time: ", dateRcv, time, "\n")
gotdate = true
sk:close()
end)
sk:connect(portno, tcpserverip)
sk:on("connection",function(sk, payload)
sk:send(" ")
end)
sk:on("disconnection",function(sk)
sk=nil
print("Disconnecting...")
collectgarbage()
end )
else
print("Failed to connect. Stopped retry!")
end
return
end
--
gettime(portno, tcpserverip)
--[[ remove below comment block will allow function to exit but
dateRcv can't be retrived.
repeat
tmr.alarm(0, 1000, 0, function() end)
until dateRcv ~= ""
print("Date Received: ", dateRcv)
-]]
Output:
Get IP address status: 5
DNS server: 58.176.125.223
> Received data 29 OCT 2015 10:48:23 UTC
Date, time: 15-10-29 10:48:23
Disconnecting...