ESP8266 multiple pages access using net.createConnection(net.TCP, 0)

492 views Asked by At

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?

1

There are 1 answers

0
Marcel Stör On

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 a tmr.alarm that "loops" in 1s intervals until WiFi is ready.

--init.lua
function startup()
    dofile("humi.lua")
    dofile("time.lua")
end

print("set up wifi mode")
wifi.setmode(wifi.STATION)
wifi.sta.config(SSID,PASSWORD)
wifi.sta.connect()
tmr.alarm(1, 1000, 1, function() 
    if wifi.sta.getip() == nil then 
        print("IP unavaiable, Waiting...") 
    else 
        tmr.stop(1)
        print("Config done, IP is "..wifi.sta.getip())
        print("You have 5 seconds to abort Startup")
        print("Waiting...")
        tmr.alarm(0, 5000, 0, startup)
    end 
 end)

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

http.get("https://api.thingspeak.com/update?api_key=" .. CHANNEL_API_KEY .. "&field1=" .. humi, nil, function(code, data)
  if (code < 0) then
    print("HTTP request failed")
  else
    print(code, data)
  end
end)

Note that it does so over HTTPS rather than HTTP.