-- mqtt.lua local M = {} -- public interface function M:on_connect(client, topic, message) self.connected = true end function M:on_offline(client, topic, message) self.connected = false end function M:on_message(client, topic, message) end function M:on_newconnection() end function M:subscribe(topic, qos) self.subscriptions[topic] = qos self.attempt_subscribes() end function attmpet_subscribes() local uv_topic, uv_qos = next(self.subscriptions, nil) -- more upvals local function subscribe_cb(client) print("subscribed to topic", uv_topic) uv_topic, uv_qos = next(uv_topics, uv_topic) if uv_topic ~= nil and uv_qos ~= nil then client:subscribe(uv_topic, uv_qos, subscribe_cb) else uv_cb(client) end end client:subscribe(uv_topic, uv_qos, subscribe_cb) end function M:connect(host, port) self.m:connect(host, port, 0, function(client) self.connected = true self.on_newconnection() end, function(client, reason) print("mqtt "..name.." failed to connect: "..reason) tmr.create():alarm(10*1000, tmr.ALARM_SINGLE, self.connect(host, port)) end ) end setmetatable( M, { __call = function (cls, name) local self = setmetatable({}, MyClass) self.m = mqtt.Client(name, 120) self.name = name self.connected = false self.m:on("connect", M.on_connect) self.m:on("offline", M.on_offline) self.m:on("message", M.on_message) return self end, }) oskar_m:lwt("/lwt", "offline", 0, 0) oskar_m:on("connect", function(client) print ("connected") end) oskar_m:on("offline", function(client) print ("offline") end) oskar_topicsub = { } oskar_topichandle = { status=(function (client, topic, message) print("Handle status") end), } oskar_m:on("message", function(client, topic, data) print("MQTT: msg recieved: "..topic) if data ~= nil then print(data) end oskar_topichandle[topic](client,topic,message) end) -- for TLS: m:connect("192.168.11.118", secure-port, 1) oskar_m:connect("172.105.7.171", 1883, 0, function(client) print("connected") -- Calling subscribe/publish only makes sense once the connection -- was successfully established. You can do that either here in the -- 'connect' callback or you need to otherwise make sure the -- connection was established (e.g. tracking connection status or in -- m:on("connect", function)). -- subscribe topic with qos = 0 client:subscribe("/topic", 0, function(client) print("subscribe success") end) -- publish a message with data = hello, QoS = 0, retain = 0 client:publish("/topic", "hello", 0, 0, function(client) print("sent") end) end, function(client, reason) print("failed reason: " .. reason) end) return M