Wordclock/mqtt.lua

77 lines
2.4 KiB
Lua
Raw Normal View History

-- Global variable
2021-01-14 21:27:13 +01:00
m=nil
mqttConnected = false
2020-12-07 21:26:02 +01:00
-- MQTT extension
2021-01-14 21:27:13 +01:00
function registerMqtt()
2020-12-07 21:26:02 +01:00
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)
2021-01-14 22:14:59 +01:00
elseif (data:sub(1,1) == "#" and data:len() == 7) then
red = tonumber(data:sub(2,3), 16)
green = tonumber(data:sub(4,5), 16)
blue = tonumber(data:sub(6,7), 16)
colorBg=string.char(red, green, blue)
print("Updated BG: " .. tostring(red) .. "," .. tostring(green) .. "," .. tostring(blue) )
if (displayTime~= nil) then
displayTime()
end
2020-12-07 21:26:02 +01:00
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)
2021-01-14 22:14:59 +01:00
else
print "Unknown MQTT command"
2020-12-07 21:26:02 +01:00
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)
2021-01-14 21:27:13 +01:00
tmr.alarm(3, 500, 0, function()
-- publish a message with data = hello, QoS = 0, retain = 0
client:publish(mqttPrefix .. "/ip", tostring(wifi.sta.getip()), 0, 0)
end)
2020-12-07 21:26:02 +01:00
end,
function(client, reason)
print("failed reason: " .. reason)
2021-01-14 21:32:12 +01:00
mqttConnected = false
2020-12-07 21:26:02 +01:00
end)
end
2021-01-14 21:51:29 +01:00
function startMqttClient()
2020-12-08 21:51:14 +01:00
if (mqttServer ~= nil and mqttPrefix ~= nil) then
2021-01-14 21:27:13 +01:00
registerMqtt()
2020-12-08 21:51:14 +01:00
print "Started MQTT client"
oldBrightness=0
oldTemp=0
2020-12-10 21:11:35 +01:00
tmr.alarm(5, 5001, 1 ,function()
if (mqttConnected) then
local temp = nil
if (t ~= nil) then
temp=readTemp()
end
if (oldBrightness ~= briPercent) then
m:publish(mqttPrefix .. "/brightness", tostring(briPercent), 0, 0)
else
m:publish(mqttPrefix .. "/heap", tostring(node.heap()), 0, 0)
end
oldBrightness = briPercent
2020-12-08 21:51:14 +01:00
end
end)
end
2020-12-10 21:11:35 +01:00
end