Compare commits

..

2 Commits

Author SHA1 Message Date
znetsixe
b6ffefc92b Lots of minor bug fixes to update on architecture choices 2025-11-13 19:39:32 +01:00
znetsixe
ed2cf4c23d fixed outputformats 2025-11-06 11:18:38 +01:00
2 changed files with 80 additions and 56 deletions

View File

@@ -67,8 +67,8 @@ class nodeClass {
const totalFlow = mg.measurements const totalFlow = mg.measurements
?.type("flow") ?.type("flow")
?.variant("predicted") ?.variant("predicted")
?.position("downstream") ?.position("atequipment")
?.getCurrentValue() || 0; ?.getCurrentValue('m3/h') || 0;
const totalPower = mg.measurements const totalPower = mg.measurements
?.type("power") ?.type("power")
@@ -181,8 +181,8 @@ class nodeClass {
*/ */
_tick() { _tick() {
const raw = this.source.getOutput(); const raw = this.source.getOutput();
const processMsg = this._output.formatMsg(raw, this.config, "process"); const processMsg = this._output.formatMsg(raw, this.source.config, "process");
const influxMsg = this._output.formatMsg(raw, this.config, "influxdb"); const influxMsg = this._output.formatMsg(raw, this.source.config, "influxdb");
// Send only updated outputs on ports 0 & 1 // Send only updated outputs on ports 0 & 1
this.node.send([processMsg, influxMsg]); this.node.send([processMsg, influxMsg]);
@@ -199,16 +199,16 @@ class nodeClass {
const RED = this.RED; const RED = this.RED;
switch (msg.topic) { switch (msg.topic) {
case "registerChild": case "registerChild":
console.log(`Registering child in mgc: ${msg.payload}`); //console.log(`Registering child in mgc: ${msg.payload}`);
const childId = msg.payload; const childId = msg.payload;
const childObj = RED.nodes.getNode(childId); const childObj = RED.nodes.getNode(childId);
// Debug: Check what we're getting // Debug: Check what we're getting
console.log(`Child object:`, childObj ? 'found' : 'NOT FOUND'); //console.log(`Child object:`, childObj ? 'found' : 'NOT FOUND');
console.log(`Child source:`, childObj?.source ? 'exists' : 'MISSING'); //console.log(`Child source:`, childObj?.source ? 'exists' : 'MISSING');
if (childObj?.source) { if (childObj?.source) {
console.log(`Child source type:`, childObj.source.constructor.name); //console.log(`Child source type:`, childObj.source.constructor.name);
console.log(`Child has state:`, !!childObj.source.state); //console.log(`Child has state:`, !!childObj.source.state);
} }
mg.childRegistrationUtils.registerChild( mg.childRegistrationUtils.registerChild(
@@ -217,7 +217,7 @@ class nodeClass {
); );
// Debug: Check machines after registration // Debug: Check machines after registration
console.log(`Total machines after registration:`, Object.keys(mg.machines || {}).length); //console.log(`Total machines after registration:`, Object.keys(mg.machines || {}).length);
break; break;
case "setMode": case "setMode":

View File

@@ -15,7 +15,17 @@ class MachineGroup {
this.logger = new logger(this.config.general.logging.enabled,this.config.general.logging.logLevel, this.config.general.name); this.logger = new logger(this.config.general.logging.enabled,this.config.general.logging.logLevel, this.config.general.name);
// Initialize measurements // Initialize measurements
this.measurements = new MeasurementContainer(); this.measurements = new MeasurementContainer({
autoConvert: true,
windowSize: 50,
defaultUnits: {
pressure: 'mbar',
flow: 'l/s',
power: 'kW',
temperature: 'C'
}
});
this.interpolation = new interpolation(); this.interpolation = new interpolation();
// Machines and child data // Machines and child data
@@ -40,6 +50,8 @@ class MachineGroup {
registerChild(child,softwareType) { registerChild(child,softwareType) {
this.logger.debug('Setting up childs specific for this class'); this.logger.debug('Setting up childs specific for this class');
const position = child.config.general.positionVsParent;
if(softwareType == "machine"){ if(softwareType == "machine"){
// Check if the machine is already registered // Check if the machine is already registered
this.machines[child.config.general.id] === undefined ? this.machines[child.config.general.id] = child : this.logger.warn(`Machine ${child.config.general.id} is already registered.`); this.machines[child.config.general.id] === undefined ? this.machines[child.config.general.id] = child : this.logger.warn(`Machine ${child.config.general.id} is already registered.`);
@@ -133,15 +145,23 @@ class MachineGroup {
this.logger.debug(`\n --------- Calculating dynamic totals for ${Object.keys(this.machines).length} machines. @ current pressure settings : ----------`); this.logger.debug(`\n --------- Calculating dynamic totals for ${Object.keys(this.machines).length} machines. @ current pressure settings : ----------`);
Object.values(this.machines).forEach(machine => { Object.values(this.machines).forEach(machine => {
//skip machines without valid curve
if(!machine.hasCurve){
this.logger.error(`Machine ${machine.config.general.id} does not have a valid curve. Skipping in dynamic totals calculation.`);
return;
}
this.logger.debug(`Processing machine with id: ${machine.config.general.id}`); this.logger.debug(`Processing machine with id: ${machine.config.general.id}`);
this.logger.debug(`Current pressure settings: ${JSON.stringify(machine.predictFlow.currentF)}`); this.logger.debug(`Current pressure settings: ${JSON.stringify(machine.predictFlow.currentF)}`);
//fetch min flow ever seen over all machines //fetch min flow ever seen over all machines
const minFlow = machine.predictFlow.currentFxyYMin; const minFlow = machine.predictFlow.currentFxyYMin;
const maxFlow = machine.predictFlow.currentFxyYMax; const maxFlow = machine.predictFlow.currentFxyYMax;
const minPower = machine.predictPower.currentFxyYMin; const minPower = machine.predictPower.currentFxyYMin;
const maxPower = machine.predictPower.currentFxyYMax; const maxPower = machine.predictPower.currentFxyYMax;
const actFlow = machine.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue();
const actPower = machine.measurements.type("power").variant("predicted").position("atEquipment").getCurrentValue(); const actFlow = machine.measurements.type("flow").variant("predicted").position("atequipment").getCurrentValue();
const actPower = machine.measurements.type("power").variant("predicted").position("atequipment").getCurrentValue();
this.logger.debug(`Machine ${machine.config.general.id} - Min Flow: ${minFlow}, Max Flow: ${maxFlow}, Min Power: ${minPower}, Max Power: ${maxPower}, NCog: ${machine.NCog}`); this.logger.debug(`Machine ${machine.config.general.id} - Min Flow: ${minFlow}, Max Flow: ${maxFlow}, Min Power: ${minPower}, Max Power: ${maxPower}, NCog: ${machine.NCog}`);
@@ -195,11 +215,11 @@ class MachineGroup {
const { flow, power } = this.calcDynamicTotals(); const { flow, power } = this.calcDynamicTotals();
this.logger.debug(`Dynamic Totals after pressure change - Flow: Min ${flow.min}, Max ${flow.max}, Act ${flow.act} | Power: Min ${power.min}, Max ${power.max}, Act ${power.act}`); this.logger.debug(`Dynamic Totals after pressure change - Flow: Min ${flow.min}, Max ${flow.max}, Act ${flow.act} | Power: Min ${power.min}, Max ${power.max}, Act ${power.act}`);
this.measurements.type("flow").variant("predicted").position("downstream").value(flow.act); this.measurements.type("flow").variant("predicted").position("atequipment").value(flow.act);
this.measurements.type("power").variant("predicted").position("atEquipment").value(power.act); this.measurements.type("power").variant("predicted").position("atequipment").value(power.act);
const { maxEfficiency, lowestEfficiency } = this.calcGroupEfficiency(this.machines); const { maxEfficiency, lowestEfficiency } = this.calcGroupEfficiency(this.machines);
const efficiency = this.measurements.type("efficiency").variant("predicted").position("atEquipment").getCurrentValue(); const efficiency = this.measurements.type("efficiency").variant("predicted").position("atequipment").getCurrentValue();
this.calcDistanceBEP(efficiency,maxEfficiency,lowestEfficiency); this.calcDistanceBEP(efficiency,maxEfficiency,lowestEfficiency);
} }
@@ -238,8 +258,8 @@ class MachineGroup {
if(machine.measurements.type("flow").variant("measured").position("downstream").getCurrentValue()){ if(machine.measurements.type("flow").variant("measured").position("downstream").getCurrentValue()){
flow = machine.measurements.type("flow").variant("measured").position("downstream").getCurrentValue(); flow = machine.measurements.type("flow").variant("measured").position("downstream").getCurrentValue();
} }
else if(machine.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue()){ else if(machine.measurements.type("flow").variant("predicted").position("atequipment").getCurrentValue()){
flow = machine.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue(); flow = machine.measurements.type("flow").variant("predicted").position("atequipment").getCurrentValue();
} }
else{ else{
this.logger.error("Dont perform calculation at all seeing that there is a machine working but we dont know the flow its producing"); this.logger.error("Dont perform calculation at all seeing that there is a machine working but we dont know the flow its producing");
@@ -264,7 +284,7 @@ class MachineGroup {
Object.keys(machines).forEach(machineId => { Object.keys(machines).forEach(machineId => {
const state = machines[machineId].state.getCurrentState(); const state = machines[machineId].state.getCurrentState();
const validActionForMode = machines[machineId].isValidActionForMode("execSequence", "auto"); const validActionForMode = machines[machineId].isValidActionForMode("execsequence", "auto");
// Reasons why a machine is not valid for the combination // Reasons why a machine is not valid for the combination
@@ -451,10 +471,10 @@ class MachineGroup {
this.logger.debug(`Moving to demand: ${Qd.toFixed(2)} -> Pumps: [${debugInfo}] => Total Power: ${bestResult.bestPower.toFixed(2)}`); this.logger.debug(`Moving to demand: ${Qd.toFixed(2)} -> Pumps: [${debugInfo}] => Total Power: ${bestResult.bestPower.toFixed(2)}`);
//store the total delivered power //store the total delivered power
this.measurements.type("power").variant("predicted").position("atEquipment").value(bestResult.bestPower); this.measurements.type("power").variant("predicted").position("atequipment").value(bestResult.bestPower);
this.measurements.type("flow").variant("predicted").position("downstream").value(bestResult.bestFlow); this.measurements.type("flow").variant("predicted").position("atequipment").value(bestResult.bestFlow);
this.measurements.type("efficiency").variant("predicted").position("atEquipment").value(bestResult.bestFlow / bestResult.bestPower); this.measurements.type("efficiency").variant("predicted").position("atequipment").value(bestResult.bestFlow / bestResult.bestPower);
this.measurements.type("Ncog").variant("predicted").position("atEquipment").value(bestResult.bestCog); this.measurements.type("Ncog").variant("predicted").position("atequipment").value(bestResult.bestCog);
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => { await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
// Find the flow for this machine in the best combination // Find the flow for this machine in the best combination
@@ -469,16 +489,16 @@ class MachineGroup {
} }
if( (flow <= 0 ) && ( machineStates[machineId] === "operational" || machineStates[machineId] === "accelerating" || machineStates[machineId] === "decelerating" ) ){ if( (flow <= 0 ) && ( machineStates[machineId] === "operational" || machineStates[machineId] === "accelerating" || machineStates[machineId] === "decelerating" ) ){
await machine.handleInput("parent", "execSequence", "shutdown"); await machine.handleInput("parent", "execsequence", "shutdown");
} }
if(machineStates[machineId] === "idle" && flow > 0){ if(machineStates[machineId] === "idle" && flow > 0){
await machine.handleInput("parent", "execSequence", "startup"); await machine.handleInput("parent", "execsequence", "startup");
await machine.handleInput("parent", "flowMovement", flow); await machine.handleInput("parent", "flowmovement", flow);
} }
if(machineStates[machineId] === "operational" && flow > 0 ){ if(machineStates[machineId] === "operational" && flow > 0 ){
await machine.handleInput("parent", "flowMovement", flow); await machine.handleInput("parent", "flowmovement", flow);
} }
})); }));
} }
@@ -551,7 +571,7 @@ class MachineGroup {
filterOutUnavailableMachines(list) { filterOutUnavailableMachines(list) {
const newList = list.filter(({ id, machine }) => { const newList = list.filter(({ id, machine }) => {
const state = machine.state.getCurrentState(); const state = machine.state.getCurrentState();
const validActionForMode = machine.isValidActionForMode("execSequence", "auto"); const validActionForMode = machine.isValidActionForMode("execsequence", "auto");
return !(state === "off" || state === "coolingdown" || state === "stopping" || state === "emergencystop" || !validActionForMode); return !(state === "off" || state === "coolingdown" || state === "stopping" || state === "emergencystop" || !validActionForMode);
}); });
@@ -681,10 +701,10 @@ class MachineGroup {
this.logger.debug(`Priority control for demand: ${totalFlow.toFixed(2)} -> Active pumps: [${debugInfo}] => Total Power: ${totalPower.toFixed(2)}`); this.logger.debug(`Priority control for demand: ${totalFlow.toFixed(2)} -> Active pumps: [${debugInfo}] => Total Power: ${totalPower.toFixed(2)}`);
// Store measurements // Store measurements
this.measurements.type("power").variant("predicted").position("atEquipment").value(totalPower); this.measurements.type("power").variant("predicted").position("atequipment").value(totalPower);
this.measurements.type("flow").variant("predicted").position("downstream").value(totalFlow); this.measurements.type("flow").variant("predicted").position("atequipment").value(totalFlow);
this.measurements.type("efficiency").variant("predicted").position("atEquipment").value(totalFlow / totalPower); this.measurements.type("efficiency").variant("predicted").position("atequipment").value(totalFlow / totalPower);
this.measurements.type("Ncog").variant("predicted").position("atEquipment").value(totalCog); this.measurements.type("Ncog").variant("predicted").position("atequipment").value(totalCog);
this.logger.debug(`Flow distribution: ${JSON.stringify(flowDistribution)}`); this.logger.debug(`Flow distribution: ${JSON.stringify(flowDistribution)}`);
// Apply the flow distribution to machines // Apply the flow distribution to machines
@@ -694,13 +714,13 @@ class MachineGroup {
const currentState = this.machines[machineId].state.getCurrentState(); const currentState = this.machines[machineId].state.getCurrentState();
if (flow <= 0 && (currentState === "operational" || currentState === "accelerating" || currentState === "decelerating")) { if (flow <= 0 && (currentState === "operational" || currentState === "accelerating" || currentState === "decelerating")) {
await machine.handleInput("parent", "execSequence", "shutdown"); await machine.handleInput("parent", "execsequence", "shutdown");
} }
else if (currentState === "idle" && flow > 0) { else if (currentState === "idle" && flow > 0) {
await machine.handleInput("parent", "execSequence", "startup"); await machine.handleInput("parent", "execsequence", "startup");
} }
else if (currentState === "operational" && flow > 0) { else if (currentState === "operational" && flow > 0) {
await machine.handleInput("parent", "flowMovement", flow); await machine.handleInput("parent", "flowmovement", flow);
} }
})); }));
} }
@@ -716,7 +736,7 @@ class MachineGroup {
if(input < 0 ){ if(input < 0 ){
//turn all machines off //turn all machines off
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => { await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
if (this.isMachineActive(machineId)) { await machine.handleInput("parent", "execSequence", "shutdown"); } if (this.isMachineActive(machineId)) { await machine.handleInput("parent", "execsequence", "shutdown"); }
})); }));
return; return;
} }
@@ -780,13 +800,13 @@ class MachineGroup {
const currentState = this.machines[machineId].state.getCurrentState(); const currentState = this.machines[machineId].state.getCurrentState();
if (ctrl < 0 && (currentState === "operational" || currentState === "accelerating" || currentState === "decelerating")) { if (ctrl < 0 && (currentState === "operational" || currentState === "accelerating" || currentState === "decelerating")) {
await machine.handleInput("parent", "execSequence", "shutdown"); await machine.handleInput("parent", "execsequence", "shutdown");
} }
else if (currentState === "idle" && ctrl >= 0) { else if (currentState === "idle" && ctrl >= 0) {
await machine.handleInput("parent", "execSequence", "startup"); await machine.handleInput("parent", "execsequence", "startup");
} }
else if (currentState === "operational" && ctrl > 0) { else if (currentState === "operational" && ctrl > 0) {
await machine.handleInput("parent", "execMovement", ctrl); await machine.handleInput("parent", "execmovement", ctrl);
} }
})); }));
@@ -796,8 +816,8 @@ class MachineGroup {
// fetch and store measurements // fetch and store measurements
Object.entries(this.machines).forEach(([machineId, machine]) => { Object.entries(this.machines).forEach(([machineId, machine]) => {
const powerValue = machine.measurements.type("power").variant("predicted").position("atEquipment").getCurrentValue(); const powerValue = machine.measurements.type("power").variant("predicted").position("atequipment").getCurrentValue();
const flowValue = machine.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue(); const flowValue = machine.measurements.type("flow").variant("predicted").position("atequipment").getCurrentValue();
if (powerValue !== null) { if (powerValue !== null) {
totalPower.push(powerValue); totalPower.push(powerValue);
@@ -807,11 +827,11 @@ class MachineGroup {
} }
}); });
this.measurements.type("power").variant("predicted").position("atEquipment").value(totalPower.reduce((a, b) => a + b, 0)); this.measurements.type("power").variant("predicted").position("atequipment").value(totalPower.reduce((a, b) => a + b, 0));
this.measurements.type("flow").variant("predicted").position("downstream").value(totalFlow.reduce((a, b) => a + b, 0)); this.measurements.type("flow").variant("predicted").position("atequipment").value(totalFlow.reduce((a, b) => a + b, 0));
if(totalPower.reduce((a, b) => a + b, 0) > 0){ if(totalPower.reduce((a, b) => a + b, 0) > 0){
this.measurements.type("efficiency").variant("predicted").position("atEquipment").value(totalFlow.reduce((a, b) => a + b, 0) / totalPower.reduce((a, b) => a + b, 0)); this.measurements.type("efficiency").variant("predicted").position("atequipment").value(totalFlow.reduce((a, b) => a + b, 0) / totalPower.reduce((a, b) => a + b, 0));
} }
} }
@@ -822,13 +842,19 @@ class MachineGroup {
async handleInput(source, demand, powerCap = Infinity, priorityList = null) { async handleInput(source, demand, powerCap = Infinity, priorityList = null) {
const demandQ = parseFloat(demand);
if(!Number.isFinite(demandQ)){
this.logger.error(`Invalid flow demand input: ${demand}. Must be a finite number.`);
return;
}
//abort current movements //abort current movements
await this.abortActiveMovements("new demand received"); await this.abortActiveMovements("new demand received");
const scaling = this.scaling; const scaling = this.scaling;
const mode = this.mode; const mode = this.mode;
const dynamicTotals = this.calcDynamicTotals(); const dynamicTotals = this.calcDynamicTotals();
const demandQ = parseFloat(demand);
let demandQout = 0; // keep output Q by default 0 for safety let demandQout = 0; // keep output Q by default 0 for safety
this.logger.debug(`Handling input from ${source}: Demand = ${demand}, Power Cap = ${powerCap}, Priority List = ${priorityList}`); this.logger.debug(`Handling input from ${source}: Demand = ${demand}, Power Cap = ${powerCap}, Priority List = ${priorityList}`);
@@ -857,7 +883,6 @@ class MachineGroup {
break; break;
case "normalized": case "normalized":
this.logger.debug(`Normalizing flow demand: ${demandQ} with min: ${dynamicTotals.flow.min} and max: ${dynamicTotals.flow.max}`); this.logger.debug(`Normalizing flow demand: ${demandQ} with min: ${dynamicTotals.flow.min} and max: ${dynamicTotals.flow.max}`);
if(demand < 0){ if(demand < 0){
this.logger.debug(`Turning machines off`); this.logger.debug(`Turning machines off`);
@@ -875,7 +900,6 @@ class MachineGroup {
} }
// Execute control based on mode // Execute control based on mode
switch(mode) { switch(mode) {
case "prioritycontrol": case "prioritycontrol":
@@ -911,7 +935,7 @@ class MachineGroup {
async turnOffAllMachines(){ async turnOffAllMachines(){
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => { await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
if (this.isMachineActive(machineId)) { await machine.handleInput("parent", "execSequence", "shutdown"); } if (this.isMachineActive(machineId)) { await machine.handleInput("parent", "execsequence", "shutdown"); }
})); }));
} }
@@ -929,7 +953,7 @@ class MachineGroup {
this.measurements.getVariants(type).forEach(variant => { this.measurements.getVariants(type).forEach(variant => {
const downstreamVal = this.measurements.type(type).variant(variant).position("downstream").getCurrentValue(); const downstreamVal = this.measurements.type(type).variant(variant).position("downstream").getCurrentValue();
const atEquipmentVal = this.measurements.type(type).variant(variant).position("atEquipment").getCurrentValue(); const atEquipmentVal = this.measurements.type(type).variant(variant).position("atequipment").getCurrentValue();
const upstreamVal = this.measurements.type(type).variant(variant).position("upstream").getCurrentValue(); const upstreamVal = this.measurements.type(type).variant(variant).position("upstream").getCurrentValue();
if (downstreamVal != null) { if (downstreamVal != null) {
@@ -939,7 +963,7 @@ class MachineGroup {
output[`upstream_${variant}_${type}`] = upstreamVal; output[`upstream_${variant}_${type}`] = upstreamVal;
} }
if (atEquipmentVal != null) { if (atEquipmentVal != null) {
output[`atEquipment_${variant}_${type}`] = atEquipmentVal; output[`atequipment${variant}_${type}`] = atEquipmentVal;
} }
if (downstreamVal != null && upstreamVal != null) { if (downstreamVal != null && upstreamVal != null) {
const diffVal = this.measurements.type(type).variant(variant).difference().value; const diffVal = this.measurements.type(type).variant(variant).difference().value;
@@ -964,8 +988,8 @@ class MachineGroup {
} }
module.exports = MachineGroup; module.exports = MachineGroup;
/*
/*
const Machine = require('../../rotatingMachine/src/specificClass'); const Machine = require('../../rotatingMachine/src/specificClass');
const Measurement = require('../../measurement/src/specificClass'); const Measurement = require('../../measurement/src/specificClass');
const specs = require('../../generalFunctions/datasets/assetData/curves/hidrostal-H05K-S03R.json'); const specs = require('../../generalFunctions/datasets/assetData/curves/hidrostal-H05K-S03R.json');
@@ -993,9 +1017,9 @@ function createBaseMachineConfig(machineNum, name,specs) {
mode: { mode: {
current: "auto", current: "auto",
allowedActions: { allowedActions: {
auto: ["execSequence", "execMovement", "statusCheck"], auto: ["execsequence", "execmovement", "statuscheck"],
virtualControl: ["execMovement", "statusCheck"], virtualControl: ["execmovement", "statuscheck"],
fysicalControl: ["statusCheck"] fysicalControl: ["statuscheck"]
}, },
allowedSources: { allowedSources: {
auto: ["parent", "GUI"], auto: ["parent", "GUI"],
@@ -1103,7 +1127,7 @@ async function makeMachines(){
const percMax = 100; const percMax = 100;
try{ try{
/*
for(let demand = mg.dynamicTotals.flow.min ; demand <= mg.dynamicTotals.flow.max ; demand += 2){ for(let demand = mg.dynamicTotals.flow.min ; demand <= mg.dynamicTotals.flow.max ; demand += 2){
//set pressure //set pressure