diff --git a/wiki/Home.md b/wiki/Home.md index b6e2cb3..0385142 100644 --- a/wiki/Home.md +++ b/wiki/Home.md @@ -1,260 +1,153 @@ # valveGroupControl -> **Reflects code as of `ef34c82` · regenerated `2026-05-11` via `npm run wiki:all`** -> If this banner is stale, the page may be out of date. Treat as informative, not authoritative. +![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) -## 1. What this node is +A `valveGroupControl` (VGC) coordinates a group of `valve` children that share a common manifold — 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 coordinator for a group of `valve` children. It distributes a group-level flow target across registered valves proportional to their Kv rating, runs a residual-reconciliation pass to absorb per-valve acceptance limits, aggregates group max delta-P, and reconciles upstream fluid-contract advertisements 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 — 2 + valves sharing a header, distributing one total flow target | +| S88 level | Unit | +| Use it when | You have 2 + 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 — typically `pumpingStation`, `reactor`, or another VGC; VGC registers via Port 2 | + +--- + +## How it fits ```mermaid flowchart LR - src[machine / MGC / PS
upstream source]:::unit -.flow.predicted.-> vgc[valveGroupControl
Unit]:::unit - vgc -->|updateFlow predicted| v1[valve A]:::equip - vgc -->|updateFlow predicted| v2[valve B]:::equip - v1 -->|positionChange| vgc - v2 -->|positionChange| vgc - v1 -->|deltaPChange| vgc - v2 -->|deltaPChange| vgc - vgc -->|child.register| parent[upstream parent]:::unit + src[machine / MGC /
pumpingStation
upstream source]:::unit -.flow.predicted.*.-> vgc[valveGroupControl
Unit]:::unit + vgc -->|updateFlow predicted
downstream| v1[valve A]:::equip + vgc -->|updateFlow predicted
downstream| v2[valve B]:::equip + v1 -->|positionChange
deltaPChange| vgc + v2 -->|positionChange
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: 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 | -|---|---|---| -| Proportional flow distribution by Kv | ✅ | `groupOps/flowDistribution.js`. | -| Two-pass residual reconciliation | ✅ | Default `maxPasses: 2`, `residualTolerance: 0.001`. | -| Periodic tick re-balance | ✅ | `tick()` calls `calcValveFlows()`; `set.reconcileInterval` re-tunes interval. | -| Group `maxDeltaP` aggregation | ✅ | Recomputed on any child `deltaPChange` event. | -| Upstream fluid-contract aggregation | ✅ | `sources/fluidContract.js`; emits `fluidContractChange`. | -| Group-wide sequence dispatch | ✅ | `cmd.execSequence` → `executeSequence` → per-state `transitionToState`. | -| Emergency stop | ✅ | `cmd.emergencyStop` → `emergencystop` sequence on all valves. | -| Per-valve positional override | ⚠️ | `set.position` is a debug-logged **no-op** pending Phase 7. See §14. | -| Multi-source aggregation | ✅ | Multiple machines / MGCs / PSs may register as upstream sources. | -| Cascaded VGC as upstream source | ⚠️ | Accepted by router but not exercised in production; test coverage absent. | +## Try it — 3-minute demo -## 4. Code map +Import the basic example flow, deploy, and drive a 2-valve group with an injected total-flow setpoint. -```mermaid -flowchart TB - subgraph nodeRED["nodeClass.js — adapter (BaseNodeAdapter)"] - nc["buildDomainConfig()
static DomainClass, commands"] - end - subgraph domain["specificClass.js — orchestrator (BaseDomain)"] - sc["ValveGroupControl.configure()
router.onRegister: valve + sources
tick() → calcValveFlows()"] - end - subgraph concerns["src/ concern modules"] - gops["groupOps/
flowDistribution + calcMaxDeltaP"] - srcs["sources/
fluidContract registration"] - cmds["commands/
topic registry + handlers"] - io["io/
getOutput + getStatusBadge"] - end - nc --> sc - sc --> gops - sc --> srcs - sc --> io - nc --> cmds +```bash +curl -X POST -H 'Content-Type: application/json' \ + --data @nodes/valveGroupControl/examples/basic.flow.json \ + http://localhost:1880/flow ``` -| Module | Owns | Read first if you're changing… | -|---|---|---| -| `groupOps/` | Kv-share solver, residual pass, max-deltaP aggregation | How the group divides flow between valves. | -| `sources/` | Upstream-source registration, flow-event subscription, fluid-contract reconciliation | Service-type aggregation, source event wiring. | -| `commands/` | Input-topic registry + per-topic handlers | New input topics or payload validation rules. | -| `io/` | Port-0 output shape + status badge composition | What lands on the wire, badge text. | +What to click after deploy (the inject buttons map to canonical topics in [Reference — Contracts](Reference-Contracts#topic-contract)): -## 5. Topic contract +1. `child.register` for each `valve` — or rely on Port-2 wiring to auto-register. +2. `set.mode = auto` — lets the parent source drive the group. +3. `data.totalFlow = 80` (with `unit: 'm3/h'`) — 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"}` — runs the group-wide startup sequence through `executeSequence`, transitioning the group state machine through each step. +5. `cmd.emergencyStop` — runs the `emergencystop` sequence on all valves (`[emergencystop, off]`). +6. `set.reconcileInterval = 2` — 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–6 with the live status panel. Save as `wiki/_partial-gifs/valveGroupControl/01-basic-demo.gif`, target ≤ 1 MB after `gifsicle -O3 --lossy=80`. -The **Unit** column reflects the descriptor's `units: { measure, default }` declaration, rendered as ` (default )`. Topics without a `units` field show `—`. The **Effect** column is sourced from the descriptor's `description` field. +--- - +## The seven things you'll send -| Canonical topic | Aliases | Payload | Unit | Effect | -|---|---|---|---|---| -| `set.mode` | `setMode` | `string` | — | Switch the valve group between auto / manual control modes. | -| `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). | +| 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)` — 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 — 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. -## 6. Child registration +--- + +## 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: **`__`** — 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 — 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 — 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 - subgraph kids["accepted children (softwareType)"] - v["valve"]:::equip - src["machine / rotatingmachine /
machinegroup / pumpingstation /
valvegroupcontrol"]:::unit - end - v -->|positionChange| handler1[onPositionChange
→ calcValveFlows] - v -->|deltaPChange| handler2[onDeltaPChange
→ calcMaxDeltaP] - src -->|flow.predicted.*
flow.measured.*| handler3[updateFlow
atEquipment] - src -->|fluidContractChange| handler4[sources.refresh
aggregate contract] - classDef equip fill:#86bbdd,color:#000 - classDef unit fill:#50a8d9,color:#000 + src[data.totalFlow /
upstream source event] --> upd[updateFlow
predicted/measured atEquipment] + upd --> avail[getAvailableValves
state ≠ off/maintenance, kv > 0] + avail --> solve[solveFlowDistribution
share by Kv / totalKv] + solve --> push[valve.updateFlow predicted
downstream] + push --> readback[read accepted from
flow.predicted.downstream] + readback --> residual[residual = target − sum(accepted)] + residual -->|residual > tol & passes < max| solve + residual --> writeback[write flow.predicted.atEquipment
= sum(accepted)] + writeback --> dp[calcMaxDeltaP] + dp --> emit[notifyOutputChanged] ``` -| softwareType | onRegister side-effect | Subscribed events | -|---|---|---| -| `valve` | Stored in `this.valves[id]`; binds `positionChange` (via `child.state.emitter`) + `deltaPChange` (via `child.emitter`); triggers `calcValveFlows` + `calcMaxDeltaP`. | `positionChange`, `deltaPChange`. | -| `machine` / `rotatingmachine` | Stored as upstream source; reads `getFluidContract()` or infers `liquid` by default. | `flow.predicted.*`, `flow.measured.*`, `fluidContractChange`. | -| `machinegroup` / `machinegroupcontrol` | Same as machine. | Same as machine. | -| `pumpingstation` | Same as machine. | Same as machine. | -| `valvegroupcontrol` | Cascaded VGC; accepted by router. Not exercised in production. | Same as machine. | +Reconciliation defaults (`flowReconciliation`): -## 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 — m³/s for flow). | -```mermaid -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 +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')`. - src->>vgc: flow.predicted.downstream (m³/h) - vgc->>vgc: updateFlow('predicted', value, 'atEquipment') - vgc->>vgc: calcValveFlows() - Note over vgc: solveFlowDistribution
by Kv share (≤ maxPasses) - vgc->>v1: updateFlow('predicted', shareA, 'downstream') - vgc->>v2: updateFlow('predicted', shareB, 'downstream') - v1-->>vgc: positionChange / deltaPChange - v2-->>vgc: positionChange / deltaPChange - vgc->>vgc: calcMaxDeltaP - vgc->>vgc: notifyOutputChanged() - vgc->>out: msg{topic, payload (delta-compressed)} -``` +VGC has **no FSM of its own** — 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. -## 8. Data model — `getOutput()` +--- -What lands on Port 0. Composed in `io/output.getOutput()`, then delta-compressed by `outputUtils.formatMsg`. +## Need more? - +| Page | What you'll find | +|:---|:---| +| [Reference — Contracts](Reference-Contracts) | Topic registry, config schema, child-registration filters | +| [Reference — Architecture](Reference-Architecture) | Code map, flow-distribution loop, source aggregation, output ports | +| [Reference — Examples](Reference-Examples) | Shipped flows, debug recipes | +| [Reference — Limitations](Reference-Limitations) | When not to use, known issues, open questions | -| Key | Type | Unit | Sample | -|---|---|---|---| -| `maxDeltaP` | number | — | `0` | -| `mode` | string | — | `"auto"` | - - - -Measurement-derived keys follow the `__` shape and are emitted only when the container holds a finite value. - -| Example key | Unit | Description | -|---|---|---| -| `atEquipment_predicted_flow` | m³/h | Total group predicted flow (sum of per-valve assigned flows). | -| `atEquipment_measured_flow` | m³/h | Total group measured flow (from upstream source). | -| `deltaMax_predicted_pressure` | mbar | Max delta-P across registered valves. | - -> Delta compression: only changed fields are sent per tick. Consumers must cache and merge. See `outputUtils.formatMsg`. - -## 9. Configuration — editor form ↔ config keys - -```mermaid -flowchart TB - subgraph editor["Node-RED editor form (vgc.html)"] - f1[Name] - f2[Process output format] - f3[Database output format] - f4[Position vs parent] - f5[Logger / log level] - end - subgraph config["Domain config (runtime / schema)"] - c1[general.name] - c2[output.process] - c3[output.dbase] - c4[functionality.positionVsParent] - c5[logging.enableLog / logLevel] - end - f1 --> c1 - f2 --> c2 - f3 --> c3 - f4 --> c4 - f5 --> c5 -``` - -| Form field | Config key | Default | Where used | -|---|---|---|---| -| Name | `general.name` | `""` | Node label, InfluxDB tag, status badge. | -| Process output format | `output.process` | `"process"` | `outputUtils.formatMsg` Port-0 formatter. | -| Database output format | `output.dbase` | `"influxdb"` | `outputUtils.formatMsg` Port-1 formatter. | -| Position vs parent | `functionality.positionVsParent` | `""` | Child registration Port-2 message; read by upstream parent. | -| Enable log / log level | `logging.enableLog`, `logging.logLevel` | `false` / `"error"` | Logger verbosity. Never ship `debug` in demos. | - -> Domain-level config (`mode.current`, `sequences`, `mode.allowedSources`, `flowReconciliation`) is loaded from the node's schema defaults and updated at runtime via `set.mode` / `set.reconcileInterval`. These fields are not exposed in the editor form. - -## 10. Flow-distribution loop (replaces state chart) - -VGC has no FSM of its own — state semantics belong to the child valves. The core coordination loop is the Kv-share solver described below. - -```mermaid -sequenceDiagram - participant tick as adapter tick / incoming event - participant vgc as VGC - participant solver as solveFlowDistribution - participant valves as valve children - - tick->>vgc: calcValveFlows() - vgc->>vgc: read flow.measured (or predicted) .atEquipment - vgc->>solver: target=totalFlow, entries=availableValves - loop ≤ maxPasses while |residual| > tolerance - solver->>valves: updateFlow share by (Kv / totalKv) - valves-->>solver: accepted flow (read back from child.measurements) - solver->>solver: residual = target − sum(accepted) - end - solver-->>vgc: { flowsById, residual, passes } - vgc->>vgc: write flow.predicted.atEquipment = assignedTotal - vgc->>vgc: calcMaxDeltaP() - vgc->>vgc: notifyOutputChanged() -``` - -A valve is **available** if: `state ≠ off|maintenance`, `mode ≠ maintenance`, and `kv > 0`. Unavailable valves receive `updateFlow('predicted', 0)` and are excluded from the solver. - -## 11. Examples - -| Tier | File | What it shows | Mandatory? | -|---|---|---|---| -| Basic | `examples/basic.flow.json` | Inject `data.totalFlow` + 2 valves (no parent) | ✅ | -| Integration | `examples/integration.flow.json` | VGC + valves + upstream rotatingMachine | ✅ | -| Edge | `examples/edge.flow.json` | Edge cases: no valves, residual non-convergence, cascaded VGC | ⭕ | - -Tier-1 / Tier-2 / Tier-3 naming scheme pending when existing flows are validated on live Node-RED. Screenshots under `wiki/_partial-screenshots/valveGroupControl/` when produced. - -## 12. Debug recipes - -| Symptom | First thing to check | Where to look | -|---|---|---| -| All valves receive `assigned flow = 0` | `getAvailableValves()` returns empty list; check Kv > 0 and child state ≠ `off` / `maintenance`. | `groupOps/flowDistribution.isValveAvailable` | -| Residual never converges | `flowReconciliation.maxPasses` too low for valve curve shape; check `lastFlowSolve.residual`. | `groupOps/flowDistribution.js` | -| Group `maxDeltaP` stale | Child `deltaPChange` not subscribed; valve emitter not exposed via `child.emitter`. | `specificClass._bindValveEvents` | -| Service-type stays `unknown` | No upstream source registered, or all advertise unknown type. | `sources/fluidContract.refreshFluidContract` | -| `data.totalFlow` silently ignored | Mode rejects the source id; check `mode.allowedSources` for the current mode. | `specificClass.isValidSourceForMode` | -| `set.position` has no effect | Known limitation — handler is a no-op. See §14. | `commands/handlers.setPosition` | - -> 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 `valve` directly when you have a **single** valve under an upstream parent. VGC adds coordination overhead for no benefit with one child. -- Do NOT use VGC to coordinate **series** valves — the Kv-share solver assumes parallel branches sharing a common header pressure. -- Skip VGC when the upstream source already publishes **per-branch flow setpoints**; route those directly to each valve instead. - -## 14. Known limitations / current issues - -| # | Issue | Tracked in | -|---|---|---| -| 1 | `set.position` is a debug-logged **no-op** — per-valve positional override is reserved, pending Phase 7 topic standardisation of valve setpoint payloads. The handler in `commands/handlers.setPosition` intentionally does nothing. | `CONTRACT.md §Inputs`; `OPEN_QUESTIONS.md` Phase 7 | -| 2 | Residual solver assumes Kv share is a valid first estimate. Pathological valve curves (e.g. very non-linear Kv vs position) may need more passes than the default `maxPasses: 2` to reach `residualTolerance`. | `groupOps/flowDistribution.js` | -| 3 | Cascaded `valvegroupcontrol` registration (VGC as upstream source of another VGC) is accepted by the router but has no test coverage and is not exercised in production. | `CONTRACT.md §Children` | +[EVOLV master wiki](https://gitea.wbd-rd.nl/RnD/EVOLV/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) diff --git a/wiki/Reference-Architecture.md b/wiki/Reference-Architecture.md new file mode 100644 index 0000000..ffeb0ce --- /dev/null +++ b/wiki/Reference-Architecture.md @@ -0,0 +1,238 @@ +# Reference — 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 — 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 ≤ 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 — 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 — 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` — 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 — tick + event sources + +| Source | Where it fires | What it triggers | +|:---|:---|:---| +| Periodic tick | `nodeClass` `setInterval(tickInterval = 1000 ms)` | `source.tick()` → `calcValveFlows()` → `notifyOutputChanged()`. | +| Child `state.emitter` `'positionChange'` | per child valve | `onPositionChange` → `calcValveFlows()`. | +| Child `emitter` `'deltaPChange'` | per child valve | `onDeltaPChange` → `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)` — 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 — `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 — `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: , positionVsParent}` | + +Port-0 key shape is **`__`** (same as MGC) — 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` — 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… | 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 — Contracts](Reference-Contracts) | Topic + config + child filters | +| [Reference — Examples](Reference-Examples) | Shipped flows + debug recipes | +| [Reference — 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 — Architecture](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Architecture) | Platform-wide three-tier pattern | diff --git a/wiki/Reference-Contracts.md b/wiki/Reference-Contracts.md new file mode 100644 index 0000000..c7ec8c5 --- /dev/null +++ b/wiki/Reference-Contracts.md @@ -0,0 +1,257 @@ +# Reference — 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. + + + +| Canonical topic | Aliases | Payload | Unit | Effect | +|:---|:---|:---|:---|:---| +| `set.mode` | `setMode` | `string` (`auto` / `virtualControl` / `fysicalControl` / `maintenance`) | — | Switch operational mode via `source.setMode(payload)`. 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; the handler is debug-logged only. | +| `child.register` | `registerChild` | `string` (child node id) | — | Resolve via `RED.nodes.getNode`; if the child exposes `.source`, register through `childRegistrationUtils.registerChild(child.source, msg.positionVsParent)`. | +| `cmd.execSequence` | `execSequence` | `{ source, action, parameter }` | — | Forward to `source.handleInput(source, action, parameter)`. The `action` typically names a sequence; the parameter typically names the state list. | +| `data.totalFlow` | `totalFlowChange` | number, `{ value, position?, variant?, unit? }`, or `{ source, action, ... }` | `volumeFlowRate` (default `m3/h`) | Update total measured/predicted flow at the configured position; drives `calcValveFlows` to re-distribute. If `payload.source` is present, route via `handleInput(src, action, payload)`; otherwise treat as `parent`/`totalFlowChange`. | +| `cmd.emergencyStop` | `emergencyStop`, `emergencystop` | optional `{ source }` | — | Run the `emergencystop` sequence via `handleInput(src, 'emergencystop')`. Default source is `parent`. | +| `set.reconcileInterval` | `setReconcileInterval` | number — seconds (> 0) | seconds | Re-tune the periodic flow-reconciliation interval (`setReconcileIntervalSeconds`). Min clamp 100 ms. Non-finite or ≤ 0 logs a warn and is dropped. | + + + +### Mode / source allow-lists + +A topic that survives the registry still passes through `flowController` → `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 — 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` — **`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 — `getOutput()` shape + +Composed each tick by `src/io/output.getOutput()`. Delta-compressed: consumers see only keys whose `getCurrentValue()` is non-null. + + + +### 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: + +``` +__ +``` + +| 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`. + + + +### Status badge + +`io/output.getStatusBadge`: + +``` + | flow= | 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 — editor form to config keys + +Source of truth: `generalFunctions/src/configs/valveGroupControl.json` plus `nodeClass.buildDomainConfig` (which returns `{}` — 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 — 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.` | see [Mode allow-lists](#mode--source-allow-lists) | enforced by `flowController` (NOT implemented — see warning above) | +| (defaults) | `mode.allowedSources.` | 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 — 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']` — 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` (→ `calcValveFlows`) and `emitter.deltaPChange` (→ `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 — see [Limitations](Reference-Limitations#cascaded-vgc-not-test-covered). | + +Position labels accepted from children are `upstream`, `downstream`, `atEquipment` (and case variants — 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 — 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 — Architecture](Reference-Architecture) | Code map, flow-distribution loop, source aggregation | +| [Reference — Examples](Reference-Examples) | Shipped flows + debug recipes | +| [Reference — Limitations](Reference-Limitations) | Known issues and open questions | +| [EVOLV — Topic Conventions](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Topic-Conventions) | Platform-wide topic rules | +| [EVOLV — Telemetry](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Telemetry) | Port 0 / 1 / 2 InfluxDB layout | diff --git a/wiki/Reference-Examples.md b/wiki/Reference-Examples.md new file mode 100644 index 0000000..a9ce624 --- /dev/null +++ b/wiki/Reference-Examples.md @@ -0,0 +1,157 @@ +# Reference — 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 — TODO consult `examples/edge.flow.json` for actual scenarios. | + +> [!IMPORTANT] +> The Tier-1 / Tier-2 / Tier-3 naming convention (`01 - .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 → Import → 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 — 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` — the next `data.totalFlow` (or tick) routes 100% to the remaining valve. +5. Set the offlined valve back to operational — 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` — 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 — 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` → 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** — all in `off` / `maintenance`. Expected: status badge `'No valves'` red, every valve pushed `0`, `lastFlowSolve.assignedTotal = 0`. +> - **Residual non-convergence** — valve curve where Kv-share is a bad first estimate. Expected: loop exits after `maxPasses: 2` with non-zero residual; assignedTotal < target; behaviour graceful. +> - **Cascaded VGC** — upstream source is another VGC. Expected: source registered, `flow.*` events bound, `getFluidContract()` propagated up. **Not exercised in production.** +> - **Conflicting fluid contracts** — 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` — if `passes === maxPasses` and residual is large, the loop ran out. Raise `flowReconciliation.maxPasses` (no editor field yet — 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` — 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 '' is not valid for 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 — treat as experimental. | `src/sources/fluidContract.SOURCE_SOFTWARE_TYPES` | +| Output port-0 key shape differs from rotatingMachine's | VGC uses `__` (same as MGC) — the inverse of rotatingMachine's `...`. Don't mix. | `src/io/output.getOutput` | + +> Never ship `enableLog: 'debug'` in a demo — 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 — Contracts](Reference-Contracts) | Topic + config + child filters | +| [Reference — Architecture](Reference-Architecture) | Code map, flow-distribution loop, source aggregation | +| [Reference — Limitations](Reference-Limitations) | Known issues and open questions | +| [machineGroupControl — 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 — Topology Patterns](https://gitea.wbd-rd.nl/RnD/EVOLV/wiki/Topology-Patterns) | Where valveGroupControl fits in a larger plant | diff --git a/wiki/Reference-Limitations.md b/wiki/Reference-Limitations.md new file mode 100644 index 0000000..cf07dfa --- /dev/null +++ b/wiki/Reference-Limitations.md @@ -0,0 +1,150 @@ +# Reference — 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` — 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` — VGC's group-level redistribution would discard the upstream split. | +| Curve-based pumps grouped on a manifold | `machineGroupControl` — 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 — 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 — 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.` (`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 — 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` — 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 — 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 — 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 — 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` § 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 — contract text remains correct in spirit | None — 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 — not yet ticketed | +| Cascaded `valvegroupcontrol` as upstream source — 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}` → `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` — 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 — Contracts](Reference-Contracts) | Topic + config + child filters (alias map) | +| [Reference — Architecture](Reference-Architecture) | Code map, flow-distribution loop, source aggregation | +| [Reference — Examples](Reference-Examples) | Shipped flows + debug recipes | +| [machineGroupControl — 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 | diff --git a/wiki/_Sidebar.md b/wiki/_Sidebar.md new file mode 100644 index 0000000..df5c027 --- /dev/null +++ b/wiki/_Sidebar.md @@ -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)