Compare commits

...

10 Commits

Author SHA1 Message Date
znetsixe
bd67b22197 style: palette swatch → (domain-hue redesign 2026-05-21)
Sidebar swatch now follows function family rather than S88 level, so the
palette is visually identifiable instead of monochromatically blue. Editor-group
rectangles in flow.json still follow S88 — only the registerType color changed.
Full table + rationale: superproject .claude/rules/node-red-flow-layout.md §10.0
and .claude/refactor/OPEN_QUESTIONS.md (2026-05-21 entry).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 15:05:55 +02:00
znetsixe
91f98414d1 fix(commands): point set.mode description at the schema enum
Old description said "auto / manual" but the schema declares four modes
(auto, virtualControl, fysicalControl, maintenance). New description
enumerates the allowed values and refers readers to the schema as the
source of truth. wiki-gen regenerated Reference-Contracts.md to match.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 16:05:40 +02:00
znetsixe
d81aedc9bc docs(wiki): regenerate topic-contract AUTOGEN block via wiki-gen
Replaces the agent-written placeholder inside Reference-Contracts.md with
the authoritative table generated from src/commands/index.js. Both the
BEGIN and END markers are normalized to the canonical form used by
`@evolv/wiki-gen`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 10:11:51 +02:00
znetsixe
9552e4fba9 docs(wiki): full 5-page wiki matching the rotatingMachine reference format
Replaces the prior stub/partial wiki with a Home + Reference-{Architecture,
Contracts,Examples,Limitations} + _Sidebar structure. Topic-contract and
data-model sections wrapped in AUTOGEN markers for the future wiki-gen tool.
Source-vs-spec contradictions surfaced and flagged inline (not silently
fixed). Pending-review notes mark sections that need a full node review.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:42:12 +02:00
znetsixe
b20a57360d docs: Folder & File Layout section + flag vgc.{js,html} naming drift
Entry/HTML files should be valveGroupControl.{js,html} to match the folder
name. Rename when the file is next touched. Full rule:
.claude/rules/node-architecture.md in the EVOLV superproject.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 21:30:43 +02:00
znetsixe
618ad27e03 docs(wiki): rewrite Home.md to 14-section visual-first template
Fixes section ordering (11-8-9-10 scramble + duplicate §11), updates
banner hash to ef34c82, corrects §2 diagram (set.position → updateFlow,
evt.deltaPChange → positionChange/deltaPChange), upgrades capability
matrix to ⚠️ for set.position and cascaded VGC, rewrites §9 to reflect
the actual editor form fields (name/format/position/logger), and
replaces the orphaned "Distribution loop" duplicate-§11 with a proper
§10. AUTOGEN markers verified intact via npm run wiki:all.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 21:05:17 +02:00
znetsixe
ef34c82f13 P11.6 wiki regen + Phase 10 private-test rewrites where applicable
For all 11 nodes with auto-gen markers: wiki/Home.md sections 5 (topic
contract) and 9 (data model) regenerated via npm run wiki:all. New
Unit column shows '<measure> (default <unit>)' for declared topics,
'—' otherwise. Effect column now uses descriptor.description (P11.2
field) overriding the generic per-prefix fallback.

For rotatingMachine + reactor: Phase 10 test rewrites — 3 + 8 files
moved off private nodeClass internals (_attachInputHandler, _commands,
_pendingExtras, _registerChild, _tick, etc.) to the public
BaseNodeAdapter surface (node.handlers.input, node.source.*).
+6 / +7 net new tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 19:44:15 +02:00
znetsixe
778b2e0c79 P11.5 + B2.1/B2.2: per-command units + description (where applicable)
Adds  to scalar setters whose payloads are
plain numbers OR {value, unit}. Skipped where payload is compound or
mode-dependent (control-%, {F, C: [...]}, etc.) — documented inline.
Every command gains a description field for wikiGen consumption.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 17:41:17 +02:00
znetsixe
c44d5959ad P9.3: wiki/Home.md following 14-section visual-first template + wiki:* scripts
Auto-generated topic-contract + data-model sections via shared wikiGen
script. Hand-written Mermaid diagrams for position-in-platform, code
map, child registration, lifecycle, configuration, state chart (where
applicable).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 15:17:39 +02:00
znetsixe
e02cd1a7a7 P6: convert valveGroupControl to BaseDomain + BaseNodeAdapter + concern split
Refactor of valveGroupControl to use the platform infrastructure (BaseDomain, BaseNodeAdapter,
ChildRouter, commandRegistry, statusBadge). Extracts concerns into
focused modules per .claude/refactor/MODULE_SPLIT.md generic template.
Tests stay green; CONTRACT.md generated; legacy aliases preserved.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 22:09:24 +02:00
18 changed files with 1757 additions and 916 deletions

View File

