Compare commits
3 Commits
0430471dca
...
dev-Rene
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b337bf9eb7 | ||
|
|
f8012c8bad | ||
|
|
ee38c8b581 |
8
examples/README.md
Normal file
8
examples/README.md
Normal file
@@ -0,0 +1,8 @@
|
||||
# machineGroupControl Example Flows
|
||||
|
||||
Import-ready Node-RED examples for machineGroupControl.
|
||||
|
||||
## Files
|
||||
- basic.flow.json
|
||||
- integration.flow.json
|
||||
- edge.flow.json
|
||||
6
examples/basic.flow.json
Normal file
6
examples/basic.flow.json
Normal file
@@ -0,0 +1,6 @@
|
||||
[
|
||||
{"id":"machineGroupControl_basic_tab","type":"tab","label":"machineGroupControl basic","disabled":false,"info":"machineGroupControl basic example"},
|
||||
{"id":"machineGroupControl_basic_node","type":"machineGroupControl","z":"machineGroupControl_basic_tab","name":"machineGroupControl basic","x":420,"y":180,"wires":[["machineGroupControl_basic_dbg"]]},
|
||||
{"id":"machineGroupControl_basic_inj","type":"inject","z":"machineGroupControl_basic_tab","name":"basic trigger","props":[{"p":"topic","vt":"str"},{"p":"payload","vt":"str"}],"topic":"ping","payload":"1","payloadType":"str","x":160,"y":180,"wires":[["machineGroupControl_basic_node"]]},
|
||||
{"id":"machineGroupControl_basic_dbg","type":"debug","z":"machineGroupControl_basic_tab","name":"machineGroupControl basic debug","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":660,"y":180,"wires":[]}
|
||||
]
|
||||
6
examples/edge.flow.json
Normal file
6
examples/edge.flow.json
Normal file
@@ -0,0 +1,6 @@
|
||||
[
|
||||
{"id":"machineGroupControl_edge_tab","type":"tab","label":"machineGroupControl edge","disabled":false,"info":"machineGroupControl edge example"},
|
||||
{"id":"machineGroupControl_edge_node","type":"machineGroupControl","z":"machineGroupControl_edge_tab","name":"machineGroupControl edge","x":420,"y":180,"wires":[["machineGroupControl_edge_dbg"]]},
|
||||
{"id":"machineGroupControl_edge_inj","type":"inject","z":"machineGroupControl_edge_tab","name":"unknown topic","props":[{"p":"topic","vt":"str"},{"p":"payload","vt":"str"}],"topic":"doesNotExist","payload":"x","payloadType":"str","x":170,"y":180,"wires":[["machineGroupControl_edge_node"]]},
|
||||
{"id":"machineGroupControl_edge_dbg","type":"debug","z":"machineGroupControl_edge_tab","name":"machineGroupControl edge debug","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":660,"y":180,"wires":[]}
|
||||
]
|
||||
6
examples/integration.flow.json
Normal file
6
examples/integration.flow.json
Normal file
@@ -0,0 +1,6 @@
|
||||
[
|
||||
{"id":"machineGroupControl_int_tab","type":"tab","label":"machineGroupControl integration","disabled":false,"info":"machineGroupControl integration example"},
|
||||
{"id":"machineGroupControl_int_node","type":"machineGroupControl","z":"machineGroupControl_int_tab","name":"machineGroupControl integration","x":420,"y":180,"wires":[["machineGroupControl_int_dbg"]]},
|
||||
{"id":"machineGroupControl_int_inj","type":"inject","z":"machineGroupControl_int_tab","name":"registerChild","props":[{"p":"topic","vt":"str"},{"p":"payload","vt":"str"}],"topic":"registerChild","payload":"example-child-id","payloadType":"str","x":170,"y":180,"wires":[["machineGroupControl_int_node"]]},
|
||||
{"id":"machineGroupControl_int_dbg","type":"debug","z":"machineGroupControl_int_tab","name":"machineGroupControl integration debug","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","x":680,"y":180,"wires":[]}
|
||||
]
|
||||
2
mgc.html
2
mgc.html
@@ -39,7 +39,7 @@
|
||||
icon: "font-awesome/fa-cogs",
|
||||
|
||||
label: function () {
|
||||
return this.positionIcon + " " + "machineGroup";
|
||||
return (this.positionIcon || "") + " machineGroup";
|
||||
},
|
||||
oneditprepare: function() {
|
||||
// Initialize the menu data for the node
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"description": "Control module machineGroupControl",
|
||||
"main": "mgc.js",
|
||||
"scripts": {
|
||||
"test": "node mgc.js"
|
||||
"test": "node --test test/basic/*.test.js test/integration/*.test.js test/edge/*.test.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
const { outputUtils, configManager } = require("generalFunctions");
|
||||
const { outputUtils, configManager, convert } = require("generalFunctions");
|
||||
const Specific = require("./specificClass");
|
||||
|
||||
class nodeClass {
|
||||
@@ -37,13 +37,14 @@ class nodeClass {
|
||||
_loadConfig(uiConfig, node) {
|
||||
const cfgMgr = new configManager();
|
||||
this.defaultConfig = cfgMgr.getConfig(this.name);
|
||||
const flowUnit = this._resolveUnitOrFallback(uiConfig.unit, 'volumeFlowRate', 'm3/h', 'flow');
|
||||
|
||||
// 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)
|
||||
unit: flowUnit,
|
||||
logging: {
|
||||
enabled: uiConfig.enableLog,
|
||||
logLevel: uiConfig.logLevel,
|
||||
@@ -57,6 +58,24 @@ class nodeClass {
|
||||
this._output = new outputUtils();
|
||||
}
|
||||
|
||||
_resolveUnitOrFallback(candidate, expectedMeasure, fallbackUnit, label) {
|
||||
const raw = typeof candidate === "string" ? candidate.trim() : "";
|
||||
const fallback = String(fallbackUnit || "").trim();
|
||||
if (!raw) {
|
||||
return fallback;
|
||||
}
|
||||
try {
|
||||
const desc = convert().describe(raw);
|
||||
if (expectedMeasure && desc.measure !== expectedMeasure) {
|
||||
throw new Error(`expected '${expectedMeasure}' but got '${desc.measure}'`);
|
||||
}
|
||||
return raw;
|
||||
} catch (error) {
|
||||
this.node?.warn?.(`Invalid ${label} unit '${raw}' (${error.message}). Falling back to '${fallback}'.`);
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
_updateNodeStatus() {
|
||||
//console.log('Updating node status...');
|
||||
const mg = this.source;
|
||||
@@ -68,19 +87,19 @@ class nodeClass {
|
||||
?.type("flow")
|
||||
?.variant("predicted")
|
||||
?.position("atequipment")
|
||||
?.getCurrentValue('m3/h') || 0;
|
||||
?.getCurrentValue(mg?.unitPolicy?.output?.flow || 'm3/h') || 0;
|
||||
|
||||
const totalPower = mg.measurements
|
||||
?.type("power")
|
||||
?.variant("predicted")
|
||||
?.position("atEquipment")
|
||||
?.getCurrentValue() || 0;
|
||||
?.getCurrentValue(mg?.unitPolicy?.output?.power || 'kW') || 0;
|
||||
|
||||
// Calculate total capacity based on available machines with safety checks
|
||||
const availableMachines = Object.values(mg.machines || {}).filter((machine) => {
|
||||
// Safety check: ensure machine and machine.state exist
|
||||
if (!machine || !machine.state || typeof machine.state.getCurrentState !== 'function') {
|
||||
console.warn(`Machine missing or invalid:`, machine?.config?.general?.id || 'unknown');
|
||||
mg.logger?.warn(`Machine missing or invalid: ${machine?.config?.general?.id || 'unknown'}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -197,64 +216,49 @@ class nodeClass {
|
||||
async (msg, send, done) => {
|
||||
const mg = this.source;
|
||||
const RED = this.RED;
|
||||
try {
|
||||
switch (msg.topic) {
|
||||
case "registerChild":
|
||||
//console.log(`Registering child in mgc: ${msg.payload}`);
|
||||
case "registerChild": {
|
||||
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');
|
||||
if (childObj?.source) {
|
||||
//console.log(`Child source type:`, childObj.source.constructor.name);
|
||||
//console.log(`Child has state:`, !!childObj.source.state);
|
||||
if (!childObj || !childObj.source) {
|
||||
mg.logger.warn(`registerChild skipped: missing child/source for id=${childId}`);
|
||||
break;
|
||||
}
|
||||
|
||||
mg.childRegistrationUtils.registerChild(
|
||||
childObj.source,
|
||||
msg.positionVsParent
|
||||
);
|
||||
|
||||
// Debug: Check machines after registration
|
||||
//console.log(`Total machines after registration:`, Object.keys(mg.machines || {}).length);
|
||||
mg.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent);
|
||||
break;
|
||||
|
||||
}
|
||||
case "setMode":
|
||||
const mode = msg.payload;
|
||||
mg.setMode(mode);
|
||||
mg.setMode(msg.payload);
|
||||
break;
|
||||
|
||||
case "setScaling":
|
||||
const scaling = msg.payload;
|
||||
mg.setScaling(scaling);
|
||||
|
||||
mg.setScaling(msg.payload);
|
||||
break;
|
||||
|
||||
case "Qd":
|
||||
case "Qd": {
|
||||
const Qd = parseFloat(msg.payload);
|
||||
const sourceQd = "parent";
|
||||
|
||||
if (isNaN(Qd)) {
|
||||
return mg.logger.error(`Invalid demand value: ${Qd}`);
|
||||
mg.logger.error(`Invalid demand value: ${msg.payload}`);
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
await mg.handleInput(sourceQd, Qd);
|
||||
msg.topic = mg.config.general.name;
|
||||
msg.payload = "done";
|
||||
send(msg);
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
} catch (error) {
|
||||
mg.logger.error(`Failed to process Qd: ${error.message}`);
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
default:
|
||||
// Handle unknown topics if needed
|
||||
mg.logger.warn(`Unknown topic: ${msg.topic}`);
|
||||
break;
|
||||
}
|
||||
done();
|
||||
} catch (error) {
|
||||
mg.logger.error(`Input handler failure: ${error.message}`);
|
||||
}
|
||||
if (typeof done === 'function') done();
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -266,7 +270,7 @@ class nodeClass {
|
||||
this.node.on("close", (done) => {
|
||||
clearInterval(this._tickInterval);
|
||||
clearInterval(this._statusInterval);
|
||||
done();
|
||||
if (typeof done === 'function') done();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,25 @@
|
||||
//load local dependencies
|
||||
const EventEmitter = require("events");
|
||||
const {logger,configUtils,configManager, MeasurementContainer, interpolation , childRegistrationUtils} = require('generalFunctions');
|
||||
const {logger,configUtils,configManager, MeasurementContainer, interpolation , childRegistrationUtils, convert} = require('generalFunctions');
|
||||
|
||||
const CANONICAL_UNITS = Object.freeze({
|
||||
pressure: 'Pa',
|
||||
flow: 'm3/s',
|
||||
power: 'W',
|
||||
temperature: 'K',
|
||||
});
|
||||
|
||||
const DEFAULT_IO_UNITS = Object.freeze({
|
||||
pressure: 'mbar',
|
||||
flow: 'm3/h',
|
||||
power: 'kW',
|
||||
temperature: 'C',
|
||||
});
|
||||
|
||||
/**
|
||||
* Machine group controller domain model.
|
||||
* Aggregates multiple rotating machines and coordinates group-level optimization/control.
|
||||
*/
|
||||
class MachineGroup {
|
||||
constructor(machineGroupConfig = {}) {
|
||||
|
||||
@@ -10,6 +28,12 @@ class MachineGroup {
|
||||
this.defaultConfig = this.configManager.getConfig('machineGroupControl'); // Load default config for rotating machine ( use software type name ? )
|
||||
this.configUtils = new configUtils(this.defaultConfig);// this will handle the config endpoints so we can load them dynamically
|
||||
this.config = this.configUtils.initConfig(machineGroupConfig); // verify and set the config for the machine group
|
||||
this.unitPolicy = this._buildUnitPolicy(this.config);
|
||||
this.config = this.configUtils.updateConfig(this.config, {
|
||||
general: {
|
||||
unit: this.unitPolicy.output.flow,
|
||||
}
|
||||
});
|
||||
|
||||
// Init after config is set
|
||||
this.logger = new logger(this.config.general.logging.enabled,this.config.general.logging.logLevel, this.config.general.name);
|
||||
@@ -19,11 +43,22 @@ class MachineGroup {
|
||||
autoConvert: true,
|
||||
windowSize: 50,
|
||||
defaultUnits: {
|
||||
pressure: 'mbar',
|
||||
flow: 'l/s',
|
||||
power: 'kW',
|
||||
temperature: 'C'
|
||||
}
|
||||
pressure: this.unitPolicy.output.pressure,
|
||||
flow: this.unitPolicy.output.flow,
|
||||
power: this.unitPolicy.output.power,
|
||||
temperature: this.unitPolicy.output.temperature
|
||||
},
|
||||
preferredUnits: {
|
||||
pressure: this.unitPolicy.output.pressure,
|
||||
flow: this.unitPolicy.output.flow,
|
||||
power: this.unitPolicy.output.power,
|
||||
temperature: this.unitPolicy.output.temperature
|
||||
},
|
||||
canonicalUnits: this.unitPolicy.canonical,
|
||||
storeCanonical: true,
|
||||
strictUnitValidation: true,
|
||||
throwOnInvalidUnit: true,
|
||||
requireUnitForTypes: ['pressure', 'flow', 'power', 'temperature']
|
||||
});
|
||||
|
||||
this.interpolation = new interpolation();
|
||||
@@ -50,7 +85,8 @@ class MachineGroup {
|
||||
registerChild(child,softwareType) {
|
||||
this.logger.debug('Setting up childs specific for this class');
|
||||
|
||||
const position = child.config.general.positionVsParent;
|
||||
// Prefer functionality-scoped position metadata; keep general fallback for legacy nodes.
|
||||
const position = child.config?.functionality?.positionVsParent || child.config?.general?.positionVsParent;
|
||||
|
||||
if(softwareType == "machine"){
|
||||
// Check if the machine is already registered
|
||||
@@ -160,8 +196,8 @@ class MachineGroup {
|
||||
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 = this._readChildMeasurement(machine, "flow", "predicted", "atequipment", this.unitPolicy.canonical.flow) || 0;
|
||||
const actPower = this._readChildMeasurement(machine, "power", "predicted", "atequipment", this.unitPolicy.canonical.power) || 0;
|
||||
|
||||
this.logger.debug(`Machine ${machine.config.general.id} - Min Flow: ${minFlow}, Max Flow: ${maxFlow}, Min Power: ${minPower}, Max Power: ${maxPower}, NCog: ${machine.NCog}`);
|
||||
|
||||
@@ -210,13 +246,13 @@ class MachineGroup {
|
||||
}
|
||||
|
||||
handlePressureChange() {
|
||||
this.logger.info("---------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>Pressure change detected.");
|
||||
this.logger.debug("Pressure change detected.");
|
||||
// Recalculate totals
|
||||
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._writeMeasurement("flow", "predicted", "atequipment", flow.act, this.unitPolicy.canonical.flow);
|
||||
this._writeMeasurement("power", "predicted", "atequipment", power.act, this.unitPolicy.canonical.power);
|
||||
|
||||
const { maxEfficiency, lowestEfficiency } = this.calcGroupEfficiency(this.machines);
|
||||
const efficiency = this.measurements.type("efficiency").variant("predicted").position("atequipment").getCurrentValue();
|
||||
@@ -255,11 +291,13 @@ class MachineGroup {
|
||||
//add special cases
|
||||
if( state === "operational" && ( mode == "virtualControl" || mode === "fysicalControl") ){
|
||||
let flow = 0;
|
||||
if(machine.measurements.type("flow").variant("measured").position("downstream").getCurrentValue()){
|
||||
flow = machine.measurements.type("flow").variant("measured").position("downstream").getCurrentValue();
|
||||
const measuredFlow = this._readChildMeasurement(machine, "flow", "measured", "downstream", this.unitPolicy.canonical.flow);
|
||||
const predictedFlow = this._readChildMeasurement(machine, "flow", "predicted", "atequipment", this.unitPolicy.canonical.flow);
|
||||
if (Number.isFinite(measuredFlow) && measuredFlow !== 0) {
|
||||
flow = measuredFlow;
|
||||
}
|
||||
else if(machine.measurements.type("flow").variant("predicted").position("atequipment").getCurrentValue()){
|
||||
flow = machine.measurements.type("flow").variant("predicted").position("atequipment").getCurrentValue();
|
||||
else if (Number.isFinite(predictedFlow) && predictedFlow !== 0) {
|
||||
flow = predictedFlow;
|
||||
}
|
||||
else{
|
||||
this.logger.error("Dont perform calculation at all seeing that there is a machine working but we dont know the flow its producing");
|
||||
@@ -611,8 +649,8 @@ class MachineGroup {
|
||||
// this is to ensure a correct evaluation of the flow and power consumption
|
||||
const pressures = Object.entries(this.machines).map(([machineId, machine]) => {
|
||||
return {
|
||||
downstream: machine.measurements.type("pressure").variant("measured").position("downstream").getCurrentValue(),
|
||||
upstream: machine.measurements.type("pressure").variant("measured").position("upstream").getCurrentValue()
|
||||
downstream: this._readChildMeasurement(machine, "pressure", "measured", "downstream", this.unitPolicy.canonical.pressure),
|
||||
upstream: this._readChildMeasurement(machine, "pressure", "measured", "upstream", this.unitPolicy.canonical.pressure)
|
||||
};
|
||||
});
|
||||
|
||||
@@ -626,8 +664,8 @@ class MachineGroup {
|
||||
if(machine.state.getCurrentState() !== "operational" && machine.state.getCurrentState() !== "accelerating" && machine.state.getCurrentState() !== "decelerating"){
|
||||
|
||||
//Equilize pressures over all machines so we can make a proper calculation
|
||||
machine.measurements.type("pressure").variant("measured").position("downstream").value(maxDownstream);
|
||||
machine.measurements.type("pressure").variant("measured").position("upstream").value(minUpstream);
|
||||
this._writeChildMeasurement(machine, "pressure", "measured", "downstream", maxDownstream, this.unitPolicy.canonical.pressure);
|
||||
this._writeChildMeasurement(machine, "pressure", "measured", "upstream", minUpstream, this.unitPolicy.canonical.pressure);
|
||||
|
||||
// after updating the measurement directly we need to force the update of the value OLIFANT this is not so clear now in the code
|
||||
// we need to find a better way to do this but for now it works
|
||||
@@ -690,8 +728,8 @@ 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._writeMeasurement("power", "predicted", "atequipment", bestResult.bestPower, this.unitPolicy.canonical.power);
|
||||
this._writeMeasurement("flow", "predicted", "atequipment", bestResult.bestFlow, this.unitPolicy.canonical.flow);
|
||||
this.measurements.type("efficiency").variant("predicted").position("atequipment").value(bestResult.bestFlow / bestResult.bestPower);
|
||||
this.measurements.type("Ncog").variant("predicted").position("atequipment").value(bestResult.bestCog);
|
||||
|
||||
@@ -731,8 +769,8 @@ class MachineGroup {
|
||||
// Get current pressures from all machines
|
||||
const pressures = Object.entries(this.machines).map(([machineId, machine]) => {
|
||||
return {
|
||||
downstream: machine.measurements.type("pressure").variant("measured").position("downstream").getCurrentValue(),
|
||||
upstream: machine.measurements.type("pressure").variant("measured").position("upstream").getCurrentValue()
|
||||
downstream: this._readChildMeasurement(machine, "pressure", "measured", "downstream", this.unitPolicy.canonical.pressure),
|
||||
upstream: this._readChildMeasurement(machine, "pressure", "measured", "upstream", this.unitPolicy.canonical.pressure)
|
||||
};
|
||||
});
|
||||
|
||||
@@ -743,8 +781,8 @@ class MachineGroup {
|
||||
// Set consistent pressures across machines
|
||||
Object.entries(this.machines).forEach(([machineId, machine]) => {
|
||||
if(!this.isMachineActive(machineId)){
|
||||
machine.measurements.type("pressure").variant("measured").position("downstream").value(maxDownstream);
|
||||
machine.measurements.type("pressure").variant("measured").position("upstream").value(minUpstream);
|
||||
this._writeChildMeasurement(machine, "pressure", "measured", "downstream", maxDownstream, this.unitPolicy.canonical.pressure);
|
||||
this._writeChildMeasurement(machine, "pressure", "measured", "upstream", minUpstream, this.unitPolicy.canonical.pressure);
|
||||
// Update the measured pressure value
|
||||
const pressure = machine.getMeasuredPressure();
|
||||
this.logger.debug(`Setting pressure for machine ${machineId} to ${pressure}`);
|
||||
@@ -920,8 +958,8 @@ 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._writeMeasurement("power", "predicted", "atequipment", totalPower, this.unitPolicy.canonical.power);
|
||||
this._writeMeasurement("flow", "predicted", "atequipment", totalFlow, this.unitPolicy.canonical.flow);
|
||||
this.measurements.type("efficiency").variant("predicted").position("atequipment").value(totalFlow / totalPower);
|
||||
this.measurements.type("Ncog").variant("predicted").position("atequipment").value(totalCog);
|
||||
|
||||
@@ -1035,8 +1073,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 = this._readChildMeasurement(machine, "power", "predicted", "atequipment", this.unitPolicy.canonical.power);
|
||||
const flowValue = this._readChildMeasurement(machine, "flow", "predicted", "atequipment", this.unitPolicy.canonical.flow);
|
||||
|
||||
if (powerValue !== null) {
|
||||
totalPower.push(powerValue);
|
||||
@@ -1046,8 +1084,8 @@ 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._writeMeasurement("power", "predicted", "atequipment", totalPower.reduce((a, b) => a + b, 0), this.unitPolicy.canonical.power);
|
||||
this._writeMeasurement("flow", "predicted", "atequipment", totalFlow.reduce((a, b) => a + b, 0), this.unitPolicy.canonical.flow);
|
||||
|
||||
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));
|
||||
@@ -1158,6 +1196,106 @@ class MachineGroup {
|
||||
}));
|
||||
}
|
||||
|
||||
_buildUnitPolicy(config = {}) {
|
||||
const flowUnit = this._resolveUnitOrFallback(
|
||||
config?.general?.unit,
|
||||
'volumeFlowRate',
|
||||
DEFAULT_IO_UNITS.flow
|
||||
);
|
||||
const pressureUnit = this._resolveUnitOrFallback(
|
||||
config?.general?.pressureUnit,
|
||||
'pressure',
|
||||
DEFAULT_IO_UNITS.pressure
|
||||
);
|
||||
const powerUnit = this._resolveUnitOrFallback(
|
||||
config?.general?.powerUnit,
|
||||
'power',
|
||||
DEFAULT_IO_UNITS.power
|
||||
);
|
||||
|
||||
return {
|
||||
canonical: { ...CANONICAL_UNITS },
|
||||
output: {
|
||||
flow: flowUnit,
|
||||
pressure: pressureUnit,
|
||||
power: powerUnit,
|
||||
temperature: DEFAULT_IO_UNITS.temperature,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
_resolveUnitOrFallback(candidate, expectedMeasure, fallbackUnit) {
|
||||
const fallback = String(fallbackUnit || '').trim();
|
||||
const raw = typeof candidate === 'string' ? candidate.trim() : '';
|
||||
if (!raw) {
|
||||
return fallback;
|
||||
}
|
||||
try {
|
||||
const desc = convert().describe(raw);
|
||||
if (expectedMeasure && desc.measure !== expectedMeasure) {
|
||||
throw new Error(`expected '${expectedMeasure}', got '${desc.measure}'`);
|
||||
}
|
||||
return raw;
|
||||
} catch (error) {
|
||||
this.logger?.warn?.(`Invalid unit '${raw}' (${error.message}); falling back to '${fallback}'.`);
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
_outputUnitForType(type) {
|
||||
switch (String(type || '').toLowerCase()) {
|
||||
case 'flow':
|
||||
return this.unitPolicy.output.flow;
|
||||
case 'power':
|
||||
return this.unitPolicy.output.power;
|
||||
case 'pressure':
|
||||
return this.unitPolicy.output.pressure;
|
||||
case 'temperature':
|
||||
return this.unitPolicy.output.temperature;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
_readMeasurement(type, variant, position, unit = null) {
|
||||
const requestedUnit = unit || this._outputUnitForType(type);
|
||||
return this.measurements
|
||||
.type(type)
|
||||
.variant(variant)
|
||||
.position(position)
|
||||
.getCurrentValue(requestedUnit || undefined);
|
||||
}
|
||||
|
||||
_writeMeasurement(type, variant, position, value, unit = null, timestamp = Date.now()) {
|
||||
if (!Number.isFinite(value)) {
|
||||
return;
|
||||
}
|
||||
this.measurements
|
||||
.type(type)
|
||||
.variant(variant)
|
||||
.position(position)
|
||||
.value(value, timestamp, unit || undefined);
|
||||
}
|
||||
|
||||
_readChildMeasurement(machine, type, variant, position, unit = null) {
|
||||
return machine?.measurements
|
||||
?.type(type)
|
||||
?.variant(variant)
|
||||
?.position(position)
|
||||
?.getCurrentValue(unit || undefined);
|
||||
}
|
||||
|
||||
_writeChildMeasurement(machine, type, variant, position, value, unit = null, timestamp = Date.now()) {
|
||||
if (!machine?.measurements || !Number.isFinite(value)) {
|
||||
return;
|
||||
}
|
||||
machine.measurements
|
||||
.type(type)
|
||||
.variant(variant)
|
||||
.position(position)
|
||||
.value(value, timestamp, unit || undefined);
|
||||
}
|
||||
|
||||
setMode(mode) {
|
||||
this.mode = mode;
|
||||
}
|
||||
@@ -1168,12 +1306,12 @@ class MachineGroup {
|
||||
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 atEquipmentVal = this.measurements.type(type).variant(variant).position("atequipment").getCurrentValue();
|
||||
const upstreamVal = this.measurements.type(type).variant(variant).position("upstream").getCurrentValue();
|
||||
Object.entries(this.measurements.measurements || {}).forEach(([type, variants]) => {
|
||||
Object.keys(variants || {}).forEach((variant) => {
|
||||
const unit = this._outputUnitForType(type);
|
||||
const downstreamVal = this._readMeasurement(type, variant, "downstream", unit);
|
||||
const atEquipmentVal = this._readMeasurement(type, variant, "atequipment", unit);
|
||||
const upstreamVal = this._readMeasurement(type, variant, "upstream", unit);
|
||||
|
||||
if (downstreamVal != null) {
|
||||
output[`downstream_${variant}_${type}`] = downstreamVal;
|
||||
@@ -1185,8 +1323,13 @@ class MachineGroup {
|
||||
output[`atequipment${variant}_${type}`] = atEquipmentVal;
|
||||
}
|
||||
if (downstreamVal != null && upstreamVal != null) {
|
||||
const diffVal = this.measurements.type(type).variant(variant).difference().value;
|
||||
output[`differential_${variant}_${type}`] = diffVal;
|
||||
const diff = this.measurements
|
||||
.type(type)
|
||||
.variant(variant)
|
||||
.difference({ from: 'downstream', to: 'upstream', unit });
|
||||
if (diff?.value != null) {
|
||||
output[`differential_${variant}_${type}`] = diff.value;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1396,6 +1539,8 @@ async function makeMachines(){
|
||||
}
|
||||
|
||||
|
||||
if (require.main === module) {
|
||||
makeMachines();
|
||||
}
|
||||
|
||||
//*/
|
||||
|
||||
12
test/README.md
Normal file
12
test/README.md
Normal file
@@ -0,0 +1,12 @@
|
||||
# machineGroupControl Test Suite Layout
|
||||
|
||||
Required EVOLV layout:
|
||||
- basic/
|
||||
- integration/
|
||||
- edge/
|
||||
- helpers/
|
||||
|
||||
Baseline structure tests:
|
||||
- basic/structure-module-load.basic.test.js
|
||||
- integration/structure-examples.integration.test.js
|
||||
- edge/structure-examples-node-type.edge.test.js
|
||||
0
test/basic/.gitkeep
Normal file
0
test/basic/.gitkeep
Normal file
8
test/basic/structure-module-load.basic.test.js
Normal file
8
test/basic/structure-module-load.basic.test.js
Normal file
@@ -0,0 +1,8 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
test('machineGroupControl module load smoke', () => {
|
||||
assert.doesNotThrow(() => {
|
||||
require('../../mgc.js');
|
||||
});
|
||||
});
|
||||
0
test/edge/.gitkeep
Normal file
0
test/edge/.gitkeep
Normal file
11
test/edge/structure-examples-node-type.edge.test.js
Normal file
11
test/edge/structure-examples-node-type.edge.test.js
Normal file
@@ -0,0 +1,11 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const flow = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../../examples/basic.flow.json'), 'utf8'));
|
||||
|
||||
test('basic example includes node type machineGroupControl', () => {
|
||||
const count = flow.filter((n) => n && n.type === 'machineGroupControl').length;
|
||||
assert.equal(count >= 1, true);
|
||||
});
|
||||
0
test/helpers/.gitkeep
Normal file
0
test/helpers/.gitkeep
Normal file
0
test/integration/.gitkeep
Normal file
0
test/integration/.gitkeep
Normal file
23
test/integration/structure-examples.integration.test.js
Normal file
23
test/integration/structure-examples.integration.test.js
Normal file
@@ -0,0 +1,23 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const dir = path.resolve(__dirname, '../../examples');
|
||||
|
||||
function loadJson(file) {
|
||||
return JSON.parse(fs.readFileSync(path.join(dir, file), 'utf8'));
|
||||
}
|
||||
|
||||
test('examples package exists for machineGroupControl', () => {
|
||||
for (const file of ['README.md', 'basic.flow.json', 'integration.flow.json', 'edge.flow.json']) {
|
||||
assert.equal(fs.existsSync(path.join(dir, file)), true, file + ' missing');
|
||||
}
|
||||
});
|
||||
|
||||
test('example flows are parseable arrays for machineGroupControl', () => {
|
||||
for (const file of ['basic.flow.json', 'integration.flow.json', 'edge.flow.json']) {
|
||||
const parsed = loadJson(file);
|
||||
assert.equal(Array.isArray(parsed), true);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user