From 6d04ada06ce29868338face2fbbec8ab72c48dd2 Mon Sep 17 00:00:00 2001 From: Trygve Laugstøl Date: Thu, 15 Oct 2015 18:34:07 +0200 Subject: wip --- diller/mq.lua | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 53 insertions(+), 5 deletions(-) (limited to 'diller/mq.lua') diff --git a/diller/mq.lua b/diller/mq.lua index 0b4a884..74f3ef8 100644 --- a/diller/mq.lua +++ b/diller/mq.lua @@ -1,12 +1,48 @@ local P = {} local m, topic, cid +local active_subscriptions = {} +local pending_subscriptions = {} +local pending_subcsription local function p(msg) print("MQTT: "..msg) end +-- Subscribe to all registered subscriptions +-- TODO: subscriptions that are not successfull will remain in state = 1. Might not be a real problem if it happens, the server probably disallowed the subscription. +local function create_subscriptions() + print("create_subscriptions, pending count "..table.getn(pending_subscriptions)..", pending: "..tostring(pending_subscription)) + + if (pending_subscription) then + return + end + + pending_subcsription = table.remove(pending_subscriptions) + + -- The API claims that the callback has this signature: function(client, topic, message) + -- but that doesn't seems right from the source code. The code doesn't + -- remember the topics that is being subscribed to. + m:subscribe(pending_subcsription, 0, function(client) + print("success: "..pending_subcsription) + table.insert(active_subscriptions, pending_subscription) + pending_subscription = nil + create_subscriptions() + end) +end + local function mq_client_connected(con) p("connected") + + create_subscriptions() +end + +local function disconnect() + p("Lost wifi connection, disconnecting") + m:close() + m = nil + + -- append active_subscriptions to pending_subscriptions + active_subscriptions = {} end function mq_on_timer() @@ -30,9 +66,7 @@ function mq_on_timer() end else if m then - p("Lost wifi connection, disconnecting") - m:close() - m = nil + disconnect() end end end @@ -45,17 +79,31 @@ function P.init(timer_id, client_id) tmr.alarm(timer_id, 3 * 1000, 1, mq_on_timer) end +function P.subscribe(path, cb) + subscription = subscriptions[path] + if subscription then + print("subscription on "..path.." already registered, state="..tostring(subscription.state)) + return + end + + print("Registering subscription on "..path) + + pending_subscriptions[path] = true + + create_subscriptions() +end + function P.publish(path, payload) if not m then print("Not connected, dropping message to "..path) - return + return false, 'not connected' end path = topic.."/"..path print("path="..path) m:publish(path, payload, 0, 0) - return true, "yo?" + return true, 'ok' end return P -- cgit v1.2.3