Compare commits

..

20 Commits

Author SHA1 Message Date
1009b2f38b Update public/heatmap.html 2025-04-30 09:54:15 +00:00
f34be42792 sql bug fix?
This should fix the sql server issue with the server
2025-04-30 03:43:04 +00:00
66d95fb9c8 Update server.js 2025-04-30 03:34:08 +00:00
100271e022 Update server.js 2025-04-30 03:28:45 +00:00
dfa833e799 Update server.js 2025-04-30 03:04:12 +00:00
612ba2bb24 Update server.js 2025-04-30 02:58:54 +00:00
f0bacd9cde Update server.js 2025-04-30 02:54:22 +00:00
68b421bdac Update public/scripts/trends.js 2025-04-30 02:38:25 +00:00
04100e8d5f Update server.js 2025-04-30 02:37:58 +00:00
8780fb2ea4 Update public/scripts/trends.js 2025-04-30 02:29:04 +00:00
b584087a4e Update server.js 2025-04-30 02:28:32 +00:00
1c312ab0a5 Update public/scripts/trends.js 2025-04-30 02:21:43 +00:00
9283a6d31a Update server.js 2025-04-30 02:20:54 +00:00
bc3ff28ad2 Update server.js 2025-04-30 01:45:41 +00:00
ccc9818242 Update public/scripts/trends.js
time
2025-04-30 01:40:12 +00:00
6cdf71f4bc Update server.js
timing
2025-04-30 01:38:01 +00:00
fd85289d61 Update server.js
update time fromat
2025-04-30 01:30:26 +00:00
34dd53c0fd Update public/scripts/trends.js
fixed time formatting
2025-04-30 01:17:18 +00:00
1989484ec0 Update .env 2025-04-30 00:04:35 +00:00
7afc0a14c7 Update public/trends.html 2025-04-23 02:06:23 +00:00
13 changed files with 589 additions and 885 deletions

7
.env
View File

@ -1,10 +1,13 @@
# Server port # Server port
PORT=3000 PORT=3000
WEATHER_API_KEY=27a2e8429bdc47104adb6572ef9f7ad9
ZIP_CODE=21224
# MariaDB connection # MariaDB connection
DB_CLIENT=mysql DB_CLIENT=mysql
DB_HOST=0.0.0.0 DB_HOST=172.23.0.3
DB_PORT=3307 DB_PORT=3306
DB_USER=joshbaney DB_USER=joshbaney
DB_PASSWORD=Ran0dal5! DB_PASSWORD=Ran0dal5!
DB_NAME=heatmap DB_NAME=heatmap

View File

@ -1,16 +0,0 @@
# Dockerfile
FROM node:18-alpine
# Create app directory
WORKDIR /usr/src/app
# Install dependencies
COPY package*.json ./
RUN npm install --production
# Bundle app source
COPY . .
# Expose port and run
EXPOSE 3000
CMD ["node", "server.js"]

View File

@ -1,14 +0,0 @@
version: '3.8'
services:
fuego-app:
build:
context: .
dockerfile: Dockerfile
extra_hosts:
- "host.docker.internal:host-gateway"
env_file:
- .env
ports:
- "3000:3000"
restart: unless-stopped

View File

@ -1,18 +1,14 @@
{ {
"name": "Amazon-Fuego", "name": "warehouse-heatmap-app",
"version": "1.0.0", "version": "1.0.0",
"main": "server.js", "main": "server.js",
"scripts": { "scripts": {
"start": "node server.js" "start": "node server.js"
}, },
"dependencies": { "dependencies": {
"@aws-sdk/client-s3": "^3.300.0", "express": "^4.18.2",
"axios": "^1.4.0", "mysql2": "^3.2.0",
"body-parser": "^1.20.2", "knex": "^2.4.2",
"csv-stringify": "^6.0.8", "body-parser": "^1.20.2"
"dotenv": "^16.3.1", }
"express": "^4.18.2", }
"mysql2": "^3.3.3",
"sqlite3": "^5.1.6"
}
}

View File

@ -2,38 +2,59 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="/favicon.ico"> <link rel="icon" href="/favicon.ico">
<link rel="stylesheet" href="styles.css"> <link rel="stylesheet" href="styles.css">
<title>Heat Map</title> <title>Heat Map</title>
</head> </head>
<body> <body>
<!-- BINSstyle fixed header -->
<header class="main-header"> <header class="main-header">
<img src="/image/logo.png" class="logo" alt="Amazon Logo"> <img src="/image/logo.png" class="logo" alt="Amazon Logo">
<span class="header-title"> | Fuego - Heat Tracker</span> <span class="header-title"> | Fuego - Heat Tracker</span>
<button class="nav-btn" onclick="location.href='/input.html'">Log Reading</button> <button class="nav-btn" onclick="location.href='/input.html'">Log Reading</button>
<button class="nav-btn" onclick="location.href='/heatmap.html'">Heat Map</button> <button class="nav-btn" onclick="location.href='/heatmap.html'">Heat Map</button>
<button class="nav-btn" onclick="location.href='/trends.html'">Trends</button> <button class="nav-btn" onclick="location.href='/trends.html'">Trends</button>
<button class="nav-btn" onclick="location.href='/input-area.html'">Area Reading</button>
</header> </header>
<div class="page-container"> <div class="heatmap-container">
<div class="heatmap-wrapper">
<!-- Floor selector -->
<div id="floor-selector" class="floor-selector">
<label><input type="radio" name="floor" value="1" checked> Floor 1</label>
<label><input type="radio" name="floor" value="2"> Floor 2</label>
<label><input type="radio" name="floor" value="3"> Floor 3</label>
<label><input type="radio" name="floor" value="4"> Floor 4</label>
</div>
<div class="heatmap-scroll">
<div id="diagram" class="diagram-container"> <div id="diagram" class="diagram-container">
<!-- Dock-door row -->
<div id="dock-row" class="dock-row"></div> <div id="dock-row" class="dock-row"></div>
<!-- Regions: A-Mod (east) now on left, AFE center, B-Mod (west) on right -->
<div class="regions-container">
<div id="region-amod" class="region region-amod">
<div class="ar-center">AR Floor<br>A MOD</div>
</div>
<div id="region-preslam" class="region region-preslam">
<div class="ar-center">Outbound Pre-Slam<br>AFE</div>
</div>
<div id="region-bmod" class="region region-bmod">
<div class="ar-center">AR Floor<br>B MOD</div>
</div>
</div>
<!-- Warehouse rectangle -->
<div class="warehouse"></div> <div class="warehouse"></div>
</div> </div>
</div> </div>
<!-- Tooltip -->
<div id="tooltip" class="tooltip"></div> <div id="tooltip" class="tooltip"></div>
</div> </div>
<script src="scripts/heatmap.js"></script> <script src="scripts/heatmap.js"></script>
</body> </body>
</html> </html>
<script src="scripts/heatmap.js"></script>
</body>
</html>

