Compare commits

..

2 Commits

2 changed files with 73 additions and 127 deletions

View File

@@ -67,8 +67,8 @@ class nodeClass {
const totalFlow = mg.measurements
?.type("flow")
?.variant("predicted")
?.position("atequipment")
?.getCurrentValue('m3/h') || 0;
?.position("downstream")
?.getCurrentValue() || 0;
const totalPower = mg.measurements
?.type("power")
@@ -181,8 +181,8 @@ class nodeClass {
*/
_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");
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]);
@@ -199,16 +199,16 @@ class nodeClass {
const RED = this.RED;
switch (msg.topic) {
case "registerChild":
//console.log(`Registering child in mgc: ${msg.payload}`);
console.log(`Registering child in mgc: ${msg.payload}`);
const childId = msg.payload;
const childObj = RED.nodes.getNode(childId);
// Debug: Check what we're getting
//console.log(`Child object:`, childObj ? 'found' : 'NOT FOUND');
//console.log(`Child source:`, childObj?.source ? 'exists' : 'MISSING');
console.log(`Child object:`, childObj ? 'found' : 'NOT FOUND');
console.log(`Child source:`, childObj?.source ? 'exists' : 'MISSING');
if (childObj?.source) {
//console.log(`Child source type:`, childObj.source.constructor.name);
//console.log(`Child has state:`, !!childObj.source.state);
console.log(`Child source type:`, childObj.source.constructor.name);
console.log(`Child has state:`, !!childObj.source.state);
}
mg.childRegistrationUtils.registerChild(
@@ -217,7 +217,7 @@ class nodeClass {
);
// 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;
case "setMode":

View File

@@ -15,17 +15,7 @@ class MachineGroup {
this.logger = new logger(this.config.general.logging.enabled,this.config.general.logging.logLevel, this.config.general.name);
// Initialize measurements
this.measurements = new MeasurementContainer({
autoConvert: true,
windowSize: 50,
defaultUnits: {
pressure: 'mbar',
flow: 'l/s',
power: 'kW',
temperature: 'C'
}
});
this.measurements = new MeasurementContainer();
this.interpolation = new interpolation();
// Machines and child data
@@ -50,8 +40,6 @@ class MachineGroup {
registerChild(child,softwareType) {
this.logger.debug('Setting up childs specific for this class');
const position = child.config.general.positionVsParent;
if(softwareType == "machine"){
// 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.`);
@@ -145,23 +133,15 @@ class MachineGroup {
this.logger.debug(`\n --------- Calculating dynamic totals for ${Object.keys(this.machines).length} machines. @ current pressure settings : ----------`);
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(`Current pressure settings: ${JSON.stringify(machine.predictFlow.currentF)}`);
//fetch min flow ever seen over all machines
const minFlow = machine.predictFlow.currentFxyYMin;
const maxFlow = machine.predictFlow.currentFxyYMax;
const minPower = machine.predictPower.currentFxyYMin;
const maxPower = machine.predictPower.currentFxyYMax;
const actFlow = machine.measurements.type("flow").variant("predicted").position("atequipment").getCurrentValue();
const actPower = machine.measurements.type("power").variant("predicted").position("atequipment").getCurrentValue();
const actFlow = machine.measurements.type("flow").variant("predicted").position("downstream").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}`);
@@ -215,11 +195,11 @@ class MachineGroup {
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.measurements.type("flow").variant("predicted").position("atequipment").value(flow.act);
this.measurements.type("power").variant("predicted").position("atequipment").value(power.act);
this.measurements.type("flow").variant("predicted").position("downstream").value(flow.act);
this.measurements.type("power").variant("predicted").position("atEquipment").value(power.act);
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);
}
@@ -258,8 +238,8 @@ class MachineGroup {
if(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("atequipment").getCurrentValue()){
flow = machine.measurements.type("flow").variant("predicted").position("atequipment").getCurrentValue();
else if(machine.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue()){
flow = machine.measurements.type("flow").variant("predicted").position("downstream").getCurrentValue();
}
else{
this.logger.error("Dont perform calculation at all seeing that there is a machine working but we dont know the flow its producing");
@@ -284,7 +264,7 @@ class MachineGroup {
Object.keys(machines).forEach(machineId => {
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
@@ -333,71 +313,42 @@ class MachineGroup {
calcBestCombination(combinations, Qd) {
let bestCombination = null;
//keep track of totals
let bestPower = Infinity;
let bestFlow = 0;
let bestCog = 0;
combinations.forEach(combination => {
let flowDistribution = [];
let flowDistribution = []; // Stores the flow distribution for the best combination
let totalCoG = 0;
let totalPower = 0;
let totalFlow = 0;
// Sum normalized CoG for the combination
combination.forEach(machineId => {
totalCoG += Math.round((this.machines[machineId].NCog || 0) * 100) / 100;
});
// Calculate the total CoG for the current combination
combination.forEach(machineId => { totalCoG += ( Math.round(this.machines[machineId].NCog * 100 ) /100 ) ; });
// Initial CoG-based distribution
// Calculate the total power for the current combination
combination.forEach(machineId => {
let flow = 0;
// Prevent division by zero
if (totalCoG === 0) {
// Distribute flow equally among all pumps
flow = Qd / combination.length;
} else {
flow = ((this.machines[machineId].NCog || 0) / totalCoG) * Qd;
// Normal CoG-based distribution
flow = (this.machines[machineId].NCog / totalCoG) * Qd ;
this.logger.debug(`Machine Normalized CoG-based distribution ${machineId} flow: ${flow}`);
}
flowDistribution.push({ machineId, flow });
});
// Clamp to min/max and spill leftover once
const clamped = flowDistribution.map(entry => {
const machine = this.machines[entry.machineId];
const min = machine.predictFlow.currentFxyYMin;
const max = machine.predictFlow.currentFxyYMax;
const clampedFlow = Math.min(max, Math.max(min, entry.flow));
return { ...entry, flow: clampedFlow, min, max, desired: entry.flow };
});
let remainder = Qd - clamped.reduce((sum, entry) => sum + entry.flow, 0);
if (Math.abs(remainder) > 1e-6) {
const adjustable = clamped.filter(entry =>
remainder > 0 ? entry.flow < entry.max : entry.flow > entry.min
);
const weightSum = adjustable.reduce((sum, entry) => sum + entry.desired, 0) || adjustable.length;
adjustable.forEach(entry => {
const weight = entry.desired / weightSum || 1 / adjustable.length;
const delta = remainder * weight;
const next = remainder > 0
? Math.min(entry.max, entry.flow + delta)
: Math.max(entry.min, entry.flow + delta);
remainder -= (next - entry.flow);
entry.flow = next;
});
}
flowDistribution = clamped;
let totalFlow = 0;
flowDistribution.forEach(({ machineId, flow }) => {
totalFlow += flow;
totalPower += this.machines[machineId].inputFlowCalcPower(flow);
flowDistribution.push({ machineId: machineId,flow: flow });
});
// Update the best combination if the current one is better
if (totalPower < bestPower) {
this.logger.debug(`New best combination found: ${totalPower} < ${bestPower}`);
this.logger.debug(`combination ${JSON.stringify(flowDistribution)}`);
@@ -411,7 +362,6 @@ class MachineGroup {
return { bestCombination, bestPower, bestFlow, bestCog };
}
// -------- Mode and Input Management -------- //
isValidActionForMode(action, mode) {
const allowedActionsSet = this.config.mode.allowedActions[mode] || [];
@@ -501,10 +451,10 @@ class MachineGroup {
this.logger.debug(`Moving to demand: ${Qd.toFixed(2)} -> Pumps: [${debugInfo}] => Total Power: ${bestResult.bestPower.toFixed(2)}`);
//store the total delivered power
this.measurements.type("power").variant("predicted").position("atequipment").value(bestResult.bestPower);
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("Ncog").variant("predicted").position("atequipment").value(bestResult.bestCog);
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("efficiency").variant("predicted").position("atEquipment").value(bestResult.bestFlow / bestResult.bestPower);
this.measurements.type("Ncog").variant("predicted").position("atEquipment").value(bestResult.bestCog);
await Promise.all(Object.entries(this.machines).map(async ([machineId, machine]) => {
// Find the flow for this machine in the best combination
@@ -519,16 +469,16 @@ class MachineGroup {
}
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){
await machine.handleInput("parent", "execsequence", "startup");
await machine.handleInput("parent", "flowmovement", flow);
await machine.handleInput("parent", "execSequence", "startup");
await machine.handleInput("parent", "flowMovement", flow);
}
if(machineStates[machineId] === "operational" && flow > 0 ){
await machine.handleInput("parent", "flowmovement", flow);
await machine.handleInput("parent", "flowMovement", flow);
}
}));
}
@@ -601,7 +551,7 @@ class MachineGroup {
filterOutUnavailableMachines(list) {
const newList = list.filter(({ id, machine }) => {
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);
});
@@ -731,10 +681,10 @@ class MachineGroup {
this.logger.debug(`Priority control for demand: ${totalFlow.toFixed(2)} -> Active pumps: [${debugInfo}] => Total Power: ${totalPower.toFixed(2)}`);
// Store measurements
this.measurements.type("power").variant("predicted").position("atequipment").value(totalPower);
this.measurements.type("flow").variant("predicted").position("atequipment").value(totalFlow);
this.measurements.type("efficiency").variant("predicted").position("atequipment").value(totalFlow / totalPower);
this.measurements.type("Ncog").variant("predicted").position("atequipment").value(totalCog);
this.measurements.type("power").variant("predicted").position("atEquipment").value(totalPower);
this.measurements.type("flow").variant("predicted").position("downstream").value(totalFlow);
this.measurements.type("efficiency").variant("predicted").position("atEquipment").value(totalFlow / totalPower);
this.measurements.type("Ncog").variant("predicted").position("atEquipment").value(totalCog);
this.logger.debug(`Flow distribution: ${JSON.stringify(flowDistribution)}`);
// Apply the flow distribution to machines
@@ -744,13 +694,13 @@ class MachineGroup {
const currentState = this.machines[machineId].state.getCurrentState();
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) {
await machine.handleInput("parent", "execsequence", "startup");
await machine.handleInput("parent", "execSequence", "startup");
}
else if (currentState === "operational" && flow > 0) {
await machine.handleInput("parent", "flowmovement", flow);
await machine.handleInput("parent", "flowMovement", flow);
}
}));
}
@@ -766,7 +716,7 @@ class MachineGroup {
if(input < 0 ){
//turn all machines off
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;
}
@@ -830,13 +780,13 @@ class MachineGroup {
const currentState = this.machines[machineId].state.getCurrentState();
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) {
await machine.handleInput("parent", "execsequence", "startup");
await machine.handleInput("parent", "execSequence", "startup");
}
else if (currentState === "operational" && ctrl > 0) {
await machine.handleInput("parent", "execmovement", ctrl);
await machine.handleInput("parent", "execMovement", ctrl);
}
}));
@@ -846,8 +796,8 @@ class MachineGroup {
// fetch and store measurements
Object.entries(this.machines).forEach(([machineId, machine]) => {
const powerValue = machine.measurements.type("power").variant("predicted").position("atequipment").getCurrentValue();
const flowValue = machine.measurements.type("flow").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();
if (powerValue !== null) {
totalPower.push(powerValue);
@@ -857,11 +807,11 @@ class MachineGroup {
}
});
this.measurements.type("power").variant("predicted").position("atequipment").value(totalPower.reduce((a, b) => a + b, 0));
this.measurements.type("flow").variant("predicted").position("atequipment").value(totalFlow.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));
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));
}
}
@@ -872,19 +822,13 @@ class MachineGroup {
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
await this.abortActiveMovements("new demand received");
const scaling = this.scaling;
const mode = this.mode;
const dynamicTotals = this.calcDynamicTotals();
const demandQ = parseFloat(demand);
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}`);
@@ -913,6 +857,7 @@ class MachineGroup {
break;
case "normalized":
this.logger.debug(`Normalizing flow demand: ${demandQ} with min: ${dynamicTotals.flow.min} and max: ${dynamicTotals.flow.max}`);
if(demand < 0){
this.logger.debug(`Turning machines off`);
@@ -930,6 +875,7 @@ class MachineGroup {
}
// Execute control based on mode
switch(mode) {
case "prioritycontrol":
@@ -965,7 +911,7 @@ class MachineGroup {
async turnOffAllMachines(){
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"); }
}));
}
@@ -983,7 +929,7 @@ class MachineGroup {
this.measurements.getVariants(type).forEach(variant => {
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();
if (downstreamVal != null) {
@@ -993,7 +939,7 @@ class MachineGroup {
output[`upstream_${variant}_${type}`] = upstreamVal;
}
if (atEquipmentVal != null) {
output[`atequipment${variant}_${type}`] = atEquipmentVal;
output[`atEquipment_${variant}_${type}`] = atEquipmentVal;
}
if (downstreamVal != null && upstreamVal != null) {
const diffVal = this.measurements.type(type).variant(variant).difference().value;
@@ -1018,8 +964,8 @@ class MachineGroup {
}
module.exports = MachineGroup;
/*
const Machine = require('../../rotatingMachine/src/specificClass');
const Measurement = require('../../measurement/src/specificClass');
const specs = require('../../generalFunctions/datasets/assetData/curves/hidrostal-H05K-S03R.json');
@@ -1047,9 +993,9 @@ function createBaseMachineConfig(machineNum, name,specs) {
mode: {
current: "auto",
allowedActions: {
auto: ["execsequence", "execmovement", "statuscheck"],
virtualControl: ["execmovement", "statuscheck"],
fysicalControl: ["statuscheck"]
auto: ["execSequence", "execMovement", "statusCheck"],
virtualControl: ["execMovement", "statusCheck"],
fysicalControl: ["statusCheck"]
},
allowedSources: {
auto: ["parent", "GUI"],
@@ -1157,7 +1103,7 @@ async function makeMachines(){
const percMax = 100;
try{
/*
for(let demand = mg.dynamicTotals.flow.min ; demand <= mg.dynamicTotals.flow.max ; demand += 2){
//set pressure