Files
valveGroupControl/dependencies/valveGroupControlClass.js
2025-05-14 10:05:34 +02:00

246 lines
9.7 KiB
JavaScript

//TODO Moet een attribute in die valves = {} houd zodat daar alle child valves in bijgehouden wordt
/**
* @file valveGroupControlClass.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 #NOTE: Vul hier nog de juiste dependencies in als meer nodig of sommige niet nodig
const EventEmitter = require('events');
const Logger = require('../../generalFunctions/helper/logger');
const State = require('../../generalFunctions/helper/state/state');
const { MeasurementContainer } = require('../../generalFunctions/helper/measurements/index');
//load all config modules #NOTE: Vul hier nog de juiste dependencies in als meer nodig of sommige niet nodig
const defaultConfig = require('./valveGroupControlConfig.json');
const ConfigUtils = require('../../generalFunctions/helper/configUtils');
//load registration utility #NOTE: Vul hier nog de juiste dependencies in als meer nodig of sommige niet nodig
const ChildRegistrationUtils = require('../../generalFunctions/helper/childRegistrationUtils');
class ValveGroupControl {
constructor(valveGroupControlConfig = {}, stateConfig = {}) {
this.emitter = new EventEmitter(); // nodig voor ontvangen en uitvoeren van events emit() en on() --> Zien als internet berichten (niet bedraad in node-red)
this.configUtils = new ConfigUtils(defaultConfig); // nodig voor het ophalen van de default configuaratie
this.config = this.configUtils.initConfig(valveGroupControlConfig); //valve configurations die bij invoer in node-red worden gegeven
// Initialize measurements
this.measurements = new MeasurementContainer();
this.valves = {}; // hold child object so we can get information from its child valves
// Initialize variables
this.maxDeltaP = 0; // max deltaP is 0 als er geen child valves zijn
// Init after config is set
this.logger = new Logger(this.config.general.logging.enabled, this.config.general.logging.logLevel, this.config.general.logging.name);
this.state = new State(stateConfig, this.logger); // Init State manager and pass logger
this.state.stateManager.currentState = "operational"; // Set default state to operational
this.currentMode = this.config.mode.current;
this.childRegistrationUtils = new ChildRegistrationUtils(this); // Child registration utility
}
// -------- Config -------- //
updateConfig(newConfig) {
this.config = this.configUtils.updateConfig(this.config, newConfig);
}
isValidSourceForMode(source, mode) {
const allowedSourcesSet = this.config.mode.allowedSources[mode] || [];
this.logger.info(`Allowed sources for mode '${mode}': ${allowedSourcesSet}`);
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 "totalFlowChange": // total flow veranderd dus nieuwe flow per valve berekenen.
this.measurements.type("totalFlow").variant("predicted").position("upstream").value(parameter);
const totalFlow = this.measurements.type("totalFlow").variant("predicted").position("upstream").getCurrentValue(); //CHECKPOINT
this.logger.info('Total flow changed to: ' + totalFlow); //CHECKPOINT
await this.calcValveFlows();
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(vgc => vgc.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}'.`);
}
// -------- Sequence Handlers -------- //
async executeSequence(sequenceName) {
const sequence = this.config.sequences[sequenceName];
if (!sequence || sequence.size === 0) {
this.logger.warn(`Sequence '${sequenceName}' not defined.`);
return;
}
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
}
}
}
calcValveFlows() {
const totalFlow = this.measurements.type("totalFlow").variant("predicted").position("upstream").getCurrentValue(); // haal de totalFlow op uit de measurement container
let totalKv = 0;
this.logger.info('this.valves = ' + this.valves); //CHECKPOINT
for (const key in this.valves){ //bereken sum kv values om verdeling total flow te maken
this.logger.info('kv: ' + this.valves[key].kv); //CHECKPOINT
if (this.valves[key].state.getCurrentPosition() != null) {
totalKv += this.valves[key].kv;
this.logger.info('Total Kv = ' + totalKv); //CHECKPOINT
}
}
for (const key in this.valves){
const valve = this.valves[key];
const ratio = valve.kv / totalKv;
const flow = ratio * totalFlow; // bereken flow per valve
// Check of update in valve object vanuit valvegroupcontrol werk
this.logger.info(`Flow for valve ${key} is ${flow} and updateFlowKlep event triggered in valve object`);
const currentFlow = valve.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue();
this.logger.info('Current flow valve = ' + currentFlow);
//update flow per valve in de object zelf wat daar vervolgens weer de nieuwe deltaP berekent
valve.updateFlowKlep(flow);
this.logger.info('--> Sending updated flow to valves --> ') //Checkpoint
// Check of update in valve object vanuit valvegroupcontrol werk
const updatedFlow = valve.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue();
this.logger.info('Updated flow valve = ' + updatedFlow);
}
}
calcMaxDeltaP() { // bereken de max deltaP van alle child valves
let maxDeltaP = 0; //max deltaP is 0 als er geen child valves zijn
this.logger.info('CHECK!'); //CHECKPOINT
this.logger.info('CHECK! Valves: ' + this.valves); //CHECKPOINT
this.logger.info('Calculating new max deltaP...');
for (const key in this.valves) {
const valve = this.valves[key]; //haal de child valve object op
const deltaP = valve.measurements.type("pressure").variant("predicted").position("delta").getCurrentValue(); //get delta P
if (deltaP > maxDeltaP) { //als de deltaP van de child valve groter is dan de huidige maxDeltaP, dan update deze
maxDeltaP = deltaP;
}
}
this.logger.info('Max Delta P updated to: ' + maxDeltaP);
this.maxDeltaP = maxDeltaP; //update de max deltaP in de measurement container van de valveGroupControl class
}
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["moveTimeleft"] = this.state.getMoveTimeLeft();
output["mode"] = this.currentMode;
output["maxDeltaP"] = this.maxDeltaP;
//this.logger.debug(`Output: ${JSON.stringify(output)}`);
return output;
}
}
module.exports = ValveGroupControl;
/*
const valve = require('../../valve/dependencies/valveClass.js');
const valve1 = new valve();
const valve2 = new valve();
const valve3 = new valve();
const vgc = new ValveGroupControl();
vgc.childRegistrationUtils.registerChild(valve1, "downStream");
vgc.childRegistrationUtils.registerChild(valve2, "downStream");
vgc.childRegistrationUtils.registerChild(valve3, "downStream");
vgc.handleInput("parent", "totalFlowChange", Number(1600));
*/