Update server.js

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

View File

@ -1,9 +1,10 @@
// server.js
require('dotenv').config();
const express = require('express');
const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');
const bodyParser = require('body-parser');
const path = require('path');
const axios = require('axios');
const { uploadTrendsCsv } = require('./s3');
@ -14,12 +15,10 @@
const shiftCounters = {};
// ─── Helpers ──────────────────────────────────────────────────────────────────
// pad to two digits
function pad2(n) {
return n.toString().padStart(2, '0');
}
// Format epoch_ms → "M/D/YY @HH:mm" (24-hour) in America/New_York
function formatForSlack(epoch) {
return new Date(epoch).toLocaleString('en-US', {
timeZone: 'America/New_York',
@ -32,7 +31,6 @@
}).replace(',', ' @');
}
// 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,
@ -44,9 +42,7 @@
return Math.round(HI * 100) / 100;
}
// Determine Day/Night shift & period key from epoch_ms
function getShiftInfo(epoch) {
// Convert to EST by string-round-trip
const estString = new Date(epoch)
.toLocaleString('en-US', { timeZone: 'America/New_York' });
const est = new Date(estString);
@ -69,9 +65,9 @@
return { shift, key, estNow: est };
}
// Fetch current Baltimore weather
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(
@ -102,7 +98,6 @@
});
(async () => {
// Create table with epoch_ms only
await pool.execute(`
CREATE TABLE IF NOT EXISTS readings (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
@ -118,6 +113,29 @@
`);
})();
// ─── Load trends.html template ────────────────────────────────────────────────
const trendsTemplate = fs.readFileSync(
path.join(__dirname, 'public', 'trends.html'),
'utf8'
);
// ─── Inject initial data into trends.html ────────────────────────────────────
app.get('/trends.html', async (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' }));
@ -139,7 +157,7 @@
clients.forEach(c => c.write(msg));
}
// ─── Dual Dock-Door Endpoint ───────────────────────────────────────────────────
// ─── Dual Dock-Door Readings Endpoint ─────────────────────────────────────────
app.post('/api/readings', async (req, res) => {
try {
const { inbound = {}, outbound = {} } = req.body;
@ -157,15 +175,13 @@
const period = shiftCounters[key];
const slackTs = formatForSlack(epoch);
// Insert inbound + outbound
const sql = `
const insertSQL = `
INSERT INTO readings(location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex)
VALUES (?, ?, ?, ?, ?, ?)
`;
await pool.execute(sql, ['Inbound', String(inD), epoch, inT, inH, hiIn]);
await pool.execute(sql, ['Outbound', String(outD), epoch, outT, outH, hiOut]);
await pool.execute(insertSQL, ['Inbound', String(inD), epoch, inT, inH, hiIn]);
await pool.execute(insertSQL, ['Outbound', String(outD), epoch, outT, outH, hiOut]);
// SSE broadcast
broadcast('new-reading', {
location: 'Inbound',
stationDockDoor: String(inD),
@ -183,7 +199,6 @@
heatIndex: hiOut
});
// 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(`
@ -195,7 +210,6 @@
try { csvUrl = await uploadTrendsCsv(dateKey, rows); }
catch (e) { console.error('CSV upload error:', e); }
// Slack message
const weather = await fetchCurrentWeather();
const text =
`*_${shift} shift Period ${period} dock/trailer temperature checks for ${slackTs}_*\n` +
@ -209,9 +223,11 @@
`*_Humidity:_* ${outH} % 💦\n` +
`*_Heat Index:_* ${hiOut} °F 🥵`;
await axios.post(process.env.SLACK_WEBHOOK_URL, { text }, {
headers:{ 'Content-Type':'application/json' }
});
await axios.post(
process.env.SLACK_WEBHOOK_URL,
{ text },
{ headers: { 'Content-Type':'application/json' } }
);
res.json({ success: true, shift, period, csvUrl });
} catch (err) {
@ -220,7 +236,7 @@
}
});
// ─── Area/Mod Endpoint ───────────────────────────────────────────────────────
// ─── Area/Mod Readings Endpoint ──────────────────────────────────────────────
app.post('/api/area-readings', async (req, res) => {
try {
const { area, stationCode, temperature: T, humidity: H } = req.body;
@ -267,9 +283,11 @@
`*_Humidity:_* ${H} % 💦\n` +
`*_Heat Index:_* ${hi} °F 🥵`;
await axios.post(process.env.SLACK_WEBHOOK_URL, { text }, {
headers:{ 'Content-Type':'application/json' }
});
await axios.post(
process.env.SLACK_WEBHOOK_URL,
{ text },
{ headers: { 'Content-Type':'application/json' } }
);
res.json({ success: true, csvUrl });
} catch (err) {
@ -278,7 +296,7 @@
}
});
// ─── Fetch & Export ─────────────────────────────────────────────────────────
// ─── Fetch & Export Endpoints ─────────────────────────────────────────────────
app.get('/api/readings', async (req, res) => {
try {
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`);
@ -288,6 +306,7 @@
res.status(500).json({ error: err.message });
}
});
app.get('/api/export', async (req, res) => {
try {
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`);
@ -295,10 +314,8 @@
res.set('Content-Type','text/csv');
res.write('id,location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex\n');
rows.forEach(r => {
res.write(
`${r.id},${r.location},${r.stationDockDoor},${r.epoch_ms},` +
`${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();
} catch (err) {