main.lua 2.3 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. 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.BAIDU,{produt_id = "aakyhyw",device_name = "869329069169988",device_secret = "IzNIWqXdGRPEoUlS"})
  26. -- 证书认证(自动注册)
  27. iotcloudc = iotcloud.new(iotcloud.BAIDU,{produt_id = "aakyhyw",device_name = "869329069169988"},{tls={server_cert=io.readFile("/luadb/GlobalSign.cer"),client_cert=io.readFile("/luadb/client_cert.txt"),client_key=io.readFile("/luadb/client_private_key.txt")}})
  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("$iot/869329069169988/user/fortest") -- 可以自由订阅主题等
  37. elseif event == iotcloud.RECEIVE then
  38. print("iotcloud","topic", data, "payload", payload)
  39. if payload == "open" then
  40. log.info("main", "收到云平台下发的指令")
  41. LED(1)
  42. elseif payload == "close" then
  43. LED(0)
  44. end
  45. -- 用户处理代码
  46. elseif event == iotcloud.OTA then
  47. if data then
  48. rtos.reboot()
  49. end
  50. elseif event == iotcloud.DISCONNECT then -- 云平台断开了
  51. -- 用户处理代码
  52. print("iotcloud","DISCONNECT", "云平台连接断开")
  53. end
  54. end)
  55. -- 用户代码已结束---------------------------------------------
  56. -- 结尾总是这一句
  57. sys.run()
  58. -- sys.run()之后后面不要加任何语句!!!!!