Files
machineGroupControl/src/nodeClass.js

281 lines
8.9 KiB
JavaScript
Raw Normal View History

2026-03-11 11:12:52 +01:00
const { outputUtils, configManager, convert } = require("generalFunctions");
const Specific = require("./specificClass");
class nodeClass {
/**
* Create a MeasurementNode.
* @param {object} uiConfig - Node-RED node configuration.
* @param {object} RED - Node-RED runtime API.
* @param {object} nodeInstance - The Node-RED node instance.
* @param {string} nameOfNode - The name of the node, used for
*/
constructor(uiConfig, RED, nodeInstance, nameOfNode) {
// Preserve RED reference for HTTP endpoints if needed
this.node = nodeInstance; // This is the Node-RED node instance, we can use this to send messages and update status
this.RED = RED; // This is the Node-RED runtime API, we can use this to create endpoints if needed
this.name = nameOfNode; // This is the name of the node, it should match the file name and the node type in Node-RED
this.source = null; // Will hold the specific class instance
// Load default & UI config
this._loadConfig(uiConfig, this.node);
// Instantiate core Measurement class
this._setupSpecificClass();
// Wire up event and lifecycle handlers
this._bindEvents();
this._registerChild();
this._startTickLoop();
this._attachInputHandler();
this._attachCloseHandler();
}
/**
* Load and merge default config with user-defined settings.
* @param {object} uiConfig - Raw config from Node-RED UI.
*/
_loadConfig(uiConfig, node) {
const cfgMgr = new configManager();
this.defaultConfig = cfgMgr.getConfig(this.name);
2026-03-11 11:12:52 +01:00
const flowUnit = this._resolveUnitOrFallback(uiConfig.unit, 'volumeFlowRate', 'm3/h', 'flow');
// Build config: base sections (no domain-specific config for group controller)
this.config = cfgMgr.buildConfig(this.name, uiConfig, node.id);
// Utility for formatting outputs
this._output = new outputUtils();
}
2026-03-11 11:12:52 +01:00
_resolveUnitOrFallback(candidate, expectedMeasure, fallbackUnit, label) {
const raw = typeof candidate === "string" ? candidate.trim() : "";
const fallback = String(fallbackUnit || "").trim();
if (!raw) {
return fallback;
}
try {
const desc = convert().describe(raw);
if (expectedMeasure && desc.measure !== expectedMeasure) {
throw new Error(`expected '${expectedMeasure}' but got '${desc.measure}'`);
}
return raw;
} catch (error) {
this.node?.warn?.(`Invalid ${label} unit '${raw}' (${error.message}). Falling back to '${fallback}'.`);
return fallback;
}
}
_updateNodeStatus() {
2025-10-02 17:08:41 +02:00
//console.log('Updating node status...');
const mg = this.source;
const mode = mg.mode;
const scaling = mg.scaling;
2025-09-23 11:19:22 +02:00
// Add safety checks for measurements
const totalFlow = mg.measurements
?.type("flow")
?.variant("predicted")
?.position("atequipment")
2026-03-11 11:12:52 +01:00
?.getCurrentValue(mg?.unitPolicy?.output?.flow || 'm3/h') || 0;
2025-09-23 11:19:22 +02:00
const totalPower = mg.measurements
?.type("power")
?.variant("predicted")
2025-10-02 17:08:41 +02:00
?.position("atEquipment")
2026-03-11 11:12:52 +01:00
?.getCurrentValue(mg?.unitPolicy?.output?.power || 'kW') || 0;
2025-09-23 11:19:22 +02:00
// Calculate total capacity based on available machines with safety checks
const availableMachines = Object.values(mg.machines || {}).filter((machine) => {
// Safety check: ensure machine and machine.state exist
if (!machine || !machine.state || typeof machine.state.getCurrentState !== 'function') {
2026-02-23 13:17:39 +01:00
mg.logger?.warn(`Machine missing or invalid: ${machine?.config?.general?.id || 'unknown'}`);
2025-09-23 11:19:22 +02:00
return false;
}
const state = machine.state.getCurrentState();
const mode = machine.currentMode;
return !(
state === "off" ||
state === "maintenance" ||
mode === "maintenance"
);
});
2025-09-23 11:19:22 +02:00
const totalCapacity = Math.round((mg.dynamicTotals?.flow?.max || 0) * 1) / 1;
// Determine overall status based on available machines
2025-09-23 11:19:22 +02:00
const status = availableMachines.length > 0
? `${availableMachines.length} machine(s) connected`
: "No machines";
let scalingSymbol = "";
2025-09-23 11:19:22 +02:00
switch ((scaling || "").toLowerCase()) {
case "absolute":
2025-09-23 11:19:22 +02:00
scalingSymbol = "Ⓐ";
break;
case "normalized":
2025-09-23 11:19:22 +02:00
scalingSymbol = "Ⓝ";
break;
default:
2025-09-23 11:19:22 +02:00
scalingSymbol = mode || "";
break;
}
2025-09-23 11:19:22 +02:00
const text = ` ${mode || 'Unknown'} | ${scalingSymbol}: 💨=${Math.round(totalFlow)}/${totalCapacity} | ⚡=${Math.round(totalPower)} | ${status}`;
return {
fill: availableMachines.length > 0 ? "green" : "red",
shape: "dot",
text,
};
}
/**
* Instantiate the core logic and store as source.
*/
_setupSpecificClass() {
this.source = new Specific(this.config);
this.node.source = this.source; // Store the source in the node instance for easy access
}
/**
* Bind events to Node-RED status updates. Using internal emitter. --> REMOVE LATER WE NEED ONLY COMPLETE CHILDS AND THEN CHECK FOR UPDATES
*/
_bindEvents() {
this.source.emitter.on("mAbs", (val) => {
this.node.status({
fill: "green",
shape: "dot",
text: `${val} ${this.config.general.unit}`,
});
});
}
/**
* Register this node as a child upstream and downstream.
* Delayed to avoid Node-RED startup race conditions.
*/
_registerChild() {
setTimeout(() => {
this.node.send([
null,
null,
{
topic: "registerChild",
payload: this.node.id,
positionVsParent:
this.config?.functionality?.positionVsParent || "atEquipment",
},
]);
}, 100);
}
/**
* Start the periodic tick loop to drive the Measurement class.
*/
_startTickLoop() {
setTimeout(() => {
this._tickInterval = setInterval(() => this._tick(), 1000);
// Update node status on nodered screen every second ( this is not the best way to do this, but it works for now)
this._statusInterval = setInterval(() => {
const status = this._updateNodeStatus();
this.node.status(status);
}, 1000);
}, 1000);
}
/**
* Execute a single tick: update measurement, format and send outputs.
*/
_tick() {
const raw = this.source.getOutput();
2025-11-06 11:18:38 +01:00
const processMsg = this._output.formatMsg(raw, this.source.config, "process");
const influxMsg = this._output.formatMsg(raw, this.source.config, "influxdb");
// Send only updated outputs on ports 0 & 1
this.node.send([processMsg, influxMsg]);
}
/**
* Attach the node's input handler, routing control messages to the class.
*/
_attachInputHandler() {
this.node.on(
"input",
2025-07-02 10:52:37 +02:00
async (msg, send, done) => {
2026-02-23 13:17:39 +01:00
const mg = this.source;
const RED = this.RED;
try {
switch (msg.topic) {
2026-02-23 13:17:39 +01:00
case "registerChild": {
const childId = msg.payload;
const childObj = RED.nodes.getNode(childId);
if (!childObj || !childObj.source) {
mg.logger.warn(`registerChild skipped: missing child/source for id=${childId}`);
break;
}
mg.logger.debug(`Registering child: ${childId}, found: ${!!childObj}, source: ${!!childObj?.source}`);
2026-02-23 13:17:39 +01:00
mg.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent);
mg.logger.debug(`Total machines after registration: ${Object.keys(mg.machines || {}).length}`);
2026-02-23 13:17:39 +01:00
break;
}
case "setMode": {
const mode = msg.payload;
2025-09-23 15:03:57 +02:00
mg.setMode(mode);
break;
}
case "setScaling": {
const scaling = msg.payload;
mg.setScaling(scaling);
break;
}
2026-02-23 13:17:39 +01:00
case "Qd": {
const Qd = parseFloat(msg.payload);
const sourceQd = "parent";
if (isNaN(Qd)) {
2026-02-23 13:17:39 +01:00
mg.logger.error(`Invalid demand value: ${msg.payload}`);
break;
}
try {
await mg.handleInput(sourceQd, Qd);
msg.topic = mg.config.general.name;
msg.payload = "done";
send(msg);
2026-02-23 13:17:39 +01:00
} catch (error) {
mg.logger.error(`Failed to process Qd: ${error.message}`);
}
break;
2026-02-23 13:17:39 +01:00
}
default:
2025-07-02 10:52:37 +02:00
mg.logger.warn(`Unknown topic: ${msg.topic}`);
break;
}
2026-02-23 13:17:39 +01:00
} catch (error) {
mg.logger.error(`Input handler failure: ${error.message}`);
}
2026-02-23 13:17:39 +01:00
if (typeof done === 'function') done();
}
);
}
/**
* Clean up timers and intervals when Node-RED stops the node.
*/
_attachCloseHandler() {
this.node.on("close", (done) => {
clearInterval(this._tickInterval);
2025-07-02 10:52:37 +02:00
clearInterval(this._statusInterval);
Fix stale flow cache on MGC shutdown; correct NCog physics tests ### Bug fix — stale flow cache on shutdown (specificClass.js) When turnOffAllMachines() fires (negative demand, zero flow demand, or safety trip), the MGC was only shutting pumps down. The pumps' last emitted predicted flow / power stayed in the MeasurementContainer, so the parent pumpingStation kept computing net flow from cached non-zero values — reading the MGC as "still draining" when it wasn't. Net: net-flow direction and safety triggers misfired during and shortly after an MGC shutdown. Fix: after shutting down all machines, write 0 to the predicted flow (downstream + atEquipment) and predicted power (atEquipment) slots so the cache reflects reality immediately. ### Correctness — async/await on shutdown (specificClass.js) Two call sites invoked turnOffAllMachines() without awaiting it, so the subsequent `return` raced the shutdown promises. Now awaited. Also DRY'd one inline shutdown loop into a call to turnOffAllMachines(). ### Physics correction — NCog for centrifugal pumps (integration tests) The previous tests asserted NCog > 0 for centrifugal pumps. That's physically wrong: for variable-speed centrifugal pumps P ∝ n³ and Q ∝ n, so Q/P ∝ 1/n² is monotonically decreasing with speed. Peak efficiency (peak Q/P) is always at minimum speed → cogIndex = 0 → NCog = 0 by the current formula. Tests now: - Assert NCog == 0 for all centrifugal configurations - Assert distributeByNCog() falls back to equal distribution when NCog == 0 (confirmed by the existing tests 4-6 that slope-based redistribution is what actually differentiates pumps with different BEPs — not NCog) This matches the actual implementation; the previous tests were asserting an idealised COG model that doesn't apply here. ### Editor hygiene (mgc.html, nodeClass.js) - mgc.html: add missing asset-menu defaults (uuid, supplier, category, assetType, model, unit) — brings MGC in line with rotatingMachine and pumpingStation editor shapes. - nodeClass.js: clear node status badge on close. All 13 tests (basic + integration) pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 17:51:10 +02:00
this.node.status({}); // clear node status badge
2026-02-23 13:17:39 +01:00
if (typeof done === 'function') done();
});
}
}
module.exports = nodeClass; // Export the class for Node-RED to use