Update public/scripts/trends.js
This commit is contained in:
parent
9e169cd742
commit
67e036df63
@ -1,6 +1,6 @@
|
||||
// public/scripts/trends.js
|
||||
|
||||
// ─── Timeframes ──────────────────────────────────────────────────────────────
|
||||
// --- Timeframe options ---
|
||||
const tfConfig = [
|
||||
{ unit:'hours', count:24, label:'Last 24 Hours' },
|
||||
{ unit:'days', count:7, label:'Last 7 Days' },
|
||||
@ -9,15 +9,11 @@ const tfConfig = [
|
||||
{ unit:'years', count:1, label:'All Time' }
|
||||
];
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
function formatESTTimestamp(ts) {
|
||||
// ts is "YYYY-MM-DD HH:mm:ss" or ISO → we assume you converted to "M/D/YY @HH:mm"
|
||||
return ts; // adjust if you need to parse differently
|
||||
}
|
||||
function parseLocalDate(ts) {
|
||||
// if you have epoch_ms, convert: return new Date(epoch_ms)
|
||||
return new Date(ts.replace(' ', 'T'));
|
||||
}
|
||||
// --- State ---
|
||||
let readings = [];
|
||||
let chart;
|
||||
|
||||
// --- Helpers ---
|
||||
function subtract(date, count, unit) {
|
||||
const d = new Date(date);
|
||||
switch(unit) {
|
||||
@ -30,37 +26,36 @@ function subtract(date, count, unit) {
|
||||
return d;
|
||||
}
|
||||
|
||||
// ─── State & Chart Ref ───────────────────────────────────────────────────────
|
||||
let readings = [];
|
||||
let chart;
|
||||
|
||||
// ─── Initialize ───────────────────────────────────────────────────────────────
|
||||
// --- Load & initialize ---
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
await loadReadings();
|
||||
setupUI();
|
||||
initChart();
|
||||
updateView();
|
||||
});
|
||||
|
||||
// ─── Load data ────────────────────────────────────────────────────────────────
|
||||
async function loadReadings() {
|
||||
console.log('📡 Loading readings from /api/readings…');
|
||||
try {
|
||||
const data = await fetch('/api/readings').then(r => r.json());
|
||||
console.log('✅ Received readings:', data);
|
||||
readings = data.map(r => ({
|
||||
stationDockDoor: r.stationDockDoor,
|
||||
location: r.location,
|
||||
temperature: r.temperature,
|
||||
humidity: r.humidity,
|
||||
heatIndex: r.heatIndex,
|
||||
dateObj: new Date(r.epoch_ms),
|
||||
formattedTs: new Date(r.epoch_ms).toLocaleString('en-US', {
|
||||
timeZone:'America/New_York',
|
||||
month:'numeric', day:'numeric', year:'2-digit',
|
||||
hour12: false, hour:'2-digit', minute:'2-digit'
|
||||
}).replace(',',' @'),
|
||||
dateObj: new Date(r.epoch_ms)
|
||||
hour:'2-digit', minute:'2-digit', hour12:false
|
||||
}).replace(',',' @')
|
||||
}));
|
||||
}
|
||||
console.log('✔ Parsed readings:', readings);
|
||||
|
||||
// ─── UI Wiring ────────────────────────────────────────────────────────────────
|
||||
setupUI();
|
||||
initChart();
|
||||
updateView();
|
||||
} catch (err) {
|
||||
console.error('❌ Failed to load readings:', err);
|
||||
}
|
||||
});
|
||||
|
||||
// --- UI wiring ---
|
||||
function setupUI() {
|
||||
// Slider
|
||||
const slider = document.getElementById('timeframe-slider');
|
||||
@ -71,7 +66,7 @@ function setupUI() {
|
||||
});
|
||||
label.textContent = tfConfig[slider.value].label;
|
||||
|
||||
// Metric checkboxes
|
||||
// Metrics toggles
|
||||
document.getElementsByName('metric').forEach(cb => {
|
||||
cb.addEventListener('change', updateView);
|
||||
});
|
||||
@ -93,8 +88,13 @@ function setupUI() {
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Chart.js Initialization ──────────────────────────────────────────────────
|
||||
// --- Chart.js init ---
|
||||
function initChart() {
|
||||
if (typeof Chart === 'undefined') {
|
||||
console.error('❌ Chart.js not loaded!');
|
||||
return;
|
||||
}
|
||||
console.log('📊 Initializing Chart.js');
|
||||
const ctx = document.getElementById('trend-chart').getContext('2d');
|
||||
chart = new Chart(ctx, {
|
||||
type: 'line',
|
||||
@ -111,20 +111,27 @@ function initChart() {
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Update chart & table ────────────────────────────────────────────────────
|
||||
// --- Render chart & table ---
|
||||
function updateView() {
|
||||
if (!chart) return;
|
||||
console.log('🔄 updateView called');
|
||||
|
||||
// Timeframe cutoff
|
||||
const idx = +document.getElementById('timeframe-slider').value;
|
||||
const { unit, count } = tfConfig[idx];
|
||||
const cutoff = subtract(new Date(), count, unit);
|
||||
console.log(` Showing data since ${cutoff.toISOString()}`);
|
||||
|
||||
// Filter
|
||||
// Filter readings
|
||||
const filtered = readings.filter(r => r.dateObj >= cutoff);
|
||||
console.log(` ${filtered.length}/${readings.length} points after filtering`);
|
||||
|
||||
// Metrics selected
|
||||
const selected = Array.from(document.getElementsByName('metric'))
|
||||
.filter(cb => cb.checked).map(cb => cb.value);
|
||||
console.log(' Metrics selected:', selected);
|
||||
|
||||
// Chart data
|
||||
// Update chart
|
||||
chart.data.labels = filtered.map(r => r.formattedTs);
|
||||
chart.data.datasets = [];
|
||||
if (selected.includes('temperature')) {
|
||||
@ -148,9 +155,10 @@ function updateView() {
|
||||
tension: 0.3
|
||||
});
|
||||
}
|
||||
console.log(' Chart update:', chart.data);
|
||||
chart.update();
|
||||
|
||||
// Table
|
||||
// Update table
|
||||
const tbody = document.getElementById('trends-table-body');
|
||||
tbody.innerHTML = '';
|
||||
filtered.forEach(r => {
|
||||
@ -165,4 +173,5 @@ function updateView() {
|
||||
`;
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
console.log(' Table populated with', filtered.length, 'rows');
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user