Update server.js

This commit is contained in:
JoshBaneyCS 2025-04-30 02:28:32 +00:00
parent 1c312ab0a5
commit b584087a4e

167
server.js
View File

@ -11,10 +11,18 @@ const app = express();
const PORT = process.env.PORT || 3000;
// ─── Helpers ────────────────────────────────────────────────────────────────
// zero-pad
const pad2 = n => n.toString().padStart(2,'0');
// Fetch current New York time (with DST) via worldtimeapi.org
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
}
}
// Build an SQLcompatible DATETIME string in America/New_York (with DST)
// Format a JS Date into "YYYY-MM-DD HH:mm:ss" in NY time for SQL DATETIME
function localDatetimeSQL(date) {
// datePart = "YYYY-MM-DD"
const datePart = new Intl.DateTimeFormat('en-CA', {
@ -34,7 +42,7 @@ function localDatetimeSQL(date) {
return `${datePart} ${timePart}`;
}
// Format a Date in EST as “M/D/YY @HH:mm” (24-hour, for Slack)
// 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',
@ -53,9 +61,10 @@ function shortEST(date) {
// NOAA heat-index formula
function computeHeatIndex(T, R) {
const [c1,c2,c3,c4,c5,c6,c7,c8,c9] =
[-42.379,2.04901523,10.14333127,-0.22475541,
-0.00683783,-0.05481717,0.00122874,0.00085282,-0.00000199];
const [c1,c2,c3,c4,c5,c6,c7,c8,c9] = [
-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
+ c8*T*R*R + c9*T*T*R*R;
@ -64,8 +73,8 @@ function computeHeatIndex(T, R) {
// Determine Day/Night shift and rolling period
function getShiftInfo(now) {
const est = new Date(now.toLocaleString('en-US', { timeZone:'America/New_York' }));
const h = est.getHours(), m = est.getMinutes();
const est = new Date(now.toLocaleString('en-US',{timeZone:'America/New_York'}));
const h = est.getHours(), m = est.getMinutes();
let shift, start = new Date(est);
if (h > 7 || (h === 7 && m >= 0)) {
@ -84,15 +93,14 @@ function getShiftInfo(now) {
return { shift, key, estNow: est };
}
// Fetch current Baltimore forecast
// Fetch current weather for Baltimore
async function fetchCurrentWeather() {
const key = process.env.WEATHER_API_KEY;
const zip = process.env.ZIP_CODE;
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' } }
{ 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);
@ -104,59 +112,50 @@ async function fetchCurrentWeather() {
}
}
// ─── MariaDB Pool ─────────────────────────────────────────────────────────────
// ─── MariaDB Pool & Table Setup ───────────────────────────────────────────────
const pool = mysql.createPool({
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT,10)||3306,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
connectTimeout: 10000,
dateStrings: ['DATETIME'] // ensure we get raw strings back
host: process.env.DB_HOST,
port: +process.env.DB_PORT||3306,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
waitForConnections:true,
connectionLimit: 10,
queueLimit: 0,
connectTimeout: 10000,
dateStrings: ['DATETIME']
});
// Ensure table exists
(async () => {
const sql = `
;(async()=>{
await pool.execute(`
CREATE TABLE IF NOT EXISTS readings (
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);
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
) CHARSET=utf8mb4;
`);
})();
// ─── Middleware & Static ─────────────────────────────────────────────────────
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname,'public'), { index: 'heatmap.html' }));
app.use(express.static(path.join(__dirname,'public'), { index:'heatmap.html' }));
// ─── SSE Setup ────────────────────────────────────────────────────────────────
let clients = [];
app.get('/api/stream',(req,res)=>{
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); });
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(evt,data){
const msg = `event: ${evt}\ndata: ${JSON.stringify(data)}\n\n`;
clients.forEach(c=>c.write(msg));
}
// ─── Dual Dock-Door Endpoint ─────────────────────────────────────────────────
app.post('/api/readings', async (req,res) => {
// ─── Dual Dock-Door Endpoint ─────────────────────────────────────────────────
app.post('/api/readings', async (req,res)=>{
try {
const { inbound={}, outbound={} } = req.body;
const { dockDoor: inD, temperature: inT, humidity: inH } = inbound;
@ -164,41 +163,42 @@ app.post('/api/readings', async (req,res) => {
if ([inD,inT,inH,outD,outT,outH].some(v=>v==null))
return res.status(400).json({ error:'Missing fields' });
// compute
const hiIn = computeHeatIndex(inT,inH);
const hiOut = computeHeatIndex(outT,outH);
const now = new Date();
const now = await getNYTime();
const { shift, key, estNow } = getShiftInfo(now);
shiftCounters[key] = (shiftCounters[key]||0)+1;
shiftCounters[key] = (shiftCounters[key]||0) +1;
const period = shiftCounters[key];
// timestamps
const sqlTs = localDatetimeSQL(estNow);
const shortTs = shortEST(estNow);
// insert
const ins = `
INSERT INTO readings
(location,stationDockDoor,timestamp,temperature,humidity,heatIndex)
VALUES(?,?,?,?,?,?)`;
await pool.execute(ins, ['Inbound', String(inD), sqlTs, inT, inH, hiIn]);
await pool.execute(ins, ['Outbound', String(outD), sqlTs, outT, outH, hiOut]);
await pool.execute(
`INSERT INTO readings(location,stationDockDoor,timestamp,temperature,humidity,heatIndex)
VALUES(?,?,?,?,?,?)`,
['Inbound',String(inD),sqlTs,inT,inH,hiIn]
);
await pool.execute(
`INSERT INTO readings(location,stationDockDoor,timestamp,temperature,humidity,heatIndex)
VALUES(?,?,?,?,?,?)`,
['Outbound',String(outD),sqlTs,outT,outH,hiOut]
);
// SSE
broadcast('new-reading', { location:'Inbound', stationDockDoor:String(inD), timestamp:shortTs, temperature:inT, humidity:inH, heatIndex:hiIn });
broadcast('new-reading', { location:'Outbound', stationDockDoor:String(outD), timestamp:shortTs, temperature:outT, humidity:outH, heatIndex:hiOut });
broadcast('new-reading',{location:'Inbound',stationDockDoor:String(inD),timestamp:shortTs,temperature:inT,humidity:inH,heatIndex:hiIn});
broadcast('new-reading',{location:'Outbound',stationDockDoor:String(outD),timestamp:shortTs,temperature:outT,humidity:outH,heatIndex:hiOut});
// upload CSV
const y=estNow.getFullYear(), m=pad2(estNow.getMonth()+1), d=pad2(estNow.getDate());
const dateKey = `${y}${m}${d}`;
const [rows] = await pool.execute(`SELECT * FROM readings WHERE DATE(timestamp)=CURDATE() ORDER BY timestamp`);
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(e)}
try{ csvUrl = await uploadTrendsCsv(
shortTs.slice(6,8)+shortTs.slice(0,2)+shortTs.slice(3,5), rows
); }catch(_){}
// weather + Slack
const weather = await fetchCurrentWeather();
const text =
`*_${shift} shift Period ${period} dock/ trailer temperature checks for ${shortTs}_*\n`+
`*_${shift} shift Period ${period} dock/trailer temperature checks for ${shortTs}_*\n`+
`*_Current Weather Forecast for Baltimore: ${weather}_*\n\n`+
`*_⬇ Inbound Dock Door 🚛 :_* ${inD}\n`+
`*_Temp:_* ${inT} °F 🌡️\n`+
@ -216,38 +216,41 @@ app.post('/api/readings', async (req,res) => {
);
res.json({ success:true, shift, period, csvUrl });
} catch(err) {
} catch (err) {
console.error(err);
res.status(500).json({ error: err.message });
}
});
// ─── Area/Mod Endpoint ───────────────────────────────────────────────────────
app.post('/api/area-readings', async (req,res) => {
app.post('/api/area-readings', async (req,res)=>{
try {
const { area, stationCode, temperature:T, humidity:H } = req.body;
if (!area||!stationCode||T==null||H==null)
return res.status(400).json({ error:'Missing fields' });
const hi = computeHeatIndex(T,H);
const now = new Date();
const now = await getNYTime();
const { shift, estNow } = getShiftInfo(now);
const sqlTs = localDatetimeSQL(estNow);
const shortTs = shortEST(estNow);
await pool.execute(
`INSERT INTO readings(location,stationDockDoor,timestamp,temperature,humidity,heatIndex)
VALUES(?,?,?,?,?,?)`,
[area, stationCode, sqlTs, T, H, hi]
[area,stationCode,sqlTs,T,H,hi]
);
broadcast('new-area-reading', { location:area, stationDockDoor:stationCode, timestamp:shortTs, temperature:T, humidity:H, heatIndex:hi });
broadcast('new-area-reading',{location:area,stationDockDoor:stationCode,timestamp:shortTs,temperature:T,humidity:H,heatIndex:hi});
const y=estNow.getFullYear(), m=pad2(estNow.getMonth()+1), d=pad2(estNow.getDate());
const dateKey = `${y}${m}${d}`;
const [rows] = await pool.execute(`SELECT * FROM readings WHERE DATE(timestamp)=CURDATE() ORDER BY timestamp`);
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(e)}
try{ csvUrl = await uploadTrendsCsv(
shortTs.slice(6,8)+shortTs.slice(0,2)+shortTs.slice(3,5), rows
); }catch(_){}
const weather = await fetchCurrentWeather();
const text =
@ -271,7 +274,7 @@ app.post('/api/area-readings', async (req,res) => {
}
});
// ─── Export & Fetch ──────────────────────────────────────────────────────────
// ─── Fetch & Export ─────────────────────────────────────────────────────────
app.get('/api/readings', async (req,res)=>{
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY timestamp`);
res.json(rows);
@ -281,15 +284,11 @@ app.get('/api/export', async (req,res)=>{
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=>{
// r.timestamp is already "YYYY-MM-DD HH:mm:ss" in EST/EDT
rows.forEach(r => {
res.write(`${r.id},${r.location},${r.stationDockDoor},${r.timestamp},${r.temperature},${r.humidity},${r.heatIndex}\n`);
});
res.end();
});
// ─── Start ───────────────────────────────────────────────────────────────────
app.listen(PORT, ()=>{
console.log(`Server running on http://localhost:${PORT}`);
});
app.listen(PORT, ()=>console.log(`Server running http://localhost:${PORT}`));