main.lua 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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.HUAWEI,{produt_id = "670c7b2dfc8d5a4ea71c6a79",
  26. -- project_id = "c086a58ebd714bfcb1a0fea2f0edde36",
  27. -- endpoint = "9098a2ff3c.st1",
  28. -- iam_username="hao",
  29. -- iam_password="Wsh1322764769",
  30. -- iam_domain="hao15738882476"})
  31. -- 密钥校验 (预注册)
  32. iotcloudc = iotcloud.new(iotcloud.HUAWEI,{produt_id = "670c7b2dfc8d5a4ea71c6a79",endpoint = "5341624af8.st1",device_name = "869329069169988",device_secret = "XXX"})
  33. if iotcloudc then
  34. iotcloudc:connect()
  35. end
  36. end)
  37. sys.subscribe("iotcloud", function(cloudc,event,data,payload)
  38. -- 注意,此处不是协程内,复杂操作发消息给协程内进行处理
  39. if event == iotcloud.CONNECT then -- 云平台联上了
  40. print("iotcloud","CONNECT", "云平台连接成功")
  41. -- iotcloudc:subscribe("/huawei/down/869329069169988") -- 可以自由定阅主题等
  42. -- iotcloudc:subscribe("$oc/devices/869329069169988/user/869329069169988")
  43. elseif event == iotcloud.RECEIVE then
  44. print("iotcloud","topic", data, "payload", payload)
  45. -- local test_value = json.decode(payload).content.switch
  46. -- print("test value:", test_value)
  47. -- if test_value == 1 then
  48. -- LED(1)
  49. -- elseif test_value == 0 then
  50. -- LED(0)
  51. -- end
  52. -- 用户处理代码
  53. elseif event == iotcloud.OTA then
  54. if data then
  55. rtos.reboot()
  56. end
  57. elseif event == iotcloud.DISCONNECT then -- 云平台断开了
  58. -- 用户处理代码
  59. print("iotcloud","DISCONNECT", "云平台连接断开")
  60. end
  61. end)
  62. -- -- 每隔2秒发布一次qos为1的消息到云平台
  63. -- sys.taskInit(function()
  64. -- while 1 do
  65. -- sys.wait(2000)
  66. -- if iotcloudc then
  67. -- iotcloudc:publish("$oc/devices/869329069169988/user/869329069169988", "hello world!", 1) -- 上传数据
  68. -- end
  69. -- end
  70. -- end)
  71. -- 用户代码已结束---------------------------------------------
  72. -- 结尾总是这一句
  73. sys.run()
  74. -- sys.run()之后后面不要加任何语句!!!!!