Update server.js

This commit is contained in:
JoshBaneyCS 2025-04-30 02:37:58 +00:00
parent 8780fb2ea4
commit 04100e8d5f

185
server.js
View File

@ -10,73 +10,38 @@ const { uploadTrendsCsv } = require('./s3');
const app = express(); const app = express();
const PORT = process.env.PORT || 3000; const PORT = process.env.PORT || 3000;
// ─── Helpers ──────────────────────────────────────────────────────────────── // Inmemory shift counters
// Fetch current New York time (with DST) via worldtimeapi.org const shiftCounters = {};
async function getNYTime() {
try {
const res = await axios.get('http://worldtimeapi.org/api/timezone/America/New_York');
return new Date(res.data.datetime); // ISO string with offset
} catch (e) {
console.error('Time API error:', e.message);
return new Date(); // fallback to local clock
}
}
// Format a JS Date into "YYYY-MM-DD HH:mm:ss" in NY time for SQL DATETIME // ─── Helpers ─────────────────────────────────────────────────────────────────
function localDatetimeSQL(date) { // Format a millisecond timestamp into "M/D/YY @HH:mm" 24-hr in New York
// datePart = "YYYY-MM-DD" function formatForSlack(epoch) {
const datePart = new Intl.DateTimeFormat('en-CA', { return new Date(epoch).toLocaleString('en-US', {
timeZone: 'America/New_York',
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).format(date);
// timePart = "HH:MM:SS"
const timePart = new Intl.DateTimeFormat('en-GB', {
timeZone: 'America/New_York',
hour12: false,
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
}).format(date);
return `${datePart} ${timePart}`;
}
// Format a JS Date into "M/D/YY @HH:mm" (24-hour) for Slack
function shortEST(date) {
const dateFmt = new Intl.DateTimeFormat('en-US', {
timeZone: 'America/New_York', timeZone: 'America/New_York',
month: 'numeric', month: 'numeric',
day: 'numeric', day: 'numeric',
year: '2-digit' year: '2-digit',
});
const timeFmt = new Intl.DateTimeFormat('en-US', {
timeZone: 'America/New_York',
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 // 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
// Determine Day/Night shift and rolling period function getShiftInfo(epoch) {
function getShiftInfo(now) { const estNow = new Date(epoch).toLocaleString('en-US',{timeZone:'America/New_York'});
const est = new Date(now.toLocaleString('en-US',{timeZone:'America/New_York'})); const d = new Date(estNow);
const h = est.getHours(), m = est.getMinutes(); const h = d.getHours(), m = d.getMinutes();
let shift, start = new Date(est); let shift, start = new Date(d);
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);
@ -88,12 +53,10 @@ function getShiftInfo(now) {
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: est }; return { shift, key, estNow:d };
} }
// Fetch weather
// Fetch current weather 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';
@ -103,16 +66,14 @@ 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());
const hi = Math.round(data.main.temp_max); return `${desc}. Hi of ${Math.round(data.main.temp_max)}, Humidity ${data.main.humidity}%`;
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 & Table Setup ─────────────────────────────────────────────── // ─── MariaDB Pool ─────────────────────────────────────────────────────────────
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: +process.env.DB_PORT||3306,
@ -122,19 +83,19 @@ const pool = mysql.createPool({
waitForConnections:true, waitForConnections:true,
connectionLimit: 10, connectionLimit: 10,
queueLimit: 0, queueLimit: 0,
connectTimeout: 10000, connectTimeout: 10000
dateStrings: ['DATETIME']
}); });
;(async()=>{ // Ensure table exists (no-op if already ran above)
(async()=>{
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 AUTO_INCREMENT PRIMARY KEY,
location VARCHAR(20) NOT NULL, location VARCHAR(20) NOT NULL,
stationDockDoor VARCHAR(10) NOT NULL, stationDockDoor VARCHAR(10) NOT NULL,
timestamp DATETIME NOT NULL, epoch_ms BIGINT NOT NULL,
temperature DOUBLE, humidity DOUBLE, heatIndex DOUBLE temperature DOUBLE, humidity DOUBLE, heatIndex DOUBLE
) CHARSET=utf8mb4; );
`); `);
})(); })();
@ -145,16 +106,21 @@ app.use(express.static(path.join(__dirname,'public'), { index:'heatmap.html' }))
// ─── SSE Setup ──────────────────────────────────────────────────────────────── // ─── SSE Setup ────────────────────────────────────────────────────────────────
let clients = []; let clients = [];
app.get('/api/stream',(req,res)=>{ app.get('/api/stream',(req,res)=>{
res.set({ 'Content-Type':'text/event-stream', 'Cache-Control':'no-cache', Connection:'keep-alive' }); res.set({
res.flushHeaders(); clients.push(res); 'Content-Type':'text/event-stream',
req.on('close',()=> clients=clients.filter(c=>c!==res)); 'Cache-Control':'no-cache',
Connection:'keep-alive'
});
res.flushHeaders();
clients.push(res);
req.on('close',()=>{ clients = clients.filter(c=>c!==res); });
}); });
function broadcast(evt,data){ function broadcast(evt,data){
const msg = `event: ${evt}\ndata: ${JSON.stringify(data)}\n\n`; const msg = `event: ${evt}\ndata: ${JSON.stringify(data)}\n\n`;
clients.forEach(c=>c.write(msg)); clients.forEach(c=>c.write(msg));
} }
// ─── Dual Dock-Door Endpoint ───────────────────────────────────────────────── // ─── Dual DockDoor 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;
@ -163,42 +129,39 @@ app.post('/api/readings', async (req,res)=>{
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 hiIn = computeHeatIndex(inT,inH); const hiIn = computeHeatIndex(inT,inH);
const hiOut = computeHeatIndex(outT,outH); const hiOut = computeHeatIndex(outT,outH);
const now = await getNYTime(); const { shift, key, estNow } = getShiftInfo(epoch);
const { shift, key, estNow } = getShiftInfo(now);
shiftCounters[key] = (shiftCounters[key]||0)+1; shiftCounters[key] = (shiftCounters[key]||0)+1;
const period = shiftCounters[key]; const period = shiftCounters[key];
const sqlTs = localDatetimeSQL(estNow); // insert both readings
const shortTs = shortEST(estNow); const ins = `
INSERT INTO readings(location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex)
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( // broadcast SSE
`INSERT INTO readings(location,stationDockDoor,timestamp,temperature,humidity,heatIndex) const slackTs = formatForSlack(epoch);
VALUES(?,?,?,?,?,?)`, broadcast('new-reading',{location:'Inbound',stationDockDoor:String(inD),timestamp:slackTs,temperature:inT,humidity:inH,heatIndex:hiIn});
['Inbound',String(inD),sqlTs,inT,inH,hiIn] broadcast('new-reading',{location:'Outbound',stationDockDoor:String(outD),timestamp:slackTs,temperature:outT,humidity:outH,heatIndex:hiOut});
);
await pool.execute(
`INSERT INTO readings(location,stationDockDoor,timestamp,temperature,humidity,heatIndex)
VALUES(?,?,?,?,?,?)`,
['Outbound',String(outD),sqlTs,outT,outH,hiOut]
);
broadcast('new-reading',{location:'Inbound',stationDockDoor:String(inD),timestamp:shortTs,temperature:inT,humidity:inH,heatIndex:hiIn}); // CSV upload
broadcast('new-reading',{location:'Outbound',stationDockDoor:String(outD),timestamp:shortTs,temperature:outT,humidity:outH,heatIndex:hiOut}); const y=estNow.getFullYear(), m=pad2(estNow.getMonth()+1), d=pad2(estNow.getDate());
const dateKey = `${y}${m}${d}`;
// upload CSV
const [rows] = await pool.execute( const [rows] = await pool.execute(
`SELECT * FROM readings WHERE DATE(timestamp)=CURDATE() ORDER BY timestamp` `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( try { csvUrl = await uploadTrendsCsv(dateKey, rows); }
shortTs.slice(6,8)+shortTs.slice(0,2)+shortTs.slice(3,5), rows catch(e){ console.error(e); }
); }catch(_){}
// Slack
const weather = await fetchCurrentWeather(); const weather = await fetchCurrentWeather();
const text = const text =
`*_${shift} shift Period ${period} dock/trailer temperature checks for ${shortTs}_*\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`+
@ -229,32 +192,32 @@ app.post('/api/area-readings', async (req,res)=>{
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 hi = computeHeatIndex(T,H); const hi = computeHeatIndex(T,H);
const now = await getNYTime(); const { shift, estNow } = getShiftInfo(epoch);
const { shift, estNow } = getShiftInfo(now);
const sqlTs = localDatetimeSQL(estNow);
const shortTs = shortEST(estNow);
await pool.execute( await pool.execute(
`INSERT INTO readings(location,stationDockDoor,timestamp,temperature,humidity,heatIndex) `INSERT INTO readings(location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex)
VALUES(?,?,?,?,?,?)`, VALUES(?,?,?,?,?,?)`,
[area,stationCode,sqlTs,T,H,hi] [area, stationCode, epoch, T, H, hi]
); );
broadcast('new-area-reading',{location:area,stationDockDoor:stationCode,timestamp:shortTs,temperature:T,humidity:H,heatIndex:hi}); const slackTs = formatForSlack(epoch);
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 dateKey = `${y}${m}${d}`;
const [rows] = await pool.execute( const [rows] = await pool.execute(
`SELECT * FROM readings WHERE DATE(timestamp)=CURDATE() ORDER BY timestamp` `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( try { csvUrl = await uploadTrendsCsv(dateKey, rows); }
shortTs.slice(6,8)+shortTs.slice(0,2)+shortTs.slice(3,5), rows catch(e){ console.error(e); }
); }catch(_){}
const weather = await fetchCurrentWeather(); const weather = await fetchCurrentWeather();
const text = const text =
`*_${shift} shift ${area} temp check for ${shortTs}_*\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`+
@ -276,19 +239,19 @@ app.post('/api/area-readings', async (req,res)=>{
// ─── Fetch & Export ───────────────────────────────────────────────────────── // ─── Fetch & Export ─────────────────────────────────────────────────────────
app.get('/api/readings', async (req,res)=>{ app.get('/api/readings', async (req,res)=>{
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY timestamp`); const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`);
res.json(rows); res.json(rows);
}); });
app.get('/api/export', async (req,res)=>{ app.get('/api/export', async (req,res)=>{
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY timestamp`); 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,timestamp,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.timestamp},${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();
}); });
// ─── Start ─────────────────────────────────────────────────────────────────── // ─── Start ───────────────────────────────────────────────────────────────────
app.listen(PORT, ()=>console.log(`Server running http://localhost:${PORT}`)); app.listen(PORT, ()=>console.log(`Server running on http://localhost:${PORT}`));