Move init.lua code into 3 smaller files. Consolidate server configuration. (#94)

* Move server initialization out of init.lua and into new httpserver-init.lua

* Use wildcard for finding server files to upload.

* Break init.lua up into 3 files. Move all configuration to httpserver.conf.

New files are:
* httpserver-compile.lua
* httpserver-wifi.lua
* httpserver-init.lua
This commit is contained in:
Marcos 2017-07-01 22:01:45 -05:00 committed by GitHub
parent adde150009
commit 7cdbe0ffd0
6 changed files with 173 additions and 152 deletions

View File

@ -1,8 +1,10 @@
###################################################################### ######################################################################
# User configuration # Makefile user configuration
###################################################################### ######################################################################
# Path to nodemcu-uploader (https://github.com/kmpm/nodemcu-uploader) # Path to nodemcu-uploader (https://github.com/kmpm/nodemcu-uploader)
NODEMCU-UPLOADER=../nodemcu-uploader/nodemcu-uploader.py NODEMCU-UPLOADER=../nodemcu-uploader/nodemcu-uploader.py
# Serial port # Serial port
PORT=/dev/cu.SLAB_USBtoUART PORT=/dev/cu.SLAB_USBtoUART
SPEED=115200 SPEED=115200
@ -10,20 +12,9 @@ SPEED=115200
NODEMCU-COMMAND=$(NODEMCU-UPLOADER) -b $(SPEED) --start_baud $(SPEED) -p $(PORT) upload NODEMCU-COMMAND=$(NODEMCU-UPLOADER) -b $(SPEED) --start_baud $(SPEED) -p $(PORT) upload
###################################################################### ######################################################################
# End of user config
######################################################################
HTTP_FILES := $(wildcard http/*) HTTP_FILES := $(wildcard http/*)
LUA_FILES := \ LUA_FILES := $(wildcard *.lua)
init.lua \
httpserver.lua \
httpserver-b64decode.lua \
httpserver-basicauth.lua \
httpserver-conf.lua \
httpserver-connection.lua \
httpserver-error.lua \
httpserver-header.lua \
httpserver-request.lua \
httpserver-static.lua \
# Print usage # Print usage
usage: usage:

34
httpserver-compile.lua Normal file
View File

@ -0,0 +1,34 @@
-- httpserver-compile.lua
-- Part of nodemcu-httpserver, compiles server code after upload.
-- Author: Marcos Kirsch
local compileAndRemoveIfNeeded = function(f)
if file.open(f) then
file.close()
print('Compiling:', f)
node.compile(f)
file.remove(f)
collectgarbage()
end
end
local serverFiles = {
'httpserver.lua',
'httpserver-b64decode.lua',
'httpserver-basicauth.lua',
'httpserver-compile.lua',
'httpserver-conf.lua',
'httpserver-connection.lua',
'httpserver-error.lua',
'httpserver-header.lua',
'httpserver-init.lua',
'httpserver-request.lua',
'httpserver-static.lua',
'httpserver-wifi.lua',
}
for i, f in ipairs(serverFiles) do compileAndRemoveIfNeeded(f) end
compileAndRemoveIfNeeded = nil
serverFiles = nil
collectgarbage()

View File

@ -1,17 +1,49 @@
-- httpserver-conf.lua -- httpserver-conf.lua
-- Part of nodemcu-httpserver, contains static configuration for httpserver. -- Part of nodemcu-httpserver, contains static configuration for httpserver.
-- Edit your server's configuration below.
-- Author: Sam Dieck -- Author: Sam Dieck
local conf = {} local conf = {}
-- Configure Basic HTTP Authentication. -- General server configuration.
local auth = {} conf.general = {}
-- Set to true if you want to enable. -- TCP port in which to listen for incoming HTTP requests.
auth.enabled = false conf.general.port = 80
-- Displayed in the login dialog users see before authenticating.
auth.realm = "nodemcu" -- WiFi configuration
-- Add users and passwords to this table. Do not leave this unchanged if you enable authentication! conf.wifi = {}
auth.users = {user1 = "password1", user2 = "password2", user3 = "password3"} -- Can be wifi.STATION, wifi.SOFTAP, or wifi.STATIONAP
conf.wifi.mode = wifi.STATION
-- Theses apply only when configured as Access Point (wifi.SOFTAP or wifi.STATIONAP)
if (conf.wifi.mode == wifi.SOFTAP) or (conf.wifi.mode == wifi.STATIONAP) then
conf.wifi.accessPoint = {}
conf.wifi.accessPoint.config = {}
conf.wifi.accessPoint.config.ssid = "ESP-"..node.chipid() -- Name of the WiFi network to create.
conf.wifi.accessPoint.config.pwd = "ESP-"..node.chipid() -- WiFi password for joining - at least 8 characters
conf.wifi.accessPoint.ip = "192.168.111.1"
-- conf.wifi.accessPoint.netmask = "255.255.255.0"
-- conf.wifi.accessPoint.gateway = "192.168.111.1"
end
-- These apply only when connecting to a router as a client
if (conf.wifi.mode == wifi.STATION) or (conf.wifi.mode == wifi.STATIONAP) then
conf.wifi.station = {}
conf.wifi.station.ssid = "Internet" -- Name of the WiFi network you want to join
conf.wifi.station.pwd = "" -- Password for the WiFi network
end
-- mDNS, applies if you compiled the mdns module in your firmware.
conf.mdns = {}
conf.mdns.hostname = 'nodemcu' -- You will be able to access your server at "http://nodemcu.local."
conf.mdns.location = 'Earth'
conf.mdns.description = 'A tiny HTTP server'
-- Basic HTTP Authentication.
conf.auth = {}
-- Set to true if you want to enable.
conf.auth.enabled = false
-- Displayed in the login dialog users see before authenticating.
conf.auth.realm = "nodemcu"
-- Add users and passwords to this table. Do not leave this unchanged if you enable authentication!
conf.auth.users = {user1 = "password1", user2 = "password2", user3 = "password3"}
conf.auth = auth
return conf return conf

53
httpserver-init.lua Normal file
View File

@ -0,0 +1,53 @@
-- httpserver-init.lua
-- Part of nodemcu-httpserver, launches the server.
-- Author: Marcos Kirsch
-- Function for starting the server.
-- If you compiled the mdns module, then it will also register with mDNS.
local startServer = function(ip)
local conf = dofile('httpserver-conf.lc')
if (dofile("httpserver.lc")(conf['general']['port'])) then
print("nodemcu-httpserver running at:")
print(" http://" .. ip .. ":" .. conf['general']['port'])
if (mdns) then
mdns.register(conf['mdns']['hostname'], { description=conf['mdns']['description'], service="http", port=conf['general']['port'], location=conf['mdns']['location'] })
print (' http://' .. conf['mdns']['hostname'] .. '.local.:' .. conf['general']['port'])
end
end
conf = nil
end
if (wifi.getmode() == wifi.STATION) or (wifi.getmode() == wifi.STATIONAP) then
-- Connect to the WiFi access point and start server once connected.
-- If the server loses connectivity, server will restart.
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(args)
print("Connected to WiFi Access Point. Got IP: " .. args["IP"])
startServer(args["IP"])
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(args)
print("Lost connectivity! Restarting...")
node.restart()
end)
end)
-- What if after a while (30 seconds) we didn't connect? Restart and keep trying.
local watchdogTimer = tmr.create()
watchdogTimer:register(30000, tmr.ALARM_SINGLE, function (watchdogTimer)
local ip = wifi.sta.getip()
if (not ip) then ip = wifi.ap.getip() end
if ip == nil then
print("No IP after a while. Restarting...")
node.restart()
else
--print("Successfully got IP. Good, no need to restart.")
watchdogTimer:unregister()
end
end)
watchdogTimer:start()
else
startServer(wifi.ap.getip())
end

31
httpserver-wifi.lua Normal file
View File

@ -0,0 +1,31 @@
-- httpserver-wifi.lua
-- Part of nodemcu-httpserver, configures NodeMCU's WiFI in boot.
-- Author: Marcos Kirsch
local conf = nil
if file.exists("httpserver-conf.lc") then
conf = dofile("httpserver-conf.lc")
else
conf = dofile("httpserver-conf.lua")
end
wifi.setmode(conf.wifi.mode)
if (conf.wifi.mode == wifi.SOFTAP) or (conf.wifi.mode == wifi.STATIONAP) then
print('AP MAC: ',wifi.ap.getmac())
wifi.ap.config(conf.wifi.accessPoint.config)
wifi.ap.setip(conf.wifi.accessPoint.ip)
end
if (conf.wifi.mode == wifi.STATION) or (conf.wifi.mode == wifi.STATIONAP) then
print('Client MAC: ',wifi.sta.getmac())
wifi.sta.config(conf.wifi.station.ssid, conf.wifi.station.pwd, 1)
end
print('chip: ',node.chipid())
print('heap: ',node.heap())
conf = nil
collectgarbage()
-- End WiFi configuration

138
init.lua
View File

@ -1,132 +1,12 @@
-- Begin WiFi configuration -- Compile freshly uploaded nodemcu-httpserver lua files.
if file.exists("httpserver-compile.lc") then
local wifiConfig = {} dofile("httpserver-compile.lc")
-- Possible modes: wifi.STATION : station: join a WiFi network
-- wifi.SOFTAP : access point: create a WiFi network
-- wifi.STATIONAP : both station and access point
wifiConfig.mode = wifi.STATION
if (wifiConfig.mode == wifi.SOFTAP) or (wifiConfig.mode == wifi.STATIONAP) then
wifiConfig.accessPointConfig = {}
wifiConfig.accessPointConfig.ssid = "ESP-"..node.chipid() -- Name of the SSID you want to create
wifiConfig.accessPointConfig.pwd = "ESP-"..node.chipid() -- WiFi password - at least 8 characters
wifiConfig.accessPointIpConfig = {}
wifiConfig.accessPointIpConfig.ip = "192.168.111.1"
wifiConfig.accessPointIpConfig.netmask = "255.255.255.0"
wifiConfig.accessPointIpConfig.gateway = "192.168.111.1"
end
if (wifiConfig.mode == wifi.STATION) or (wifiConfig.mode == wifi.STATIONAP) then
wifiConfig.stationConfig = {}
wifiConfig.stationConfig.ssid = "Internet" -- Name of the WiFi network you want to join
wifiConfig.stationConfig.pwd = "" -- Password for the WiFi network
end
-- Tell the chip to connect to the access point
wifi.setmode(wifiConfig.mode)
--print('set (mode='..wifi.getmode()..')')
if (wifiConfig.mode == wifi.SOFTAP) or (wifiConfig.mode == wifi.STATIONAP) then
print('AP MAC: ',wifi.ap.getmac())
wifi.ap.config(wifiConfig.accessPointConfig)
wifi.ap.setip(wifiConfig.accessPointIpConfig)
end
if (wifiConfig.mode == wifi.STATION) or (wifiConfig.mode == wifi.STATIONAP) then
print('Client MAC: ',wifi.sta.getmac())
wifi.sta.config(wifiConfig.stationConfig.ssid, wifiConfig.stationConfig.pwd, 1)
end
print('chip: ',node.chipid())
print('heap: ',node.heap())
wifiConfig = nil
collectgarbage()
-- End WiFi configuration
-- Compile server code and remove original .lua files.
-- This only happens the first time after server .lua files are uploaded.
local compileAndRemoveIfNeeded = function(f)
if file.open(f) then
file.close()
print('Compiling:', f)
node.compile(f)
file.remove(f)
collectgarbage()
end
end
local serverFiles = {
'httpserver.lua',
'httpserver-b64decode.lua',
'httpserver-basicauth.lua',
'httpserver-conf.lua',
'httpserver-connection.lua',
'httpserver-error.lua',
'httpserver-header.lua',
'httpserver-request.lua',
'httpserver-static.lua',
}
for i, f in ipairs(serverFiles) do compileAndRemoveIfNeeded(f) end
compileAndRemoveIfNeeded = nil
serverFiles = nil
collectgarbage()
-- Function for starting the server.
-- If you compiled the mdns module, then it will register the server with that name.
local startServer = function(ip, hostname)
local serverPort = 80
if (dofile("httpserver.lc")(serverPort)) then
print("nodemcu-httpserver running at:")
print(" http://" .. ip .. ":" .. serverPort)
if (mdns) then
mdns.register(hostname, { description="A tiny server", service="http", port=serverPort, location='Earth' })
print (' http://' .. hostname .. '.local.:' .. serverPort)
end
end
end
if (wifi.getmode() == wifi.STATION) or (wifi.getmode() == wifi.STATIONAP) then
-- Connect to the WiFi access point and start server once connected.
-- If the server loses connectivity, server will restart.
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(args)
print("Connected to WiFi Access Point. Got IP: " .. args["IP"])
startServer(args["IP"], "nodemcu")
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(args)
print("Lost connectivity! Restarting...")
node.restart()
end)
end)
-- What if after a while (30 seconds) we didn't connect? Restart and keep trying.
local watchdogTimer = tmr.create()
watchdogTimer:register(30000, tmr.ALARM_SINGLE, function (watchdogTimer)
local ip = wifi.sta.getip()
if (not ip) then ip = wifi.ap.getip() end
if ip == nil then
print("No IP after a while. Restarting...")
node.restart()
else
--print("Successfully got IP. Good, no need to restart.")
watchdogTimer:unregister()
end
end)
watchdogTimer:start()
else else
dofile("httpserver-compile.lua")
startServer(wifi.ap.getip(), "nodemcu")
end end
-- Set up NodeMCU's WiFi
dofile("httpserver-wifi.lc")
-- Start nodemcu-httpsertver
dofile("httpserver-init.lc")