connect_ap.lua 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. -- Author: moononournation
  2. -- Notes by Marcos: This example could be improved quite a bit.
  3. -- We should provide a way to return available access points as JSON, then populated
  4. -- a drop down list using JavaScript every 5-10 seconds. I'm not sure it's worth it,
  5. -- however.
  6. return function (connection, req, args)
  7. dofile('httpserver-header.lc')(connection, 200, 'html')
  8. connection:send('<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Connect AP</title></head><body><h1>Connect AP</h1>')
  9. if req.method == 'GET' then
  10. local ip = wifi.sta.getip()
  11. if not (ip == nil) then
  12. connection:send('<p>IP: ' .. ip .. '</p>')
  13. end
  14. connection:send('<form method="POST">SSID:<br><input type="text" name="ssid"><br>PWD:<br><input type="text" name="pwd"><br><input type="submit" name="submit" value="Submit"></form>')
  15. elseif req.method == 'POST' then
  16. local rd = req.getRequestData()
  17. collectgarbage()
  18. wifi.sta.config(rd['ssid'], rd['pwd'])
  19. wifi.sta.connect()
  20. local joinCounter = 0
  21. local joinMaxAttempts = 15
  22. tmr.alarm(0, 1000, 1, function()
  23. local ip = wifi.sta.getip()
  24. if ip == nil and joinCounter < joinMaxAttempts then
  25. joinCounter = joinCounter + 1
  26. else
  27. if joinCounter >= joinMaxAttempts then
  28. connection:send('<p>Failed to connect to WiFi Access Point.</p>')
  29. else
  30. connection:send('<p>IP: ' .. ip .. '</p>')
  31. end
  32. tmr.stop(0)
  33. joinCounter = nil
  34. joinMaxAttempts = nil
  35. collectgarbage()
  36. end
  37. end)
  38. end
  39. connection:send('</body></html>')
  40. end