init.lua 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. -- Begin WiFi configuration
  2. local wifiConfig = {}
  3. -- wifi.STATION -- station: join a WiFi network
  4. -- wifi.AP -- access point: create a WiFi network
  5. -- wifi.wifi.STATIONAP -- both station and access point
  6. wifiConfig.mode = wifi.STATIONAP -- both station and access point
  7. wifiConfig.accessPointConfig = {}
  8. wifiConfig.accessPointConfig.ssid = "ESP-"..node.chipid() -- Name of the SSID you want to create
  9. wifiConfig.accessPointConfig.pwd = "ESP-"..node.chipid() -- WiFi password - at least 8 characters
  10. wifiConfig.stationPointConfig = {}
  11. wifiConfig.stationPointConfig.ssid = "Internet" -- Name of the WiFi network you want to join
  12. wifiConfig.stationPointConfig.pwd = "" -- Password for the WiFi network
  13. -- Tell the chip to connect to the access point
  14. wifi.setmode(wifiConfig.mode)
  15. print('set (mode='..wifi.getmode()..')')
  16. print('MAC: ',wifi.sta.getmac())
  17. print('chip: ',node.chipid())
  18. print('heap: ',node.heap())
  19. wifi.ap.config(wifiConfig.accessPointConfig)
  20. wifi.sta.config(wifiConfig.stationPointConfig.ssid, wifiConfig.stationPointConfig.pwd)
  21. wifiConfig = nil
  22. collectgarbage()
  23. -- End WiFi configuration
  24. -- Compile server code and remove original .lua files.
  25. -- This only happens the first time afer the .lua files are uploaded.
  26. local compileAndRemoveIfNeeded = function(f)
  27. if file.open(f) then
  28. file.close()
  29. print('Compiling:', f)
  30. node.compile(f)
  31. file.remove(f)
  32. collectgarbage()
  33. end
  34. end
  35. local serverFiles = {'httpserver.lua', 'httpserver-request.lua', 'httpserver-static.lua', 'httpserver-error.lua'}
  36. for i, f in ipairs(serverFiles) do compileAndRemoveIfNeeded(f) end
  37. compileAndRemoveIfNeeded = nil
  38. serverFiles = nil
  39. collectgarbage()
  40. -- Connect to the WiFi access point.
  41. -- Once the device is connected, you may start the HTTP server.
  42. local joinCounter = 0
  43. local joinMaxAttempts = 5
  44. tmr.alarm(0, 3000, 1, function()
  45. if wifi.sta.getip() == nil and joinCounter < joinMaxAttempts then
  46. print('Connecting to WiFi Access Point ...')
  47. joinCounter = joinCounter +1
  48. else
  49. if joinCounter == joinMaxAttempts then
  50. print('Faild to connect to WiFi Access Point.')
  51. else
  52. print('IP: ',wifi.sta.getip())
  53. -- Uncomment to automatically start the server in port 80
  54. --dofile("httpserver.lc")(80)
  55. end
  56. tmr.stop(0)
  57. joinCounter = nil
  58. joinMaxAttempts = nil
  59. collectgarbage()
  60. end
  61. end)