document.addEventListener('DOMContentLoaded', function () { var chartContainer = document.getElementById('chart-container'); var myChart = echarts.init(chartContainer); var timestamps = [], temperatures = []; function fetchInitialData() { fetch('http://111.230.197.156:8000/get_sensor_data') .then(response => response.json()) .then(data => { timestamps = data.timestamps.slice(-200); // 只保留最新的200个时间戳 temperatures = data.temperatures.slice(-200); // 只保留最新的200个温度数据 updateChart(); }); } function fetchLatestData() { fetch('http://111.230.197.156:8000/get_latest_sensor_data') .then(response => response.json()) .then(data => { // 如果已有200个数据则移除最旧的一条 if (timestamps.length >= 200) { timestamps.shift(); temperatures.shift(); } // 添加新的数据 timestamps.push(data.timestamps); temperatures.push(data.temperature); updateChart(); }); } function updateChart() { var option = { title: { text: '温度数据', textStyle: { color: 'white' } }, tooltip: { trigger: 'axis' }, legend: { data: ['温度'], textStyle: { color: 'white' } }, xAxis: { type: 'category', data: timestamps, axisLabel: { color: 'white' } }, yAxis: { type: 'value', axisLabel: { color: 'white' } }, series: [{ name: '温度', type: 'line', data: temperatures }] }; myChart.setOption(option); document.getElementById('temperature').textContent = `当前温度: ${temperatures[temperatures.length - 1]}℃`; } // 初始化时获取所有数据 fetchInitialData(); // 每5秒获取最新的数据 setInterval(fetchLatestData, 1000); });