Update server.js
This commit is contained in:
parent
c372146ba8
commit
b280a720d7
137
server.js
137
server.js
@ -10,13 +10,12 @@ 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
|
||||||
const pad2 = n => n.toString().padStart(2, '0');
|
const pad2 = n => n.toString().padStart(2, '0');
|
||||||
|
|
||||||
// Format Date in EST as “M/D/YY @HH:mm”
|
|
||||||
function shortEST(d) {
|
function shortEST(d) {
|
||||||
const est = new Date(d.toLocaleString('en-US', { timeZone: 'America/New_York' }));
|
const est = new Date(d.toLocaleString('en-US', { timeZone: 'America/New_York' }));
|
||||||
const M = est.getMonth() + 1, D = est.getDate(), YY = String(est.getFullYear()).slice(-2);
|
const M = est.getMonth() + 1, D = est.getDate(), YY = String(est.getFullYear()).slice(-2);
|
||||||
@ -24,7 +23,6 @@ function shortEST(d) {
|
|||||||
return `${M}/${D}/${YY} @${hh}:${mm}`;
|
return `${M}/${D}/${YY} @${hh}:${mm}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Format Date in EST as SQL DATETIME
|
|
||||||
function formatDateEST(d) {
|
function formatDateEST(d) {
|
||||||
const est = new Date(d.toLocaleString('en-US', { timeZone: 'America/New_York' }));
|
const est = new Date(d.toLocaleString('en-US', { timeZone: 'America/New_York' }));
|
||||||
const y = est.getFullYear(), M = pad2(est.getMonth()+1), D = pad2(est.getDate());
|
const y = est.getFullYear(), M = pad2(est.getMonth()+1), D = pad2(est.getDate());
|
||||||
@ -32,7 +30,6 @@ function formatDateEST(d) {
|
|||||||
return `${y}-${M}-${D} ${hh}:${mm}:${ss}`;
|
return `${y}-${M}-${D} ${hh}:${mm}:${ss}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compute heat index (NOAA)
|
|
||||||
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,
|
||||||
@ -43,7 +40,6 @@ function computeHeatIndex(T, R) {
|
|||||||
return Math.round(HI * 100) / 100;
|
return Math.round(HI * 100) / 100;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Determine shift info in EST
|
|
||||||
function getShiftInfo(now) {
|
function getShiftInfo(now) {
|
||||||
const est = new Date(now.toLocaleString('en-US', { timeZone:'America/New_York' }));
|
const est = new Date(now.toLocaleString('en-US', { timeZone:'America/New_York' }));
|
||||||
const h = est.getHours(), m = est.getMinutes();
|
const h = est.getHours(), m = est.getMinutes();
|
||||||
@ -65,23 +61,21 @@ function getShiftInfo(now) {
|
|||||||
return { shift, start, key, estNow: est };
|
return { shift, start, key, estNow: est };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch current weather from OpenWeatherMap
|
|
||||||
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 null;
|
|
||||||
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;
|
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.charAt(0).toUpperCase()+desc.slice(1)}. Hi of ${hi}, Humidity ${hum}%`;
|
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 null;
|
return 'Unavailable';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -113,6 +107,11 @@ const pool = mysql.createPool({
|
|||||||
await pool.execute(sql);
|
await pool.execute(sql);
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
// Middleware & static (serve heatmap.html as index)
|
||||||
|
app.use(bodyParser.json());
|
||||||
|
const publicDir = path.join(__dirname,'public');
|
||||||
|
app.use(express.static(publicDir, { index: 'heatmap.html' }));
|
||||||
|
|
||||||
// SSE setup
|
// SSE setup
|
||||||
let clients = [];
|
let clients = [];
|
||||||
app.get('/api/stream',(req,res)=>{
|
app.get('/api/stream',(req,res)=>{
|
||||||
@ -123,22 +122,13 @@ app.get('/api/stream',(req,res)=>{
|
|||||||
});
|
});
|
||||||
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(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));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Middleware
|
|
||||||
app.use(bodyParser.json());
|
|
||||||
app.use(express.static(path.join(__dirname,'public')));
|
|
||||||
|
|
||||||
const publicDir = path.join(__dirname, 'public');
|
|
||||||
// Serve heatmap.html as the index page
|
|
||||||
app.use(express.static(publicDir, { index: 'heatmap.html' }));
|
|
||||||
|
|
||||||
|
|
||||||
// ---- Dual dock-door endpoint ----
|
// ---- Dual dock-door endpoint ----
|
||||||
app.post('/api/readings', async (req,res)=>{
|
app.post('/api/readings', async (req,res)=>{
|
||||||
try {
|
try {
|
||||||
@ -151,15 +141,15 @@ app.post('/api/readings', async (req, res) => {
|
|||||||
const hiIn = computeHeatIndex(inT,inH);
|
const hiIn = computeHeatIndex(inT,inH);
|
||||||
const hiOut = computeHeatIndex(outT,outH);
|
const hiOut = computeHeatIndex(outT,outH);
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const { shift, start, key, estNow } = getShiftInfo(now);
|
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 = formatDateEST(estNow);
|
const sqlTs = formatDateEST(estNow);
|
||||||
const shortTs = shortEST(estNow);
|
const shortTs = shortEST(estNow);
|
||||||
|
|
||||||
// Insert inbound & outbound
|
// insert
|
||||||
const ins = `INSERT INTO readings(location,stationDockDoor,timestamp,temperature,humidity,heatIndex)
|
const ins = `
|
||||||
|
INSERT INTO readings(location,stationDockDoor,timestamp,temperature,humidity,heatIndex)
|
||||||
VALUES(?,?,?,?,?,?)`;
|
VALUES(?,?,?,?,?,?)`;
|
||||||
await pool.execute(ins,['Inbound',String(inD),sqlTs,inT,inH,hiIn]);
|
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(ins,['Outbound',String(outD),sqlTs,outT,outH,hiOut]);
|
||||||
@ -168,19 +158,21 @@ app.post('/api/readings', async (req, res) => {
|
|||||||
broadcast('new-reading',{ location:'Inbound',stationDockDoor:String(inD),timestamp:shortTs,temperature:inT,humidity:inH,heatIndex:hiIn });
|
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:'Outbound',stationDockDoor:String(outD),timestamp:shortTs,temperature:outT,humidity:outH,heatIndex:hiOut });
|
||||||
|
|
||||||
// CSV upload
|
// CSV
|
||||||
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(`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;
|
let csvUrl=null;
|
||||||
try { csvUrl = await uploadTrendsCsv(dateKey, rows); }
|
try{ csvUrl=await uploadTrendsCsv(dateKey,rows) }catch(e){console.error(e)}
|
||||||
catch(e){ console.error('CSV upload error',e); }
|
|
||||||
|
|
||||||
// Weather
|
// weather
|
||||||
const weather = await fetchCurrentWeather() || 'Unavailable';
|
const weather = await fetchCurrentWeather();
|
||||||
|
|
||||||
// Slack payload
|
// build text
|
||||||
const text = `*_${shift} shift Period ${period} dock/ trailer temperature checks for ${shortTs}_*\n` +
|
const text =
|
||||||
|
`*_${shift} shift Period ${period} dock/ trailer temperature checks for ${shortTs}_*\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`+
|
||||||
@ -191,22 +183,13 @@ app.post('/api/readings', async (req, res) => {
|
|||||||
`*_Humidity:_* ${outH} % 💦\n`+
|
`*_Humidity:_* ${outH} % 💦\n`+
|
||||||
`*_Heat Index:_* ${hiOut} °F 🥵`;
|
`*_Heat Index:_* ${hiOut} °F 🥵`;
|
||||||
|
|
||||||
const payload = {
|
const payload = { text };
|
||||||
text,
|
|
||||||
shift,
|
// send as url-encoded string
|
||||||
period,
|
const body = `payload=${encodeURIComponent(JSON.stringify(payload))}`;
|
||||||
timestamp: shortTs,
|
await axios.post(process.env.SLACK_WEBHOOK_URL, body, {
|
||||||
current_weather: weather,
|
headers:{ 'Content-Type':'application/x-www-form-urlencoded' }
|
||||||
inbound_dock_door: inD,
|
});
|
||||||
inbound_temperature: inT,
|
|
||||||
inbound_humidity: inH,
|
|
||||||
inbound_heat_index: hiIn,
|
|
||||||
outbound_dock_door: outD,
|
|
||||||
outbound_temperature: outT,
|
|
||||||
outbound_humidity: outH,
|
|
||||||
outbound_heat_index: hiOut
|
|
||||||
};
|
|
||||||
await axios.post(process.env.SLACK_WEBHOOK_URL, payload);
|
|
||||||
|
|
||||||
res.json({ success:true, shift, period, csvUrl });
|
res.json({ success:true, shift, period, csvUrl });
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
@ -215,7 +198,7 @@ app.post('/api/readings', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ---- Area (Mod/AFE) endpoint ----
|
// ---- Area/Mod 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;
|
||||||
@ -224,51 +207,45 @@ app.post('/api/area-readings', async (req, res) => {
|
|||||||
|
|
||||||
const hi = computeHeatIndex(T,H);
|
const hi = computeHeatIndex(T,H);
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const { shift, start, key, estNow } = getShiftInfo(now);
|
const { shift, estNow } = getShiftInfo(now);
|
||||||
|
|
||||||
// NOTE: area checks do NOT increment period counter
|
|
||||||
const shortTs = shortEST(estNow);
|
|
||||||
const sqlTs = formatDateEST(estNow);
|
const sqlTs = formatDateEST(estNow);
|
||||||
|
const shortTs = shortEST(estNow);
|
||||||
|
|
||||||
// Insert
|
// insert
|
||||||
const ins = `INSERT INTO readings(location,stationDockDoor,timestamp,temperature,humidity,heatIndex)
|
const ins = `
|
||||||
|
INSERT INTO readings(location,stationDockDoor,timestamp,temperature,humidity,heatIndex)
|
||||||
VALUES(?,?,?,?,?,?)`;
|
VALUES(?,?,?,?,?,?)`;
|
||||||
await pool.execute(ins,[area,stationCode,sqlTs,T,H,hi]);
|
await pool.execute(ins,[area,stationCode,sqlTs,T,H,hi]);
|
||||||
|
|
||||||
// SSE
|
// SSE
|
||||||
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 });
|
||||||
|
|
||||||
// CSV upload
|
// CSV
|
||||||
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(`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;
|
let csvUrl=null;
|
||||||
try { csvUrl = await uploadTrendsCsv(dateKey, rows); }
|
try{ csvUrl=await uploadTrendsCsv(dateKey,rows) }catch(e){console.error(e)}
|
||||||
catch(e){ console.error('CSV upload error',e); }
|
|
||||||
|
|
||||||
// Weather
|
// weather
|
||||||
const weather = await fetchCurrentWeather() || 'Unavailable';
|
const weather = await fetchCurrentWeather();
|
||||||
|
|
||||||
// Slack text
|
// build text
|
||||||
const text = `*_${shift} shift ${area} temp check for ${shortTs}_*\n` +
|
const text =
|
||||||
|
`*_${shift} shift ${area} temp check for ${shortTs}_*\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 🥵`;
|
||||||
|
|
||||||
const payload = {
|
const payload = { text };
|
||||||
text,
|
const body = `payload=${encodeURIComponent(JSON.stringify(payload))}`;
|
||||||
shift,
|
await axios.post(process.env.SLACK_WEBHOOK_URL, body, {
|
||||||
timestamp: shortTs,
|
headers:{ 'Content-Type':'application/x-www-form-urlencoded' }
|
||||||
current_weather: weather,
|
});
|
||||||
location: area,
|
|
||||||
station_dock_door: stationCode,
|
|
||||||
temperature: T,
|
|
||||||
humidity: H,
|
|
||||||
heat_index: hi
|
|
||||||
};
|
|
||||||
await axios.post(process.env.SLACK_WEBHOOK_URL, payload);
|
|
||||||
|
|
||||||
res.json({ success:true, csvUrl });
|
res.json({ success:true, csvUrl });
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
@ -307,6 +284,4 @@ app.get('/api/export', async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 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}`);
|
|
||||||
});
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user