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