mqtt.lua 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. --- 模块功能:MQTT客户端
  2. -- @module mqtt
  3. -- @author openLuat
  4. -- @license MIT
  5. -- @copyright openLuat
  6. -- @release 2017.10.24
  7. local mqtt = {}
  8. -- MQTT 指令id
  9. local CONNECT, CONNACK, PUBLISH, PUBACK, PUBREC, PUBREL, PUBCOMP, SUBSCRIBE, SUBACK, UNSUBSCRIBE, UNSUBACK, PINGREQ, PINGRESP, DISCONNECT = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
  10. local CLIENT_COMMAND_TIMEOUT = 60000
  11. local sys = _G.sys
  12. local pack = _G.pack
  13. local string = _G.string
  14. local encodeLen = mqttcore.encodeLen
  15. -- local function encodeLen(len)
  16. -- local s = ""
  17. -- local digit
  18. -- repeat
  19. -- digit = len % 128
  20. -- len = (len - digit) / 128
  21. -- if len > 0 then
  22. -- --digit = bit.bor(digit, 0x80)
  23. -- digit = digit | 0x80
  24. -- end
  25. -- s = s .. string.char(digit)
  26. -- until (len <= 0)
  27. -- return s
  28. -- end
  29. local function encodeUTF8(s)
  30. if not s or #s == 0 then
  31. return ""
  32. else
  33. return pack.pack(">P", s)
  34. end
  35. end
  36. local function packCONNECT(clientId, keepAlive, username, password, cleanSession, will, version)
  37. local content = pack.pack(">PbbHPAAAA",
  38. version == "3.1" and "MQIsdp" or "MQTT",
  39. version == "3.1" and 3 or 4,
  40. (#username == 0 and 0 or 1) * 128 + (#password == 0 and 0 or 1) * 64 + will.retain * 32 + will.qos * 8 + will.flag * 4 + cleanSession * 2,
  41. keepAlive,
  42. clientId,
  43. encodeUTF8(will.topic),
  44. encodeUTF8(will.payload),
  45. encodeUTF8(username),
  46. encodeUTF8(password))
  47. return pack.pack(">bAA",
  48. CONNECT * 16,
  49. encodeLen(string.len(content)),
  50. content)
  51. end
  52. local function packSUBSCRIBE(dup, packetId, topics)
  53. local header = SUBSCRIBE * 16 + dup * 8 + 2
  54. local data = pack.pack(">H", packetId)
  55. for topic, qos in pairs(topics) do
  56. data = data .. pack.pack(">Pb", topic, qos)
  57. end
  58. return pack.pack(">bAA", header, encodeLen(#data), data)
  59. end
  60. local function packUNSUBSCRIBE(dup, packetId, topics)
  61. local header = UNSUBSCRIBE * 16 + dup * 8 + 2
  62. local data = pack.pack(">H", packetId)
  63. for k, topic in pairs(topics) do
  64. data = data .. pack.pack(">P", topic)
  65. end
  66. return pack.pack(">bAA", header, encodeLen(#data), data)
  67. end
  68. local function packPUBLISH(dup, qos, retain, packetId, topic, payload)
  69. local header = PUBLISH * 16 + dup * 8 + qos * 2 + retain
  70. local len = 2 + #topic + #payload
  71. if qos > 0 then
  72. return pack.pack(">bAPHA", header, encodeLen(len + 2), topic, packetId, payload)
  73. else
  74. return pack.pack(">bAPA", header, encodeLen(len), topic, payload)
  75. end
  76. end
  77. local function packACK(id, dup, packetId)
  78. return pack.pack(">bbH", id * 16 + dup * 8 + (id == PUBREL and 1 or 0) * 2, 0x02, packetId)
  79. end
  80. local function packZeroData(id, dup, qos, retain)
  81. dup = dup or 0
  82. qos = qos or 0
  83. retain = retain or 0
  84. return pack.pack(">bb", id * 16 + dup * 8 + qos * 2 + retain, 0)
  85. end
  86. local function unpack(s)
  87. if #s < 2 then return end
  88. log.debug("mqtt.unpack", #s, string.toHex(string.sub(s, 1, 50)))
  89. -- read remaining length
  90. local len = 0
  91. local multiplier = 1
  92. local pos = 2
  93. repeat
  94. if pos > #s then return end
  95. local digit = string.byte(s, pos)
  96. len = len + ((digit % 128) * multiplier)
  97. multiplier = multiplier * 128
  98. pos = pos + 1
  99. until digit < 128
  100. if #s < len + pos - 1 then return end
  101. local header = string.byte(s, 1)
  102. --local packet = {id = (header - (header % 16)) / 16, dup = ((header % 16) - ((header % 16) % 8)) / 8, qos = bit.band(header, 0x06) / 2, retain = bit.band(header, 0x01)}
  103. local packet = {id = (header - (header % 16)) / 16, dup = ((header % 16) - ((header % 16) % 8)) / 8, qos = (header & 0x06) / 2, retain = (header & 0x01)}
  104. local nextpos
  105. if packet.id == CONNACK then
  106. nextpos, packet.ackFlag, packet.rc = pack.unpack(s, "bb", pos)
  107. elseif packet.id == PUBLISH then
  108. nextpos, packet.topic = pack.unpack(s, ">P", pos)
  109. if packet.qos > 0 then
  110. nextpos, packet.packetId = pack.unpack(s, ">H", nextpos)
  111. end
  112. packet.payload = string.sub(s, nextpos, pos + len - 1)
  113. elseif packet.id ~= PINGRESP then
  114. if len >= 2 then
  115. nextpos, packet.packetId = pack.unpack(s, ">H", pos)
  116. else
  117. packet.packetId = 0
  118. end
  119. end
  120. return packet, pos + len
  121. end
  122. local mqttc = {}
  123. mqttc.__index = mqttc
  124. --- 创建一个mqtt client实例
  125. -- @string clientId
  126. -- @number[opt=300] keepAlive 心跳间隔(单位为秒),默认300秒
  127. -- @string[opt=""] username 用户名,用户名为空配置为""或者nil
  128. -- @string[opt=""] password 密码,密码为空配置为""或者nil
  129. -- @number[opt=1] cleanSession 1/0
  130. -- @table[opt=nil] will 遗嘱参数,格式为{qos=, retain=, topic=, payload=}
  131. -- @string[opt="3.1.1"] version MQTT版本号
  132. -- @return table mqttc client实例
  133. -- @usage
  134. -- mqttc = mqtt.client("clientid-123")
  135. -- mqttc = mqtt.client("clientid-123",200)
  136. -- mqttc = mqtt.client("clientid-123",nil,"user","password")
  137. -- mqttc = mqtt.client("clientid-123",nil,"user","password",nil,nil,"3.1")
  138. function mqtt.client(clientId, keepAlive, username, password, cleanSession, will, version)
  139. local o = {}
  140. local packetId = 1
  141. if will then
  142. will.flag = 1
  143. else
  144. will = {flag = 0, qos = 0, retain = 0, topic = "", payload = ""}
  145. end
  146. o.clientId = clientId
  147. o.keepAlive = keepAlive or 300
  148. o.username = username or ""
  149. o.password = password or ""
  150. o.cleanSession = cleanSession or 1
  151. o.version = version or "3.1.1"
  152. o.will = will
  153. o.commandTimeout = CLIENT_COMMAND_TIMEOUT
  154. o.cache = {}-- 接收到的mqtt数据包缓冲
  155. o.inbuf = "" -- 未完成的数据缓冲
  156. o.connected = false
  157. o.getNextPacketId = function()
  158. packetId = packetId == 65535 and 1 or (packetId + 1)
  159. return packetId
  160. end
  161. o.lastOTime = 0
  162. setmetatable(o, mqttc)
  163. return o
  164. end
  165. -- 检测是否需要发送心跳包
  166. function mqttc:checkKeepAlive()
  167. if self.keepAlive == 0 then return true end
  168. if os.time() - self.lastOTime >= self.keepAlive then
  169. if not self:write(packZeroData(PINGREQ)) then
  170. log.info("mqtt.client:", "pingreq send fail")
  171. return false
  172. end
  173. end
  174. return true
  175. end
  176. -- 发送mqtt数据
  177. function mqttc:write(data)
  178. log.debug("mqtt.client:write", string.toHex(string.sub(data, 1, 50)))
  179. local r = self.io:send(data)
  180. if r then self.lastOTime = os.time() end
  181. return r
  182. end
  183. -- 接收mqtt数据包
  184. function mqttc:read(timeout, msg, msgNoResume)
  185. if not self:checkKeepAlive() then
  186. log.warn("mqtt.read checkKeepAlive fail")
  187. return false
  188. end
  189. local topic = "MQTTC_PKG_" .. tostring(self.io:id())
  190. local result, data = sys.waitUntil(topic, timeout)
  191. --log.info("mqtt.read", result, data)
  192. if result then -- 收到topic消息
  193. return true, data
  194. else
  195. if self.io:closed() == 1 then
  196. return false
  197. else
  198. return false, "timeout"
  199. end
  200. end
  201. end
  202. local function update_resp(_self, data)
  203. if #data > 0 then
  204. if #_self.inbuf > 0 then
  205. _self.inbuf = _self.inbuf .. data
  206. else
  207. _self.inbuf = data
  208. end
  209. end
  210. --log.debug("mqttc", "data recv to unpack", _self.inbuf:toHex())
  211. local packet, nextpos = unpack(_self.inbuf)
  212. if packet then
  213. log.info("mqttc", "msg unpack ok", packet.id)
  214. _self.inbuf = string.sub(_self.inbuf, nextpos)
  215. sys.publish("MQTTC_PKG_" .. tostring(_self.io:id()), packet)
  216. if #_self.inbuf > 0 then
  217. update_resp(_self, "")
  218. end
  219. else
  220. log.info("mqttc", "data not full")
  221. end
  222. return true
  223. end
  224. -- 等待接收指定的mqtt消息
  225. function mqttc:waitfor(id, timeout, msg, msgNoResume)
  226. for index, packet in ipairs(self.cache) do
  227. if packet.id == id then
  228. return true, table.remove(self.cache, index)
  229. end
  230. end
  231. while true do
  232. local insertCache = true
  233. local r, data, param = self:read(timeout, msg, msgNoResume)
  234. if r then
  235. if data.id == PUBLISH then
  236. if data.qos > 0 then
  237. if not self:write(packACK(data.qos == 1 and PUBACK or PUBREC, 0, data.packetId)) then
  238. log.info("mqtt.client:waitfor", "send publish ack failed", data.qos)
  239. return false
  240. end
  241. end
  242. elseif data.id == PUBREC or data.id == PUBREL then
  243. if not self:write(packACK(data.id == PUBREC and PUBREL or PUBCOMP, 0, data.packetId)) then
  244. log.info("mqtt.client:waitfor", "send ack fail", data.id == PUBREC and "PUBREC" or "PUBCOMP")
  245. return false
  246. end
  247. insertCache = false
  248. end
  249. if data.id == id then
  250. return true, data
  251. end
  252. if insertCache then table.insert(self.cache, data) end
  253. else
  254. return false, data, param
  255. end
  256. end
  257. end
  258. --- 连接mqtt服务器
  259. -- @string host 服务器地址
  260. -- @param port string或者number类型,服务器端口
  261. -- @string[opt="tcp"] transport "tcp"或者"tcp_ssl"
  262. -- @table[opt=nil] cert,table或者nil类型,ssl证书,当transport为"tcp_ssl"时,此参数才有意义。cert格式如下:
  263. -- {
  264. -- caCert = "ca.crt", --CA证书文件(Base64编码 X.509格式),如果存在此参数,则表示客户端会对服务器的证书进行校验;不存在则不校验
  265. -- clientCert = "client.crt", --客户端证书文件(Base64编码 X.509格式),服务器对客户端的证书进行校验时会用到此参数
  266. -- clientKey = "client.key", --客户端私钥文件(Base64编码 X.509格式)
  267. -- clientPassword = "123456", --客户端证书文件密码[可选]
  268. -- }
  269. -- @number timeout, 链接服务器最长超时时间
  270. -- @return result true表示成功,false或者nil表示失败
  271. -- @usage mqttc = mqtt.client("clientid-123", nil, nil, false); mqttc:connect("mqttserver.com", 1883, "tcp", 5)
  272. function mqttc:connect(host, port, transport, cert, timeout)
  273. if self.connected then
  274. log.info("mqtt.client:connect", "has connected")
  275. return false
  276. end
  277. if self.io then
  278. self.io:close()
  279. self.io = nil
  280. end
  281. if transport and transport ~= "tcp" and transport ~= "tcp_ssl" then
  282. log.info("mqtt.client:connect", "invalid transport", transport)
  283. return false
  284. end
  285. self.io = socket.tcp(transport == "tcp_ssl" or type(cert) == "table", cert)
  286. self.io:host(host)
  287. self.io:port(port)
  288. local connect_topic = "NETC_CONNECT_" .. tostring(self.io:id())
  289. self.io:on("connect", function(id, re)
  290. log.info("mqtt", "connect result", re)
  291. sys.publish(connect_topic, re == 0)
  292. if not re then
  293. self.io:clean()
  294. self.io:close()
  295. end
  296. end)
  297. self.io:on("recv", function(id, data)
  298. if not update_resp(self, data) then
  299. log.info("mqtt", "close connect for bad data")
  300. self.io:clean()
  301. self.io:close()
  302. end
  303. end)
  304. if not self.io:start() then
  305. self.io:clean()
  306. self.io:close()
  307. log.info("mqtt", "fail to start socket thread")
  308. return false
  309. end
  310. --log.info("mqtt", "wait for connect")
  311. local result, linked = sys.waitUntil(connect_topic, 15000)
  312. if not result then
  313. log.info("mqtt", "connect timeout")
  314. return false
  315. end
  316. if not linked or self.io:closed() == 1 then
  317. log.info("mqtt", "connect fail")
  318. return false
  319. end
  320. --log.info("mqtt", "send packCONNECT")
  321. if not self:write(packCONNECT(self.clientId, self.keepAlive, self.username, self.password, self.cleanSession, self.will, self.version)) then
  322. log.info("mqtt.client:connect", "send fail")
  323. return false
  324. end
  325. --log.info("mqtt", "waitfor CONNACK")
  326. local r, packet = self:waitfor(CONNACK, self.commandTimeout, nil, true)
  327. if not r or packet.rc ~= 0 then
  328. log.info("mqtt.client:connect", "connack error", r and packet.rc or -1)
  329. return false
  330. end
  331. self.connected = true
  332. --log.info("mqtt", "connected!~!")
  333. return true
  334. end
  335. --- 订阅主题
  336. -- @param topic,string或者table类型,一个主题时为string类型,多个主题时为table类型,主题内容为UTF8编码
  337. -- @param[opt=0] qos,number或者nil,topic为一个主题时,qos为number类型(0/1/2,默认0);topic为多个主题时,qos为nil
  338. -- @return bool true表示成功,false或者nil表示失败
  339. -- @usage
  340. -- mqttc:subscribe("/abc", 0) -- subscribe topic "/abc" with qos = 0
  341. -- mqttc:subscribe({["/topic1"] = 0, ["/topic2"] = 1, ["/topic3"] = 2}) -- subscribe multi topic
  342. function mqttc:subscribe(topic, qos)
  343. if not self.connected then
  344. log.info("mqtt.client:subscribe", "not connected")
  345. return false
  346. end
  347. local topics
  348. if type(topic) == "string" then
  349. topics = {[topic] = qos and qos or 0}
  350. else
  351. topics = topic
  352. end
  353. if not self:write(packSUBSCRIBE(0, self.getNextPacketId(), topics)) then
  354. log.info("mqtt.client:subscribe", "send failed")
  355. return false
  356. end
  357. if not self:waitfor(SUBACK, self.commandTimeout, nil, true) then
  358. log.info("mqtt.client:subscribe", "wait ack failed")
  359. return false
  360. end
  361. return true
  362. end
  363. --- 取消订阅主题
  364. -- @param topic,string或者table类型,一个主题时为string类型,多个主题时为table类型,主题内容为UTF8编码
  365. -- @return bool true表示成功,false或者nil表示失败
  366. -- @usage
  367. -- mqttc:unsubscribe("/abc") -- unsubscribe topic "/abc"
  368. -- mqttc:unsubscribe({"/topic1", "/topic2", "/topic3"}) -- unsubscribe multi topic
  369. function mqttc:unsubscribe(topic)
  370. if not self.connected then
  371. log.info("mqtt.client:unsubscribe", "not connected")
  372. return false
  373. end
  374. local topics
  375. if type(topic) == "string" then
  376. topics = {topic}
  377. else
  378. topics = topic
  379. end
  380. if not self:write(packUNSUBSCRIBE(0, self.getNextPacketId(), topics)) then
  381. log.info("mqtt.client:unsubscribe", "send failed")
  382. return false
  383. end
  384. if not self:waitfor(UNSUBACK, self.commandTimeout, nil, true) then
  385. log.info("mqtt.client:unsubscribe", "wait ack failed")
  386. return false
  387. end
  388. return true
  389. end
  390. --- 发布一条消息
  391. -- @string topic UTF8编码的字符串
  392. -- @string payload 用户自己控制payload的编码,mqtt.lua不会对payload做任何编码转换
  393. -- @number[opt=0] qos 0/1/2, default 0
  394. -- @number[opt=0] retain 0或者1
  395. -- @return bool 发布成功返回true,失败返回false
  396. -- @usage
  397. -- mqttc = mqtt.client("clientid-123", nil, nil, false)
  398. -- mqttc:connect("mqttserver.com", 1883, "tcp")
  399. -- mqttc:publish("/topic", "publish from luat mqtt client", 0)
  400. function mqttc:publish(topic, payload, qos, retain)
  401. if not self.connected then
  402. log.info("mqtt.client:publish", "not connected")
  403. return false
  404. end
  405. qos = qos or 0
  406. retain = retain or 0
  407. if not self:write(packPUBLISH(0, qos, retain, qos > 0 and self.getNextPacketId() or 0, topic, payload)) then
  408. log.info("mqtt.client:publish", "socket send failed")
  409. return false
  410. end
  411. if qos == 0 then return true end
  412. if not self:waitfor(qos == 1 and PUBACK or PUBCOMP, self.commandTimeout, nil, true) then
  413. log.warn("mqtt.client:publish", "wait ack timeout")
  414. return false
  415. end
  416. return true
  417. end
  418. --- 接收消息
  419. -- @number timeout 接收超时时间,单位毫秒
  420. -- @string[opt=nil] msg 可选参数,控制socket所在的线程退出recv阻塞状态
  421. -- @return result 数据接收结果,true表示成功,false表示失败
  422. -- @return data 如果result为true,表示服务器发过来的包;如果result为false,表示错误信息,超时失败时为"timeout"
  423. -- @return param msg控制退出时,返回msg的字符串
  424. -- @usage
  425. -- true, packet = mqttc:receive(2000)
  426. -- false, error_message = mqttc:receive(2000)
  427. -- false, msg, para = mqttc:receive(2000)
  428. function mqttc:receive(timeout, msg)
  429. if not self.connected then
  430. log.info("mqtt.client:receive", "not connected")
  431. return false
  432. end
  433. return self:waitfor(PUBLISH, timeout, msg)
  434. end
  435. --- 断开与服务器的连接
  436. -- @return nil
  437. -- @usage
  438. -- mqttc = mqtt.client("clientid-123", nil, nil, false)
  439. -- mqttc:connect("mqttserver.com", 1883, "tcp")
  440. -- process data
  441. -- mqttc:disconnect()
  442. function mqttc:disconnect()
  443. if self.io then
  444. if self.connected then self:write(packZeroData(DISCONNECT)) end
  445. self.io:close()
  446. self.io = nil
  447. end
  448. self.cache = {}
  449. self.inbuf = ""
  450. self.connected = false
  451. end
  452. return mqtt