From b36b6c7528fe443de9278802d0022e696727486b Mon Sep 17 00:00:00 2001 From: Trygve Laugstøl Date: Sat, 24 Oct 2015 22:55:27 +0200 Subject: o Subscribing to property/../{name,description} and notifying on changes. --- diller/mq.lua | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/diller/mq.lua b/diller/mq.lua index 212d964..66927e2 100644 --- a/diller/mq.lua +++ b/diller/mq.lua @@ -3,19 +3,38 @@ local m, topic, cid local subscriptions = {} local function p(msg) - print("MQTT: "..msg) + print("# MQTT: "..msg) end local function mq_client_connected(con) p("connected") end +local function subscribed() + p("subscribed") +end + local function disconnect() p("Lost wifi connection, disconnecting") m:close() m = nil end +local function on_message(client, topic, message) + -- p("on_message: topic="..topic..", message="..message) + + local _, _, new_property_name = string.find(topic, '/property/([%a%d-]+)/name$') + if new_property_name then + print("msg cmd=new-property-name id="..new_property_name..", name="..message) + return; + end + + local _, _, new_description_name = string.find(topic, '/property/([%a%d-]+)/description$') + if new_description_name then + print("msg cmd=new-property-description id="..new_description_name..", description="..message) + end +end + function mq_on_timer() -- This crashes the module: -- local status = wifi.sta.status() @@ -31,6 +50,7 @@ function mq_on_timer() m = mqtt.Client(cid, 120) -- m:on("connect", mq_connected) m:on("offline", function() m:close(); m = nil end) + m:on("message", on_message) -- host, port, secure, auto_reconnect, function(client), ssl=8883 m:connect("trygvis.io", 1883, 0, 0, mq_client_connected) @@ -50,7 +70,7 @@ function P.init(timer_id, device_id, client_id) tmr.alarm(timer_id, 4 * 1000, 1, mq_on_timer) end -function P.subscribe(path, cb) +function P.subscribe(path) local subscription = subscriptions[path] if subscription then print("subscription on "..path.." already registered, state="..tostring(subscription.state)) @@ -60,9 +80,9 @@ function P.subscribe(path, cb) print("Registering subscription on "..path) subscriptions[path] = true - -- pending_subscriptions[path] = true - -- create_subscriptions() + local qos = 0 + m:subscribe(topic.."/"..path, qos, subscribed) end function P.publish(path, payload) -- cgit v1.2.3