local P = {} local m, topic, cid local subscriptions = {} local function mq_client_connected(con) info("mqtt: connected") end local function subscribed() info("mqtt: subscribed") end local function disconnect() info("mqtt: Lost wifi connection, disconnecting") m:close() m = nil end local function on_message(client, topic, message) -- p("mqtt: 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() -- p("mqtt: checking status, status="..status) local status = wifi.sta.getip() if status and status ~= "0.0.0.0" then if not m then info("mqtt: 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) m:on("message", on_message) -- host, port, secure, auto_reconnect, function(client), ssl=8883 m:connect("trygvis.io", 1883, 0, 0, mq_client_connected) end else if m then disconnect() end end end function P.init(timer_id, device_id, client_id) cid = client_id topic = "/diller/"..device_id tmr.alarm(timer_id, 4 * 1000, 1, mq_on_timer) end function P.subscribe(path) local subscription = subscriptions[path] if subscription then info("mqtt: subscription on "..path.." already registered, state="..tostring(subscription.state)) return end info("mqtt: Registering subscription on "..path) subscriptions[path] = true local qos = 0 m:subscribe(topic.."/"..path, qos, subscribed) end function P.publish(path, payload) if not m then info("mqtt: Not connected, dropping message to "..path) return false, 'not connected' end path = topic.."/"..path info("mqtt: path="..path) m:publish(path, payload, 0, 0) return true, 'ok' end return P