group.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import { parseTime } from '@/utils'
  2. import {
  3. subscribe,
  4. unsubscribe
  5. } from '@/utils/mqtt'
  6. export default {
  7. inject: ['dashboard'],
  8. data () {
  9. return {
  10. groupOptions: this.createGroupOptions({ ignore: true })
  11. }
  12. },
  13. created () {
  14. this.$timer = -1
  15. this.refreshGroups(true)
  16. },
  17. beforeDestroy () {
  18. this.onResetGroupOptions()
  19. },
  20. methods: {
  21. createGroupOptions (options) {
  22. return {
  23. ignore: false,
  24. loading: false,
  25. loaded: false,
  26. list: [],
  27. ...options
  28. }
  29. },
  30. refreshGroups (force) {
  31. // todo
  32. console.log(force)
  33. },
  34. onResetGroupOptions () {
  35. this.groupOptions.ignore = true
  36. this.groupOptions.list = []
  37. clearTimeout(this.$timer)
  38. if (this.groupOptions.topics) {
  39. unsubscribe(this.groupOptions.topics, this.onMessage)
  40. }
  41. },
  42. createTopics ({ id, productId }) {
  43. const topic = `${productId}/${id}`
  44. return [
  45. `${topic}/online`,
  46. `${topic}/offline`/* ,
  47. `${topic}/calendar/update` */
  48. ]
  49. },
  50. onSubscribe (topics) {
  51. if (topics.length) {
  52. this.groupOptions.topics = topics
  53. subscribe(this.groupOptions.topics, this.onMessage)
  54. }
  55. },
  56. onMessage (topic) {
  57. if (!this.groupOptions.loaded || this.groupOptions.ignore) {
  58. return
  59. }
  60. const result = /^\d+\/(\d+)\/(online|offline|calendar\/update)$/.exec(topic)
  61. if (!result) {
  62. return
  63. }
  64. const deviceId = result[1]
  65. const topicKey = result[2]
  66. const device = this.groupOptions.map?.[deviceId]
  67. if (device) {
  68. switch (topicKey) {
  69. case 'calendar/update':
  70. device.flag = -Date.now()
  71. break
  72. default:
  73. if (topicKey !== (device.onlineStatus === 1 ? 'online' : 'offline')) {
  74. if (topicKey === 'online') {
  75. device.onlineStatus = 1
  76. } else {
  77. device.onlineStatus = 2
  78. }
  79. device.lastOnline = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
  80. this.onStatusChanged(topicKey)
  81. }
  82. break
  83. }
  84. }
  85. },
  86. onStatusChanged (topicKey) {
  87. this.dashboard?.onDeviceStatusChanged(topicKey === 'online' ? 1 : -1)
  88. },
  89. transformDevice ({ id, name, productId, onlineStatus, lastOnline, address }) {
  90. return {
  91. id, name, productId, onlineStatus, lastOnline, address,
  92. flag: 0
  93. }
  94. }
  95. }
  96. }