feat: Add a real-time Shelly device status dashboard with WebSocket updates and associated model images.

This commit is contained in:
sebseb7
2026-01-18 04:57:26 -05:00
parent c512ca9549
commit 5333a3770a
8 changed files with 598 additions and 3 deletions

583
status_server.js Normal file
View File

@@ -0,0 +1,583 @@
import http from 'http';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { WebSocketServer } from 'ws';
import sqlite3 from 'sqlite3';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const PORT = 8081;
const MODEL_PICS_DIR = path.join(__dirname, 'modelPics');
// SQLite database connection (read-only for status queries)
const db = new sqlite3.Database('devices.db', sqlite3.OPEN_READONLY);
// WebSocket clients for broadcasting
const wsClients = new Set();
// Query initial status data
function getStatusData() {
return new Promise((resolve, reject) => {
const sql = `
SELECT d.mac, d.model, d.connected, d.last_seen,
c.id as channel_id, c.component, c.field, c.type,
(SELECT e.event FROM events e WHERE e.channel_id = c.id ORDER BY e.id DESC LIMIT 1) as last_event,
(SELECT e.timestamp FROM events e WHERE e.channel_id = c.id ORDER BY e.id DESC LIMIT 1) as last_ts
FROM devices d
LEFT JOIN channels c ON c.mac = d.mac
ORDER BY d.mac, c.component, c.field
`;
db.all(sql, [], (err, rows) => {
if (err) reject(err);
else {
// Group by device
const devices = {};
for (const row of rows) {
if (!devices[row.mac]) {
devices[row.mac] = {
mac: row.mac,
model: row.model,
connected: row.connected,
last_seen: row.last_seen,
channels: []
};
}
if (row.channel_id) {
devices[row.mac].channels.push({
id: row.channel_id,
component: row.component,
field: row.field,
type: row.type,
event: row.last_event,
timestamp: row.last_ts
});
}
}
resolve(Object.values(devices));
}
});
});
}
// Broadcast event to all connected WebSocket clients
export function broadcastEvent(mac, component, field, type, event) {
const message = JSON.stringify({
type: 'event',
mac,
component,
field,
eventType: type,
event,
timestamp: new Date().toISOString()
});
for (const client of wsClients) {
if (client.readyState === 1) { // OPEN
client.send(message);
}
}
}
// HTML Dashboard
const dashboardHTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shelly Status Dashboard</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--bg-primary: #0f0f14;
--bg-secondary: #1a1a24;
--bg-card: rgba(30, 30, 45, 0.8);
--border-color: rgba(255, 255, 255, 0.1);
--text-primary: #ffffff;
--text-secondary: #a0a0b0;
--accent-online: #22c55e;
--accent-offline: #ef4444;
--accent-blue: #3b82f6;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background: var(--bg-primary);
color: var(--text-primary);
min-height: 100vh;
padding: 2rem;
}
.header {
text-align: center;
margin-bottom: 2rem;
}
.header h1 {
font-size: 2rem;
font-weight: 700;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.header p {
color: var(--text-secondary);
margin-top: 0.5rem;
}
.status-indicator {
display: inline-flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
}
.status-dot {
width: 10px;
height: 10px;
border-radius: 50%;
animation: pulse 2s infinite;
}
.status-dot.connected {
background: var(--accent-online);
box-shadow: 0 0 10px var(--accent-online);
}
#connection-status.connected {
color: var(--accent-online);
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.devices-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
gap: 1.5rem;
max-width: 1400px;
margin: 0 auto;
}
.device-card {
background: var(--bg-card);
border: 1px solid var(--border-color);
border-radius: 16px;
padding: 1.5rem;
backdrop-filter: blur(10px);
transition: transform 0.2s, box-shadow 0.2s;
}
.device-card:hover {
transform: translateY(-4px);
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
}
.device-card.flash {
animation: flash-update 0.5s ease-out;
}
@keyframes flash-update {
0% { box-shadow: 0 0 30px rgba(59, 130, 246, 0.8); }
100% { box-shadow: none; }
}
.device-header {
display: flex;
align-items: center;
gap: 1rem;
margin-bottom: 1rem;
padding-bottom: 1rem;
border-bottom: 1px solid var(--border-color);
}
.device-image {
width: 64px;
height: 64px;
object-fit: contain;
border-radius: 8px;
background: var(--bg-secondary);
padding: 8px;
}
.device-info {
flex: 1;
}
.device-mac {
font-family: monospace;
font-size: 0.9rem;
font-weight: 600;
}
.device-model {
font-size: 0.75rem;
color: var(--text-secondary);
margin-top: 2px;
}
.device-status {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.375rem 0.75rem;
border-radius: 999px;
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
}
.device-status.online {
background: rgba(34, 197, 94, 0.2);
color: var(--accent-online);
}
.device-status.offline {
background: rgba(239, 68, 68, 0.2);
color: var(--accent-offline);
}
.device-status .dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
}
.channels-table {
width: 100%;
font-size: 0.8rem;
}
.channels-table th {
text-align: left;
color: var(--text-secondary);
font-weight: 500;
padding: 0.5rem 0;
border-bottom: 1px solid var(--border-color);
}
.channels-table td {
padding: 0.5rem 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}
.channels-table tr:last-child td {
border-bottom: none;
}
.channel-component {
font-family: monospace;
color: var(--accent-blue);
}
.channel-field {
color: var(--text-secondary);
}
.channel-event {
font-family: monospace;
font-weight: 500;
}
.channel-timestamp {
font-size: 0.7rem;
color: var(--text-secondary);
}
.channel-event.flash {
animation: value-flash 0.5s ease-out;
}
@keyframes value-flash {
0% { color: #fbbf24; transform: scale(1.1); }
100% { color: inherit; transform: scale(1); }
}
.empty-state {
text-align: center;
padding: 4rem 2rem;
color: var(--text-secondary);
}
.empty-state svg {
width: 64px;
height: 64px;
margin-bottom: 1rem;
opacity: 0.5;
}
</style>
</head>
<body>
<div class="header">
<h1>Shelly Status Dashboard</h1>
<p class="status-indicator">
<span class="status-dot" id="ws-dot"></span>
<span id="connection-status">Connecting...</span>
</p>
</div>
<div id="devices-container" class="devices-grid">
<div class="empty-state">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2z" />
</svg>
<p>Loading devices...</p>
</div>
</div>
<script>
let devices = {};
let ws;
function connectWebSocket() {
ws = new WebSocket('ws://' + window.location.host);
ws.onopen = () => {
document.getElementById('ws-dot').classList.add('connected');
document.getElementById('connection-status').textContent = 'Connected';
document.getElementById('connection-status').classList.add('connected');
};
ws.onclose = () => {
document.getElementById('ws-dot').classList.remove('connected');
document.getElementById('connection-status').textContent = 'Disconnected - Reconnecting...';
document.getElementById('connection-status').classList.remove('connected');
setTimeout(connectWebSocket, 2000);
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'init') {
// Initial data load
devices = {};
for (const device of data.devices) {
devices[device.mac] = device;
}
renderDevices();
} else if (data.type === 'event') {
// Real-time event update
handleEvent(data);
}
};
}
function handleEvent(data) {
const { mac, component, field, event, eventType } = data;
if (!devices[mac]) {
// New device, request full refresh
return;
}
// Flash the device card
const card = document.querySelector(\`[data-mac="\${mac}"]\`);
if (card) {
card.classList.remove('flash');
void card.offsetWidth; // Trigger reflow
card.classList.add('flash');
}
// Update channel value
const device = devices[mac];
let channel = device.channels.find(c => c.component === component && c.field === field);
if (channel) {
channel.event = event;
channel.timestamp = data.timestamp;
} else {
device.channels.push({
component,
field,
type: eventType,
event,
timestamp: data.timestamp
});
}
// Update online status if it's a system.online event
if (component === 'system' && field === 'online') {
device.connected = event === 'true' || event === true ? 1 : 0;
}
// Re-render the specific device card
renderDevice(device);
// Flash the updated value
const eventCell = document.querySelector(\`[data-mac="\${mac}"] [data-channel="\${component}_\${field}"]\`);
if (eventCell) {
eventCell.classList.remove('flash');
void eventCell.offsetWidth;
eventCell.classList.add('flash');
}
}
function renderDevices() {
const container = document.getElementById('devices-container');
if (Object.keys(devices).length === 0) {
container.innerHTML = \`
<div class="empty-state">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2z" />
</svg>
<p>No devices found</p>
</div>
\`;
return;
}
container.innerHTML = Object.values(devices).map(d => renderDeviceHTML(d)).join('');
}
function renderDevice(device) {
const existing = document.querySelector(\`[data-mac="\${device.mac}"]\`);
if (existing) {
const temp = document.createElement('div');
temp.innerHTML = renderDeviceHTML(device);
existing.outerHTML = temp.innerHTML;
}
}
function renderDeviceHTML(device) {
const isOnline = device.connected === 1;
const statusClass = isOnline ? 'online' : 'offline';
const statusText = isOnline ? 'Online' : 'Offline';
const channelsHTML = device.channels.length > 0 ? \`
<table class="channels-table">
<thead>
<tr>
<th>Component</th>
<th>Field</th>
<th>Value</th>
<th>When</th>
</tr>
</thead>
<tbody>
\${device.channels.map(ch => \`
<tr>
<td class="channel-component">\${ch.component}</td>
<td class="channel-field">\${ch.field}</td>
<td class="channel-event" data-channel="\${ch.component}_\${ch.field}">\${ch.event ?? '-'}</td>
<td class="channel-timestamp">\${formatTimestamp(ch.timestamp)}</td>
</tr>
\`).join('')}
</tbody>
</table>
\` : '<p style="color: var(--text-secondary); font-size: 0.8rem;">No channels</p>';
return \`
<div class="device-card" data-mac="\${device.mac}">
<div class="device-header">
<img class="device-image" src="/modelPics/\${device.model}.png"
onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 24 24%22 fill=%22%23666%22><rect width=%2224%22 height=%2224%22 rx=%224%22/><text x=%2212%22 y=%2216%22 text-anchor=%22middle%22 fill=%22%23999%22 font-size=%228%22>?</text></svg>'"
alt="\${device.model}">
<div class="device-info">
<div class="device-mac">\${device.mac}</div>
<div class="device-model">\${device.model}</div>
</div>
<div class="device-status \${statusClass}">
<span class="dot"></span>
\${statusText}
</div>
</div>
\${channelsHTML}
</div>
\`;
}
function formatTimestamp(ts) {
if (!ts) return '-';
const date = new Date(ts);
const now = new Date();
const diffMs = now - date;
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
if (diffMins < 1) return 'just now';
if (diffMins < 60) return \`\${diffMins}m ago\`;
if (diffHours < 24) return \`\${diffHours}h ago\`;
if (diffDays < 7) return \`\${diffDays}d ago\`;
return date.toLocaleDateString();
}
connectWebSocket();
</script>
</body>
</html>`;
// Create HTTP server
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
// Serve model images
if (url.pathname.startsWith('/modelPics/')) {
const filename = path.basename(url.pathname);
const filepath = path.join(MODEL_PICS_DIR, filename);
if (fs.existsSync(filepath)) {
res.writeHead(200, { 'Content-Type': 'image/png' });
fs.createReadStream(filepath).pipe(res);
} else {
res.writeHead(404);
res.end('Not found');
}
return;
}
// Serve dashboard
if (url.pathname === '/' || url.pathname === '/index.html') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(dashboardHTML);
return;
}
res.writeHead(404);
res.end('Not found');
});
// Create WebSocket server attached to HTTP server
const wss = new WebSocketServer({ server });
wss.on('connection', async (ws) => {
console.log('[Status] Browser client connected');
wsClients.add(ws);
// Send initial status data
try {
const devices = await getStatusData();
ws.send(JSON.stringify({ type: 'init', devices }));
} catch (err) {
console.error('[Status] Error fetching initial data:', err);
}
ws.on('close', () => {
console.log('[Status] Browser client disconnected');
wsClients.delete(ws);
});
});
// Start server function
export function startStatusServer() {
server.listen(PORT, () => {
console.log(`[Status] Dashboard server running at http://localhost:${PORT}`);
});
}
// Allow running standalone
if (process.argv[1] === fileURLToPath(import.meta.url)) {
startStatusServer();
}