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

User avatar
By darethehair
#57093 Time for a software question from me instead of a hardware one...

I have my NodeMCU connected to some enviro sensors, and my LUA code contains a simple webserver (gleaned from many examples out there on how to do it). Works great -- when I query the webserver from another PC, my sensor readings are returned.

However, I *also* would like to periodically send/upload my data to another site (i.e. Weather Underground). I see examples on how to do that as well -- but can I do *both* of these functions at the same time? Won't the webserver code just 'sit and wait' and exclude all other activity that I might want to do with some other (timer?) function like uploading to Wunderground?
User avatar
By marcelstoer
#57107
darethehair wrote:can I do *both* of these functions at the same time?


Definitely. The server does something like this:

Code: Select allsrv = net.createServer(net.TCP)
srv:listen(80, function(conn)
  conn:on("receive", function(sck, req)
    local response = {}
    -- sending response back
  end)
end)


Before or after that code you can configure your timer:

Code: Select allmytimer = tmr.create()
mytimer:register(60000, tmr.ALARM_AUTO, function ()
  http.post('http://httpbin.org/post',
    'Content-Type: application/json\r\n',
    '{"sensor":"value"}',
    function(code, data)
      if (code < 0) then
        print("HTTP request failed")
      else
        print(code, data)
      end
    end)
end)
mytimer:start()
User avatar
By darethehair
#57143 Thanks marcelstoer!

So instead of using 'createConnection' to send data, this is an alternate method using 'http.post'? And since it is in an 'alarm' interrupt, it has the ability to fire independently from the 'createServer' code?
User avatar
By marcelstoer
#57144
darethehair wrote:So instead of using 'createConnection' to send data, this is an alternate method using 'http.post'?


The implementation of the timer callback can really be anything. Me using HTTP to POST something (you need the NodeMCU HTTP module for that) is really just an example. You can also use the low-level functions of the net module to establish a socket connection.

darethehair wrote:And since it is in an 'alarm' interrupt, it has the ability to fire independently from the 'createServer' code?


The two don't have anything to do with each other, yes. Unless you would try to create another server instance in the callback but that's not a realistic use case anyway.