init.lua 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. -- load credentials, 'SSID' and 'PASSWORD' declared and initialize in there
  2. dofile("credentials.lua")
  3. function startup()
  4. if file.open("init.lua") == nil then
  5. print("init.lua deleted or renamed")
  6. else
  7. print("Running")
  8. file.close("init.lua")
  9. -- the actual application is stored in 'application.lua'
  10. dofile("application.lua")
  11. end
  12. end
  13. -- Define WiFi station event callbacks
  14. wifi_connect_event = function(T)
  15. print("Connection to AP("..T.SSID..") established!")
  16. print("Waiting for IP address...")
  17. if disconnect_ct ~= nil then disconnect_ct = nil end
  18. end
  19. wifi_got_ip_event = function(T)
  20. -- Note: Having an IP address does not mean there is internet access!
  21. -- Internet connectivity can be determined with net.dns.resolve().
  22. print("Wifi connection is ready! IP address is: "..T.IP)
  23. print("Startup will resume momentarily, you have 3 seconds to abort.")
  24. print("Waiting...")
  25. tmr.create():alarm(1000, tmr.ALARM_SINGLE, startup)
  26. end
  27. wifi_disconnect_event = function(T)
  28. if T.reason == wifi.eventmon.reason.ASSOC_LEAVE then
  29. --the station has disassociated from a previously connected AP
  30. return
  31. end
  32. -- total_tries: how many times the station will attempt to connect to the AP. Should consider AP reboot duration.
  33. local total_tries = 75
  34. print("\nWiFi connection to AP("..T.SSID..") has failed!")
  35. --There are many possible disconnect reasons, the following iterates through
  36. --the list and returns the string corresponding to the disconnect reason.
  37. for key,val in pairs(wifi.eventmon.reason) do
  38. if val == T.reason then
  39. print("Disconnect reason: "..val.."("..key..")")
  40. break
  41. end
  42. end
  43. if disconnect_ct == nil then
  44. disconnect_ct = 1
  45. else
  46. disconnect_ct = disconnect_ct + 1
  47. end
  48. if disconnect_ct < total_tries then
  49. print("Retrying connection...(attempt "..(disconnect_ct+1).." of "..total_tries..")")
  50. else
  51. wifi.sta.disconnect()
  52. print("Aborting connection to AP!")
  53. disconnect_ct = nil
  54. end
  55. end
  56. -- Register WiFi Station event callbacks
  57. wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, wifi_connect_event)
  58. wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, wifi_got_ip_event)
  59. wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, wifi_disconnect_event)
  60. print("Connecting to WiFi access point...")
  61. wifi.setmode(wifi.STATION)
  62. if STATIC_IP ~= nil then
  63. wifi.sta.setip(STATIC_IP)
  64. end
  65. wifi.sta.config({ssid=SSID, pwd=PASSWORD})
  66. -- wifi.sta.connect() not necessary because config() uses auto-connect=true by default