feat: Implement type casting for channel states and events, refine Shelly device online/offline logic, and improve event handling on server startup.

This commit is contained in:
sebseb7
2026-01-17 00:50:32 -05:00
parent 55e4dc56c3
commit 2468f7b5e0
3 changed files with 67 additions and 13 deletions

View File

@@ -56,20 +56,36 @@ export async function loadRules() {
console.log(`Loaded ${rules.length} rule(s)`);
}
/**
* Cast string value to proper type based on channel type
*/
function castValue(value, type) {
if (value === null || value === undefined) return null;
switch (type) {
case 'boolean':
return value === 'true' || value === true;
case 'range':
return parseInt(value, 10);
case 'enum':
default:
return value;
}
}
/**
* Get current state of a channel
*/
function getChannelState(mac, component, field) {
return new Promise((resolve, reject) => {
db.get(
`SELECT e.event FROM events e
`SELECT e.event, c.type FROM events e
JOIN channels c ON e.channel_id = c.id
WHERE c.mac = ? AND c.component = ? AND c.field = ?
ORDER BY e.id DESC LIMIT 1`,
[mac, component, field],
(err, row) => {
if (err) reject(err);
else resolve(row ? row.event : null);
else resolve(row ? castValue(row.event, row.type) : null);
}
);
});
@@ -137,7 +153,9 @@ function createContext(triggerEvent) {
* Run all rules after an event occurs
*/
export async function runRules(mac, component, field, type, event) {
const triggerEvent = { 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) {