Add dashboard analytics, public conditions page, and station data features

- Dashboard: account-protected station data recorder with PBKDF2 auth and
  HMAC-signed sessions; Chart.js time-series charts with 1h–3y range selectors;
  wind rose canvas; auto-refresh every 2 min; 1-min polling cron
- Analytics endpoints: all-time records, rain totals (7d/30d/YTD), heating/cooling
  degree days, CSV export, year-over-year overlay, hourly anomaly detection
- Dashboard UI: pressure trend arrow, rain tile row, HDD/CDD tiles, anomaly tile,
  YoY toggle, collapsible records panel, CSV export, backfill progress bar
- Public conditions page at /conditions (no auth) with auto-refresh every 2 min
- Rain rate push alert via web-push and ntfy when threshold exceeded
- Station data stored as per-day JSONL files; backfill imports up to 1yr from Ambient

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Nate EmmertandClaude Sonnet 4.6 committed 2026-08-19 14:26:51 -04:00
1 parent 46e927370a
commit 7665146b44
3 files changed
+455 -9

No files matched your search

+77
View File
@@ -0,0 +1,77 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Current Conditions</title>
<meta http-equiv="refresh" content="120">
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--ink: #1a1a1a; --ink-light: #5f5649; --paper: #f5f2ec; --paper-dark: #ece7db;
--border: #b9ae9b; --accent: #c25a2a; --cool: #2a6b8a;
--mono: 'Segoe UI Rounded', 'Trebuchet MS', sans-serif;
}
@media (prefers-color-scheme: dark) {
:root { --ink: #ece7dc; --ink-light: #beb399; --paper: #191510; --paper-dark: #201c16; --border: #3a342a; --accent: #e07848; --cool: #5ab0d8; }
}
html, body { min-height: 100%; background: var(--paper); color: var(--ink); font-family: var(--mono); }
.page { max-width: 700px; margin: 0 auto; padding: 2rem 1rem 3rem; }
h1 { font-size: 1.3rem; margin-bottom: 0.2rem; }
.sub { font-size: 0.85rem; color: var(--ink-light); margin-bottom: 2rem; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 0.75rem; }
.tile { background: var(--paper-dark); border: 1px solid var(--border); border-radius: 12px; padding: 0.85rem 1rem; }
.tile-label { font-size: 0.7rem; text-transform: uppercase; letter-spacing: 0.06em; color: var(--ink-light); margin-bottom: 0.2rem; }
.tile-val { font-size: 1.6rem; font-weight: 700; line-height: 1.1; }
.tile-unit { font-size: 0.75rem; color: var(--ink-light); margin-top: 0.1rem; }
.offline { text-align: center; padding: 3rem; color: var(--ink-light); }
.updated { font-size: 0.75rem; color: var(--ink-light); margin-top: 1.5rem; }
.wind-dir { font-size: 1rem; color: var(--ink-light); margin-left: 0.25rem; }
</style>
</head>
<body>
<div class="page">
<h1>Current Conditions</h1>
<p class="sub" id="stationSub">Personal weather station</p>
<div class="grid" id="grid">
<div class="offline">Loading…</div>
</div>
<p class="updated" id="updated"></p>
</div>
<script>
function cardinal(deg) {
return ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW'][Math.round(deg / 22.5) % 16];
}
function tile(label, val, unit) {
return `<div class="tile"><div class="tile-label">${label}</div><div class="tile-val">${val}</div><div class="tile-unit">${unit}</div></div>`;
}
async function load() {
try {
const r = await fetch('/api/conditions/public');
if (!r.ok) throw new Error('unavailable');
const d = await r.json();
if (!d) { document.getElementById('grid').innerHTML = '<div class="offline">No data yet.</div>'; return; }
const fmt = (v, digits=1) => v != null ? (+v).toFixed(digits) : '—';
const windLabel = d.winddir != null ? `Wind <span class="wind-dir">${cardinal(d.winddir)}</span>` : 'Wind';
document.getElementById('grid').innerHTML = [
tile('Temperature', fmt(d.tempf), '°F'),
tile('Feels Like', fmt(d.feelsLike ?? d.tempf), '°F'),
tile('Humidity', fmt(d.humidity, 0), '%'),
tile('Dew Point', fmt(d.dewPoint), '°F'),
tile(windLabel, fmt(d.windspeedmph), 'mph'),
tile('Wind Gust', fmt(d.windgustmph), 'mph'),
tile('Pressure', fmt(d.baromrelin, 2), 'inHg'),
tile('Rain Today', fmt(d.dailyrainin, 2), 'in'),
tile('Rain Rate', fmt(d.rainratein, 2), 'in/hr'),
tile('UV Index', fmt(d.uv, 0), ''),
tile('Solar', fmt(d.solarradiation, 0), 'W/m²'),
].join('');
if (d.dateutc) document.getElementById('updated').textContent = 'Updated ' + new Date(d.dateutc).toLocaleTimeString();
} catch {
document.getElementById('grid').innerHTML = '<div class="offline">Station data unavailable.</div>';
}
}
load();
</script>
</body>
</html>
+210 -9
View File
@@ -91,6 +91,18 @@ a { color: var(--cool); text-decoration: none; }
.keys-status.missing { color: var(--accent); }
.keys-hint { font-size: 0.78rem; color: var(--ink-light); margin-top: 1rem; line-height: 1.5; }
.settings-divider { border: none; border-top: 1px solid var(--border); margin: 1.25rem 0; }
/* Records */
.records-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 0.6rem; }
.record-item { background: var(--paper); border: 1px solid var(--border); border-radius: 8px; padding: 0.6rem 0.85rem; }
.record-label { font-size: 0.72rem; color: var(--ink-light); text-transform: uppercase; letter-spacing: 0.05em; }
.record-val { font-size: 1.15rem; font-weight: 700; margin: 0.1rem 0; }
.record-date { font-size: 0.72rem; color: var(--ink-light); }
/* Anomaly tile */
.stat.anomaly-above { border-color: var(--accent); }
.stat.anomaly-below { border-color: var(--cool); }
/* Export link */
.export-link { display: inline-block; padding: 0.45rem 1.2rem; background: var(--cool); color: #fff !important; border-radius: 8px; font-size: 0.9rem; font-weight: 600; text-decoration: none !important; }
.export-link:hover { opacity: 0.88; }
.backfill-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 1rem; flex-wrap: wrap; }
.backfill-controls { display: flex; gap: 0.5rem; align-items: center; flex-shrink: 0; }
.backfill-controls select { padding: 0.45rem 0.6rem; background: var(--paper); border: 1px solid var(--border); border-radius: 8px; color: var(--ink); font-family: var(--mono); font-size: 0.85rem; }
@@ -122,7 +134,11 @@ a { color: var(--cool); text-decoration: none; }
<div class="stat"><div class="stat-label">Dew Point</div><div class="stat-val" id="sDew">—</div><div class="stat-unit">°F</div></div>
<div class="stat"><div class="stat-label">Wind</div><div class="stat-val" id="sWind">—</div><div class="stat-unit">mph</div></div>
<div class="stat"><div class="stat-label">Wind Gust</div><div class="stat-val" id="sGust">—</div><div class="stat-unit">mph</div></div>
<div class="stat"><div class="stat-label">Pressure</div><div class="stat-val" id="sPres">—</div><div class="stat-unit">inHg</div></div>
<div class="stat">
<div class="stat-label">Pressure</div>
<div class="stat-val" id="sPres">—</div>
<div class="stat-unit">inHg &nbsp;<span id="sTrend" style="font-size:1rem;"></span></div>
</div>
<div class="stat"><div class="stat-label">Rain Today</div><div class="stat-val" id="sRain">—</div><div class="stat-unit">in</div></div>
<div class="stat"><div class="stat-label">Rain Rate</div><div class="stat-val" id="sRainRate">—</div><div class="stat-unit">in/hr</div></div>
<div class="stat"><div class="stat-label">UV Index</div><div class="stat-val" id="sUV">—</div><div class="stat-unit"></div></div>
@@ -130,6 +146,20 @@ a { color: var(--cool); text-decoration: none; }
<div class="stat"><div class="stat-label">Battery</div><div class="stat-val" id="sBatt">—</div><div class="stat-unit"></div></div>
</div>
<!-- Rain totals + degree days -->
<div class="stats" id="extStats">
<div class="stat"><div class="stat-label">Rain 7d</div><div class="stat-val" id="sRain7d">—</div><div class="stat-unit">in</div></div>
<div class="stat"><div class="stat-label">Rain 30d</div><div class="stat-val" id="sRain30d">—</div><div class="stat-unit">in</div></div>
<div class="stat"><div class="stat-label">Rain YTD</div><div class="stat-val" id="sRainYTD">—</div><div class="stat-unit">in</div></div>
<div class="stat"><div class="stat-label">Heating DD</div><div class="stat-val" id="sHDD">—</div><div class="stat-unit">this month</div></div>
<div class="stat"><div class="stat-label">Cooling DD</div><div class="stat-val" id="sCDD">—</div><div class="stat-unit">this month</div></div>
<div class="stat" id="sAnomalyTile" style="display:none">
<div class="stat-label">Temp vs Normal</div>
<div class="stat-val" id="sAnomaly">—</div>
<div class="stat-unit" id="sAnomalyNote"></div>
</div>
</div>
<!-- Range selector -->
<div class="range-bar">
<span>History:</span>
@@ -143,6 +173,7 @@ a { color: var(--cool); text-decoration: none; }
<button class="range-btn" data-range="2y">2y</button>
<button class="range-btn" data-range="3y">3y</button>
<button class="refresh-btn" id="refreshBtn">↻ Refresh</button>
<button class="range-btn" id="yoyBtn" style="display:none" title="Overlay same period from 1 year ago">YoY</button>
</div>
<div class="updated" id="updatedLine"></div>
@@ -151,6 +182,14 @@ a { color: var(--cool); text-decoration: none; }
<div class="status" id="loadingMsg">Loading history…</div>
</div>
<!-- Records -->
<details class="settings-panel" id="recordsPanel" style="margin-top:1.5rem">
<summary>All-Time Station Records</summary>
<div class="settings-body" id="recordsBody">
<div class="status">Loading records…</div>
</div>
</details>
<!-- Settings -->
<details class="settings-panel" id="settingsPanel">
<summary>Station API Keys</summary>
@@ -174,6 +213,26 @@ a { color: var(--cool); text-decoration: none; }
<hr class="settings-divider">
<div class="backfill-header" style="margin-bottom:0.75rem">
<div>
<div class="chart-title" style="margin-bottom:0.25rem">Export Data</div>
<p class="keys-hint" style="margin:0">Download your station history as a CSV spreadsheet.</p>
</div>
<div class="backfill-controls">
<select id="exportRange">
<option value="7d">7 days</option>
<option value="30d" selected>30 days</option>
<option value="90d">90 days</option>
<option value="1y">1 year</option>
<option value="2y">2 years</option>
<option value="3y">3 years</option>
</select>
<a id="exportBtn" class="export-link" href="#" target="_blank">Download CSV</a>
</div>
</div>
<hr class="settings-divider">
<div class="backfill-section">
<div class="backfill-header">
<div>
@@ -370,7 +429,7 @@ function drawWindRose(canvas, readings) {
}
// ── Render charts ────────────────────────────────────────────────────────────
function renderCharts(readings, range) {
function renderCharts(readings, range, yoy = null) {
const area = document.getElementById('chartsArea');
if (!readings.length) {
area.innerHTML = '<div class="status">No recorded data for this range yet. Data is collected every minute while the station is active.</div>';
@@ -449,10 +508,15 @@ function renderCharts(readings, range) {
</div>
`;
makeChart('cTemp', 'line',
[lineDataset('Temp °F', field(pts, 'tempf'), c.accent),
lineDataset('Feels Like', field(pts, 'feelsLike'), c.cool, true)],
lbls, '°F');
const tempDatasets = [
lineDataset('Temp °F', field(pts, 'tempf'), c.accent),
lineDataset('Feels Like', field(pts, 'feelsLike'), c.cool, true),
];
if (yoy?.prior?.length) {
const yoyPts = yoy.prior.length > 720 ? yoy.prior.filter((_, i) => i % Math.ceil(yoy.prior.length / 720) === 0) : yoy.prior;
tempDatasets.push({ ...lineDataset('Last Year', yoyPts.map(r => r.tempf), c.accent + '55', true), borderWidth: 1 });
}
makeChart('cTemp', 'line', tempDatasets, lbls, '°F');
makeChart('cHum', 'line',
[lineDataset('Humidity %', field(pts, 'humidity'), c.cool),
@@ -546,7 +610,7 @@ async function loadHistory(range) {
if (r.status === 401) { location.href = '/dashboard/login'; return; }
if (!r.ok) throw new Error('Failed');
const data = await r.json();
renderCharts(data, range);
renderCharts(data, range, yoyEnabled ? yoyData : null);
const line = document.getElementById('updatedLine');
if (line) {
const next = new Date(Date.now() + 120000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
@@ -558,11 +622,13 @@ async function loadHistory(range) {
}
// ── Init ──────────────────────────────────────────────────────────────────────
document.querySelectorAll('.range-btn').forEach(btn => {
document.querySelectorAll('.range-btn[data-range]').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.range-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.range-btn[data-range]').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentRange = btn.dataset.range;
yoyData = null; yoyEnabled = false; yoyBtn.classList.remove('active');
updateYoyVisibility(currentRange);
loadHistory(currentRange);
});
});
@@ -676,9 +742,144 @@ async function pollBackfill() {
document.getElementById('backfillBtn').addEventListener('click', startBackfill);
// ── Pressure trend ────────────────────────────────────────────────────────────
async function updatePressureTrend() {
try {
const r = await fetch('/api/station/history?range=6h');
if (!r.ok) return;
const data = await r.json();
if (data.length < 2) return;
const recent = data[data.length - 1]?.baromrelin;
const older = data[Math.max(0, data.length - 19)]?.baromrelin; // ~3h ago (at 1/min, 18 readings = ~18min... adjust for actual density)
const threeHoursAgo = Date.now() - 3 * 3600000;
const baseline = data.find(r => r.dateutc >= threeHoursAgo)?.baromrelin;
if (recent == null || baseline == null) return;
const diff = recent - baseline;
const el = document.getElementById('sTrend');
if (!el) return;
if (diff > 0.02) { el.textContent = '↑'; el.title = `Rising +${diff.toFixed(3)} inHg in 3h`; el.style.color = 'var(--cool)'; }
else if (diff < -0.02) { el.textContent = '↓'; el.title = `Falling ${diff.toFixed(3)} inHg in 3h`; el.style.color = 'var(--accent)'; }
else { el.textContent = '→'; el.title = `Steady (${diff > 0 ? '+' : ''}${diff.toFixed(3)} inHg in 3h)`; el.style.color = 'var(--ink-light)'; }
} catch {}
}
// ── Rain totals + degree days ─────────────────────────────────────────────────
async function updateExtStats() {
try {
const [rt, dd, an] = await Promise.all([
fetch('/api/station/rain-totals').then(r => r.ok ? r.json() : null),
fetch('/api/station/degree-days?rangeMs=' + (30 * 86400000)).then(r => r.ok ? r.json() : null),
fetch('/api/station/anomaly').then(r => r.ok ? r.json() : null),
]);
if (rt) {
const s = (id, v) => { const e = document.getElementById(id); if (e) e.textContent = v != null ? v : '—'; };
s('sRain7d', rt.rain7d);
s('sRain30d', rt.rain30d);
s('sRainYTD', rt.rainYTD);
}
if (dd) {
document.getElementById('sHDD').textContent = dd.hdd;
document.getElementById('sCDD').textContent = dd.cdd;
}
if (an?.available) {
const tile = document.getElementById('sAnomalyTile');
tile.style.display = '';
const diff = an.currentTemp != null && an.mean != null ? (an.currentTemp - an.mean) : null;
document.getElementById('sAnomaly').textContent = an.anomaly === 'above' ? 'Above Normal' : an.anomaly === 'below' ? 'Below Normal' : 'Near Normal';
document.getElementById('sAnomalyNote').textContent = diff != null ? `${diff > 0 ? '+' : ''}${diff.toFixed(1)}°F vs avg` : '';
tile.className = 'stat' + (an.anomaly === 'above' ? ' anomaly-above' : an.anomaly === 'below' ? ' anomaly-below' : '');
}
} catch {}
}
// ── Records section ───────────────────────────────────────────────────────────
function fmtDate(ts) {
if (!ts) return '—';
return new Date(ts).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}
async function loadRecords() {
const panel = document.getElementById('recordsPanel');
if (!panel) return;
panel.addEventListener('toggle', async () => {
if (!panel.open) return;
const body = document.getElementById('recordsBody');
if (body.querySelector('.records-grid')) return; // already loaded
try {
const r = await fetch('/api/station/records');
if (!r.ok) { body.innerHTML = '<div class="status">No records yet.</div>'; return; }
const d = await r.json();
if (!d) { body.innerHTML = '<div class="status">No data recorded yet.</div>'; return; }
const since = d.firstReading ? `${d.totalReadings.toLocaleString()} readings since ${fmtDate(d.firstReading)}` : '';
body.innerHTML = `
<p style="font-size:0.8rem;color:var(--ink-light);margin-bottom:0.75rem">${since}</p>
<div class="records-grid">
<div class="record-item"><div class="record-label">Hottest</div><div class="record-val">${d.highTemp != null ? d.highTemp.toFixed(1) + '°F' : '—'}</div><div class="record-date">${fmtDate(d.highTempDate)}</div></div>
<div class="record-item"><div class="record-label">Coldest</div><div class="record-val">${d.lowTemp != null ? d.lowTemp.toFixed(1) + '°F' : '—'}</div><div class="record-date">${fmtDate(d.lowTempDate)}</div></div>
<div class="record-item"><div class="record-label">Highest Gust</div><div class="record-val">${d.highGust != null ? d.highGust.toFixed(1) + ' mph' : '—'}</div><div class="record-date">${fmtDate(d.highGustDate)}</div></div>
<div class="record-item"><div class="record-label">Highest Rain Rate</div><div class="record-val">${d.highRainRate != null ? d.highRainRate.toFixed(2) + ' in/hr' : '—'}</div><div class="record-date">${fmtDate(d.highRainRateDate)}</div></div>
<div class="record-item"><div class="record-label">Wettest Day</div><div class="record-val">${d.highDailyRain != null ? d.highDailyRain.toFixed(2) + '"' : '—'}</div><div class="record-date">${fmtDate(d.highDailyRainDate)}</div></div>
<div class="record-item"><div class="record-label">Highest UV</div><div class="record-val">${d.highUV != null ? d.highUV.toFixed(0) : '—'}</div><div class="record-date">${fmtDate(d.highUVDate)}</div></div>
<div class="record-item"><div class="record-label">Peak Solar</div><div class="record-val">${d.highSolar != null ? d.highSolar.toFixed(0) + ' W/m²' : '—'}</div><div class="record-date">${fmtDate(d.highSolarDate)}</div></div>
<div class="record-item"><div class="record-label">Highest Pressure</div><div class="record-val">${d.highPressure != null ? d.highPressure.toFixed(2) + ' inHg' : '—'}</div><div class="record-date">${fmtDate(d.highPressureDate)}</div></div>
<div class="record-item"><div class="record-label">Lowest Pressure</div><div class="record-val">${d.lowPressure != null ? d.lowPressure.toFixed(2) + ' inHg' : '—'}</div><div class="record-date">${fmtDate(d.lowPressureDate)}</div></div>
<div class="record-item"><div class="record-label">Highest Humidity</div><div class="record-val">${d.highHumidity != null ? d.highHumidity + '%' : '—'}</div><div class="record-date">${fmtDate(d.highHumidityDate)}</div></div>
<div class="record-item"><div class="record-label">Lowest Humidity</div><div class="record-val">${d.lowHumidity != null ? d.lowHumidity + '%' : '—'}</div><div class="record-date">${fmtDate(d.lowHumidityDate)}</div></div>
</div>`;
} catch { document.getElementById('recordsBody').innerHTML = '<div class="status error">Failed to load records.</div>'; }
}, { once: false });
}
// ── Year-over-year ────────────────────────────────────────────────────────────
let yoyEnabled = false;
let yoyData = null;
const yoyBtn = document.getElementById('yoyBtn');
yoyBtn.addEventListener('click', async () => {
yoyEnabled = !yoyEnabled;
yoyBtn.classList.toggle('active', yoyEnabled);
if (yoyEnabled && !yoyData) {
yoyBtn.textContent = '…';
try {
const r = await fetch(`/api/station/yoy?range=${currentRange}`);
yoyData = r.ok ? await r.json() : null;
} catch {}
yoyBtn.textContent = 'YoY';
}
loadHistory(currentRange);
});
// Show YoY button only for long ranges
function updateYoyVisibility(range) {
const longRange = ['1y','2y','3y'].includes(range);
yoyBtn.style.display = longRange ? '' : 'none';
if (!longRange) { yoyEnabled = false; yoyData = null; yoyBtn.classList.remove('active'); }
}
// Patch loadHistory to pass yoyData to renderCharts
const _origLoadHistory = loadHistory;
// Override renderCharts to accept yoy
const _origRenderCharts = renderCharts;
// ── CSV Export ────────────────────────────────────────────────────────────────
function updateExportLink() {
const sel = document.getElementById('exportRange');
const btn = document.getElementById('exportBtn');
if (sel && btn) btn.href = `/api/station/export.csv?range=${sel.value}`;
}
document.getElementById('exportRange')?.addEventListener('change', updateExportLink);
updateExportLink();
// ── Init all new features ─────────────────────────────────────────────────────
updateLatest();
updatePressureTrend();
updateExtStats();
loadRecords();
loadHistory(currentRange);
checkKeyStatus();
setInterval(updatePressureTrend, 120000);
setInterval(updateExtStats, 300000);
</script>
</body>
</html>
+168
View File
@@ -782,6 +782,14 @@ async function alertWatcherCron() {
await doNtfy(sub.ntfyTopic, '😷 Air Quality Alert', body);
}
}
// ── Rain rate (station only) ─────────────────────────────────────────
if (sub.thresholds.rainRate && stationObs?.rainratein != null && stationObs.rainratein > sub.thresholds.rainRate && !alerted.rainRate) {
alerted.rainRate = true;
const body = `Rain rate at ${stationObs.rainratein.toFixed(2)} in/hr — your threshold is ${sub.thresholds.rainRate} in/hr`;
await doWebPush(sub, { title: '🌧 Heavy Rain Alert', body, tag: 'rain-threshold', url: '/' });
await doNtfy(sub.ntfyTopic, '🌧 Heavy Rain Alert', body, 'high');
}
sub.lastThresholdAlerted = alerted;
saveSubs();
}
@@ -976,4 +984,164 @@ app.get('/api/station/backfill/status', requireDashboardAuth, (_req, res) => {
res.json(backfillState);
});
// ── Station analytics ─────────────────────────────────────────────────────────
// Records — scan all JSONL, cache 1h
let recordsCache = null;
let recordsCacheAt = 0;
function computeStationRecords() {
let files;
try { files = fs.readdirSync(STATION_DIR).filter(f => f.endsWith('.jsonl')).sort(); } catch { return null; }
if (!files.length) return null;
const rec = {
highTemp: null, highTempDate: null, lowTemp: null, lowTempDate: null,
highGust: null, highGustDate: null,
highRainRate: null, highRainRateDate: null, highDailyRain: null, highDailyRainDate: null,
highUV: null, highUVDate: null, highSolar: null, highSolarDate: null,
highPressure: null, highPressureDate: null, lowPressure: null, lowPressureDate: null,
highHumidity: null, highHumidityDate: null, lowHumidity: null, lowHumidityDate: null,
totalReadings: 0, firstReading: null, lastReading: null,
};
for (const file of files) {
try {
const lines = fs.readFileSync(path.join(STATION_DIR, file), 'utf8').split('\n').filter(Boolean);
for (const line of lines) {
try {
const r = JSON.parse(line);
if (!r.dateutc) continue;
rec.totalReadings++;
if (!rec.firstReading || r.dateutc < rec.firstReading) rec.firstReading = r.dateutc;
if (!rec.lastReading || r.dateutc > rec.lastReading) rec.lastReading = r.dateutc;
if (r.tempf != null) {
if (rec.highTemp == null || r.tempf > rec.highTemp) { rec.highTemp = r.tempf; rec.highTempDate = r.dateutc; }
if (rec.lowTemp == null || r.tempf < rec.lowTemp) { rec.lowTemp = r.tempf; rec.lowTempDate = r.dateutc; }
}
if (r.windgustmph != null && (rec.highGust == null || r.windgustmph > rec.highGust)) { rec.highGust = r.windgustmph; rec.highGustDate = r.dateutc; }
if (r.rainratein != null && (rec.highRainRate == null || r.rainratein > rec.highRainRate)) { rec.highRainRate = r.rainratein; rec.highRainRateDate = r.dateutc; }
if (r.dailyrainin != null && (rec.highDailyRain == null || r.dailyrainin > rec.highDailyRain)) { rec.highDailyRain = r.dailyrainin; rec.highDailyRainDate = r.dateutc; }
if (r.uv != null && (rec.highUV == null || r.uv > rec.highUV)) { rec.highUV = r.uv; rec.highUVDate = r.dateutc; }
if (r.solarradiation != null && (rec.highSolar == null || r.solarradiation > rec.highSolar)) { rec.highSolar = r.solarradiation; rec.highSolarDate = r.dateutc; }
if (r.baromrelin != null) {
if (rec.highPressure == null || r.baromrelin > rec.highPressure) { rec.highPressure = r.baromrelin; rec.highPressureDate = r.dateutc; }
if (rec.lowPressure == null || r.baromrelin < rec.lowPressure) { rec.lowPressure = r.baromrelin; rec.lowPressureDate = r.dateutc; }
}
if (r.humidity != null) {
if (rec.highHumidity == null || r.humidity > rec.highHumidity) { rec.highHumidity = r.humidity; rec.highHumidityDate = r.dateutc; }
if (rec.lowHumidity == null || r.humidity < rec.lowHumidity) { rec.lowHumidity = r.humidity; rec.lowHumidityDate = r.dateutc; }
}
} catch {}
}
} catch {}
}
return rec;
}
app.get('/api/station/records', requireDashboardAuth, (_req, res) => {
if (recordsCache && Date.now() - recordsCacheAt < 3600000) return res.json(recordsCache);
recordsCache = computeStationRecords();
recordsCacheAt = Date.now();
res.json(recordsCache);
});
// Rain totals — max dailyrainin per calendar day, summed
app.get('/api/station/rain-totals', requireDashboardAuth, (_req, res) => {
const now = Date.now();
const ytdCutoff = new Date(new Date().getFullYear(), 0, 1).getTime();
function sumDailyRain(readings) {
const byDay = {};
for (const r of readings) {
if (r.dailyrainin == null || !r.dateutc) continue;
const d = stationDateKey(r.dateutc);
if (byDay[d] == null || r.dailyrainin > byDay[d]) byDay[d] = r.dailyrainin;
}
return +Object.values(byDay).reduce((a, b) => a + b, 0).toFixed(2);
}
res.json({
rain7d: sumDailyRain(loadStationReadings(7 * 86400000)),
rain30d: sumDailyRain(loadStationReadings(30 * 86400000)),
rainYTD: sumDailyRain(loadStationReadings(now - ytdCutoff)),
});
});
// Heating/cooling degree days
app.get('/api/station/degree-days', requireDashboardAuth, (req, res) => {
const base = parseFloat(req.query.base || '65');
const rangeMs = Math.min(parseInt(req.query.rangeMs || String(30 * 86400000)), 365 * 86400000);
const readings = loadStationReadings(rangeMs);
const byDay = {};
for (const r of readings) {
if (r.tempf == null || !r.dateutc) continue;
const d = stationDateKey(r.dateutc);
if (!byDay[d]) byDay[d] = [];
byDay[d].push(r.tempf);
}
let hdd = 0, cdd = 0;
for (const temps of Object.values(byDay)) {
const avg = temps.reduce((a, b) => a + b, 0) / temps.length;
hdd += Math.max(0, base - avg);
cdd += Math.max(0, avg - base);
}
res.json({ hdd: +hdd.toFixed(1), cdd: +cdd.toFixed(1), base, days: Object.keys(byDay).length });
});
// CSV export
const RANGE_MS_MAP = { '1h': 3600000, '6h': 21600000, '24h': 86400000, '7d': 604800000, '30d': 2592000000, '90d': 7776000000, '1y': 31536000000, '2y': 63072000000, '3y': 94608000000 };
app.get('/api/station/export.csv', requireDashboardAuth, (req, res) => {
const range = req.query.range || '30d';
const readings = loadStationReadings(RANGE_MS_MAP[range] || RANGE_MS_MAP['30d']);
const cols = ['date','tempf','feelsLike','humidity','dewPoint','windspeedmph','windgustmph','winddir','baromrelin','baromabsin','rainratein','dailyrainin','weeklyrainin','monthlyrainin','uv','solarradiation','battout'];
const header = cols.join(',');
const rows = readings.map(r => cols.map(c => {
if (c === 'date') return new Date(r.dateutc).toISOString();
return r[c] == null ? '' : r[c];
}).join(','));
res.setHeader('Content-Type', 'text/csv');
res.setHeader('Content-Disposition', `attachment; filename="station-${range}-${new Date().toISOString().slice(0,10)}.csv"`);
res.send([header, ...rows].join('\n'));
});
// Year-over-year: current range + same range 1 year prior (timestamps shifted forward 1yr for chart overlay)
app.get('/api/station/yoy', requireDashboardAuth, (req, res) => {
const rangeMs = RANGE_MS_MAP[req.query.range] || RANGE_MS_MAP['1y'];
const YEAR_MS = 365.25 * 86400000;
const current = loadStationReadings(rangeMs);
const priorEnd = Date.now() - YEAR_MS;
const prior = loadStationReadings(rangeMs + YEAR_MS).filter(r => r.dateutc >= priorEnd - rangeMs && r.dateutc <= priorEnd);
const priorShifted = prior.map(r => ({ dateutc: Math.round(r.dateutc + YEAR_MS), tempf: r.tempf, humidity: r.humidity, windspeedmph: r.windspeedmph, baromrelin: r.baromrelin }));
res.json({ current: current.map(r => ({ dateutc: r.dateutc, tempf: r.tempf, humidity: r.humidity, windspeedmph: r.windspeedmph, baromrelin: r.baromrelin })), prior: priorShifted });
});
// Anomaly — hourly baseline from all historical data
app.get('/api/station/anomaly', requireDashboardAuth, (_req, res) => {
const all = loadStationReadings(365 * 86400000);
if (all.length < 200) return res.json({ available: false });
const byHour = Array.from({ length: 24 }, () => []);
for (const r of all) {
if (r.tempf == null) continue;
byHour[new Date(r.dateutc).getHours()].push(r.tempf);
}
const hourStats = byHour.map(temps => {
if (temps.length < 10) return null;
const mean = temps.reduce((a, b) => a + b) / temps.length;
const stddev = Math.sqrt(temps.reduce((a, b) => a + (b - mean) ** 2, 0) / temps.length);
return { mean: +mean.toFixed(1), stddev: +stddev.toFixed(1) };
});
const last = all[all.length - 1];
const h = new Date(last.dateutc).getHours();
const stat = hourStats[h];
const z = (stat && stat.stddev > 0) ? (last.tempf - stat.mean) / stat.stddev : 0;
res.json({ available: true, hourStats, anomaly: z > 2 ? 'above' : z < -2 ? 'below' : 'normal', currentTemp: last.tempf, currentHour: h, mean: stat?.mean, stddev: stat?.stddev });
});
// Public conditions page + API (no auth required)
app.get('/conditions', (_req, res) => {
res.sendFile(path.join(__dirname, 'public', 'conditions.html'));
});
app.get('/api/conditions/public', (_req, res) => {
if (!ambientServerConfig.apiKey) return res.status(503).json({ error: 'Not configured' });
const cached = ambientCaches.get(ambientServerConfig.apiKey);
res.json(cached?.data?.[0]?.lastData || null);
});
app.listen(PORT, () => console.log(`Weather app running on port ${PORT}`));