webap_toggle_pin.lua 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. wifi.setmode(wifi.SOFTAP)
  2. wifi.ap.config({ ssid = "test", pwd = "12345678" })
  3. gpio.mode(1, gpio.OUTPUT)
  4. srv = net.createServer(net.TCP)
  5. srv:listen(80, function(conn)
  6. conn:on("receive", function(client, request)
  7. local buf = ""
  8. local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP")
  9. if (method == nil) then
  10. _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP")
  11. end
  12. local _GET = {}
  13. if (vars ~= nil) then
  14. for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
  15. _GET[k] = v
  16. end
  17. end
  18. buf = buf .. "<!DOCTYPE html><html><body><h1>Hello, this is NodeMCU.</h1><form src=\"/\">Turn PIN1 <select name=\"pin\" onchange=\"form.submit()\">"
  19. local _on, _off = "", ""
  20. if (_GET.pin == "ON") then
  21. _on = " selected=true"
  22. gpio.write(1, gpio.HIGH)
  23. elseif (_GET.pin == "OFF") then
  24. _off = " selected=\"true\""
  25. gpio.write(1, gpio.LOW)
  26. end
  27. buf = buf .. "<option" .. _on .. ">ON</option><option" .. _off .. ">OFF</option></select></form></body></html>"
  28. client:send(buf)
  29. end)
  30. conn:on("sent", function(c) c:close() end)
  31. end)