@@ -21,3 +21,28 @@ Key points for this node:
- Stack same-level siblings vertically. - Stack same-level siblings vertically.
- Parent/children sit on adjacent lanes (children one lane left, parent one lane right). - Parent/children sit on adjacent lanes (children one lane left, parent one lane right).
- Wrap in a Node-RED group box coloured `#50a8d9` (Unit). - Wrap in a Node-RED group box coloured `#50a8d9` (Unit).
## Folder & File Layout
Every per-node file MUST use the folder name (`valveGroupControl`) **exactly**, case-sensitive. Full rule: [`.claude/rules/node-architecture.md`](https://gitea.wbd-rd.nl/RnD/EVOLV/src/branch/development/.claude/rules/node-architecture.md) in the EVOLV superproject.
| Path | Required name |
|---|---|
| Entry file | `valveGroupControl.js` |
| Editor HTML | `valveGroupControl.html` |
| Node adapter | `src/nodeClass.js` |
| Domain logic | `src/specificClass.js` |
| Editor JS modules | `src/editor/*.js` (extract when inline editor JS exceeds ~50 lines) |
| Tests | `test/{basic,integration,edge}/*.test.js` |
| Example flows | `examples/*.flow.json` |
> ⚠️ **Legacy naming drift in this repo** — to be renamed when the file is next touched:
>
> | Path | Currently | Should be |
> |---|---|---|
> | Entry file | `vgc.js` | `valveGroupControl.js` |
> | Editor HTML | `vgc.html` | `valveGroupControl.html` |
>
> Renames require updating: the file itself, `package.json#node-red.nodes`, any `require()` / `import` paths, and superproject submodule references in one commit.
When adding new files, read the rule above first to avoid drift.

67
CONTRACT.md Normal file
View File

@@ -0,0 +1,67 @@
# valveGroupControl — Contract
Hand-maintained for Phase 6; the `## Inputs` table is generated from
`src/commands/index.js` (see Phase 9 generator). Keep ≤ 80 lines.
## Inputs (msg.topic on Port 0)
| Canonical | Aliases (deprecated) | Payload | Effect |
|---|---|---|---|
| `set.mode` | `setMode` | `string` — one of `auto`, `virtualControl`, `fysicalControl`, `maintenance` | Switches the control strategy via `source.setMode(payload)`. |
| `set.position` | `setpoint` | `any` | Reserved for future per-valve positional override; currently a debug-logged no-op pending Phase 7. |
| `child.register` | `registerChild` | `string` — the child node's Node-RED id | Resolves the child via `RED.nodes.getNode` and registers it through `childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent)`. |
| `cmd.execSequence` | `execSequence` | `{ source, action, parameter }` | Forwards to `source.handleInput(source, action, parameter)`. |
| `data.totalFlow` | `totalFlowChange` | numeric, `{ value, position?, variant?, unit? }`, or `{ source, action, ... }` | Updates total measured/predicted flow at the configured position; drives `calcValveFlows` to re-distribute across valves. |
| `cmd.emergencyStop` | `emergencyStop`, `emergencystop` | optional `{ source }` | Runs the `emergencystop` sequence via `handleInput`. |
| `set.reconcileInterval` | `setReconcileInterval` | numeric — seconds (> 0) | Re-tunes the periodic flow-reconciliation interval. Min clamp 100 ms. |
Aliases log a one-time deprecation warning the first time they fire.
## Outputs (msg.topic on Port 0/1/2)
- **Port 0 (process):** `msg.topic = config.general.name`. Payload built by
`outputUtils.formatMsg(..., 'process')` from `getOutput()` — delta-compressed
(only changed fields are emitted). Output keys follow
`<position>_<variant>_<type>` plus `mode` and `maxDeltaP`.
- **Port 1 (InfluxDB telemetry):** same shape as Port 0, formatted with the
`'influxdb'` formatter.
- **Port 2 (registration):** at startup the node sends one
`{ topic: 'child.register', payload: <node.id>, positionVsParent }`
to the upstream parent.
## Events emitted by `source.emitter` / `source.measurements.emitter`
- `output-changed` (`source.emitter`) — public output state shifted; the
adapter listens and pushes Ports 0/1.
- `fluidContractChange` (`source.emitter`) — group-level fluid contract
(status / serviceType / sourceCount) changed. Parents (e.g. an upstream
valve registering this VGC as its parent) subscribe to react.
- `reconcileIntervalChange` (`source.emitter`) — emitted by
`setReconcileIntervalSeconds`; the adapter restarts the tick loop.
- `flow.predicted.atequipment` (`source.measurements.emitter`) — total
predicted group flow (sum of per-valve assigned flows).
- `pressure.predicted.deltaMax` (`source.measurements.emitter`) — max
delta-P across registered valves.
The exact set is data-driven by which sources/valves register and what
they publish; downstream consumers subscribe by event name.
## Children registered by this node
valveGroupControl accepts two child classes through the
`childRegistrationUtils` handshake:
- `valve` — an individual valve. Stored in `source.valves[id]`. VGC binds
to the child's `positionChange` (via `child.state.emitter`) and
`deltaPChange` (via `child.emitter`) events to re-distribute flow and
re-compute group max delta-P.
- `machine` / `rotatingmachine` / `machinegroup` / `machinegroupcontrol` /
`pumpingstation` / `valvegroupcontrol` — an upstream **source**. Stored
in `source.sources[id]`. VGC subscribes to the source's
`flow.predicted.*` / `flow.measured.*` events to drive `updateFlow`,
and reads the child's `getFluidContract()` (if present) plus
`fluidContractChange` events to aggregate the group's upstream service
type (`getFluidContract()` exposes the resolved view).
Position labels accepted from children are `upstream`, `downstream`,
`atEquipment` (and case variants — normalised internally).

View File

@@ -4,7 +4,10 @@
"description": "Valve group control module", "description": "Valve group control module",
"main": "valveGroupControl.js", "main": "valveGroupControl.js",
"scripts": { "scripts": {
"test": "node --test test/basic/*.test.js test/integration/*.test.js test/edge/*.test.js" "test": "node --test test/basic/*.test.js test/integration/*.test.js test/edge/*.test.js",
"wiki:contract": "node ../generalFunctions/scripts/wikiGen.js contract ./src/commands/index.js --write ./wiki/Home.md",
"wiki:datamodel": "node ../generalFunctions/scripts/wikiGen.js datamodel ./src/specificClass.js --write ./wiki/Home.md",
"wiki:all": "npm run wiki:contract && npm run wiki:datamodel"
}, },
"repository": { "repository": {
"type": "git", "type": "git",

65
src/commands/handlers.js Normal file
View File

@@ -0,0 +1,65 @@
'use strict';
// Handler functions for valveGroupControl commands. Pure functions:
// source = domain (specificClass) instance
// msg = Node-RED input message
// ctx = { node, RED, send, logger } — provided by BaseNodeAdapter
function _logger(source, ctx) {
return ctx?.logger || source?.logger || null;
}
exports.setMode = (source, msg) => {
source.setMode(msg.payload);
};
exports.setPosition = (source, msg) => {
// Reserved for future per-valve positional override; currently a no-op
// pending Phase 7 topic standardisation of valve setpoint payloads.
_logger(source, null)?.debug?.(`set.position received (no-op): ${JSON.stringify(msg.payload ?? null)}`);
};
exports.registerChild = (source, msg, ctx) => {
const log = _logger(source, ctx);
const childId = msg.payload;
const childObj = ctx?.RED?.nodes?.getNode?.(childId);
if (!childObj || !childObj.source) {
log?.warn?.(`registerChild: child '${childId}' not found or has no .source`);
return;
}
source.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent);
};
exports.execSequence = async (source, msg) => {
const { source: seqSource, action: seqAction, parameter } = msg.payload || {};
await source.handleInput(seqSource, seqAction, parameter);
};
exports.totalFlowChange = async (source, msg) => {
const payload = msg.payload || {};
if (payload && typeof payload === 'object' && Object.prototype.hasOwnProperty.call(payload, 'source')) {
const src = payload.source || 'parent';
const action = payload.action || 'totalFlowChange';
await source.handleInput(src, action, payload);
return;
}
await source.handleInput('parent', 'totalFlowChange', payload);
};
exports.emergencyStop = async (source, msg) => {
const payload = msg.payload || {};
const src = payload.source || 'parent';
await source.handleInput(src, 'emergencystop');
};
exports.setReconcileInterval = (source, msg) => {
const log = _logger(source, null);
const nextSec = Number(msg.payload);
if (!Number.isFinite(nextSec) || nextSec <= 0) {
log?.warn?.(`Invalid reconcile interval payload '${msg.payload}'. Expected seconds > 0.`);
return;
}
if (typeof source.setReconcileIntervalSeconds === 'function') {
source.setReconcileIntervalSeconds(nextSec);
}
};

63
src/commands/index.js Normal file
View File

@@ -0,0 +1,63 @@
'use strict';
// valveGroupControl command registry. Consumed by BaseNodeAdapter via
// `static commands = require('./commands')`. Canonical names follow
// CONTRACTS.md §1; legacy names live in `aliases` and emit a one-time
// deprecation warning at runtime.
const handlers = require('./handlers');
module.exports = [
{
topic: 'set.mode',
aliases: ['setMode'],
payloadSchema: { type: 'string' },
description: 'Switch the operating mode. Allowed: `auto`, `virtualControl`, `fysicalControl`, `maintenance` (schema-validated in `valveGroupControl.json` → `mode.current`).',
handler: handlers.setMode,
},
{
topic: 'set.position',
aliases: ['setpoint'],
payloadSchema: { type: 'any' },
// Control-percent setpoint — no `units` (no `percent` measure in convert).
description: 'Set the group-level valve position (currently a no-op pending Phase 7).',
handler: handlers.setPosition,
},
{
topic: 'child.register',
aliases: ['registerChild'],
payloadSchema: { type: 'string' },
description: 'Register a child valve with this group.',
handler: handlers.registerChild,
},
{
topic: 'cmd.execSequence',
aliases: ['execSequence'],
payloadSchema: { type: 'object' },
description: 'Run a group-wide sequence (startup / shutdown / emergencystop).',
handler: handlers.execSequence,
},
{
topic: 'data.totalFlow',
aliases: ['totalFlowChange'],
payloadSchema: { type: 'any' },
// Compound payload `{source, action, ...}` in some shapes — no scalar
// normalisation. The handler routes by payload.source.
description: 'Notify the group that the total flow setpoint has changed.',
handler: handlers.totalFlowChange,
},
{
topic: 'cmd.emergencyStop',
aliases: ['emergencyStop', 'emergencystop'],
payloadSchema: { type: 'any' },
description: 'Trigger an emergency stop across all valves in the group.',
handler: handlers.emergencyStop,
},
{
topic: 'set.reconcileInterval',
aliases: ['setReconcileInterval'],
payloadSchema: { type: 'any' },
description: 'Update the reconciliation interval (seconds).',
handler: handlers.setReconcileInterval,
},
];

View File

@@ -0,0 +1,126 @@
'use strict';
// Per-valve flow distribution. Splits the group's total flow across
// available valves proportional to Kv, then asks each valve back what
// flow it actually accepted and re-balances the residual. Also surfaces
// max delta-P across the group for downstream readers.
const DEFAULT_RECONCILIATION = Object.freeze({ maxPasses: 2, residualTolerance: 0.001 });
function isValveAvailable(valve) {
const currentState = valve?.state?.getCurrentState?.();
const mode = valve?.currentMode;
const kv = Number(valve?.kv);
return (
currentState !== 'off'
&& currentState !== 'maintenance'
&& mode !== 'maintenance'
&& Number.isFinite(kv)
&& kv > 0
);
}
function listAvailableValves(valves) {
return Object.entries(valves)
.filter(([, valve]) => isValveAvailable(valve))
.map(([id, valve]) => ({ id, valve }));
}
function _readAcceptedFlow(valve, flowUnit) {
const accepted = Number(
valve?.measurements
?.type('flow')
?.variant('predicted')
?.position('downstream')
?.getCurrentValue(flowUnit)
);
return Number.isFinite(accepted) ? accepted : null;
}
function solveFlowDistribution(totalFlow, availableEntries, reconciliation, flowUnit) {
const totalKv = availableEntries.reduce((sum, { valve }) => sum + Number(valve.kv), 0);
if (!Number.isFinite(totalKv) || totalKv <= 0) {
return { flowsById: {}, residual: Number(totalFlow) || 0, passes: 0 };
}
const targetById = Object.fromEntries(availableEntries.map(({ id }) => [id, 0]));
let residual = Number(totalFlow);
let passes = 0;
const maxPasses = Math.max(1, Number(reconciliation?.maxPasses) || DEFAULT_RECONCILIATION.maxPasses);
const tolerance = Math.max(0, Number(reconciliation?.residualTolerance) || DEFAULT_RECONCILIATION.residualTolerance);
while (passes < maxPasses && Number.isFinite(residual) && Math.abs(residual) > tolerance) {
availableEntries.forEach(({ id, valve }) => {
const share = (Number(valve.kv) / totalKv) * residual;
targetById[id] = Number(targetById[id]) + share;
valve.updateFlow('predicted', targetById[id], 'downstream', flowUnit);
});
let acceptedTotal = 0;
availableEntries.forEach(({ id, valve }) => {
const accepted = _readAcceptedFlow(valve, flowUnit);
if (Number.isFinite(accepted)) {
targetById[id] = accepted;
acceptedTotal += accepted;
return;
}
acceptedTotal += Number(targetById[id]) || 0;
});
residual = Number(totalFlow) - acceptedTotal;
passes += 1;
}
return { flowsById: targetById, residual: Number.isFinite(residual) ? residual : 0, passes };
}
function distributeFlow(vgc) {
const flowUnit = vgc.unitPolicy.output('flow');
const totalFlowMeasured = vgc._read('flow', 'measured', 'atEquipment', flowUnit);
const totalFlowPredicted = vgc._read('flow', 'predicted', 'atEquipment', flowUnit);
const totalFlow = Number.isFinite(totalFlowMeasured) ? totalFlowMeasured : totalFlowPredicted;
if (!Number.isFinite(totalFlow)) return;
const availableEntries = listAvailableValves(vgc.valves);
const availableIds = new Set(availableEntries.map((entry) => entry.id));
const totalKv = availableEntries.reduce((sum, { valve }) => sum + Number(valve.kv), 0);
if (!availableEntries.length || !Number.isFinite(totalKv) || totalKv <= 0) {
vgc.logger.warn('No available valves with valid Kv, setting assigned flow to 0.');
for (const valve of Object.values(vgc.valves)) {
valve.updateFlow('predicted', 0, 'downstream', flowUnit);
}
vgc._write('flow', 'predicted', 'atEquipment', 0, flowUnit);
vgc.lastFlowSolve = { passes: 0, residual: Number(totalFlow) || 0, targetTotal: Number(totalFlow) || 0, assignedTotal: 0 };
return;
}
const solve = solveFlowDistribution(totalFlow, availableEntries, vgc.flowReconciliation, flowUnit);
let assignedTotal = 0;
for (const [id, valve] of Object.entries(vgc.valves)) {
const flow = availableIds.has(id) ? (solve.flowsById[id] || 0) : 0;
valve.updateFlow('predicted', flow, 'downstream', flowUnit);
assignedTotal += flow;
}
vgc._write('flow', 'predicted', 'atEquipment', assignedTotal, flowUnit);
vgc.lastFlowSolve = { passes: solve.passes, residual: solve.residual, targetTotal: totalFlow, assignedTotal };
calcMaxDeltaP(vgc);
}
function calcMaxDeltaP(vgc) {
const pUnit = vgc.unitPolicy.output('pressure');
let maxDeltaP = 0;
for (const [id, valve] of Object.entries(vgc.valves)) {
const deltaP = Number(
valve.measurements.type('pressure').variant('predicted').position('delta').getCurrentValue(pUnit)
);
if (!Number.isFinite(deltaP)) continue;
vgc.logger.debug(`Delta P for valve ${id}: ${deltaP}`);
if (deltaP > maxDeltaP) maxDeltaP = deltaP;
}
vgc.maxDeltaP = maxDeltaP;
vgc._write('pressure', 'predicted', 'deltaMax', maxDeltaP, pUnit);
}
module.exports = { distributeFlow, calcMaxDeltaP, listAvailableValves, isValveAvailable, DEFAULT_RECONCILIATION };

47
src/io/output.js Normal file
View File

@@ -0,0 +1,47 @@
'use strict';
// getOutput + getStatusBadge composition for valveGroupControl. Keeps
// the orchestrator under its file-size budget.
const { statusBadge } = require('generalFunctions');
function _outputUnitForType(unitPolicy, type) {
switch (String(type || '').toLowerCase()) {
case 'flow': return unitPolicy.output('flow');
case 'pressure': return unitPolicy.output('pressure');
default: return null;
}
}
function getOutput(vgc) {
const out = {};
const measurements = vgc.measurements;
Object.entries(measurements.measurements || {}).forEach(([type, variants]) => {
Object.entries(variants || {}).forEach(([variant, positions]) => {
const unit = _outputUnitForType(vgc.unitPolicy, type);
Object.keys(positions || {}).forEach((position) => {
const value = measurements.type(type).variant(variant).position(position).getCurrentValue(unit || undefined);
if (value != null) out[`${position}_${variant}_${type}`] = value;
});
});
});
out.mode = vgc.currentMode;
out.maxDeltaP = vgc.maxDeltaP;
return out;
}
function getStatusBadge(vgc) {
const flowUnit = vgc.unitPolicy.output('flow');
const measured = vgc.measurements.type('flow').variant('measured').position('atEquipment').getCurrentValue(flowUnit);
const predicted = vgc.measurements.type('flow').variant('predicted').position('atEquipment').getCurrentValue(flowUnit);
const raw = Number.isFinite(measured) ? measured : predicted;
const totalFlow = Number.isFinite(raw) ? Math.round(raw) : 0;
const available = vgc.getAvailableValves();
const status = available.length > 0 ? `${available.length} valve(s) connected` : 'No valves';
return statusBadge.text(
`${vgc.currentMode} | flow=${totalFlow} ${flowUnit} | ${status}`,
{ fill: available.length > 0 ? 'green' : 'red', shape: 'dot' }
);
}
module.exports = { getOutput, getStatusBadge };

View File

@@ -1,258 +1,33 @@
const { outputUtils, configManager, convert } = require("generalFunctions"); 'use strict';
const Specific = require("./specificClass");
class nodeClass { const { BaseNodeAdapter } = require('generalFunctions');
/** const ValveGroupControl = require('./specificClass');
* Create a MeasurementNode. const commands = require('./commands');
* @param {object} uiConfig - Node-RED node configuration.
* @param {object} RED - Node-RED runtime API.
* @param {object} nodeInstance - The Node-RED node instance.
* @param {string} nameOfNode - The name of the node, used for
*/
constructor(uiConfig, RED, nodeInstance, nameOfNode) {
// Preserve RED reference for HTTP endpoints if needed
this.node = nodeInstance; // This is the Node-RED node instance, we can use this to send messages and update status
this.RED = RED; // This is the Node-RED runtime API, we can use this to create endpoints if needed
this.name = nameOfNode; // This is the name of the node, it should match the file name and the node type in Node-RED
this.source = null; // Will hold the specific class instance
// Load default & UI config // Tick-driven: a periodic reconcile pass re-balances per-valve flow if
this._loadConfig(uiConfig, this.node); // a child's accepted value drifts between event-driven recalcs.
this._reconcileIntervalMs = this._resolveReconcileIntervalMs(uiConfig); class nodeClass extends BaseNodeAdapter {
static DomainClass = ValveGroupControl;
static commands = commands;
static tickInterval = 1000;
static statusInterval = 1000;
// Instantiate core Measurement class buildDomainConfig() { return {}; }
this._setupSpecificClass();
// Wire up event and lifecycle handlers extraSetup() {
this._bindEvents(); this.source?.emitter?.on?.('reconcileIntervalChange', (ms) => this._restartTick(ms));
this._registerChild();
this._startTickLoop();
this._attachInputHandler();
this._attachCloseHandler();
} }
/** _restartTick(ms) {
* Load and merge default config with user-defined settings. const next = Math.max(100, Math.round(Number(ms) || 0));
* @param {object} uiConfig - Raw config from Node-RED UI. if (!next) return;
*/ if (this._tickInterval) clearInterval(this._tickInterval);
_loadConfig(uiConfig, node) { this._tickInterval = setInterval(() => {
const cfgMgr = new configManager(); try { this.source.tick?.(); }
this.defaultConfig = cfgMgr.getConfig(this.name); catch (err) { this.source?.logger?.error?.(`tick threw: ${err.message}`); }
this._emitOutputs();
// Resolve flow unit with validation before building config }, next);
const flowUnit = this._resolveUnitOrFallback(uiConfig.unit, 'volumeFlowRate', 'm3/h', 'flow');
const resolvedUiConfig = { ...uiConfig, unit: flowUnit };
// Build config: base sections (no domain-specific config for group controller)
this.config = cfgMgr.buildConfig(this.name, resolvedUiConfig, node.id);
// Utility for formatting outputs
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.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?
// Determine overall status based on available valves
const status =
availableValves.length > 0
? `${availableValves.length} valve(s) connected`
: "No valves";
// Generate status text in a single line
const text = `${mode} | flow=${totalFlow} ${flowUnit} | ${status}`;
return {
fill: availableValves.length > 0 ? "green" : "red",
shape: "dot",
text,
};
}
/**
* Instantiate the core logic and store as source.
*/
_setupSpecificClass() {
this.source = new Specific(this.config);
this.node.source = this.source; // Store the source in the node instance for easy access
}
/**
* Bind events to Node-RED status updates. Using internal emitter. --> REMOVE LATER WE NEED ONLY COMPLETE CHILDS AND THEN CHECK FOR UPDATES
*/
_bindEvents() {
}
/**
* Register this node as a child upstream and downstream.
* Delayed to avoid Node-RED startup race conditions.
*/
_registerChild() {
setTimeout(() => {
this.node.send([
null,
null,
{
topic: "registerChild",
payload: this.node.id,
positionVsParent:
this.config?.functionality?.positionVsParent || "atEquipment",
},
]);
}, 100);
}
/**
* Start the periodic tick loop to drive the Measurement class.
*/
_startTickLoop() {
setTimeout(() => {
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();
this.node.status(status);
}, 1000);
}, 1000);
}
/**
* 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");
// Send only updated outputs on ports 0 & 1
this.node.send([processMsg, influxMsg]);
}
/**
* Attach the node's input handler, routing control messages to the class.
*/
_attachInputHandler() {
this.node.on(
"input",
async (msg, send, done) => {
const vg = this.source;
const RED = this.RED;
try {
switch (msg.topic) {
case "registerChild": {
const childId = msg.payload;
const childObj = RED.nodes.getNode(childId);
if (!childObj || !childObj.source) {
vg.logger.warn(`registerChild skipped: missing child/source for id=${childId}`);
break;
}
vg.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent);
break;
}
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 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:
vg.logger.warn(`Unknown topic: ${msg.topic}`);
break;
}
} catch (error) {
vg.logger.error(`Input handler failure: ${error.message}`);
}
if (typeof done === 'function') done();
}
);
}
/**
* Clean up timers and intervals when Node-RED stops the node.
*/
_attachCloseHandler() {
this.node.on("close", (done) => {
clearInterval(this._tickInterval);
clearInterval(this._statusInterval);
this.source?.destroy?.();
if (typeof done === 'function') done();
});
} }
} }
module.exports = nodeClass; // Export the class for Node-RED to use module.exports = nodeClass;

View File

