updated valve to latest version of EVOLV eco

This commit is contained in:
znetsixe
2025-07-24 13:14:19 +02:00
parent 9b1af8ffa2
commit 167628a436
6 changed files with 527 additions and 918 deletions

294
src/nodeClass.js Normal file
View File

@@ -0,0 +1,294 @@
/**
* 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 } = 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) {
// Merge UI config over defaults
this.config = {
general: {
name: uiConfig.name,
id: node.id, // node.id is for the child registration process
unit: uiConfig.unit, // add converter options later to convert to default units (need like a model that defines this which units we are going to use and then conver to those standards)
logging: {
enabled: uiConfig.enableLog,
logLevel: uiConfig.logLevel
}
},
asset: {
uuid: uiConfig.assetUuid, //need to add this later to the asset model
tagCode: uiConfig.assetTagCode, //need to add this later to the asset model
supplier: uiConfig.supplier,
category: uiConfig.category, //add later to define as the software type
type: uiConfig.assetType,
model: uiConfig.model,
unit: uiConfig.unit
},
functionality: {
positionVsParent: uiConfig.positionVsParent || 'atEquipment', // Default to 'atEquipment' if not specified
}
};
// Utility for formatting outputs
this._output = new outputUtils();
}
/**
* Instantiate the core logic and store as source.
*/
_setupSpecificClass(uiConfig) {
const vconfig = this.config;
// need extra state for this
const stateConfig = {
general: {
logging: {
enabled: vconfig.eneableLog,
logLevel: vconfig.logLevel
}
},
movement: {
speed: Number(uiConfig.speed)
},
time: {
starting: Number(uiConfig.startup),
warmingup: Number(uiConfig.warmup),
stopping: Number(uiConfig.shutdown),
coolingdown: Number(uiConfig.cooldown)
}
};
this.source = new Specific(vconfig, stateConfig);
//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 flow = Math.round(v.measurements.type("flow").variant("measured").position("downstream").getCurrentValue());
let deltaP = v.measurements.type("pressure").variant("predicted").position("delta").getCurrentValue();
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}m³/h | ΔP${deltaP} mbar`}; //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}m³/h | ΔP${deltaP} mbar`}; //deltaP toegevoegd
break;
case "accelerating":
status = { fill: "yellow", shape: "dot", text: `${mode}: ${symbolState} | ${roundedPosition}% | 💨${flow}m³/h | ΔP${deltaP} mbar` }; //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}m³/h | ΔP${deltaP} mbar`}; //deltaP toegevoegd
break;
default:
status = { fill: "grey", shape: "dot", text: `${mode}: ${symbolState}` };
}
return status;
} catch (error) {
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.config, 'process');
const influxMsg = this._output.formatMsg(raw, this.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;
switch(msg.topic) {
case 'registerChild':
const childId = msg.payload;
const childObj = this.RED.nodes.getNode(childId);
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':
const { source: esSource, action: esAction } = msg.payload;
v.handleInput(esSource, esAction);
break;
case 'showcurve':
v.showCurve();
send({ topic : "Showing curve" , payload: v.showCurve() });
break;
case 'updateFlow': //Als nieuwe flow van header node dan moet deltaP weer opnieuw worden berekend en doorgegeven aan header node
v.updateFlow(msg.payload.variant, msg.payload.value, msg.payload.position);
}
done();
});
}
/**
* Clean up timers and intervals when Node-RED stops the node.
*/
_attachCloseHandler() {
this.node.on('close', (done) => {
clearInterval(this._tickInterval);
clearInterval(this._statusInterval);
done();
});
}
}
module.exports = nodeClass;

355
src/specificClass.js Normal file
View File

