Compare commits

..

8 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
11 changed files with 1029 additions and 242 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.

View File

@@ -12,42 +12,52 @@ module.exports = [
topic: 'set.mode', topic: 'set.mode',
aliases: ['setMode'], aliases: ['setMode'],
payloadSchema: { type: 'string' }, payloadSchema: { type: 'string' },
description: 'Switch the operating mode. Allowed: `auto`, `virtualControl`, `fysicalControl`, `maintenance` (schema-validated in `valveGroupControl.json` → `mode.current`).',
handler: handlers.setMode, handler: handlers.setMode,
}, },
{ {
topic: 'set.position', topic: 'set.position',
aliases: ['setpoint'], aliases: ['setpoint'],
payloadSchema: { type: 'any' }, 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, handler: handlers.setPosition,
}, },
{ {
topic: 'child.register', topic: 'child.register',
aliases: ['registerChild'], aliases: ['registerChild'],
payloadSchema: { type: 'string' }, payloadSchema: { type: 'string' },
description: 'Register a child valve with this group.',
handler: handlers.registerChild, handler: handlers.registerChild,
}, },
{ {
topic: 'cmd.execSequence', topic: 'cmd.execSequence',
aliases: ['execSequence'], aliases: ['execSequence'],
payloadSchema: { type: 'object' }, payloadSchema: { type: 'object' },
description: 'Run a group-wide sequence (startup / shutdown / emergencystop).',
handler: handlers.execSequence, handler: handlers.execSequence,
}, },
{ {
topic: 'data.totalFlow', topic: 'data.totalFlow',
aliases: ['totalFlowChange'], aliases: ['totalFlowChange'],
payloadSchema: { type: 'any' }, 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, handler: handlers.totalFlowChange,
}, },
{ {
topic: 'cmd.emergencyStop', topic: 'cmd.emergencyStop',
aliases: ['emergencyStop', 'emergencystop'], aliases: ['emergencyStop', 'emergencystop'],
payloadSchema: { type: 'any' }, payloadSchema: { type: 'any' },
description: 'Trigger an emergency stop across all valves in the group.',
handler: handlers.emergencyStop, handler: handlers.emergencyStop,
}, },
{ {
topic: 'set.reconcileInterval', topic: 'set.reconcileInterval',
aliases: ['setReconcileInterval'], aliases: ['setReconcileInterval'],
payloadSchema: { type: 'any' }, payloadSchema: { type: 'any' },
description: 'Update the reconciliation interval (seconds).',
handler: handlers.setReconcileInterval, handler: handlers.setReconcileInterval,
}, },
]; ];

View File

