I am trying to implement a script with a server socket that will also periodically poll for data from several sensors (i.e on 59th second of every minute). I do not want to serialize the data to disk but rather keep it in a table which the socket will respond with when polled. Here's some sketch the code to illustrate what I am trying to do (I've not included the client code that accesses this server, but that part is OK)
#!/usr/bin/env lua
local socket = require("socket")
local server = assert(socket.bind("*", 0))
local ip, port = server:getsockname()
local data = {}
local count = 1
local function pollSensors()
-- I do the sensor polling here and add to table e.g os.time()
table.insert(data, os.time() .."\t" .. tostring(count))
count = count + 1
end
while true do
local client = server:accept()
client:settimeout(2)
local line, err = client:receive()
-- I do process the received line to determine the response
-- for illustration I'll just send the number of items in the table
if not err then client:send("Records: " ..table.getn(data) .. "\n") end
client:close()
if os.time().sec == 59 then
pollSensors()
end
end
I am concerned that the server may on occasion(s) block and therefore I'll miss the 59th second.
Is this a good way to implement this or is there a (simpler) better way to do this (say using coroutines)? If coroutines would be better, how do I implement them for my scenario?