forked from elric91/nodemcu_sonoff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.lua
110 lines (99 loc) · 2.62 KB
/
init.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
-- safe library load
function load_lib(fname)
function try_load(fname)
if file.open(fname) then
file.close()
local ret, err = pcall(function() dofile(fname) end)
if ret == false then
print(fname .. " -- load failed!")
print(err)
end
return ret
else
return false
end
end
if try_load(fname..".lc") then return true end
if try_load(fname..".lua") then return true end
print(fname .. ".lua/.lc -- not found!")
return false
end
-- get table length
function tablelen(table)
local n = 0
for _ in pairs(table) do
n = n + 1
end
return n
end
load_lib("gpio")
-- init all globals
if not load_lib("config") then
load_lib("default_config")
end
load_lib("led")
local ssid, pass = nil
local wifiReady = 0
local firstPass = 0
-- connect to WIFI network(s) from SSID list
function connectWiFi(ssid_list)
for k,v in pairs(WIFI_AUTH) do
if ssid_list[k] then
ssid, pass = k, v
break
end
end
if ssid ~= nil then
print("Connecting to "..ssid)
-- New wifi module API used since nodemcu fw pull request #1497
station_cfg={}
station_cfg.ssid = ssid
station_cfg.pwd = pass
wifi.sta.config(station_cfg)
tmr.alarm(WIFI_ALARM_ID, 2000, tmr.ALARM_AUTO, wifi_watch)
else
print("No SSIDs found")
LedFlicker(50, 100, 5)
end
end
-- configure WIFI network
function configureWiFi()
LedFlicker(50, 500, 10)
wifi.setmode(wifi.STATION)
if tablelen(WIFI_AUTH) > 1 then
-- scan available networks
wifi.sta.getap(connectWiFi)
else
-- connect to the predefined SSID
connectWiFi(WIFI_AUTH)
end
end
-- WIFI connection status checking
function wifi_watch()
status = wifi.sta.status()
-- only do something if the status actually changed
if status == wifi.STA_GOTIP and wifiReady == 0 then
wifiReady = 1
print("WiFi: connected with " .. wifi.sta.getip())
LedBlink(400)
--run modules on first start only
if firstPass == 0 then
if TELNET_MODULE == 1 then
load_lib("telnet")
end
if HTTP_MODULE == 1 then
load_lib("http")
end
load_lib("start")
firstPass = 1
end
elseif status == wifi.STA_GOTIP and wifiReady == 1 then
--pass
else
wifiReady = 0
LedFlicker(50, 500, 10)
print("WiFi: (re-)connecting")
end
end
-- Configure
configureWiFi()