Mar 222015
 
Toggling LEDs

Here was a great start and given that I did not know Lua a lot (and I am sure I don’t still), it was a nice little challenge to expand the example to include all 6 LEDs.

Here the result:

 

myled={ 4, 3, 2, 1, 5, 0, 6, 7, 8 }
mystate={}

start_init = function()
local i
for i=1,6 do
 gpio.mode(myled[i], gpio.OUTPUT)
 gpio.write(myled[i],gpio.HIGH)
 mystate[i]=0
end 
end 
 
sendFileContents = function(conn, filename) 
    if file.open(filename, "r") then 
        --conn:send(responseHeader("200 OK","text/html"))
        repeat  
        local line=file.readline()  
        if line then  
            conn:send(line)
        end  
        until not line  
        file.close()
    else 
        conn:send(responseHeader("404 Not Found","text/html"))
        conn:send("Page not found")
            end 
end 
 
responseHeader = function(code, type) 
    return "HTTP/1.1 " .. code .. "\nConnection: close\nServer: nunu-Luaweb\nContent-Type: " .. type .. "\n\n";  
end 
 
httpserver = function () 
    start_init(); 
    srv=net.createServer(net.TCP)  
    srv:listen(80,function(conn)  
      conn:on("receive",function(conn,request)  
        conn:send(responseHeader("200 OK","text/html")); 
        fflag, findex, pin=string.find(request, "gpio=(%d+)")
        pin=tonumber(pin)
        if fflag and pin>=1 and pin<=6 then
          print("Changing pin "..pin.." to ")
          if mystate[pin]==0 then
               mystate[pin]=1
               gpio.write(myled[pin], gpio.LOW)
               print("on\n")
          else
               mystate[pin]=0
                gpio.write(myled[pin],gpio.HIGH)
               print("off\n")
          end         
        else 
            sendFileContents(conn,"schead.htm")
            local i
            for i=1,6 do
             if mystate[i]==0 then
              preset=""
             else
              preset="checked=\"checked\""
             end
             conn:send("<div><input type=\"checkbox\" id=\"chbox"..i.."\" name=\"chbox"..i.."\" class=\"switch\" onclick=\"loadXMLDoc("..i..")\" "..preset.." />")
             conn:send("<label for=\"chbox"..i.."\">GPIO "..i.."</label></div>\n")
            end
            conn:send("</div>")            
        end 
        print(request); 
      end)  
      conn:on("sent",function(conn)  
        conn:close() 
        conn = nil  
 
      end) 
    end) 
end 
 
httpserver()

Note:

  1. I use only the 6 red LEDs on the dev board I have
  2. I had to shorten the text sent to the web client from “checkbox2” to “chbox2” as otherwise the last characters of those 6 lines were missing. That showed when some LEDs were on and I reloaded the page. Then toggle 6 went missing. Thus don’t send too much too fast.