mqttOutMsg.lua 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. --- 模块功能:MQTT客户端数据发送处理
  2. -- @author openLuat
  3. -- @module mqtt.mqttOutMsg
  4. -- @license MIT
  5. -- @copyright openLuat
  6. -- @release 2018.03.28
  7. module(...,package.seeall)
  8. --数据发送的消息队列
  9. local msgQueue = {}
  10. local data1=0
  11. local function insertMsg(topic,payload,qos,user)
  12. table.insert(msgQueue,{t=topic,p=payload,q=qos,user=user})
  13. sys.publish("APP_SOCKET_SEND_DATA")
  14. end
  15. local function pubQos0TestCb(result)
  16. log.info("mqttOutMsg.pubQos0TestCb",result)
  17. if result then sys.timerStart(pubQos0Test,20000) end
  18. end
  19. function pubQos0Test()
  20. insertMsg("/qos0topic","qos0data",0,{cb=pubQos0TestCb})
  21. end
  22. local function pubQos1TestCb(result)
  23. log.info("mqttOutMsg.pubQos1TestCb",result)
  24. if result then sys.timerStart(pubQos1Test,10000) end
  25. end
  26. function pubQos1Test()
  27. data1=data1+1
  28. insertMsg("/中文qos1topic","中文qos1data"..data1,1,{cb=pubQos1TestCb})
  29. end
  30. --- 初始化“MQTT客户端数据发送”
  31. -- @return 无
  32. -- @usage mqttOutMsg.init()
  33. function init()
  34. --pubQos0Test()
  35. pubQos1Test()
  36. end
  37. --- 去初始化“MQTT客户端数据发送”
  38. -- @return 无
  39. -- @usage mqttOutMsg.unInit()
  40. function unInit()
  41. sys.timerStop(pubQos0Test)
  42. sys.timerStop(pubQos1Test)
  43. while #msgQueue>0 do
  44. local outMsg = table.remove(msgQueue,1)
  45. if outMsg.user and outMsg.user.cb then outMsg.user.cb(false,outMsg.user.para) end
  46. end
  47. end
  48. --- MQTT客户端数据发送处理
  49. -- @param mqttClient,MQTT客户端对象
  50. -- @return 处理成功返回true,处理出错返回false
  51. -- @usage mqttOutMsg.proc(mqttClient)
  52. function proc(mqttClient)
  53. while #msgQueue>0 do
  54. log.info('mqtt发消息')
  55. local outMsg = table.remove(msgQueue,1)
  56. local result = mqttClient:publish(outMsg.t,outMsg.p,outMsg.q)
  57. if outMsg.user and outMsg.user.cb then outMsg.user.cb(result,outMsg.user.para) end
  58. if not result then return end
  59. end
  60. return true
  61. end