Update server.js

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

623
server.js
View File

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