<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Power Graph</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Real-Time Power Graph</h1>
<canvas id="powerChart" width="800" height="400"></canvas>
<script>
// Initialize the chart
const ctx = document.getElementById('powerChart').getContext('2d');
const powerChart = new Chart(ctx, {
type: 'line',
data: {
labels: [], // Timestamps will be added here
datasets: [{
label: 'Current Power (W)',
data: [], // Power values will be added here
borderWidth: 1,
borderColor: 'blue',
backgroundColor: 'rgba(0, 0, 255, 0.1)',
}]
},
options: {
responsive: true,
scales: {
x: {
title: {
display: true,
text: 'Timestamp'
}
},
y: {
title: {
display: true,
text: 'Current Power (W)'
},
beginAtZero: true
}
}
}
});
// Function to fetch data and update the chart
function fetchDataAndUpdateChart() {
$.ajax({
url: 'fetch_data.php', // Replace with the correct path to your PHP file
method: 'GET',
dataType: 'json', // Ensure response is parsed as JSON
success: function (response) {
// Check if cur_power and timestamp exist in the response
if (response.cur_power !== undefined && response.timestamp !== undefined) {
console.log("Data received:", response); // Debug log for data
// Add new data to the chart
powerChart.data.labels.push(response.timestamp);
powerChart.data.datasets[0].data.push(response.cur_power/10000);
// Limit data points for better performance (e.g., max 20 points)
// Update the chart
powerChart.update();
} else {
console.error("Invalid data format:", response);
}
},
error: function (xhr, status, error) {
console.error("AJAX Error:", status, error);
}
});
}
// Fetch data every 10 seconds
setInterval(fetchDataAndUpdateChart, 10000);
// Initial call to populate the chart immediately
fetchDataAndUpdateChart();
</script>
</body>
</html>