Compare commits

...

19 Commits
0.1.0 ... main

Author SHA1 Message Date
f34be42792 sql bug fix?
This should fix the sql server issue with the server
2025-04-30 03:43:04 +00:00
66d95fb9c8 Update server.js 2025-04-30 03:34:08 +00:00
100271e022 Update server.js 2025-04-30 03:28:45 +00:00
dfa833e799 Update server.js 2025-04-30 03:04:12 +00:00
612ba2bb24 Update server.js 2025-04-30 02:58:54 +00:00
f0bacd9cde Update server.js 2025-04-30 02:54:22 +00:00
68b421bdac Update public/scripts/trends.js 2025-04-30 02:38:25 +00:00
04100e8d5f Update server.js 2025-04-30 02:37:58 +00:00
8780fb2ea4 Update public/scripts/trends.js 2025-04-30 02:29:04 +00:00
b584087a4e Update server.js 2025-04-30 02:28:32 +00:00
1c312ab0a5 Update public/scripts/trends.js 2025-04-30 02:21:43 +00:00
9283a6d31a Update server.js 2025-04-30 02:20:54 +00:00
bc3ff28ad2 Update server.js 2025-04-30 01:45:41 +00:00
ccc9818242 Update public/scripts/trends.js
time
2025-04-30 01:40:12 +00:00
6cdf71f4bc Update server.js
timing
2025-04-30 01:38:01 +00:00
fd85289d61 Update server.js
update time fromat
2025-04-30 01:30:26 +00:00
34dd53c0fd Update public/scripts/trends.js
fixed time formatting
2025-04-30 01:17:18 +00:00
1989484ec0 Update .env 2025-04-30 00:04:35 +00:00
7afc0a14c7 Update public/trends.html 2025-04-23 02:06:23 +00:00
4 changed files with 483 additions and 136 deletions

22
.env
View File

@ -1,10 +1,24 @@
# Server port
PORT=3000
WEATHER_API_KEY=27a2e8429bdc47104adb6572ef9f7ad9
ZIP_CODE=21224
# MariaDB connection
DB_CLIENT=mysql
DB_HOST=localhost
DB_HOST=172.23.0.3
DB_PORT=3306
DB_USER=your_db_user
DB_PASSWORD=your_db_password
DB_NAME=warehouse_heatmap
DB_USER=joshbaney
DB_PASSWORD=Ran0dal5!
DB_NAME=heatmap
#AWS s3
S3_BUCKET_URL=https://s3.amazonaws.com/bwi2temps/trends
# Slack & AWS creds
SLACK_WEBHOOK_URL=https://hooks.slack.com/triggers/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
AWS_ACCESS_KEY_ID=ihya/m4CONlywOPCNER22oZrbOeCdJLxp3R4H3oF
AWS_SECRET_ACCESS_KEY=AKIAQ3EGSIYOYP4L37HH
AWS_REGION=us-east-2
S3_BUCKET_NAME=bwi2temps
S3_BASE_URL=https://s3.amazonaws.com/bwi2temps/

View File