View File

@ -1,71 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Fuego Heat Tracker</title>
<!-- your other CSS/links here -->
<style>
/* 1) Scrollable container taking full viewport height */
#scroll-container {
height: 100vh;
overflow-y: auto;
scroll-behavior: smooth;
}
/* 2) WebKit browsers */
#scroll-container::-webkit-scrollbar {
width: 12px;
}
#scroll-container::-webkit-scrollbar-track {
background: #f1f1f1;
}
#scroll-container::-webkit-scrollbar-thumb {
background-color: #888;
border-radius: 6px;
border: 3px solid #f1f1f1;
}
#scroll-container::-webkit-scrollbar-thumb:hover {
background-color: #555;
}
/* 3) Firefox */
#scroll-container {
scrollbar-width: thin;
scrollbar-color: #888 #f1f1f1;
}
</style>
</head>
<body>
<div id="scroll-container">
<!-- Your graph/chart -->
<div id="graph" style="height: 60vh; padding: 1rem;">
<!-- e.g. <canvas id="myChart"></canvas> or your chart library mount point -->
</div>
<!-- Your spreadsheet/table -->
<div id="spreadsheet" style="height: 60vh; padding: 1rem;">
<!-- e.g. a table or your react/vanilla table component -->
<table>
<thead>
<tr>
<th>Date/Time</th>
<th>Temperature</th>
<th>Humidity</th>
<th>Heat Index</th>
<th>Location</th>
<th>Direction</th>
</tr>
</thead>
<tbody>
<!-- rows go here -->
</tbody>
</table>
</div>
</div>
<!-- your scripts here -->
<script src="/socket.io.js"></script>
<script src="main.js"></script>
</body>
</html>

View File

@ -8,70 +8,32 @@
<title>Log Dual Readings</title> <title>Log Dual Readings</title>
</head> </head>
<body> <body>
<header class="main-header"> <header class="main-header">
<img src="/image/logo.png" alt="Amazon Logo" class="logo"> <img src="/image/logo.png" alt="Amazon Logo" class="logo">
<span class="header-title"> | Fuego - Heat Tracker</span> <span class="header-title"> | Fuego - Heat Tracker</span>
<button class="nav-btn" onclick="location.href='/input.html'">Log Reading</button> <button class="nav-btn" onclick="location.href='/input.html'">Log Reading</button>
<button class="nav-btn" onclick="location.href='/heatmap.html'">Heat Map</button> <button class="nav-btn" onclick="location.href='/heatmap.html'">Heat Map</button>
<button class="nav-btn" onclick="location.href='/trends.html'">Trends</button> <button class="nav-btn" onclick="location.href='/trends.html'">Trends</button>
</header> </header>
<div class="page-container"> <div class="page-container">
<h1>Enter Inbound & Outbound Readings</h1> <h1>Enter Inbound & Outbound Readings</h1>
<form id="reading-form"> <form id="reading-form">
<fieldset> <fieldset>
<legend>Inbound</legend> <legend>Inbound</legend>
<input class="form-input" id="inboundDoor" type="number" placeholder="Dock Door # (124138,202209)" required> <input class="form-input" id="inboundDoor" type="number" placeholder="Dock Door # (124138,202209)" required>
<input class="form-input" id="inboundTemp" type="number" step="0.1" placeholder="Temperature (°F)" required> <input class="form-input" id="inboundTemp" type="number" step="0.1" placeholder="Temperature (°F)" required>
<input class="form-input" id="inboundHum" type="number" step="0.1" placeholder="Humidity (%)" required> <input class="form-input" id="inboundHum" type="number" step="0.1" placeholder="Humidity (%)" required>
</fieldset> </fieldset>
<fieldset> <fieldset>
<legend>Outbound</legend> <legend>Outbound</legend>
<input class="form-input" id="outboundDoor" type="number" placeholder="Dock Door # (142201)" required> <input class="form-input" id="outboundDoor" type="number" placeholder="Dock Door # (142201)" required>
<input class="form-input" id="outboundTemp" type="number" step="0.1" placeholder="Temperature (°F)" required> <input class="form-input" id="outboundTemp" type="number" step="0.1" placeholder="Temperature (°F)" required>
<input class="form-input" id="outboundHum" type="number" step="0.1" placeholder="Humidity (%)" required> <input class="form-input" id="outboundHum" type="number" step="0.1" placeholder="Humidity (%)" required>
</fieldset> </fieldset>
<button type="submit" class="big-button">Submit Both</button> <button type="submit" class="big-button">Submit Both</button>
</form> </form>
</div> </div>
<script src="scripts/input.js"></script> <script src="scripts/input.js"></script>
</body> </body>
</html> </html>
<script>
// make sure this runs *after* your form is in the DOM
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('readingForm');
form.addEventListener('submit', async e => {
e.preventDefault();
// grab your values
const inbound_dockDoor = +document.querySelector('input[name="inbound_dockDoor"]').value;
const inbound_temperature = +document.querySelector('input[name="inbound_temperature"]').value;
const inbound_humidity = +document.querySelector('input[name="inbound_humidity"]').value;
const outbound_dockDoor = +document.querySelector('input[name="outbound_dockDoor"]').value;
const outbound_temperature = +document.querySelector('input[name="outbound_temperature"]').value;
const outbound_humidity = +document.querySelector('input[name="outbound_humidity"]').value;
const payload = {
inbound_dockDoor,
inbound_temperature,
inbound_humidity,
outbound_dockDoor,
outbound_temperature,
outbound_humidity
};
console.log('👉 Sending payload:', payload);
try {
const resp = await fetch('/api/readings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const data = await resp.json();
console.log('✅ Server response:', data);
} catch (err) {
console.error('❌ Fetch error:', err);
}
});
});
</script>

View File

