Skip to content

Commit 7cdbe0f

Browse files
authored
Move init.lua code into 3 smaller files. Consolidate server configuration. (marcoskirsch#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
1 parent adde150 commit 7cdbe0f

File tree

6 files changed

+170
-149
lines changed

6 files changed

+170
-149
lines changed

Makefile

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,20 @@
11
######################################################################
2-
# User configuration
2+
# Makefile user configuration
33
######################################################################
4+
45
# Path to nodemcu-uploader (https://github.com/kmpm/nodemcu-uploader)
56
NODEMCU-UPLOADER=../nodemcu-uploader/nodemcu-uploader.py
7+
68
# Serial port
79
PORT=/dev/cu.SLAB_USBtoUART
810
SPEED=115200
911

1012
NODEMCU-COMMAND=$(NODEMCU-UPLOADER) -b $(SPEED) --start_baud $(SPEED) -p $(PORT) upload
1113

1214
######################################################################
13-
# End of user config
14-
######################################################################
15+
1516
HTTP_FILES := $(wildcard http/*)
16-
LUA_FILES := \
17-
init.lua \
18-
httpserver.lua \
19-
httpserver-b64decode.lua \
20-
httpserver-basicauth.lua \
21-
httpserver-conf.lua \
22-
httpserver-connection.lua \
23-
httpserver-error.lua \
24-
httpserver-header.lua \
25-
httpserver-request.lua \
26-
httpserver-static.lua \
17+
LUA_FILES := $(wildcard *.lua)
2718

2819
# Print usage
2920
usage:

httpserver-compile.lua

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
-- httpserver-compile.lua
2+
-- Part of nodemcu-httpserver, compiles server code after upload.
3+
-- Author: Marcos Kirsch
4+
5+
local compileAndRemoveIfNeeded = function(f)
6+
if file.open(f) then
7+
file.close()
8+
print('Compiling:', f)
9+
node.compile(f)
10+
file.remove(f)
11+
collectgarbage()
12+
end
13+
end
14+
15+
local serverFiles = {
16+
'httpserver.lua',
17+
'httpserver-b64decode.lua',
18+
'httpserver-basicauth.lua',
19+
'httpserver-compile.lua',
20+
'httpserver-conf.lua',
21+
'httpserver-connection.lua',
22+
'httpserver-error.lua',
23+
'httpserver-header.lua',
24+
'httpserver-init.lua',
25+
'httpserver-request.lua',
26+
'httpserver-static.lua',
27+
'httpserver-wifi.lua',
28+
}
29+
for i, f in ipairs(serverFiles) do compileAndRemoveIfNeeded(f) end
30+
31+
compileAndRemoveIfNeeded = nil
32+
serverFiles = nil
33+
collectgarbage()
34+

httpserver-conf.lua

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,49 @@
11
-- httpserver-conf.lua
22
-- Part of nodemcu-httpserver, contains static configuration for httpserver.
3+
-- Edit your server's configuration below.
34
-- Author: Sam Dieck
45

56
local conf = {}
67

7-
-- Configure Basic HTTP Authentication.
8-
local auth = {}
8+
-- General server configuration.
9+
conf.general = {}
10+
-- TCP port in which to listen for incoming HTTP requests.
11+
conf.general.port = 80
12+
13+
-- WiFi configuration
14+
conf.wifi = {}
15+
-- Can be wifi.STATION, wifi.SOFTAP, or wifi.STATIONAP
16+
conf.wifi.mode = wifi.STATION
17+
-- Theses apply only when configured as Access Point (wifi.SOFTAP or wifi.STATIONAP)
18+
if (conf.wifi.mode == wifi.SOFTAP) or (conf.wifi.mode == wifi.STATIONAP) then
19+
conf.wifi.accessPoint = {}
20+
conf.wifi.accessPoint.config = {}
21+
conf.wifi.accessPoint.config.ssid = "ESP-"..node.chipid() -- Name of the WiFi network to create.
22+
conf.wifi.accessPoint.config.pwd = "ESP-"..node.chipid() -- WiFi password for joining - at least 8 characters
23+
conf.wifi.accessPoint.ip = "192.168.111.1"
24+
-- conf.wifi.accessPoint.netmask = "255.255.255.0"
25+
-- conf.wifi.accessPoint.gateway = "192.168.111.1"
26+
end
27+
-- These apply only when connecting to a router as a client
28+
if (conf.wifi.mode == wifi.STATION) or (conf.wifi.mode == wifi.STATIONAP) then
29+
conf.wifi.station = {}
30+
conf.wifi.station.ssid = "Internet" -- Name of the WiFi network you want to join
31+
conf.wifi.station.pwd = "" -- Password for the WiFi network
32+
end
33+
34+
-- mDNS, applies if you compiled the mdns module in your firmware.
35+
conf.mdns = {}
36+
conf.mdns.hostname = 'nodemcu' -- You will be able to access your server at "http://nodemcu.local."
37+
conf.mdns.location = 'Earth'
38+
conf.mdns.description = 'A tiny HTTP server'
39+
40+
-- Basic HTTP Authentication.
41+
conf.auth = {}
942
-- Set to true if you want to enable.
10-
auth.enabled = false
43+
conf.auth.enabled = false
1144
-- Displayed in the login dialog users see before authenticating.
12-
auth.realm = "nodemcu"
45+
conf.auth.realm = "nodemcu"
1346
-- Add users and passwords to this table. Do not leave this unchanged if you enable authentication!
14-
auth.users = {user1 = "password1", user2 = "password2", user3 = "password3"}
47+
conf.auth.users = {user1 = "password1", user2 = "password2", user3 = "password3"}
1548

16-
conf.auth = auth
1749
return conf

httpserver-init.lua

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

httpserver-wifi.lua

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
-- httpserver-wifi.lua
2+
-- Part of nodemcu-httpserver, configures NodeMCU's WiFI in boot.
3+
-- Author: Marcos Kirsch
4+
5+
local conf = nil
6+
if file.exists("httpserver-conf.lc") then
7+
conf = dofile("httpserver-conf.lc")
8+
else
9+
conf = dofile("httpserver-conf.lua")
10+
end
11+
12+
wifi.setmode(conf.wifi.mode)
13+
14+
if (conf.wifi.mode == wifi.SOFTAP) or (conf.wifi.mode == wifi.STATIONAP) then
15+
print('AP MAC: ',wifi.ap.getmac())
16+
wifi.ap.config(conf.wifi.accessPoint.config)
17+
wifi.ap.setip(conf.wifi.accessPoint.ip)
18+
end
19+
20+
if (conf.wifi.mode == wifi.STATION) or (conf.wifi.mode == wifi.STATIONAP) then
21+
print('Client MAC: ',wifi.sta.getmac())
22+
wifi.sta.config(conf.wifi.station.ssid, conf.wifi.station.pwd, 1)
23+
end
24+
25+
print('chip: ',node.chipid())
26+
print('heap: ',node.heap())
27+
28+
conf = nil
29+
collectgarbage()
30+
31+
-- End WiFi configuration

init.lua

Lines changed: 9 additions & 129 deletions
Original file line numberDiff line numberDiff line change
@@ -1,132 +1,12 @@
1-
-- Begin WiFi configuration
2-
3-
local wifiConfig = {}
4-
5-
-- Possible modes: wifi.STATION : station: join a WiFi network
6-
-- wifi.SOFTAP : access point: create a WiFi network
7-
-- wifi.STATIONAP : both station and access point
8-
wifiConfig.mode = wifi.STATION
9-
10-
if (wifiConfig.mode == wifi.SOFTAP) or (wifiConfig.mode == wifi.STATIONAP) then
11-
wifiConfig.accessPointConfig = {}
12-
wifiConfig.accessPointConfig.ssid = "ESP-"..node.chipid() -- Name of the SSID you want to create
13-
wifiConfig.accessPointConfig.pwd = "ESP-"..node.chipid() -- WiFi password - at least 8 characters
14-
15-
wifiConfig.accessPointIpConfig = {}
16-
wifiConfig.accessPointIpConfig.ip = "192.168.111.1"
17-
wifiConfig.accessPointIpConfig.netmask = "255.255.255.0"
18-
wifiConfig.accessPointIpConfig.gateway = "192.168.111.1"
19-
end
20-
21-
if (wifiConfig.mode == wifi.STATION) or (wifiConfig.mode == wifi.STATIONAP) then
22-
wifiConfig.stationConfig = {}
23-
wifiConfig.stationConfig.ssid = "Internet" -- Name of the WiFi network you want to join
24-
wifiConfig.stationConfig.pwd = "" -- Password for the WiFi network
25-
end
26-
27-
-- Tell the chip to connect to the access point
28-
29-
wifi.setmode(wifiConfig.mode)
30-
--print('set (mode='..wifi.getmode()..')')
31-
32-
if (wifiConfig.mode == wifi.SOFTAP) or (wifiConfig.mode == wifi.STATIONAP) then
33-
print('AP MAC: ',wifi.ap.getmac())
34-
wifi.ap.config(wifiConfig.accessPointConfig)
35-
wifi.ap.setip(wifiConfig.accessPointIpConfig)
36-
end
37-
38-
if (wifiConfig.mode == wifi.STATION) or (wifiConfig.mode == wifi.STATIONAP) then
39-
print('Client MAC: ',wifi.sta.getmac())
40-
wifi.sta.config(wifiConfig.stationConfig.ssid, wifiConfig.stationConfig.pwd, 1)
41-
end
42-
43-
print('chip: ',node.chipid())
44-
print('heap: ',node.heap())
45-
46-
wifiConfig = nil
47-
collectgarbage()
48-
49-
-- End WiFi configuration
50-
51-
52-
-- Compile server code and remove original .lua files.
53-
-- This only happens the first time after server .lua files are uploaded.
54-
55-
local compileAndRemoveIfNeeded = function(f)
56-
if file.open(f) then
57-
file.close()
58-
print('Compiling:', f)
59-
node.compile(f)
60-
file.remove(f)
61-
collectgarbage()
62-
end
63-
end
64-
65-
local serverFiles = {
66-
'httpserver.lua',
67-
'httpserver-b64decode.lua',
68-
'httpserver-basicauth.lua',
69-
'httpserver-conf.lua',
70-
'httpserver-connection.lua',
71-
'httpserver-error.lua',
72-
'httpserver-header.lua',
73-
'httpserver-request.lua',
74-
'httpserver-static.lua',
75-
}
76-
for i, f in ipairs(serverFiles) do compileAndRemoveIfNeeded(f) end
77-
78-
compileAndRemoveIfNeeded = nil
79-
serverFiles = nil
80-
collectgarbage()
81-
82-
83-
-- Function for starting the server.
84-
-- If you compiled the mdns module, then it will register the server with that name.
85-
local startServer = function(ip, hostname)
86-
local serverPort = 80
87-
if (dofile("httpserver.lc")(serverPort)) then
88-
print("nodemcu-httpserver running at:")
89-
print(" http://" .. ip .. ":" .. serverPort)
90-
if (mdns) then
91-
mdns.register(hostname, { description="A tiny server", service="http", port=serverPort, location='Earth' })
92-
print (' http://' .. hostname .. '.local.:' .. serverPort)
93-
end
94-
end
95-
end
96-
97-
98-
if (wifi.getmode() == wifi.STATION) or (wifi.getmode() == wifi.STATIONAP) then
99-
100-
-- Connect to the WiFi access point and start server once connected.
101-
-- If the server loses connectivity, server will restart.
102-
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(args)
103-
print("Connected to WiFi Access Point. Got IP: " .. args["IP"])
104-
startServer(args["IP"], "nodemcu")
105-
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(args)
106-
print("Lost connectivity! Restarting...")
107-
node.restart()
108-
end)
109-
end)
110-
111-
-- What if after a while (30 seconds) we didn't connect? Restart and keep trying.
112-
local watchdogTimer = tmr.create()
113-
watchdogTimer:register(30000, tmr.ALARM_SINGLE, function (watchdogTimer)
114-
local ip = wifi.sta.getip()
115-
if (not ip) then ip = wifi.ap.getip() end
116-
if ip == nil then
117-
print("No IP after a while. Restarting...")
118-
node.restart()
119-
else
120-
--print("Successfully got IP. Good, no need to restart.")
121-
watchdogTimer:unregister()
122-
end
123-
end)
124-
watchdogTimer:start()
125-
126-
1+
-- Compile freshly uploaded nodemcu-httpserver lua files.
2+
if file.exists("httpserver-compile.lc") then
3+
dofile("httpserver-compile.lc")
1274
else
128-
129-
startServer(wifi.ap.getip(), "nodemcu")
130-
5+
dofile("httpserver-compile.lua")
1316
end
1327

8+
-- Set up NodeMCU's WiFi
9+
dofile("httpserver-wifi.lc")
10+
11+
-- Start nodemcu-httpsertver
12+
dofile("httpserver-init.lc")

0 commit comments

Comments
 (0)