attributes.lua 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. local t = {}
  2. local attributes = {
  3. location = {
  4. lat = 0,
  5. lng = 0,
  6. },
  7. isCharging = false,
  8. battery = 0,
  9. step = 0,
  10. ledControl = false,
  11. redLed = true,
  12. blueLed = true,
  13. isFixed = "获取中",
  14. lat = "无数据",
  15. lng = "无数据",
  16. rsrp = 0,
  17. rsrq = 0,
  18. vbat = 0,
  19. audioStatus = "空闲",
  20. callStatus = "不支持",
  21. isGPSOn = true,
  22. sleepMode = false,
  23. }
  24. --已修改的数据,缓存在这里,等待上报
  25. local reportTemp = {}
  26. --初始化
  27. function t.initial()
  28. sys.taskInit(function()
  29. sys.waitUntil("CLOUD_CONNECTED") -- 连接成功
  30. for k,v in pairs(reportTemp) do
  31. attributes[k] = v
  32. end
  33. --上报数据初始化一下
  34. --ThingsCloud.reportAttributes(attributes)
  35. while true do
  36. local hasData = false
  37. for _,_ in pairs(reportTemp) do
  38. hasData = true
  39. break
  40. end
  41. if not hasData then
  42. --没数据,等待
  43. sys.waitUntil("ATTRIBUTES_UPDATED")
  44. end
  45. sys.wait(100)
  46. --有数据,复制数据
  47. local temp = {}
  48. for k,v in pairs(reportTemp) do
  49. temp[k] = v
  50. end
  51. reportTemp = {}
  52. --上报数据
  53. ThingsCloud.reportAttributes(temp)
  54. sys.wait(5500)--防止上报太频繁,最快5秒一次
  55. end
  56. end)
  57. end
  58. --修改数据
  59. function t.set(k,v,fromCloud)
  60. --值没改变,不用处理
  61. if attributes[k] == v then
  62. return
  63. end
  64. --休眠模式下,只有sleepMode属性可以修改
  65. if attributes.sleepMode then
  66. log.info("attributes.set", "sleepMode",k,v)
  67. if fromCloud then--云端下发的数据只能修改sleepMode属性
  68. if k ~= "sleepMode" then
  69. return
  70. end
  71. else
  72. return
  73. end
  74. end
  75. if type(v) == "table" then
  76. local hasChange = false
  77. for k1,v1 in pairs(v) do
  78. if attributes[k][k1] ~= v1 then
  79. hasChange = true
  80. break
  81. end
  82. end
  83. if not hasChange then
  84. return
  85. end
  86. end
  87. attributes[k] = v
  88. --来自云端的数据不用缓存
  89. if not fromCloud then
  90. --缓存数据,等待上报
  91. reportTemp[k] = v
  92. sys.publish("ATTRIBUTES_UPDATED")
  93. end
  94. end
  95. --获取数据
  96. function t.get(k)
  97. return attributes[k]
  98. end
  99. --获取所有数据
  100. function t.all()
  101. return attributes
  102. end
  103. --刷新所有数据
  104. function t.setAll()
  105. reportTemp = attributes
  106. end
  107. return t