Update public/scripts/trends.js

This commit is contained in:
JoshBaneyCS 2025-04-30 04:07:14 +00:00
parent 199449ea8f
commit 9e169cd742

View File

@ -11,21 +11,16 @@ const tfConfig = [
// ─── Helpers ───────────────────────────────────────────────────────────────── // ─── Helpers ─────────────────────────────────────────────────────────────────
function formatESTTimestamp(ts) { function formatESTTimestamp(ts) {
// ts is "YYYY-MM-DD HH:mm:ss" in Eastern time // ts is "YYYY-MM-DD HH:mm:ss" or ISO → we assume you converted to "M/D/YY @HH:mm"
const [date, time] = ts.split(' '); return ts; // adjust if you need to parse differently
const [Y, M, D] = date.split('-').map(Number);
const [h, m] = time.split(':');
return `${M}/${D}/${String(Y).slice(-2)} @${h.padStart(2,'0')}:${m}`;
} }
function parseLocalDate(ts) { function parseLocalDate(ts) {
const [date, time] = ts.split(' '); // if you have epoch_ms, convert: return new Date(epoch_ms)
const [Y, M, D] = date.split('-').map(Number); return new Date(ts.replace(' ', 'T'));
const [h, m, s] = time.split(':').map(Number);
return new Date(Y, M-1, D, h, m, s);
} }
function subtract(date, count, unit) { function subtract(date, count, unit) {
const d = new Date(date); const d = new Date(date);
switch(unit) { switch(unit){
case 'hours': d.setHours(d.getHours() - count); break; case 'hours': d.setHours(d.getHours() - count); break;
case 'days': d.setDate(d.getDate() - count); break; case 'days': d.setDate(d.getDate() - count); break;
case 'weeks': d.setDate(d.getDate() - 7*count); break; case 'weeks': d.setDate(d.getDate() - 7*count); break;
@ -35,11 +30,11 @@ function subtract(date, count, unit) {
return d; return d;
} }
// ─── State ──────────────────────────────────────────────────────────────────── // ─── State & Chart Ref ───────────────────────────────────────────────────────
let readings = []; let readings = [];
let chart; let chart;
// ─── Init ───────────────────────────────────────────────────────────────────── // ─── Initialize ───────────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', async () => { document.addEventListener('DOMContentLoaded', async () => {
await loadReadings(); await loadReadings();
setupUI(); setupUI();
@ -47,100 +42,118 @@ document.addEventListener('DOMContentLoaded', async () => {
updateView(); updateView();
}); });
// ─── Load readings ──────────────────────────────────────────────────────────── // ─── Load data ────────────────────────────────────────────────────────────────
async function loadReadings() { async function loadReadings() {
const data = await fetch('/api/readings').then(r=>r.json()); const data = await fetch('/api/readings').then(r=>r.json());
readings = data.map(r => ({ readings = data.map(r => ({
...r, stationDockDoor: r.stationDockDoor,
formattedTs: formatESTTimestamp(r.timestamp), location: r.location,
dateObj: parseLocalDate(r.timestamp) temperature: r.temperature,
humidity: r.humidity,
heatIndex: r.heatIndex,
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)
})); }));
} }
// ─── UI Wiring ──────────────────────────────────────────────────────────────── // ─── UI Wiring ────────────────────────────────────────────────────────────────
function setupUI() { function setupUI() {
// Slider
const slider = document.getElementById('timeframe-slider'); const slider = document.getElementById('timeframe-slider');
const label = document.getElementById('timeframe-label'); const label = document.getElementById('timeframe-label');
slider.addEventListener('input', ()=>{ slider.addEventListener('input', () => {
label.textContent = tfConfig[slider.value].label; label.textContent = tfConfig[slider.value].label;
updateView(); updateView();
}); });
label.textContent = tfConfig[slider.value].label; label.textContent = tfConfig[slider.value].label;
document.getElementsByName('metric').forEach(cb=>{ // Metric checkboxes
document.getElementsByName('metric').forEach(cb => {
cb.addEventListener('change', updateView); cb.addEventListener('change', updateView);
}); });
// Table sorting
document.querySelectorAll('#trends-table thead th.sortable').forEach(th=>{ document.querySelectorAll('#trends-table thead th.sortable').forEach(th=>{
th.addEventListener('click', ()=>{ th.addEventListener('click', ()=>{
const idx = th.cellIndex; const idx = th.cellIndex;
const asc = !th.classList.contains('asc'); const asc = !th.classList.contains('asc');
const tbody = document.getElementById('trends-table-body'); const tbody = document.getElementById('trends-table-body');
const rows = Array.from(tbody.rows); Array.from(tbody.rows)
rows.sort((a,b)=>{ .sort((a,b) => asc
return asc ? a.cells[idx].textContent.localeCompare(b.cells[idx].textContent, undefined, {numeric:true})
? a.cells[idx].textContent.localeCompare(b.cells[idx].textContent,undefined,{numeric:true}) : b.cells[idx].textContent.localeCompare(a.cells[idx].textContent, undefined, {numeric:true})
: b.cells[idx].textContent.localeCompare(a.cells[idx].textContent,undefined,{numeric:true}); )
}); .forEach(r=>tbody.appendChild(r));
th.classList.toggle('asc',asc); th.classList.toggle('asc', asc);
rows.forEach(r=>tbody.appendChild(r));
}); });
}); });
} }
// ─── Chart Setup ────────────────────────────────────────────────────────────── // ─── Chart.js Initialization ──────────────────────────────────────────────────
function initChart() { function initChart() {
const ctx = document.getElementById('trend-chart').getContext('2d'); const ctx = document.getElementById('trend-chart').getContext('2d');
chart = new Chart(ctx, { chart = new Chart(ctx, {
type:'line', type: 'line',
data:{ labels:[], datasets:[] }, data: { labels: [], datasets: [] },
options:{ options: {
scales:{ scales: {
x:{ title:{display:true,text:'Time (EST)'} }, x: { title: { display:true, text:'Time (EST)' } },
y:{ title:{display:true,text:'Value'} } y: { title: { display:true, text:'Value' } }
}, },
interaction:{mode:'index',intersect:false}, interaction: { mode:'index', intersect:false },
plugins:{legend:{position:'top'}}, plugins: { legend:{ position:'top' } },
maintainAspectRatio:false maintainAspectRatio: false
} }
}); });
} }
// ─── Render ─────────────────────────────────────────────────────────────────── // ─── Update chart & table ────────────────────────────────────────────────────
function updateView() { function updateView() {
const idx = +document.getElementById('timeframe-slider').value; const idx = +document.getElementById('timeframe-slider').value;
const { unit, count } = tfConfig[idx]; const {unit,count} = tfConfig[idx];
const cutoff = subtract(new Date(), count, unit); const cutoff = subtract(new Date(), count, unit);
const filtered = readings.filter(r=>r.dateObj >= cutoff); // Filter
const filtered = readings.filter(r => r.dateObj >= cutoff);
// Metrics selected
const selected = Array.from(document.getElementsByName('metric')) const selected = Array.from(document.getElementsByName('metric'))
.filter(cb=>cb.checked).map(cb=>cb.value); .filter(cb=>cb.checked).map(cb=>cb.value);
const labels = filtered.map(r=>r.formattedTs); // Chart data
const datasets = []; chart.data.labels = filtered.map(r=>r.formattedTs);
chart.data.datasets = [];
if (selected.includes('temperature')) { if (selected.includes('temperature')) {
datasets.push({ label:'Temperature (°F)', data:filtered.map(r=>r.temperature), tension:0.3 }); chart.data.datasets.push({
label: 'Temperature (°F)',
data: filtered.map(r=>r.temperature),
tension: 0.3
});
} }
if (selected.includes('humidity')) { if (selected.includes('humidity')) {
datasets.push({ label:'Humidity (%)', data:filtered.map(r=>r.humidity), tension:0.3 }); chart.data.datasets.push({
label: 'Humidity (%)',
data: filtered.map(r=>r.humidity),
tension: 0.3
});
} }
if (selected.includes('heatIndex')) { if (selected.includes('heatIndex')) {
datasets.push({ label:'Heat Index (°F)', data:filtered.map(r=>r.heatIndex), tension:0.3 }); chart.data.datasets.push({
label: 'Heat Index (°F)',
data: filtered.map(r=>r.heatIndex),
tension: 0.3
});
} }
chart.data.labels = labels;
chart.data.datasets = datasets;
chart.update(); chart.update();
populateTable(filtered); // Table
}
// ─── Table ───────────────────────────────────────────────────────────────────
function populateTable(data) {
const tbody = document.getElementById('trends-table-body'); const tbody = document.getElementById('trends-table-body');
tbody.innerHTML = ''; tbody.innerHTML = '';
data.forEach(r=>{ filtered.forEach(r => {
const tr = document.createElement('tr'); const tr = document.createElement('tr');
tr.innerHTML = ` tr.innerHTML = `
<td>${r.formattedTs}</td> <td>${r.formattedTs}</td>