local P = {} local m, topic, cid, connected local subscriptions = {} local function mq_client_connected(con) info("mqtt: connected") connected = true end local function subscribed() info("mqtt: subscribed") end local function offline() info("mqtt: disconnected") connected = false -- m:close() -- m = nil end local function on_message(client, topic, message) -- p("mqtt: on_message: topic="..topic..", message="..message) local _, _, key = string.find(topic, '/property/([%a%d-]+)/name$') if key then local filename = 'property-'..key..'-name' local old = read_cfg(filename, false) if old ~= message then write_cfg(filename, message) end print("msg cmd=new-property-name key="..key..", name=\""..message.."\"") end local _, _, key = string.find(topic, '/property/([%a%d-]+)/description$') if key then local filename = 'property-'..key..'-description' local old = read_cfg(filename, false) if old ~= message then write_cfg(filename, message) end print("msg cmd=new-property-description key="..key..", description=\""..message.."\"") end end function mq_on_timer() -- This crashes the module: -- local status = wifi.sta.status() -- p("mqtt: checking status, status="..status) info("mqtt: connecting") -- client id, keepalive, username, password m = mqtt.Client(cid, 120) -- m:on("connect", mq_connected) m:on("offline", offline) m:on("message", on_message) -- host, port, secure, auto_reconnect, function(client), ssl=8883 m:connect("trygvis.io", 1883, 0, 1, mq_client_connected) end function P.init(timer_id, device_id, client_id) cid = client_id topic = "/diller/"..device_id -- Wait a bit to get a connection first tmr.alarm(timer_id, 5 * 1000, 0, 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 function P.status() if connected then return 'connected' else return 'disconnected' end end return P