Update server.js

This commit is contained in:
JoshBaneyCS 2025-04-30 03:28:45 +00:00
parent dfa833e799
commit 100271e022

177
server.js
View File

@ -14,7 +14,12 @@ const PORT = process.env.PORT || 3000;
const shiftCounters = {}; const shiftCounters = {};
// ─── Helpers ───────────────────────────────────────────────────────────────── // ─── Helpers ─────────────────────────────────────────────────────────────────
// Format a millisecond timestamp into "M/D/YY @HH:mm" 24-hr in New York // pad two digits
function pad2(n) {
return n.toString().padStart(2, '0');
}
// Format an epochms timestamp for Slack: "M/D/YY @HH:mm" in America/New_York
function formatForSlack(epoch) { function formatForSlack(epoch) {
return new Date(epoch).toLocaleString('en-US', { return new Date(epoch).toLocaleString('en-US', {
timeZone: 'America/New_York', timeZone: 'America/New_York',
@ -26,37 +31,47 @@ function formatForSlack(epoch) {
minute: '2-digit' minute: '2-digit'
}).replace(',', ' @'); }).replace(',', ' @');
} }
// NOAA heat-index formula
// Compute NOAA heatindex
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 & period
// Determine Day/Night shift & rolling period key based on a JS epoch
function getShiftInfo(epoch) { function getShiftInfo(epoch) {
const estNow = new Date(epoch).toLocaleString('en-US',{timeZone:'America/New_York'}); // convert epoch to an EST Date object by roundtrip through toLocaleString
const d = new Date(estNow); const estString = new Date(epoch)
const h = d.getHours(), m = d.getMinutes(); .toLocaleString('en-US', { timeZone: 'America/New_York' });
let shift, start = new Date(d); 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 > 7 || (h === 7 && m >= 0)) {
if (h < 17 || (h === 17 && m < 30)) { if (h < 17 || (h === 17 && m < 30)) {
shift='Day'; start.setHours(7,0,0,0); shift = 'Day';
start.setHours(7, 0, 0, 0);
} else { } else {
shift='Night'; start.setHours(17,30,0,0); shift = 'Night';
start.setHours(17, 30, 0, 0);
} }
} else { } else {
shift = 'Night'; shift = 'Night';
start.setDate(start.getDate() - 1); start.setDate(start.getDate() - 1);
start.setHours(17, 30, 0, 0); start.setHours(17, 30, 0, 0);
} }
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, key, estNow:d }; return { shift, key, estNow: est };
} }
// Fetch weather
// Fetch current weather forecast for Baltimore
async function fetchCurrentWeather() { async function fetchCurrentWeather() {
const key = process.env.WEATHER_API_KEY, zip = process.env.ZIP_CODE; const key = process.env.WEATHER_API_KEY, zip = process.env.ZIP_CODE;
if (!key || !zip) return 'Unavailable'; if (!key || !zip) return 'Unavailable';
@ -66,17 +81,19 @@ async function fetchCurrentWeather(){
{ params: { zip:`${zip},us`, appid:key, units:'imperial' } } { 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());
return `${desc}. Hi of ${Math.round(data.main.temp_max)}, Humidity ${data.main.humidity}%`; const hi = Math.round(data.main.temp_max);
const hum = data.main.humidity;
return `${desc}. Hi of ${hi}, Humidity ${hum}%`;
} catch (e) { } catch (e) {
console.error('Weather API error',e.message); console.error('Weather API error:', e.message);
return 'Unavailable'; return 'Unavailable';
} }
} }
// ─── MariaDB Pool ───────────────────────────────────────────────────────────── // ─── MariaDB Pool & Table Setup ───────────────────────────────────────────────
const pool = mysql.createPool({ const pool = mysql.createPool({
host: process.env.DB_HOST, host: process.env.DB_HOST,
port: +process.env.DB_PORT||3306, port: parseInt(process.env.DB_PORT, 10) || 3306,
user: process.env.DB_USER, user: process.env.DB_USER,
password: process.env.DB_PASSWORD, password: process.env.DB_PASSWORD,
database: process.env.DB_NAME, database: process.env.DB_NAME,
@ -86,16 +103,20 @@ const pool = mysql.createPool({
connectTimeout: 10000 connectTimeout: 10000
}); });
// Ensure table exists (no-op if already ran above)
(async () => { (async () => {
// Create readings table with epoch_ms instead of timestamp
await pool.execute(` 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,
epoch_ms BIGINT NOT NULL, epoch_ms BIGINT NOT NULL,
temperature DOUBLE, humidity DOUBLE, heatIndex DOUBLE temperature DOUBLE,
); humidity DOUBLE,
heatIndex DOUBLE,
INDEX idx_time (epoch_ms),
INDEX idx_loc (location)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
`); `);
})(); })();
@ -115,19 +136,20 @@ app.get('/api/stream',(req,res)=>{
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 DockDoor Endpoint ───────────────────────────────────────────────── // ─── Dual Dock-Door Readings 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 epoch = Date.now();
const hiIn = computeHeatIndex(inT, inH); const hiIn = computeHeatIndex(inT, inH);
@ -136,29 +158,49 @@ app.post('/api/readings', async (req,res)=>{
shiftCounters[key] = (shiftCounters[key] || 0) + 1; shiftCounters[key] = (shiftCounters[key] || 0) + 1;
const period = shiftCounters[key]; const period = shiftCounters[key];
// insert both readings // Insert inbound and outbound
const ins = ` const insertSQL = `
INSERT INTO readings(location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex) INSERT INTO readings(location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex)
VALUES(?,?,?,?,?,?)`; VALUES (?, ?, ?, ?, ?, ?)
await pool.execute(ins,['Inbound', String(inD), epoch, inT, inH, hiIn]); `;
await pool.execute(ins,['Outbound',String(outD), epoch,outT,outH,hiOut]); await pool.execute(insertSQL, ['Inbound', String(inD), epoch, inT, inH, hiIn]);
await pool.execute(insertSQL, ['Outbound', String(outD), epoch, outT, outH, hiOut]);
// broadcast SSE // Broadcast via SSE
const slackTs = formatForSlack(epoch); const slackTs = formatForSlack(epoch);
broadcast('new-reading',{location:'Inbound',stationDockDoor:String(inD),timestamp:slackTs,temperature:inT,humidity:inH,heatIndex:hiIn}); broadcast('new-reading', {
broadcast('new-reading',{location:'Outbound',stationDockDoor:String(outD),timestamp:slackTs,temperature:outT,humidity:outH,heatIndex:hiOut}); 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 // Upload today's CSV
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(FROM_UNIXTIME(epoch_ms/1000))=CURDATE() ORDER BY epoch_ms` `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 {
catch(e){ console.error(e); } csvUrl = await uploadTrendsCsv(dateKey, rows);
} catch (e) {
console.error('CSV upload error:', e);
}
// Slack // Send Slack notification
const weather = await fetchCurrentWeather(); const weather = await fetchCurrentWeather();
const text = const text =
`*_${shift} shift Period ${period} dock/trailer temperature checks for ${slackTs}_*\n` + `*_${shift} shift Period ${period} dock/trailer temperature checks for ${slackTs}_*\n` +
@ -180,21 +222,22 @@ app.post('/api/readings', async (req,res)=>{
res.json({ success: true, shift, period, csvUrl }); res.json({ success: true, shift, period, csvUrl });
} catch (err) { } catch (err) {
console.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 Endpoint ─────────────────────────────────────────────────────── // ─── Area/Mod Station Readings 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 epoch = Date.now();
const hi = computeHeatIndex(T, H); const hi = computeHeatIndex(T, H);
const { shift, estNow } = getShiftInfo(epoch); const { shift, key, estNow } = getShiftInfo(epoch);
await pool.execute( await pool.execute(
`INSERT INTO readings(location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex) `INSERT INTO readings(location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex)
@ -203,17 +246,28 @@ app.post('/api/area-readings', async (req,res)=>{
); );
const slackTs = formatForSlack(epoch); const slackTs = formatForSlack(epoch);
broadcast('new-area-reading',{location:area,stationDockDoor:stationCode,timestamp:slackTs,temperature:T,humidity:H,heatIndex:hi}); broadcast('new-area-reading', {
location: area,
stationDockDoor: stationCode,
timestamp: slackTs,
temperature: T,
humidity: H,
heatIndex: hi
});
// CSV
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(FROM_UNIXTIME(epoch_ms/1000))=CURDATE() ORDER BY epoch_ms` `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 {
catch(e){ console.error(e); } csvUrl = await uploadTrendsCsv(dateKey, rows);
} catch (e) {
console.error('CSV upload error:', e);
}
const weather = await fetchCurrentWeather(); const weather = await fetchCurrentWeather();
const text = const text =
@ -232,27 +286,44 @@ app.post('/api/area-readings', async (req,res)=>{
res.json({ success: true, csvUrl }); res.json({ success: true, csvUrl });
} catch (err) { } catch (err) {
console.error(err); console.error('POST /api/area-readings error:', err);
res.status(500).json({ error: err.message }); res.status(500).json({ error: err.message });
} }
}); });
// ─── Fetch & Export ───────────────────────────────────────────────────────── // ─── Fetch All Readings ────────────────────────────────────────────────────────
app.get('/api/readings', async (req, res) => { app.get('/api/readings', async (req, res) => {
try {
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`); const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`);
res.json(rows); res.json(rows);
} catch (err) {
console.error('GET /api/readings error:', err);
res.status(500).json({ error: err.message });
}
}); });
// ─── Export CSV ───────────────────────────────────────────────────────────────
app.get('/api/export', async (req, res) => { app.get('/api/export', async (req, res) => {
try {
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`); 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,epoch_ms,temperature,humidity,heatIndex\n'); res.write('id,location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex\n');
rows.forEach(r => { rows.forEach(r => {
res.write(`${r.id},${r.location},${r.stationDockDoor},${r.epoch_ms},${r.temperature},${r.humidity},${r.heatIndex}\n`); res.write(
`${r.id},${r.location},${r.stationDockDoor},${r.epoch_ms},` +
`${r.temperature},${r.humidity},${r.heatIndex}\n`
);
}); });
res.end(); res.end();
} catch (err) {
console.error('GET /api/export error:', err);
res.status(500).send(err.message);
}
}); });
// ─── Start ─────────────────────────────────────────────────────────────────── // ─── Start Server ────────────────────────────────────────────────────────────
app.listen(PORT, ()=>console.log(`Server running on http://localhost:${PORT}`)); app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});