charles
2024-04-29 c7f3fd5215399b37d0511b3bd555150ff1b13507
src/stores/plc.ts
@@ -5,6 +5,7 @@
import { useRequest } from 'vue-hooks-plus'
import { useTasksStore } from '@/stores/tasks'
import type { PLCResponse } from '@/api/plc'
import { PLC_POLLING_DURATION } from '@/common/constants'
// 全局 watcher ref 防止多次调用 usePLCStore 时重复注册侦听器
const unwatch = ref()
@@ -12,50 +13,48 @@
export const usePLCStore = defineStore('plc', () => {
  const taskStore = useTasksStore()
  const plcInfo = computed(() => {
    return plcRes?.value?.data as PLCResponse
  })
  const plcInfo = ref()
  /**
   * 如果任务状态是进行中, 则轮询 plc 取进度
   */
  const {
    data: plcRes,
    run: startPLCPolling,
    cancel: cancelPLCPolling
  } = useRequest(
    () =>
      getProductProgress({
        channel: taskStore.activeTask?.Channel,
        procedureId: taskStore.activeTask?.Procedure.ID
      } as ProductProgressParams),
    {
      manual: true,
      pollingInterval: 6000,
      pollingWhenHidden: false
    }
  )
  // const {
  //   data: plcRes,
  //   run: startPLCPolling,
  //   cancel: cancelPLCPolling
  // } = useRequest(
  //   () =>
  //     getProductProgress({
  //       channel: taskStore.activeChannel ?? 0,
  //       procedureId: taskStore.activeTask?.Procedure.ID ?? undefined
  //     } as ProductProgressParams),
  //   {
  //     manual: true,
  //     pollingInterval: PLC_POLLING_DURATION,
  //     pollingWhenHidden: false
  //   }
  // )
  if (!unwatch.value) {
    /**
     * 如果切换到其他通道的任务,则重新轮询plc
     */
    unwatch.value = watch(
      () => taskStore.activeTask?.Channel,
      () => taskStore.activeChannel,
      () => {
        cancelPLCPolling()
        startPLCPolling()
        // cancelPLCPolling()
        // startPLCPolling()
      }
    )
  }
  function startPollingPLC() {
    cancelPLCPolling()
    startPLCPolling()
    // cancelPLCPolling()
    // startPLCPolling()
  }
  onUnmounted(() => {
    cancelPLCPolling()
    // cancelPLCPolling()
  })
  return { plcInfo, startPollingPLC }