@ -1,129 +1,51 @@
// dockdoor ranges // door ranges
const doors = [ const doors = [
...Array.from({length: 138 - 124 + 1}, (_, i) => 124 + i), ...Array.from({length: 138 - 124 + 1}, (_, i) => 124 + i),
...Array.from({length: 201 - 142 + 1}, (_, i) => 142 + i), ...Array.from({length: 201 - 142 + 1}, (_, i) => 142 + i),
...Array.from({length: 209 - 202 + 1}, (_, i) => 202 + i), ...Array.from({length: 209 - 202 + 1}, (_, i) => 202 + i),
]; ];
// store readings per door // NOAA heatindex formula
const doorData = {}; function getColorFromHI(H) {
const pct = Math.min(Math.max((H - 70) / 30, 0), 1);
// color by heat index const r = 255;
function getColorFromHI(H) { const g = Math.round(255 * (1 - pct));
const pct = Math.min(Math.max((H - 70) / 30, 0), 1); return `rgba(${r},${g},0,0.8)`;
const r = 255, g = Math.round(255 * (1 - pct)); }
return `rgba(${r},${g},0,0.8)`;
} function createGrid() {
const row = document.getElementById('dock-row');
// build the row of squares doors.forEach(d => {
function createGrid() { const sq = document.createElement('div');
const row = document.getElementById('dock-row'); sq.className = 'dock-square';
doors.forEach(d => { sq.dataset.door = d;
doorData[d] = []; row.appendChild(sq);
const sq = document.createElement('div');
sq.className = 'dock-square';
sq.dataset.door = d;
sq.textContent = d;
row.appendChild(sq);
});
}
// compute stats
function computeStats(arr) {
if (!arr.length) return null;
let sum = 0, max = arr[0], min = arr[0];
arr.forEach(r => {
sum += r.heatIndex;
if (r.heatIndex > max.heatIndex) max = r;
if (r.heatIndex < min.heatIndex) min = r;
});
const avg = (sum / arr.length).toFixed(2);
const latest = arr[arr.length - 1];
return { latest, max, min, avg };
}
// color a square
function fillSquare(door, hi) {
const sq = document.querySelector(`.dock-square[data-door="${door}"]`);
if (sq) sq.style.background = getColorFromHI(hi);
}
// load initial readings
async function loadInitial() {
const all = await fetch('/api/readings').then(r => r.json());
all.forEach(r => {
if (doorData[r.dockDoor]) doorData[r.dockDoor].push(r);
});
Object.entries(doorData).forEach(([d, arr]) => {
const stats = computeStats(arr);
if (stats) fillSquare(d, stats.latest.heatIndex);
});
}
// realtime updates
function subscribeRealtime() {
const es = new EventSource('/api/stream');
es.addEventListener('new-reading', e => {
const r = JSON.parse(e.data);
if (doorData[r.dockDoor]) {
doorData[r.dockDoor].push(r);
fillSquare(r.dockDoor, r.heatIndex);
}
});
}
// tooltips on hover
function setupTooltips() {
const tooltip = document.getElementById('tooltip');
document.querySelectorAll('.dock-square').forEach(sq => {
sq.addEventListener('mouseenter', () => {
const d = Number(sq.dataset.door);
const stats = computeStats(doorData[d]);
if (!stats) return;
tooltip.innerHTML = `
<strong>Door ${d}</strong><br/>
Latest: HI ${stats.latest.heatIndex}, T ${stats.latest.temperature}°F, H ${stats.latest.humidity}%<br/>
Time: ${new Date(stats.latest.timestamp).toLocaleString()}<br/>
Max: ${stats.max.heatIndex} at ${new Date(stats.max.timestamp).toLocaleString()}<br/>
Min: ${stats.min.heatIndex} at ${new Date(stats.min.timestamp).toLocaleString()}<br/>
Avg HI: ${stats.avg}
`;
tooltip.style.display = 'block';
}); });
sq.addEventListener('mousemove', e => { }
tooltip.style.top = `${e.clientY + 10}px`;
tooltip.style.left = `${e.clientX + 10}px`; // apply a new reading to its square
function colorize(door, hi) {
const sq = document.querySelector(`.dock-square[data-door="${door}"]`);
if (!sq) return;
sq.style.background = getColorFromHI(hi);
}
async function init() {
createGrid();
// initial fill
const all = await fetch('/api/readings').then(r=>r.json());
// pick latest per door
const latest = {};
all.forEach(r => { latest[r.dockDoor] = r.heatIndex; });
Object.entries(latest).forEach(([door, hi]) => colorize(door, hi));
// subscribe SSE
const es = new EventSource('/api/stream');
es.addEventListener('new-reading', e => {
const { dockDoor, heatIndex } = JSON.parse(e.data);
colorize(dockDoor, heatIndex);
}); });
sq.addEventListener('mouseleave', () => { }
tooltip.style.display = 'none';
}); document.addEventListener('DOMContentLoaded', init);
});
}
// zoom via CSS vars
function setupZoom() {
const root = document.documentElement.style;
let scale = 1;
const initial = { size: 60, gap: 8, vgap: 24, wh: 200 };
const wrapper = document.querySelector('.heatmap-wrapper');
wrapper.addEventListener('wheel', e => {
if (e.ctrlKey) {
e.preventDefault();
scale += e.deltaY * -0.001;
scale = Math.min(Math.max(scale, 0.5), 3);
root.setProperty('--square-size', `${initial.size * scale}px`);
root.setProperty('--gap', `${initial.gap * scale}px`);
root.setProperty('--vertical-gap', `${initial.vgap * scale}px`);
root.setProperty('--warehouse-height', `${initial.wh * scale}px`);
}
});
}
document.addEventListener('DOMContentLoaded', () => {
createGrid();
loadInitial();
subscribeRealtime();
setupTooltips();
setupZoom();
});

View File

