code-lua-iot/mqtt.lua
2024-12-20 13:51:47 +01:00

50 lines
1.1 KiB
Lua

client = mqtt.client("ESP32", "192.168.0.11", 1883, false)
client:connect("","")
nb = 0
net.service.http.start()
console(net.stat(true)[0]["ip"])
function printMaster(length, msg)
console("[MASTER]"..msg)
end
function printAlt(length, msg)
console("[ALT]"..msg)
end
max_temp = 0
min_temp = 100
max_place = ""
min_place = ""
function printBuildingTemp(length, msg)
local temp_str, place = split(msg, ":")
local temp = tonumber(temp_str)
if temp > max_temp then
max_temp = temp
max_place = place
end
if temp < min_temp then
min_temp = temp
min_place = place
end
end
function sendTemp()
s = sensor.attach("DHT22", pio.GPIO21)
tmr.delayms(500)
while true do
client:publish("Building/temp", s:read("temperature")..":Salon", mqtt.QOS0)
tmr.delayms(5000)
end
end
client:subscribe("MASTER", mqtt.QOS0, printMaster)
client:subscribe("ALT", mqtt.QOS0, printAlt)
-- client:publish("MASTER", "Hello, world!", mqtt.QOS0)
-- client:publish("ALT", "Hello, world!", mqtt.QOS0)
temp_sender = thread.start(sendTemp)
client:subscribe("Building/temp", mqtt.QOS0, printBuildingTemp)