mqtt.lua 17 KB

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