Update server.js
update time fromat
This commit is contained in:
parent
34dd53c0fd
commit
fd85289d61
361
server.js
361
server.js
@ -1,126 +1,327 @@
|
|||||||
require('dotenv').config();
|
require('dotenv').config();
|
||||||
const express = require('express');
|
const express = require('express');
|
||||||
|
const mysql = require('mysql2/promise');
|
||||||
const bodyParser = require('body-parser');
|
const bodyParser = require('body-parser');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const knex = require('knex');
|
|
||||||
const axios = require('axios');
|
const axios = require('axios');
|
||||||
|
const { uploadTrendsCsv } = require('./s3');
|
||||||
// Initialize MariaDB connection via Knex
|
|
||||||
const db = knex({
|
|
||||||
client: process.env.DB_CLIENT,
|
|
||||||
connection: {
|
|
||||||
host: process.env.DB_HOST,
|
|
||||||
port: process.env.DB_PORT,
|
|
||||||
user: process.env.DB_USER,
|
|
||||||
password: process.env.DB_PASSWORD,
|
|
||||||
database: process.env.DB_NAME
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
const PORT = process.env.PORT || 3000;
|
const PORT = process.env.PORT || 3000;
|
||||||
const slackWebhook = process.env.SLACK_WEBHOOK_URL;
|
|
||||||
|
|
||||||
// Create table if not exists, now with direction
|
// In-memory shift counters
|
||||||
(async () => {
|
const shiftCounters = {};
|
||||||
if (!await db.schema.hasTable('readings')) {
|
|
||||||
await db.schema.createTable('readings', table => {
|
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||||
table.increments('id').primary();
|
// zero-pad
|
||||||
table.integer('dockDoor');
|
const pad2 = n => n.toString().padStart(2,'0');
|
||||||
table.string('direction');
|
|
||||||
table.timestamp('timestamp');
|
// Format Date in EST as “M/D/YY @HH:mm” using Intl
|
||||||
table.float('temperature');
|
function shortEST(date) {
|
||||||
table.float('humidity');
|
const dateFmt = new Intl.DateTimeFormat('en-US', {
|
||||||
table.float('heatIndex');
|
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)}`;
|
||||||
|
}
|
||||||
|
|
||||||
// Compute heat index (NOAA formula)
|
// Format Date in EST as SQL DATETIME “YYYY-MM-DD HH:mm:ss”
|
||||||
|
function formatDateEST(date) {
|
||||||
|
// datePart as “YYYY-MM-DD”
|
||||||
|
const datePart = new Intl.DateTimeFormat('en-CA', {
|
||||||
|
timeZone: 'America/New_York',
|
||||||
|
year: 'numeric',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit'
|
||||||
|
}).format(date);
|
||||||
|
// timePart as “HH:MM:SS”
|
||||||
|
const timePart = new Intl.DateTimeFormat('en-GB', {
|
||||||
|
timeZone: 'America/New_York',
|
||||||
|
hour12: false,
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
second: '2-digit'
|
||||||
|
}).format(date);
|
||||||
|
return `${datePart} ${timePart}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// NOAA heat-index formula
|
||||||
function computeHeatIndex(T, R) {
|
function computeHeatIndex(T, R) {
|
||||||
const c1 = -42.379, c2 = 2.04901523, c3 = 10.14333127;
|
const [c1,c2,c3,c4,c5,c6,c7,c8,c9] =
|
||||||
const c4 = -0.22475541, c5 = -6.83783e-3, c6 = -5.481717e-2;
|
[-42.379,2.04901523,10.14333127,-0.22475541,
|
||||||
const c7 = 1.22874e-3, c8 = 8.5282e-4, c9 = -1.99e-6;
|
-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;
|
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;
|
||||||
return Math.round(HI * 100) / 100;
|
return Math.round(HI * 100) / 100;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Determine direction based on door number
|
// Determine Day/Night shift and period key
|
||||||
function getDirection(door) {
|
function getShiftInfo(now) {
|
||||||
door = Number(door);
|
const est = new Date(now.toLocaleString('en-US', { timeZone:'America/New_York' }));
|
||||||
if (door >= 124 && door <= 138) return 'Inbound';
|
const h = est.getHours(), m = est.getMinutes();
|
||||||
if (door >= 142 && door <= 201) return 'Outbound';
|
let shift, start = new Date(est);
|
||||||
if (door >= 202 && door <= 209) return 'Inbound';
|
|
||||||
return 'Unknown';
|
if (h > 7 || (h === 7 && m >= 0)) {
|
||||||
|
if (h < 17 || (h === 17 && m < 30)) {
|
||||||
|
shift = 'Day'; start.setHours(7,0,0,0);
|
||||||
|
} else {
|
||||||
|
shift = 'Night'; start.setHours(17,30,0,0);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
shift = 'Night';
|
||||||
|
start.setDate(start.getDate() - 1);
|
||||||
|
start.setHours(17,30,0,0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const key = `${shift}-${start.toISOString().slice(0,10)}-${start.getHours()}${start.getMinutes()}`;
|
||||||
|
return { shift, start, key, estNow: est };
|
||||||
}
|
}
|
||||||
|
|
||||||
app.use(bodyParser.json());
|
// Fetch current weather from OpenWeatherMap
|
||||||
app.use(express.static(path.join(__dirname, 'public')));
|
async function fetchCurrentWeather() {
|
||||||
|
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 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 (e) {
|
||||||
|
console.error('Weather API error:', e.message);
|
||||||
|
return 'Unavailable';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── 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
|
||||||
|
});
|
||||||
|
|
||||||
|
(async ()=>{
|
||||||
|
const sql = `
|
||||||
|
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);
|
||||||
|
})();
|
||||||
|
|
||||||
|
// ─── 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 ───────────────────────────────────────────────────────────────
|
||||||
let clients = [];
|
let clients = [];
|
||||||
app.get('/api/stream', (req, res) => {
|
app.get('/api/stream',(req,res) => {
|
||||||
res.set({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
|
res.set({
|
||||||
|
'Content-Type': 'text/event-stream',
|
||||||
|
'Cache-Control': 'no-cache',
|
||||||
|
Connection: 'keep-alive'
|
||||||
|
});
|
||||||
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(event, data) {
|
function broadcast(evt,data){
|
||||||
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
const msg = `event: ${evt}\ndata: ${JSON.stringify(data)}\n\n`;
|
||||||
clients.forEach(res => res.write(payload));
|
clients.forEach(c=>c.write(msg));
|
||||||
}
|
}
|
||||||
|
|
||||||
app.post('/api/readings', async (req, res) => {
|
// ─── Dual Dock-Door Readings Endpoint ────────────────────────────────────────
|
||||||
|
app.post('/api/readings', async (req,res) => {
|
||||||
try {
|
try {
|
||||||
const { inbound, outbound } = req.body; // each: {dockDoor,temperature,humidity}
|
const { inbound={}, outbound={} } = req.body;
|
||||||
const timestamp = new Date();
|
const { dockDoor: inD, temperature: inT, humidity: inH } = inbound;
|
||||||
const entries = [inbound, outbound].map(r => {
|
const { dockDoor: outD, temperature: outT, humidity: outH } = outbound;
|
||||||
const direction = getDirection(r.dockDoor);
|
if ([inD,inT,inH,outD,outT,outH].some(v=>v==null))
|
||||||
const heatIndex = computeHeatIndex(r.temperature, r.humidity);
|
return res.status(400).json({ error:'Missing fields' });
|
||||||
return { ...r, direction, timestamp, heatIndex };
|
|
||||||
|
const hiIn = computeHeatIndex(inT, inH);
|
||||||
|
const hiOut = computeHeatIndex(outT, outH);
|
||||||
|
const now = new Date();
|
||||||
|
const { shift, key, estNow } = getShiftInfo(now);
|
||||||
|
shiftCounters[key] = (shiftCounters[key]||0) + 1;
|
||||||
|
const period = shiftCounters[key];
|
||||||
|
|
||||||
|
const sqlTs = formatDateEST(estNow);
|
||||||
|
const shortTs = shortEST(estNow);
|
||||||
|
|
||||||
|
const insertSQL = `
|
||||||
|
INSERT INTO readings(location,stationDockDoor,timestamp,temperature,humidity,heatIndex)
|
||||||
|
VALUES(?,?,?,?,?,?)`;
|
||||||
|
await pool.execute(insertSQL, ['Inbound', String(inD), sqlTs, inT, inH, hiIn]);
|
||||||
|
await pool.execute(insertSQL, ['Outbound', String(outD), sqlTs, outT, outH, 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
|
||||||
});
|
});
|
||||||
// Insert both
|
|
||||||
const ids = await db('readings').insert(entries);
|
|
||||||
const saved = entries.map((e, i) => ({ id: ids[i], ...e }));
|
|
||||||
|
|
||||||
// Broadcast and respond
|
// CSV Upload
|
||||||
saved.forEach(reading => broadcast('new-reading', reading));
|
const y=estNow.getFullYear(), m=pad2(estNow.getMonth()+1), d=pad2(estNow.getDate());
|
||||||
|
const dateKey=`${y}${m}${d}`;
|
||||||
// Slack notification with both
|
const [rows] = await pool.execute(
|
||||||
if (slackWebhook) {
|
`SELECT * FROM readings WHERE DATE(timestamp)=CURDATE() ORDER BY timestamp`
|
||||||
const textLines = saved.map(r =>
|
|
||||||
`Door *${r.dockDoor}* (${r.direction}) – Temp: ${r.temperature}°F, Humidity: ${r.humidity}%, HI: ${r.heatIndex}`
|
|
||||||
);
|
);
|
||||||
await axios.post(slackWebhook, { text: 'New dual readings:\n' + textLines.join('\n') });
|
let csvUrl=null;
|
||||||
}
|
try{ csvUrl=await uploadTrendsCsv(dateKey,rows) }
|
||||||
res.json(saved);
|
catch(e){ console.error('CSV upload error',e) }
|
||||||
|
|
||||||
|
const weather = await fetchCurrentWeather();
|
||||||
|
|
||||||
|
const text =
|
||||||
|
`*_${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` +
|
||||||
|
`*_Humidity:_* ${inH} % 💦\n` +
|
||||||
|
`*_Heat Index:_* ${hiIn} °F 🥵\n\n` +
|
||||||
|
`*_⬆️ Outbound Dock Door 🚛 :_* ${outD}\n` +
|
||||||
|
`*_Temp:_* ${outT} °F 🌡️\n` +
|
||||||
|
`*_Humidity:_* ${outH} % 💦\n` +
|
||||||
|
`*_Heat Index:_* ${hiOut} °F 🥵`;
|
||||||
|
|
||||||
|
// Send to Slack workflow trigger
|
||||||
|
await axios.post(
|
||||||
|
process.env.SLACK_WEBHOOK_URL,
|
||||||
|
{ text },
|
||||||
|
{ headers:{ 'Content-Type':'application/json' } }
|
||||||
|
);
|
||||||
|
|
||||||
|
res.json({ success:true, shift, period, csvUrl });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Error saving readings or sending Slack:', err);
|
console.error('POST /api/readings error:', err);
|
||||||
res.status(500).json({ error: err.message });
|
res.status(500).json({ error: err.message });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
app.get('/api/readings', async (req, res) => {
|
// ─── Area/Mod Station Readings Endpoint ─────────────────────────────────────
|
||||||
|
app.post('/api/area-readings', async (req,res) => {
|
||||||
try {
|
try {
|
||||||
const rows = await db('readings').orderBy('timestamp', 'asc');
|
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 { shift, estNow } = getShiftInfo(now);
|
||||||
|
|
||||||
|
const sqlTs = formatDateEST(estNow);
|
||||||
|
const shortTs = shortEST(estNow);
|
||||||
|
|
||||||
|
const insertSQL = `
|
||||||
|
INSERT INTO readings(location,stationDockDoor,timestamp,temperature,humidity,heatIndex)
|
||||||
|
VALUES(?,?,?,?,?,?)`;
|
||||||
|
await pool.execute(insertSQL, [area, stationCode, sqlTs, T, H, hi]);
|
||||||
|
|
||||||
|
broadcast('new-area-reading', {
|
||||||
|
location: area,
|
||||||
|
stationDockDoor: stationCode,
|
||||||
|
timestamp: shortTs,
|
||||||
|
temperature: T,
|
||||||
|
humidity: H,
|
||||||
|
heatIndex: hi
|
||||||
|
});
|
||||||
|
|
||||||
|
// 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(
|
||||||
|
`SELECT * FROM readings WHERE DATE(timestamp)=CURDATE() ORDER BY timestamp`
|
||||||
|
);
|
||||||
|
let csvUrl=null;
|
||||||
|
try{ csvUrl=await uploadTrendsCsv(dateKey,rows) }
|
||||||
|
catch(e){ console.error('CSV upload error',e) }
|
||||||
|
|
||||||
|
const weather = await fetchCurrentWeather();
|
||||||
|
|
||||||
|
const text =
|
||||||
|
`*_${shift} shift ${area} temp check for ${shortTs}_*\n` +
|
||||||
|
`*_Current Weather Forecast for Baltimore: ${weather}_*\n\n` +
|
||||||
|
`*_${area.toUpperCase()} station:_* ${stationCode}\n` +
|
||||||
|
`*_Temp:_* ${T} °F 🌡️\n` +
|
||||||
|
`*_Humidity:_* ${H} % 💦\n` +
|
||||||
|
`*_Heat Index:_* ${hi} °F 🥵`;
|
||||||
|
|
||||||
|
await axios.post(
|
||||||
|
process.env.SLACK_WEBHOOK_URL,
|
||||||
|
{ text },
|
||||||
|
{ headers:{ 'Content-Type':'application/json' } }
|
||||||
|
);
|
||||||
|
|
||||||
|
res.json({ success:true, csvUrl });
|
||||||
|
} catch (err) {
|
||||||
|
console.error('POST /api/area-readings error:', err);
|
||||||
|
res.status(500).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── GET all readings & CSV export ───────────────────────────────────────────
|
||||||
|
app.get('/api/readings', async (req,res) => {
|
||||||
|
try {
|
||||||
|
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY timestamp`);
|
||||||
res.json(rows);
|
res.json(rows);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
console.error('GET /api/readings error:', err);
|
||||||
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 db('readings').orderBy('timestamp', 'asc');
|
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY timestamp`);
|
||||||
res.setHeader('Content-disposition', 'attachment; filename=readings.csv');
|
res.setHeader('Content-disposition','attachment; filename=readings.csv');
|
||||||
res.set('Content-Type', 'text/csv');
|
res.set('Content-Type','text/csv');
|
||||||
res.write('id,dockDoor,direction,timestamp,temperature,humidity,heatIndex\n');
|
res.write('id,location,stationDockDoor,timestamp,temperature,humidity,heatIndex\n');
|
||||||
rows.forEach(r =>
|
rows.forEach(r => {
|
||||||
res.write(`${r.id},${r.dockDoor},${r.direction},${r.timestamp},${r.temperature},${r.humidity},${r.heatIndex}\n`)
|
const ts = formatDateEST(new Date(r.timestamp));
|
||||||
);
|
res.write(`${r.id},${r.location},${r.stationDockDoor},${ts},${r.temperature},${r.humidity},${r.heatIndex}\n`);
|
||||||
|
});
|
||||||
res.end();
|
res.end();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
console.error('GET /api/export error:', err);
|
||||||
res.status(500).send(err.message);
|
res.status(500).send(err.message);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
|
// ─── Start Server ───────────────────────────────────────────────────────────
|
||||||
|
app.listen(PORT, ()=>console.log(`Server running http://localhost:${PORT}`));
|
||||||
|
Loading…
x
Reference in New Issue
Block a user