Update server.js

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

255
server.js
View File

@ -1,26 +1,25 @@
// 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 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 ──────────────────────────────────────────────────────────────────
// pad to two digits 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',
@ -30,23 +29,20 @@
hour: '2-digit', hour: '2-digit',
minute: '2-digit' minute: '2-digit'
}).replace(',', ' @'); }).replace(',', ' @');
} }
// 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 & period key from epoch_ms function getShiftInfo(epoch) {
function getShiftInfo(epoch) {
// Convert to EST by string-round-trip
const estString = new Date(epoch) const estString = new Date(epoch)
.toLocaleString('en-US', { timeZone: 'America/New_York' }); .toLocaleString('en-US', { timeZone: 'America/New_York' });
const est = new Date(estString); const est = new Date(estString);
@ -67,18 +63,18 @@
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: est }; return { shift, key, estNow: est };
} }
// 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( const { data } = await axios.get(
'https://api.openweathermap.org/data/2.5/weather', 'https://api.openweathermap.org/data/2.5/weather',
{ 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());
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;
return `${desc}. Hi of ${hi}, Humidity ${hum}%`; return `${desc}. Hi of ${hi}, Humidity ${hum}%`;
@ -86,12 +82,12 @@
console.error('Weather API error:', e.message); console.error('Weather API error:', e.message);
return 'Unavailable'; return 'Unavailable';
} }
} }
// ─── MariaDB Pool & Table Setup ─────────────────────────────────────────────── // ─── MariaDB Pool & Table Setup ───────────────────────────────────────────────
const pool = mysql.createPool({ const pool = mysql.createPool({
host: process.env.DB_HOST, host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT,10) || 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,
@ -99,10 +95,9 @@
connectionLimit: 10, connectionLimit: 10,
queueLimit: 0, queueLimit: 0,
connectTimeout: 10000 connectTimeout: 10000
}); });
(async () => { (async () => {
// Create table with epoch_ms only
await pool.execute(` await pool.execute(`
CREATE TABLE IF NOT EXISTS readings ( CREATE TABLE IF NOT EXISTS readings (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
@ -116,36 +111,59 @@
INDEX idx_loc (location) INDEX idx_loc (location)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
`); `);
})(); })();
// ─── Middleware & Static ───────────────────────────────────────────────────── // ─── Load trends.html template ────────────────────────────────────────────────
app.use(bodyParser.json()); const trendsTemplate = fs.readFileSync(
app.use(express.static(path.join(__dirname,'public'), { index:'heatmap.html' })); path.join(__dirname, 'public', 'trends.html'),
'utf8'
);
// ─── SSE Setup ──────────────────────────────────────────────────────────────── // ─── Inject initial data into trends.html ────────────────────────────────────
let clients = []; app.get('/trends.html', async (req, res) => {
app.get('/api/stream',(req,res)=>{ try {
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`);
const injected = trendsTemplate.replace(
'<!--INITIAL_DATA-->',
`<script>
window.__INITIAL_READINGS__ = ${JSON.stringify(rows)};
</script>`
);
res.send(injected);
} catch (err) {
console.error('Error rendering /trends.html:', err);
res.status(500).send('Server error');
}
});
// ─── Middleware & Static ─────────────────────────────────────────────────────
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public'), { index: 'heatmap.html' }));
// ─── SSE Setup ────────────────────────────────────────────────────────────────
let clients = [];
app.get('/api/stream', (req, res) => {
res.set({ res.set({
'Content-Type':'text/event-stream', 'Content-Type': 'text/event-stream',
'Cache-Control':'no-cache', 'Cache-Control': 'no-cache',
Connection:'keep-alive' Connection: 'keep-alive'
}); });
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(event,data){ function broadcast(event, data) {
const msg = `event: ${event}\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 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' });
} }
@ -153,19 +171,17 @@
const hiIn = computeHeatIndex(inT, inH); const hiIn = computeHeatIndex(inT, inH);
const hiOut = computeHeatIndex(outT, outH); const hiOut = computeHeatIndex(outT, outH);
const { shift, key, estNow } = getShiftInfo(epoch); const { shift, key, estNow } = getShiftInfo(epoch);
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 slackTs = formatForSlack(epoch);
// Insert inbound + outbound const insertSQL = `
const sql = `
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(sql, ['Inbound', String(inD), epoch, inT, inH, hiIn]); await pool.execute(insertSQL, ['Inbound', String(inD), epoch, inT, inH, hiIn]);
await pool.execute(sql, ['Outbound', String(outD), epoch, outT, outH, hiOut]); await pool.execute(insertSQL, ['Outbound', String(outD), epoch, outT, outH, hiOut]);
// SSE broadcast
broadcast('new-reading', { broadcast('new-reading', {
location: 'Inbound', location: 'Inbound',
stationDockDoor: String(inD), stationDockDoor: String(inD),
@ -183,49 +199,49 @@
heatIndex: hiOut heatIndex: hiOut
}); });
// 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 SELECT * FROM readings
WHERE DATE(FROM_UNIXTIME(epoch_ms/1000))=CURDATE() WHERE DATE(FROM_UNIXTIME(epoch_ms/1000)) = CURDATE()
ORDER BY epoch_ms 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 ${slackTs}_*\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` +
`*_Humidity:_* ${inH} % 💦\n`+ `*_Humidity:_* ${inH} % 💦\n` +
`*_Heat Index:_* ${hiIn} °F 🥵\n\n`+ `*_Heat Index:_* ${hiIn} °F 🥵\n\n` +
`*_⬆ Outbound Dock Door 🚛 :_* ${outD}\n`+ `*_⬆ Outbound Dock Door 🚛 :_* ${outD}\n` +
`*_Temp:_* ${outT} °F 🌡️\n`+ `*_Temp:_* ${outT} °F 🌡️\n` +
`*_Humidity:_* ${outH} % 💦\n`+ `*_Humidity:_* ${outH} % 💦\n` +
`*_Heat Index:_* ${hiOut} °F 🥵`; `*_Heat Index:_* ${hiOut} °F 🥵`;
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) {
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 Endpoint ─────────────────────────────────────────────────────── // ─── Area/Mod 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();
@ -235,7 +251,7 @@
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)
VALUES(?,?,?,?,?,?) VALUES (?, ?, ?, ?, ?, ?)
`, [area, stationCode, epoch, T, H, hi]); `, [area, stationCode, epoch, T, H, hi]);
broadcast('new-area-reading', { broadcast('new-area-reading', {
@ -247,39 +263,41 @@
heatIndex: hi 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 SELECT * FROM readings
WHERE DATE(FROM_UNIXTIME(epoch_ms/1000))=CURDATE() WHERE DATE(FROM_UNIXTIME(epoch_ms/1000)) = CURDATE()
ORDER BY epoch_ms 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 ${slackTs}_*\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(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, csvUrl }); res.json({ success: true, csvUrl });
} catch (err) { } catch (err) {
console.error('POST /api/area-readings 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 & Export Endpoints ─────────────────────────────────────────────────
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 epoch_ms`); const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`);
res.json(rows); res.json(rows);
@ -287,27 +305,26 @@
console.error('GET /api/readings error:', err); console.error('GET /api/readings error:', err);
res.status(500).json({ error: err.message }); res.status(500).json({ error: err.message });
} }
}); });
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 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( res.write(`${r.id},${r.location},${r.stationDockDoor},${r.epoch_ms},`
`${r.id},${r.location},${r.stationDockDoor},${r.epoch_ms},` + +`${r.temperature},${r.humidity},${r.heatIndex}\n`);
`${r.temperature},${r.humidity},${r.heatIndex}\n`
);
}); });
res.end(); res.end();
} catch (err) { } catch (err) {
console.error('GET /api/export error:', err); console.error('GET /api/export error:', err);
res.status(500).send(err.message); res.status(500).send(err.message);
} }
}); });
// ─── 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}`);
}); });