main.lua 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. -- LuaTools需要PROJECT和VERSION这两个信息
  2. PROJECT = "iotclouddemo"
  3. VERSION = "1.0.0"
  4. -- sys库是标配
  5. _G.sys = require("sys")
  6. --[[特别注意, 使用mqtt库需要下列语句]]
  7. _G.sysplus = require("sysplus")
  8. local iotcloud = require("iotcloud")
  9. -- 统一联网函数
  10. sys.taskInit(function()
  11. local device_id = mcu.unique_id():toHex()
  12. -----------------------------
  13. if mobile then
  14. device_id = mobile.imei()
  15. else
  16. -- 其他不认识的bsp, 循环提示一下吧
  17. while 1 do
  18. sys.wait(1000)
  19. log.info("bsp", "本bsp可能未适配网络层, 请查证")
  20. end
  21. end
  22. -- 默认都等到联网成功
  23. sys.waitUntil("IP_READY")
  24. sys.publish("net_ready", device_id)
  25. end)
  26. sys.taskInit(function()
  27. -- 等待联网
  28. local ret, device_id = sys.waitUntil("net_ready")
  29. -------- 以下接入方式根据自己需要修改,相关参数修改为自己的 ---------
  30. -- -- 涂鸦云
  31. iotcloudc = iotcloud.new(iotcloud.TUYA,{device_name = "xxx",device_secret = "xxx"})
  32. if iotcloudc then
  33. iotcloudc:connect()
  34. else
  35. log.error("iotcloud", "创建失败, 请检查参数")
  36. end
  37. end)
  38. sys.subscribe("iotcloud", function(cloudc,event,data,payload)
  39. -- 注意,此处不是协程内,复杂操作发消息给协程内进行处理
  40. if event == iotcloud.CONNECT then -- 云平台联上了
  41. print("iotcloud","CONNECT", "云平台连接成功")
  42. iotcloudc : subscribe("tylink/${deviceId}/thing/property/set") -- 订阅信息
  43. iotcloudc : publish("tylink/${deviceId}/thing/property/report" , '{"data":{"device_status":"999"}}' , 1) -- 上报信息
  44. elseif event == iotcloud.RECEIVE then
  45. print("iotcloud","topic", data, "payload", payload)
  46. -- 用户处理代码
  47. elseif event == iotcloud.OTA then
  48. if data then
  49. rtos.reboot()
  50. end
  51. elseif event == iotcloud.DISCONNECT then -- 云平台断开了
  52. -- 用户处理代码
  53. end
  54. end)
  55. -- 用户代码已结束---------------------------------------------
  56. -- 结尾总是这一句
  57. sys.run()
  58. -- sys.run()之后后面不要加任何语句!!!!!