g33mqtt.lua 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. module(..., package.seeall)
  2. require "mqtt"
  3. require "sim"
  4. require "net"
  5. require "misc"
  6. require "pins"
  7. require "nvm"
  8. require"mqtt_recieve"
  9. -- require"mqtt_send"
  10. local host, port = nvm.get("mqttIp") or "develop.rltest.cn", nvm.get("mqttPort") or "1883"
  11. local username = nvm.get("mqttUser") or "rl517"
  12. local password = nvm.get("mqttPassword") or "rlian2022"
  13. --mqttc 连接状态
  14. local isConnected = false
  15. local isWaitReconnect = false
  16. --ota 升级检测是否结束
  17. local isOtaCheckEnd = false
  18. --等待ota升级检测结束
  19. -- sys.subscribe("ota_update_check_end", function(data)
  20. -- isOtaCheckEnd = true
  21. -- end)
  22. --启动MQTT客户端任务
  23. sys.taskInit(
  24. function()
  25. local retryConnectCnt = 0
  26. while true do
  27. if not socket.isReady() then
  28. retryConnectCnt = 0
  29. --等待网络环境准备就绪,超时时间是5分钟
  30. log.info("socket 1 is not ready")
  31. sys.wait(1000)
  32. sys.waitUntil("IP_READY_IND",300000)
  33. end
  34. if socket.isReady() then
  35. local imei = misc.getImei()
  36. --创建一个MQTT客户端
  37. local mqttClient = mqtt.client(imei,300,username,password)
  38. --阻塞执行MQTT CONNECT动作,直至成功
  39. --如果使用ssl连接,打开mqttClient:connect("lbsmqtt.airm2m.com",1884,"tcp_ssl",{caCert="ca.crt"}),根据自己的需求配置
  40. --mqttClient:connect("lbsmqtt.airm2m.com",1884,"tcp_ssl",{caCert="ca.crt"})
  41. if mqttClient:connect(host,port,"tcp") then
  42. log.info("imei:", imei)
  43. retryConnectCnt = 0
  44. isConnected = true
  45. --订阅主题
  46. local topics = {
  47. ["SHEGCL/IntelligenTool/UpdateToolInfo/"..imei] = 0,
  48. ["SHEGCL/IntelligenTool/UploadWorkRecordMA/"..imei]=0,
  49. ["SHEGCL/IntelligenTool/UploadWorkRecordFA/"..imei]=0,
  50. ["SHEGCL/IntelligenTool/UploadWorkRecordSimple/"..imei]=0,
  51. ["SHEGCL/IntelligenTool/Heart/"..imei]=0
  52. }
  53. if mqttClient:subscribe(topics) then
  54. --循环处理接收和发送的数据
  55. while true do
  56. -- if not mqtt_send.proc(mqttClient) then log.error("mqttTask.mqtt_send proc error") break end
  57. if not mqtt_recieve.proc(mqttClient) then log.error("mqttTask.mqtt_recieve.proc error") break end
  58. -- local a = mqtt_send.proc(mqttClient)
  59. -- log.info("send proc res", a)
  60. end
  61. end
  62. isConnected = false
  63. else
  64. retryConnectCnt = retryConnectCnt+1
  65. end
  66. --断开MQTT连接
  67. mqttClient:disconnect()
  68. if retryConnectCnt>=5 then link.shut() retryConnectCnt=0 end
  69. sys.wait(5000)
  70. else
  71. --进入飞行模式,20秒之后,退出飞行模式
  72. net.switchFly(true)
  73. sys.wait(20000)
  74. net.switchFly(false)
  75. end
  76. end
  77. end
  78. )