Update server.js

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

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