Update server.js

This commit is contained in:
JoshBaneyCS 2025-04-30 03:55:03 +00:00
parent 6461fc8e85
commit ca7fd0c033

225
server.js
View File

@ -1,3 +1,4 @@
// server.js
require('dotenv').config(); require('dotenv').config();
const express = require('express'); const express = require('express');
const mysql = require('mysql2/promise'); const mysql = require('mysql2/promise');
@ -13,52 +14,42 @@ const PORT = process.env.PORT || 3000;
const shiftCounters = {}; const shiftCounters = {};
// ─── Helpers ────────────────────────────────────────────────────────────────── // ─── Helpers ──────────────────────────────────────────────────────────────────
// zero-pad // pad to two digits
const pad2 = n => n.toString().padStart(2,'0'); function pad2(n) {
return n.toString().padStart(2, '0');
}
// Format Date in EST as “M/D/YY @HH:mm” using Intl (no round-trip through string) // Format epoch_ms → "M/D/YY @HH:mm" (24-hour) in America/New_York
function shortEST(date) { function formatForSlack(epoch) {
const dateFmt = new Intl.DateTimeFormat('en-US', { return new Date(epoch).toLocaleString('en-US', {
timeZone: 'America/New_York', timeZone: 'America/New_York',
month: 'numeric', month: 'numeric',
day: 'numeric', day: 'numeric',
year: '2-digit' year: '2-digit',
});
const timeFmt = new Intl.DateTimeFormat('en-US', {
timeZone: 'America/New_York',
hour12: false, hour12: false,
hour: '2-digit', hour: '2-digit',
minute: '2-digit' minute: '2-digit'
}); }).replace(',', ' @');
return `${dateFmt.format(date)} @${timeFmt.format(date)}`;
}
// Format Date in EST as SQL DATETIME “YYYY-MM-DD HH:mm:ss”
function formatDateEST(date) {
const est = new Date(date.toLocaleString('en-US', { timeZone: 'America/New_York' }));
const Y = est.getFullYear();
const M = pad2(est.getMonth() + 1);
const D = pad2(est.getDate());
const h = pad2(est.getHours());
const m = pad2(est.getMinutes());
const s = pad2(est.getSeconds());
return `${Y}-${M}-${D} ${h}:${m}:${s}`;
} }
// NOAA heat-index formula // NOAA heat-index formula
function computeHeatIndex(T, R) { function computeHeatIndex(T, R) {
const [c1,c2,c3,c4,c5,c6,c7,c8,c9] = const [c1,c2,c3,c4,c5,c6,c7,c8,c9] = [
[-42.379,2.04901523,10.14333127,-0.22475541, -42.379,2.04901523,10.14333127,-0.22475541,
-0.00683783,-0.05481717,0.00122874,0.00085282,-0.00000199]; -0.00683783,-0.05481717,0.00122874,0.00085282,-0.00000199
];
const HI = c1 + c2*T + c3*R + c4*T*R const HI = c1 + c2*T + c3*R + c4*T*R
+ c5*T*T + c6*R*R + c7*T*T*R + c5*T*T + c6*R*R + c7*T*T*R
+ c8*T*R*R + c9*T*T*R*R; + c8*T*R*R + c9*T*T*R*R;
return Math.round(HI * 100) / 100; return Math.round(HI * 100) / 100;
} }
// Determine Day/Night shift and period key // Determine Day/Night shift & period key from epoch_ms
function getShiftInfo(now) { function getShiftInfo(epoch) {
const est = new Date(now.toLocaleString('en-US', { timeZone:'America/New_York' })); // 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(); const h = est.getHours(), m = est.getMinutes();
let shift, start = new Date(est); let shift, start = new Date(est);
@ -75,18 +66,18 @@ function getShiftInfo(now) {
} }
const key = `${shift}-${start.toISOString().slice(0,10)}-${start.getHours()}${start.getMinutes()}`; const key = `${shift}-${start.toISOString().slice(0,10)}-${start.getHours()}${start.getMinutes()}`;
return { shift, start, key, estNow: est }; return { shift, key, estNow: est };
} }
// Fetch current weather from OpenWeatherMap // Fetch current Baltimore weather
async function fetchCurrentWeather() { async function fetchCurrentWeather() {
const key = process.env.WEATHER_API_KEY; const key = process.env.WEATHER_API_KEY, zip = process.env.ZIP_CODE;
const zip = process.env.ZIP_CODE;
if (!key || !zip) return 'Unavailable'; if (!key || !zip) return 'Unavailable';
try { try {
const { data } = await axios.get('https://api.openweathermap.org/data/2.5/weather', { const { data } = await axios.get(
params: { zip: `${zip},us`, appid: key, units: 'imperial' } '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 desc = data.weather[0].description.replace(/^\w/,c=>c.toUpperCase());
const hi = Math.round(data.main.temp_max); const hi = Math.round(data.main.temp_max);
const hum = data.main.humidity; const hum = data.main.humidity;
@ -111,23 +102,25 @@ const pool = mysql.createPool({
}); });
(async () => { (async () => {
const sql = ` // Create table with epoch_ms only
await pool.execute(`
CREATE TABLE IF NOT EXISTS readings ( CREATE TABLE IF NOT EXISTS readings (
id INT AUTO_INCREMENT PRIMARY KEY, id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
location VARCHAR(20) NOT NULL, location VARCHAR(20) NOT NULL,
stationDockDoor VARCHAR(10) NOT NULL, stationDockDoor VARCHAR(10) NOT NULL,
timestamp DATETIME NOT NULL, epoch_ms BIGINT NOT NULL,
temperature DOUBLE, temperature DOUBLE,
humidity DOUBLE, humidity DOUBLE,
heatIndex DOUBLE heatIndex DOUBLE,
);`; INDEX idx_time (epoch_ms),
await pool.execute(sql); INDEX idx_loc (location)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
`);
})(); })();
// ─── Middleware & Static (default to heatmap.html) ─────────────────────────── // ─── Middleware & Static ─────────────────────────────────────────────────────
app.use(bodyParser.json()); app.use(bodyParser.json());
const publicDir = path.join(__dirname,'public'); app.use(express.static(path.join(__dirname,'public'), { index:'heatmap.html' }));
app.use(express.static(publicDir, { index: 'heatmap.html' }));
// ─── SSE Setup ──────────────────────────────────────────────────────────────── // ─── SSE Setup ────────────────────────────────────────────────────────────────
let clients = []; let clients = [];
@ -139,63 +132,73 @@ app.get('/api/stream',(req,res)=>{
}); });
res.flushHeaders(); res.flushHeaders();
clients.push(res); clients.push(res);
req.on('close',()=>clients = clients.filter(c=>c!==res)); req.on('close',()=>{ clients = clients.filter(c=>c!==res); });
}); });
function broadcast(evt,data){ function broadcast(event,data){
const msg = `event: ${evt}\ndata: ${JSON.stringify(data)}\n\n`; const msg = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
clients.forEach(c=>c.write(msg)); clients.forEach(c=>c.write(msg));
} }
// ─── Dual Dock-Door Readings Endpoint ──────────────────────────────────────── // ─── Dual Dock-Door Endpoint ───────────────────────────────────────────────────
app.post('/api/readings', async (req,res) => { app.post('/api/readings', async (req,res) => {
try { try {
const { inbound={}, outbound={} } = req.body; const { inbound={}, outbound={} } = req.body;
const { dockDoor: inD, temperature: inT, humidity: inH } = inbound; const { dockDoor: inD, temperature: inT, humidity: inH } = inbound;
const { dockDoor: outD, temperature: outT, humidity: outH } = outbound; const { dockDoor: outD, temperature: outT, humidity: outH } = outbound;
if ([inD,inT,inH,outD,outT,outH].some(v=>v==null)) if ([inD,inT,inH,outD,outT,outH].some(v=>v==null)) {
return res.status(400).json({ error: 'Missing fields' }); return res.status(400).json({ error: 'Missing fields' });
}
const epoch = Date.now();
const hiIn = computeHeatIndex(inT, inH); const hiIn = computeHeatIndex(inT, inH);
const hiOut = computeHeatIndex(outT, outH); const hiOut = computeHeatIndex(outT, outH);
const now = new Date(); const { shift, key, estNow } = getShiftInfo(epoch);
const { shift, key, estNow } = getShiftInfo(now);
shiftCounters[key] = (shiftCounters[key]||0) + 1; shiftCounters[key] = (shiftCounters[key]||0) + 1;
const period = shiftCounters[key]; const period = shiftCounters[key];
const slackTs = formatForSlack(epoch);
const sqlTs = formatDateEST(estNow); // Insert inbound + outbound
const shortTs = shortEST(estNow); const sql = `
INSERT INTO readings(location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex)
const insertSQL = ` VALUES(?,?,?,?,?,?)
INSERT INTO readings(location,stationDockDoor,timestamp,temperature,humidity,heatIndex) `;
VALUES(?,?,?,?,?,?)`; await pool.execute(sql, ['Inbound', String(inD), epoch, inT, inH, hiIn]);
await pool.execute(insertSQL, ['Inbound', String(inD), sqlTs, inT, inH, hiIn]); await pool.execute(sql, ['Outbound', String(outD), epoch, outT, outH, hiOut]);
await pool.execute(insertSQL, ['Outbound', String(outD), sqlTs, outT, outH, hiOut]);
// SSE broadcast
broadcast('new-reading', { broadcast('new-reading', {
location: 'Inbound', stationDockDoor:String(inD), location: 'Inbound',
timestamp: shortTs, temperature:inT, stationDockDoor: String(inD),
humidity: inH, heatIndex: hiIn timestamp: slackTs,
temperature: inT,
humidity: inH,
heatIndex: hiIn
}); });
broadcast('new-reading', { broadcast('new-reading', {
location:'Outbound', stationDockDoor:String(outD), location: 'Outbound',
timestamp: shortTs, temperature:outT, stationDockDoor: String(outD),
humidity: outH, heatIndex: hiOut timestamp: slackTs,
temperature: outT,
humidity: outH,
heatIndex: hiOut
}); });
// CSV Upload // CSV upload
const y=estNow.getFullYear(), m=pad2(estNow.getMonth()+1), d=pad2(estNow.getDate()); const y=estNow.getFullYear(), m=pad2(estNow.getMonth()+1), d=pad2(estNow.getDate());
const dateKey=`${y}${m}${d}`; const dateKey=`${y}${m}${d}`;
const [rows] = await pool.execute( const [rows] = await pool.execute(`
`SELECT * FROM readings WHERE DATE(timestamp)=CURDATE() ORDER BY timestamp` SELECT * FROM readings
); WHERE DATE(FROM_UNIXTIME(epoch_ms/1000))=CURDATE()
ORDER BY epoch_ms
`);
let csvUrl=null; let csvUrl=null;
try { csvUrl = await uploadTrendsCsv(dateKey, rows); } try { csvUrl = await uploadTrendsCsv(dateKey, rows); }
catch(e){ console.error('CSV upload error',e); } catch(e){ console.error('CSV upload error:', e); }
// Slack message
const weather = await fetchCurrentWeather(); const weather = await fetchCurrentWeather();
const text = const text =
`*_${shift} shift Period ${period} dock/ trailer temperature checks for ${shortTs}_*\n` + `*_${shift} shift Period ${period} dock/trailer temperature checks for ${slackTs}_*\n`+
`*_Current Weather Forecast for Baltimore: ${weather}_*\n\n`+ `*_Current Weather Forecast for Baltimore: ${weather}_*\n\n`+
`*_⬇ Inbound Dock Door 🚛 :_* ${inD}\n`+ `*_⬇ Inbound Dock Door 🚛 :_* ${inD}\n`+
`*_Temp:_* ${inT} °F 🌡️\n`+ `*_Temp:_* ${inT} °F 🌡️\n`+
@ -206,12 +209,9 @@ app.post('/api/readings', async (req,res) => {
`*_Humidity:_* ${outH} % 💦\n`+ `*_Humidity:_* ${outH} % 💦\n`+
`*_Heat Index:_* ${hiOut} °F 🥵`; `*_Heat Index:_* ${hiOut} °F 🥵`;
// Send to Slack workflow trigger await axios.post(process.env.SLACK_WEBHOOK_URL, { text }, {
await axios.post( headers:{ 'Content-Type':'application/json' }
process.env.SLACK_WEBHOOK_URL, });
{ text },
{ headers: {'Content-Type':'application/json'} }
);
res.json({ success:true, shift, period, csvUrl }); res.json({ success:true, shift, period, csvUrl });
} catch (err) { } catch (err) {
@ -220,55 +220,56 @@ app.post('/api/readings', async (req,res) => {
} }
}); });
// ─── Area/Mod Station Readings Endpoint ───────────────────────────────────── // ─── Area/Mod Endpoint ───────────────────────────────────────────────────────
app.post('/api/area-readings', async (req,res) => { app.post('/api/area-readings', async (req,res) => {
try { try {
const { area, stationCode, temperature:T, humidity:H } = req.body; const { area, stationCode, temperature:T, humidity:H } = req.body;
if (!area || !stationCode || T==null || H==null) if (!area||!stationCode||T==null||H==null) {
return res.status(400).json({ error:'Missing fields' }); return res.status(400).json({ error:'Missing fields' });
}
const epoch = Date.now();
const hi = computeHeatIndex(T, H); const hi = computeHeatIndex(T, H);
const now = new Date(); const { shift, key, estNow } = getShiftInfo(epoch);
const { shift, estNow } = getShiftInfo(now); const slackTs = formatForSlack(epoch);
const sqlTs = formatDateEST(estNow); await pool.execute(`
const shortTs = shortEST(estNow); INSERT INTO readings(location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex)
VALUES(?,?,?,?,?,?)
const insertSQL = ` `, [area, stationCode, epoch, T, H, hi]);
INSERT INTO readings(location,stationDockDoor,timestamp,temperature,humidity,heatIndex)
VALUES(?,?,?,?,?,?)`;
await pool.execute(insertSQL, [area, stationCode, sqlTs, T, H, hi]);
broadcast('new-area-reading', { broadcast('new-area-reading', {
location:area, stationDockDoor:stationCode, location: area,
timestamp:shortTs, temperature:T, stationDockDoor: stationCode,
humidity:H, heatIndex:hi timestamp: slackTs,
temperature: T,
humidity: H,
heatIndex: hi
}); });
const y=estNow.getFullYear(), m=pad2(estNow.getMonth()+1), d=pad2(estNow.getDate()); const y=estNow.getFullYear(), m=pad2(estNow.getMonth()+1), d=pad2(estNow.getDate());
const dateKey=`${y}${m}${d}`; const dateKey=`${y}${m}${d}`;
const [rows] = await pool.execute( const [rows] = await pool.execute(`
`SELECT * FROM readings WHERE DATE(timestamp)=CURDATE() ORDER BY timestamp` SELECT * FROM readings
); WHERE DATE(FROM_UNIXTIME(epoch_ms/1000))=CURDATE()
ORDER BY epoch_ms
`);
let csvUrl=null; let csvUrl=null;
try { csvUrl = await uploadTrendsCsv(dateKey, rows); } try { csvUrl = await uploadTrendsCsv(dateKey, rows); }
catch(e){ console.error('CSV upload error',e); } catch(e){ console.error('CSV upload error:', e); }
const weather = await fetchCurrentWeather(); const weather = await fetchCurrentWeather();
const text = const text =
`*_${shift} shift ${area} temp check for ${shortTs}_*\n` + `*_${shift} shift ${area} temp check for ${slackTs}_*\n`+
`*_Current Weather Forecast for Baltimore: ${weather}_*\n\n`+ `*_Current Weather Forecast for Baltimore: ${weather}_*\n\n`+
`*_${area.toUpperCase()} station:_* ${stationCode}\n`+ `*_${area.toUpperCase()} station:_* ${stationCode}\n`+
`*_Temp:_* ${T} °F 🌡️\n`+ `*_Temp:_* ${T} °F 🌡️\n`+
`*_Humidity:_* ${H} % 💦\n`+ `*_Humidity:_* ${H} % 💦\n`+
`*_Heat Index:_* ${hi} °F 🥵`; `*_Heat Index:_* ${hi} °F 🥵`;
await axios.post( await axios.post(process.env.SLACK_WEBHOOK_URL, { text }, {
process.env.SLACK_WEBHOOK_URL, headers:{ 'Content-Type':'application/json' }
{ text }, });
{ headers: {'Content-Type':'application/json'} }
);
res.json({ success:true, csvUrl }); res.json({ success:true, csvUrl });
} catch (err) { } catch (err) {
@ -277,10 +278,10 @@ app.post('/api/area-readings', async (req,res) => {
} }
}); });
// ─── GET all readings & CSV export ─────────────────────────────────────────── // ─── Fetch & Export ─────────────────────────────────────────────────────────
app.get('/api/readings', async (req,res) => { app.get('/api/readings', async (req,res) => {
try { try {
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY timestamp`); const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`);
res.json(rows); res.json(rows);
} catch (err) { } catch (err) {
console.error('GET /api/readings error:', err); console.error('GET /api/readings error:', err);
@ -289,13 +290,15 @@ app.get('/api/readings', async (req,res) => {
}); });
app.get('/api/export', async (req,res) => { app.get('/api/export', async (req,res) => {
try { try {
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY timestamp`); const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`);
res.setHeader('Content-disposition','attachment; filename=readings.csv'); res.setHeader('Content-disposition','attachment; filename=readings.csv');
res.set('Content-Type','text/csv'); res.set('Content-Type','text/csv');
res.write('id,location,stationDockDoor,timestamp,temperature,humidity,heatIndex\n'); res.write('id,location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex\n');
rows.forEach(r => { rows.forEach(r => {
const ts = (r.timestamp instanceof Date) ? formatDateEST(r.timestamp) : r.timestamp; res.write(
res.write(`${r.id},${r.location},${r.stationDockDoor},${ts},${r.temperature},${r.humidity},${r.heatIndex}\n`); `${r.id},${r.location},${r.stationDockDoor},${r.epoch_ms},` +
`${r.temperature},${r.humidity},${r.heatIndex}\n`
);
}); });
res.end(); res.end();
} catch (err) { } catch (err) {
@ -304,7 +307,7 @@ app.get('/api/export', async (req,res) => {
} }
}); });
// ─── Start Server ─────────────────────────────────────────────────────────── // ─── Start Server ───────────────────────────────────────────────────────────
app.listen(PORT, () => { app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`); console.log(`Server running on http://localhost:${PORT}`);
}); });