use-connect-mqtt.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { ref, watch, computed, onUnmounted } from 'vue'
  2. import { useMyStore } from '/@/store'
  3. import { postDrc } from '/@/api/drc'
  4. import { UranusMqtt } from '/@/mqtt'
  5. type StatusOptions = {
  6. status: 'close';
  7. event?: CloseEvent;
  8. } | {
  9. status: 'open';
  10. retryCount: number;
  11. } | {
  12. status: 'pending';
  13. }
  14. export function useConnectMqtt() {
  15. const store = useMyStore()
  16. const dockOsdVisible = computed(() => {
  17. return store.state.osdVisible && store.state.osdVisible.visible && store.state.osdVisible.is_dock
  18. })
  19. const mqttState = ref<UranusMqtt | null>(null)
  20. // 监听已打开的设备小窗 窗口数量
  21. watch(() => dockOsdVisible.value, async (val) => {
  22. // 1.打开小窗
  23. // 2.设备拥有飞行控制权
  24. // 3.请求建立mqtt连接的认证信息
  25. if (val) {
  26. if (mqttState.value) return
  27. const result = await postDrc({})
  28. if (result?.code === 0) {
  29. const { address, client_id, username, password, expire_time } = result.data
  30. // @TODO: 校验 expire_time
  31. mqttState.value = new UranusMqtt(address, {
  32. clientId: client_id,
  33. username,
  34. password,
  35. })
  36. mqttState.value?.initMqtt()
  37. mqttState.value?.on('onStatus', (statusOptions: StatusOptions) => {
  38. // @TODO: 异常case
  39. })
  40. store.commit('SET_MQTT_STATE', mqttState.value)
  41. store.commit('SET_CLIENT_ID', client_id)
  42. }
  43. // @TODO: 认证失败case
  44. return
  45. }
  46. // 关闭所有小窗后
  47. // 1.销毁mqtt连接重置mqtt状态
  48. if (mqttState?.value) {
  49. mqttState.value?.destroyed()
  50. mqttState.value = null
  51. store.commit('SET_MQTT_STATE', null)
  52. store.commit('SET_CLIENT_ID', '')
  53. }
  54. }, { immediate: true })
  55. onUnmounted(() => {
  56. mqttState.value?.destroyed()
  57. })
  58. }