From d4bf879721479706582315d7de8acad314cc2409 Mon Sep 17 00:00:00 2001 From: IrisVega Date: Sat, 20 Jul 2024 16:46:26 +0800 Subject: [PATCH] modified: static/js/sensor-1.js --- static/js/sensor-1.js | 93 +++++++++++++++++++------------------------ 1 file changed, 42 insertions(+), 51 deletions(-) diff --git a/static/js/sensor-1.js b/static/js/sensor-1.js index d8f5de0..db310cf 100644 --- a/static/js/sensor-1.js +++ b/static/js/sensor-1.js @@ -2,62 +2,53 @@ document.addEventListener('DOMContentLoaded', function () { var chartContainer = document.getElementById('chart-container'); var myChart = echarts.init(chartContainer); - var timestamps = []; - var temperatures = []; + var timestamps = [], temperatures = []; - function fetchAndUpdateData() { + 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个数据 + timestamps = data.timestamps.slice(-200); // 只保留最新的200个时间戳 + temperatures = data.temperatures.slice(-200); // 只保留最新的200个温度数据 - 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.slice(-1)}℃`; + updateChart(); }); } - // 每5秒刷新一次数据 - setInterval(fetchAndUpdateData, 1000); - fetchAndUpdateData(); -}); + function fetchLatestData() { + fetch('http://111.230.197.156:8000/get_latest_data') + .then(response => response.json()) + .then(data => { + // 如果已有200个数据则移除最旧的一条 + if (timestamps.length >= 200) { + timestamps.shift(); + temperatures.shift(); + } + + // 添加新的数据 + timestamps.push(data.timestamp); + 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, 5000); +}); \ No newline at end of file