Mqtt Commissioning
Jump to navigation
Jump to search
Lua Code
| file | lua code | Notes |
|---|---|---|
| config.lua | wifi.setmode(wifi.STATION)
wifi.sta.config("YOUR-SSID","YOUR-PASSWORD")
wifi.sta.connect()
MqttBroker = 'YOUR-MQTTBORKER'
|
setup file, connects the esp to the router |
| init.lua
(part 1) |
print("\n\nHold gpio0 low to stop boot")
tmr.delay(1000000)
if gpio.read(3) == 0 then print("...boot stopped") return end
print("...booting", collectgarbage('count'))
print('ready',collectgarbage('count'))
dofile('config.lc')
|
Startup code that allows stopping the boot by holding GPIO0 low. |
| init.lua
(part 2) |
-- restart if stall
tmr.softwd(30)
tmr.softwd(30) -- restart if stall
action = function()
print("Mqtt try connect")
if m then m:close() m=nil collectgarbage() end
m = mqtt.Client("clientid",-1)
--m:lwt("/node/lwt/"..wifi.ap.getmac(), ''..rtctime.get(),0,1)
m:on("offline", function(con) print("Mqtt offline") end)
m:on("message", function(conn, topic, data) tmr.softwd(30) print('Mqtt "' .. topic .. '":' ) if data ~= nil then print(data) node.input(data) end end)
m:connect(MqttBroker, 1883, 0, function(conn)
print("Mqtt Connected")
m:subscribe("/node/config/"..wifi.ap.getmac(), 0, function(conn) tmr.softwd(30) print("Mqtt subscribes") end)
m:publish("/node/heartbeat/"..wifi.ap.getmac(),''..rtctime.get(),0,1, function(conn) print("Mqtt heartbeat sent") end)
end)
end
try_sntp_sync = function()
print('Try sntp.sync ...')
sntp.sync('www.ntp.org', function(sec,usec,server) print('sntp.sync', sec, usec, server) end, function() print('Error: sntp.sync !') end)
end
tmr.alarm(0, 2000, tmr.ALARM_SEMI, function()
if rtctime.get()==0 then try_sntp_sync() tmr.start(0)
else action() end
end)
|
|
Commissioning
Commissioning is currently done from a Linux command line using mosquitto mqtt client. The -t option defines the topic to subscribe to. The '#' in the topic is a wildcard.
mosquitto_sub -t "/node/heartbeat/#" -v
The response lists nodes that were ever booted up and their boot time in in Unix Epoch Time. In this example one node with MAC 1a:fe:34:a0:e0:4d was booted at 1456378653 Epoch Time:
/node/heartbeat/1a:fe:34:a0:e0:4d 1456378653
Now having the MAC we can commission the device by sending lua code to the '/node/config' topic for the given MAC:
mosquitto_pub -t "/node/config/1a:fe:34:a0:e0:4d" -r -m "pin=7 gpio.mode(pin, gpio.OUTPUT) local b=0 tmr.alarm(0, 500, 1, function() gpio.write(pin, b) if b==0 then b=1 else b=0 end end)"
The lua code uses a timer to toggle and LED every half a second:
pin=7
gpio.mode(pin, gpio.OUTPUT)
local b=0
tmr.alarm(0, 500, 1, function()
gpio.write(pin, b)
if b==0 then b=1
else b=0 end
end)