WebSocket是实现医学数据实时波形图绘制的理想技术,下面我将详细介绍完整的实现方案。
Node.js示例:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
console.log('新的客户端连接');
// 模拟发送医学数据(实际应用中从设备获取)
const interval = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
const data = generateMedicalData();
ws.send(JSON.stringify(data));
}
}, 50); // 20Hz采样率
ws.on('close', () => {
clearInterval(interval);
console.log('客户端断开连接');
});
});
function generateMedicalData() {
return {
timestamp: Date.now(),
ecg: Math.random() * 2 - 1, // 模拟ECG数据
bloodPressure: 80 + Math.random() * 40, // 模拟血压
spo2: 95 + Math.random() * 5 // 血氧饱和度
};
}
HTML结构:
<!DOCTYPE html>
<html>
<head>
<title>医学数据实时监测</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div style="width: 100%; max-width: 1200px; margin: 0 auto;">
<canvas id="ecgChart" height="200"></canvas>
<canvas id="bpChart" height="200"></canvas>
<canvas id="spo2Chart" height="200"></canvas>
</div>
<script src="app.js"></script>
</body>
</html>
JavaScript (app.js):
// 初始化图表
const ecgCtx = document.getElementById('ecgChart').getContext('2d');
const bpCtx = document.getElementById('bpChart').getContext('2d');
const spo2Ctx = document.getElementById('spo2Chart').getContext('2d');
const ecgChart = new Chart(ecgCtx, {
type: 'line',
data: { labels: [], datasets: [{ label: 'ECG', data: [], borderColor: 'rgb(75, 192, 192)' }] },
options: { responsive: true, animation: { duration: 0 } }
});
const bpChart = new Chart(bpCtx, {
type: 'line',
data: { labels: [], datasets: [{ label: '血压', data: [], borderColor: 'rgb(255, 99, 132)' }] },
options: { responsive: true, animation: { duration: 0 } }
});
const spo2Chart = new Chart(spo2Ctx, {
type: 'line',
data: { labels: [], datasets: [{ label: '血氧饱和度', data: [], borderColor: 'rgb(54, 162, 235)' }] },
options: { responsive: true, animation: { duration: 0 }, scales: { y: { min: 90, max: 100 } } }
});
// WebSocket连接
const ws = new WebSocket('ws://localhost:8080');
const maxDataPoints = 200; // 每个图表显示的最大数据点数
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
const timestamp = new Date(data.timestamp).toLocaleTimeString();
// 更新ECG图表
updateChart(ecgChart, timestamp, data.ecg);
// 更新血压图表
updateChart(bpChart, timestamp, data.bloodPressure);
// 更新血氧图表
updateChart(spo2Chart, timestamp, data.spo2);
};
function updateChart(chart, label, value) {
// 添加新数据
chart.data.labels.push(label);
chart.data.datasets[0].data.push(value);
// 限制数据点数
if (chart.data.labels.length > maxDataPoints) {
chart.data.labels.shift();
chart.data.datasets[0].data.shift();
}
// 更新图表
chart.update();
}
通过上述方案,您可以构建一个稳定、实时的医学数据监测系统,适用于ECG、EEG、血压等多种医学波形数据的可视化。