Rookie Lua annd nodemcu user need some input on a few questions.
I am setting up some nodemcu units for my "smarthome".
I have read some code and tutorials around the Lua, and have a working mqtt connection that listens to a topic and reacts to the messages.
But i need my node to do several things, one of them is going to controll a steppermotor and a PIR sensor (and maybe a temperaturesensor).
Another node is going to have several buttons , some leds and maybe some encoders.
A third node is going to have temperaturesensor, relay and other komponents.
I have found som code on the forum to make MQTT work, but i am struggeling to expand the codes.
In my example i have found a code (Engeneerd by rutierut, inspired by MikeV) that controlls gpio output. Originaly it listens for the word "ON" and "OFF" on a spesific topic.
If i add an extra "else if input = <command>" i can listen for additional commands from the MQTT.
BUT, is it possible to load a file when a certain MQTT command is received? I want to start the stepper motor when i certain command is received, can i just put the stepper code in a single file and load it from "if input = <command> then <load file.lua>"?
How do i subscribe for additional topics?
How do i add additional buttons to the MQTT Button code in this discussion?
viewtopic.php?f=19&t=2029
-- Engeneerd by rutierut, inspired by MikeV
broker = "192.168.0.100" -- IP or hostname of MQTT broker
mqttport = 1883 -- MQTT port (default 1883)
userID = "" -- username for authentication if required
userPWD = "" -- user password if needed for security
clientID = "ESP1" -- Device ID
GPIO2 = 4 -- IO Index of GPIO2 which is connected to a device
gpio.mode(GPIO2, gpio.OUTPUT)
-- Wifi credentials
wifi.setmode(wifi.STATION)
wifi.sta.config("Rosander","280411050313")
function wifi_connect()
ip = wifi.sta.getip()
if ip ~= nil then
print('Connected, ip is:' .. ip)
tmr.stop(1)
ready = 1
else
ready = 0
end
end
function mqtt_do()
if ready == 1 then
m = mqtt.Client(clientID, 120, userID, userPWD)
m:connect( broker , mqttport, 0,
function(conn)
print("Connected to MQTT:" .. broker .. ":" .. mqttport .." as " .. clientID )
tmr.stop(0)
connected = 1;
sub_mqtt()
m:on('message', function(conn, topic, input)
print(input)
if input == "ON" then
gpio.write(GPIO2, gpio.HIGH)
elseif input == "OFF" then
gpio.write(GPIO2, gpio.LOW)
elseif input == "TEST" then
print('Dette var en test')
else
print('error')
end
end)
end)
end
end
function sub_mqtt()
m:subscribe('testtopic', 0, function(conn)
print('Subscribed')
end)
end
tmr.alarm(0, 1000, 1, function()
mqtt_do()
tmr.delay(1000)
end)
tmr.alarm(1, 1111, 1, function()
wifi_connect()
end)