main.lua 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. if mobile then
  13. LED = gpio.setup(27, 0, gpio.PULLUP)
  14. device_id = mobile.imei()
  15. end
  16. -- 默认都等到联网成功
  17. sys.waitUntil("IP_READY")
  18. sys.publish("net_ready", device_id)
  19. end)
  20. sys.taskInit(function()
  21. -- 等待联网
  22. local ret, device_id = sys.waitUntil("net_ready")
  23. -- -- 腾讯云
  24. -- -- 动态注册
  25. -- iotcloudc = iotcloud.new(iotcloud.TENCENT,{produt_id = "ZAJCHA24SH" ,product_secret = "vGGwnSkyM4eD5ddbNrQoGJox"})
  26. -- -- 密钥校验
  27. iotcloudc = iotcloud.new(iotcloud.TENCENT,{produt_id = "ZAJCHA24SH",device_name = "869329069169988",device_secret = "xNWcxDX0qzSM74oFteehvw=="})
  28. if iotcloudc then
  29. iotcloudc:connect()
  30. end
  31. end)
  32. sys.subscribe("iotcloud", function(cloudc,event,data,payload)
  33. -- 注意,此处不是协程内,复杂操作发消息给协程内进行处理
  34. if event == iotcloud.CONNECT then -- 云平台联上了
  35. print("iotcloud","CONNECT", "云平台连接成功")
  36. iotcloudc:subscribe("$thing/down/property/ZAJCHA24SH/869329069169988") -- 可以自由定阅主题等
  37. elseif event == iotcloud.RECEIVE then
  38. print("iotcloud","topic", data, "payload", payload)
  39. local test_value = json.decode(payload).params.switch
  40. print("test value:", test_value)
  41. if test_value == 1 then
  42. LED(1)
  43. elseif test_value == 0 then
  44. LED(0)
  45. end
  46. -- 用户处理代码
  47. elseif event == iotcloud.OTA then
  48. if data then
  49. rtos.reboot()
  50. end
  51. elseif event == iotcloud.DISCONNECT then -- 云平台断开了
  52. -- 用户处理代码
  53. print("iotcloud","DISCONNECT", "云平台连接断开")
  54. end
  55. end)
  56. -- 每隔2秒发布一次qos为1的消息到云平台
  57. sys.taskInit(function()
  58. while 1 do
  59. sys.wait(2000)
  60. if iotcloudc then
  61. iotcloudc:publish("$thing/up/property/ZAJCHA24SH/869329069169988", "hello world!", 1) -- 上传数据
  62. end
  63. end
  64. end)
  65. -- 用户代码已结束---------------------------------------------
  66. -- 结尾总是这一句
  67. sys.run()
  68. -- sys.run()之后后面不要加任何语句!!!!!