@@ -0,0 +1,186 @@
'use strict';
// Upstream-source registration + fluid-contract reconciliation.
// Sources are non-valve upstream children (rotatingMachine, MGC, PS, …)
// that publish flow events and optionally a service-type contract.
// VGC aggregates their contracts into one group-level view that valves
// can read for compatibility checks.
const SERVICE_TYPES = new Set(['gas', 'liquid']);
const SOURCE_SOFTWARE_TYPES = new Set([
'machine',
'rotatingmachine',
'machinegroup',
'machinegroupcontrol',
'pumpingstation',
'valvegroupcontrol',
]);
const SOURCE_FLOW_EVENTS = [
'flow.predicted.downstream',
'flow.predicted.atEquipment',
'flow.predicted.atequipment',
'flow.measured.downstream',
'flow.measured.atEquipment',
'flow.measured.atequipment',
];
const DEFAULT_SOURCE_SERVICE_TYPE = Object.freeze({
machine: 'liquid',
rotatingmachine: 'liquid',
machinegroup: 'liquid',
machinegroupcontrol: 'liquid',
pumpingstation: 'liquid',
});
function normalizeServiceType(value) {
const raw = String(value || '').trim().toLowerCase();
return SERVICE_TYPES.has(raw) ? raw : null;
}
function isSourceSoftwareType(softwareType) {
return SOURCE_SOFTWARE_TYPES.has(String(softwareType || '').trim().toLowerCase());
}
function isSourceLike(child, softwareType) {
if (isSourceSoftwareType(softwareType)) return true;
return typeof child?.getFluidContract === 'function';
}
function extractFluidContract(child, softwareType, logger) {
let contract = null;
if (typeof child?.getFluidContract === 'function') {
try { contract = child.getFluidContract(); }
catch (error) { logger?.warn?.(`Failed to read child fluid contract: ${error.message}`); }
}
const status = String(contract?.status || '').trim().toLowerCase();
if (status === 'conflict') return { status: 'conflict', serviceType: null };
const fromContract = normalizeServiceType(contract?.serviceType);
if (fromContract) return { status: 'resolved', serviceType: fromContract };
const direct = normalizeServiceType(
child?.serviceType || child?.expectedServiceType || child?.config?.asset?.serviceType
);
if (direct) return { status: 'resolved', serviceType: direct };
const fallback = DEFAULT_SOURCE_SERVICE_TYPE[String(softwareType || '').trim().toLowerCase()] || null;
if (fallback) return { status: 'inferred', serviceType: fallback };
return { status: 'unknown', serviceType: null };
}
function _diff(prev, next) {
return (
prev.status !== next.status
|| prev.serviceType !== next.serviceType
|| prev.sourceCount !== next.sourceCount
|| (prev.message || '') !== (next.message || '')
);
}
function refreshFluidContract(vgc) {
const contracts = Object.values(vgc.sources).map((s) => s?.fluidContract || null).filter(Boolean);
const serviceTypes = Array.from(new Set(
contracts.map((c) => normalizeServiceType(c.serviceType)).filter(Boolean)
));
const hasConflict = contracts.some((c) => String(c.status || '').toLowerCase() === 'conflict');
const sourceCount = Object.keys(vgc.sources).length;
let next;
if (hasConflict || serviceTypes.length > 1) {
next = {
status: 'conflict', serviceType: null, upstreamServiceTypes: serviceTypes, sourceCount,
message: `Conflicting upstream fluids detected: ${serviceTypes.join(', ') || 'unknown'}.`,
};
} else if (serviceTypes.length === 1) {
next = {
status: 'resolved', serviceType: serviceTypes[0], upstreamServiceTypes: serviceTypes, sourceCount,
message: `Upstream fluid resolved as ${serviceTypes[0]}.`,
};
} else {
next = {
status: 'unknown', serviceType: null, upstreamServiceTypes: [], sourceCount,
message: 'No upstream fluid sources registered.',
};
}
const prev = vgc.fluidContract || {};
vgc.fluidContract = next;
if (_diff(prev, next)) vgc.emitter.emit('fluidContractChange', vgc.getFluidContract());
}
function registerSource(vgc, child, positionVsParent, softwareType) {
const id = child?.config?.general?.id || child?.config?.general?.name || `source-${Object.keys(vgc.sources).length + 1}`;
if (vgc._sourceListeners.has(id)) unbindSource(vgc, id);
child.positionVsParent = positionVsParent;
vgc.sources[id] = child;
bindSource(vgc, id, child);
vgc.sources[id].fluidContract = extractFluidContract(child, softwareType, vgc.logger);
refreshFluidContract(vgc);
vgc.logger.info(`Source '${id}' (${softwareType || 'unknown'}) registered at ${positionVsParent}.`);
return true;
}
function bindSource(vgc, sourceId, source) {
const listeners = { flow: [], onFluidContractChange: null };
if (source?.measurements?.emitter?.on) {
SOURCE_FLOW_EVENTS.forEach((eventName) => {
const handler = (eventData = {}) => {
const value = Number(eventData.value);
if (!Number.isFinite(value)) return;
const variant = String(eventName).split('.')[1] === 'measured' ? 'measured' : 'predicted';
const unit = eventData.unit || vgc.unitPolicy.output('flow');
vgc.updateFlow(variant, value, 'atEquipment', unit);
};
source.measurements.emitter.on(eventName, handler);
listeners.flow.push({ emitter: source.measurements.emitter, eventName, handler });
});
}
if (source?.emitter?.on) {
listeners.onFluidContractChange = () => {
if (!vgc.sources[sourceId]) return;
vgc.sources[sourceId].fluidContract = extractFluidContract(source, source?.config?.functionality?.softwareType, vgc.logger);
refreshFluidContract(vgc);
};
source.emitter.on('fluidContractChange', listeners.onFluidContractChange);
}
vgc._sourceListeners.set(sourceId, { source, listeners });
}
function unbindSource(vgc, sourceId) {
const entry = vgc._sourceListeners.get(sourceId);
if (!entry) return;
const { source, listeners } = entry;
listeners.flow.forEach(({ emitter, eventName, handler }) => {
if (typeof emitter?.off === 'function') emitter.off(eventName, handler);
else if (typeof emitter?.removeListener === 'function') emitter.removeListener(eventName, handler);
});
if (listeners.onFluidContractChange) {
if (typeof source?.emitter?.off === 'function') source.emitter.off('fluidContractChange', listeners.onFluidContractChange);
else if (typeof source?.emitter?.removeListener === 'function') source.emitter.removeListener('fluidContractChange', listeners.onFluidContractChange);
}
vgc._sourceListeners.delete(sourceId);
}
function getFluidContract(vgc) {
const s = vgc.fluidContract || {};
return {
status: s.status || 'unknown',
serviceType: s.serviceType || null,
upstreamServiceTypes: Array.isArray(s.upstreamServiceTypes) ? [...s.upstreamServiceTypes] : [],
sourceCount: Number(s.sourceCount) || 0,
message: s.message || '',
source: 'valvegroupcontrol',
};
}
module.exports = {
isSourceLike,
isSourceSoftwareType,
registerSource,
unbindSource,
refreshFluidContract,
getFluidContract,
SOURCE_SOFTWARE_TYPES,
};

View File

