attributes.lua 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. }
  22. --已修改的数据,缓存在这里,等待上报
  23. local reportTemp = {}
  24. --初始化
  25. function t.initial()
  26. sys.taskInit(function()
  27. sys.waitUntil("CLOUD_CONNECTED") -- 连接成功
  28. for k,v in pairs(reportTemp) do
  29. attributes[k] = v
  30. end
  31. --上报数据初始化一下
  32. ThingsCloud.reportAttributes(attributes)
  33. while true do
  34. local hasData = false
  35. for _,_ in pairs(reportTemp) do
  36. hasData = true
  37. break
  38. end
  39. if not hasData then
  40. --没数据,等待
  41. sys.waitUntil("ATTRIBUTES_UPDATED")
  42. end
  43. sys.wait(100)
  44. --有数据,复制数据
  45. local temp = {}
  46. for k,v in pairs(reportTemp) do
  47. temp[k] = v
  48. end
  49. reportTemp = {}
  50. --上报数据
  51. ThingsCloud.reportAttributes(temp)
  52. sys.wait(5500)--防止上报太频繁,最快5秒一次
  53. end
  54. end)
  55. end
  56. --修改数据
  57. function t.set(k,v,fromCloud)
  58. --值没改变,不用处理
  59. if attributes[k] == v then
  60. return
  61. end
  62. if type(v) == "table" then
  63. local hasChange = false
  64. for k1,v1 in pairs(v) do
  65. if attributes[k][k1] ~= v1 then
  66. hasChange = true
  67. break
  68. end
  69. end
  70. if not hasChange then
  71. return
  72. end
  73. end
  74. attributes[k] = v
  75. --来自云端的数据不用缓存
  76. if not fromCloud then
  77. --缓存数据,等待上报
  78. reportTemp[k] = v
  79. sys.publish("ATTRIBUTES_UPDATED")
  80. end
  81. end
  82. --获取数据
  83. function t.get(k)
  84. return attributes[k]
  85. end
  86. --获取所有数据
  87. function t.all()
  88. return attributes
  89. end
  90. return t