webap_toggle_pin.lua 1.2 KB

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