From d9da54abcc784ecca5e1c0c415820a32e68c2296 Mon Sep 17 00:00:00 2001 From: Trygve Laugstøl Date: Sun, 11 Oct 2015 14:07:42 +0200 Subject: o Initial import of diller firmware. --- diller/mq.lua | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 diller/mq.lua (limited to 'diller/mq.lua') diff --git a/diller/mq.lua b/diller/mq.lua new file mode 100644 index 0000000..0b4a884 --- /dev/null +++ b/diller/mq.lua @@ -0,0 +1,61 @@ +local P = {} +local m, topic, cid + +local function p(msg) + print("MQTT: "..msg) +end + +local function mq_client_connected(con) + p("connected") +end + +function mq_on_timer() + -- This crashes the module: + -- local status = wifi.sta.status() + -- p("checking status, status="..status) + + local status = wifi.sta.getip() + + if status and status ~= "0.0.0.0" then + if not m then + p("connecting") + + -- client id, keepalive, username, password + m = mqtt.Client(cid, 120) + -- m:on("connect", mq_connected) + m:on("offline", function() m:close(); m = nil end) + + -- host, port, secure, auto_reconnect, function(client), ssl=8883 + m:connect("trygvis.io", 1883, 0, 0, mq_client_connected) + end + else + if m then + p("Lost wifi connection, disconnecting") + m:close() + m = nil + end + end +end + +function P.init(timer_id, client_id) + cid = client_id + + topic = "/esp8266/"..client_id + + tmr.alarm(timer_id, 3 * 1000, 1, mq_on_timer) +end + +function P.publish(path, payload) + if not m then + print("Not connected, dropping message to "..path) + return + end + + path = topic.."/"..path + print("path="..path) + m:publish(path, payload, 0, 0) + + return true, "yo?" +end + +return P -- cgit v1.2.3