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