I want to read the turns of my gas gauge to accumulate how much gas I've used.
At every startup the ESP8266 board should fetch the last entry from the thingspeak database. I've done this like that:
-- Config:
srvip = "192.168.1.3"
srvport = 3000
channel = 1
field_kWh = 1
field_W = 2
-- END Config
function split(str, delim)
local result,pat,lastPos = {},"(.-)" .. delim .. "()",1
for part, pos in string.gfind(str, pat) do
table.insert(result, part); lastPos = pos
end
table.insert(result, string.sub(str, lastPos))
return result
end
-- GET DATA FROM THINGSPEAK
function split(str, delim)
local result,pat,lastPos = {},"(.-)" .. delim .. "()",1
for part, pos in string.gfind(str, pat) do
table.insert(result, part); lastPos = pos
end
table.insert(result, string.sub(str, lastPos))
return result
end
function GetDataFromThingspeak(_server, _port, _channel, _field)
--print("Querying data from thingspeak")
conn=net.createConnection(net.TCP, 0)
conn:on("receive", function(conn, payload)
tmr.wdclr()
--print(payload)
tmr.wdclr()
conn:close()
splittable = split(payload, "\r\n")
ThingspeakReply = splittable[15]
print("Query ".._server..":".._port.." channel".._channel.." field".._field.." REPLY: "..ThingspeakReply.."\n")
if ThingspeakReply == "\"-1\"" then ThingspeakReply = "0.000" print("!! REPLY REPLACED WITH 0.000 !!\n") end
end)
conn:connect(_port,_server)
conn:send("GET http://"..srvip.."/channels/".._channel.."/fields/".._field.."/last HTTP/1.1\r\n")
conn:send("Host: api.thingspeak.com\r\n")
conn:send("Accept: */*\r\n")
conn:send("User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n")
conn:send("\r\n")
conn:on("disconnection", function(conn)
--print("Got disconnection...")
conn=nil
end)
end
-- END GET DATA FROM THINGSPEAK
function Ausgabe()
if ThingspeakReply == nil then
GetDataFromThingspeak(srvip, srvport, channel, field_kWh)
else
print("Last entry in Thingspeak database: "..ThingspeakReply.."\n")
-- now a valid reply is available, do whatever you want with the read value
end
end
tmr.alarm(0,5000, 1, function() Ausgabe() end )
This works but there must be a better solution to the following problem: I'd like to have a function like
LastValue = ReadFromThingspeak(server, port, channel, field)But the reply which triggers conn:on("receive") is completely asynchronous from my request (it's roughly 100ms later), so how could I write a function which waits for a valid reply?
I tried (pseudocode)
GetDataFromThingspeak('192.168.1.3', 3000, 1, 'field1')
repeat
tmr.wdtclr()
tmr.delay(10000)
while ThingspeakReply == nil
But that freezes the ESP...
This might be trivial for you but it's the first time I struggle with lua
Thanks a lot in advance!