Compare commits

...

6 Commits

2 changed files with 119 additions and 44 deletions

View File

@@ -114,8 +114,8 @@ class nodeClass {
try {
const mode = m.currentMode;
const state = m.state.getCurrentState();
const flow = Math.round(m.measurements.type("flow").variant("predicted").position('downstream').getCurrentValue());
const power = Math.round(m.measurements.type("power").variant("predicted").position('upstream').getCurrentValue());
const flow = Math.round(m.measurements.type("flow").variant("predicted").position('downstream').getCurrentValue('m3/h'));
const power = Math.round(m.measurements.type("power").variant("predicted").position('atequipment').getCurrentValue('kW'));
let symbolState;
switch(state){
case "off":
@@ -145,6 +145,9 @@ class nodeClass {
case "decelerating":
symbolState = "⏪";
break;
case "maintenance":
symbolState = "🔧";
break;
}
const position = m.state.getCurrentPosition();
const roundedPosition = Math.round(position * 100) / 100;
@@ -224,8 +227,8 @@ class nodeClass {
//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');
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]);

View File

@@ -1,6 +1,6 @@
const EventEmitter = require('events');
const {loadCurve,logger,configUtils,configManager,state, nrmse, MeasurementContainer, predict, interpolation , childRegistrationUtils} = require('generalFunctions');
const { name } = require('../../generalFunctions/src/convert/lodash/lodash._shimkeys');
const {loadCurve,gravity,logger,configUtils,configManager,state, nrmse, MeasurementContainer, predict, interpolation , childRegistrationUtils,coolprop} = require('generalFunctions');
const pressure = require('../../generalFunctions/src/convert/definitions/pressure');
class Machine {
@@ -48,7 +48,17 @@ class Machine {
this.errorMetrics = new nrmse(errorMetricsConfig, this.logger);
// Initialize measurements
this.measurements = new MeasurementContainer();
this.measurements = new MeasurementContainer({
autoConvert: true,
windowSize: 50,
defaultUnits: {
pressure: 'mbar',
flow: this.config.general.unit,
power: 'kW',
temperature: 'C'
}
});
this.interpolation = new interpolation();
this.flowDrift = null;
@@ -68,9 +78,35 @@ class Machine {
this.updatePosition();
});
//When state changes look if we need to do other updates
this.state.emitter.on("stateChange", (newState) => {
this.logger.debug(`State change detected: ${newState}`);
this._updateState();
});
//perform init for certain values
this._init();
this.child = {}; // object to hold child information so we know on what to subscribe
this.childRegistrationUtils = new childRegistrationUtils(this); // Child registration utility
}
_init(){
//assume standard temperature is 20degrees
this.measurements.type('temperature').variant('measured').position('atEquipment').value(15).unit('C');
//assume standard atm pressure is at sea level
this.measurements.type('atmPressure').variant('measured').position('atEquipment').value(101325).unit('Pa');
}
_updateState(){
const isOperational = this._isOperationalState();
if(!isOperational){
//overrule the last prediction this should be 0 now
this.measurements.type("flow").variant("predicted").position("downstream").value(0);
}
}
/*------------------- Register child events -------------------*/
@@ -165,43 +201,65 @@ _callMeasurementHandler(measurementType, value, position, context) {
// -------- Mode and Input Management -------- //
isValidSourceForMode(source, mode) {
const allowedSourcesSet = this.config.mode.allowedSources[mode] || [];
return allowedSourcesSet.has(source);
const allowed = allowedSourcesSet.has(source);
allowed?
this.logger.debug(`source is allowed proceeding with ${source} for mode ${mode}`) :
this.logger.warn(`${source} is not allowed in mode ${mode}`);
return allowed;
}
isValidActionForMode(action, mode) {
const allowedActionsSet = this.config.mode.allowedActions[mode] || [];
return allowedActionsSet.has(action);
const allowed = allowedActionsSet.has(action);
allowed ?
this.logger.debug(`Action is allowed proceeding with ${action} for mode ${mode}`) :
this.logger.warn(`${action} is not allowed in mode ${mode}`);
return allowed;
}
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};
}
//sanitize input
if( typeof action !== 'string'){this.logger.error(`Action must be string`); return;}
//convert to lower case to avoid to many mistakes in commands
action = action.toLowerCase();
// check for validity of the request
if(!this.isValidActionForMode(action,this.currentMode)){return ;}
if (!this.isValidSourceForMode(source, this.currentMode)) {return ;}
this.logger.info(`Handling input from source '${source}' with action '${action}' in mode '${this.currentMode}'.`);
try {
switch (action) {
case "execSequence":
case "execsequence":
return await this.executeSequence(parameter);
case "execMovement":
case "execmovement":
return await this.setpoint(parameter);
case "flowMovement":
case "entermaintenance":
return await this.executeSequence(parameter);
case "exitmaintenance":
return await this.executeSequence(parameter);
case "flowmovement":
// Calculate the control value for a desired flow
const pos = this.calcCtrl(parameter);
// Move to the desired setpoint
return await this.setpoint(pos);
case "emergencyStop":
case "emergencystop":
this.logger.warn(`Emergency stop activated by '${source}'.`);
return await this.executeSequence("emergencyStop");
case "statusCheck":
case "statuscheck":
this.logger.info(`Status Check: Mode = '${this.currentMode}', Source = '${source}'.`);
break;
@@ -501,13 +559,14 @@ _callMeasurementHandler(measurementType, value, position, context) {
// Update predicted flow if you have prediction capability
if (this.predictFlow) {
this.measurements.type("flow").variant("predicted").position("atEquipment").value(this.predictFlow.outputY || 0);
this.measurements.type("flow").variant("predicted").position("downstream").value(this.predictFlow.outputY || 0);
}
}
// Helper method for operational state check
_isOperationalState() {
const state = this.state.getCurrentState();
this.logger.debug(`Checking operational state ${this.state.getCurrentState()} ? ${["operational", "accelerating", "decelerating"].includes(state)}`);
return ["operational", "accelerating", "decelerating"].includes(state);
}
@@ -531,6 +590,9 @@ _callMeasurementHandler(measurementType, value, position, context) {
this.calcDistanceBEP(efficiency,cog,minEfficiency);
}
}
calcDistanceFromPeak(currentEfficiency,peakEfficiency){
@@ -561,7 +623,6 @@ _callMeasurementHandler(measurementType, value, position, context) {
};
}
// Calculate the center of gravity for current pressure
calcCog() {
@@ -623,13 +684,34 @@ _callMeasurementHandler(measurementType, value, position, context) {
calcEfficiency(power,flow,variant) {
const pressureDiff = this.measurements.type('pressure').variant('measured').difference('Pa');
const g = gravity.getStandardGravity();
const temp = this.measurements.type('temperature').variant('measured').position('atEquipment').getCurrentValue('K');
const atmPressure = this.measurements.type('atmPressure').variant('measured').position('atEquipment').getCurrentValue('Pa');
const rho = coolprop.PropsSI('D', 'T', temp, 'P', atmPressure, 'WasteWater');
this.logger.debug(`temp: ${temp} atmPressure : ${atmPressure} rho : ${rho} pressureDiff: ${pressureDiff?.value || 0}`);
const flowM3s = this.measurements.type('flow').variant('predicted').position('atEquipment').getCurrentValue('m3/s');
const powerWatt = this.measurements.type('power').variant('predicted').position('atEquipment').getCurrentValue('W');
this.logger.debug(`Flow : ${flowM3s} power: ${powerWatt}`);
if (power != 0 && flow != 0) {
// Calculate efficiency after measurements update
this.measurements.type("efficiency").variant(variant).position('atEquipment').value((flow / power));
} else {
this.measurements.type("efficiency").variant(variant).position('atEquipment').value(null);
const specificFlow = flow / power;
const specificEnergyConsumption = power / flow;
this.measurements.type("efficiency").variant(variant).position('atEquipment').value(specificFlow);
this.measurements.type("specificEnergyConsumption").variant(variant).position('atEquipment').value(specificEnergyConsumption);
if(pressureDiff?.value != null && flowM3s != null && powerWatt != null){
const meterPerBar = pressureDiff.value / rho * g;
const nHydraulicEfficiency = rho * g * flowM3s * (pressureDiff.value * meterPerBar ) / powerWatt;
this.measurements.type("nHydraulicEfficiency").variant(variant).position('atEquipment').value(nHydraulicEfficiency);
}
}
//change this to nhydrefficiency ?
return this.measurements.type("efficiency").variant(variant).position('atEquipment').getCurrentValue();
}
@@ -677,23 +759,12 @@ _callMeasurementHandler(measurementType, value, position, context) {
// Improved output object generation
const output = {};
//build the output object
this.measurements.getTypes().forEach(type => {
this.measurements.getVariants(type).forEach(variant => {
const downstreamVal = this.measurements.type(type).variant(variant).position("downstream").getCurrentValue();
const upstreamVal = this.measurements.type(type).variant(variant).position("upstream").getCurrentValue();
if (downstreamVal != null) {
output[`downstream_${variant}_${type}`] = downstreamVal;
}
if (upstreamVal != null) {
output[`upstream_${variant}_${type}`] = upstreamVal;
}
if (downstreamVal != null && upstreamVal != null) {
const diffVal = this.measurements.type(type).variant(variant).difference().value;
output[`differential_${variant}_${type}`] = diffVal;
}
Object.entries(this.measurements.measurements).forEach(([type, variants]) => {
Object.entries(variants).forEach(([variant, positions]) => {
Object.entries(positions).forEach(([position, measurement]) => {
output[`${type}.${variant}.${position}`] = measurement.getCurrentValue();
});
});
});
@@ -706,6 +777,7 @@ _callMeasurementHandler(measurementType, value, position, context) {
output["cog"] = this.cog; // flow / power efficiency
output["NCog"] = this.NCog; // normalized cog
output["NCogPercent"] = Math.round(this.NCog * 100 * 100) / 100 ;
output["maintenanceTime"] = this.state.getMaintenanceTimeHours();
if(this.flowDrift != null){
const flowDrift = this.flowDrift;
@@ -729,8 +801,8 @@ _callMeasurementHandler(measurementType, value, position, context) {
module.exports = Machine;
/*------------------- Testing -------------------*/
/*
/*
curve = require('C:/Users/zn375/.node-red/public/fallbackData.json');
//import a child