Files
rotatingMachine/src/nodeClass.js

434 lines
16 KiB
JavaScript
Raw Normal View History

2025-06-25 17:26:13 +02:00
/**
2025-07-01 15:25:07 +02:00
* node class.js
2025-06-25 17:26:13 +02:00
*
* Encapsulates all node logic in a reusable class. In future updates we can split this into multiple generic classes and use the config to specifiy which ones to use.
* This allows us to keep the Node-RED node clean and focused on wiring up the UI and event handlers.
*/
2026-03-11 11:13:26 +01:00
const { outputUtils, configManager, convert } = require('generalFunctions');
2025-06-25 17:26:13 +02:00
const Specific = require("./specificClass");
class nodeClass {
/**
* Create a Node.
* @param {object} uiConfig - Node-RED node configuration.
* @param {object} RED - Node-RED runtime API.
*/
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
2025-07-02 17:07:19 +02:00
this.config = null; // Will hold the merged configuration
2026-02-19 17:36:44 +01:00
this._pressureInitWarned = false;
2025-06-25 17:26:13 +02:00
// Load default & UI config
this._loadConfig(uiConfig,this.node);
2025-07-24 13:15:33 +02:00
// Instantiate core class
2025-07-02 17:07:19 +02:00
this._setupSpecificClass(uiConfig);
2025-06-25 17:26:13 +02:00
// 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();
2026-03-11 11:13:26 +01:00
const resolvedAssetUuid = uiConfig.assetUuid || uiConfig.uuid || null;
const resolvedAssetTagCode = uiConfig.assetTagCode || uiConfig.assetTagNumber || null;
const flowUnit = this._resolveUnitOrFallback(uiConfig.unit, 'volumeFlowRate', 'm3/h', 'flow');
const curveUnits = {
pressure: this._resolveUnitOrFallback(uiConfig.curvePressureUnit, 'pressure', 'mbar', 'curve pressure'),
flow: this._resolveUnitOrFallback(uiConfig.curveFlowUnit || flowUnit, 'volumeFlowRate', flowUnit, 'curve flow'),
power: this._resolveUnitOrFallback(uiConfig.curvePowerUnit, 'power', 'kW', 'curve power'),
control: this._resolveControlUnitOrFallback(uiConfig.curveControlUnit, '%'),
};
2025-06-25 17:26:13 +02:00
// Build config: base sections + rotatingMachine-specific domain config
this.config = cfgMgr.buildConfig(this.name, uiConfig, node.id, {
flowNumber: uiConfig.flowNumber
});
2025-06-25 17:26:13 +02:00
// Override asset with rotatingMachine-specific fields
this.config.asset = {
...this.config.asset,
uuid: resolvedAssetUuid,
tagCode: resolvedAssetTagCode,
tagNumber: uiConfig.assetTagNumber || null,
unit: flowUnit,
curveUnits
2025-06-25 17:26:13 +02:00
};
// Ensure general unit uses resolved flow unit
this.config.general.unit = flowUnit;
2025-06-25 17:26:13 +02:00
// Utility for formatting outputs
this._output = new outputUtils();
}
2026-03-11 11:13:26 +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;
}
}
_resolveControlUnitOrFallback(candidate, fallback = '%') {
const raw = typeof candidate === 'string' ? candidate.trim() : '';
return raw || fallback;
}
2025-06-25 17:26:13 +02:00
/**
* Instantiate the core Measurement logic and store as source.
*/
2025-07-02 17:07:19 +02:00
_setupSpecificClass(uiConfig) {
2025-07-01 15:25:07 +02:00
const machineConfig = this.config;
2025-06-25 17:26:13 +02:00
// need extra state for this
const stateConfig = {
general: {
logging: {
2026-03-11 11:13:26 +01:00
enabled: machineConfig.general.logging.enabled,
logLevel: machineConfig.general.logging.logLevel
2025-06-25 17:26:13 +02:00
}
},
movement: {
2025-11-20 11:09:44 +01:00
speed: Number(uiConfig.speed),
mode: uiConfig.movementMode
2025-06-25 17:26:13 +02:00
},
time: {
2025-07-02 17:07:19 +02:00
starting: Number(uiConfig.startup),
warmingup: Number(uiConfig.warmup),
stopping: Number(uiConfig.shutdown),
coolingdown: Number(uiConfig.cooldown)
2025-06-25 17:26:13 +02:00
}
};
2025-07-01 15:25:07 +02:00
this.source = new Specific(machineConfig, stateConfig);
//store in node
this.node.source = this.source; // Store the source in the node instance for easy access
2025-06-25 17:26:13 +02:00
}
/**
2025-07-01 17:02:51 +02:00
* Bind events to Node-RED status updates. Using internal emitter. --> REMOVE LATER WE NEED ONLY COMPLETE CHILDS AND THEN CHECK FOR UPDATES
2025-06-25 17:26:13 +02:00
*/
_bindEvents() {
2025-07-24 13:15:33 +02:00
2025-06-25 17:26:13 +02:00
}
_updateNodeStatus() {
const m = this.source;
try {
const mode = m.currentMode;
const state = m.state.getCurrentState();
2026-02-19 17:36:44 +01:00
const requiresPressurePrediction = ["operational", "warmingup", "accelerating", "decelerating"].includes(state);
const pressureStatus = typeof m.getPressureInitializationStatus === "function"
? m.getPressureInitializationStatus()
: { initialized: true };
if (requiresPressurePrediction && !pressureStatus.initialized) {
if (!this._pressureInitWarned) {
this.node.warn("Pressure input is not initialized (upstream/downstream missing). Predictions are using minimum pressure.");
this._pressureInitWarned = true;
}
return { fill: "yellow", shape: "ring", text: `${mode}: pressure not initialized` };
}
if (pressureStatus.initialized) {
this._pressureInitWarned = false;
}
2026-03-11 11:13:26 +01:00
const flowUnit = m?.config?.general?.unit || 'm3/h';
const flow = Math.round(m.measurements.type("flow").variant("predicted").position('downstream').getCurrentValue(flowUnit));
2026-02-12 10:48:44 +01:00
const power = Math.round(m.measurements.type("power").variant("predicted").position('atEquipment').getCurrentValue('kW'));
2025-06-25 17:26:13 +02:00
let symbolState;
switch(state){
case "off":
symbolState = "⬛";
break;
case "idle":
symbolState = "⏸️";
break;
case "operational":
symbolState = "⏵️";
break;
case "starting":
symbolState = "⏯️";
break;
case "warmingup":
symbolState = "🔄";
break;
case "accelerating":
symbolState = "⏩";
break;
case "stopping":
symbolState = "⏹️";
break;
case "coolingdown":
symbolState = "❄️";
break;
case "decelerating":
symbolState = "⏪";
break;
case "maintenance":
symbolState = "🔧";
break;
2025-06-25 17:26:13 +02:00
}
const position = m.state.getCurrentPosition();
const roundedPosition = Math.round(position * 100) / 100;
let status;
switch (state) {
case "off":
status = { fill: "red", shape: "dot", text: `${mode}: OFF` };
break;
case "idle":
status = { fill: "blue", shape: "dot", text: `${mode}: ${symbolState}` };
break;
case "operational":
2026-03-11 11:13:26 +01:00
status = { fill: "green", shape: "dot", text: `${mode}: ${symbolState} | ${roundedPosition}% | 💨${flow}${flowUnit} | ⚡${power}kW` };
2025-06-25 17:26:13 +02:00
break;
case "starting":
status = { fill: "yellow", shape: "dot", text: `${mode}: ${symbolState}` };
break;
case "warmingup":
2026-03-11 11:13:26 +01:00
status = { fill: "green", shape: "dot", text: `${mode}: ${symbolState} | ${roundedPosition}% | 💨${flow}${flowUnit} | ⚡${power}kW` };
2025-06-25 17:26:13 +02:00
break;
case "accelerating":
2026-03-11 11:13:26 +01:00
status = { fill: "yellow", shape: "dot", text: `${mode}: ${symbolState} | ${roundedPosition}%| 💨${flow}${flowUnit} | ⚡${power}kW` };
2025-06-25 17:26:13 +02:00
break;
case "stopping":
status = { fill: "yellow", shape: "dot", text: `${mode}: ${symbolState}` };
break;
case "coolingdown":
status = { fill: "yellow", shape: "dot", text: `${mode}: ${symbolState}` };
break;
case "decelerating":
2026-03-11 11:13:26 +01:00
status = { fill: "yellow", shape: "dot", text: `${mode}: ${symbolState} - ${roundedPosition}% | 💨${flow}${flowUnit} | ⚡${power}kW` };
2025-06-25 17:26:13 +02:00
break;
default:
status = { fill: "grey", shape: "dot", text: `${mode}: ${symbolState}` };
}
return status;
} catch (error) {
2026-02-12 10:48:44 +01:00
this.node.error("Error in updateNodeStatus: " + error.message);
2025-06-25 17:26:13 +02:00
return { fill: "red", shape: "ring", text: "Status Error" };
}
}
/**
* 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' },
2025-06-25 17:26:13 +02:00
]);
}, 100);
}
/**
2025-07-24 13:15:33 +02:00
* Start the periodic tick loop.
2025-06-25 17:26:13 +02:00
*/
_startTickLoop() {
this._startupTimeout = setTimeout(() => {
this._startupTimeout = null;
2025-06-25 17:26:13 +02:00
this._tickInterval = setInterval(() => this._tick(), 1000);
// Update node status on nodered screen every second
2025-06-25 17:26:13 +02:00
this._statusInterval = setInterval(() => {
const status = this._updateNodeStatus();
this.node.status(status);
}, 1000);
}, 1000);
}
/**
* Execute a single tick: update measurement, format and send outputs.
*/
_tick() {
2025-07-01 15:25:07 +02:00
//this.source.tick();
2025-06-25 17:26:13 +02:00
const raw = this.source.getOutput();
2025-11-06 11:19:08 +01:00
const processMsg = this._output.formatMsg(raw, this.source.config, 'process');
const influxMsg = this._output.formatMsg(raw, this.source.config, 'influxdb');
2025-06-25 17:26:13 +02:00
// Send only updated outputs on ports 0 & 1
2026-02-19 17:36:44 +01:00
this.node.send([processMsg, influxMsg, null]);
2025-06-25 17:26:13 +02:00
}
/**
* Attach the node's input handler, routing control messages to the class.
*/
_attachInputHandler() {
this.node.on('input', async (msg, send, done) => {
2025-06-25 17:26:13 +02:00
const m = this.source;
2026-02-19 17:36:44 +01:00
const nodeSend = typeof send === 'function' ? send : (outMsg) => this.node.send(outMsg);
try {
switch(msg.topic) {
case 'registerChild': {
2025-06-25 17:26:13 +02:00
const childId = msg.payload;
2026-02-19 17:36:44 +01:00
const childObj = this.RED.nodes.getNode(childId);
if (!childObj || !childObj.source) {
this.node.warn(`registerChild failed: child '${childId}' not found or has no source`);
break;
}
2025-06-25 17:26:13 +02:00
m.childRegistrationUtils.registerChild(childObj.source ,msg.positionVsParent);
break;
}
2025-06-25 17:26:13 +02:00
case 'setMode':
m.setMode(msg.payload);
break;
case 'execSequence': {
2025-06-25 17:26:13 +02:00
const { source, action, parameter } = msg.payload;
await m.handleInput(source, action, parameter);
2025-06-25 17:26:13 +02:00
break;
}
case 'execMovement': {
2025-06-25 17:26:13 +02:00
const { source: mvSource, action: mvAction, setpoint } = msg.payload;
await m.handleInput(mvSource, mvAction, Number(setpoint));
2025-06-25 17:26:13 +02:00
break;
}
case 'flowMovement': {
2025-06-25 17:26:13 +02:00
const { source: fmSource, action: fmAction, setpoint: fmSetpoint } = msg.payload;
await m.handleInput(fmSource, fmAction, Number(fmSetpoint));
2025-06-25 17:26:13 +02:00
break;
}
case 'emergencystop': {
2025-06-25 17:26:13 +02:00
const { source: esSource, action: esAction } = msg.payload;
await m.handleInput(esSource, esAction);
2025-06-25 17:26:13 +02:00
break;
}
2026-02-12 10:48:44 +01:00
case 'simulateMeasurement':
{
const payload = msg.payload || {};
const type = String(payload.type || '').toLowerCase();
const position = payload.position || 'atEquipment';
const value = Number(payload.value);
2026-03-11 11:13:26 +01:00
const unit = typeof payload.unit === 'string' ? payload.unit.trim() : '';
const supportedTypes = new Set(['pressure', 'flow', 'temperature', 'power']);
2026-02-12 10:48:44 +01:00
const context = {
timestamp: payload.timestamp || Date.now(),
unit,
childName: 'dashboard-sim',
childId: 'dashboard-sim',
};
if (!Number.isFinite(value)) {
this.node.warn('simulateMeasurement payload.value must be a finite number');
break;
}
2026-03-11 11:13:26 +01:00
if (!supportedTypes.has(type)) {
this.node.warn(`Unsupported simulateMeasurement type: ${type}`);
break;
}
if (!unit) {
this.node.warn('simulateMeasurement payload.unit is required');
break;
}
if (typeof m.isUnitValidForType === 'function' && !m.isUnitValidForType(type, unit)) {
this.node.warn(`simulateMeasurement payload.unit '${unit}' is invalid for type '${type}'`);
break;
}
2026-02-12 10:48:44 +01:00
switch (type) {
case 'pressure':
2026-02-19 17:36:44 +01:00
if (typeof m.updateSimulatedMeasurement === "function") {
m.updateSimulatedMeasurement(type, position, value, context);
} else {
m.updateMeasuredPressure(value, position, context);
}
2026-02-12 10:48:44 +01:00
break;
case 'flow':
m.updateMeasuredFlow(value, position, context);
break;
case 'temperature':
m.updateMeasuredTemperature(value, position, context);
break;
2026-03-11 11:13:26 +01:00
case 'power':
m.updateMeasuredPower(value, position, context);
break;
2026-02-12 10:48:44 +01:00
}
}
break;
2025-07-24 13:15:33 +02:00
case 'showWorkingCurves':
2026-02-19 17:36:44 +01:00
nodeSend([{ ...msg, topic : "showWorkingCurves" , payload: m.showWorkingCurves() }, null, null]);
2025-06-25 17:26:13 +02:00
break;
case 'CoG':
2026-02-19 17:36:44 +01:00
nodeSend([{ ...msg, topic : "showCoG" , payload: m.showCoG() }, null, null]);
2025-06-25 17:26:13 +02:00
break;
}
2026-02-19 17:36:44 +01:00
if (typeof done === 'function') done();
} catch (error) {
if (typeof done === 'function') {
done(error);
} else {
this.node.error(error, msg);
}
}
2025-06-25 17:26:13 +02:00
});
}
/**
* Clean up timers and intervals when Node-RED stops the node.
*/
_attachCloseHandler() {
this.node.on('close', (done) => {
clearTimeout(this._startupTimeout);
2025-06-25 17:26:13 +02:00
clearInterval(this._tickInterval);
clearInterval(this._statusInterval);
this.node.status({}); // clear node status badge
// Clean up child measurement listeners
const m = this.source;
if (m?.childMeasurementListeners) {
for (const [, entry] of m.childMeasurementListeners) {
if (typeof entry.emitter?.off === 'function') {
entry.emitter.off(entry.eventName, entry.handler);
} else if (typeof entry.emitter?.removeListener === 'function') {
entry.emitter.removeListener(entry.eventName, entry.handler);
}
}
m.childMeasurementListeners.clear();
}
// Clean up state emitter listeners
if (m?.state?.emitter) {
m.state.emitter.removeAllListeners();
}
2026-02-23 13:17:18 +01:00
if (typeof done === 'function') done();
2025-06-25 17:26:13 +02:00
});
}
}
module.exports = nodeClass;