Wordclock/mqtt.lua

48 lines
1.4 KiB
Lua
Raw Normal View History

2020-12-07 21:26:02 +01:00
-- MQTT extension
function startMqtt()
m = mqtt.Client("wordclock", 120)
-- on publish message receive event
m:on("message", function(client, topic, data)
print(topic .. ":" )
if data ~= nil then
print(data)
if (data == "ON") then
2020-12-07 21:37:04 +01:00
briPercent=100
2020-12-07 21:26:02 +01:00
m:publish(mqttPrefix .. "/clock", "ON", 0, 0)
elseif (data == "OFF") then
2020-12-07 21:37:04 +01:00
briPercent=0
2020-12-07 21:26:02 +01:00
m:publish(mqttPrefix .. "/clock", "OFF", 0, 0)
else
if (tonumber(data) >= 0 and tonumber(data) <= 100) then
2020-12-07 21:37:04 +01:00
briPercent=tonumber(data)
2020-12-07 21:26:02 +01:00
m:publish(mqttPrefix .. "/clock", tostring(data), 0, 0)
end
end
end
end)
m:connect(mqttServer, 1883, 0, function(client)
2020-12-07 21:37:04 +01:00
print("MQTT is connected")
2020-12-07 21:26:02 +01:00
mqttConnected = true
-- subscribe topic with qos = 0
client:subscribe(mqttPrefix .. "/command", 0)
-- publish a message with data = hello, QoS = 0, retain = 0
client:publish(mqttPrefix .. "/ip", tostring(wifi.sta.getip()), 0, 0)
end,
function(client, reason)
print("failed reason: " .. reason)
end)
end
if (mqttServer ~= nil and mqttPrefix ~= nil) then
startMqtt()
print "Started MQTT client"
2020-12-08 20:30:43 +01:00
oldBrightness=0
tmr.alarm(5, 10000, 1 ,function()
2020-12-08 20:45:18 +01:00
if (oldBrightness ~= briPercent) then
2020-12-07 21:26:02 +01:00
m:publish(mqttPrefix .. "/brightness", tostring(briPercent), 0, 0)
2020-12-08 20:30:43 +01:00
end
oldBrightness = briPercent
2020-12-07 21:26:02 +01:00
end)
2020-12-08 20:30:43 +01:00
end