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

User avatar
By Raptor
#10606 Hi, i am new to LUA and the esp8266, normally used to working with the arduino.

i have modified the code for the google time script to allow for GMT offset and i was getting ready to use this to do a tweet when the code is loaded.

where i am struggling is that it seems to be executing the google fetch code after the final print.

here is the output:
dofile("test2.lua")
test2.lua:37: attempt to concatenate global 'timestring' (a nil value)
> Date: 24 Feb 2015
Hour: 16
Mins: 06
Offset Time: 11:06

here is the code:
Code: Select all-- retrieve the current time from Google
-- tested on NodeMCU 0.9.5 build 20150108
do
local GMToffset=-5

conn=net.createConnection(net.TCP, 0)

conn:on("connection",function(conn, payload)
            conn:send("HEAD / HTTP/1.1\r\n"..
                      "Host: google.com\r\n"..
                      "Accept: */*\r\n"..
                      "User-Agent: Mozilla/4.0 (compatible; esp8266 Lua;)"..
                      "\r\n\r\n")
            end)
           
conn:on("receive", function(conn, payload,timestring)
 --   print('\nRetrieved in '..((tmr.now()-t)/1000)..' milliseconds.')
--    print('Google says it is '..string.sub(payload,string.find(payload,"Date: ")+6,string.find(payload,"Date: ")+35))
--Date: Tue, 24 Feb 2015 01:51:35 GMT -- print(payload) 
-- 123456789

datestring=string.sub(payload,string.find(payload,"Date: ")+11,string.find(payload,"Date: ")+21)
print("Date: "..datestring)
hourstring=string.sub(payload,string.find(payload,"Date: ")+23,string.find(payload,"Date: ")+24)   
print("Hour: "..hourstring)
minutestring=string.sub(payload,string.find(payload,"Date: ")+26,string.find(payload,"Date: ")+27)   
print("Mins: "..minutestring)
timestring=hourstring+GMToffset..":"..minutestring
print("Offset Time: "..timestring)
conn:close()
return timestring
    end)
   
t = tmr.now()
conn:connect(80,'google.com')
tmr.delay(1,1000)
print("Time local: "..timestring)   


end


could someone guide me where i am going wrong with the variables and the execution order?

thanks Raptor
User avatar
By draco
#10661 tmr.delay() only takes one argument, which is the amount of time to delay, in microseconds. so you are delaying one millionth of a second after doing your request before trying to read the result. See https://github.com/nodemcu/nodemcu-firm ... n#tmrdelay for reference.

Network things can take a variable amount of time to complete, so simply delaying a short time and hoping it's done isn't a very safe strategy. You could check to see if it's empty still, then wait some more if necessary, maybe.