107 lines
3.6 KiB
JavaScript
107 lines
3.6 KiB
JavaScript
document.addEventListener('DOMContentLoaded', function () {
|
|
const co2HistoryChartCanvas = document.getElementById('co2HistoryChart');
|
|
const co2HistoryTableBody = document.getElementById('co2HistoryTableBody');
|
|
let chart;
|
|
|
|
async function fetchCo2Data() {
|
|
try {
|
|
const response = await fetch('api/co2-data.php');
|
|
if (!response.ok) {
|
|
throw new Error(`HTTP error! status: ${response.status}`);
|
|
}
|
|
const result = await response.json();
|
|
|
|
if (result.success && result.data) {
|
|
updateChart(result.data);
|
|
updateTable(result.data);
|
|
} else {
|
|
console.error('Failed to fetch CO2 data:', result.error);
|
|
co2HistoryTableBody.innerHTML = '<tr><td colspan="5" class="text-center">Error loading data.</td></tr>';
|
|
}
|
|
} catch (error) {
|
|
console.error('Error fetching CO2 data:', error);
|
|
co2HistoryTableBody.innerHTML = '<tr><td colspan="5" class="text-center">Error loading data.</td></tr>';
|
|
}
|
|
}
|
|
|
|
function updateChart(data) {
|
|
if (!co2HistoryChartCanvas) return;
|
|
|
|
// Data is fetched DESC, reverse for chronological chart
|
|
const chartData = data.slice().reverse();
|
|
|
|
const labels = chartData.map(d => new Date(d.reading_time).toLocaleString());
|
|
const values = chartData.map(d => d.reading_value);
|
|
|
|
const chartConfig = {
|
|
type: 'line',
|
|
data: {
|
|
labels: labels,
|
|
datasets: [{
|
|
label: 'CO2 Level (PPM)',
|
|
data: values,
|
|
borderColor: '#1A73E8',
|
|
backgroundColor: 'rgba(26, 115, 232, 0.1)',
|
|
fill: true,
|
|
tension: 0.4,
|
|
pointBackgroundColor: '#1A73E8'
|
|
}]
|
|
},
|
|
options: {
|
|
responsive: true,
|
|
maintainAspectRatio: false,
|
|
scales: {
|
|
y: {
|
|
beginAtZero: false,
|
|
title: {
|
|
display: true,
|
|
text: 'CO2 (PPM)'
|
|
}
|
|
},
|
|
x: {
|
|
title: {
|
|
display: true,
|
|
text: 'Timestamp'
|
|
}
|
|
}
|
|
},
|
|
plugins: {
|
|
legend: {
|
|
display: false
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
if (chart) {
|
|
chart.destroy();
|
|
}
|
|
chart = new Chart(co2HistoryChartCanvas, chartConfig);
|
|
}
|
|
|
|
function updateTable(data) {
|
|
if (!co2HistoryTableBody) return;
|
|
|
|
co2HistoryTableBody.innerHTML = ''; // Clear existing data
|
|
|
|
if (data.length === 0) {
|
|
co2HistoryTableBody.innerHTML = '<tr><td colspan="5" class="text-center">No historical data available.</td></tr>';
|
|
return;
|
|
}
|
|
|
|
data.forEach(reading => {
|
|
const row = document.createElement('tr');
|
|
row.innerHTML = `
|
|
<td>${new Date(reading.reading_time).toLocaleString()}</td>
|
|
<td>${parseFloat(reading.reading_value).toFixed(2)}</td>
|
|
<td>${reading.warehouse_name}</td>
|
|
<td>${reading.slot_name}</td>
|
|
<td>${reading.node_name}</td>
|
|
`;
|
|
co2HistoryTableBody.appendChild(row);
|
|
});
|
|
}
|
|
|
|
fetchCo2Data();
|
|
});
|