screenshot.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import {
  2. subscribe,
  3. publish
  4. } from '@/utils/mqtt'
  5. const cache = new Map()
  6. let listening = false
  7. export function getAndCheck ({ productId, id }, cb, expired) {
  8. if (!listening) {
  9. subscribe('+/+/screenshot/reply', onMessage)
  10. listening = true
  11. }
  12. let inst = cache.get(id)
  13. if (inst) {
  14. inst.cb = cb
  15. } else {
  16. cache.set(id, inst = createInst(productId, id, cb))
  17. }
  18. if (retry(inst, expired)) {
  19. screenshot(id, true)
  20. } else {
  21. cb(inst)
  22. }
  23. }
  24. function retry (inst, expired = 30000) {
  25. if (!inst) {
  26. return false
  27. }
  28. if (inst.waiting && inst.timestamp + 10000 >= Date.now()) {
  29. return false
  30. }
  31. if (inst.base64 && inst.timestamp + expired >= Date.now()) {
  32. return false
  33. }
  34. return true
  35. }
  36. export function stop (deviceId) {
  37. const inst = cache.get(deviceId)
  38. if (inst) {
  39. inst.cb = null
  40. }
  41. }
  42. export function screenshot (deviceId, silence) {
  43. const inst = cache.get(deviceId)
  44. if (inst) {
  45. inst.waiting = true
  46. inst.base64 = null
  47. publish(`${inst.productId}/${inst.deviceId}/screenshot/ask`, JSON.stringify({ timestamp: inst.timestamp })).then(() => {
  48. startTimer(inst)
  49. }, () => {
  50. inst.waiting = false
  51. if (!silence) {
  52. this.$message({
  53. type: 'warning',
  54. message: '正在连接,请稍后再试'
  55. })
  56. }
  57. }).finally(() => {
  58. emit(inst)
  59. })
  60. }
  61. }
  62. function createInst (productId, deviceId, cb) {
  63. return {
  64. productId,
  65. deviceId,
  66. cb,
  67. timer: -1,
  68. waiting: false,
  69. timestamp: Date.now(),
  70. base64: null
  71. }
  72. }
  73. function startTimer (inst) {
  74. clearTimeout(inst.timer)
  75. inst.timer = setTimeout(() => {
  76. inst.waiting = false
  77. emit(inst)
  78. }, 20000)
  79. }
  80. function emit (inst) {
  81. inst.cb && inst.cb(inst)
  82. }
  83. function onMessage (topic, message) {
  84. const result = /^(\d+)\/(\d+)\/screenshot\/reply$/.exec(topic)
  85. if (result) {
  86. const inst = cache.get(result[2])
  87. if (inst) {
  88. clearTimeout(inst.timer)
  89. inst.waiting = false
  90. inst.base64 = `data:image/jpeg;base64,${message.replace(/\s/g, '')}`
  91. inst.timestamp = Date.now()
  92. emit(inst)
  93. }
  94. }
  95. }
  96. export function reset (deviceId) {
  97. const inst = cache.get(deviceId)
  98. if (inst) {
  99. clearTimeout(inst.timer)
  100. inst.waiting = false
  101. inst.base64 = null
  102. emit(inst)
  103. }
  104. }