--------------------------------- --! @file --! @brief 内部消息API封装 --------------------------------- siganl = require 'posix.signal' syswait = require 'posix.sys.wait' unistd = require 'posix.unistd' mqtt=require "mosquitto" M={...} local func_meta = { __index = M } mqtt.init() --! @brief 模块功能:创建MQTT连接句柄,自动维护连接,采用回调函数方式接收消息,相关接口mqtt_send --! @param addr: broker address --! @param port: broker port ,默认1883 --! @param usr: broker usr --! @param pwd: broker pwd --! @param subscribe: 订阅topic的数组,数组里面是字符串 --! @param cb: 收到的mqtt消息,回调函数 --! @remarks --! @code --! client = internal_api.mqtt_session("localhost",1883,nil,nil,{"topic1","topic2"}) --! local function callback(topic,payload) print(topic,payload) end --! client = internal_api.mqtt_session("localhost",1883,nil,nil,{"topic1","topic2"},callback) --! @endcode --! @return --! @retval port:设备port,string类型 function M:publish(topic,payload) return self.client:publish(topic,payload) end return setmetatable({client_instance = {},}, { __call = function(self,addr, port, usr, pwd, subscribe, cb,connect_cb,disconnect_cb) local instance = setmetatable({ count = 0, client = mqtt.new(), addr = addr, port = port, usr = usr, pwd = pwd, subscribe = subscribe, cb = cb, connect_cb = connect_cb, disconnect_cb = disconnect_cb, }, func_meta) self.client_instance = instance log.info(nil,instance) log.info(nil,instance.client) local others_topic = {} function init(self) for _,v in pairs(self.subscribe) do if type(v) == "string" then table.insert( others_topic,v) end end self.client.ON_CONNECT = function() log.warn("mqtt","client connected") for _,v in pairs(others_topic) do if type(v) == "string" then self.client:subscribe(v) end end if connect_cb then connect_cb() end end self.client.ON_MESSAGE = function(mid, topic, payload) cb(topic,payload) end self.client.ON_DISCONNECT = function() log.warn("mqtt","client disconnected") if disconnect_cb then disconnect_cb() end end if usr and pwd then self.client:login_set(usr,pwd) end self.client:connect(addr,port) table.insert(sys.poll_socket,function() msg={} msg.id = rtos.MSG_SOCK_RECV_IND self.client:loop(50,1) return msg end) sys.taskInit(function() while(true) do while self.client:socket() do sys.wait(2000) end sys.wait(1000) self.client:reconnect() end end) end init(instance) return instance end })