Post your best Lua script examples here

User avatar
By maverick
#52018 Hello i have been playing around with a file i fond on the web to control 2 relays from a webpage is there a way i can program the button to say stay high for a set amount of time like 15 secs or then turn off? or a push to make button that will only stay live for the amont of time it is pushed for any help with this would be grate

here is te code i have been playing about with

Code: Select allwifi.setmode(wifi.STATION)
wifi.sta.config("__________","__________")
print(wifi.sta.getip())
led1 = 1
led2 = 2
gpio.mode(led1, gpio.OUTPUT)
gpio.mode(led2, gpio.OUTPUT)
srv=net.createServer(net.TCP)
srv:listen(90,function(conn)
    conn:on("receive", function(client,request)
        local buf = "";
        local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
        if(method == nil)then
            _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
        end
        local _GET = {}
        if (vars ~= nil)then
            for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
                _GET[k] = v
            end
        end
        buf = buf.."<h1>Frontline Security</h1>";
        buf = buf.."<p>Open <a href=\"?pin=ON1\"><button>ON</button></a>&nbsp;<a href=\"?pin=OFF1\"><button>OFF</button></a></p>";
        buf = buf.."<p>Close <a href=\"?pin=ON2\"><button>ON</button></a>&nbsp;<a href=\"?pin=OFF2\"><button>OFF</button></a></p>";
       
        local _on,_off = "",""
        if(_GET.pin == "ON1")then
              gpio.write(led1, gpio.LOW);
        elseif(_GET.pin == "OFF1")then
              gpio.write(led1, gpio.HIGH);
        elseif(_GET.pin == "ON2")then
              gpio.write(led2, gpio.LOW);
        elseif(_GET.pin == "OFF2")then
              gpio.write(led2, gpio.HIGH);
        end
        client:send(buf);
        client:close();
        collectgarbage();
    end)
        end)
User avatar
By jankop
#52040
Code: Select all-- server port is set to 80 !!!
-- set youř router parameters
--*********************************************************

DEBUGPRINT=true -- true = with debugg prints; false = without debugg prints
_, BoRe= node.bootreason()
wifi.setmode(wifi.STATION)
--wifi.sta.config("yourSSID","yourPASSWORD")
wifi.sta.connect()
rel1gpio=2  --GPIO4 for relay
rel2gpio=1  --GPIO5 for relay
rel1stat=0
rel2stat=0
timeON=15
on='<span style="color: red;">ON '..timeON..' s</span>'
off='<span style="color: blue;">OFF</span>'
rel1info = off
rel2info = off
timeON=15

gpio.mode(rel1gpio, gpio.OUTPUT)
gpio.mode(rel2gpio, gpio.OUTPUT)
gpio.write(rel1gpio,rel1stat)
gpio.write(rel2gpio,rel2stat)

function debugprint(...)
   if DEBUGPRINT then
      print(...)
   end
end

local function cgidecode(str)
  return (str:gsub('+', ' '):gsub("%%(%x%x)", function(xx) return string.char(tonumber(xx, 16)) end))
end

