Update server.js

fixed time.
This commit is contained in:
JoshBaneyCS 2025-04-30 01:12:34 +00:00
parent 5f029f492a
commit 6461fc8e85

142
server.js
View File

@ -1,4 +1,3 @@
// server.js
require('dotenv').config();
const express = require('express');
const mysql = require('mysql2/promise');
@ -13,23 +12,40 @@ const PORT = process.env.PORT || 3000;
// In-memory shift counters
const shiftCounters = {};
// Helpers
// ─── Helpers ──────────────────────────────────────────────────────────────────
// zero-pad
const pad2 = n => n.toString().padStart(2,'0');
// Format Date in EST as “M/D/YY @HH:mm” using Intl (no round-trip through string)
function shortEST(date) {
const est = new Date(date.toLocaleString('en-US', { timeZone: 'America/New_York' }));
const M = est.getMonth() + 1, D = est.getDate(), YY = String(est.getFullYear()).slice(-2);
const hh = pad2(est.getHours()), mm = pad2(est.getMinutes());
return `${M}/${D}/${YY} @${hh}:${mm}`;
const dateFmt = new Intl.DateTimeFormat('en-US', {
timeZone: 'America/New_York',
month: 'numeric',
day: 'numeric',
year: '2-digit'
});
const timeFmt = new Intl.DateTimeFormat('en-US', {
timeZone: 'America/New_York',
hour12: false,
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”
function formatDateEST(date) {
const est = new Date(date.toLocaleString('en-US', { timeZone: 'America/New_York' }));
const y = est.getFullYear(), M = pad2(est.getMonth()+1), D = pad2(est.getDate());
const hh = pad2(est.getHours()), mm = pad2(est.getMinutes()), ss = pad2(est.getSeconds());
return `${y}-${M}-${D} ${hh}:${mm}:${ss}`;
const Y = est.getFullYear();
const M = pad2(est.getMonth() + 1);
const D = pad2(est.getDate());
const h = pad2(est.getHours());
const m = pad2(est.getMinutes());
const s = pad2(est.getSeconds());
return `${Y}-${M}-${D} ${h}:${m}:${s}`;
}
// 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,
@ -40,6 +56,7 @@ function computeHeatIndex(T, R) {
return Math.round(HI * 100) / 100;
}
// Determine Day/Night shift and period key
function getShiftInfo(now) {
const est = new Date(now.toLocaleString('en-US', { timeZone:'America/New_York' }));
const h = est.getHours(), m = est.getMinutes();
@ -61,25 +78,26 @@ function getShiftInfo(now) {
return { shift, start, key, estNow: est };
}
// Fetch current weather from OpenWeatherMap
async function fetchCurrentWeather() {
const key = process.env.WEATHER_API_KEY, zip = process.env.ZIP_CODE;
const key = process.env.WEATHER_API_KEY;
const 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 { 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 (err) {
console.error('Weather API error:', err.message);
} catch (e) {
console.error('Weather API error:', e.message);
return 'Unavailable';
}
}
// MariaDB pool
// ─── MariaDB Pool & Table Setup ───────────────────────────────────────────────
const pool = mysql.createPool({
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT,10) || 3306,
@ -92,7 +110,6 @@ const pool = mysql.createPool({
connectTimeout: 10000
});
// Ensure readings table exists
(async()=>{
const sql = `
CREATE TABLE IF NOT EXISTS readings (
@ -107,12 +124,12 @@ const pool = mysql.createPool({
await pool.execute(sql);
})();
// Middleware & static (serve heatmap.html at '/')
// ─── Middleware & Static (default to heatmap.html) ───────────────────────────
app.use(bodyParser.json());
const publicDir = path.join(__dirname,'public');
app.use(express.static(publicDir, { index: 'heatmap.html' }));
// SSE setup
// ─── SSE Setup ────────────────────────────────────────────────────────────────
let clients = [];
app.get('/api/stream',(req,res)=>{
res.set({
@ -122,22 +139,21 @@ app.get('/api/stream', (req, res) => {
});
res.flushHeaders();
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) {
const msg = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
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 ===
// ─── Dual Dock-Door Readings Endpoint ────────────────────────────────────────
app.post('/api/readings', async (req,res) => {
try {
const { inbound={}, outbound={} } = req.body;
const { dockDoor: inD, temperature: inT, humidity: inH } = inbound;
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' });
}
const hiIn = computeHeatIndex(inT, inH);
const hiOut = computeHeatIndex(outT, outH);
@ -149,32 +165,24 @@ app.post('/api/readings', async (req, res) => {
const sqlTs = formatDateEST(estNow);
const shortTs = shortEST(estNow);
// Insert inbound + outbound
const ins = `
const insertSQL = `
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(insertSQL, ['Inbound', String(inD), sqlTs, inT, inH, hiIn]);
await pool.execute(insertSQL, ['Outbound', String(outD), sqlTs, outT, outH, hiOut]);
// SSE broadcast
broadcast('new-reading', {
location: 'Inbound',
stationDockDoor: String(inD),
timestamp: shortTs,
temperature: inT,
humidity: inH,
heatIndex: hiIn
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
location:'Outbound', stationDockDoor:String(outD),
timestamp: shortTs, temperature:outT,
humidity: outH, heatIndex: hiOut
});
// Generate/upload CSV
// CSV Upload
const y=estNow.getFullYear(), m=pad2(estNow.getMonth()+1), d=pad2(estNow.getDate());
const dateKey = `${y}${m}${d}`;
const [rows] = await pool.execute(
@ -182,12 +190,10 @@ app.post('/api/readings', async (req, res) => {
);
let csvUrl=null;
try { csvUrl=await uploadTrendsCsv(dateKey,rows); }
catch (e) { console.error('CSV upload error:', e); }
catch(e){ console.error('CSV upload error',e); }
// Fetch weather
const weather = await fetchCurrentWeather();
// Build Slack message text
const text =
`*_${shift} shift Period ${period} dock/ trailer temperature checks for ${shortTs}_*\n` +
`*_Current Weather Forecast for Baltimore: ${weather}_*\n\n` +
@ -200,10 +206,10 @@ app.post('/api/readings', async (req, res) => {
`*_Humidity:_* ${outH} % 💦\n` +
`*_Heat Index:_* ${hiOut} °F 🥵`;
// Send JSON with top-level "text" field
// Send to Slack workflow trigger
await axios.post(
process.env.SLACK_WEBHOOK_URL,
{ text, shift, period, timestamp: shortTs },
{ text },
{ headers: {'Content-Type':'application/json'} }
);
@ -214,37 +220,31 @@ app.post('/api/readings', async (req, res) => {
}
});
// === Area/mod readings endpoint ===
// ─── Area/Mod Station Readings Endpoint ─────────────────────────────────────
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) {
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 { shift, estNow } = getShiftInfo(now);
const sqlTs = formatDateEST(estNow);
const shortTs = shortEST(estNow);
// Insert
const ins = `
const insertSQL = `
INSERT INTO readings(location,stationDockDoor,timestamp,temperature,humidity,heatIndex)
VALUES(?,?,?,?,?,?)`;
await pool.execute(ins, [area, stationCode, sqlTs, T, H, hi]);
await pool.execute(insertSQL, [area, stationCode, sqlTs, T, H, hi]);
// SSE
broadcast('new-area-reading', {
location: area,
stationDockDoor: stationCode,
timestamp: shortTs,
temperature: T,
humidity: H,
heatIndex: hi
location:area, stationDockDoor:stationCode,
timestamp:shortTs, 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(
@ -252,12 +252,10 @@ app.post('/api/area-readings', async (req, res) => {
);
let csvUrl=null;
try { csvUrl=await uploadTrendsCsv(dateKey,rows); }
catch (e) { console.error('CSV upload error:', e); }
catch(e){ console.error('CSV upload error',e); }
// Fetch weather
const weather = await fetchCurrentWeather();
// Build Slack message text
const text =
`*_${shift} shift ${area} temp check for ${shortTs}_*\n` +
`*_Current Weather Forecast for Baltimore: ${weather}_*\n\n` +
@ -266,10 +264,9 @@ app.post('/api/area-readings', async (req, res) => {
`*_Humidity:_* ${H} % 💦\n` +
`*_Heat Index:_* ${hi} °F 🥵`;
// Send JSON with top-level "text" field
await axios.post(
process.env.SLACK_WEBHOOK_URL,
{ text, location: area, station_dock_door: stationCode, temperature: T, humidity: H, heat_index: hi },
{ text },
{ headers: {'Content-Type':'application/json'} }
);
@ -280,7 +277,7 @@ app.post('/api/area-readings', async (req, res) => {
}
});
// GET all readings
// ─── GET all readings & CSV export ───────────────────────────────────────────
app.get('/api/readings', async (req,res) => {
try {
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY timestamp`);
@ -290,8 +287,6 @@ app.get('/api/readings', async (req, res) => {
res.status(500).json({ error: err.message });
}
});
// Export CSV
app.get('/api/export', async (req,res) => {
try {
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY timestamp`);
@ -299,7 +294,7 @@ app.get('/api/export', async (req, res) => {
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;
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();
@ -309,8 +304,7 @@ app.get('/api/export', async (req, res) => {
}
});
// Start server
// ─── Start Server ───────────────────────────────────────────────────────────
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});