@ -1,40 +1,135 @@
const ctxD = document.getElementById('dailyChart').getContext('2d');
const ctxW = document.getElementById('weeklyChart').getContext('2d');
const ctxM = document.getElementById('monthlyChart').getContext('2d');
// public/scripts/trends.js
async function drawTrend(ctx, period) {
const all = await fetch('/api/readings').then(r=>r.json());
// group by day/week/month
const groups = {};
all.forEach(r => {
const d = new Date(r.timestamp);
let key;
if (period==='daily') key = d.toISOString().slice(0,10);
if (period==='weekly') key = `${d.getFullYear()}-W${Math.ceil(d.getDate()/7)}`;
if (period==='monthly') key = d.toISOString().slice(0,7);
groups[key] = groups[key]||[];
groups[key].push(r.heatIndex);
// ─── Timeframes ──────────────────────────────────────────────────────────────
const tfConfig = [
{ unit:'hours', count:24, label:'Last 24 Hours' },
{ unit:'days', count:7, label:'Last 7 Days' },
{ unit:'weeks', count:4, label:'Last 4 Weeks' },
{ unit:'months', count:12, label:'Last 12 Months' },
{ unit:'years', count:1, label:'All Time' }
];
// ─── Helpers ─────────────────────────────────────────────────────────────────
function formatEST(epoch) {
return new Date(epoch).toLocaleString('en-US', {
timeZone: 'America/New_York',
month: 'numeric',
day: 'numeric',
year: '2-digit',
hour12: false,
hour: '2-digit',
minute: '2-digit'
}).replace(',', ' @');
}
function subtract(date, count, unit) {
const d = new Date(date);
switch(unit){
case 'hours': d.setHours(d.getHours() - count); break;
case 'days': d.setDate(d.getDate() - count); break;
case 'weeks': d.setDate(d.getDate() - 7*count); break;
case 'months': d.setMonth(d.getMonth() - count); break;
case 'years': d.setFullYear(d.getFullYear() - count); break;
}
return d;
}
// ─── State ────────────────────────────────────────────────────────────────────
let readings = [];
let chart;
// ─── On Load ─────────────────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', async() => {
const data = await fetch('/api/readings').then(r=>r.json());
readings = data.map(r=>({
...r,
ts: formatEST(r.epoch_ms),
date: new Date(r.epoch_ms)
}));
setupUI(); initChart(); updateView();
});
// ─── UI Wiring ────────────────────────────────────────────────────────────────
function setupUI(){
const slider = document.getElementById('timeframe-slider');
const label = document.getElementById('timeframe-label');
slider.addEventListener('input',()=>{
label.textContent = tfConfig[slider.value].label;
updateView();
});
const labels = Object.keys(groups);
const data = labels.map(k => {
const arr = groups[k];
return {
max: Math.max(...arr),
min: Math.min(...arr),
avg: arr.reduce((a,b)=>a+b,0)/arr.length
};
label.textContent = tfConfig[slider.value].label;
document.getElementsByName('metric').forEach(cb=>cb.addEventListener('change',updateView));
document.querySelectorAll('#trends-table thead th.sortable').forEach(th=>{
th.addEventListener('click', ()=>{
const idx = th.cellIndex;
const asc = !th.classList.contains('asc');
const tbody = document.getElementById('trends-table-body');
const rows = Array.from(tbody.rows);
rows.sort((a,b)=>{
return asc
? a.cells[idx].textContent.localeCompare(b.cells[idx].textContent,undefined,{numeric:true})
: b.cells[idx].textContent.localeCompare(a.cells[idx].textContent,undefined,{numeric:true});
});
new Chart(ctx, {
type: 'line',
data: {
labels,
datasets: [
{ label: 'Max', data: data.map(x=>x.max) },
{ label: 'Avg', data: data.map(x=>x.avg) },
{ label: 'Min', data: data.map(x=>x.min) }
]
th.classList.toggle('asc',asc);
rows.forEach(r=>tbody.appendChild(r));
});
});
}
// ─── Chart.js Setup ──────────────────────────────────────────────────────────
function initChart(){
const ctx = document.getElementById('trend-chart').getContext('2d');
chart = new Chart(ctx,{
type:'line',
data:{labels:[],datasets:[]},
options:{
scales:{
x:{ title:{display:true,text:'Time (EST)'} },
y:{ title:{display:true,text:'Value'} }
},
interaction:{mode:'index',intersect:false},
plugins:{legend:{position:'top'}},
maintainAspectRatio:false
}
});
}
['daily','weekly','monthly'].forEach((p,i)=>drawTrend([ctxD,ctxW,ctxM][i], p));
// ─── Render ───────────────────────────────────────────────────────────────────
function updateView(){
const idx = +document.getElementById('timeframe-slider').value;
const {unit,count} = tfConfig[idx];
const cutoff = subtract(Date.now(),count,unit);
const filtered = readings.filter(r=>r.date>=cutoff);
const selected = Array.from(document.getElementsByName('metric'))
.filter(cb=>cb.checked).map(cb=>cb.value);
const labels = filtered.map(r=>r.ts);
const datasets = [];
if (selected.includes('temperature'))
datasets.push({ label:'Temperature (°F)', data:filtered.map(r=>r.temperature), tension:0.3 });
if (selected.includes('humidity'))
datasets.push({ label:'Humidity (%)', data:filtered.map(r=>r.humidity), tension:0.3 });
if (selected.includes('heatIndex'))
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();
const tbody = document.getElementById('trends-table-body');
tbody.innerHTML = '';
filtered.forEach(r=>{
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${r.ts}</td>
<td>${r.temperature.toFixed(1)}</td>
<td>${r.humidity.toFixed(1)}</td>
<td>${r.heatIndex.toFixed(2)}</td>
<td>${r.stationDockDoor}</td>
<td>${r.location}</td>
`;
tbody.appendChild(tr);
});
}

View File

@ -1,27 +1,78 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="/favicon.ico">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<link rel="stylesheet" href="styles.css">
<title>| Fuego - Heat Tracker</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
<link rel="stylesheet" href="styles.css" />
<!-- DataTables CSS for table styling, sorting arrows, etc. -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" />
<title>Trend Graph & Table</title>
</head>
<body>
<header class="main-header">
<img src="/image/logo.png" alt="Amazon Logo" class="logo">
<span class="header-title">| Fuego - Heat Tracker</span>
<img src="/image/logo.png" class="logo" alt="Amazon Logo" />
<span class="header-title"> | Fuego - Heat Tracker</span>
<button class="nav-btn" onclick="location.href='/input.html'">Log Reading</button>
<button class="nav-btn" onclick="location.href='/heatmap.html'">Heat Map</button>
<button class="nav-btn" onclick="location.href='/trends.html'">Trends</button>
</header>
<div class="page-container">
<canvas id="dailyChart"></canvas>
<canvas id="weeklyChart"></canvas>
<canvas id="monthlyChart"></canvas>
<h1>Trend Analysis</h1>
<div id="trend-controls" style="text-align:center; margin-bottom:1rem;">
<!-- Interval slider -->
<label for="periodSlider">
Interval: <strong><span id="periodLabel">Daily</span></strong>
</label><br/>
<input type="range" id="periodSlider" min="0" max="4" step="1" value="1" />
<!-- Metric/stat toggles -->
<div id="metricToggles" style="margin-top:1rem;">
<label><input type="checkbox" data-metric="temp" data-stat="avg" checked /> Temp Avg</label>
<label><input type="checkbox" data-metric="temp" data-stat="min" checked /> Temp Min</label>
<label><input type="checkbox" data-metric="temp" data-stat="max" checked /> Temp Max</label>
<label><input type="checkbox" data-metric="hum" data-stat="avg" checked /> Hum Avg</label>
<label><input type="checkbox" data-metric="hum" data-stat="min" checked /> Hum Min</label>
<label><input type="checkbox" data-metric="hum" data-stat="max" checked /> Hum Max</label>
<label><input type="checkbox" data-metric="hi" data-stat="avg" checked /> HI Avg</label>
<label><input type="checkbox" data-metric="hi" data-stat="min" checked /> HI Min</label>
<label><input type="checkbox" data-metric="hi" data-stat="max" checked /> HI Max</label>
</div>
</div>
<div class="chart-container">
<canvas id="trendChart"></canvas>
</div>
<!-- Table container -->
<div class="table-container">
<table id="trendTable" class="display" style="width:100%">
<thead>
<tr>
<th>Date/Time</th>
<th>Temperature (°F)</th>
<th>Humidity (%)</th>
<th>Heat Index</th>
<th>Location</th>
<th>Direction</th>
</tr>
</thead>
<tbody>
<!-- populated dynamically -->
</tbody>
</table>
</div>
</div>
<!-- Chart.js and zoom plugin -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@2.0.1/dist/chartjs-plugin-zoom.min.js"></script>
<!-- jQuery + DataTables -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<!-- Your trends logic -->
<script src="scripts/trends.js"></script>
</body>
</html>

351
server.js
View File

@ -1,126 +1,313 @@
// server.js
require('dotenv').config();
const express = require('express');
const mysql = require('mysql2/promise');
const bodyParser = require('body-parser');
const path = require('path');
const knex = require('knex');
const axios = require('axios');
// Initialize MariaDB connection via Knex
const db = knex({
client: process.env.DB_CLIENT,
connection: {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
}
});
const { uploadTrendsCsv } = require('./s3');
const app = express();
const PORT = process.env.PORT || 3000;
const slackWebhook = process.env.SLACK_WEBHOOK_URL;
// Create table if not exists, now with direction
(async () => {
if (!await db.schema.hasTable('readings')) {
await db.schema.createTable('readings', table => {
table.increments('id').primary();
table.integer('dockDoor');
table.string('direction');
table.timestamp('timestamp');
table.float('temperature');
table.float('humidity');
table.float('heatIndex');
});
}
})();
// In-memory shift counters
const shiftCounters = {};
// Compute heat index (NOAA formula)
// ─── Helpers ──────────────────────────────────────────────────────────────────
// pad to two digits
function pad2(n) {
return n.toString().padStart(2, '0');
}
// Format epoch_ms → "M/D/YY @HH:mm" (24-hour) in America/New_York
function formatForSlack(epoch) {
return new Date(epoch).toLocaleString('en-US', {
timeZone: 'America/New_York',
month: 'numeric',
day: 'numeric',
year: '2-digit',
hour12: false,
hour: '2-digit',
minute: '2-digit'
}).replace(',', ' @');
}
// NOAA heat-index formula
function computeHeatIndex(T, R) {
const c1 = -42.379, c2 = 2.04901523, c3 = 10.14333127;
const c4 = -0.22475541, c5 = -6.83783e-3, c6 = -5.481717e-2;
const c7 = 1.22874e-3, c8 = 8.5282e-4, c9 = -1.99e-6;
const HI = c1 + c2*T + c3*R + c4*T*R + c5*T*T + c6*R*R + c7*T*T*R + c8*T*R*R + c9*T*T*R*R;
const [c1,c2,c3,c4,c5,c6,c7,c8,c9] = [
-42.379,2.04901523,10.14333127,-0.22475541,
-0.00683783,-0.05481717,0.00122874,0.00085282,-0.00000199
];
const HI = c1 + c2*T + c3*R + c4*T*R
+ c5*T*T + c6*R*R + c7*T*T*R
+ c8*T*R*R + c9*T*T*R*R;
return Math.round(HI * 100) / 100;
}
// Determine direction based on door number
function getDirection(door) {
door = Number(door);
if (door >= 124 && door <= 138) return 'Inbound';
if (door >= 142 && door <= 201) return 'Outbound';
if (door >= 202 && door <= 209) return 'Inbound';
return 'Unknown';
// Determine Day/Night shift & period key from epoch_ms
function getShiftInfo(epoch) {
// Convert to EST by string-round-trip
const estString = new Date(epoch)
.toLocaleString('en-US', { timeZone: 'America/New_York' });
const est = new Date(estString);
const h = est.getHours(), m = est.getMinutes();
let shift, start = new Date(est);
if (h > 7 || (h === 7 && m >= 0)) {
if (h < 17 || (h === 17 && m < 30)) {
shift = 'Day'; start.setHours(7, 0, 0, 0);
} else {
shift = 'Night'; start.setHours(17, 30, 0, 0);
}
} else {
shift = 'Night';
start.setDate(start.getDate() - 1);
start.setHours(17, 30, 0, 0);
}
const key = `${shift}-${start.toISOString().slice(0,10)}-${start.getHours()}${start.getMinutes()}`;
return { shift, key, estNow: est };
}
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
// Fetch current Baltimore weather
async function fetchCurrentWeather() {
const key = process.env.WEATHER_API_KEY, zip = process.env.ZIP_CODE;
if (!key || !zip) return 'Unavailable';
try {
const { data } = await axios.get(
'https://api.openweathermap.org/data/2.5/weather',
{ params: { zip:`${zip},us`, appid:key, units:'imperial' } }
);
const desc = data.weather[0].description.replace(/^\w/,c=>c.toUpperCase());
const hi = Math.round(data.main.temp_max);
const hum = data.main.humidity;
return `${desc}. Hi of ${hi}, Humidity ${hum}%`;
} catch (e) {
console.error('Weather API error:', e.message);
return 'Unavailable';
}
}
// ─── MariaDB Pool & Table Setup ───────────────────────────────────────────────
const pool = mysql.createPool({
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT,10) || 3306,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
connectTimeout: 10000
});
(async () => {
// Create table with epoch_ms only
await pool.execute(`
CREATE TABLE IF NOT EXISTS readings (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
location VARCHAR(20) NOT NULL,
stationDockDoor VARCHAR(10) NOT NULL,
epoch_ms BIGINT NOT NULL,
temperature DOUBLE,
humidity DOUBLE,
heatIndex DOUBLE,
INDEX idx_time (epoch_ms),
INDEX idx_loc (location)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
`);
})();
// ─── Middleware & Static ─────────────────────────────────────────────────────
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname,'public'), { index:'heatmap.html' }));
// ─── SSE Setup ────────────────────────────────────────────────────────────────
let clients = [];
app.get('/api/stream', (req, res) => {
res.set({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
app.get('/api/stream',(req,res)=>{
res.set({
'Content-Type':'text/event-stream',
'Cache-Control':'no-cache',
Connection:'keep-alive'
});
res.flushHeaders();
clients.push(res);
req.on('close', () => { clients = clients.filter(c => c !== res); });
req.on('close',()=>{ clients = clients.filter(c=>c!==res); });
});
function broadcast(event, data) {
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
clients.forEach(res => res.write(payload));
function broadcast(event,data){
const msg = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
clients.forEach(c=>c.write(msg));
}
app.post('/api/readings', async (req, res) => {
// ─── Dual Dock-Door Endpoint ───────────────────────────────────────────────────
app.post('/api/readings', async (req,res) => {
try {
const { inbound, outbound } = req.body; // each: {dockDoor,temperature,humidity}
const timestamp = new Date();
const entries = [inbound, outbound].map(r => {
const direction = getDirection(r.dockDoor);
const heatIndex = computeHeatIndex(r.temperature, r.humidity);
return { ...r, direction, timestamp, heatIndex };
});
// Insert both
const ids = await db('readings').insert(entries);
const saved = entries.map((e, i) => ({ id: ids[i], ...e }));
// Broadcast and respond
saved.forEach(reading => broadcast('new-reading', reading));
// Slack notification with both
if (slackWebhook) {
const textLines = saved.map(r =>
`Door *${r.dockDoor}* (${r.direction}) Temp: ${r.temperature}°F, Humidity: ${r.humidity}%, HI: ${r.heatIndex}`
);
await axios.post(slackWebhook, { text: 'New dual readings:\n' + textLines.join('\n') });
const { inbound={}, outbound={} } = req.body;
const { dockDoor: inD, temperature: inT, humidity: inH } = inbound;
const { dockDoor: outD, temperature: outT, humidity: outH } = outbound;
if ([inD,inT,inH,outD,outT,outH].some(v=>v==null)) {
return res.status(400).json({ error: 'Missing fields' });
}
res.json(saved);
const epoch = Date.now();
const hiIn = computeHeatIndex(inT, inH);
const hiOut = computeHeatIndex(outT, outH);
const { shift, key, estNow } = getShiftInfo(epoch);
shiftCounters[key] = (shiftCounters[key]||0) + 1;
const period = shiftCounters[key];
const slackTs = formatForSlack(epoch);
// Insert inbound + outbound
const sql = `
INSERT INTO readings(location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex)
VALUES(?,?,?,?,?,?)
`;
await pool.execute(sql, ['Inbound', String(inD), epoch, inT, inH, hiIn]);
await pool.execute(sql, ['Outbound', String(outD), epoch, outT, outH, hiOut]);
// SSE broadcast
broadcast('new-reading', {
location: 'Inbound',
stationDockDoor: String(inD),
timestamp: slackTs,
temperature: inT,
humidity: inH,
heatIndex: hiIn
});
broadcast('new-reading', {
location: 'Outbound',
stationDockDoor: String(outD),
timestamp: slackTs,
temperature: outT,
humidity: outH,
heatIndex: hiOut
});
// CSV upload
const y=estNow.getFullYear(), m=pad2(estNow.getMonth()+1), d=pad2(estNow.getDate());
const dateKey=`${y}${m}${d}`;
const [rows] = await pool.execute(`
SELECT * FROM readings
WHERE DATE(FROM_UNIXTIME(epoch_ms/1000))=CURDATE()
ORDER BY epoch_ms
`);
let csvUrl=null;
try { csvUrl = await uploadTrendsCsv(dateKey, rows); }
catch(e){ console.error('CSV upload error:', e); }
// Slack message
const weather = await fetchCurrentWeather();
const text =
`*_${shift} shift Period ${period} dock/trailer temperature checks for ${slackTs}_*\n`+
`*_Current Weather Forecast for Baltimore: ${weather}_*\n\n`+
`*_⬇ Inbound Dock Door 🚛 :_* ${inD}\n`+
`*_Temp:_* ${inT} °F 🌡️\n`+
`*_Humidity:_* ${inH} % 💦\n`+
`*_Heat Index:_* ${hiIn} °F 🥵\n\n`+
`*_⬆ Outbound Dock Door 🚛 :_* ${outD}\n`+
`*_Temp:_* ${outT} °F 🌡️\n`+
`*_Humidity:_* ${outH} % 💦\n`+
`*_Heat Index:_* ${hiOut} °F 🥵`;
await axios.post(process.env.SLACK_WEBHOOK_URL, { text }, {
headers:{ 'Content-Type':'application/json' }
});
res.json({ success:true, shift, period, csvUrl });
} catch (err) {
console.error('Error saving readings or sending Slack:', err);
console.error('POST /api/readings error:', err);
res.status(500).json({ error: err.message });
}
});
app.get('/api/readings', async (req, res) => {
// ─── Area/Mod Endpoint ───────────────────────────────────────────────────────
app.post('/api/area-readings', async (req,res) => {
try {
const rows = await db('readings').orderBy('timestamp', 'asc');
const { area, stationCode, temperature:T, humidity:H } = req.body;
if (!area||!stationCode||T==null||H==null) {
return res.status(400).json({ error:'Missing fields' });
}
const epoch = Date.now();
const hi = computeHeatIndex(T, H);
const { shift, key, estNow } = getShiftInfo(epoch);
const slackTs = formatForSlack(epoch);
await pool.execute(`
INSERT INTO readings(location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex)
VALUES(?,?,?,?,?,?)
`, [area, stationCode, epoch, T, H, hi]);
broadcast('new-area-reading', {
location: area,
stationDockDoor: stationCode,
timestamp: slackTs,
temperature: T,
humidity: H,
heatIndex: hi
});
const y=estNow.getFullYear(), m=pad2(estNow.getMonth()+1), d=pad2(estNow.getDate());
const dateKey=`${y}${m}${d}`;
const [rows] = await pool.execute(`
SELECT * FROM readings
WHERE DATE(FROM_UNIXTIME(epoch_ms/1000))=CURDATE()
ORDER BY epoch_ms
`);
let csvUrl=null;
try { csvUrl = await uploadTrendsCsv(dateKey, rows); }
catch(e){ console.error('CSV upload error:', e); }
const weather = await fetchCurrentWeather();
const text =
`*_${shift} shift ${area} temp check for ${slackTs}_*\n`+
`*_Current Weather Forecast for Baltimore: ${weather}_*\n\n`+
`*_${area.toUpperCase()} station:_* ${stationCode}\n`+
`*_Temp:_* ${T} °F 🌡️\n`+
`*_Humidity:_* ${H} % 💦\n`+
`*_Heat Index:_* ${hi} °F 🥵`;
await axios.post(process.env.SLACK_WEBHOOK_URL, { text }, {
headers:{ 'Content-Type':'application/json' }
});
res.json({ success:true, csvUrl });
} catch (err) {
console.error('POST /api/area-readings error:', err);
res.status(500).json({ error: err.message });
}
});
// ─── Fetch & Export ─────────────────────────────────────────────────────────
app.get('/api/readings', async (req,res) => {
try {
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`);
res.json(rows);
} catch (err) {
console.error('GET /api/readings error:', err);
res.status(500).json({ error: err.message });
}
});
app.get('/api/export', async (req, res) => {
app.get('/api/export', async (req,res) => {
try {
const rows = await db('readings').orderBy('timestamp', 'asc');
res.setHeader('Content-disposition', 'attachment; filename=readings.csv');
res.set('Content-Type', 'text/csv');
res.write('id,dockDoor,direction,timestamp,temperature,humidity,heatIndex\n');
rows.forEach(r =>
res.write(`${r.id},${r.dockDoor},${r.direction},${r.timestamp},${r.temperature},${r.humidity},${r.heatIndex}\n`)
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`);
res.setHeader('Content-disposition','attachment; filename=readings.csv');
res.set('Content-Type','text/csv');
res.write('id,location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex\n');
rows.forEach(r => {
res.write(
`${r.id},${r.location},${r.stationDockDoor},${r.epoch_ms},` +
`${r.temperature},${r.humidity},${r.heatIndex}\n`
);
});
res.end();
} catch (err) {
console.error('GET /api/export error:', err);
res.status(500).send(err.message);
}
});
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
// ─── Start Server ────────────────────────────────────────────────────────────
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});