I would like to read time from Google and send data to my ThingSpeak channel all in one Lua program.
First program:
connout = nil
connout = net.createConnection(net.TCP, 0)
connout:on("receive",
function(connout, payloadout)
if (string.find(payloadout, "Status: 200 OK") ~= nil) then
end
end)
connout:on("connection",
function(connout, payloadout)
connout:send("GET /update?api_key="..CHANNEL_API_KEY.."&field1="
.. humi .. " HTTP/1.1\r\n" .. "Host: api.thingspeak.com\r\n"
.. "Connection: close\r\n" .. "Accept: */*\r\n"
.. "User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n"
.. "\r\n")
end)
connout:on("disconnection",
function(connout, payloadout)
connout:close();
collectgarbage();
end)
connout:connect(80,'api.thingspeak.com')
gpio.write(pinled,gpio.LOW)
end)
Second program:
conn=net.createConnection(net.TCP, 0)
conn:on("connection",function(conn, payloadout)
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)
tmp = string.find(payload,"Date: ")
print(tmp)
conn:close()
end)
t = tmr.now()
conn:connect(80,'google.com')
The programs work fine alone, but I want them both in one Lua file. Should I create two TCP connections? Or arrange them in some other way?
Whether you want to split this into two files or keep all in one is up to you. Assuming you keep them separate a sensible startup sequence in
init.lua
might look like this. It sets up atmr.alarm
that "loops" in 1s intervals until WiFi is ready.What I would strongly suggest though is that you use the dedicated HTTP module for HTTP operations. Here's an example of how to talk to thingspeak.com
Note that it does so over HTTPS rather than HTTP.