@@ -1,161 +1,65 @@
/** 'use strict';
* @file valveGroupControl.js
*/
const EventEmitter = require('events'); // ValveGroupControl — S88 Unit orchestrator coordinating valve children.
const { logger, configUtils, configManager, state, MeasurementContainer, childRegistrationUtils, convert } = require('generalFunctions'); // Concern modules under src/{groupOps,sources,io,commands} carry the
// real work; this file stitches them together: registration, valve event
// routing, source fluid-contract aggregation, mode/sequence dispatch.
const CANONICAL_UNITS = Object.freeze({ const { BaseDomain, UnitPolicy, state } = require('generalFunctions');
pressure: 'Pa', const flowDist = require('./groupOps/flowDistribution');
flow: 'm3/s', const sources = require('./sources/fluidContract');
}); const io = require('./io/output');
const DEFAULT_IO_UNITS = Object.freeze({ // Source softwareTypes after BaseDomain canonicalisation
pressure: 'mbar', // (rotatingmachine→machine, machinegroupcontrol→machinegroup).
flow: 'm3/h', const SOURCE_SOFTWARE_TYPES = ['machine', 'machinegroup', 'pumpingstation', 'valvegroupcontrol'];
});
const KNOWN_POSITIONS = new Set(['upstream', 'downstream', 'atEquipment']); class ValveGroupControl extends BaseDomain {
const SERVICE_TYPES = new Set(['gas', 'liquid']); static name = 'valveGroupControl';
const SOURCE_SOFTWARE_TYPES = new Set([
'machine',
'rotatingmachine',
'machinegroup',
'machinegroupcontrol',
'pumpingstation',
'valvegroupcontrol',
]);
const SOURCE_FLOW_EVENTS = [
'flow.predicted.downstream',
'flow.predicted.atEquipment',
'flow.predicted.atequipment',
'flow.measured.downstream',
'flow.measured.atEquipment',
'flow.measured.atequipment',
];
const DEFAULT_SOURCE_SERVICE_TYPE = Object.freeze({
machine: 'liquid',
rotatingmachine: 'liquid',
machinegroup: 'liquid',
machinegroupcontrol: 'liquid',
pumpingstation: 'liquid',
});
const DEFAULT_FLOW_RECONCILIATION = Object.freeze({
maxPasses: 2,
residualTolerance: 0.001,
});
class ValveGroupControl { static unitPolicy = UnitPolicy.declare({
constructor(valveGroupControlConfig = {}) { canonical: { flow: 'm3/s', pressure: 'Pa' },
this.emitter = new EventEmitter(); output: { flow: 'm3/h', pressure: 'mbar' },
this.configManager = new configManager(); requireUnitForTypes: ['pressure', 'flow'],
this.defaultConfig = this.configManager.getConfig('valveGroupControl'); });
this.configUtils = new configUtils(this.defaultConfig);
this.config = this.configUtils.initConfig(valveGroupControlConfig); configure() {
this.unitPolicy = this._buildUnitPolicy(this.config);
this.config = this.configUtils.updateConfig(this.config, { this.config = this.configUtils.updateConfig(this.config, {
general: { unit: this.unitPolicy.output.flow }, general: { unit: this.unitPolicy.output('flow') },
}); });
this.logger = new logger(this.config.general.logging.enabled, this.config.general.logging.logLevel, this.config.general.name);
this.measurements = new MeasurementContainer({
autoConvert: true,
defaultUnits: {
pressure: this.unitPolicy.output.pressure,
flow: this.unitPolicy.output.flow,
},
preferredUnits: {
pressure: this.unitPolicy.output.pressure,
flow: this.unitPolicy.output.flow,
},
canonicalUnits: this.unitPolicy.canonical,
storeCanonical: true,
strictUnitValidation: true,
throwOnInvalidUnit: true,
requireUnitForTypes: ['pressure', 'flow'],
}, this.logger);
this.child = {};
this.valves = {}; this.valves = {};
this._valveListeners = new Map(); this._valveListeners = new Map();
this.sources = {}; this.sources = {};
this._sourceListeners = new Map(); this._sourceListeners = new Map();
this.fluidContract = { this.fluidContract = {
status: 'unknown', status: 'unknown', serviceType: null, upstreamServiceTypes: [],
serviceType: null, sourceCount: 0, message: 'No upstream fluid sources registered.',
upstreamServiceTypes: [],
sourceCount: 0,
message: 'No upstream fluid sources registered.',
}; };
this.flowReconciliation = { ...DEFAULT_FLOW_RECONCILIATION }; this.flowReconciliation = { ...flowDist.DEFAULT_RECONCILIATION };
this.lastFlowSolve = { this.lastFlowSolve = { passes: 0, residual: 0, targetTotal: 0, assignedTotal: 0 };
passes: 0,
residual: 0,
targetTotal: 0,
assignedTotal: 0,
};
this.maxDeltaP = 0; this.maxDeltaP = 0;
this.currentMode = this.config.mode.current; this.currentMode = this.config.mode.current;
this.childRegistrationUtils = new childRegistrationUtils(this);
this.state = new state({}, this.logger); this.state = new state({}, this.logger);
this.state.stateManager.currentState = 'operational'; this.state.stateManager.currentState = 'operational';
}
registerOnChildEvents() {} this.router.onRegister('valve', (child) => this._registerValve(child));
for (const swType of SOURCE_SOFTWARE_TYPES) {
_resolveRegistrationContext(child, positionVsParentOrSoftwareType) { this.router.onRegister(swType, (child, canonicalKey) => this._registerSource(child, canonicalKey));
const fromArg = String(positionVsParentOrSoftwareType || '').trim();
if (KNOWN_POSITIONS.has(fromArg)) {
return {
positionVsParent: fromArg,
softwareType: child?.config?.functionality?.softwareType || null,
};
} }
return {
positionVsParent: child?.positionVsParent || 'atEquipment',
softwareType: fromArg || child?.config?.functionality?.softwareType || null,
};
} }
_isValveLike(child) { _isValveLike(child) {
return Boolean( return Boolean(
child child
&& typeof child.updateFlow === 'function' && typeof child.updateFlow === 'function'
&& child.state && child.state && typeof child.state.getCurrentState === 'function'
&& typeof child.state.getCurrentState === 'function'
&& child.measurements && child.measurements
); );
} }
_isSourceLike(child, softwareType) { _registerValve(child) {
const type = String(softwareType || child?.config?.functionality?.softwareType || '').trim().toLowerCase();
if (SOURCE_SOFTWARE_TYPES.has(type)) {
return true;
}
return typeof child?.getFluidContract === 'function';
}
registerChild(child, positionVsParentOrSoftwareType) {
const ctx = this._resolveRegistrationContext(child, positionVsParentOrSoftwareType);
const softwareType = String(ctx.softwareType || child?.config?.functionality?.softwareType || '').trim().toLowerCase();
if (softwareType === 'valve' || (!softwareType && this._isValveLike(child))) {
return this._registerValve(child, ctx.positionVsParent);
}
if (this._isSourceLike(child, softwareType)) {
return this._registerSource(child, ctx.positionVsParent, softwareType);
}
this.logger.warn(`registerChild skipped: unsupported child type '${softwareType || 'unknown'}'`);
return false;
}
_registerValve(child, positionVsParent) {
if (!this._isValveLike(child)) { if (!this._isValveLike(child)) {
this.logger.warn('registerChild skipped: child is not valve-like'); this.logger.warn('registerChild skipped: child is not valve-like');
return false; return false;
@@ -165,314 +69,154 @@ class ValveGroupControl {
this.logger.debug(`registerChild skipped: valve ${id} already registered`); this.logger.debug(`registerChild skipped: valve ${id} already registered`);
return true; return true;
} }
const positionVsParent = child.positionVsParent
|| child.config?.functionality?.positionVsParent
|| 'atEquipment';
child.positionVsParent = positionVsParent; child.positionVsParent = positionVsParent;
this.valves[id] = child; this.valves[id] = child;
this._bindValveEvents(id, child); this._bindValveEvents(id, child);
this.calcValveFlows(); this.calcValveFlows();
this.calcMaxDeltaP(); this.calcMaxDeltaP();
this._refreshFluidContract(); sources.refreshFluidContract(this);
this.logger.info(`Valve '${id}' registered at ${positionVsParent}.`); this.logger.info(`Valve '${id}' registered at ${positionVsParent}.`);
return true; return true;
} }
_registerSource(child, positionVsParent, softwareType) { _registerSource(child, softwareType) {
const id = child?.config?.general?.id || child?.config?.general?.name || `source-${Object.keys(this.sources).length + 1}`; const positionVsParent = child.positionVsParent
if (this._sourceListeners.has(id)) { || child.config?.functionality?.positionVsParent
this._unbindSourceEvents(id); || 'atEquipment';
} return sources.registerSource(this, child, positionVsParent, softwareType);
child.positionVsParent = positionVsParent;
this.sources[id] = child;
this._bindSourceEvents(id, child);
const contract = this._extractFluidContractFromChild(child, softwareType);
this.sources[id].fluidContract = contract;
this._refreshFluidContract();
this.logger.info(`Source '${id}' (${softwareType || 'unknown'}) registered at ${positionVsParent}.`);
return true;
} }
_bindValveEvents(valveId, valve) { _bindValveEvents(valveId, valve) {
const handlers = { const handlers = {
onPositionChange: () => { onPositionChange: () => { this.logger.debug(`Valve ${valveId} position changed, recalculating flows.`); this.calcValveFlows(); },
this.logger.debug(`Valve ${valveId} position changed, recalculating flows.`); onDeltaPChange: () => { this.logger.debug(`Valve ${valveId} deltaP changed, recalculating max deltaP.`); this.calcMaxDeltaP(); },
this.calcValveFlows();
},
onDeltaPChange: () => {
this.logger.debug(`Valve ${valveId} deltaP changed, recalculating max deltaP.`);
this.calcMaxDeltaP();
},
}; };
if (valve.state?.emitter?.on) valve.state.emitter.on('positionChange', handlers.onPositionChange);
if (valve.state?.emitter?.on) { if (valve.emitter?.on) valve.emitter.on('deltaPChange', handlers.onDeltaPChange);
valve.state.emitter.on('positionChange', handlers.onPositionChange);
}
if (valve.emitter?.on) {
valve.emitter.on('deltaPChange', handlers.onDeltaPChange);
}
this._valveListeners.set(valveId, { valve, handlers }); this._valveListeners.set(valveId, { valve, handlers });
} }
_unbindValveEvents(valveId) { _unbindValveEvents(valveId) {
const listener = this._valveListeners.get(valveId); const entry = this._valveListeners.get(valveId);
if (!listener) { if (!entry) return;
return; const { valve, handlers } = entry;
} if (handlers.onPositionChange && valve.state?.emitter?.off) valve.state.emitter.off('positionChange', handlers.onPositionChange);
const { valve, handlers } = listener; if (handlers.onDeltaPChange && valve.emitter?.off) valve.emitter.off('deltaPChange', handlers.onDeltaPChange);
if (handlers.onPositionChange && valve.state?.emitter?.off) {
valve.state.emitter.off('positionChange', handlers.onPositionChange);
}
if (handlers.onDeltaPChange && valve.emitter?.off) {
valve.emitter.off('deltaPChange', handlers.onDeltaPChange);
}
this._valveListeners.delete(valveId); this._valveListeners.delete(valveId);
} }
_bindSourceEvents(sourceId, source) { registerOnChildEvents() {}
const listeners = {
flow: [],
onFluidContractChange: null,
};
if (source?.measurements?.emitter?.on) {
SOURCE_FLOW_EVENTS.forEach((eventName) => {
const handler = (eventData = {}) => {
this._handleSourceFlowEvent(eventName, eventData);
};
source.measurements.emitter.on(eventName, handler);
listeners.flow.push({
emitter: source.measurements.emitter,
eventName,
handler,
});
});
}
if (source?.emitter?.on) {
listeners.onFluidContractChange = () => {
const contract = this._extractFluidContractFromChild(
source,
source?.config?.functionality?.softwareType
);
if (!this.sources[sourceId]) {
return;
}
this.sources[sourceId].fluidContract = contract;
this._refreshFluidContract();
};
source.emitter.on('fluidContractChange', listeners.onFluidContractChange);
}
this._sourceListeners.set(sourceId, { source, listeners });
}
_unbindSourceEvents(sourceId) {
const listener = this._sourceListeners.get(sourceId);
if (!listener) {
return;
}
const { source, listeners } = listener;
listeners.flow.forEach(({ emitter, eventName, handler }) => {
if (typeof emitter?.off === 'function') {
emitter.off(eventName, handler);
} else if (typeof emitter?.removeListener === 'function') {
emitter.removeListener(eventName, handler);
}
});
if (listeners.onFluidContractChange) {
if (typeof source?.emitter?.off === 'function') {
source.emitter.off('fluidContractChange', listeners.onFluidContractChange);
} else if (typeof source?.emitter?.removeListener === 'function') {
source.emitter.removeListener('fluidContractChange', listeners.onFluidContractChange);
}
}
this._sourceListeners.delete(sourceId);
}
_handleSourceFlowEvent(eventName, eventData = {}) {
const value = Number(eventData.value);
if (!Number.isFinite(value)) {
return;
}
const eventParts = String(eventName || '').split('.');
const variant = eventParts[1] === 'measured' ? 'measured' : 'predicted';
const unit = eventData.unit || this.unitPolicy.output.flow;
this.updateFlow(variant, value, 'atEquipment', unit);
}
_normalizeOptionalServiceType(value) {
const raw = String(value || '').trim().toLowerCase();
if (SERVICE_TYPES.has(raw)) {
return raw;
}
return null;
}
_deriveDefaultServiceTypeForSoftwareType(softwareType) {
const key = String(softwareType || '').trim().toLowerCase();
return DEFAULT_SOURCE_SERVICE_TYPE[key] || null;
}
_extractFluidContractFromChild(child, softwareType) {
let contract = null;
if (typeof child?.getFluidContract === 'function') {
try {
contract = child.getFluidContract();
} catch (error) {
this.logger.warn(`Failed to read child fluid contract: ${error.message}`);
}
}
const contractStatus = String(contract?.status || '').trim().toLowerCase();
if (contractStatus === 'conflict') {
return { status: 'conflict', serviceType: null };
}
const serviceTypeFromContract = this._normalizeOptionalServiceType(contract?.serviceType);
if (serviceTypeFromContract) {
return { status: 'resolved', serviceType: serviceTypeFromContract };
}
const directType = this._normalizeOptionalServiceType(
child?.serviceType
|| child?.expectedServiceType
|| child?.config?.asset?.serviceType
);
if (directType) {
return { status: 'resolved', serviceType: directType };
}
const fallbackType = this._deriveDefaultServiceTypeForSoftwareType(softwareType);
if (fallbackType) {
return { status: 'inferred', serviceType: fallbackType };
}
return { status: 'unknown', serviceType: null };
}
_refreshFluidContract() {
const contracts = Object.values(this.sources)
.map((source) => source?.fluidContract || null)
.filter(Boolean);
const serviceTypes = Array.from(new Set(
contracts
.map((contract) => this._normalizeOptionalServiceType(contract.serviceType))
.filter(Boolean)
));
const hasConflict = contracts.some((contract) => String(contract.status || '').toLowerCase() === 'conflict');
let next = null;
if (hasConflict || serviceTypes.length > 1) {
next = {
status: 'conflict',
serviceType: null,
upstreamServiceTypes: serviceTypes,
sourceCount: Object.keys(this.sources).length,
message: `Conflicting upstream fluids detected: ${serviceTypes.join(', ') || 'unknown'}.`,
};
} else if (serviceTypes.length === 1) {
next = {
status: 'resolved',
serviceType: serviceTypes[0],
upstreamServiceTypes: serviceTypes,
sourceCount: Object.keys(this.sources).length,
message: `Upstream fluid resolved as ${serviceTypes[0]}.`,
};
} else {
next = {
status: 'unknown',
serviceType: null,
upstreamServiceTypes: [],
sourceCount: Object.keys(this.sources).length,
message: 'No upstream fluid sources registered.',
};
}
const prev = this.fluidContract || {};
const changed = (
prev.status !== next.status
|| prev.serviceType !== next.serviceType
|| prev.sourceCount !== next.sourceCount
|| (prev.message || '') !== (next.message || '')
);
this.fluidContract = next;
if (changed) {
this.emitter.emit('fluidContractChange', this.getFluidContract());
}
}
getFluidContract() {
const state = this.fluidContract || {};
return {
status: state.status || 'unknown',
serviceType: state.serviceType || null,
upstreamServiceTypes: Array.isArray(state.upstreamServiceTypes) ? [...state.upstreamServiceTypes] : [],
sourceCount: Number(state.sourceCount) || 0,
message: state.message || '',
source: 'valvegroupcontrol',
};
}
destroy() { destroy() {
for (const valveId of this._valveListeners.keys()) { for (const id of this._valveListeners.keys()) this._unbindValveEvents(id);
this._unbindValveEvents(valveId); for (const id of this._sourceListeners.keys()) sources.unbindSource(this, id);
} }
for (const sourceId of this._sourceListeners.keys()) {
this._unbindSourceEvents(sourceId); // ── measurement read/write helpers used by concern modules ─────────
_outputUnitForType(type) {
switch (String(type || '').toLowerCase()) {
case 'flow': return this.unitPolicy.output('flow');
case 'pressure': return this.unitPolicy.output('pressure');
default: return null;
} }
} }
_isValveAvailable(valve) { _read(type, variant, position, unit = null) {
const currentState = valve.state.getCurrentState(); const u = unit || this._outputUnitForType(type);
const mode = valve.currentMode; return this.measurements.type(type).variant(variant).position(position).getCurrentValue(u || undefined);
const kv = Number(valve.kv);
return (
currentState !== 'off'
&& currentState !== 'maintenance'
&& mode !== 'maintenance'
&& Number.isFinite(kv)
&& kv > 0
);
} }
getAvailableValves() { _write(type, variant, position, value, unit = null, timestamp = Date.now()) {
return Object.entries(this.valves) const v = Number(value);
.filter(([, valve]) => this._isValveAvailable(valve)) if (!Number.isFinite(v)) return;
.map(([id, valve]) => ({ id, valve })); this.measurements.type(type).variant(variant).position(position).value(v, timestamp, unit || undefined);
} }
// ── public surface used by adapter, tests, commands, valves ────────
getAvailableValves() { return flowDist.listAvailableValves(this.valves); }
calcValveFlows() { flowDist.distributeFlow(this); this.notifyOutputChanged(); }
calcMaxDeltaP() { flowDist.calcMaxDeltaP(this); }
getFluidContract() { return sources.getFluidContract(this); }
isValidSourceForMode(source, mode) { isValidSourceForMode(source, mode) {
const allowedSourcesSet = this.config.mode.allowedSources[mode] || []; const allowedSourcesSet = this.config.mode.allowedSources[mode] || [];
return allowedSourcesSet.has(source); return allowedSourcesSet.has(source);
} }
setMode(newMode) {
const availableModes = Array.isArray(this.defaultConfig?.mode?.current?.rules?.values)
? this.defaultConfig.mode.current.rules.values.map((m) => m.value)
: Object.keys(this.config?.mode?.allowedSources || {});
if (!availableModes.includes(newMode)) {
this.logger.warn(`Invalid mode '${newMode}'. Allowed modes are: ${availableModes.join(', ')}`);
return;
}
this.currentMode = newMode;
this.logger.info(`Mode successfully changed to '${newMode}'.`);
this.notifyOutputChanged();
}
async executeSequence(sequenceName) {
const sequence = this.config.sequences[sequenceName];
if (!sequence || sequence.size === 0) {
this.logger.warn(`Sequence '${sequenceName}' not defined.`);
return;
}
this.logger.info(` --------- Executing sequence: ${sequenceName} -------------`);
for (const stateName of sequence) {
try { await this.state.transitionToState(stateName); }
catch (error) { this.logger.error(`Error during sequence '${sequenceName}': ${error}`); break; }
}
}
updateFlow(variant, value, position, unit = this.unitPolicy.output('flow')) {
if (value === null || value === undefined) {
this.logger.warn(`Received null or undefined value for flow update. Variant: ${variant}, Position: ${position}`);
return;
}
if (variant !== 'measured' && variant !== 'predicted') {
this.logger.warn(`Unrecognized variant '${variant}' for flow update.`);
return;
}
this.logger.debug(`Updating ${variant} flow for position ${position} with value ${value}`);
this._write('flow', variant, position, value, unit);
this.calcValveFlows();
}
updateMeasurement(variant, subType, value, position, unit) {
this.logger.debug(`---------------------- updating ${subType} ------------------ `);
if (subType === 'flow') {
this.updateFlow(variant, value, position, unit || this.unitPolicy.output('flow'));
return;
}
this.logger.error(`Type '${subType}' not recognized for measured update.`);
}
async handleInput(source, action, parameter) { async handleInput(source, action, parameter) {
if (!this.isValidSourceForMode(source, this.currentMode)) { if (!this.isValidSourceForMode(source, this.currentMode)) {
const warningTxt = `Source '${source}' is not valid for mode '${this.currentMode}'.`; const warningTxt = `Source '${source}' is not valid for mode '${this.currentMode}'.`;
this.logger.warn(warningTxt); this.logger.warn(warningTxt);
return { status: false, feedback: warningTxt }; return { status: false, feedback: warningTxt };
} }
this.logger.info(`Handling input from source '${source}' with action '${action}' in mode '${this.currentMode}'.`); this.logger.info(`Handling input from source '${source}' with action '${action}' in mode '${this.currentMode}'.`);
try { try {
const flowUnit = this.unitPolicy.output('flow');
switch (action) { switch (action) {
case 'execSequence': case 'execSequence':
await this.executeSequence(parameter); await this.executeSequence(parameter);
break; break;
case 'totalFlowChange': { case 'totalFlowChange':
if (parameter && typeof parameter === 'object' && Object.prototype.hasOwnProperty.call(parameter, 'value')) { if (parameter && typeof parameter === 'object' && Object.prototype.hasOwnProperty.call(parameter, 'value')) {
await this.updateFlow(parameter.variant || 'measured', parameter.value, parameter.position || 'atEquipment', parameter.unit || this.unitPolicy.output.flow); await this.updateFlow(parameter.variant || 'measured', parameter.value, parameter.position || 'atEquipment', parameter.unit || flowUnit);
} else if (parameter && typeof parameter === 'object' && Object.prototype.hasOwnProperty.call(parameter, 'q')) { } else if (parameter && typeof parameter === 'object' && Object.prototype.hasOwnProperty.call(parameter, 'q')) {
await this.updateFlow('measured', Number(parameter.q), 'atEquipment', parameter.unit || this.unitPolicy.output.flow); await this.updateFlow('measured', Number(parameter.q), 'atEquipment', parameter.unit || flowUnit);
} else { } else {
await this.updateFlow('measured', Number(parameter), 'atEquipment', this.unitPolicy.output.flow); await this.updateFlow('measured', Number(parameter), 'atEquipment', flowUnit);
} }
break; break;
}
case 'emergencyStop': case 'emergencyStop':
case 'emergencystop': case 'emergencystop':
this.logger.warn(`Emergency stop activated by '${source}'.`); this.logger.warn(`Emergency stop activated by '${source}'.`);
@@ -493,288 +237,19 @@ class ValveGroupControl {
} }
} }
setMode(newMode) { setReconcileIntervalSeconds(sec) {
const availableModes = Array.isArray(this.defaultConfig?.mode?.current?.rules?.values) const ms = Math.max(100, Math.round(Number(sec) * 1000));
? this.defaultConfig.mode.current.rules.values.map((vgc) => vgc.value) this.emitter.emit('reconcileIntervalChange', ms);
: Object.keys(this.config?.mode?.allowedSources || {}); this.logger.info(`Flow reconciliation interval updated to ${sec}s (${ms}ms).`);
if (!availableModes.includes(newMode)) {
this.logger.warn(`Invalid mode '${newMode}'. Allowed modes are: ${availableModes.join(', ')}`);
return;
}
this.currentMode = newMode;
this.logger.info(`Mode successfully changed to '${newMode}'.`);
} }
_buildUnitPolicy(config = {}) { // Periodic reconciliation — adapter fires this each tickInterval. Keeps
const flowUnit = this._resolveUnitOrFallback( // per-valve assigned flow in sync if a child's accepted value drifts
config?.general?.unit, // between event-driven recalcs.
'volumeFlowRate', tick() { this.calcValveFlows(); }
DEFAULT_IO_UNITS.flow
);
return { getOutput() { return io.getOutput(this); }
canonical: { ...CANONICAL_UNITS }, getStatusBadge() { return io.getStatusBadge(this); }
output: {
flow: flowUnit,
pressure: DEFAULT_IO_UNITS.pressure,
},
};
}
_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 'pressure':
return this.unitPolicy.output.pressure;
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()) {
const valueNum = Number(value);
if (!Number.isFinite(valueNum)) {
return;
}
this.measurements
.type(type)
.variant(variant)
.position(position)
.value(valueNum, timestamp, unit || undefined);
}
async executeSequence(sequenceName) {
const sequence = this.config.sequences[sequenceName];
if (!sequence || sequence.size === 0) {
this.logger.warn(`Sequence '${sequenceName}' not defined.`);
return;
}
this.logger.info(` --------- Executing sequence: ${sequenceName} -------------`);
for (const stateName of sequence) {
try {
await this.state.transitionToState(stateName);
} catch (error) {
this.logger.error(`Error during sequence '${sequenceName}': ${error}`);
break;
}
}
}
updateFlow(variant, value, position, unit = this.unitPolicy.output.flow) {
if (value === null || value === undefined) {
this.logger.warn(`Received null or undefined value for flow update. Variant: ${variant}, Position: ${position}`);
return;
}
switch (variant) {
case 'measured':
this.logger.debug(`Updating measured flow for position ${position} with value ${value}`);
this._writeMeasurement('flow', 'measured', position, value, unit);
this.calcValveFlows();
break;
case 'predicted':
this.logger.debug(`Updating predicted flow for position ${position} with value ${value}`);
this._writeMeasurement('flow', 'predicted', position, value, unit);
this.calcValveFlows();
break;
default:
this.logger.warn(`Unrecognized variant '${variant}' for flow update.`);
break;
}
}
updateMeasurement(variant, subType, value, position, unit) {
this.logger.debug(`---------------------- updating ${subType} ------------------ `);
switch (subType) {
case 'flow':
this.updateFlow(variant, value, position, unit || this.unitPolicy.output.flow);
break;
default:
this.logger.error(`Type '${subType}' not recognized for measured update.`);
break;
}
}
calcValveFlows() {
const totalFlowMeasured = this._readMeasurement('flow', 'measured', 'atEquipment', this.unitPolicy.output.flow);
const totalFlowPredicted = this._readMeasurement('flow', 'predicted', 'atEquipment', this.unitPolicy.output.flow);
const totalFlow = Number.isFinite(totalFlowMeasured) ? totalFlowMeasured : totalFlowPredicted;
if (!Number.isFinite(totalFlow)) {
return;
}
const availableEntries = this.getAvailableValves();
const availableIds = new Set(availableEntries.map((entry) => entry.id));
const totalKv = availableEntries.reduce((sum, { valve }) => sum + Number(valve.kv), 0);
if (!availableEntries.length || !Number.isFinite(totalKv) || totalKv <= 0) {
this.logger.warn('No available valves with valid Kv, setting assigned flow to 0.');
for (const valve of Object.values(this.valves)) {
valve.updateFlow('predicted', 0, 'downstream', this.unitPolicy.output.flow);
}
this._writeMeasurement('flow', 'predicted', 'atEquipment', 0, this.unitPolicy.output.flow);
this.lastFlowSolve = {
passes: 0,
residual: Number(totalFlow) || 0,
targetTotal: Number(totalFlow) || 0,
assignedTotal: 0,
};
return;
}
const solve = this._solveFlowDistribution(totalFlow, availableEntries);
let assignedTotal = 0;
for (const [id, valve] of Object.entries(this.valves)) {
const flow = availableIds.has(id) ? (solve.flowsById[id] || 0) : 0;
valve.updateFlow('predicted', flow, 'downstream', this.unitPolicy.output.flow);
assignedTotal += flow;
}
this._writeMeasurement('flow', 'predicted', 'atEquipment', assignedTotal, this.unitPolicy.output.flow);
this.lastFlowSolve = {
passes: solve.passes,
residual: solve.residual,
targetTotal: totalFlow,
assignedTotal,
};
this.calcMaxDeltaP();
}
_readValveAcceptedFlow(valve) {
const accepted = Number(
valve?.measurements
?.type('flow')
?.variant('predicted')
?.position('downstream')
?.getCurrentValue(this.unitPolicy.output.flow)
);
return Number.isFinite(accepted) ? accepted : null;
}
_solveFlowDistribution(totalFlow, availableEntries) {
const totalKv = availableEntries.reduce((sum, { valve }) => sum + Number(valve.kv), 0);
if (!Number.isFinite(totalKv) || totalKv <= 0) {
return { flowsById: {}, residual: Number(totalFlow) || 0, passes: 0 };
}
const targetById = {};
availableEntries.forEach(({ id }) => {
targetById[id] = 0;
});
let residual = Number(totalFlow);
let passes = 0;
const maxPasses = Math.max(1, Number(this.flowReconciliation?.maxPasses) || DEFAULT_FLOW_RECONCILIATION.maxPasses);
const tolerance = Math.max(0, Number(this.flowReconciliation?.residualTolerance) || DEFAULT_FLOW_RECONCILIATION.residualTolerance);
while (passes < maxPasses && Number.isFinite(residual) && Math.abs(residual) > tolerance) {
availableEntries.forEach(({ id, valve }) => {
const kv = Number(valve.kv);
const share = (kv / totalKv) * residual;
const nextTarget = Number(targetById[id]) + share;
targetById[id] = nextTarget;
valve.updateFlow('predicted', nextTarget, 'downstream', this.unitPolicy.output.flow);
});
let acceptedTotal = 0;
availableEntries.forEach(({ id, valve }) => {
const accepted = this._readValveAcceptedFlow(valve);
if (Number.isFinite(accepted)) {
targetById[id] = accepted;
acceptedTotal += accepted;
return;
}
acceptedTotal += Number(targetById[id]) || 0;
});
residual = Number(totalFlow) - acceptedTotal;
passes += 1;
}
return {
flowsById: targetById,
residual: Number.isFinite(residual) ? residual : 0,
passes,
};
}
calcMaxDeltaP() {
let maxDeltaP = 0;
for (const [id, valve] of Object.entries(this.valves)) {
const deltaP = Number(
valve.measurements
.type('pressure')
.variant('predicted')
.position('delta')
.getCurrentValue(this.unitPolicy.output.pressure)
);
if (!Number.isFinite(deltaP)) {
continue;
}
this.logger.debug(`Delta P for valve ${id}: ${deltaP}`);
if (deltaP > maxDeltaP) {
maxDeltaP = deltaP;
}
}
this.maxDeltaP = maxDeltaP;
this._writeMeasurement('pressure', 'predicted', 'deltaMax', maxDeltaP, this.unitPolicy.output.pressure);
}
getOutput() {
const output = {};
Object.entries(this.measurements.measurements || {}).forEach(([type, variants]) => {
Object.entries(variants || {}).forEach(([variant, positions]) => {
Object.keys(positions || {}).forEach((position) => {
const value = this._readMeasurement(type, variant, position, this._outputUnitForType(type));
if (value != null) {
output[`${position}_${variant}_${type}`] = value;
}
});
});
});
output.mode = this.currentMode;
output.maxDeltaP = this.maxDeltaP;
return output;
}
} }
module.exports = ValveGroupControl; module.exports = ValveGroupControl;

View File

@@ -84,10 +84,43 @@ test('valveGroupControl distributes total flow according to supplier-curve Kv an
valve2.destroy(); valve2.destroy();
}); });
test('valveGroupControl rejects non-valve-like child payload', () => { test('valveGroupControl skips a non-valve-like payload registered as a valve', () => {
const group = buildGroup(); const group = buildGroup();
const result = group.registerChild({ config: { functionality: { softwareType: 'valve' } } }, 'atEquipment'); // Router dispatches by softwareType; the _registerValve handler rejects
assert.equal(result, false); // non-valve-like children (missing updateFlow/state/measurements) by
// returning false from its branch — the registry side-effect (valves[])
// stays empty even though BaseDomain's registerChild returns true.
group.registerChild({ config: { functionality: { softwareType: 'valve' } } }, 'valve');
assert.equal(Object.keys(group.valves).length, 0); assert.equal(Object.keys(group.valves).length, 0);
group.destroy(); group.destroy();
}); });
test('valveGroupControl router dispatches valve registration by softwareType, honouring config positionVsParent', async () => {
const valve = (function buildValveAtUpstream() {
const Valve = require('../../../valve/src/specificClass');
return new Valve(
{
general: { name: 'valve-upstream', logging: { enabled: false, logLevel: 'error' } },
asset: { supplier: 'binder', category: 'valve', type: 'control', model: 'ECDV', unit: 'm3/h' },
functionality: { positionVsParent: 'upstream', softwareType: 'valve' },
},
{
general: { logging: { enabled: false, logLevel: 'error' } },
movement: { speed: 1 },
time: { starting: 0, warmingup: 0, stopping: 0, coolingdown: 0 },
}
);
})();
primeValve(valve, 50);
const group = buildGroup();
// childRegistrationUtils consumes positionVsParent (2nd arg) and forwards
// softwareType='valve' to the parent — the router fans out from there.
assert.equal(await group.childRegistrationUtils.registerChild(valve, 'upstream'), true);
assert.equal(Object.keys(group.valves).length, 1);
const registered = Object.values(group.valves)[0];
assert.equal(registered.positionVsParent, 'upstream');
group.destroy();
valve.destroy();
});

