From 8858fa19bd971738709ce411d641bdf49c511ab2 Mon Sep 17 00:00:00 2001 From: Ollo Date: Mon, 7 Dec 2020 21:26:02 +0100 Subject: [PATCH] Added MQTT module --- main.lua | 4 ++-- mqtt.lua | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 mqtt.lua diff --git a/main.lua b/main.lua index 51e3e0e..1260ff7 100644 --- a/main.lua +++ b/main.lua @@ -42,6 +42,7 @@ function syncTimeFromInternet() end ) end + briPercent = 50 function displayTime() local sec, usec = rtctime.get() @@ -146,7 +147,7 @@ function normalOperation() print('IP: ',wifi.sta.getip()) -- Here the WLAN is found, and something is done print("Solving dependencies") - local dependModules = { "timecore" , "wordclock", "telnet" } + local dependModules = { "timecore" , "wordclock", "telnet", "mqtt" } for _,mod in pairs(dependModules) do print("Loading " .. mod) mydofile(mod) @@ -154,7 +155,6 @@ function normalOperation() tmr.alarm(2, 500, 0 ,function() syncTimeFromInternet() - displayTime() end) tmr.alarm(3, 2000, 0 ,function() if (startTelnetServer ~= nil) then diff --git a/mqtt.lua b/mqtt.lua new file mode 100644 index 0000000..845a6eb --- /dev/null +++ b/mqtt.lua @@ -0,0 +1,44 @@ +-- 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 + mqttBrightness=100 + m:publish(mqttPrefix .. "/clock", "ON", 0, 0) + elseif (data == "OFF") then + mqttBrightness=0 + m:publish(mqttPrefix .. "/clock", "OFF", 0, 0) + else + if (tonumber(data) >= 0 and tonumber(data) <= 100) then + mqttBrightness=tonumber(data) + m:publish(mqttPrefix .. "/clock", tostring(data), 0, 0) + end + end + end + end) + + m:connect(mqttServer, 1883, 0, function(client) + print("[MQTT] connected") + 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" + + tmr.alarm(5, 60000, 1 ,function() + m:publish(mqttPrefix .. "/brightness", tostring(briPercent), 0, 0) + end) +end \ No newline at end of file