This commit is contained in:
znetsixe
2026-03-11 11:13:11 +01:00
parent cbe868a148
commit 5e1f3946bf
5 changed files with 1013 additions and 282 deletions

View File

@@ -1,4 +1,4 @@
const { outputUtils, configManager } = require("generalFunctions");
const { outputUtils, configManager, convert } = require("generalFunctions");
const Specific = require("./specificClass");
class nodeClass {
@@ -18,6 +18,7 @@ class nodeClass {
// Load default & UI config
this._loadConfig(uiConfig, this.node);
this._reconcileIntervalMs = this._resolveReconcileIntervalMs(uiConfig);
// Instantiate core Measurement class
this._setupSpecificClass();
@@ -37,13 +38,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,29 +59,44 @@ 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;
}
}
_resolveReconcileIntervalMs(uiConfig) {
const raw = Number(
uiConfig?.reconcileIntervalSeconds
?? uiConfig?.reconcileIntervalSec
?? uiConfig?.reconcileEverySeconds
?? 1
);
const sec = Number.isFinite(raw) && raw > 0 ? raw : 1;
return Math.max(100, Math.round(sec * 1000));
}
_updateNodeStatus() {
const vg = this.source;
const mode = vg.mode;
const scaling = vg.scaling;
const totalFlow =
Math.round(
vg.measurements
.type("flow")
.variant("measured")
.position("downstream")
.getCurrentValue() * 1
) / 1;
// Calculate total capacity based on available valves
const availableValves = Object.values(vg.valves).filter((valve) => {
const state = valve.state.getCurrentState();
const mode = valve.currentMode;
return !(
state === "off" ||
state === "maintenance" ||
mode === "maintenance"
);
});
const mode = vg.currentMode;
const flowUnit = vg?.unitPolicy?.output?.flow || this.config.general.unit || "m3/h";
const measuredFlow = vg.measurements.type("flow").variant("measured").position("atEquipment").getCurrentValue(flowUnit);
const predictedFlow = vg.measurements.type("flow").variant("predicted").position("atEquipment").getCurrentValue(flowUnit);
const totalFlowRaw = Number.isFinite(measuredFlow) ? measuredFlow : predictedFlow;
const totalFlow = Number.isFinite(totalFlowRaw) ? Math.round(totalFlowRaw) : 0;
const availableValves = Array.isArray(vg.getAvailableValves?.()) ? vg.getAvailableValves() : [];
// const totalCapacity = Math.round(vg.dynamicTotals.flow.max * 1) / 1; ADD LATER?
@@ -91,7 +108,7 @@ class nodeClass {
// Generate status text in a single line
const text = ` ${mode} | 💨=${totalFlow} | ${status}`;
const text = `${mode} | flow=${totalFlow} ${flowUnit} | ${status}`;
return {
fill: availableValves.length > 0 ? "green" : "red",
@@ -139,7 +156,7 @@ class nodeClass {
*/
_startTickLoop() {
setTimeout(() => {
this._tickInterval = setInterval(() => this._tick(), 1000);
this._tickInterval = setInterval(() => this._tick(), this._reconcileIntervalMs);
// Update node status on nodered screen every second ( this is not the best way to do this, but it works for now)
this._statusInterval = setInterval(() => {
const status = this._updateNodeStatus();
@@ -152,6 +169,9 @@ class nodeClass {
* Execute a single tick: update measurement, format and send outputs.
*/
_tick() {
if (typeof this.source?.calcValveFlows === 'function') {
this.source.calcValveFlows();
}
const raw = this.source.getOutput();
const processMsg = this._output.formatMsg(raw, this.config, "process");
const influxMsg = this._output.formatMsg(raw, this.config, "influxdb");
@@ -184,14 +204,39 @@ class nodeClass {
case 'setMode':
vg.setMode(msg.payload);
break;
case 'setReconcileInterval': {
const nextSec = Number(msg.payload);
if (!Number.isFinite(nextSec) || nextSec <= 0) {
vg.logger.warn(`Invalid reconcile interval payload '${msg.payload}'. Expected seconds > 0.`);
break;
}
this._reconcileIntervalMs = Math.max(100, Math.round(nextSec * 1000));
clearInterval(this._tickInterval);
this._tickInterval = setInterval(() => this._tick(), this._reconcileIntervalMs);
vg.logger.info(`Flow reconciliation interval updated to ${nextSec}s (${this._reconcileIntervalMs}ms).`);
break;
}
case 'execSequence': {
const { source: seqSource, action: seqAction, parameter } = msg.payload;
vg.handleInput(seqSource, seqAction, parameter);
break;
}
case 'totalFlowChange': {
const { source: tfcSource, action: tfcAction, q} = msg.payload;
vg.handleInput(tfcSource, tfcAction, Number(q));
const payload = msg.payload || {};
if (payload && typeof payload === "object" && Object.prototype.hasOwnProperty.call(payload, "source")) {
const tfcSource = payload.source || "parent";
const tfcAction = payload.action || "totalFlowChange";
vg.handleInput(tfcSource, tfcAction, payload);
} else {
vg.handleInput("parent", "totalFlowChange", payload);
}
break;
}
case 'emergencystop':
case 'emergencyStop': {
const payload = msg.payload || {};
const esSource = payload.source || "parent";
vg.handleInput(esSource, "emergencystop");
break;
}
default:
@@ -213,6 +258,7 @@ class nodeClass {
this.node.on("close", (done) => {
clearInterval(this._tickInterval);
clearInterval(this._statusInterval);
this.source?.destroy?.();
if (typeof done === 'function') done();
});
}