Post your best Lua script examples here

User avatar
By The_Praiodanish
#8692 Hi,

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:
Code: Select all-- 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
Code: Select allLastValue = 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)
Code: Select allGetDataFromThingspeak('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!
User avatar
By freedom2000
#16981 Hi,

I do have the same problem but ven you scripot doesn't work for me ...

Here is the full script to copy into init.lua

Code: Select allwifi.setmode(wifi.STATION)
wifi.sta.autoconnect(1)
function DoIt()
conn = nil
conn = net.createConnection(net.TCP, 0)
conn:on("receive", function(conn, payload)success = true print("receive"..payload) end) --send and deep sleep
conn:on("connection",
   function(conn, payload)
      print("Connected TS")
      conn:send('GET /channels/37123/fields/1/last?key=MyAPIKEY'..'HTTP/1.1\r\n\
      Host: api.thingspeak.com\r\nAccept: */*\r\nUser-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n\r\n')
   end)
conn:on("disconnection", function(conn, payload) print('Disconnected') end)
conn:connect(80,'184.106.153.149')
end
-- every 5 second, check thingspeak
tmr.alarm(0, 5000, 1, function() DoIt() end)


Something should be wrong with the GET command, because I always get an "-1" answer...
If i directly use my browser, then the answer is correct and the last field1 value is returned...

Any help please
JP
User avatar
By freedom2000
#17016 Ok I found the bug... bad syntax into the GET line

conn:send("GET /channels/28607/fields/2/last?key=MyAPIKEY HTTP/1.1\r\n")
conn:send('Host: api.thingspeak.com\r\nAccept: */*\r\nUser-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n\r\n')

JP