@ -1,161 +1,135 @@
// average helper // public/scripts/trends.js
function average(arr) {
return arr.reduce((a, b) => a + b, 0) / arr.length; // ─── Timeframes ──────────────────────────────────────────────────────────────
const tfConfig = [
{ unit:'hours', count:24, label:'Last 24 Hours' },
{ unit:'days', count:7, label:'Last 7 Days' },
{ unit:'weeks', count:4, label:'Last 4 Weeks' },
{ unit:'months', count:12, label:'Last 12 Months' },
{ unit:'years', count:1, label:'All Time' }
];
// ─── Helpers ─────────────────────────────────────────────────────────────────
function formatEST(epoch) {
return new Date(epoch).toLocaleString('en-US', {
timeZone: 'America/New_York',
month: 'numeric',
day: 'numeric',
year: '2-digit',
hour12: false,
hour: '2-digit',
minute: '2-digit'
}).replace(',', ' @');
} }
function subtract(date, count, unit) {
// interval mappings const d = new Date(date);
const periodKeys = ['hourly','daily','weekly','monthly','yearly']; switch(unit){
const periodLabels = ['Hourly','Daily','Weekly','Monthly','Yearly']; case 'hours': d.setHours(d.getHours() - count); break;
case 'days': d.setDate(d.getDate() - count); break;
// bucket definitions case 'weeks': d.setDate(d.getDate() - 7*count); break;
const periodConfig = { case 'months': d.setMonth(d.getMonth() - count); break;
hourly: { keyFn: r => r.timestamp.slice(0,13), labelFn: k => k.replace('T',' ') }, case 'years': d.setFullYear(d.getFullYear() - count); break;
daily: { keyFn: r => r.timestamp.slice(0,10), labelFn: k => k },
weekly: { keyFn: r => {
const d = new Date(r.timestamp), y = d.getFullYear();
const w = Math.ceil((((d - new Date(y,0,1))/864e5) + new Date(y,0,1).getDay()+1)/7);
return `${y}-W${w}`;
}, labelFn: k => k },
monthly: { keyFn: r => r.timestamp.slice(0,7), labelFn: k => k },
yearly: { keyFn: r => r.timestamp.slice(0,4), labelFn: k => k }
};
// global Chart.js instance
let trendChart, dataTable;
// fetch readings from server
async function fetchReadings() {
const res = await fetch('/api/readings');
return res.ok ? res.json() : [];
}
// determine direction based on dock door #
function getDirection(dock) {
return ( (dock>=124 && dock<=138) || (dock>=202 && dock<=209) )
? 'Inbound'
: 'Outbound';
}
// render DataTable
function renderTable(allReadings) {
const tbody = $('#trendTable tbody').empty();
allReadings.forEach(r => {
const ts = new Date(r.timestamp).toLocaleString('en-US', { timeZone:'America/New_York' });
const dir = getDirection(r.dockDoor);
tbody.append(`
<tr>
<td>${ts}</td>
<td>${r.temperature.toFixed(1)}</td>
<td>${r.humidity.toFixed(1)}</td>
<td>${r.heatIndex.toFixed(1)}</td>
<td>${r.dockDoor}</td>
<td>${dir}</td>
</tr>
`);
});
// initialize or redraw DataTable
if ($.fn.DataTable.isDataTable('#trendTable')) {
dataTable.clear().rows.add($('#trendTable tbody tr')).draw();
} else {
dataTable = $('#trendTable').DataTable({
paging: true,
pageLength: 25,
ordering: true,
order: [[0,'desc']],
autoWidth: false,
scrollX: true
});
} }
return d;
} }
// draw or update chart // ─── State ────────────────────────────────────────────────────────────────────
async function drawTrend() { let readings = [];
const all = await fetchReadings(); let chart;
const slider = document.getElementById('periodSlider');
const periodKey = periodKeys[slider.value];
const cfg = periodConfig[periodKey];
// group & stats // ─── On Load ─────────────────────────────────────────────────────────────────
const groups = {}; document.addEventListener('DOMContentLoaded', async() => {
all.forEach(r => { const data = await fetch('/api/readings').then(r=>r.json());
const key = cfg.keyFn(r); readings = data.map(r=>({
groups[key] = groups[key] || { temps:[], hums:[], his:[] }; ...r,
groups[key].temps.push(r.temperature); ts: formatEST(r.epoch_ms),
groups[key].hums.push(r.humidity); date: new Date(r.epoch_ms)
groups[key].his.push(r.heatIndex); }));
setupUI(); initChart(); updateView();
});
// ─── UI Wiring ────────────────────────────────────────────────────────────────
function setupUI(){
const slider = document.getElementById('timeframe-slider');
const label = document.getElementById('timeframe-label');
slider.addEventListener('input',()=>{
label.textContent = tfConfig[slider.value].label;
updateView();
}); });
label.textContent = tfConfig[slider.value].label;
const labels = Object.keys(groups).sort(); document.getElementsByName('metric').forEach(cb=>cb.addEventListener('change',updateView));
const stats = labels.map(k => {
const g = groups[k];
return {
temp: { avg: average(g.temps).toFixed(2), min: Math.min(...g.temps), max: Math.max(...g.temps) },
hum: { avg: average(g.hums).toFixed(2), min: Math.min(...g.hums), max: Math.max(...g.hums) },
hi: { avg: average(g.his).toFixed(2), min: Math.min(...g.his), max: Math.max(...g.his) }
};
});
// selected toggles document.querySelectorAll('#trends-table thead th.sortable').forEach(th=>{
const checks = Array.from(document.querySelectorAll('#metricToggles input:checked')); th.addEventListener('click', ()=>{
const datasets = checks.map(chk => { const idx = th.cellIndex;
const m = chk.dataset.metric, s = chk.dataset.stat; const asc = !th.classList.contains('asc');
return { const tbody = document.getElementById('trends-table-body');
label: `${m.toUpperCase()} ${s.toUpperCase()}`, const rows = Array.from(tbody.rows);
data: stats.map(x => x[m][s]), rows.sort((a,b)=>{
fill: false, return asc
tension: 0.1 ? a.cells[idx].textContent.localeCompare(b.cells[idx].textContent,undefined,{numeric:true})
}; : b.cells[idx].textContent.localeCompare(a.cells[idx].textContent,undefined,{numeric:true});
});
const ctx = document.getElementById('trendChart').getContext('2d');
if (trendChart) {
trendChart.data.labels = labels.map(cfg.labelFn);
trendChart.data.datasets = datasets;
trendChart.update();
} else {
trendChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels.map(cfg.labelFn),
datasets
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: true },
tooltip: { mode:'index', intersect:false },
zoom: {
pan: { enabled:true, mode:'x', modifierKey:'ctrl' },
zoom: { wheel:{enabled:true}, pinch:{enabled:true}, mode:'x' }
}
},
scales: {
x: { display:true },
y: { display:true }
}
}
});
}
// always update table below
renderTable(all);
}
// wire up controls
document.addEventListener('DOMContentLoaded', () => {
// initial draw
drawTrend();
// slider
document.getElementById('periodSlider')
.addEventListener('input', e => {
document.getElementById('periodLabel').textContent = periodLabels[e.target.value];
drawTrend();
}); });
th.classList.toggle('asc',asc);
rows.forEach(r=>tbody.appendChild(r));
});
});
}
// toggles // ─── Chart.js Setup ──────────────────────────────────────────────────────────
document.querySelectorAll('#metricToggles input') function initChart(){
.forEach(chk => chk.addEventListener('change', drawTrend)); const ctx = document.getElementById('trend-chart').getContext('2d');
}); chart = new Chart(ctx,{
type:'line',
data:{labels:[],datasets:[]},
options:{
scales:{
x:{ title:{display:true,text:'Time (EST)'} },
y:{ title:{display:true,text:'Value'} }
},
interaction:{mode:'index',intersect:false},
plugins:{legend:{position:'top'}},
maintainAspectRatio:false
}
});
}
// ─── Render ───────────────────────────────────────────────────────────────────
function updateView(){
const idx = +document.getElementById('timeframe-slider').value;
const {unit,count} = tfConfig[idx];
const cutoff = subtract(Date.now(),count,unit);
const filtered = readings.filter(r=>r.date>=cutoff);
const selected = Array.from(document.getElementsByName('metric'))
.filter(cb=>cb.checked).map(cb=>cb.value);
const labels = filtered.map(r=>r.ts);
const datasets = [];
if (selected.includes('temperature'))
datasets.push({ label:'Temperature (°F)', data:filtered.map(r=>r.temperature), tension:0.3 });
if (selected.includes('humidity'))
datasets.push({ label:'Humidity (%)', data:filtered.map(r=>r.humidity), tension:0.3 });
if (selected.includes('heatIndex'))
datasets.push({ label:'Heat Index (°F)', data:filtered.map(r=>r.heatIndex), tension:0.3 });
chart.data.labels = labels;
chart.data.datasets = datasets;
chart.update();
const tbody = document.getElementById('trends-table-body');
tbody.innerHTML = '';
filtered.forEach(r=>{
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${r.ts}</td>
<td>${r.temperature.toFixed(1)}</td>
<td>${r.humidity.toFixed(1)}</td>
<td>${r.heatIndex.toFixed(2)}</td>
<td>${r.stationDockDoor}</td>
<td>${r.location}</td>
`;
tbody.appendChild(tr);
});
}

View File

@ -1,176 +1,63 @@
/* ================ CSS VARIABLES ================ */ /* Favicon support (no CSS needed) */
:root {
--square-size: 60px;
--gap: 8px;
--v-gap: 24px;
--warehouse-height: 200px;
}
/* ================ GLOBAL & LAYOUT ================ */ /* BINS Project Header & Buttons */
html, body {
height: 100%;
margin: 0;
padding: 0;
background: #f4f4f4;
font-family: Arial, sans-serif;
}
h1 {
text-align: center;
margin-bottom: 1rem;
}
/* ================ BINS HEADER & NAV BUTTONS ================ */
.main-header { .main-header {
background-color: #232F3E; background-color: #232F3E;
display: flex; display: flex;
align-items: center; align-items: center;
padding: 0.5rem 2rem; padding: 0.5rem 1rem;
position: fixed; position: fixed; top: 0; left: 0; right: 0;
top: 0; left: 0; right: 0; width: 100%; z-index: 1000;
z-index: 1000; }
} .main-header .logo {
.logo { height: 40px;
height: 40px; margin-right: 1rem;
margin-right: 1rem; }
} .main-header .header-title {
.header-title { color: #fff;
color: #fff; font-size: 1.2rem;
font-size: 1.2rem; font-weight: bold;
font-weight: bold; margin-right: auto;
margin-right: auto; }
} .main-header .nav-btn {
.nav-btn { background-color: #FF9900;
background-color: #FF9900; color: #111;
color: #111; border: none;
border: none; border-radius: 5px;
border-radius: 5px; padding: 0.5rem 1rem;
padding: 0.5rem 1rem; margin-left: 0.5rem;
margin-left: 0.5rem; cursor: pointer;
cursor: pointer; font-weight: bold;
font-weight: bold; }
} .main-header .nav-btn:hover {
.nav-btn:hover { background-color: #e48f00;
background-color: #e48f00; }
} .page-container {
margin-top: 70px;
/* ================ PAGE CONTAINER ================ */ width: 95%; margin: 0 auto;
/* full-height container under header, using flex for trends page */ padding: 1rem;
.page-container { background-color: #fff;
margin-top: 70px; /* offset header */ border-radius: 6px;
display: flex; }
flex-direction: column; .form-input, .form-textarea {
width: 100%; width: 90%; margin: 0.5rem auto; display: block;
height: calc(100vh - 70px); padding: 0.5rem; border: 1px solid #ccc; border-radius: 6px;
box-sizing: border-box; }
background: #fff; .big-button {
padding: 1rem; background-color: #28a745; color: white;
} padding: 0.75rem 1.5rem; border: none; border-radius: 6px;
cursor: pointer; font-size: 1rem;
/* ================ FORM STYLES ================ */ margin: 1rem auto; display: block;
.form-input { }
width: 80%; .big-button:hover { background-color: #218838; }
max-width: 400px; .hidden { display: none; }
margin: 1rem auto;
display: block; /* Diagram styling */
padding: 1rem; .diagram-container { width: 95%; margin: 0 auto; text-align: center; }
font-size: 1rem; .dock-row { display: grid; grid-template-columns: repeat(83, 1fr); gap: 4px; margin-bottom: 8px; }
border: 1px solid #ccc; .dock-square { width: 100%; padding-top: 100%; position: relative; background: #ddd; border-radius: 2px; }
border-radius: 6px; .dock-square::after { content: attr(data-door); position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) scale(0.6); color: #333; }
} .warehouse { width: 95%; height: 200px; margin: 0 auto; background: #ccc; border-radius: 6px; }
.big-button {
background-color: #28a745; /* Existing element styles */
color: white; body { font-family: Arial, sans-serif; margin: 20px; }
padding: 0.75rem 1.5rem;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 1rem;
margin: 1rem auto;
display: block;
}
.big-button:hover {
background-color: #218838;
}
fieldset {
border: 1px solid #ccc;
border-radius: 6px;
padding: 1rem;
margin-bottom: 1.5rem;
}
legend {
font-weight: bold;
}
/* ================ TRENDS PAGE SPECIFIC ================ */
/* Controls area stays at top */
#trend-controls {
flex: 0 0 auto;
}
/* Chart container fills all remaining height */
.chart-container {
flex: 1 1 auto;
width: 100%;
position: relative;
}
.chart-container canvas {
width: 100% !important;
height: 100% !important;
}
/* ================ HEATMAP STYLES ================= */
/* (unchanged from before) */
.heatmap-wrapper {
width: 100%;
height: 100%;
overflow-x: auto;
overflow-y: hidden;
display: flex;
justify-content: flex-start;
align-items: center;
}
.diagram-container {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--v-gap);
}
.dock-row {
display: flex;
gap: var(--gap);
}
.dock-square {
width: var(--square-size);
height: var(--square-size);
background: #ddd;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.75rem;
color: #333;
cursor: pointer;
user-select: none;
}
.warehouse {
width: calc((var(--square-size) * 83) + (var(--gap) * 82));
height: var(--warehouse-height);
background: #ccc;
border-radius: 6px;
}
.tooltip {
position: absolute;
pointer-events: none;
background: rgba(0,0,0,0.75);
color: #fff;
padding: 8px;
border-radius: 4px;
font-size: 0.9rem;
line-height: 1.2;
display: none;
z-index: 2000;
}
/* ================ UTILITY ================= */
.hidden {
display: none;
}

View File

@ -10,69 +10,69 @@
<title>Trend Graph & Table</title> <title>Trend Graph & Table</title>
</head> </head>
<body> <body>
<header class="main-header"> <header class="main-header">
<img src="/image/logo.png" class="logo" alt="Amazon Logo" /> <img src="/image/logo.png" class="logo" alt="Amazon Logo" />
<span class="header-title"> | Fuego - Heat Tracker</span> <span class="header-title"> | Fuego - Heat Tracker</span>
<button class="nav-btn" onclick="location.href='/input.html'">Log Reading</button> <button class="nav-btn" onclick="location.href='/input.html'">Log Reading</button>
<button class="nav-btn" onclick="location.href='/heatmap.html'">Heat Map</button> <button class="nav-btn" onclick="location.href='/heatmap.html'">Heat Map</button>
<button class="nav-btn" onclick="location.href='/trends.html'">Trends</button> <button class="nav-btn" onclick="location.href='/trends.html'">Trends</button>
</header> </header>
<div class="page-container"> <div class="page-container">
<h1>Trend Analysis</h1> <h1>Trend Analysis</h1>
<div id="trend-controls" style="text-align:center; margin-bottom:1rem;"> <div id="trend-controls" style="text-align:center; margin-bottom:1rem;">
<!-- Interval slider --> <!-- Interval slider -->
<label for="periodSlider"> <label for="periodSlider">
Interval: <strong><span id="periodLabel">Daily</span></strong> Interval: <strong><span id="periodLabel">Daily</span></strong>
</label><br/> </label><br/>
<input type="range" id="periodSlider" min="0" max="4" step="1" value="1" /> <input type="range" id="periodSlider" min="0" max="4" step="1" value="1" />
<!-- Metric/stat toggles --> <!-- Metric/stat toggles -->
<div id="metricToggles" style="margin-top:1rem;"> <div id="metricToggles" style="margin-top:1rem;">
<label><input type="checkbox" data-metric="temp" data-stat="avg" checked /> Temp Avg</label> <label><input type="checkbox" data-metric="temp" data-stat="avg" checked /> Temp Avg</label>
<label><input type="checkbox" data-metric="temp" data-stat="min" checked /> Temp Min</label> <label><input type="checkbox" data-metric="temp" data-stat="min" checked /> Temp Min</label>
<label><input type="checkbox" data-metric="temp" data-stat="max" checked /> Temp Max</label> <label><input type="checkbox" data-metric="temp" data-stat="max" checked /> Temp Max</label>
<label><input type="checkbox" data-metric="hum" data-stat="avg" checked /> Hum Avg</label> <label><input type="checkbox" data-metric="hum" data-stat="avg" checked /> Hum Avg</label>
<label><input type="checkbox" data-metric="hum" data-stat="min" checked /> Hum Min</label> <label><input type="checkbox" data-metric="hum" data-stat="min" checked /> Hum Min</label>
<label><input type="checkbox" data-metric="hum" data-stat="max" checked /> Hum Max</label> <label><input type="checkbox" data-metric="hum" data-stat="max" checked /> Hum Max</label>
<label><input type="checkbox" data-metric="hi" data-stat="avg" checked /> HI Avg</label> <label><input type="checkbox" data-metric="hi" data-stat="avg" checked /> HI Avg</label>
<label><input type="checkbox" data-metric="hi" data-stat="min" checked /> HI Min</label> <label><input type="checkbox" data-metric="hi" data-stat="min" checked /> HI Min</label>
<label><input type="checkbox" data-metric="hi" data-stat="max" checked /> HI Max</label> <label><input type="checkbox" data-metric="hi" data-stat="max" checked /> HI Max</label>
</div>
</div>
<div class="chart-container">
<canvas id="trendChart"></canvas>
</div>
<!-- Table container -->
<div class="table-container">
<table id="trendTable" class="display" style="width:100%">
<thead>
<tr>
<th>Date/Time</th>
<th>Temperature (°F)</th>
<th>Humidity (%)</th>
<th>Heat Index</th>
<th>Location</th>
<th>Direction</th>
</tr>
</thead>
<tbody>
<!-- populated dynamically -->
</tbody>
</table>
</div> </div>
</div> </div>
<div class="chart-container"> <!-- Chart.js and zoom plugin -->
<canvas id="trendChart"></canvas> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</div> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@2.0.1/dist/chartjs-plugin-zoom.min.js"></script>
<!-- jQuery + DataTables -->
<!-- Table container --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div class="table-container"> <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<table id="trendTable" class="display" style="width:100%"> <!-- Your trends logic -->
<thead> <script src="scripts/trends.js"></script>
<tr>
<th>Date/Time</th>
<th>Temperature (°F)</th>
<th>Humidity (%)</th>
<th>Heat Index</th>
<th>Location</th>
<th>Direction</th>
</tr>
</thead>
<tbody>
<!-- populated dynamically -->
</tbody>
</table>
</div>
</div>
<!-- Chart.js and zoom plugin -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@2.0.1/dist/chartjs-plugin-zoom.min.js"></script>
<!-- jQuery + DataTables -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<!-- Your trends logic -->
<script src="scripts/trends.js"></script>
</body> </body>
</html> </html>

30
s3.js
View File

@ -1,30 +0,0 @@
// s3.js
require('dotenv').config();
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const { stringify } = require('csv-stringify/sync');
const s3 = new S3Client({
region: process.env.AWS_REGION
});
/**
* Uploads a CSV to s3://<bucket>/trends/<key>.csv with public-read ACL.
* @param {string} key Date key like '20250423'
* @param {Array<Object>} rows Array of DB rows to stringify into CSV
* @returns {string} Public URL of the uploaded CSV
*/
async function uploadTrendsCsv(key, rows) {
// Convert rows to CSV string (includes header)
const csv = stringify(rows, { header: true });
const cmd = new PutObjectCommand({
Bucket: process.env.S3_BUCKET_NAME,
Key: `trends/${key}.csv`,
Body: csv,
ContentType: 'text/csv',
ACL: 'public-read'
});
await s3.send(cmd);
return `${process.env.S3_BASE_URL}/${key}.csv`;
}
module.exports = { uploadTrendsCsv };

366
server.js
View File

@ -13,231 +13,301 @@ const PORT = process.env.PORT || 3000;
// In-memory shift counters // In-memory shift counters
const shiftCounters = {}; const shiftCounters = {};
// Helper: format a Date in EST as SQL DATETIME string // ─── Helpers ──────────────────────────────────────────────────────────────────
function formatDateEST(date) { // pad to two digits
const pad = n => n.toString().padStart(2, '0'); function pad2(n) {
return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ` + return n.toString().padStart(2, '0');
`${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
} }
// Helper: format a Date in EST as ISO-like string (no “Z”) // Format epoch_ms → "M/D/YY @HH:mm" (24-hour) in America/New_York
function isoStringEST(date) { function formatForSlack(epoch) {
const pad = n => n.toString().padStart(2, '0'); return new Date(epoch).toLocaleString('en-US', {
return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())}` + timeZone: 'America/New_York',
`T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`; month: 'numeric',
day: 'numeric',
year: '2-digit',
hour12: false,
hour: '2-digit',
minute: '2-digit'
}).replace(',', ' @');
} }
// Compute heat index (NOAA formula) // 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,-0.00683783, -42.379,2.04901523,10.14333127,-0.22475541,
-0.05481717,0.00122874,0.00085282,-0.00000199]; -0.00683783,-0.05481717,0.00122874,0.00085282,-0.00000199
];
const HI = c1 + c2*T + c3*R + c4*T*R const HI = c1 + c2*T + c3*R + c4*T*R
+ c5*T*T + c6*R*R + c7*T*T*R + c5*T*T + c6*R*R + c7*T*T*R
+ c8*T*R*R + c9*T*T*R*R; + c8*T*R*R + c9*T*T*R*R;
return Math.round(HI * 100) / 100; return Math.round(HI * 100) / 100;
} }
// Determine shift info in EST // Determine Day/Night shift & period key from epoch_ms
function getShiftInfo(now) { function getShiftInfo(epoch) {
const estNow = new Date(now.toLocaleString('en-US', { timeZone: 'America/New_York' })); // Convert to EST by string-round-trip
const [h,m] = [estNow.getHours(), estNow.getMinutes()]; const estString = new Date(epoch)
let shift, shiftStart = new Date(estNow); .toLocaleString('en-US', { timeZone: 'America/New_York' });
const est = new Date(estString);
const h = est.getHours(), m = est.getMinutes();
let shift, start = new Date(est);
if (h > 7 || (h === 7 && m >= 0)) { if (h > 7 || (h === 7 && m >= 0)) {
if (h < 17 || (h === 17 && m < 30)) { if (h < 17 || (h === 17 && m < 30)) {
shift = 'Day'; shift = 'Day'; start.setHours(7, 0, 0, 0);
shiftStart.setHours(7,0,0,0);
} else { } else {
shift = 'Night'; shift = 'Night'; start.setHours(17, 30, 0, 0);
shiftStart.setHours(17,30,0,0);
} }
} else { } else {
shift = 'Night'; shift = 'Night';
shiftStart.setDate(shiftStart.getDate() - 1); start.setDate(start.getDate() - 1);
shiftStart.setHours(17,30,0,0); start.setHours(17, 30, 0, 0);
} }
const key = `${shift}-${shiftStart.toISOString().slice(0,10)}-` + const key = `${shift}-${start.toISOString().slice(0,10)}-${start.getHours()}${start.getMinutes()}`;
`${shiftStart.getHours()}${shiftStart.getMinutes()}`; return { shift, key, estNow: est };
return { shift, shiftStart, key, estNow };
} }
// MariaDB connection pool // Fetch current Baltimore weather
async function fetchCurrentWeather() {
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' } }
);
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({ const pool = mysql.createPool({
host: process.env.DB_HOST, 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, user: process.env.DB_USER,
password: process.env.DB_PASSWORD, password: process.env.DB_PASSWORD,
database: process.env.DB_NAME, database: process.env.DB_NAME,
waitForConnections: true, waitForConnections: true,
connectionLimit: 10, connectionLimit: 10,
queueLimit: 0, queueLimit: 0,
connectTimeout: 10000, connectTimeout: 10000
enableKeepAlive: true,
keepAliveInitialDelay: 10000,
}); });
// Ensure readings table exists
(async () => { (async () => {
const createSQL = ` // Create table with epoch_ms only
await pool.execute(`
CREATE TABLE IF NOT EXISTS readings ( CREATE TABLE IF NOT EXISTS readings (
id INT AUTO_INCREMENT PRIMARY KEY, id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
dockDoor INT NOT NULL, location VARCHAR(20) NOT NULL,
direction VARCHAR(10) NOT NULL, stationDockDoor VARCHAR(10) NOT NULL,
timestamp DATETIME NOT NULL, epoch_ms BIGINT NOT NULL,
temperature DOUBLE, temperature DOUBLE,
humidity DOUBLE, humidity DOUBLE,
heatIndex DOUBLE heatIndex DOUBLE,
); INDEX idx_time (epoch_ms),
`; INDEX idx_loc (location)
await pool.execute(createSQL); ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
`);
})(); })();
// SSE setup // ─── Middleware & Static ─────────────────────────────────────────────────────
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname,'public'), { index:'heatmap.html' }));
// ─── SSE Setup ────────────────────────────────────────────────────────────────
let clients = []; let clients = [];
app.get('/api/stream', (req, res) => { app.get('/api/stream',(req,res)=>{
res.set({ res.set({
'Content-Type': 'text/event-stream', 'Content-Type':'text/event-stream',
'Cache-Control': 'no-cache', 'Cache-Control':'no-cache',
Connection: 'keep-alive' 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(event,data){
const msg = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; const msg = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
clients.forEach(c => c.write(msg)); clients.forEach(c=>c.write(msg));
} }
// Middleware & static files // ─── Dual Dock-Door Endpoint ───────────────────────────────────────────────────
app.use(bodyParser.json()); app.post('/api/readings', async (req,res) => {
app.use(express.static(path.join(__dirname, 'public')));
// Dual-reading POST endpoint
app.post('/api/readings', async (req, res) => {
try { try {
console.log('🔔 POST /api/readings body:', req.body); const { inbound={}, outbound={} } = req.body;
const { inbound = {}, outbound = {} } = req.body; const { dockDoor: inD, temperature: inT, humidity: inH } = inbound;
const { dockDoor: inDoor, temperature: inTemp, humidity: inHum } = inbound; const { dockDoor: outD, temperature: outT, humidity: outH } = outbound;
const { dockDoor: outDoor, temperature: outTemp, humidity: outHum } = outbound; if ([inD,inT,inH,outD,outT,outH].some(v=>v==null)) {
return res.status(400).json({ error: 'Missing fields' });
// Validate inputs
if ([inDoor, inTemp, inHum, outDoor, outTemp, outHum].some(v => v === undefined)) {
return res.status(400).json({ error: 'Missing one of inbound/outbound fields' });
} }
// Compute heat indices const epoch = Date.now();
const hiIn = computeHeatIndex(inTemp, inHum); const hiIn = computeHeatIndex(inT, inH);
const hiOut = computeHeatIndex(outTemp, outHum); const hiOut = computeHeatIndex(outT, outH);
const { shift, key, estNow } = getShiftInfo(epoch);
// Shift & period logic shiftCounters[key] = (shiftCounters[key]||0) + 1;
const { shift, shiftStart, key, estNow } = getShiftInfo(new Date());
shiftCounters[key] = (shiftCounters[key] || 0) + 1;
const period = shiftCounters[key]; const period = shiftCounters[key];
const slackTs = formatForSlack(epoch);
// Prepare EST timestamps // Insert inbound + outbound
const sqlTimestamp = formatDateEST(estNow); const sql = `
const broadcastTimestamp = isoStringEST(estNow); INSERT INTO readings(location,stationDockDoor,epoch_ms,temperature,humidity,heatIndex)
VALUES(?,?,?,?,?,?)
// Insert readings into DB
const insertSQL = `
INSERT INTO readings
(dockDoor, direction, timestamp, temperature, humidity, heatIndex)
VALUES (?, ?, ?, ?, ?, ?)
`; `;
await pool.execute(insertSQL, [inDoor, 'inbound', sqlTimestamp, inTemp, inHum, hiIn]); await pool.execute(sql, ['Inbound', String(inD), epoch, inT, inH, hiIn]);
await pool.execute(insertSQL, [outDoor, 'outbound', sqlTimestamp, outTemp, outHum, hiOut]); await pool.execute(sql, ['Outbound', String(outD), epoch, outT, outH, hiOut]);
// Broadcast via SSE (EST) // SSE broadcast
broadcast('new-reading', { broadcast('new-reading', {
dockDoor: inDoor, location: 'Inbound',
direction: 'inbound', stationDockDoor: String(inD),
timestamp: broadcastTimestamp, timestamp: slackTs,
temperature: inTemp, temperature: inT,
humidity: inHum, humidity: inH,
heatIndex: hiIn heatIndex: hiIn
}); });
broadcast('new-reading', { broadcast('new-reading', {
dockDoor: outDoor, location: 'Outbound',
direction: 'outbound', stationDockDoor: String(outD),
timestamp: broadcastTimestamp, timestamp: slackTs,
temperature: outTemp, temperature: outT,
humidity: outHum, humidity: outH,
heatIndex: hiOut heatIndex: hiOut
}); });
// Generate and upload today's CSV, get URL // CSV upload
const dateKey = `${estNow.getFullYear()}${String(estNow.getMonth()+1).padStart(2,'0')}${String(estNow.getDate()).padStart(2,'0')}`; const y=estNow.getFullYear(), m=pad2(estNow.getMonth()+1), d=pad2(estNow.getDate());
const [rows] = await pool.execute( const dateKey=`${y}${m}${d}`;
`SELECT * FROM readings const [rows] = await pool.execute(`
WHERE DATE(timestamp) = CURDATE() SELECT * FROM readings
ORDER BY timestamp ASC` WHERE DATE(FROM_UNIXTIME(epoch_ms/1000))=CURDATE()
); ORDER BY epoch_ms
let csvUrl = null; `);
try { let csvUrl=null;
csvUrl = await uploadTrendsCsv(dateKey, rows); try { csvUrl = await uploadTrendsCsv(dateKey, rows); }
} catch (uploadErr) { catch(e){ console.error('CSV upload error:', e); }
console.error('Failed to upload CSV to S3:', uploadErr);
}
// Flat JSON Slack payload with CSV URL // Slack message
const slackPayload = { const weather = await fetchCurrentWeather();
text: 'New temperature readings recorded', const text =
inbound_dockDoor: inDoor, `*_${shift} shift Period ${period} dock/trailer temperature checks for ${slackTs}_*\n`+
inbound_temperature: inTemp, `*_Current Weather Forecast for Baltimore: ${weather}_*\n\n`+
inbound_humidity: inHum, `*_⬇ Inbound Dock Door 🚛 :_* ${inD}\n`+
hiIn, `*_Temp:_* ${inT} °F 🌡️\n`+
outbound_dockDoor: outDoor, `*_Humidity:_* ${inH} % 💦\n`+
outbound_temperature: outTemp, `*_Heat Index:_* ${hiIn} °F 🥵\n\n`+
outbound_humidity: outHum, `*_⬆ Outbound Dock Door 🚛 :_* ${outD}\n`+
hiOut, `*_Temp:_* ${outT} °F 🌡️\n`+
shift, `*_Humidity:_* ${outH} % 💦\n`+
period, `*_Heat Index:_* ${hiOut} °F 🥵`;
timestamp: broadcastTimestamp,
csvUrl // include the CSV download URL
};
console.log('🛠️ Slack payload:', slackPayload);
await axios.post(process.env.SLACK_WEBHOOK_URL, slackPayload);
res.json({ success: true, shift, period, csvUrl }); 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('❌ POST /api/readings error:', err); console.error('POST /api/readings error:', err);
res.status(500).json({ error: err.message }); res.status(500).json({ error: err.message });
} }
}); });
// Return all readings // ─── Area/Mod Endpoint ───────────────────────────────────────────────────────
app.get('/api/readings', async (req, res) => { app.post('/api/area-readings', async (req,res) => {
try { try {
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY 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 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(?,?,?,?,?,?)
`, [area, stationCode, epoch, T, H, hi]);
broadcast('new-area-reading', {
location: area,
stationDockDoor: stationCode,
timestamp: slackTs,
temperature: T,
humidity: H,
heatIndex: hi
});
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()
ORDER BY epoch_ms
`);
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 ${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' }
});
res.json({ success:true, csvUrl });
} catch (err) {
console.error('POST /api/area-readings error:', err);
res.status(500).json({ error: err.message });
}
});
// ─── 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); res.json(rows);
} catch (err) { } catch (err) {
console.error('❌ GET /api/readings error:', 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) => {
// Export CSV of all readings
app.get('/api/export', async (req, res) => {
try { try {
const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY timestamp ASC`); const [rows] = await pool.execute(`SELECT * FROM readings ORDER BY epoch_ms`);
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,epoch_ms,temperature,humidity,heatIndex\n');
rows.forEach(r => { rows.forEach(r => {
const ts = (r.timestamp instanceof Date) ? formatDateEST(r.timestamp) : r.timestamp; res.write(
res.write(`${r.id},${r.dockDoor},${r.direction},${ts},${r.temperature},${r.humidity},${r.heatIndex}\n`); `${r.id},${r.location},${r.stationDockDoor},${r.epoch_ms},` +
`${r.temperature},${r.humidity},${r.heatIndex}\n`
);
}); });
res.end(); res.end();
} catch (err) { } catch (err) {
console.error('❌ GET /api/export error:', err); console.error('GET /api/export error:', err);
res.status(500).send(err.message); res.status(500).send(err.message);
} }
}); });
// 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}`);
}); });