@@ -0,0 +1,355 @@
/**
* @file valve.js
*
* Permission is hereby granted to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to use it for personal
* or non-commercial purposes, with the following restrictions:
*
* 1. **No Copying or Redistribution**: The Software or any of its parts may not
* be copied, merged, distributed, sublicensed, or sold without explicit
* prior written permission from the author.
*
* 2. **Commercial Use**: Any use of the Software for commercial purposes requires
* a valid license, obtainable only with the explicit consent of the author.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM,
* OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Ownership of this code remains solely with the original author. Unauthorized
* use of this Software is strictly prohibited.
*
* Author:
* - Rene De Ren
* Email:
* - r.de.ren@brabantsedelta.nl
*
* Future Improvements:
* - Time-based stability checks
* - Warmup handling
* - Dynamic outlier detection thresholds
* - Dynamic smoothing window and methods
* - Alarm and threshold handling
* - Maintenance mode
* - Historical data and trend analysis
*/
/**
* @file valveClass.js
*
* Permission is hereby granted to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to use it for personal
....
*/
//load local dependencies
const EventEmitter = require('events');
const {loadCurve,logger,configUtils,configManager,state, nrmse, MeasurementContainer, predict, interpolation , childRegistrationUtils} = require('generalFunctions');
class Valve {
constructor(valveConfig = {}, stateConfig = {}) {
//basic setup
this.emitter = new EventEmitter(); // nodig voor ontvangen en uitvoeren van events emit() --> Zien als internet berichten (niet bedraad in node-red)
this.logger = new logger(valveConfig.general.logging.enabled,valveConfig.general.logging.logLevel, valveConfig.general.name);
this.configManager = new configManager();
this.defaultConfig = this.configManager.getConfig('valve'); // Load default config for rotating machine ( use software type name ? )
this.configUtils = new configUtils(this.defaultConfig);
// Load a specific curve
this.model = valveConfig.asset.model; // Get the model from the valveConfig
this.curve = this.model ? loadCurve(this.model) : null;
//Init config and check if it is valid
this.config = this.configUtils.initConfig(valveConfig);
// Initialize measurements
this.measurements = new MeasurementContainer();
this.child = {}; // object to hold child information so we know on what to subscribe
// Init after config is set
this.state = new state(stateConfig, this.logger); // Init State manager and pass logger
this.state.stateManager.currentState = "operational"; // Set default state to operational
this.kv = 0; //default
this.rho = 1,225 //dichtheid van lucht standaard
this.T = 293; // temperatuur in K standaard
this.downstreamP = 0.54 //hardcodes for now --> assumed to be constant watercolumn and deltaP diffuser
this.currentMode = this.config.mode.current;
// wanneer hij deze ontvangt is de positie van de klep verandererd en gaat hij de updateposition functie aanroepen wat dan alle metingen en standen gaat updaten
this.state.emitter.on("positionChange", (data) => {
this.logger.debug(`Position change detected: ${data}`);
this.updatePosition()}); //To update deltaP
this.childRegistrationUtils = new childRegistrationUtils(this); // Child registration utility
this.vCurve = this.curve[1.204]; // specificy the desired density RECALC THIS AUTOMTICALLY BASED ON DENSITY OF AIR LATER OLIFANT!!
this.predictKv = new predict({curve:this.vCurve}); // load valve size (x : ctrl , y : kv relationship)
console.log(`PredictKv initialized with curve: ${JSON.stringify(this.predictKv)}`);
}
// -------- Config -------- //
updateConfig(newConfig) {
this.config = this.configUtils.updateConfig(this.config, newConfig);
}
isValidSourceForMode(source, mode) {
const allowedSourcesSet = this.config.mode.allowedSources[mode] || [];
return allowedSourcesSet.has(source);
}
async handleInput(source, action, parameter) {
if (!this.isValidSourceForMode(source, this.currentMode)) {
let warningTxt = `Source '${source}' is not valid for mode '${this.currentMode}'.`;
this.logger.warn(warningTxt);
return {status : false , feedback: warningTxt};
}
this.logger.info(`Handling input from source '${source}' with action '${action}' in mode '${this.currentMode}'.`);
try {
switch (action) {
case "execSequence":
await this.executeSequence(parameter);
break;
case "execMovement": // past het setpoint aan - movement van klep stand
await this.setpoint(parameter);
break;
case "emergencyStop":
this.logger.warn(`Emergency stop activated by '${source}'.`);
await this.executeSequence("emergencyStop");
break;
case "statusCheck":
this.logger.info(`Status Check: Mode = '${this.currentMode}', Source = '${source }'.`);
break;
default:
this.logger.warn(`Action '${action}' is not implemented.`);
break;
}
this.logger.debug(`Action '${action}' successfully executed`);
return {status : true , feedback: `Action '${action}' successfully executed.`};
} catch (error) {
this.logger.error(`Error handling input: ${error}`);
}
}
setMode(newMode) {
const availableModes = defaultConfig.mode.current.rules.values.map(v => v.value);
if (!availableModes.includes(newMode)) {
this.logger.warn(`Invalid mode '${newMode}'. Allowed modes are: ${availableModes.join(', ')}`);
return;
}
this.currentMode = newMode;
this.logger.info(`Mode successfully changed to '${newMode}'.`);
}
loadSpecs(){ //static betekend dat die in andere classes kan worden aangeroepen met const specs = Valve.loadSpecs()
//lateron based on valve caracteristics --> then it searches for right valve
let specs = {
supplier : "Binder",
type : "HDCV",
units:{
Nm3: { "temp": 20, "pressure" : 1.01325 , "RH" : 0 }, // according to DIN
v_curve : { x : "% stroke", y : "Kv value"} ,
},
v_curve: {
125: // valve size
{
x:[0,10,20,30,40,50,60,70,80,90,100], //stroke in %
y:[0,18,50,95,150,216,337,564,882,1398,1870], //Kv value expressed in m3/h
},
150: // valve size
{
x:[0,10,20,30,40,50,60,70,80,90,100], //stroke in %
y:[0,25,73,138,217,314,490,818,1281,2029,2715], //oxygen transfer rate expressed in gram o2 / normal m3/h / per m
},
400: // valve size
{
x:[0,10,20,30,40,50,60,70,80,90,100], //stroke in %
y:[0,155,443,839,1322,1911,2982,4980,7795,12349,16524], //oxygen transfer rate expressed in gram o2 / normal m3/h / per m
},
}
}
return specs;
}
// -------- Sequence Handlers -------- //
async executeSequence(sequenceName) {
const sequence = this.config.sequences[sequenceName];
if (!sequence || sequence.size === 0) {
this.logger.warn(`Sequence '${sequenceName}' not defined.`);
return;
}
if (this.state.getCurrentState() == "operational" && sequenceName == "shutdown") {
this.logger.info(`Machine will ramp down to position 0 before performing ${sequenceName} sequence`);
await this.setpoint(0);
}
this.logger.info(` --------- Executing sequence: ${sequenceName} -------------`);
for (const state of sequence) {
try {
await this.state.transitionToState(state);
// Update measurements after state change
} catch (error) {
this.logger.error(`Error during sequence '${sequenceName}': ${error}`);
break; // Exit sequence execution on error
}
}
}
async setpoint(setpoint) {
try {
// Validate setpoint
if (typeof setpoint !== 'number' || setpoint < 0) {
throw new Error("Invalid setpoint: Setpoint must be a non-negative number.");
}
// Move to the desired setpoint
await this.state.moveTo(setpoint);
} catch (error) {
console.error(`Error setting setpoint: ${error}`);
}
}
updateMeasurement(variant, subType, value, position) {
this.logger.debug(`---------------------- updating ${subType} ------------------ `);
switch (subType) {
case "pressure":
// Update pressure measurement
//this.updatePressure(variant,value,position);
break;
case "flow":
this.updateFlow(variant,value,position);
break;
case "power":
// Update power measurement
break;
default:
this.logger.error(`Type '${subType}' not recognized for measured update.`);
return;
}
}
// NOTE: Omdat met zeer kleine getallen wordt gewerkt en er kwadraten in de formule zitten kan het zijn dat we alles *1000 moeten doen
updateDeltaPKlep(q,kv,downstreamP,rho,temp){
//q must be in Nm3/h
//temp must be in K
//q must be in m3/h
//downstreamP must be in bar so transfer from mbar to bar
downstreamP = downstreamP / 1000;
//convert downstreamP to absolute bar
downstreamP += 1.01325;
//calculate deltaP
let deltaP = ( q**2 * rho * temp ) / ( 514**2 * kv**2 * downstreamP);
//convert deltaP to mbar
deltaP = deltaP * 1000;
// Synchroniseer deltaP met het Valve-object
this.deltaPKlep = deltaP
// Opslaan in measurement container
this.measurements.type("pressure").variant("predicted").position("delta").value(deltaP);
this.logger.info('DeltaP updated to: ' + deltaP);
this.emitter.emit('deltaPChange', deltaP); // Emit event to notify valveGroupController of deltaP change
this.logger.info('DeltaPChange emitted to valveGroupController');
}
// Als er een nieuwe flow door de klep komt doordat de machines harder zijn gaan werken, dan update deze functie dit ook in de valve attributes en measurements
updateFlow(variant,value,position) {
switch (variant) {
case ("measured"):
// put value in measurements
this.measurements.type("flow").variant("measured").position(position).value(value);
const downStreamP = this.measurements.type("pressure").variant("measured").position("downstream").getCurrentValue(); //update downstream pressure measurement
this.updateDeltaPKlep(value,this.kv,downStreamP,this.rho,this.T); //update deltaP based on new flow
break;
case ("predicted"):
this.logger.debug('not doing anythin yet');
break;
default:
this.logger.warn(`Unrecognized variant '${variant}' for flow update.`);
break;
}
}
updatePosition() { //update alle parameters nadat er een verandering is geweest in stand van klep
if (this.state.getCurrentState() == "operational" || this.state.getCurrentState() == "accelerating" || this.state.getCurrentState() == "decelerating") {
this.logger.debug('Calculating new deltaP');
const currentPosition = this.state.getCurrentPosition();
const currentFlow = this.measurements.type("flow").variant("measured").position("downstream").getCurrentValue(); // haal de flow op uit de measurement containe
const downstreamP = this.measurements.type("pressure").variant("measured").position("downstream").getCurrentValue(); // haal de downstream pressure op uit de measurement container
//const valveSize = 125; //NOTE: nu nog hardcoded maar moet een attribute van de valve worden
this.predictKv.fDimension = 125; //load valve size by defining fdimension in predict class
const x = currentPosition; // dit is de positie van de klep waarvoor we delta P willen berekenen
const y = this.predictKv.y(x); // haal de waarde van kv op uit de spline
this.kv = y; //update de kv waarde in de valve class
if (this.kv < 0.1){
this.kv = 0.1; //minimum waarde voor kv
}
this.logger.debug(`Kv value for position valve ${x} is ${this.kv}`); // log de waarde van kv
this.updateDeltaPKlep(currentFlow,this.kv,downstreamP,this.rho,this.T); //update deltaP
}
}
getOutput() {
// Improved output object generation
const output = {};
//build the output object
this.measurements.getTypes().forEach(type => {
this.measurements.getVariants().forEach(variant => {
this.measurements.getPositions().forEach(position => {
const value = this.measurements.type(type).variant(variant).position(position).getCurrentValue(); //get the current value of the measurement
if (value != null) {
output[`${position}_${variant}_${type}`] = value;
}
});
});
});
//fill in the rest of the output object
output["state"] = this.state.getCurrentState();
output["percentageOpen"] = this.state.getCurrentPosition();
output["moveTimeleft"] = this.state.getMoveTimeLeft();
output["mode"] = this.currentMode;
//this.logger.debug(`Output: ${JSON.stringify(output)}`);
return output;
}
}
module.exports = Valve;