Skip to content

Commit 987920d

Browse files
datetime on graph improved
1 parent 4a557e0 commit 987920d

File tree

3 files changed

+120
-20
lines changed

3 files changed

+120
-20
lines changed

src/routes/api.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,28 @@ def cpu_percent_api():
2424
@login_required
2525
def graph_data_api():
2626
try:
27+
curent_time = datetime.now()
2728
# Get the time filter from query parameters
2829
time_filter = request.args.get('filter', default='1 day')
2930

3031
# Determine the start time based on the filter
3132
now = datetime.now()
32-
if time_filter == '1 day':
33+
# 5 minutes, 15 minutes, 30 minutes, 1 hour, 3 hours, 6 hours, 12 hours, 1 day, 2 days, 3 days, 1 week, 1 month
34+
if time_filter == '5 minutes':
35+
start_time = now - timedelta(minutes=5)
36+
elif time_filter == '15 minutes':
37+
start_time = now - timedelta(minutes=15)
38+
elif time_filter == '30 minutes':
39+
start_time = now - timedelta(minutes=30)
40+
elif time_filter == '1 hour':
41+
start_time = now - timedelta(hours=1)
42+
elif time_filter == '3 hours':
43+
start_time = now - timedelta(hours=3)
44+
elif time_filter == '6 hours':
45+
start_time = now - timedelta(hours=6)
46+
elif time_filter == '12 hours':
47+
start_time = now - timedelta(hours=12)
48+
elif time_filter == '1 day':
3349
start_time = now - timedelta(days=1)
3450
elif time_filter == '2 days':
3551
start_time = now - timedelta(days=2)
@@ -72,7 +88,8 @@ def graph_data_api():
7288
"network_received": network_received_data,
7389
"dashboard_memory_usage": dashboard_memory_usage,
7490
"cpu_frequency": cpu_frequency,
75-
"current_temp": current_temp
91+
"current_temp": current_temp,
92+
"current_time": curent_time
7693
}), 200
7794
except Exception as e:
7895
# Handle and log the error for debugging purposes

src/static/js/graphs.js

Lines changed: 85 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
// Variables to store chart instances
22
let cpuTimeChart, memoryTimeChart, batteryTimeChart, networkTimeChart, dashboardMemoryTimeChart, cpuFrequencyTimeChart, currentTempTimeChart;
33

