main.lua 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. -- LuaTools需要PROJECT和VERSION这两个信息
  2. PROJECT = "air302_mqtt_demo"
  3. VERSION = "1.0.0"
  4. -- sys库是标配
  5. _G.sys = require("sys")
  6. local mqtt = require "mqtt"
  7. sys.taskInit(function()
  8. -- 服务器配置信息
  9. local host, port, selfid = "lbsmqtt.airm2m.com", 1884, nbiot.imei()
  10. -- 等待联网成功
  11. while true do
  12. while not socket.isReady() do
  13. log.info("net", "wait for network ready")
  14. sys.waitUntil("NET_READY", 1000)
  15. end
  16. log.info("main", "Airm2m mqtt loop")
  17. local mqttc = mqtt.client(selfid, nil, nil, false)
  18. while not mqttc:connect(host, port) do sys.wait(2000) end
  19. local topic_req = string.format("/device/%s/req", selfid)
  20. local topic_report = string.format("/device/%s/report", selfid)
  21. local topic_resp = string.format("/device/%s/resp", selfid)
  22. log.info("mqttc", "mqtt seem ok", "try subscribe", topic_req)
  23. if mqttc:subscribe(topic_req) then
  24. log.info("mqttc", "mqtt subscribe ok", "try publish")
  25. if mqttc:publish(topic_report, "test publish " .. os.date() .. crypto.md5("12345"), 1) then
  26. while true do
  27. log.info("mqttc", "wait for new msg")
  28. local r, data, param = mqttc:receive(120000, "pub_msg")
  29. log.info("mqttc", "mqttc:receive", r, data, param)
  30. if r then
  31. log.info("mqttc", "get message from server", data.payload or "nil", data.topic)
  32. elseif data == "pub_msg" then
  33. log.info("mqttc", "send message to server", data, param)
  34. mqttc:publish(topic_resp, "response " .. param)
  35. elseif data == "timeout" then
  36. log.info("mqttc", "wait timeout, send custom report")
  37. mqttc:publish(topic_report, "test publish " .. os.date() .. nbiot.imei())
  38. else
  39. log.info("mqttc", "ok, something happen", "close connetion")
  40. break
  41. end
  42. end
  43. end
  44. end
  45. mqttc:disconnect()
  46. sys.wait(5000) -- 等待一小会, 免得疯狂重连
  47. end
  48. end)
  49. -- 用户代码已结束---------------------------------------------
  50. -- 结尾总是这一句
  51. sys.run()
  52. -- sys.run()之后后面不要加任何语句!!!!!