Post your best Lua script examples here

User avatar
By guido25
#85898 Hello everyone, I'm trying to make a relay work with a public MQTT uploading code with the ESPLORER


conifg.lua



--- MQTT ---
mqtt_broker_ip = "broker.hivemq.com"
mqtt_broker_port = 1883
mqtt_username = ""
mqtt_password = ""
mqtt_client_id = ""

--- WIFI ---
wifi_SSID = "Guido25"
wifi_password = "peluchejacobito"
-- wifi.PHYMODE_B 802.11b, More range, Low Transfer rate, More current draw
-- wifi.PHYMODE_G 802.11g, Medium range, Medium transfer rate, Medium current draw
-- wifi.PHYMODE_N 802.11n, Least range, Fast transfer rate, Least current draw
wifi_signal_mode = wifi.PHYMODE_N

client_ip=""
client_netmask=""
client_gateway=""


main.lua
-- MAPEO PINES
pin0 = 4

polaridad ="HIGH"
-- INICIALIZAR PINES
gpio.mode(pin0,gpio.OUTPUT)


-- TODOS A HIGH
gpio.write(pin0,gpio.HIGH)
function subscribir()
-- SUBSCRIBIR TODOS LOS CANALES
m:subscribe("/Ec/Rele",0, function(conn)
end)

print("Subscrito a el canal")
end



m:on("message", function(conn, topic, data)
print(topic..":")
if data ~= nil then
print(data)
if(topic == "/Ec/Rele") then
if (data == "OFF") then
gpio.write(pin0, gpio.HIGH)
end
if (data == "ON") then
gpio.write(pin0, gpio.LOW)
end
end


connect.lua

dofile('config.lua')
m = mqtt.Client(client_id, 120, username, password)

m:on("offline", function(con)
print ("reconnecting...")
print(node.heap())
tmr.alarm(1, 1000, 1, function()
print("Conectando...")
m:connect(mqtt_broker_ip, mqtt_broker_port)
end)
end)
tmr.alarm(1, 1000, 1, function()
print("Conectando...")
m:connect(mqtt_broker_ip, mqtt_broker_port)
end)
conectado = 0
m:on("connect", function(con)
tmr.stop(1)
print("Connected to MQTT")
print(" IP: ".. mqtt_broker_ip)
print(" Port: ".. mqtt_broker_port)
print(" Client ID: ".. mqtt_client_id)
print(" Username: ".. mqtt_username)
if conectado == 0 then
dofile("main.lua")
subscribir()
else
subscribir()
end
conectado = 1

end)

init.lua
ontador = 20
tmr.alarm(1,1000,1, function()
if contador ~= 0 then
print("Esperando "..contador.." segundos antes de iniciar")
contador = contador-1
else
tmr.stop(1)
end
end)

dofile("config.lua")

--Connect to the wifi network

wifi.setmode(wifi.STATION)
wifi.setphymode(wifi_signal_mode)
wifi.sta.config(wifi_SSID, wifi_password)
wifi.sta.connect()
tmr.alarm(1, 5000, 1, function()
if wifi.sta.getip()== nil then
print('IP unavaiable, waiting...')
else
tmr.stop(1)
print('IP is '..wifi.sta.getip())
dofile('connect.lua')
end
end)