baoshiwei
2025-05-21 832991a036bcb0d99a66d2d1f059253136ddd622
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
<script setup lang="ts">
import { ref, onMounted, onUnmounted} from 'vue';
import * as echarts from 'echarts';
import { sendToPipe } from '../pipe_client';
 
const props = defineProps<{
  pipeName: string;
}>();
 
const chartContainer = ref<HTMLElement | null>(null);
let chart: echarts.ECharts | null = null;
 
// 存储六轴力数据的历史记录
const dataHistory = ref<number[][]>([[], [], [], [], [], []]);
const maxDataPoints = 100; // 最多显示100个数据点
 
// 时间轴数据
const timeData = ref<string[]>([]);
 
// 初始化图表
function initChart() {
  if (!chartContainer.value) return;
  
  chart = echarts.init(chartContainer.value);
  
  const option = {
    title: {
      text: '六维力传感器数据',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params: any[]) {
        let result = params[0].name + '<br/>';
        params.forEach(item => {
          // 根据系列名称判断单位
          const unit = item.seriesName.startsWith('M') ? 'Nm' : 'N';
          result += item.marker + ' ' + item.seriesName + ': ' + item.value.toFixed(2) + unit + '<br/>';
        });
        return result;
      }
    },
    legend: {
      data: ['Fx', 'Fy', 'Fz', 'Mx', 'My', 'Mz'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: timeData.value
    },
    yAxis: {
      type: 'value',
      name: '力/力矩值'
    },
    series: [
      {
        name: 'Fx',
        type: 'line',
        data: dataHistory.value[0],
        smooth: true
      },
      {
        name: 'Fy',
        type: 'line',
        data: dataHistory.value[1],
        smooth: true
      },
      {
        name: 'Fz',
        type: 'line',
        data: dataHistory.value[2],
        smooth: true
      },
      {
        name: 'Mx',
        type: 'line',
        data: dataHistory.value[3],
        smooth: true
      },
      {
        name: 'My',
        type: 'line',
        data: dataHistory.value[4],
        smooth: true
      },
      {
        name: 'Mz',
        type: 'line',
        data: dataHistory.value[5],
        smooth: true
      }
    ]
  };
 
  chart.setOption(option);
  
  // 响应窗口大小变化
  window.addEventListener('resize', handleResize);
}
 
// 更新图表数据
function updateChart(forceData: number[]) {
  if (!chart) return;
  
  // 添加时间戳
  const now = new Date();
  const timeStr = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
  timeData.value.push(timeStr);
  
  // 限制时间轴数据点数量
  if (timeData.value.length > maxDataPoints) {
    timeData.value.shift();
  }
  
  // 更新六轴力数据
  for (let i = 0; i < 6; i++) {
    dataHistory.value[i].push(forceData[i]);
    
    // 限制每条线的数据点数量
    if (dataHistory.value[i].length > maxDataPoints) {
      dataHistory.value[i].shift();
    }
  }
  
  // 更新图表
  chart.setOption({
    xAxis: {
      data: timeData.value
    },
    series: [
      { data: dataHistory.value[0] },
      { data: dataHistory.value[1] },
      { data: dataHistory.value[2] },
      { data: dataHistory.value[3] },
      { data: dataHistory.value[4] },
      { data: dataHistory.value[5] }
    ]
  });
}
 
// 处理窗口大小变化
function handleResize() {
  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);
});
 
onUnmounted(() => {
  // 清理定时器和事件监听
  if (dataTimer !== null) {
    clearInterval(dataTimer);
  }
  
  window.removeEventListener('resize', handleResize);
  
  // 销毁图表实例
  chart?.dispose();
  chart = null;
});
</script>
 
<template>
  <div class="chart-container" ref="chartContainer"></div>
</template>
 
<style scoped>
.chart-container {
  width: 100%;
  height: 540px;
  margin: 20px 0;
}
</style>