4-
// Function to fetch and display data
4+
function stringToDate(dateString) {
5+
const date = new Date(dateString);
6+
return date;
7+
}
8+
59
function fetchDataAndRenderCharts() {
610
// Get the selected filter value
711
const filterValue = document.getElementById('timeFilter').value;
@@ -11,20 +15,90 @@ function fetchDataAndRenderCharts() {
1115
.then(response => response.json())
1216
.then(data => {
1317
const cpuData = data.cpu;
14-
const timeData = data.time.map(t => new Date(t)); // Ensure date objects
1518
const memoryData = data.memory;
1619
const batteryData = data.battery;
1720
const networkSentData = data.network_sent;
1821
const networkReceivedData = data.network_received;
1922
const dashboardMemoryUsageData = data.dashboard_memory_usage;
2023
const cpuFrequencyData = data.cpu_frequency;
2124
const currentTempData = data.current_temp;
25+
const currentTime = data.current_time;
26+
const timeZoneName = Intl.DateTimeFormat().resolvedOptions().timeZone;
27+
console.log(currentTime);
28+
29+
// Format the time data using the currentTime from backend
30+
const timeData = data.time.map(time => formatDate(time, currentTime));
31+
32+
displayTimeAndTimeZone(currentTime, timeZoneName);
2233

2334
createCharts(cpuData, timeData, memoryData, batteryData, networkSentData, networkReceivedData, dashboardMemoryUsageData, cpuFrequencyData, currentTempData);
2435
})
2536
.catch(error => console.error('Error fetching data:', error));
2637
}
2738

39+
function formatDate(dateString, currentTime) {
40+
const date = new Date(dateString);
41+
const now = new Date(currentTime); // Use currentTime from backend
42+
43+
// Helper function to format with leading zeros
44+
const pad = (num) => String(num).padStart(2, '0');
45+
46+
// Manually extract UTC components
47+
const day = pad(date.getUTCDate()); // e.g., 09
48+
const month = pad(date.getUTCMonth() + 1); // e.g., 04
49+
const year = date.getUTCFullYear(); // e.g., 2021
50+
const hours = pad(date.getUTCHours()); // e.g., 11
51+
const minutes = pad(date.getUTCMinutes()); // e.g., 33
52+
53+
54+
// Calculate time differences
55+
const diffDays = Math.floor((now - date) / (1000 * 60 * 60 * 24));
56+
const diffWeeks = Math.floor(diffDays / 7);
57+
const diffMonths = now.getMonth() - date.getUTCMonth() + (12 * (now.getFullYear() - date.getUTCFullYear()));
58+
const diffYears = now.getFullYear() - date.getUTCFullYear();
59+
60+
// Determine the label based on time differences
61+
if (diffDays === 0) {
62+
return `Today ${hours}:${minutes}`;
63+
} else if (diffDays === 1) {
64+
return `Yesterday ${hours}:${minutes}`;
65+
} else if (diffDays <= 3) {
66+
return `${diffDays} Days Ago ${hours}:${minutes}`;
67+
} else if (diffDays <= 7) {
68+
return `${Math.ceil(diffDays / 7)} Week${diffDays > 7 ? 's' : ''} Ago ${hours}:${minutes}`;
69+
} else if (diffDays <= 30) {
70+
return `${Math.ceil(diffDays / 7)} Weeks Ago ${hours}:${minutes}`;
71+
} else if (diffMonths < 12) {
72+
return `${diffMonths} Month${diffMonths > 1 ? 's' : ''} Ago ${hours}:${minutes}`;
73+
} else if (diffYears < 2) {
74+
return `Last Year ${hours}:${minutes}`;
75+
} else {
76+
return `${year}/${month}/${day} ${hours}:${minutes}`;
77+
}
78+
}
79+
80+
function displayTimeAndTimeZone(currentTime, timeZoneName) {
81+
// Update current time and timezone
82+
function updateTime() {
83+
const options = { hour: '2-digit', minute: '2-digit', second: '2-digit', timeZone: timeZoneName };
84+
now = new Date();
85+
const timeString = now.toLocaleTimeString('en-US', options);
86+
87+
// Display the current time and timezone
88+
document.getElementById('currentTime').textContent = `Current Time: ${timeString}`;
89+
document.getElementById('timeZoneName').textContent = `Time Zone: ${timeZoneName}`;
90+
}
91+
92+
// Initial display
93+
updateTime();
94+
95+
// Update time every second
96+
setInterval(updateTime, 1000);
97+
}
98+
99+
// Display current time and time zone
100+
101+
28102
// Function to create a chart with multiple datasets
29103
function createChart(ctx, labels, datasets, yLabel) {
30104
if (ctx.chart) {
@@ -34,29 +108,22 @@ function createChart(ctx, labels, datasets, yLabel) {
34108
ctx.chart = new Chart(ctx, {
35109
type: 'line',
36110
data: {
37-
labels: labels, // Use timeData for x-axis labels
111+
labels: labels, // Use your timeData directly as labels
38112
datasets: datasets
39113
},
40114
options: {
41115
scales: {
42116
x: {
43-
type: 'time', // Use 'time' scale for proper date formatting
44-
time: {
45-
unit: 'minute', // Adjust based on the granularity of your data
46-
tooltipFormat: 'll HH:mm', // Tooltip format for time
47-
displayFormats: {
48-
minute: 'HH:mm', // Display format for minute-level granularity
49-
hour: 'MMM D, HH:mm', // Display format for hour-level granularity
50-
day: 'MMM D', // Display format for day-level granularity
51-
week: 'MMM D', // Display format for week-level granularity
52-
month: 'MMM YYYY', // Display format for month-level granularity
53-
quarter: '[Q]Q YYYY', // Display format for quarter-level granularity
54-
year: 'YYYY' // Display format for year-level granularity
55-
}
56-
},
117+
type: 'category', // Use 'category' scale to treat time as strings
57118
title: {
58119
display: true,
59120
text: 'Time'
121+
},
122+
ticks: {
123+
autoSkip: true, // Automatically skip some labels to prevent overlap
124+
maxTicksLimit: 10, // Maximum number of ticks to display
125+
maxRotation: 30, // Prevent rotating the labels for better readability
126+
minRotation: 0
60127
}
61128
},
62129
y: {
@@ -71,6 +138,7 @@ function createChart(ctx, labels, datasets, yLabel) {
71138
});
72139
}
73140

141+
74142
// Function to create charts with the fetched data
75143
function createCharts(cpuData, timeData, memoryData, batteryData, networkSentData, networkReceivedData, dashboardMemoryUsageData, cpuFrequencyData, currentTempData) {
76144
// CPU Usage Chart

src/templates/graphs.html

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,13 @@
1515
<div class="time-filter-container">
1616
<label for="timeFilter">Select Time Filter:</label>
1717
<select id="timeFilter">
18+
<option value="5 minutes">Last 5 Minutes</option>
19+
<option value="15 minutes">Last 15 Minutes</option>
20+
<option value="30 minutes">Last 30 Minutes</option>
21+
<option value="1 hour">Last 1 Hour</option>
22+
<option value="3 hours">Last 3 Hours</option>
23+
<option value="6 hours">Last 6 Hours</option>
24+
<option value="12 hours">Last 12 Hours</option>
1825
<option value="1 day">Last 1 Day</option>
1926
<option value="2 days">Last 2 Days</option>
2027
<option value="3 days">Last 3 Days</option>
@@ -25,6 +32,14 @@
2532
</div>
2633
</div>
2734

35+
<!-- Display current time and time zone -->
36+
<div class="container">
37+
<h2><i class="fas fa-clock"></i> Current Server Time & Time Zone</h2>
38+
<p id="currentTime">Current Time: </p>
39+
<p id="timeZoneName">Time Zone: </p>
40+
</div>
41+
42+
<!-- Chart containers -->
2843
<div class="container">
2944
<h2><i class="fas fa-microchip"></i> CPU Usage Over Time</h2>
3045
<canvas id="cpuTimeChart"></canvas>
@@ -64,4 +79,4 @@ <h2><i class="fas fa-thermometer-half"></i> Current Temperature Over Time</h2>
6479
{% block extra_scripts %}
6580
<script src="{{ url_for('static', filename='js/graphs.js')}}"></script>
6681
<script src="{{ url_for('static', filename='js/refresh_page.js')}}"></script>
67-
{% endblock %}
82+
{% endblock %}

0 commit comments

Comments
 (0)