Compare commits
2 Commits
a381b0e121
...
6061567871
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6061567871 | ||
|
|
e226032d0b |
@@ -15,13 +15,15 @@ const RULES_DIR = path.join(__dirname, 'rules');
|
||||
let rules = [];
|
||||
let db = null;
|
||||
let sendRPCToDevice = null;
|
||||
let statusUpdateCallback = null;
|
||||
|
||||
/**
|
||||
* Initialize rule engine with database and RPC function
|
||||
*/
|
||||
export function initRuleEngine(database, rpcFunction) {
|
||||
export function initRuleEngine(database, rpcFunction, onStatusUpdate = null) {
|
||||
db = database;
|
||||
sendRPCToDevice = rpcFunction;
|
||||
statusUpdateCallback = onStatusUpdate;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -112,7 +114,7 @@ function getAllChannelStates() {
|
||||
/**
|
||||
* Create context object passed to rule scripts
|
||||
*/
|
||||
function createContext(triggerEvent) {
|
||||
function createContext(triggerEvent, ruleName) {
|
||||
return {
|
||||
// The event that triggered this evaluation
|
||||
trigger: triggerEvent,
|
||||
@@ -144,6 +146,13 @@ function createContext(triggerEvent) {
|
||||
}
|
||||
},
|
||||
|
||||
// Push status update to dashboard
|
||||
updateStatus: (status) => {
|
||||
if (statusUpdateCallback) {
|
||||
statusUpdateCallback(ruleName, status);
|
||||
}
|
||||
},
|
||||
|
||||
// Logging
|
||||
log: (...args) => console.log('[Rule]', ...args)
|
||||
};
|
||||
@@ -156,10 +165,10 @@ export async function runRules(mac, component, field, type, event) {
|
||||
// Cast event value to proper type
|
||||
const typedEvent = castValue(event, type);
|
||||
const triggerEvent = { mac, component, field, type, event: typedEvent };
|
||||
const ctx = createContext(triggerEvent);
|
||||
|
||||
for (const rule of rules) {
|
||||
try {
|
||||
const ctx = createContext(triggerEvent, rule._filename);
|
||||
if (typeof rule.run === 'function') {
|
||||
await rule.run(ctx);
|
||||
} else if (typeof rule === 'function') {
|
||||
@@ -179,6 +188,36 @@ export async function reloadRules() {
|
||||
await loadRules();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get status from all rules that have a getStatus() hook
|
||||
*/
|
||||
export async function getRulesStatus() {
|
||||
const statuses = [];
|
||||
for (const rule of rules) {
|
||||
try {
|
||||
if (typeof rule.getStatus === 'function') {
|
||||
const status = await rule.getStatus();
|
||||
statuses.push({
|
||||
name: rule._filename,
|
||||
status
|
||||
});
|
||||
} else {
|
||||
statuses.push({
|
||||
name: rule._filename,
|
||||
status: null
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Error getting status from rule ${rule._filename}:`, err);
|
||||
statuses.push({
|
||||
name: rule._filename,
|
||||
status: { error: err.message }
|
||||
});
|
||||
}
|
||||
}
|
||||
return statuses;
|
||||
}
|
||||
|
||||
/**
|
||||
* Watch rules directory for changes and auto-reload
|
||||
*/
|
||||
|
||||
@@ -71,6 +71,14 @@ function getState(mac) {
|
||||
}
|
||||
|
||||
export default {
|
||||
getStatus() {
|
||||
const state = getState(WATER_BUTTON_MAC);
|
||||
return {
|
||||
storedDuration: state.storedDuration,
|
||||
countMode: state.countMode,
|
||||
timerActive: state.timer !== null
|
||||
};
|
||||
},
|
||||
async run(ctx) {
|
||||
// Auto-on for water button when it connects (only if remote switch is online)
|
||||
if (ctx.trigger.mac === WATER_BUTTON_MAC && ctx.trigger.field === 'online' && ctx.trigger.event === true) {
|
||||
@@ -159,6 +167,14 @@ export default {
|
||||
state.countMode = false;
|
||||
ctx.log(`Count mode ended. Stored duration: ${elapsed}ms`);
|
||||
|
||||
// Push status update to dashboard
|
||||
ctx.updateStatus({
|
||||
storedDuration: state.storedDuration,
|
||||
countMode: false,
|
||||
timerActive: false,
|
||||
lastAction: 'Duration saved'
|
||||
});
|
||||
|
||||
// Persist the new duration
|
||||
persistedState[mac] = { storedDuration: elapsed };
|
||||
saveState(persistedState);
|
||||
@@ -169,10 +185,29 @@ export default {
|
||||
// Normal mode - schedule light to turn on after stored duration
|
||||
ctx.log(`Light off. Will turn on in ${state.storedDuration}ms`);
|
||||
|
||||
// Capture updateStatus for use in timer callback
|
||||
const updateStatus = ctx.updateStatus;
|
||||
|
||||
// Push status update to dashboard
|
||||
updateStatus({
|
||||
storedDuration: state.storedDuration,
|
||||
countMode: false,
|
||||
timerActive: true,
|
||||
lastAction: 'Timer started'
|
||||
});
|
||||
|
||||
state.timer = setTimeout(async () => {
|
||||
ctx.log(`Timer elapsed. Turning light on.`);
|
||||
await setLight(ctx, mac, true, 20);
|
||||
state.timer = null;
|
||||
|
||||
// Push timer completed status
|
||||
updateStatus({
|
||||
storedDuration: state.storedDuration,
|
||||
countMode: false,
|
||||
timerActive: false,
|
||||
lastAction: 'Timer completed'
|
||||
});
|
||||
}, state.storedDuration);
|
||||
}
|
||||
}
|
||||
@@ -202,6 +237,14 @@ export default {
|
||||
state.countMode = true;
|
||||
state.countStart = Date.now();
|
||||
ctx.log('Count mode active. Light stays off. Press button to set duration and turn on.');
|
||||
|
||||
// Push status update to dashboard
|
||||
ctx.updateStatus({
|
||||
storedDuration: state.storedDuration,
|
||||
countMode: true,
|
||||
timerActive: false,
|
||||
lastAction: 'Counting...'
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@ import path from 'path';
|
||||
import sqlite3 from 'sqlite3';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { initRuleEngine, loadRules, runRules, watchRules } from './rule_engine.js';
|
||||
import { broadcastEvent, startStatusServer } from './status_server.js';
|
||||
import { broadcastEvent, broadcastRuleUpdate, startStatusServer } from './status_server.js';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
@@ -174,7 +174,7 @@ const wss = new WebSocketServer({ port: 8080 });
|
||||
console.log('Shelly Agent Server listening on port 8080');
|
||||
|
||||
// Initialize and load rules
|
||||
initRuleEngine(db, sendRPCToDevice);
|
||||
initRuleEngine(db, sendRPCToDevice, broadcastRuleUpdate);
|
||||
loadRules().then(() => {
|
||||
console.log('Rule engine ready');
|
||||
watchRules(); // Auto-reload rules when files change
|
||||
|
||||
169
status_server.js
169
status_server.js
@@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user