@gravypower/node-red-franklinwh
Version:
Node-RED node to control FranklinWH gateway
95 lines (82 loc) • 3.56 kB
JavaScript
const apiHandler = require('../../../api-handler');
module.exports = function(RED) {
const VALID_MODES = {
'self': 'Self-consumption',
'tou': 'Time of Use',
'emer': 'Emergency Backup'
};
function FranklinWHSetModeNode(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;
}
// Set initial status based on configuration
if (!config.usePayload && config.mode) {
node.status({fill:"blue", shape:"dot", text:`Default: ${VALID_MODES[config.mode]}`});
} else {
node.status({fill:"grey", shape:"ring", text:"waiting for input"});
}
node.on("input", async function (msg, send, done) {
let mode;
try {
// Determine mode source and validate
if (config.usePayload) {
if (msg.payload === undefined || msg.payload === null) {
throw new Error('Payload is empty. Mode must be specified.');
}
mode = msg.payload;
} else if (config.mode) {
mode = config.mode;
} else {
throw new Error('No mode specified. Configure default mode or enable payload usage.');
}
// Validate mode type and format
if (typeof mode !== 'string') {
throw new Error('Mode must be a string value');
}
// Convert mode to lowercase and trim
mode = mode.toLowerCase().trim();
// Validate mode value
if (!Object.keys(VALID_MODES).includes(mode)) {
throw new Error(`Invalid mode: ${mode}. Valid modes are: ${Object.keys(VALID_MODES).map(k => `${k} (${VALID_MODES[k]})`).join(', ')}`);
}
// Show processing status
node.status({fill:"yellow", shape:"dot", text:`Setting: ${VALID_MODES[mode]}`});
await apiHandler.executeWithRetry(
node,
server,
async (api) => {
const success = await api.setMode(mode);
if (!success) {
throw new Error(`Failed to set mode to ${VALID_MODES[mode]}`);
}
return {
mode,
success,
description: VALID_MODES[mode]
};
},
msg,
send,
done
);
// Update status with success
node.status({fill:"green", shape:"dot", text:`Mode: ${VALID_MODES[mode]}`});
} 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-set-mode", FranklinWHSetModeNode);
}