function parsecgi(str, keys, ignore_invalid)
  local keyfound = {}
  for pair in str:gmatch"[^&]+" do
    local key, val = pair:match"([^=]*)=(.*)"
    if not key then debugprint("1.IQS") end
    local default = keys[key]
    if default == nil then
      if not ignore_invalid then debugprint("2.IQS") end
    else
      if type(default) == "table" then default[#default+1] = cgidecode(val)
      elseif keyfound[key] then debugprint("3.IQS")
      else
        keyfound[key] = true
        keys[key] = cgidecode(val)
      end
    end
  end
  return keys
end

function SendData(client)
gpio.write(rel1gpio,rel1stat)
gpio.write(rel2gpio,rel2stat)
buff2='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">'..
'<html><head>'..
'<meta http-equiv="refresh" content="'..timeON..'">'..
'<meta content="text/html; charset=utf-8">'..
'<title>KEVA</title></head>'..
'<body style="color: brown;background:#ffe4c4">'..
'<h1>JankoP - Factory</h1><br>'..
'<form action="/" method="post">'..
'<h2>Relay 1 - '..rel1info..'<br><input type="submit" name="R1ON" value="ON">'..
'<input type="submit" name="R1OFF" value="OFF"><br><br>'..
'Relay 2 - '..rel2info..'<br><input type="submit" name="R2ON" value="ON">'..
'<input type="submit" name="R2OFF" value="OFF"><br><br>'..
'<input type="submit" name="REFRESH" value="REFRESH"><br></h2><br>'..
'Reset ID : '..BoRe..'<br>Heap : '..node.heap()..'</form></body></html>'
lenght= #buff2
buff1 = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n'..
'Content-Length: '.. lenght ..'\r\n'..
'Cache-Control: no-cache\r\n'..
'Pragma: no-cache\r\n'..
'Connection: keep-alive\r\n\r\n'..buff2
buff2=nil
collectgarbage()
client:send(buff1)
end

function Send404(client)
debugprint("Serve as 404",client:getpeer())
buff2='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">'..
'<html><head>'..
'<meta content="text/html; charset=utf-8">'..
'<title>404</title></head>'..
'<body >'..
'<h1>404 - Page not found</h1><br>'..
'</body></html>'
lenght= #buff2
buff1 = 'HTTP/1.1 404 NO\r\n'..
'Content-Type: text/html\r\n'..
'Content-Length: '.. lenght ..'\r\n'..
'Cache-Control: no-cache\r\n'..
'Pragma: no-cache\r\n'..
'Connection: keep-alive\r\n\r\n'..buff2
buff2=nil
collectgarbage()
client:send(buff1)
end

debugprint ("Reset ID :",BoRe)


srv=net.createServer(net.TCP,60) srv:listen(80,function(conn)
conn:on("receive",function(client,payload)
debugprint(payload)
if string.find(payload,"POST / HTTP/1.1\r\n.+\r\n\r\n")~=nil
   then
      _,stend=string.find(payload,"POST / HTTP/1.1\r\n.+\r\n\r\n")
      postda=string.sub(payload,stend+1)
      cgivals = parsecgi(postda, {count = 5, start = 1, R1ON="", R2ON="", R1OFF="", R2OFF="", REFRESH=""})
      if cgivals.R1ON=="ON"
      then
      rel1stat=1
       rel1info=on
      tmr.stop(0)
      tmr.alarm(0,timeON*1000, tmr.ALARM_SINGLE, function() rel1stat=0 rel1info=off gpio.write(rel1gpio,rel1stat)end)
      end
      if cgivals.R1OFF=="OFF"
      then
      rel1stat=0
       rel1info=off
      end
      if cgivals.R2ON=="ON"
      then
      rel2stat=1
      rel2info=on
      tmr.stop(1)
      tmr.alarm(1,timeON*1000, tmr.ALARM_SINGLE, function() rel2stat=0 rel2info=off gpio.write(rel2gpio,rel2stat)end)
      end
      if cgivals.R2OFF=="OFF"
      then
      rel2stat=0
       rel2info=off
      end
      debugprint("Serve as POST",client:getpeer())
      SendData(client)
   else
      if string.find(payload,"GET / HTTP/1.1\r\n.+\r\n\r\n")~=nil
      then
      debugprint("Serve as GET",client:getpeer())
      SendData(client)
      else
      Send404(client)
      end

   end
end)
end)
User avatar
By maverick
#52086 thanks for your quick reply

-- server port is set to 80 !!!


i use 90 as have my cctv on port 80 :)

but i get this error when trying to upload your code :(

Image

and when i try and load the webpage i get this error on the serial monitor

Code: Select allNodeMCU 0.9.6 build 20150704  powered by Lua 5.1.4
> PANIC: unprotected error in call to Lua API (init.lua:65: attempt to concatenate global 'BoRe' (a nil value))
PANIC: unprotected error in call to Lua API (attempt to concatenate a nil value)
PANIC: unprotected error in call to Lua API (attempt to concatenate a nil value)
ü! m•�ÿ1ä)mô1ä)Í!Üÿè

NodeMCU 0.9.6 build 20150704  powered by Lua 5.1.4
User avatar
By jankop
#52096 You are using a very very old version of Lua.
Here's the modified program , which should work with your old Lua system .

Code: Select all-- load from ESPlorer as file - button UPLOAD
-- server port is set to 90 !!!
-- set your router parameters
--*********************************************************

DEBUGPRINT=true -- true = with debugg prints; false = without debugg prints
wifi.setmode(wifi.STATION)
--wifi.sta.config("yourSSID","yourPASSWORD")-- set your router parameters
wifi.sta.connect()
sport=90
tmr.alarm(0,1000,1,
function()
   staip,_,_=wifi.sta.getip()
   print("Wait for IP...")
   if staip~=nil
      then
      tmr.stop(0)
      print(staip, "server port :",sport )
   end
end)

rel1gpio=2  --GPIO4 for relay
rel2gpio=1  --GPIO5 for relay
rel1stat=0
rel2stat=0
timeON=15
on='<span style="color: red;">ON '..timeON..' s</span>'
off='<span style="color: blue;">OFF</span>'
rel1info = off
rel2info = off
timeON=15

