Update server.js

This commit is contained in:
JoshBaneyCS 2025-04-30 05:02:09 +00:00
parent 0c0fb30f9c
commit 054b1651d2

641
server.js
View File

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