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 => { var maxDataPoints = window.innerWidth <= 768 ? 50 : 200; // 根据屏幕宽度决定数据量 timestamps = data.timestamps.slice(-maxDataPoints); temperatures = data.temperatures.slice(-maxDataPoints); updateChart(); }); } function fetchLatestData() { fetch('http://111.230.197.156:8000/get_latest_sensor_data') .then(response => response.json()) .then(data => { // 如果已有200个数据则移除最旧的一条 if (timestamps.length >= 50) { timestamps.shift(); temperatures.shift(); } // 添加新的数据 timestamps.push(data.timestamps); temperatures.push(data.temperatures); 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); });