baoshiwei
6 天以前 5bf14aed888cd0e258e325c65f14022dad02985b
src/components/ForceChart.vue
@@ -1,11 +1,7 @@
<script setup lang="ts">
import { ref, onMounted, onUnmounted} from 'vue';
import { ref, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import { sendToPipe } from '../pipe_client';
const props = defineProps<{
  pipeName: string;
}>();
import { createDataReceiver } from '../utils/dataFetcher';
const chartContainer = ref<HTMLElement | null>(null);
let chart: echarts.ECharts | null = null;
@@ -64,37 +60,43 @@
        name: 'Fx',
        type: 'line',
        data: dataHistory.value[0],
        smooth: true
        smooth: true,
        showSymbol: false
      },
      {
        name: 'Fy',
        type: 'line',
        data: dataHistory.value[1],
        smooth: true
        smooth: true,
        showSymbol: false
      },
      {
        name: 'Fz',
        type: 'line',
        data: dataHistory.value[2],
        smooth: true
        smooth: true,
        showSymbol: false
      },
      {
        name: 'Mx',
        type: 'line',
        data: dataHistory.value[3],
        smooth: true
        smooth: true,
        showSymbol: false
      },
      {
        name: 'My',
        type: 'line',
        data: dataHistory.value[4],
        smooth: true
        smooth: true,
        showSymbol: false
      },
      {
        name: 'Mz',
        type: 'line',
        data: dataHistory.value[5],
        smooth: true
        smooth: true,
        showSymbol: false
      }
    ]
  };
@@ -150,53 +152,22 @@
  chart?.resize();
}
// 状态变量,用于控制错误显示频率
const errorCount = ref(0);
const maxConsecutiveErrors = 5;
const showingError = ref(false);
// 接收管道数据的函数
async function receiveForceData() {
  try {
    // 从管道接收数据
    const response = await sendToPipe(props.pipeName, 'GET_FORCE_DATA');
    // 成功接收数据,重置错误计数
    errorCount.value = 0;
    if (showingError.value) {
      showingError.value = false;
      console.log('管道通信已恢复');
    }
    // 解析接收到的数据
    try {
      const forceData = JSON.parse(response);
      if (Array.isArray(forceData) && forceData.length === 6) {
        updateChart(forceData);
      }
    } catch (e) {
      console.warn('解析数据失败:', e);
    }
  } catch (err) {
    // 增加错误计数
    errorCount.value++;
    // 只在连续错误达到阈值时显示错误信息,避免日志刷屏
    if (errorCount.value >= maxConsecutiveErrors && !showingError.value) {
      showingError.value = true;
      console.error('管道通信持续失败,请检查服务端状态:', err);
    }
  }
}
// 定时获取数据
let dataTimer: number | null = null;
onMounted(() => {
  initChart();
  
  // 每秒获取一次数据
  dataTimer = window.setInterval(receiveForceData, 1000);
  const receiveData = createDataReceiver( (forceData) => {
    updateChart(forceData);
  });
  // 每100ms获取一次数据
  dataTimer = window.setInterval(receiveData, 100);
  // 监听窗口大小变化,调整图表大小
  window.addEventListener('resize', handleResize);
});
onUnmounted(() => {