From f34be427924e1c9aa5155b680e38294350f8af51 Mon Sep 17 00:00:00 2001 From: JoshBaneyCS Date: Wed, 30 Apr 2025 03:43:04 +0000 Subject: [PATCH] sql bug fix? This should fix the sql server issue with the server --- server.js | 184 +++++++++++++++++++++++++++--------------------------- 1 file changed, 91 insertions(+), 93 deletions(-) diff --git a/server.js b/server.js index 78b25f9..b6c3847 100644 --- a/server.js +++ b/server.js @@ -14,10 +14,12 @@ const PORT = process.env.PORT || 3000; const shiftCounters = {}; // ─── Helpers ────────────────────────────────────────────────────────────────── -// Pad to 2 digits -function pad2(n) { return n.toString().padStart(2, '0'); } +// pad to two digits +function pad2(n) { + return n.toString().padStart(2, '0'); +} -// Format epoch_ms → "M/D/YY @HH:mm" in America/New_York for Slack/SSE +// 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', @@ -30,11 +32,11 @@ function formatForSlack(epoch) { }).replace(',', ' @'); } -// NOAA heat‐index formula +// 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, - -0.00683783, -0.05481717, 0.00122874, 0.00085282, -0.00000199 + -42.379,2.04901523,10.14333127,-0.22475541, + -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 @@ -42,9 +44,9 @@ function computeHeatIndex(T, R) { return Math.round(HI * 100) / 100; } -// Determine shift (Day/Night) and period key from epoch_ms +// Determine Day/Night shift & period key from epoch_ms function getShiftInfo(epoch) { - // Convert epoch to EST Date by string-roundtrip + // Convert to EST by string-round-trip const estString = new Date(epoch) .toLocaleString('en-US', { timeZone: 'America/New_York' }); const est = new Date(estString); @@ -67,18 +69,16 @@ function getShiftInfo(epoch) { return { shift, key, estNow: est }; } -// Fetch current weather forecast for Baltimore +// Fetch current Baltimore weather async function fetchCurrentWeather() { - const key = process.env.WEATHER_API_KEY; - const zip = process.env.ZIP_CODE; + const key = process.env.WEATHER_API_KEY, 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' } - } + '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 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}%`; @@ -91,7 +91,7 @@ async function fetchCurrentWeather() { // ─── MariaDB Pool & Table Setup ─────────────────────────────────────────────── const pool = mysql.createPool({ host: process.env.DB_HOST, - port: parseInt(process.env.DB_PORT, 10) || 3306, + port: parseInt(process.env.DB_PORT,10) || 3306, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, @@ -102,7 +102,7 @@ const pool = mysql.createPool({ }); (async () => { - // Create readings table with only epoch_ms (no timestamp column) + // Create table with epoch_ms only await pool.execute(` CREATE TABLE IF NOT EXISTS readings ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, @@ -120,50 +120,50 @@ const pool = mysql.createPool({ // ─── Middleware & Static ───────────────────────────────────────────────────── 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' })); // ─── SSE Setup ──────────────────────────────────────────────────────────────── 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' + 'Content-Type':'text/event-stream', + 'Cache-Control':'no-cache', + Connection:'keep-alive' }); 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) { +function broadcast(event,data){ const msg = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; - clients.forEach(c => c.write(msg)); + clients.forEach(c=>c.write(msg)); } -// ─── Dual Dock-Door Readings Endpoint ───────────────────────────────────────── -app.post('/api/readings', async (req, res) => { +// ─── Dual Dock-Door Endpoint ─────────────────────────────────────────────────── +app.post('/api/readings', async (req,res) => { try { - const { inbound = {}, outbound = {} } = req.body; - const { dockDoor: inD, temperature: inT, humidity: inH } = inbound; + 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 epoch = Date.now(); - const hiIn = computeHeatIndex(inT, inH); - const hiOut = computeHeatIndex(outT, outH); + const epoch = Date.now(); + const hiIn = computeHeatIndex(inT, inH); + const hiOut = computeHeatIndex(outT, outH); const { shift, key, estNow } = getShiftInfo(epoch); - shiftCounters[key] = (shiftCounters[key] || 0) + 1; - const period = shiftCounters[key]; + shiftCounters[key] = (shiftCounters[key]||0) + 1; + const period = shiftCounters[key]; const slackTs = formatForSlack(epoch); - // Insert inbound/outbound into epoch_ms - const insertSQL = ` + // Insert inbound + outbound + const sql = ` INSERT INTO readings(location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex) - VALUES (?, ?, ?, ?, ?, ?) + VALUES(?,?,?,?,?,?) `; - await pool.execute(insertSQL, ['Inbound', String(inD), epoch, inT, inH, hiIn]); - await pool.execute(insertSQL, ['Outbound', String(outD), epoch, outT, outH, hiOut]); + await pool.execute(sql, ['Inbound', String(inD), epoch, inT, inH, hiIn]); + await pool.execute(sql, ['Outbound', String(outD), epoch, outT, outH, hiOut]); // SSE broadcast broadcast('new-reading', { @@ -183,61 +183,59 @@ app.post('/api/readings', async (req, res) => { heatIndex: hiOut }); - // Upload CSV of today’s readings - const y = estNow.getFullYear(), m = pad2(estNow.getMonth()+1), d = pad2(estNow.getDate()); - const dateKey = `${y}${m}${d}`; + // 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(FROM_UNIXTIME(epoch_ms/1000)) = CURDATE() + WHERE DATE(FROM_UNIXTIME(epoch_ms/1000))=CURDATE() ORDER BY epoch_ms `); - let csvUrl = null; + 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); } - // Slack notification + // Slack message const weather = await fetchCurrentWeather(); const text = - `*_${shift} shift Period ${period} dock/trailer temperature checks for ${slackTs}_*\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` + + `*_${shift} shift Period ${period} dock/trailer temperature checks for ${slackTs}_*\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 🥵`; - 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 }); + res.json({ success:true, shift, period, csvUrl }); } catch (err) { console.error('POST /api/readings error:', err); res.status(500).json({ error: err.message }); } }); -// ─── Area/Mod Station Readings Endpoint ─────────────────────────────────────── -app.post('/api/area-readings', async (req, res) => { +// ─── Area/Mod 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) { - return res.status(400).json({ error: 'Missing fields' }); + 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 epoch = Date.now(); - const hi = computeHeatIndex(T, H); + const epoch = Date.now(); + const hi = computeHeatIndex(T, H); const { shift, key, estNow } = getShiftInfo(epoch); const slackTs = formatForSlack(epoch); await pool.execute(` INSERT INTO readings(location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex) - VALUES (?, ?, ?, ?, ?, ?) + VALUES(?,?,?,?,?,?) `, [area, stationCode, epoch, T, H, hi]); broadcast('new-area-reading', { @@ -249,41 +247,39 @@ app.post('/api/area-readings', async (req, res) => { heatIndex: hi }); - const y = estNow.getFullYear(), m = pad2(estNow.getMonth()+1), d = pad2(estNow.getDate()); - const dateKey = `${y}${m}${d}`; + 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(FROM_UNIXTIME(epoch_ms/1000)) = CURDATE() + WHERE DATE(FROM_UNIXTIME(epoch_ms/1000))=CURDATE() ORDER BY epoch_ms `); - let csvUrl = null; + 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); } const weather = await fetchCurrentWeather(); const text = - `*_${shift} shift ${area} temp check for ${slackTs}_*\n` + - `*_Current Weather Forecast for Baltimore: ${weather}_*\n\n` + - `*_${area.toUpperCase()} station:_* ${stationCode}\n` + - `*_Temp:_* ${T} °F 🌡️\n` + - `*_Humidity:_* ${H} % 💦\n` + + `*_${shift} shift ${area} temp check for ${slackTs}_*\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' } } - ); + await axios.post(process.env.SLACK_WEBHOOK_URL, { text }, { + headers:{ 'Content-Type':'application/json' } + }); - res.json({ success: true, csvUrl }); + res.json({ success:true, csvUrl }); } catch (err) { console.error('POST /api/area-readings error:', err); res.status(500).json({ error: err.message }); } }); -// ─── Fetch All & Export ─────────────────────────────────────────────────────── -app.get('/api/readings', async (req, res) => { +// ─── Fetch & Export ───────────────────────────────────────────────────────── +app.get('/api/readings', async (req,res) => { try { const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`); res.json(rows); @@ -292,14 +288,17 @@ app.get('/api/readings', async (req, res) => { res.status(500).json({ error: err.message }); } }); -app.get('/api/export', async (req, res) => { +app.get('/api/export', async (req,res) => { try { const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`); - res.setHeader('Content-disposition', 'attachment; filename=readings.csv'); - res.set('Content-Type', 'text/csv'); + res.setHeader('Content-disposition','attachment; filename=readings.csv'); + 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) { @@ -312,4 +311,3 @@ app.get('/api/export', async (req, res) => { app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); }); -