got it
I think I can spend some more time here, just because lua is so fun...
it will take more than one post to get it done
today will focus on the client,
checkout the code below,
give it a try
then customize it where you find "YOUR CODE HERE"
and have a look to the docs
NodeMCU docscause I copied most of the code from there
the code will be split into four files just to keep different things separated
init.lua
Code: Select all-- init.lua
print("Running")
file.close("init.lua")
dofile("wifi_station.lua")
dofile("application.lua")
credentials.lua
Code: Select all-- credentials.lua
SSID="your-ssid"
PASSWORD="your-password"
wifi_station.lua
Code: Select all-- wifi_station.lua
-- load credentials, 'SSID' and 'PASSWORD' declared and initialize in there
dofile("credentials.lua")
connected_to_AP = false
-- Define WiFi station event callbacks
wifi_connect_event = function(T)
print("Connection to AP("..T.SSID..") established!")
print("Waiting for IP address...")
if disconnect_ct ~= nil then
disconnect_ct = nil
end
end
wifi_got_ip_event = function(T)
print("Wifi connection is ready! IP address is: "..T.IP)
connected_to_AP = true
-- turn on the connection led ...
-- YOUR CODE HERE
end
wifi_disconnect_event = function(T)
if T.reason == wifi.eventmon.reason.ASSOC_LEAVE then
--the station has disassociated from a previously connected AP
return
end
connected_to_AP = false
print("\nWiFi connection to AP("..T.SSID..") has failed!")
-- turn off the connection led ...
-- YOUR CODE HERE
--There are many possible disconnect reasons, the following iterates through
--the list and returns the string corresponding to the disconnect reason.
for key,val in pairs(wifi.eventmon.reason) do
if val == T.reason then
print("Disconnect reason: "..val.."("..key..")")
break
end
end
if disconnect_ct == nil then
disconnect_ct = 1
else
disconnect_ct = disconnect_ct + 1
end
print("Retrying connection...(attempt "..(disconnect_ct+1)..")")
end
-- Register WiFi Station event callbacks
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, wifi_connect_event)
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, wifi_got_ip_event)
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, wifi_disconnect_event)
print("Connecting to WiFi access point...")
wifi.setmode(wifi.STATION)
wifi.sta.config({ssid=SSID, pwd=PASSWORD})
-- wifi.sta.connect() not necessary because config() uses auto-connect=true by default
application.lua
Code: Select all-- application.lua
periodic_task = function()
-- custom application ...
-- YOUR CODE HERE
print("connected to AP "..tostring(connected_to_AP))
tmr.create():alarm(10000, tmr.ALARM_SINGLE, periodic_task)
end
print("now running the application")
print("connected to AP "..tostring(connected_to_AP))
tmr.create():alarm(10000, tmr.ALARM_SINGLE, periodic_task)