363 lines
13 KiB
JavaScript
363 lines
13 KiB
JavaScript
/**
|
|
* 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.
|
|
*/
|
|
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.RED = RED;
|
|
this.name = nameOfNode;
|
|
this.source = null; // Will hold the specific class instance
|
|
this.config = null; // Will hold the merged configuration
|
|
|
|
// Load default & UI config
|
|
this._loadConfig(uiConfig,this.node);
|
|
|
|
// Instantiate core Measurement class
|
|
this._setupSpecificClass(uiConfig);
|
|
|
|
// 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 flowUnit = this._resolveUnitOrFallback(uiConfig.unit, 'volumeFlowRate', 'm3/h', 'flow');
|
|
|
|
// Merge UI config over defaults
|
|
this.config = {
|
|
general: {
|
|
name: uiConfig.name,
|
|
id: node.id, // node.id is for the child registration process
|
|
unit: flowUnit,
|
|
logging: {
|
|
enabled: uiConfig.enableLog,
|
|
logLevel: uiConfig.logLevel
|
|
}
|
|
},
|
|
asset: {
|
|
uuid: uiConfig.uuid || uiConfig.assetUuid || null,
|
|
tagCode: uiConfig.tagCode || uiConfig.assetTagCode || null,
|
|
supplier: uiConfig.supplier,
|
|
category: uiConfig.category, //add later to define as the software type
|
|
type: uiConfig.assetType,
|
|
model: uiConfig.model,
|
|
unit: flowUnit
|
|
},
|
|
functionality: {
|
|
positionVsParent: uiConfig.positionVsParent || 'atEquipment', // Default to 'atEquipment' if not specified
|
|
}
|
|
};
|
|
|
|
// Utility for formatting outputs
|
|
this._output = new outputUtils();
|
|
}
|
|
|
|
_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;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Instantiate the core logic and store as source.
|
|
*/
|
|
_setupSpecificClass(uiConfig) {
|
|
const vconfig = this.config;
|
|
const asNumberOrUndefined = (value) => {
|
|
const parsed = Number(value);
|
|
return Number.isFinite(parsed) ? parsed : undefined;
|
|
};
|
|
|
|
// need extra state for this
|
|
const stateConfig = {
|
|
general: {
|
|
logging: {
|
|
enabled: vconfig.general.logging.enabled,
|
|
logLevel: vconfig.general.logging.logLevel
|
|
}
|
|
},
|
|
movement: {
|
|
speed: asNumberOrUndefined(uiConfig.speed)
|
|
},
|
|
time: {
|
|
starting: asNumberOrUndefined(uiConfig.startup),
|
|
warmingup: asNumberOrUndefined(uiConfig.warmup),
|
|
stopping: asNumberOrUndefined(uiConfig.shutdown),
|
|
coolingdown: asNumberOrUndefined(uiConfig.cooldown)
|
|
}
|
|
};
|
|
|
|
const runtimeOptions = {
|
|
serviceType: uiConfig.serviceType,
|
|
fluidDensity: asNumberOrUndefined(uiConfig.fluidDensity),
|
|
fluidTemperatureK: asNumberOrUndefined(uiConfig.fluidTemperatureK),
|
|
gasChokedRatioLimit: asNumberOrUndefined(uiConfig.gasChokedRatioLimit),
|
|
};
|
|
|
|
this.source = new Specific(vconfig, stateConfig, runtimeOptions);
|
|
|
|
//store in node
|
|
this.node.source = this.source; // Store the source in the node instance for easy access
|
|
|
|
}
|
|
|
|
/**
|
|
* Bind Measurement events to Node-RED status updates. Using internal emitter. --> REMOVE LATER WE NEED ONLY COMPLETE CHILDS AND THEN CHECK FOR UPDATES
|
|
*/
|
|
_bindEvents() {
|
|
|
|
}
|
|
|
|
_updateNodeStatus() {
|
|
const v = this.source;
|
|
|
|
try {
|
|
const mode = v.currentMode; // modus is bijv. auto, manual, etc.
|
|
const state = v.state.getCurrentState(); //is bijv. operational, idle, off, etc.
|
|
const fluidCompatibility = typeof v.getFluidCompatibility === "function"
|
|
? v.getFluidCompatibility()
|
|
: null;
|
|
const fluidWarningText = (
|
|
fluidCompatibility
|
|
&& (fluidCompatibility.status === "mismatch" || fluidCompatibility.status === "conflict")
|
|
)
|
|
? fluidCompatibility.message
|
|
: "";
|
|
const flowUnit = v?.unitPolicy?.output?.flow || this.config.general.unit || "m3/h";
|
|
const pressureUnit = v?.unitPolicy?.output?.pressure || "mbar";
|
|
// check if measured flow is available otherwise use predicted flow
|
|
const flow = Math.round(v.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue(flowUnit));
|
|
|
|
let deltaP = v.measurements.type("pressure").variant("predicted").position("delta").getCurrentValue(pressureUnit);
|
|
if (deltaP !== null) {
|
|
deltaP = parseFloat(deltaP.toFixed(0));
|
|
} //afronden op 4 decimalen indien geen "null"
|
|
if(isNaN(deltaP)) {
|
|
deltaP = "∞";
|
|
}
|
|
const roundedPosition = Math.round(v.state.getCurrentPosition() * 100) / 100;
|
|
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;
|
|
}
|
|
|
|
|
|
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":
|
|
status = { fill: "green", shape: "dot", text: `${mode}: ${symbolState} | ${roundedPosition}% | 💨${flow}${flowUnit} | ΔP${deltaP} ${pressureUnit}`}; //deltaP toegevoegd
|
|
break;
|
|
case "starting":
|
|
status = { fill: "yellow", shape: "dot", text: `${mode}: ${symbolState}` };
|
|
break;
|
|
case "warmingup":
|
|
status = { fill: "green", shape: "dot", text: `${mode}: ${symbolState} | ${roundedPosition}% | 💨${flow}${flowUnit} | ΔP${deltaP} ${pressureUnit}`}; //deltaP toegevoegd
|
|
break;
|
|
case "accelerating":
|
|
status = { fill: "yellow", shape: "dot", text: `${mode}: ${symbolState} | ${roundedPosition}% | 💨${flow}${flowUnit} | ΔP${deltaP} ${pressureUnit}` }; //deltaP toegevoegd
|
|
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":
|
|
status = { fill: "yellow", shape: "dot", text: `${mode}: ${symbolState} - ${roundedPosition}% | 💨${flow}${flowUnit} | ΔP${deltaP} ${pressureUnit}`}; //deltaP toegevoegd
|
|
break;
|
|
default:
|
|
status = { fill: "grey", shape: "dot", text: `${mode}: ${symbolState}` };
|
|
}
|
|
if (fluidWarningText) {
|
|
status = {
|
|
fill: "yellow",
|
|
shape: "ring",
|
|
text: `${status.text} | ⚠ ${fluidWarningText}`,
|
|
};
|
|
}
|
|
return status;
|
|
} catch (error) {
|
|
this.node.error("Error in updateNodeStatus: " + error.message);
|
|
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' },
|
|
]);
|
|
}, 100);
|
|
}
|
|
|
|
/**
|
|
* Start the periodic tick loop.
|
|
*/
|
|
_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() {
|
|
//this.source.tick();
|
|
|
|
const raw = this.source.getOutput();
|
|
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', (msg, send, done) => {
|
|
const v = this.source;
|
|
try {
|
|
switch(msg.topic) {
|
|
case 'registerChild': {
|
|
const childId = msg.payload;
|
|
const childObj = this.RED.nodes.getNode(childId);
|
|
if (!childObj || !childObj.source) {
|
|
v.logger.warn(`registerChild skipped: missing child/source for id=${childId}`);
|
|
break;
|
|
}
|
|
v.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent);
|
|
break;
|
|
}
|
|
case 'setMode':
|
|
v.setMode(msg.payload);
|
|
break;
|
|
case 'execSequence': {
|
|
const { source: seqSource, action: seqAction, parameter } = msg.payload;
|
|
v.handleInput(seqSource, seqAction, parameter);
|
|
break;
|
|
}
|
|
case 'execMovement': {
|
|
const { source: mvSource, action: mvAction, setpoint } = msg.payload;
|
|
v.handleInput(mvSource, mvAction, Number(setpoint));
|
|
break;
|
|
}
|
|
case 'emergencystop':
|
|
case 'emergencyStop': {
|
|
const payload = msg.payload || {};
|
|
const esSource = payload.source || 'parent';
|
|
v.handleInput(esSource, 'emergencystop');
|
|
break;
|
|
}
|
|
case 'showcurve':
|
|
send({ topic: 'Showing curve', payload: v.showCurve() });
|
|
break;
|
|
case 'updateFlow':
|
|
v.updateFlow(msg.payload.variant, msg.payload.value, msg.payload.position, msg.payload.unit || this.config.general.unit);
|
|
break;
|
|
default:
|
|
v.logger.warn(`Unknown topic: ${msg.topic}`);
|
|
}
|
|
} catch (error) {
|
|
v.logger.error(`Input handler failure: ${error.message}`);
|
|
}
|
|
|
|
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);
|
|
clearInterval(this._statusInterval);
|
|
this.source?.destroy?.();
|
|
if (typeof done === 'function') done();
|
|
});
|
|
}
|
|
}
|
|
|
|
module.exports = nodeClass;
|