httpserver-init.lua 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. -- httpserver-init.lua
  2. -- Part of nodemcu-httpserver, launches the server.
  3. -- Author: Marcos Kirsch
  4. -- Function for starting the server.
  5. -- If you compiled the mdns module, then it will also register with mDNS.
  6. local startServer = function(ip)
  7. local conf = dofile('httpserver-conf.lc')
  8. if (dofile("httpserver.lc")(conf['general']['port'])) then
  9. print("nodemcu-httpserver running at:")
  10. print(" http://" .. ip .. ":" .. conf['general']['port'])
  11. if (mdns) then
  12. mdns.register(conf['mdns']['hostname'], { description=conf['mdns']['description'], service="http", port=conf['general']['port'], location=conf['mdns']['location'] })
  13. print (' http://' .. conf['mdns']['hostname'] .. '.local.:' .. conf['general']['port'])
  14. end
  15. end
  16. conf = nil
  17. end
  18. if (wifi.getmode() == wifi.STATION) or (wifi.getmode() == wifi.STATIONAP) then
  19. -- Connect to the WiFi access point and start server once connected.
  20. -- If the server loses connectivity, server will restart.
  21. wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(args)
  22. print("Connected to WiFi Access Point. Got IP: " .. args["IP"])
  23. startServer(args["IP"])
  24. wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(args)
  25. print("Lost connectivity! Restarting...")
  26. node.restart()
  27. end)
  28. end)
  29. -- What if after a while (30 seconds) we didn't connect? Restart and keep trying.
  30. local watchdogTimer = tmr.create()
  31. watchdogTimer:register(30000, tmr.ALARM_SINGLE, function (watchdogTimer)
  32. local ip = wifi.sta.getip()
  33. if (not ip) then ip = wifi.ap.getip() end
  34. if ip == nil then
  35. print("No IP after a while. Restarting...")
  36. node.restart()
  37. else
  38. --print("Successfully got IP. Good, no need to restart.")
  39. watchdogTimer:unregister()
  40. end
  41. end)
  42. watchdogTimer:start()
  43. else
  44. startServer(wifi.ap.getip())
  45. end