init.lua 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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-basicauth.lua', 'httpserver-conf.lua', 'b64.lua', 'httpserver-request.lua', 'httpserver-static.lua', 'httpserver-header.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. local ip = wifi.sta.getip()
  46. if ip == nil and joinCounter < joinMaxAttempts then
  47. print('Connecting to WiFi Access Point ...')
  48. joinCounter = joinCounter +1
  49. else
  50. if joinCounter == joinMaxAttempts then
  51. print('Faild to connect to WiFi Access Point.')
  52. else
  53. print('IP: ',ip)
  54. -- Uncomment to automatically start the server in port 80
  55. dofile("httpserver.lc")(80)
  56. end
  57. tmr.stop(0)
  58. joinCounter = nil
  59. joinMaxAttempts = nil
  60. collectgarbage()
  61. end
  62. end)