View File

@@ -14,7 +14,7 @@
<script> <script>
RED.nodes.registerType('valveGroupControl',{ RED.nodes.registerType('valveGroupControl',{
category: "EVOLV", category: "EVOLV",
color: "#50a8d9", color: "#2A8A82",
defaults: { defaults: {
// Define default properties // Define default properties
name: { value: "" }, name: { value: "" },
@@ -91,6 +91,7 @@
<label for="node-input-dbaseOutputFormat"><i class="fa fa-database"></i> Database Output</label> <label for="node-input-dbaseOutputFormat"><i class="fa fa-database"></i> Database Output</label>
<select id="node-input-dbaseOutputFormat" style="width:60%;"> <select id="node-input-dbaseOutputFormat" style="width:60%;">
<option value="influxdb">influxdb</option> <option value="influxdb">influxdb</option>
<option value="frost">frost</option>
<option value="json">json</option> <option value="json">json</option>
<option value="csv">csv</option> <option value="csv">csv</option>
</select> </select>

153
wiki/Home.md Normal file
View File

@@ -0,0 +1,153 @@
# valveGroupControl
![code-ref](https://img.shields.io/badge/code--ref-b20a573-blue) ![s88](https://img.shields.io/badge/S88-Unit-50a8d9) ![status](https://img.shields.io/badge/status-pending--review-yellow)
A `valveGroupControl` (VGC) coordinates a group of `valve` children that share a common manifold &mdash; selector-valve banks, dosing-valve trains, mixing manifolds. It accepts a group-level total flow target, splits the flow proportional to each valve's Kv rating, runs a residual-reconciliation pass against what every valve actually accepted, and aggregates max delta-P across the group. It also reconciles upstream-source fluid-contract advertisements (`liquid` / `gas`) into one group-level service-type view that downstream consumers can read.
> [!NOTE]
> Pending full node review (2026-05). Content reflects `CONTRACT.md` and current source only.
---
## At a glance
| Thing | Value |
|:---|:---|
| What it represents | A parallel valve manifold &mdash; 2&nbsp;+ valves sharing a header, distributing one total flow target |
| S88 level | Unit |
| Use it when | You have 2&nbsp;+ parallel valves that should share an upstream flow target proportional to their Kv |
| Don't use it for | A single valve (wire `valve` directly), series valves (the Kv-share solver assumes parallel branches), or a manifold whose upstream already publishes per-branch setpoints |
| Children it accepts | `valve` (group members) + upstream sources (`machine` / `rotatingmachine` / `machinegroup` / `machinegroupcontrol` / `pumpingstation` / `valvegroupcontrol`) |
| Parents it talks to | Any upstream node &mdash; typically `pumpingStation`, `reactor`, or another VGC; VGC registers via Port 2 |
---
## How it fits
```mermaid
flowchart LR
src[machine / MGC /<br/>pumpingStation<br/>upstream source]:::unit -.flow.predicted.*.-> vgc[valveGroupControl<br/>Unit]:::unit
vgc -->|updateFlow predicted<br/>downstream| v1[valve A]:::equip
vgc -->|updateFlow predicted<br/>downstream| v2[valve B]:::equip
v1 -->|positionChange<br/>deltaPChange| vgc
v2 -->|positionChange<br/>deltaPChange| vgc
vgc -->|child.register| parent[upstream parent]:::pc
classDef pc fill:#0c99d9,color:#fff
classDef unit fill:#50a8d9,color:#000
classDef equip fill:#86bbdd,color:#000
```
S88 colours are anchored in `.claude/rules/node-red-flow-layout.md`.
---
## Try it &mdash; 3-minute demo
Import the basic example flow, deploy, and drive a 2-valve group with an injected total-flow setpoint.
```bash
curl -X POST -H 'Content-Type: application/json' \
--data @nodes/valveGroupControl/examples/basic.flow.json \
http://localhost:1880/flow
```
What to click after deploy (the inject buttons map to canonical topics in [Reference &mdash; Contracts](Reference-Contracts#topic-contract)):
1. `child.register` for each `valve` &mdash; or rely on Port-2 wiring to auto-register.
2. `set.mode = auto` &mdash; lets the parent source drive the group.
3. `data.totalFlow = 80` (with `unit: 'm3/h'`) &mdash; VGC splits 80 m³/h across the available valves by Kv share; runs up to `maxPasses: 2` residual passes; writes back `atEquipment_predicted_flow` = sum of accepted per-valve flows.
4. `cmd.execSequence` with `{action: "startup"}` &mdash; runs the group-wide startup sequence through `executeSequence`, transitioning the group state machine through each step.
5. `cmd.emergencyStop` &mdash; runs the `emergencystop` sequence on all valves (`[emergencystop, off]`).
6. `set.reconcileInterval = 2` &mdash; re-tunes the periodic tick to 2 s (`reconcileIntervalChange` event triggers the adapter to restart its tick loop; minimum 100 ms).
> [!IMPORTANT]
> **GIF needed.** Demo recording of steps 1&ndash;6 with the live status panel. Save as `wiki/_partial-gifs/valveGroupControl/01-basic-demo.gif`, target &le; 1&nbsp;MB after `gifsicle -O3 --lossy=80`.
---
## The seven things you'll send
| Topic | Aliases | Payload | What it does |
|:---|:---|:---|:---|
| `set.mode` | `setMode` | `"auto"` \| `"virtualControl"` \| `"fysicalControl"` \| `"maintenance"` | Switch operational mode. Each mode has its own allow-list of sources (`mode.allowedSources`). |
| `set.position` | `setpoint` | any | **No-op pending Phase 7.** Reserved for future per-valve positional override. Debug-logged only. |
| `child.register` | `registerChild` | `string` (child node id) | Manually register a child via `RED.nodes.getNode`; Port 2 wiring does this automatically in most flows. |
| `cmd.execSequence` | `execSequence` | `{ source, action, parameter }` | Forward to `source.handleInput(source, action, parameter)` &mdash; runs a group-wide sequence (`startup` / `shutdown` / `emergencystop` / `boot`). |
| `data.totalFlow` | `totalFlowChange` | number, `{ value, position?, variant?, unit? }`, or `{ source, action, ... }` | Update the total measured/predicted flow at the configured position; triggers `calcValveFlows` to re-distribute across valves. |
| `cmd.emergencyStop` | `emergencyStop`, `emergencystop` | optional `{ source }` | Run the `emergencystop` sequence on all valves. |
| `set.reconcileInterval` | `setReconcileInterval` | number &mdash; seconds (> 0) | Re-tune the periodic flow-reconciliation interval. Min clamp 100 ms. |
Aliases log a one-time deprecation warning the first time they fire.
---
## What you'll see come out
Sample Port 0 message (delta-compressed, after a `data.totalFlow = 80` split across two valves):
```json
{
"topic": "valveGroupControl#VGC1",
"payload": {
"mode": "auto",
"maxDeltaP": 1450,
"atEquipment_measured_flow": 80,
"atEquipment_predicted_flow": 80,
"deltaMax_predicted_pressure": 1450
}
}
```
Key shape: **`<position>_<variant>_<type>`** &mdash; same as MGC's key shape (inverse of `rotatingMachine`'s per-measurement form). The output reflects the group aggregate, not per-valve snapshots; per-valve detail comes off each valve's own Port 0.
| Field | Meaning |
|:---|:---|
| `mode` | Current operational mode (`auto` / `virtualControl` / `fysicalControl` / `maintenance`). |
| `maxDeltaP` | Max delta-P across registered valves &mdash; refreshed whenever a child emits `deltaPChange`. Also surfaced as `deltaMax_predicted_pressure` via the measurement container. |
| `atEquipment_measured_flow` | Total measured flow at the group inlet (from an upstream source's `flow.measured.*` event). |
| `atEquipment_predicted_flow` | Sum of per-valve accepted flows after the Kv-share + residual pass. |
| `deltaMax_predicted_pressure` | Max delta-P across the group, written via the measurement container at position `delta` / variant `predicted` / type `pressure`. |
---
## Flow-distribution loop &mdash; what one event does
When a `data.totalFlow` arrives (or an upstream source publishes `flow.predicted.*` / `flow.measured.*`), VGC re-distributes by Kv share:
```mermaid
flowchart LR
src[data.totalFlow /<br/>upstream source event] --> upd[updateFlow<br/>predicted/measured atEquipment]
upd --> avail[getAvailableValves<br/>state &ne; off/maintenance, kv > 0]
avail --> solve[solveFlowDistribution<br/>share by Kv / totalKv]
solve --> push[valve.updateFlow predicted<br/>downstream]
push --> readback[read accepted from<br/>flow.predicted.downstream]
readback --> residual[residual = target &minus; sum&#40;accepted&#41;]
residual -->|residual &gt; tol & passes &lt; max| solve
residual --> writeback[write flow.predicted.atEquipment<br/>= sum&#40;accepted&#41;]
writeback --> dp[calcMaxDeltaP]
dp --> emit[notifyOutputChanged]
```
Reconciliation defaults (`flowReconciliation`):
| Field | Default | Notes |
|:---|:---:|:---|
| `maxPasses` | `2` | Max iterations of the residual-correction loop. |
| `residualTolerance` | `0.001` | Stops the loop when `|residual| <` tolerance (canonical units &mdash; m³/s for flow). |
A valve is **available** if: `state.getCurrentState() !== 'off'` and `!== 'maintenance'`, `currentMode !== 'maintenance'`, and `kv > 0`. Unavailable valves are skipped and receive `updateFlow('predicted', 0, 'downstream')`.
VGC has **no FSM of its own** &mdash; state semantics belong to the child valves. `specificClass` instantiates a state object internally and stamps it `operational` at boot for sequence dispatch; the group's only coordination loop is the Kv-share solver above.
---
## Need more?
| Page | What you'll find |
|:---|:---|
| [Reference &mdash; Contracts](Reference-Contracts) | Topic registry, config schema, child-registration filters |
| [Reference &mdash; Architecture](Reference-Architecture) | Code map, flow-distribution loop, source aggregation, output ports |
| [Reference &mdash; Examples](Reference-Examples) | Shipped flows, debug recipes |
| [Reference &mdash; Limitations](Reference-Limitations) | When not to use, known issues, open questions |
[EVOLV master wiki](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Home) &middot; [Topology Patterns](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Topology-Patterns) &middot; [Topic Conventions](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Topic-Conventions)

View File

@@ -0,0 +1,238 @@
# Reference &mdash; Architecture
![code-ref](https://img.shields.io/badge/code--ref-b20a573-blue)
> [!NOTE]
> Pending full node review (2026-05). Content reflects `CONTRACT.md` and current source only.
>
> Code structure for `valveGroupControl`: the three-tier sandwich, the `src/` concern modules, the Kv-share flow-distribution loop, the source aggregation pipeline, the tick / event lifecycle, and the output-port shape. For an intuitive overview, return to [Home](Home).
---
## Three-tier code layout
```
nodes/valveGroupControl/
|
+-- vgc.js entry: RED.nodes.registerType('valveGroupControl', NodeClass)
| (LEGACY NAME — should be valveGroupControl.js; see Limitations)
+-- vgc.html editor HTML (LEGACY NAME — should be valveGroupControl.html)
|
+-- src/
| nodeClass.js extends BaseNodeAdapter (Node-RED bridge, tick loop)
| specificClass.js extends BaseDomain (orchestration: valve + source routing)
| |
| +-- commands/
| | index.js topic descriptors (canonical + aliases)
| | handlers.js pure handler functions
| |
| +-- groupOps/
| | flowDistribution.js Kv-share solver, residual pass, calcMaxDeltaP, isValveAvailable
| |
| +-- sources/
| | fluidContract.js upstream-source registration, flow-event binding, fluid-contract reconciliation
| |
| +-- io/
| output.js getOutput() + getStatusBadge()
```
### Tier responsibilities
| Tier | File | What it owns | Touches `RED.*` |
|:---|:---|:---|:---:|
| entry | `vgc.js` (legacy filename) | Type registration | Yes |
| nodeClass | `src/nodeClass.js` | Periodic tick (`tickInterval = 1000` ms), status badge (`statusInterval = 1000` ms), tick restart on `reconcileIntervalChange`. `buildDomainConfig()` returns `{}` (no domain overrides). | Yes |
| specificClass | `src/specificClass.js` | Wire concern modules in `configure()`; router callbacks for `valve` + the 4 source softwareTypes; `_bindValveEvents` / `_unbindValveEvents`; mode/sequence dispatch via `handleInput`; expose `calcValveFlows`, `calcMaxDeltaP`, `getFluidContract`, `getOutput`, `getStatusBadge`. | No |
`specificClass` is stitching. All real work lives in the concern modules: Kv-share + residual + max-deltaP in `groupOps/`; upstream-source registration + fluid-contract reconciliation in `sources/`; output shape in `io/`.
---
## What VGC does NOT have
- **No FSM of its own.** `specificClass.configure()` instantiates `new state({}, this.logger)` and stamps `this.state.stateManager.currentState = 'operational'` immediately so `executeSequence` works for group-wide sequences. State semantics belong to the child valves.
- **No predictors / curves.** Unlike `rotatingMachine`, VGC has no asset model, no characteristic curve, no prediction pipeline. The only "prediction" written is the per-valve assigned flow from the Kv-share solver.
- **No drift assessment.** No EWMA, no NRMSE, no `predictionHealth`. The Port 0 emits only `mode`, `maxDeltaP`, and per-position flow / pressure keys.
---
## Flow-distribution loop
The core coordination loop. VGC has no per-tick prediction recompute &mdash; the tick just re-runs `calcValveFlows()` to absorb any drift between event-driven recalcs.
```mermaid
sequenceDiagram
autonumber
participant src as upstream source / data.totalFlow
participant vgc as VGC
participant solver as solveFlowDistribution
participant valves as valve children
participant out as Port 0 / 1
src->>vgc: flow.predicted.downstream (m3/h) OR data.totalFlow
vgc->>vgc: updateFlow('predicted'|'measured', value, 'atEquipment')
vgc->>vgc: _write flow at position 'atEquipment'
vgc->>vgc: calcValveFlows()
vgc->>solver: target=totalFlow, entries=availableValves, recon
loop &le; maxPasses while |residual| > tol
solver->>valves: updateFlow('predicted', share, 'downstream')
valves-->>solver: read accepted (flow.predicted.downstream)
solver->>solver: residual = target sum(accepted)
end
solver-->>vgc: { flowsById, residual, passes }
vgc->>vgc: _write flow.predicted.atEquipment = sum(accepted)
vgc->>vgc: calcMaxDeltaP()
vgc->>out: notifyOutputChanged() → Port 0 / 1
valves-->>vgc: positionChange / deltaPChange (drives next calcValveFlows / calcMaxDeltaP)
```
### Availability filter
A valve participates in the split if **all** are true (`groupOps/flowDistribution.isValveAvailable`):
| Condition | Source |
|:---|:---|
| `valve.state.getCurrentState() !== 'off'` | child FSM |
| `valve.state.getCurrentState() !== 'maintenance'` | child FSM |
| `valve.currentMode !== 'maintenance'` | child mode |
| `Number.isFinite(valve.kv) && valve.kv > 0` | child config |
Unavailable valves still receive `updateFlow('predicted', 0, 'downstream', flowUnit)` so their state is consistent &mdash; they are simply excluded from the solver.
### Residual reconciliation
`flowReconciliation` defaults (`groupOps/flowDistribution.DEFAULT_RECONCILIATION`):
| Field | Default | Effect |
|:---|:---:|:---|
| `maxPasses` | `2` | Bound on the correction loop. The first pass distributes by `share = (kv / totalKv) * residual`; subsequent passes correct for the residual between target and accepted total. |
| `residualTolerance` | `0.001` | Loop exits when `|residual| < tolerance`. Units are canonical (m³/s for flow). |
After the loop:
- `lastFlowSolve = { passes, residual, targetTotal, assignedTotal }` is stamped on the domain for telemetry / debug.
- `flow.predicted.atEquipment` is written equal to `assignedTotal` (sum of per-valve accepted).
- `calcMaxDeltaP` re-reads every valve's `pressure.predicted.delta` and stores `vgc.maxDeltaP` plus `pressure.predicted.deltaMax` in the measurement container.
### Pathological-curve case
If `totalKv <= 0` or no valves are available, every valve is pushed `0`, `flow.predicted.atEquipment` is written `0`, and `lastFlowSolve` records `passes: 0, residual: target, assignedTotal: 0`. The status badge flips to `'No valves'` (red dot).
---
## Source aggregation
Upstream nodes register as **sources** (not children that VGC controls). Source softwareTypes accepted by `_registerSource`:
| Registered as (canonical) | Original softwareType examples |
|:---|:---|
| `machine` | `rotatingmachine` (canonicalised by `BaseDomain.router`) |
| `machinegroup` | `machinegroupcontrol` (canonicalised) |
| `pumpingstation` | `pumpingstation` |
| `valvegroupcontrol` | `valvegroupcontrol` (cascaded VGC; see Limitations) |
For each source `bindSource` attaches listeners to **six** flow event names on the source's `measurements.emitter`:
```
flow.predicted.downstream
flow.predicted.atEquipment
flow.predicted.atequipment
flow.measured.downstream
flow.measured.atEquipment
flow.measured.atequipment
```
The handler routes any of these to `vgc.updateFlow(variant, value, 'atEquipment', unit)`. Position-label case variants are caught explicitly &mdash; the source may publish either `atEquipment` or `atequipment` and the router normalises both into the same internal write.
### Fluid contract aggregation
Each source contributes a fluid contract (`liquid` / `gas` / `conflict` / `unknown`). `extractFluidContract`:
1. Calls `child.getFluidContract()` if present. A `conflict` status short-circuits to group conflict.
2. Falls back to a normalised `serviceType` from the child / asset config.
3. Falls back to a defaults table (`DEFAULT_SOURCE_SERVICE_TYPE` &mdash; everything maps to `liquid` except where overridden).
`refreshFluidContract` aggregates across all registered sources:
| Aggregate status | When |
|:---|:---|
| `conflict` | Any source's contract is `conflict`, OR more than one distinct `serviceType` is present. |
| `resolved` | Exactly one distinct `serviceType` across all sources. |
| `unknown` | No sources registered. |
Changes emit `fluidContractChange` on `vgc.emitter` so downstream consumers (a valve checking compatibility, another VGC) can react.
---
## Lifecycle &mdash; tick + event sources
| Source | Where it fires | What it triggers |
|:---|:---|:---|
| Periodic tick | `nodeClass` `setInterval(tickInterval = 1000 ms)` | `source.tick()` &rarr; `calcValveFlows()` &rarr; `notifyOutputChanged()`. |
| Child `state.emitter` `'positionChange'` | per child valve | `onPositionChange` &rarr; `calcValveFlows()`. |
| Child `emitter` `'deltaPChange'` | per child valve | `onDeltaPChange` &rarr; `calcMaxDeltaP()`. |
| Source `measurements.emitter` flow events | per upstream source | `updateFlow(variant, value, 'atEquipment', unit)`. |
| Source `emitter` `'fluidContractChange'` | per upstream source | Re-read source contract; `refreshFluidContract`. |
| `source.emitter` `'reconcileIntervalChange'` | `setReconcileIntervalSeconds` | `nodeClass._restartTick(ms)` &mdash; clears + re-schedules tick. |
| Inbound `msg.topic` | Node-RED input wire | `commandRegistry` dispatch (see [Contracts](Reference-Contracts#topic-contract)). |
| `setInterval(statusInterval = 1000 ms)` | `BaseNodeAdapter` | Status badge re-render. |
`tick()` itself is one line &mdash; `this.calcValveFlows()`. It exists so a child's accepted flow drift between event-driven recalcs gets re-absorbed.
---
## Output ports
| Port | Carries | Sample shape |
|:---|:---|:---|
| 0 (process) | Delta-compressed snapshot &mdash; `mode`, `maxDeltaP`, per-position flow/pressure keys | `{topic, payload: {mode, maxDeltaP, atEquipment_predicted_flow, ...}}` |
| 1 (telemetry) | InfluxDB line-protocol payload (same fields as Port 0) | `valveGroupControl,id=VGC1 mode="auto",maxDeltaP=1450,atEquipment_predicted_flow=80,...` |
| 2 (register / control) | `child.register` upward at startup | `{topic: 'child.register', payload: <node.id>, positionVsParent}` |
Port-0 key shape is **`<position>_<variant>_<type>`** (same as MGC) &mdash; written in `io/output.getOutput()` by walking `measurements.measurements` and emitting only keys whose `getCurrentValue()` is non-null. Plus the two scalar keys `mode` and `maxDeltaP`.
> [!IMPORTANT]
> See `.claude/rules/output-coverage.md` &mdash; every output should be enumerated in a `test/_output-manifest.md` and tested in both populated and degraded states. **Not yet produced** for VGC; tracked as backfill in `.agents/improvements/IMPROVEMENTS_BACKLOG.md` (TODO).
---
## Events emitted on `source.emitter` / `source.measurements.emitter`
| Event | Emitter | Fires when |
|:---|:---|:---|
| `output-changed` | `source.emitter` | Public output state shifted; adapter listens and pushes Ports 0/1. |
| `fluidContractChange` | `source.emitter` | Group-level fluid contract (status / serviceType / sourceCount) changed. |
| `reconcileIntervalChange` | `source.emitter` | `setReconcileIntervalSeconds` was called; adapter restarts the tick loop. |
| `flow.predicted.atequipment` | `source.measurements.emitter` | Group predicted flow changed (post-solve). |
| `pressure.predicted.deltaMax` | `source.measurements.emitter` | Group max delta-P changed. |
The exact emitter set is data-driven by what valves and sources publish.
---
## Where to start reading
| If you're changing&hellip; | Read first |
|:---|:---|
| Kv-share solver, residual pass, availability filter | `src/groupOps/flowDistribution.js` |
| `calcMaxDeltaP` aggregation | `src/groupOps/flowDistribution.js` `calcMaxDeltaP` |
| Upstream-source registration, flow-event names, fluid contract | `src/sources/fluidContract.js` |
| Valve event binding / unbinding | `src/specificClass.js` `_bindValveEvents` / `_unbindValveEvents` |
| Mode validation, sequence dispatch | `src/specificClass.js` `setMode` / `executeSequence` / `handleInput` |
| Reconcile-interval re-tuning | `src/specificClass.js` `setReconcileIntervalSeconds` + `src/nodeClass.js` `_restartTick` |
| Topic registration, payload validation, alias deprecation | `src/commands/index.js` + `src/commands/handlers.js` |
| Port-0 output keys, status badge | `src/io/output.js` |
---
## Related pages
| Page | Why |
|:---|:---|
| [Home](Home) | Intuitive overview |
| [Reference &mdash; Contracts](Reference-Contracts) | Topic + config + child filters |
| [Reference &mdash; Examples](Reference-Examples) | Shipped flows + debug recipes |
| [Reference &mdash; Limitations](Reference-Limitations) | Known issues and open questions |
| [machineGroupControl wiki](https://gitea.wbd-rd.nl/RnD/machineGroupControl/wiki/Home) | The sibling Unit-level group controller for pumps |
| [valve wiki](https://gitea.wbd-rd.nl/RnD/valve/wiki/Home) | The child node VGC coordinates |
| [EVOLV &mdash; Architecture](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Architecture) | Platform-wide three-tier pattern |

257
wiki/Reference-Contracts.md Normal file
View File

@@ -0,0 +1,257 @@
# Reference &mdash; Contracts
![code-ref](https://img.shields.io/badge/code--ref-b20a573-blue)
> [!NOTE]
> Pending full node review (2026-05). Content reflects `CONTRACT.md` and current source only.
>
> Full topic contract, configuration schema, and child-registration filters for `valveGroupControl`. Source of truth: `src/commands/index.js`, `src/specificClass.js` `configure()`, and the schema at `generalFunctions/src/configs/valveGroupControl.json`.
>
> For an intuitive overview, return to the [Home](Home).
---
## Topic contract
The registry lives in `src/commands/index.js`. Each descriptor maps a canonical `msg.topic` to its handler; aliases emit a one-time deprecation warning the first time they fire.
<!-- BEGIN AUTOGEN: topic-contract -->
| Canonical topic | Aliases | Payload | Unit | Effect |
|---|---|---|---|---|
| `set.mode` | `setMode` | `string` | — | Switch the operating mode. Allowed: `auto`, `virtualControl`, `fysicalControl`, `maintenance` (schema-validated in `valveGroupControl.json``mode.current`). |
| `set.position` | `setpoint` | any | — | Set the group-level valve position (currently a no-op pending Phase 7). |
| `child.register` | `registerChild` | `string` | — | Register a child valve with this group. |
| `cmd.execSequence` | `execSequence` | `object` | — | Run a group-wide sequence (startup / shutdown / emergencystop). |
| `data.totalFlow` | `totalFlowChange` | any | — | Notify the group that the total flow setpoint has changed. |
| `cmd.emergencyStop` | `emergencyStop`, `emergencystop` | any | — | Trigger an emergency stop across all valves in the group. |
| `set.reconcileInterval` | `setReconcileInterval` | any | — | Update the reconciliation interval (seconds). |
<!-- END AUTOGEN: topic-contract -->
### Mode / source allow-lists
A topic that survives the registry still passes through `flowController` &rarr; `handleInput`, which enforces:
```js
if (!host.isValidSourceForMode(source, host.currentMode)) {
this.logger.warn(`Source '${source}' is not valid for mode '${this.currentMode}'.`);
return { status: false, feedback: ... };
}
```
Defaults from the schema:
| Mode | `allowedActions` | `allowedSources` |
|:---|:---|:---|
| `auto` | `statusCheck, execSequence, emergencyStop, valvePositionChange, totalFlowChange, valveDeltaPchange` | `parent, GUI, fysical` |
| `virtualControl` | `statusCheck, execSequence, emergencyStop, valvePositionChange, totalFlowChange, valveDeltaPchange` | `GUI, fysical` |
| `fysicalControl` | `statusCheck, emergencyStop` | `fysical` |
| `maintenance` | `statusCheck` | (schema does NOT define `allowedSources.maintenance`; `isValidSourceForMode` returns `false` for every source &mdash; effectively monitoring-only) |
> [!WARNING]
> **Source contradiction:** `CONTRACT.md` describes `set.mode` as switching between "auto / manual control modes", but the schema defines four modes (`auto` / `virtualControl` / `fysicalControl` / `maintenance`) and `specificClass.setMode` validates against the schema's enum. The wider four-mode set is the implementation. TODO: tighten the prose in `CONTRACT.md` to enumerate the schema modes.
> [!WARNING]
> **Source contradiction:** the schema declares an `mode.allowedActions` table, but the running implementation only consults `isValidSourceForMode` &mdash; **`isValidActionForMode` is not implemented on VGC**. Action allow-lists are effectively dead config. TODO: either implement the action check (mirroring `rotatingMachine`'s pattern) or remove `allowedActions` from the schema.
---
## Data model &mdash; `getOutput()` shape
Composed each tick by `src/io/output.getOutput()`. Delta-compressed: consumers see only keys whose `getCurrentValue()` is non-null.
<!-- BEGIN AUTOGEN: data-model — populate via wiki-gen tool (TODO) -->
### Scalar keys
| Key | Type | Source | Notes |
|:---|:---|:---|:---|
| `mode` | string | `vgc.currentMode` | `auto` / `virtualControl` / `fysicalControl` / `maintenance`. |
| `maxDeltaP` | number | `vgc.maxDeltaP` | Cached max delta-P over registered valves (in output pressure unit, default `mbar`). Same data is also surfaced via the measurement-derived key `deltaMax_predicted_pressure`. |
### Measurement-derived keys
For every `(type, variant, position)` in MeasurementContainer with a finite value, the flattened output emits:
```
<position>_<variant>_<type>
```
| Example key | Unit | Source | Notes |
|:---|:---|:---|:---|
| `atEquipment_measured_flow` | m³/h | upstream source `flow.measured.*` events; `data.totalFlow` with `variant=measured` | Total measured flow at the group inlet. |
| `atEquipment_predicted_flow` | m³/h | written by `distributeFlow` as `sum(accepted)` | Sum of per-valve accepted flows after Kv-share + residual. |
| `deltaMax_predicted_pressure` | mbar | written by `calcMaxDeltaP` | Max `pressure.predicted.delta` across registered valves. |
> Delta compression: only changed fields are sent per tick. Consumers must cache and merge. See `outputUtils.formatMsg`.
<!-- END AUTOGEN -->
### Status badge
`io/output.getStatusBadge`:
```
<mode> | flow=<int> <flowUnit> | <N> valve(s) connected | (or 'No valves')
```
| State | Fill |
|:---|:---|
| `getAvailableValves().length > 0` | green dot |
| `getAvailableValves().length === 0` | red dot |
`flow` is the rounded `flow.measured.atEquipment`, or `flow.predicted.atEquipment` if no measured value is available.
---
## Configuration schema &mdash; editor form to config keys
Source of truth: `generalFunctions/src/configs/valveGroupControl.json` plus `nodeClass.buildDomainConfig` (which returns `{}` &mdash; no domain overrides).
### General (`config.general`)
| Form field | Config key | Default | Notes |
|:---|:---|:---|:---|
| Name | `general.name` | `"ValveGroupControl"` | Node label, status badge prefix (via `topic`). |
| (auto-assigned) | `general.id` | `null` | Node-RED node id. |
| Default unit | `general.unit` | `"unitless"` (schema) / `m3/h` (`configure()` overrides via `unitPolicy.output('flow')`) | Re-derived in `configure()`. |
| Enable logging | `general.logging.enabled` | `true` | Master switch. |
| Log level | `general.logging.logLevel` | `info` | `debug` / `info` / `warn` / `error`. |
### Functionality (`config.functionality`)
| Form field | Config key | Default | Notes |
|:---|:---|:---|:---|
| Position vs parent | `functionality.positionVsParent` | `""` (per `CONTRACT.md`) | Used in the Port-2 register payload sent to the upstream parent. (Not in the JSON schema; supplied at runtime from the editor.) |
| (hidden) | `functionality.softwareType` | `"valvegroupcontrol"` | Constant. |
| (hidden) | `functionality.role` | `"ValveGroupController"` | Constant. |
### Asset (`config.asset`)
VGC's asset block is informational &mdash; there is no curve to load, no model registry, no allowed-unit validation.
| Form field | Config key | Default | Notes |
|:---|:---|:---|:---|
| Asset UUID | `asset.uuid` | `null` | Globally-unique identifier. |
| Geolocation | `asset.geoLocation` | `{x:0, y:0, z:0}` | |
| Supplier | `asset.supplier` | `"Unknown"` | Informational. |
| Type | `asset.type` | `"valve"` | Classification only. |
| Sub-type | `asset.subType` | `"Unknown"` | |
| Model | `asset.model` | `"Unknown"` | Informational; no registry lookup. |
| Accuracy | `asset.accuracy` | `null` | |
### Mode (`config.mode`)
| Form field | Config key | Default | Range | Notes |
|:---|:---|:---|:---|:---|
| Mode | `mode.current` | `auto` | `auto` / `virtualControl` / `fysicalControl` / `maintenance` | The active operational mode. |
| (defaults) | `mode.allowedActions.<mode>` | see [Mode allow-lists](#mode--source-allow-lists) | enforced by `flowController` (NOT implemented &mdash; see warning above) |
| (defaults) | `mode.allowedSources.<mode>` | see [Mode allow-lists](#mode--source-allow-lists) | enforced by `isValidSourceForMode` |
### Sequences (`config.sequences`)
Per-sequence state-transition lists. Defaults:
| Sequence | States |
|:---|:---|
| `startup` | `[starting, warmingup, operational]` |
| `shutdown` | `[stopping, coolingdown, idle]` |
| `emergencystop` | `[emergencystop, off]` |
| `boot` | `[idle, starting, warmingup, operational]` |
`executeSequence(name)` iterates the list and awaits `state.transitionToState(stateName)` per step. The default state object is created at boot with `currentState = 'operational'` so `executeSequence` works without a pre-warmup phase. (See [Architecture &mdash; What VGC does NOT have](Reference-Architecture#what-vgc-does-not-have).)
### Calculation mode (`config.calculationMode`)
| Value | Description |
|:---|:---|
| `low` | Calculations run at fixed intervals (time-based). |
| `medium` (default) | Calculations run when new setpoints arrive or measured changes occur (event-driven). |
| `high` | Calculations run on all event-driven info, including every movement. |
> [!WARNING]
> `calculationMode` is in the schema but is not currently consulted by `specificClass` or `nodeClass`. The tick interval is fixed at `tickInterval = 1000 ms` and only retunable through `set.reconcileInterval`. TODO: wire `calculationMode` through or remove it.
### Flow reconciliation (runtime only)
`flowReconciliation` lives on the domain (not in the schema):
| Field | Default | Notes |
|:---|:---:|:---|
| `maxPasses` | `2` | Max iterations of the Kv-share residual loop. |
| `residualTolerance` | `0.001` | Stops loop when `|residual| < tolerance` (canonical units). |
These are read by `solveFlowDistribution` each call; not currently exposed via a topic or editor field.
### Unit policy
Source: `src/specificClass.js`.
| Quantity | Canonical (internal) | Output (rendered) | Required-unit |
|:---|:---|:---|:---:|
| Flow | `m3/s` | `m3/h` | ✓ |
| Pressure | `Pa` | `mbar` | ✓ |
`requireUnitForTypes: ['pressure', 'flow']` &mdash; MeasurementContainer rejects writes that omit `unit` for these types.
---
## Child registration
Source: `src/specificClass.js` `_registerValve` / `_registerSource` and `src/sources/fluidContract.js`.
| Software type | Filter | Wired to | Side-effect |
|:---|:---|:---|:---|
| `valve` | `child` exposes `updateFlow`, `state.getCurrentState`, `measurements` (`_isValveLike`) | Stored in `vgc.valves[id]`; events bound. | Subscribes to `state.emitter.positionChange` (&rarr; `calcValveFlows`) and `emitter.deltaPChange` (&rarr; `calcMaxDeltaP`). Triggers an initial `calcValveFlows` + `calcMaxDeltaP` + `refreshFluidContract`. |
| `machine` (incl. canonicalised `rotatingmachine`) | router callback | `registerSource` (`sources/fluidContract`) | Subscribes to 6 flow event names on `child.measurements.emitter`; subscribes to `child.emitter.fluidContractChange`. |
| `machinegroup` (incl. canonicalised `machinegroupcontrol`) | router callback | `registerSource` | Same as `machine`. |
| `pumpingstation` | router callback | `registerSource` | Same as `machine`. |
| `valvegroupcontrol` | router callback | `registerSource` | Cascaded VGC; accepted by router. Not exercised in production &mdash; see [Limitations](Reference-Limitations#cascaded-vgc-not-test-covered). |
Position labels accepted from children are `upstream`, `downstream`, `atEquipment` (and case variants &mdash; normalised internally).
### Source flow events
`bindSource` attaches a listener for every event name in `SOURCE_FLOW_EVENTS`:
```
flow.predicted.downstream
flow.predicted.atEquipment
flow.predicted.atequipment
flow.measured.downstream
flow.measured.atEquipment
flow.measured.atequipment
```
The handler reads `eventData.value` (number) and `eventData.unit` and writes `vgc.updateFlow(variant, value, 'atEquipment', unit)`. `variant` is derived from the event-name middle segment (`measured` vs `predicted`).
### Fluid contract reconciliation
See [Architecture &mdash; Source aggregation](Reference-Architecture#fluid-contract-aggregation) for the full reconciliation logic. The aggregated `fluidContract` is exposed via `vgc.getFluidContract()`:
```json
{
"status": "resolved" | "conflict" | "inferred" | "unknown",
"serviceType": "liquid" | "gas" | null,
"upstreamServiceTypes": ["liquid"],
"sourceCount": 2,
"message": "Upstream fluid resolved as liquid.",
"source": "valvegroupcontrol"
}
```
Changes are broadcast via `source.emitter.emit('fluidContractChange', ...)`.
---
## Related pages
| Page | Why |
|:---|:---|
| [Home](Home) | Intuitive overview |
| [Reference &mdash; Architecture](Reference-Architecture) | Code map, flow-distribution loop, source aggregation |
| [Reference &mdash; Examples](Reference-Examples) | Shipped flows + debug recipes |
| [Reference &mdash; Limitations](Reference-Limitations) | Known issues and open questions |
| [EVOLV &mdash; Topic Conventions](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Topic-Conventions) | Platform-wide topic rules |
| [EVOLV &mdash; Telemetry](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Telemetry) | Port 0 / 1 / 2 InfluxDB layout |

157
wiki/Reference-Examples.md Normal file
View File

@@ -0,0 +1,157 @@
# Reference &mdash; Examples
![code-ref](https://img.shields.io/badge/code--ref-b20a573-blue)
> [!NOTE]
> Pending full node review (2026-05). Content reflects `CONTRACT.md` and current source only.
>
> Every example flow shipped under `nodes/valveGroupControl/examples/`, plus how to load them, what they show, and the debug recipes that go with them. Live source: `nodes/valveGroupControl/examples/`.
---
## Shipped examples
| File | Tier | Dependencies | What it shows |
|:---|:---:|:---|:---|
| `basic.flow.json` | 1 | EVOLV only | Inject `data.totalFlow` + 2 `valve` children registered as the group. No parent. Verifies Kv-share split and residual reconciliation. |
| `integration.flow.json` | 2 | EVOLV only | VGC + 2 valves + one upstream `rotatingMachine` source. Source's `flow.predicted.*` events drive the group; fluid-contract aggregation resolves to `liquid`. |
| `edge.flow.json` | 3 | EVOLV only | Edge cases: no valves available, residual non-convergence, cascaded VGC as upstream source. Currently a structural placeholder &mdash; TODO consult `examples/edge.flow.json` for actual scenarios. |
> [!IMPORTANT]
> The Tier-1 / Tier-2 / Tier-3 naming convention (`01 - <name>.json`) used by `rotatingMachine` has **not yet been applied** to VGC. Filenames are still the legacy `basic`/`integration`/`edge` triad. Migration tracked in `.agents/improvements/IMPROVEMENTS_BACKLOG.md`. When renaming, update `examples/README.md` in the same commit.
---
## Loading a flow
### Via the editor
1. Open the Node-RED editor at `http://localhost:1880`.
2. Menu &rarr; Import &rarr; drag the JSON file.
3. Click Deploy.
### Via the Admin API
```bash
curl -X POST -H 'Content-Type: application/json' \
--data @"nodes/valveGroupControl/examples/basic.flow.json" \
http://localhost:1880/flows
```
---
## Example: basic.flow.json
> [!IMPORTANT]
> **TODO: not yet validated against live Node-RED.** Steps below are inferred from `CONTRACT.md` + the topic registry. Consult `examples/basic.flow.json` directly for exact node ids and inject payloads. Screenshot needed once validated &mdash; save under `wiki/_partial-screenshots/valveGroupControl/01-basic-editor.png`.
Single VGC with 2 `valve` children. Demonstrates:
1. Wire each valve's Port 2 to VGC's input so `child.register` arrives automatically on deploy.
2. Inject `data.totalFlow` with payload `{ value: 80, unit: "m3/h", position: "atEquipment", variant: "measured" }`. VGC runs `calcValveFlows`:
- Splits 80 m³/h by Kv share across the 2 valves.
- Each valve's `updateFlow('predicted', share, 'downstream')` push.
- Re-reads each valve's accepted `flow.predicted.downstream`.
- Residual loop runs up to `maxPasses: 2` until `|residual| < 0.001`.
3. Watch Port 0 debug: `atEquipment_predicted_flow` settles at the assigned total; `deltaMax_predicted_pressure` updates as each valve emits `deltaPChange`.
4. Toggle one valve to `off` &mdash; the next `data.totalFlow` (or tick) routes 100% to the remaining valve.
5. Set the offlined valve back to operational &mdash; the next tick re-includes it in the split.
### Try the residual pass
After the group settles at `80 m³/h`:
1. Inject `data.totalFlow = 200` (a value beyond aggregate Kv capacity). Watch `lastFlowSolve.residual` &mdash; it stays large because the valves cap at their accept limits. `flow.predicted.atEquipment` will read the sum of caps, not 200.
2. Inject `data.totalFlow = 0`. Every valve receives `updateFlow('predicted', 0, 'downstream')`; `maxDeltaP` collapses to 0.
---
## Example: integration.flow.json
> [!IMPORTANT]
> **TODO: not yet validated.** Screenshot needed once validated &mdash; save under `wiki/_partial-screenshots/valveGroupControl/02-integration-editor.png`.
VGC + 2 valves + 1 upstream `rotatingMachine`. Demonstrates:
- Source registration: the rotatingMachine's `child.register` (softwareType `rotatingmachine` &rarr; canonical `machine`) lands on VGC; `_registerSource` subscribes to `flow.predicted.downstream`, `flow.measured.downstream`, etc.
- Source-driven flow: a pump-state change emits `flow.predicted.downstream`; VGC's handler converts to `updateFlow('predicted', value, 'atEquipment', unit)` and re-runs `calcValveFlows`.
- Fluid-contract resolution: the pump's `getFluidContract()` (or fallback `DEFAULT_SOURCE_SERVICE_TYPE.rotatingmachine = 'liquid'`) produces `serviceType: 'liquid'`; `fluidContract` resolves to `{status: 'resolved', serviceType: 'liquid'}`.
---
## Example: edge.flow.json
> [!IMPORTANT]
> **TODO: structural placeholder.** Consult the JSON directly for the scenarios it currently exercises. The edge scenarios this node ought to test (per `CONTRACT.md` + source review):
>
> - **No available valves** &mdash; all in `off` / `maintenance`. Expected: status badge `'No valves'` red, every valve pushed `0`, `lastFlowSolve.assignedTotal = 0`.
> - **Residual non-convergence** &mdash; valve curve where Kv-share is a bad first estimate. Expected: loop exits after `maxPasses: 2` with non-zero residual; assignedTotal &lt; target; behaviour graceful.
> - **Cascaded VGC** &mdash; upstream source is another VGC. Expected: source registered, `flow.*` events bound, `getFluidContract()` propagated up. **Not exercised in production.**
> - **Conflicting fluid contracts** &mdash; two sources advertise `liquid` vs `gas`. Expected: `fluidContract.status = 'conflict'`; `fluidContractChange` event emitted.
---
## Docker compose snippet
To bring up Node-RED + InfluxDB with EVOLV nodes pre-loaded:
```yaml
# docker-compose.yml (extract)
services:
nodered:
build: ./docker/nodered
ports: ['1880:1880']
volumes:
- ./docker/nodered/data:/data/evolv
influxdb:
image: influxdb:2.7
ports: ['8086:8086']
```
Full file: [EVOLV/docker-compose.yml](https://gitea.wbd-rd.nl/RnD/EVOLV/src/branch/development/docker-compose.yml).
---
## Debug recipes
| Symptom | First thing to check | Where to look |
|:---|:---|:---|
| All valves receive `assigned flow = 0` | `getAvailableValves()` returns empty list: check every valve's state (`off` / `maintenance` excludes), `currentMode !== 'maintenance'`, and `kv > 0`. | `src/groupOps/flowDistribution.isValveAvailable` |
| Residual never converges | Pathological valve curve: Kv-share is a bad first estimate. Check `vgc.lastFlowSolve.residual` and `.passes` &mdash; if `passes === maxPasses` and residual is large, the loop ran out. Raise `flowReconciliation.maxPasses` (no editor field yet &mdash; TODO Phase 7). | `src/groupOps/flowDistribution.solveFlowDistribution` |
| Group `maxDeltaP` stale | Child `deltaPChange` not subscribed: valve emitter not exposed via `child.emitter`, or valve never registered. | `src/specificClass._bindValveEvents` |
| Service-type stays `unknown` | No upstream source registered, or all advertise unknown type. Check `vgc.sources` &mdash; if empty, no Port-2 child.register reached VGC. | `src/sources/fluidContract.refreshFluidContract` |
| `data.totalFlow` silently ignored | Mode rejects the source id: check `mode.allowedSources` for the current mode. `maintenance` rejects every source. Warn in log: `Source '<src>' is not valid for mode '<mode>'.` | `src/specificClass.isValidSourceForMode` |
| `set.position` has no effect | Known: handler is a debug-logged no-op pending Phase 7. See [Limitations](Reference-Limitations#set-position-is-a-no-op). | `src/commands/handlers.setPosition` |
| `set.reconcileInterval = 0` (or negative) silently does nothing | The handler validates `Number.isFinite(nextSec) && nextSec > 0`. Otherwise warns and returns. | `src/commands/handlers.setReconcileInterval` |
| Two emitters fight on the same flow channel (one source publishes `atEquipment`, another publishes `atequipment`) | Both event names are wired; the **last write wins** on each `updateFlow`. There is no source-priority logic. | `src/sources/fluidContract.SOURCE_FLOW_EVENTS` |
| Cascaded VGC not propagating flow | Accepted by router, but no tests &mdash; treat as experimental. | `src/sources/fluidContract.SOURCE_SOFTWARE_TYPES` |
| Output port-0 key shape differs from rotatingMachine's | VGC uses `<position>_<variant>_<type>` (same as MGC) &mdash; the inverse of rotatingMachine's `<type>.<variant>.<position>.<childId>`. Don't mix. | `src/io/output.getOutput` |
> Never ship `enableLog: 'debug'` in a demo &mdash; fills the container log within seconds and obscures real errors.
---
## Output coverage (TODO)
> [!IMPORTANT]
> Per `.claude/rules/output-coverage.md`: every output on every layer needs a manifest entry + populated + degraded test. **`test/_output-manifest.md` does not yet exist** for VGC. Backfill tracked in `.agents/improvements/IMPROVEMENTS_BACKLOG.md`.
>
> Minimum coverage to land before declaring trial-ready:
>
> - Port 0 / 1 keys: `mode`, `maxDeltaP`, `atEquipment_predicted_flow`, `atEquipment_measured_flow`, `deltaMax_predicted_pressure`. Each tested in populated AND degraded states.
> - Port 2: `child.register` payload shape.
> - Example flow function-node outputs: each `outputs > 1` fan-out enumerated; verify no `payload: null` literals (lint via `npm run lint:flow-outputs`).
---
## Related pages
| Page | Why |
|:---|:---|
| [Home](Home) | Intuitive overview |
| [Reference &mdash; Contracts](Reference-Contracts) | Topic + config + child filters |
| [Reference &mdash; Architecture](Reference-Architecture) | Code map, flow-distribution loop, source aggregation |
| [Reference &mdash; Limitations](Reference-Limitations) | Known issues and open questions |
| [machineGroupControl &mdash; Examples](https://gitea.wbd-rd.nl/RnD/machineGroupControl/wiki/Reference-Examples) | Sibling group-control demo flows |
| [valve wiki](https://gitea.wbd-rd.nl/RnD/valve/wiki/Home) | The child node VGC coordinates |
| [EVOLV &mdash; Topology Patterns](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Topology-Patterns) | Where valveGroupControl fits in a larger plant |

View File

@@ -0,0 +1,150 @@
# Reference &mdash; Limitations
![code-ref](https://img.shields.io/badge/code--ref-b20a573-blue)
> [!NOTE]
> Pending full node review (2026-05). Content reflects `CONTRACT.md` and current source only.
>
> What `valveGroupControl` does not do, current rough edges, and open questions. Open items live in `.agents/improvements/IMPROVEMENTS_BACKLOG.md` in the superproject.
---
## When you would not use this node
| Scenario | Use instead |
|:---|:---|
| A single valve under one upstream parent | `valve` &mdash; VGC adds coordination overhead for no benefit with one child. |
| Valves in **series** rather than parallel | The Kv-share solver assumes parallel branches sharing a common header pressure. Series valves need their own coordination model. |
| Upstream already publishes per-branch flow setpoints | Route the per-branch setpoints directly to each `valve` &mdash; VGC's group-level redistribution would discard the upstream split. |
| Curve-based pumps grouped on a manifold | `machineGroupControl` &mdash; that's the pump-side equivalent (BEP-aware optimizer + planner). VGC has no curves and no optimizer. |
---
## Legacy file-naming drift
The entry file and editor HTML still use the abbreviated `vgc.{js,html}` filenames:
| Path | Currently | Should be |
|:---|:---|:---|
| Entry file | `vgc.js` | `valveGroupControl.js` |
| Editor HTML | `vgc.html` | `valveGroupControl.html` |
Per the EVOLV folder-naming convention (`.claude/rules/node-architecture.md` and `CLAUDE.md`), every per-node file MUST match the folder name exactly &mdash; no abbreviations. The rename is queued for the next touch:
```
files to update in one commit:
- rename vgc.js → valveGroupControl.js
- rename vgc.html → valveGroupControl.html
- update package.json#node-red.nodes (currently maps "valveGroupControl": "vgc.js")
- update any require() / import paths
- update superproject submodule references
```
Sibling drift: `machineGroupControl/mgc.{js,html}` and `dashboardAPI/dashboardapi.{js,html}` are in the same state. See `.claude/refactor/MODULE_SPLIT.md`.
---
## Known limitations
### `set.position` is a no-op
`commands/handlers.setPosition` intentionally does nothing &mdash; the handler debug-logs the payload and returns. Per-valve positional override is reserved pending Phase 7 topic standardisation of valve setpoint payloads. The canonical topic and alias are reserved so callers can't squat them in the meantime.
Workaround: route the position setpoint to the individual `valve` node directly.
### `isValidActionForMode` is not implemented
The schema declares `mode.allowedActions.<mode>` (`statusCheck` / `execSequence` / `emergencyStop` / `valvePositionChange` / `totalFlowChange` / `valveDeltaPchange`), but `specificClass.handleInput` only consults `isValidSourceForMode`. The action allow-list is effectively dead config. Source contradiction with `CONTRACT.md` which implies action gating is active.
Workaround: rely on the source allow-list for now. TODO: implement the action check (mirror `rotatingMachine`'s pattern) OR strip `allowedActions` from the schema.
### `calculationMode` is not consulted
Schema field `calculationMode` (`low` / `medium` / `high`) is declared but ignored by both `specificClass` and `nodeClass`. The tick interval is fixed at `tickInterval = 1000 ms` and only re-tunable via `set.reconcileInterval`. TODO: wire it through or remove.
### `mode.allowedSources.maintenance` is undefined
The `maintenance` mode is enumerated in `mode.current` and `mode.allowedActions`, but `mode.allowedSources` only declares `auto` / `virtualControl` / `fysicalControl`. `isValidSourceForMode('any', 'maintenance')` returns `false` for every source &mdash; effectively monitoring-only. This may be intentional, but it's not stated explicitly in any contract.
### Residual solver assumes Kv share is a valid first estimate
Pathological valve curves (very non-linear Kv vs position) may need more passes than the default `maxPasses: 2` to reach `residualTolerance: 0.001`. The loop exits gracefully but `lastFlowSolve.residual` carries the gap; `flow.predicted.atEquipment` reads only the sum of what was accepted.
There is no editor field for `flowReconciliation` &mdash; it's a runtime-only object. TODO: expose `maxPasses` / `residualTolerance` in the editor.
### Cascaded VGC not test-covered
`valvegroupcontrol` is in `SOURCE_SOFTWARE_TYPES` and `_registerSource` accepts it, so VGC-on-VGC cascades are wired by the router. But:
- No integration tests cover the case.
- No production deployments use it.
- Fluid-contract propagation across two VGCs hasn't been validated.
Treat as experimental. Open question whether to remove the entry or harden it.
### Multi-source aggregation is "last write wins" on shared positions
If two upstream sources both publish `flow.predicted.atEquipment` to the same VGC, the later write replaces the earlier one in the measurement container. There is no merge / max / priority logic. In practice this is fine when one VGC has one upstream source; with two upstream sources the behaviour is well-defined but may surprise.
### Source flow events listen on both case variants
`SOURCE_FLOW_EVENTS` includes both `flow.predicted.atEquipment` AND `flow.predicted.atequipment`. A source that emits the event twice (defensive code) will trigger `updateFlow` twice per change &mdash; harmless because the second call writes the same value, but it doubles the recompute. Open question whether to canonicalise the event name at the source.
### No FSM &mdash; sequences depend on `state` being pre-stamped operational
`specificClass.configure()` does `this.state.stateManager.currentState = 'operational'` immediately so `executeSequence('startup')` etc. can run. This is unusual &mdash; other nodes go through `boot` to reach `operational`. The shortcut is intentional (VGC doesn't model the group as a stateful machine; sequences are pass-through to valves) but it means `state.getCurrentState()` always reads `operational` regardless of what the valves are doing.
### No `test/_output-manifest.md`
Per `.claude/rules/output-coverage.md` every node should ship an output manifest with populated + degraded tests for each Port-0 / 1 / 2 key. **Not yet produced** for VGC. Backfill tracked in `.agents/improvements/IMPROVEMENTS_BACKLOG.md`.
### Wiki source-of-truth contradictions found during this review
| Source A | Source B | Issue | TODO |
|:---|:---|:---|:---|
| `CONTRACT.md` `set.mode` payload "`auto` / manual" | Schema enum `auto` / `virtualControl` / `fysicalControl` / `maintenance`; `setMode` validates against schema | `CONTRACT.md` prose understates mode count | Update `CONTRACT.md`. |
| Schema `mode.allowedActions` | `specificClass` only consults `isValidSourceForMode` | Action allow-list dead config | Implement or remove (see above). |
| Schema `calculationMode` | `specificClass` / `nodeClass` never read it | Dead config | Implement or remove. |
| `CONTRACT.md` &sect; Children: `valve`, `machine / rotatingmachine / machinegroup / machinegroupcontrol / pumpingstation / valvegroupcontrol` | `specificClass.SOURCE_SOFTWARE_TYPES` lists post-canonicalisation names only (`machine`, `machinegroup`, `pumpingstation`, `valvegroupcontrol`) | Pre-canonical aliases (`rotatingmachine`, `machinegroupcontrol`) are accepted by the router because BaseDomain normalises them &mdash; contract text remains correct in spirit | None &mdash; informational. |
| `examples/README.md` lists 3 flows with stub descriptions | Actual flow content not validated against current source | Tier labelling missing; live-deploy validation outstanding | Backfill validation; rename to Tier-1/2/3 convention. |
---
## Open questions (tracked)
| Question | Where it lives |
|:---|:---|
| Phase 7 standardisation of valve setpoint payloads (unblocks `set.position`) | `OPEN_QUESTIONS.md` Phase 7 |
| Should `flowReconciliation.maxPasses` / `residualTolerance` be editor-configurable? | Internal &mdash; not yet ticketed |
| Cascaded `valvegroupcontrol` as upstream source &mdash; harden or remove? | Internal |
| Multi-source priority / merge strategy for shared positions | Internal |
| Wire `calculationMode` through or strip from schema | Internal |
| Implement `isValidActionForMode` or strip `allowedActions` from schema | Internal |
| Output-coverage backfill (`test/_output-manifest.md` + populated/degraded tests) | `.agents/improvements/IMPROVEMENTS_BACKLOG.md` |
| Rename `vgc.{js,html}` &rarr; `valveGroupControl.{js,html}` | `.claude/refactor/MODULE_SPLIT.md` |
| Validate example flows against live Node-RED; rename to Tier-1/2/3 convention | Internal |
---
## Migration notes
### From `setpoint` topic name (pre-canonical)
The old `setpoint` alias for `set.position` still works but logs a one-time deprecation warning. Switch to `set.position` &mdash; though note the handler is currently a no-op (see above).
### From `setMode` / `registerChild` / `execSequence` / `totalFlowChange` / `emergencyStop` / `emergencystop` / `setReconcileInterval` aliases
Every legacy alias emits a one-time deprecation warning. Switch to the canonical topic names listed in [Contracts](Reference-Contracts#topic-contract).
---
## Related pages
| Page | Why |
|:---|:---|
| [Home](Home) | Intuitive overview |
| [Reference &mdash; Contracts](Reference-Contracts) | Topic + config + child filters (alias map) |
| [Reference &mdash; Architecture](Reference-Architecture) | Code map, flow-distribution loop, source aggregation |
| [Reference &mdash; Examples](Reference-Examples) | Shipped flows + debug recipes |
| [machineGroupControl &mdash; Limitations](https://gitea.wbd-rd.nl/RnD/machineGroupControl/wiki/Reference-Limitations) | Sibling Unit-level controller's known limitations |
| [valve wiki](https://gitea.wbd-rd.nl/RnD/valve/wiki/Home) | The child node VGC coordinates |

20
wiki/_Sidebar.md Normal file
View File

@@ -0,0 +1,20 @@
### valveGroupControl
- [Home](Home)
**Reference**
- [Contracts](Reference-Contracts)
- [Architecture](Reference-Architecture)
- [Examples](Reference-Examples)
- [Limitations](Reference-Limitations)
**Related**
- [EVOLV master wiki](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Home)
- [valve wiki](https://gitea.wbd-rd.nl/RnD/valve/wiki/Home)
- [machineGroupControl wiki](https://gitea.wbd-rd.nl/RnD/machineGroupControl/wiki/Home)
- [pumpingStation wiki](https://gitea.wbd-rd.nl/RnD/pumpingStation/wiki/Home)
- [Topology Patterns](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Topology-Patterns)
- [Topic Conventions](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Topic-Conventions)
- [Telemetry](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Telemetry)