feat: Implement real-time rule status updates and dashboard display via WebSockets.

This commit is contained in:
sebseb7
2026-01-18 05:52:54 -05:00
parent a381b0e121
commit e226032d0b
4 changed files with 247 additions and 6 deletions

View File

@@ -4,6 +4,7 @@ import path from 'path';
import { fileURLToPath } from 'url';
import { WebSocketServer } from 'ws';
import sqlite3 from 'sqlite3';
import { getRulesStatus } from './rule_engine.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
@@ -79,6 +80,21 @@ export function broadcastEvent(mac, component, field, type, event) {
}
}
// Broadcast rule status update to all connected WebSocket clients
export function broadcastRuleUpdate(ruleName, status) {
const message = JSON.stringify({
type: 'rule_update',
name: ruleName,
status,
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">
@@ -401,6 +417,70 @@ const dashboardHTML = `<!DOCTYPE html>
color: var(--text-secondary);
margin-top: 2px;
}
/* Rules section */
.section-header {
max-width: 1400px;
margin: 2rem auto 1rem;
font-size: 1.25rem;
font-weight: 600;
color: var(--text-secondary);
display: flex;
align-items: center;
gap: 0.5rem;
}
.section-header svg {
width: 20px;
height: 20px;
}
.rules-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 1rem;
max-width: 1400px;
margin: 0 auto 2rem;
}
.rule-card {
background: var(--bg-card);
border: 1px solid var(--border-color);
border-radius: 12px;
padding: 1rem 1.25rem;
backdrop-filter: blur(10px);
}
.rule-name {
font-family: monospace;
font-size: 0.85rem;
font-weight: 600;
margin-bottom: 0.75rem;
color: var(--accent-blue);
}
.rule-status {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.rule-stat {
background: var(--bg-secondary);
padding: 0.375rem 0.625rem;
border-radius: 6px;
font-size: 0.75rem;
}
.rule-stat-label {
color: var(--text-secondary);
margin-right: 0.25rem;
}
.rule-stat-value {
font-family: monospace;
font-weight: 500;
}
</style>
</head>
<body>
@@ -421,6 +501,15 @@ const dashboardHTML = `<!DOCTYPE html>
</div>
</div>
<div class="section-header">
<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="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
Rules
</div>
<div id="rules-container" class="rules-grid"></div>
<div id="toast-container" class="toast-container"></div>
<script>
@@ -453,13 +542,38 @@ const dashboardHTML = `<!DOCTYPE html>
devices[device.mac] = device;
}
renderDevices();
if (data.rules) {
renderRules(data.rules);
}
} else if (data.type === 'event') {
// Real-time event update
handleEvent(data);
} else if (data.type === 'rule_update') {
// Real-time rule status update
handleRuleUpdate(data);
}
};
}
let currentRules = [];
function handleRuleUpdate(data) {
// Update the rule in our local cache
const ruleIndex = currentRules.findIndex(r => r.name === data.name);
if (ruleIndex >= 0) {
currentRules[ruleIndex].status = data.status;
} else {
currentRules.push({ name: data.name, status: data.status });
}
// Re-render rules
renderRules(currentRules);
// Show toast for the update
const action = data.status.lastAction || 'Status updated';
showToast(data.name, action, data.name, 'event');
}
function handleEvent(data) {
const { mac, component, field, event, eventType } = data;
@@ -649,6 +763,58 @@ const dashboardHTML = `<!DOCTYPE html>
return date.toLocaleDateString();
}
function formatDuration(ms) {
if (ms < 1000) return \`\${ms}ms\`;
const secs = Math.floor(ms / 1000);
if (secs < 60) return \`\${secs}s\`;
const mins = Math.floor(secs / 60);
const remainingSecs = secs % 60;
return \`\${mins}m \${remainingSecs}s\`;
}
function renderRules(rules) {
const container = document.getElementById('rules-container');
currentRules = rules; // Store for updates
if (!rules || rules.length === 0) {
container.innerHTML = '<p style="color: var(--text-secondary); font-size: 0.8rem;">No rules loaded</p>';
return;
}
container.innerHTML = rules.map(rule => {
let statusHTML = '';
if (rule.status === null) {
statusHTML = '<span style="color: var(--text-secondary); font-size: 0.75rem;">No status hook</span>';
} else if (rule.status.error) {
statusHTML = \`<span style="color: var(--accent-offline);">Error: \${rule.status.error}</span>\`;
} else {
// Display each status property as a badge
const stats = Object.entries(rule.status).map(([key, value]) => {
let displayValue = value;
if (key.toLowerCase().includes('duration') && typeof value === 'number') {
displayValue = formatDuration(value);
} else if (typeof value === 'boolean') {
displayValue = value ? '✓' : '✗';
}
return \`
<div class="rule-stat">
<span class="rule-stat-label">\${key}:</span>
<span class="rule-stat-value">\${displayValue}</span>
</div>
\`;
}).join('');
statusHTML = \`<div class="rule-status">\${stats}</div>\`;
}
return \`
<div class="rule-card">
<div class="rule-name">\${rule.name}</div>
\${statusHTML}
</div>
\`;
}).join('');
}
connectWebSocket();
</script>
</body>
@@ -694,7 +860,8 @@ wss.on('connection', async (ws) => {
// Send initial status data
try {
const devices = await getStatusData();
ws.send(JSON.stringify({ type: 'init', devices }));
const rules = await getRulesStatus();
ws.send(JSON.stringify({ type: 'init', devices, rules }));
} catch (err) {
console.error('[Status] Error fetching initial data:', err);
}