gpio.mode(rel1gpio, gpio.OUTPUT)
gpio.mode(rel2gpio, gpio.OUTPUT)
gpio.write(rel1gpio,rel1stat)
gpio.write(rel2gpio,rel2stat)

function debugprint(...)
   if DEBUGPRINT then
      print(...)
   end
end



local function cgidecode(str)
  return (str:gsub('+', ' '):gsub("%%(%x%x)", function(xx) return string.char(tonumber(xx, 16)) end))
end

function parsecgi(str, keys, ignore_invalid)
  local keyfound = {}
  for pair in str:gmatch"[^&]+" do
    local key, val = pair:match"([^=]*)=(.*)"
    if not key then debugprint("1.IQS") end
    local default = keys[key]
    if default == nil then
      if not ignore_invalid then debugprint("2.IQS") end
    else
      if type(default) == "table" then default[#default+1] = cgidecode(val)
      elseif keyfound[key] then debugprint("3.IQS")
      else
        keyfound[key] = true
        keys[key] = cgidecode(val)
      end
    end
  end
  return keys
end

function SendData(client)
gpio.write(rel1gpio,rel1stat)
gpio.write(rel2gpio,rel2stat)
buff2='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">'..
'<html><head>'..
'<meta http-equiv="refresh" content="'..timeON..'">'..
'<meta content="text/html; charset=utf-8">'..
'<title>KEVA</title></head>'..
'<body style="color: brown;background:#ffe4c4">'..
'<h1>JankoP - Factory</h1><br>'..
'<form action="/" method="post">'..
'<h2>Relay 1 - '..rel1info..'<br><input type="submit" name="R1ON" value="ON">'..
'<input type="submit" name="R1OFF" value="OFF"><br><br>'..
'Relay 2 - '..rel2info..'<br><input type="submit" name="R2ON" value="ON">'..
'<input type="submit" name="R2OFF" value="OFF"><br><br>'..
'<input type="submit" name="REFRESH" value="REFRESH"><br></h2><br>'..
'<br>Heap : '..node.heap()..'</form></body></html>'
lenght= #buff2
buff1 = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n'..
'Content-Length: '.. lenght ..'\r\n'..
'Cache-Control: no-cache\r\n'..
'Pragma: no-cache\r\n'..
'Connection: keep-alive\r\n\r\n'..buff2
buff2=nil
collectgarbage()
client:send(buff1)
end

function Send404(client)
debugprint("Serve as 404")
buff2='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">'..
'<html><head>'..
'<meta content="text/html; charset=utf-8">'..
'<title>404</title></head>'..
'<body >'..
'<h1>404 - Page not found</h1><br>'..
'</body></html>'
lenght= #buff2
buff1 = 'HTTP/1.1 404 NO\r\n'..
'Content-Type: text/html\r\n'..
'Content-Length: '.. lenght ..'\r\n'..
'Cache-Control: no-cache\r\n'..
'Pragma: no-cache\r\n'..
'Connection: keep-alive\r\n\r\n'..buff2
buff2=nil
collectgarbage()
client:send(buff1)
end

srv=net.createServer(net.TCP,60) srv:listen(90,function(conn)
conn:on("receive",function(client,payload)
debugprint(payload)
if string.find(payload,"POST / HTTP/1.1\r\n.+\r\n\r\n")~=nil
   then
      _,stend=string.find(payload,"POST / HTTP/1.1\r\n.+\r\n\r\n")
      postda=string.sub(payload,stend+1)
      cgivals = parsecgi(postda, {count = 5, start = 1, R1ON="", R2ON="", R1OFF="", R2OFF="", REFRESH=""})
      if cgivals.R1ON=="ON"
      then
      rel1stat=1
       rel1info=on
      tmr.stop(0)
      tmr.alarm(0,timeON*1000, tmr.ALARM_SINGLE, function() rel1stat=0 rel1info=off gpio.write(rel1gpio,rel1stat)end)
      end
      if cgivals.R1OFF=="OFF"
      then
      rel1stat=0
       rel1info=off
      end
      if cgivals.R2ON=="ON"
      then
      rel2stat=1
      rel2info=on
      tmr.stop(1)
      tmr.alarm(1,timeON*1000, tmr.ALARM_SINGLE, function() rel2stat=0 rel2info=off gpio.write(rel2gpio,rel2stat)end)
      end
      if cgivals.R2OFF=="OFF"
      then
      rel2stat=0
       rel2info=off
      end
      debugprint("Serve as POST")
      SendData(client)
   else
      if string.find(payload,"GET / HTTP/1.1\r\n.+\r\n\r\n")~=nil
      then
      debugprint("Serve as GET")
      SendData(client)
      else
      Send404(client)
      end

   end
end)
end)