UNPKG

@gravypower/node-red-franklinwh

Version:

Node-RED node to control FranklinWH gateway

91 lines (79 loc) 3.23 kB
const apiHandler = require('../../../api-handler'); module.exports = function(RED) { const SWITCH_NAMES = { 'sw1': 'Switch 1', 'sw2': 'Switch 2', 'sw3': 'Switch 3' }; function formatSwitchStates(states) { return Object.entries(states).map(([id, state]) => ({ id: id, name: SWITCH_NAMES[id], state: state, status: state ? 'ON' : 'OFF' })); } function FranklinWHGetSwitchesNode(config) { RED.nodes.createNode(this, config); const node = this; const server = RED.nodes.getNode(config.server); if (!server) { node.status({fill:"red", shape:"ring", text:"missing config"}); node.error("No server configuration"); return; } node.on("input", async function (msg, send, done) { try { // Show requesting status node.status({fill:"blue", shape:"dot", text:"requesting..."}); await apiHandler.executeWithRetry( node, server, async (api) => { // Get initial switch states and update with real-time data let switches = await api.getSmartSwitches(); switches = await api.updateSmartSwitches(switches); // Format switches for output const formattedSwitches = switches.map(sw => ({ id: sw.id, name: SWITCH_NAMES[sw.id] || sw.name, state: sw.state, status: sw.state ? 'ON' : 'OFF' })); // Create summary text for status const summary = formattedSwitches .filter(sw => sw.state) .map(sw => sw.name) .join(', '); // Update status to show active switches node.status({ fill: "green", shape: "dot", text: summary || "All OFF" }); // Return formatted data return { switches: formattedSwitches, summary: formattedSwitches .map(sw => `${sw.name}: ${sw.status}`) .join(', ') }; }, msg, send, done ); } catch (err) { const errorMsg = err.message || 'Unknown error'; node.status({fill:"red", shape:"ring", text: errorMsg.substring(0, 25)}); node.error("FranklinWH Error: " + errorMsg, msg); if (done) done(err); } }); node.on('close', function(done) { node.status({}); done(); }); } RED.nodes.registerType("franklinwh-get-switches", FranklinWHGetSwitchesNode); }