main.lua 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. -- LuaTools需要PROJECT和VERSION这两个信息
  2. PROJECT = "aliyun_yjym_yzc"
  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. if mobile then
  13. device_id = mobile.imei()
  14. else
  15. -- 其他不认识的bsp, 循环提示一下吧
  16. while 1 do
  17. sys.wait(1000)
  18. log.info("bsp", "本bsp可能未适配网络层, 请查证")
  19. end
  20. end
  21. -- 默认都等到联网成功
  22. sys.waitUntil("IP_READY")
  23. sys.publish("net_ready", device_id)
  24. end)
  25. sys.taskInit(function()
  26. -- 等待联网
  27. local ret, device_id = sys.waitUntil("net_ready")
  28. -------- 以下接入方式根据自己需要修改,相关参数修改为自己的 ---------
  29. -- 阿里云
  30. -- 动态注册(免预注册)(一型一密)(仅企业版支持)
  31. -- iotcloudc = iotcloud.new(iotcloud.ALIYUN,{instance_id = "xxx",produt_id = "xxx",product_secret = "xxx"}) -- 企业版公共实例
  32. -- 动态注册(预注册)(一型一密)
  33. -- iotcloudc = iotcloud.new(iotcloud.ALIYUN,{produt_id = "xxx",device_name = "xxx",product_secret = "xxx"}) -- 旧版公共实例
  34. -- iotcloudc = iotcloud.new(iotcloud.ALIYUN,{instance_id = "xxx",produt_id = "xxx",device_name = "xxx",product_secret = "xxx"}) -- 新版公共实例
  35. -- 密钥校验 (预注册)(一机一密)
  36. -- iotcloudc = iotcloud.new(iotcloud.ALIYUN,{produt_id = "xxx",device_name = "xxx",device_secret = "xxx"}) -- 旧版公共实例
  37. iotcloudc = iotcloud.new(iotcloud.ALIYUN,{instance_id = "xxx",produt_id = "xxx",device_name = "xxx",device_secret = "xxx"})-- 新版公共实例
  38. if iotcloudc then
  39. iotcloudc:connect()
  40. end
  41. end)
  42. sys.subscribe("iotcloud", function(cloudc,event,data,payload)
  43. -- 注意,此处不是协程内,复杂操作发消息给协程内进行处理
  44. if event == iotcloud.CONNECT then -- 云平台联上了
  45. print("iotcloud","CONNECT", "云平台连接成功")
  46. iotcloudc:subscribe("/"..iotcloudc.product_id.."/"..iotcloudc.device_name.."/user/get") -- 订阅主题,用于下发消息
  47. elseif event == iotcloud.RECEIVE then
  48. print("iotcloud","topic", data, "payload", payload)
  49. -- 用户处理代码
  50. elseif event == iotcloud.OTA then
  51. if data then
  52. rtos.reboot()
  53. end
  54. elseif event == iotcloud.DISCONNECT then -- 云平台断开了
  55. -- 用户处理代码
  56. end
  57. end)
  58. -- 每隔2秒发布一次qos为1的消息到云平台
  59. sys.taskInit(function()
  60. while 1 do
  61. sys.wait(2000)
  62. if iotcloudc then
  63. iotcloudc:publish("/"..iotcloudc.product_id.."/"..iotcloudc.device_name.."/user/update", "hello world", 1) -- 上传数据
  64. end
  65. end
  66. end)
  67. -- 用户代码已结束---------------------------------------------
  68. -- 结尾总是这一句
  69. sys.run()
  70. -- sys.run()之后后面不要加任何语句!!!!!