@@ -10,7 +10,9 @@ const flowDist = require('./groupOps/flowDistribution');
const sources = require('./sources/fluidContract'); const sources = require('./sources/fluidContract');
const io = require('./io/output'); const io = require('./io/output');
const KNOWN_POSITIONS = new Set(['upstream', 'downstream', 'atEquipment']); // Source softwareTypes after BaseDomain canonicalisation
// (rotatingmachine→machine, machinegroupcontrol→machinegroup).
const SOURCE_SOFTWARE_TYPES = ['machine', 'machinegroup', 'pumpingstation', 'valvegroupcontrol'];
class ValveGroupControl extends BaseDomain { class ValveGroupControl extends BaseDomain {
static name = 'valveGroupControl'; static name = 'valveGroupControl';
@@ -42,22 +44,10 @@ class ValveGroupControl extends BaseDomain {
this.state = new state({}, this.logger); this.state = new state({}, this.logger);
this.state.stateManager.currentState = 'operational'; this.state.stateManager.currentState = 'operational';
// Overloaded API: `(child, softwareTypeOrPosition)`. Tests + legacy this.router.onRegister('valve', (child) => this._registerValve(child));
// childRegistrationUtils both invoke this with a string second arg, for (const swType of SOURCE_SOFTWARE_TYPES) {
// which may be either a known position or a softwareType. Resolve this.router.onRegister(swType, (child, canonicalKey) => this._registerSource(child, canonicalKey));
// before dispatching so router-based registration keeps working.
this.registerChild = (child, positionOrType) => this._registerChild(child, positionOrType);
}
_resolveRegistrationContext(child, arg) {
const fromArg = String(arg || '').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) {
@@ -69,22 +59,7 @@ class ValveGroupControl extends BaseDomain {
); );
} }
_registerChild(child, positionOrType) { _registerValve(child) {
const ctx = this._resolveRegistrationContext(child, positionOrType);
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 (sources.isSourceLike(child, softwareType)) {
return sources.registerSource(this, 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;
@@ -94,6 +69,9 @@ class ValveGroupControl extends BaseDomain {
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);
@@ -104,6 +82,13 @@ class ValveGroupControl extends BaseDomain {
return true; return true;
} }
_registerSource(child, softwareType) {
const positionVsParent = child.positionVsParent
|| child.config?.functionality?.positionVsParent
|| 'atEquipment';
return sources.registerSource(this, child, positionVsParent, softwareType);
}
_bindValveEvents(valveId, valve) { _bindValveEvents(valveId, valve) {
const handlers = { const handlers = {
onPositionChange: () => { this.logger.debug(`Valve ${valveId} position changed, recalculating flows.`); this.calcValveFlows(); }, onPositionChange: () => { this.logger.debug(`Valve ${valveId} position changed, recalculating flows.`); this.calcValveFlows(); },

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>

View File

@@ -1,242 +1,153 @@
# valveGroupControl # valveGroupControl
> **Reflects code as of `e02cd1a` · regenerated `2026-05-11` via `npm run wiki:all`** ![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)
> If this banner is stale, the page may be out of date. Treat as informative, not authoritative.
## 1. What this node is 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.
**valveGroupControl** (VGC) is an S88 Unit that distributes a group-level flow target across registered `valve` children proportional to their current Kv, aggregates the per-valve accepted flow back into a group total, and surfaces the maximum delta-P across the group. It also reconciles each child's fluid-contract advertisement into a single group-level service-type view. > [!NOTE]
> Pending full node review (2026-05). Content reflects `CONTRACT.md` and current source only.
## 2. Position in the platform ---
## 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 ```mermaid
flowchart LR flowchart LR
src[machine / MGC / PS<br/>upstream source]:::unit -.flow.predicted.-> vgc[valveGroupControl<br/>Unit]:::unit src[machine / MGC /<br/>pumpingStation<br/>upstream source]:::unit -.flow.predicted.*.-> vgc[valveGroupControl<br/>Unit]:::unit
vgc -->|set.position| v1[valve A]:::equip vgc -->|updateFlow predicted<br/>downstream| v1[valve A]:::equip
vgc -->|set.position| v2[valve B]:::equip vgc -->|updateFlow predicted<br/>downstream| v2[valve B]:::equip
v1 -->|evt.deltaPChange| vgc v1 -->|positionChange<br/>deltaPChange| vgc
v2 -->|evt.deltaPChange| vgc v2 -->|positionChange<br/>deltaPChange| vgc
vgc -->|child.register| parent[upstream parent]:::unit vgc -->|child.register| parent[upstream parent]:::pc
classDef pc fill:#0c99d9,color:#fff
classDef unit fill:#50a8d9,color:#000 classDef unit fill:#50a8d9,color:#000
classDef equip fill:#86bbdd,color:#000 classDef equip fill:#86bbdd,color:#000
``` ```
S88 colours: Unit `#50a8d9`, Equipment `#86bbdd`. Source of truth: `.claude/rules/node-red-flow-layout.md`. S88 colours are anchored in `.claude/rules/node-red-flow-layout.md`.
## 3. Capability matrix ---
| Capability | Status | Notes | ## Try it &mdash; 3-minute demo
|---|---|---|
| Proportional flow distribution by Kv | ✅ | `groupOps/flowDistribution.js`. |
| Two-pass residual reconciliation | ✅ | `maxPasses: 2`, `residualTolerance: 0.001`. |
| Periodic tick re-balance | ✅ | Runs each adapter tick; `set.reconcileInterval` re-tunes. |
| Group `maxDeltaP` aggregation | ✅ | Recomputed on any child `deltaPChange`. |
| Upstream fluid-contract aggregation | ✅ | `sources/fluidContract.js`. |
| Sequence dispatch to all valves | ✅ | `cmd.execSequence` → per-valve `handleInput`. |
| Per-valve positional override | ❌ | `set.position` reserved; no-op in current build. |
| Multi-source aggregation | ✅ | Multiple machines / MGCs may register as sources. |
## 4. Code map Import the basic example flow, deploy, and drive a 2-valve group with an injected total-flow setpoint.
```mermaid ```bash
flowchart TB curl -X POST -H 'Content-Type: application/json' \
subgraph nodeRED["nodeClass.js — adapter (BaseNodeAdapter)"] --data @nodes/valveGroupControl/examples/basic.flow.json \
nc["buildDomainConfig()<br/>static DomainClass, commands"] http://localhost:1880/flow
end
subgraph domain["specificClass.js — orchestrator (BaseDomain)"]
sc["ValveGroupControl.configure()<br/>registerChild dispatch<br/>tick → calcValveFlows"]
end
subgraph concerns["src/ concern modules"]
gops["groupOps/<br/>flowDistribution"]
srcs["sources/<br/>fluidContract"]
cmds["commands/<br/>topic registry + handlers"]
io["io/<br/>output + status badge"]
end
nc --> sc
sc --> gops
sc --> srcs
sc --> io
nc --> cmds
``` ```
| Module | Owns | Read first if you're changing… | What to click after deploy (the inject buttons map to canonical topics in [Reference &mdash; Contracts](Reference-Contracts#topic-contract)):
|---|---|---|
| `groupOps/` | Flow distribution, residual solver, max-deltaP aggregation | How the group divides flow. |
| `sources/` | Upstream-source registration, fluid-contract reconciliation | Service-type aggregation, source-event subscriptions. |
| `commands/` | Input-topic registry + per-topic handlers | New input topics, payload validation. |
| `io/` | Port-0 output shape + status badge | What lands on the wire. |
## 5. 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).
> **Auto-generated** from `src/commands/index.js`. Do NOT hand-edit between the markers. Re-run `npm run wiki:contract`. > [!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`.
<!-- BEGIN AUTOGEN: topic-contract --> ---
| Canonical topic | Aliases | Payload | Effect | ## The seven things you'll send
|---|---|---|---|
| `set.mode` | `setMode` | `string` | Replaces the named state value with the supplied payload. |
| `set.position` | `setpoint` | `any` | Replaces the named state value with the supplied payload. |
| `child.register` | `registerChild` | `string` | Parent/child plumbing — registers or unregisters a child node. |
| `cmd.execSequence` | `execSequence` | `object` | Triggers an action / sequence — not idempotent. |
| `data.totalFlow` | `totalFlowChange` | `any` | Pushes a value into the node's measurement stream. |
| `cmd.emergencyStop` | `emergencyStop`, `emergencystop` | `any` | Triggers an action / sequence — not idempotent. |
| `set.reconcileInterval` | `setReconcileInterval` | `any` | Replaces the named state value with the supplied payload. |
<!-- END AUTOGEN: topic-contract --> | 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. |
## 6. Child registration 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 ```mermaid
flowchart LR flowchart LR
subgraph kids["accepted children (softwareType)"] src[data.totalFlow /<br/>upstream source event] --> upd[updateFlow<br/>predicted/measured atEquipment]
v["valve"]:::equip upd --> avail[getAvailableValves<br/>state &ne; off/maintenance, kv > 0]
src["machine / rotatingmachine /<br/>machinegroup / pumpingstation /<br/>valvegroupcontrol"]:::unit avail --> solve[solveFlowDistribution<br/>share by Kv / totalKv]
end solve --> push[valve.updateFlow predicted<br/>downstream]
v -->|positionChange| handler1[onPositionChange<br/>calcValveFlows] push --> readback[read accepted from<br/>flow.predicted.downstream]
v -->|deltaPChange| handler2[onDeltaPChange<br/>calcMaxDeltaP] readback --> residual[residual = target &minus; sum&#40;accepted&#41;]
src -->|flow.predicted.*| handler3[updateFlow<br/>at atEquipment] residual -->|residual &gt; tol & passes &lt; max| solve
src -->|fluidContractChange| handler4[sources.refresh<br/>aggregate contract] residual --> writeback[write flow.predicted.atEquipment<br/>= sum&#40;accepted&#41;]
classDef equip fill:#86bbdd,color:#000 writeback --> dp[calcMaxDeltaP]
classDef unit fill:#50a8d9,color:#000 dp --> emit[notifyOutputChanged]
``` ```
| softwareType | onRegister side-effect | Subscribed events | Reconciliation defaults (`flowReconciliation`):
|---|---|---|
| `valve` | Stored in `this.valves[id]`; binds `positionChange` + `deltaPChange`; triggers `calcValveFlows` + `calcMaxDeltaP`. | `positionChange`, `deltaPChange`. |
| `machine` / `rotatingmachine` | Stored as upstream source; reads `getFluidContract()` (or default `liquid`). | `flow.predicted.*`, `flow.measured.*`, `fluidContractChange`. |
| `machinegroup` / `machinegroupcontrol` | Same as machine. | Same as machine. |
| `pumpingstation` | Same as machine. | Same as machine. |
| `valvegroupcontrol` | Allowed for cascaded VGCs; not exercised in production. | Same. |
## 7. Lifecycle — what one tick / event does | 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). |
```mermaid 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')`.
sequenceDiagram
participant src as upstream source
participant vgc as VGC
participant v1 as valve A
participant v2 as valve B
participant out as Port-0
src->>vgc: flow.predicted.downstream (m3/s) 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.
vgc->>vgc: _write flow.predicted.atEquipment
vgc->>vgc: calcValveFlows()
Note over vgc: solveFlowDistribution<br/>(by Kv share)
vgc->>v1: updateFlow('predicted', shareA, 'downstream')
vgc->>v2: updateFlow('predicted', shareB, 'downstream')
v1-->>vgc: accepted flow + deltaPChange
v2-->>vgc: accepted flow + deltaPChange
vgc->>vgc: residual pass (up to maxPasses)
vgc->>vgc: calcMaxDeltaP
vgc->>out: msg{topic, payload (delta-compressed)}
```
## 11. Distribution loop — flow-share solver ---
VGC has no FSM. The loop below replaces the state chart for this section. ## Need more?
```mermaid | Page | What you'll find |
sequenceDiagram |:---|:---|
participant tick as adapter tick / event | [Reference &mdash; Contracts](Reference-Contracts) | Topic registry, config schema, child-registration filters |
participant vgc as VGC | [Reference &mdash; Architecture](Reference-Architecture) | Code map, flow-distribution loop, source aggregation, output ports |
participant solver as solveFlowDistribution | [Reference &mdash; Examples](Reference-Examples) | Shipped flows, debug recipes |
participant valves as valve children | [Reference &mdash; Limitations](Reference-Limitations) | When not to use, known issues, open questions |
tick->>vgc: calcValveFlows() [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)
vgc->>vgc: read flow.measured / predicted .atEquipment
vgc->>solver: target=totalFlow, entries=availableValves
loop ≤ maxPasses while |residual| > tolerance
solver->>valves: updateFlow share by (Kv / totalKv)
valves-->>solver: accepted flow back
solver->>solver: residual = target - sum(accepted)
end
solver-->>vgc: { flowsById, residual, passes }
vgc->>vgc: write flow.predicted.atEquipment = assignedTotal
vgc->>vgc: notifyOutputChanged()
```
## 8. Data model — `getOutput()`
What lands on Port 0. Composed in `io/output`, then delta-compressed by `outputUtils.formatMsg`.
<!-- BEGIN AUTOGEN: data-model -->
| Key | Type | Unit | Sample |
|---|---|---|---|
| `maxDeltaP` | number | — | `0` |
| `mode` | string | — | `"auto"` |
<!-- END AUTOGEN: data-model -->
Measurement-derived keys follow the `<position>_<variant>_<type>` shape (e.g. `atEquipment_predicted_flow`) and are emitted only when the container holds a finite value.
## 9. Configuration — editor form ↔ config keys
```mermaid
flowchart TB
subgraph editor["Node-RED editor form"]
f1[Mode]
f2[Sequences]
f3[Allowed sources per mode]
f4[Reconciliation interval]
end
subgraph config["Domain config slice"]
c1[mode.current]
c2[sequences.<name>]
c3[mode.allowedSources.<mode>]
c4[flowReconciliation (runtime)]
end
f1 --> c1
f2 --> c2
f3 --> c3
f4 --> c4
```
| Form field | Config key | Default | Range | Where used |
|---|---|---|---|---|
| Mode | `mode.current` | per schema | enum | `setMode` |
| Sequences | `sequences.<name>` | per schema | Set of state names | `executeSequence` |
| Allowed sources | `mode.allowedSources.<mode>` | per schema | Set of source ids | `isValidSourceForMode` |
| Reconcile maxPasses | `flowReconciliation.maxPasses` | `2` | ≥ 1 | `solveFlowDistribution` |
| Reconcile tolerance | `flowReconciliation.residualTolerance` | `0.001` | ≥ 0 | `solveFlowDistribution` |
| Reconcile interval | (runtime, via `set.reconcileInterval`) | adapter default | ≥ 100 ms | `setReconcileIntervalSeconds` |
## 10. State chart
Skipped — VGC has no FSM of its own. State semantics belong to the child valves; VGC is a coordinator. See section 11 for the flow-distribution loop.
## 11. Examples
| Tier | File | What it shows | Mandatory? |
|---|---|---|---|
| Basic | `examples/01-Basic.flow.json` | Inject `data.totalFlow` + 2 valves + dashboard | ✅ |
| Integration | `examples/02-Integration.flow.json` | VGC + valves + upstream rotatingMachine | ✅ |
| Dashboard | `examples/03-Dashboard.flow.json` | Live FlowFuse charts (per-valve flow, max ΔP) | ⭕ |
Screenshots under `wiki/_partial-screenshots/valveGroupControl/` when produced. Docker compose snippet under `examples/README.md`.
## 12. Debug recipes
| Symptom | First thing to check | Where to look |
|---|---|---|
| All valves show `assigned flow = 0` | `getAvailableValves()` empty; check Kv > 0 and state ≠ `off` / `maintenance`. | `groupOps/flowDistribution.isValveAvailable` |
| Residual never converges | `flowReconciliation.maxPasses` too low for the valve curve shape. | `lastFlowSolve.residual` |
| Group `maxDeltaP` stale | Child `deltaPChange` not subscribed; valve emitter not exposed. | `_bindValveEvents` |
| Service-type stays `unknown` | No source registered yet or all sources advertise unknown. | `sources.refreshFluidContract` |
| `data.totalFlow` ignored | Mode rejects the source; check `mode.allowedSources`. | `isValidSourceForMode` |
> Never ship `enableLog: 'debug'` in a demo — fills the container log within seconds and obscures real errors. Use only for live debugging.
## 13. When you would NOT use this node
- Use VGC for **2+ parallel valves** sharing a header. For a single valve, wire `valve` directly under the upstream parent.
- Don't use VGC to coordinate series valves — the flow-distribution model assumes parallel branches with a shared upstream pressure.
- Skip VGC when the upstream source already publishes per-branch flow setpoints; route those straight to each valve.
## 14. Known limitations / current issues
| # | Issue | Tracked in |
|---|---|---|
| 1 | `set.position` is reserved but currently a no-op — per-valve override is pending Phase 7. | CONTRACT.md `## Inputs` |
| 2 | Residual solver assumes Kv share is a good first estimate; pathological curves can need more passes than the default `2`. | `groupOps/flowDistribution.js` |
| 3 | Cascaded `valvegroupcontrol` registration accepted but not test-covered. | CONTRACT.md `## Children` |

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)