Compare commits

12 Commits

Author SHA1 Message Date
znetsixe
5e2ebe4d96 fix(safety): overfill must keep pumps running, not shut them down
Two hard rules for the safety controller, matching sewer PS design:

1. BELOW stopLevel (dry-run): pumps CANNOT start.
   All downstream equipment shut down. safetyControllerActive=true
   blocks _controlLogic so level control can't restart pumps.
   Only manual override or emergency can change this.

2. ABOVE overflow level (overfill): pumps CANNOT stop.
   Only UPSTREAM equipment is shut down (stop more water coming in).
   Machine groups (downstream pumps) are NOT shut down — they must
   keep draining. safetyControllerActive is NOT set, so _controlLogic
   continues commanding pumps at the demand dictated by the level
   curve (which is >100% near overflow = all pumps at maximum).
   Only manual override or emergency stop can shut pumps during
   an overfill event.

Previously the overfill branch called turnOffAllMachines() on machine
groups AND set safetyControllerActive=true, which shut down the pumps
and blocked level control from restarting them — exactly backwards
for a sewer pumping station where the sewage keeps coming.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 14:10:23 +02:00
znetsixe
e8dd657b4f fix: continuous proportional control — eliminate dead zone between start/stop levels
Previously PS only sent demand to MGC when level > startLevel AND
direction === 'filling'. Between startLevel and stopLevel (the 'dead
zone'), pumps kept running at their last commanded setpoint with no
updates. Basin drained uncontrolled until hitting stopLevel.

Fix: send percControl on every tick when level > stopLevel. The
_scaleLevelToFlowPercent math naturally gives:
  - Positive % above startLevel (pumps ramp up)
  - 0% at exactly startLevel (pumps at minimum)
  - Negative % below startLevel → clamped to 0 → MGC scales to 0
    → pumps ramp down gracefully

This creates smooth visible ramp-up and ramp-down as the basin fills
and drains, instead of a sudden jump at startLevel and stuck ctrl in
the dead zone.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 13:42:43 +02:00
znetsixe
c62d8bc275 fix: deduplicate predicted-flow child registration + single event subscription
Three bugs in registerChild caused multi-counted outflow in _updatePredictedVolume:

1. machinegroup registered twice (line 66 + line 70 both called
   _registerPredictedFlowChild). Fixed: only register in the
   machinegroup branch.

2. Individual machines registered alongside their machinegroup parent.
   Each pump's predicted flow is already included in MGC's aggregated
   total — subscribing to both triple-counts. Fixed: only register
   individual machines when no machinegroup is present (direct-wired
   pumps without MGC).

3. _registerPredictedFlowChild subscribed to BOTH flow.predicted.downstream
   AND flow.predicted.atequipment events. These carry the same total flow
   on two event names — the handler wrote the value twice per tick.
   Fixed: subscribe to ONE event per child (downstream for outflow,
   upstream for inflow).

These are generalizable patterns:
- When a group aggregator exists, subscribe to IT, not its children.
- One event per measurement type per child — pick the most specific.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 13:10:16 +02:00
znetsixe
f869296832 feat: level-based control now reaches machine groups + manual Qd forwarding
Two additions to pumpingStation:

1. _controlLevelBased now calls _applyMachineGroupLevelControl in
   addition to _applyMachineLevelControl when the basin is filling
   above startLevel. Previously only direct-child machines received
   the level-based percent-control signal; in a hierarchical topology
   (PS → MGC → pumps) the machines sit under MGC and PS.machines is
   empty, so the level control never reached them.

2. New 'Qd' input topic + forwardDemandToChildren() method. When PS
   is in 'manual' mode (matching the pattern from rotatingMachine's
   virtualControl), operator demand from a dashboard slider is forwarded
   to all child machine groups and direct machines. When PS is in any
   other mode (levelbased, flowbased, etc.), the Qd msg is silently
   dropped with a debug log so the automatic control isn't overridden.

No breaking changes — existing flows that don't send 'Qd' are unaffected,
and _controlLevelBased's additional call to machineGroupLevelControl
is a no-op when no machine groups are registered.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 08:27:11 +02:00
znetsixe
9f430cebb5 docs: add CLAUDE.md with S88 classification and superproject rule reference
References the flow-layout rule set in the EVOLV superproject
(.claude/rules/node-red-flow-layout.md) so Claude Code sessions working
in this repo know the S88 level, colour, and placement lane for this node.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 07:47:23 +02:00
znetsixe
7d05d37678 Merge commit '762770a' into HEAD
# Conflicts:
#	pumpingStation.html
#	src/nodeClass.js
#	src/specificClass.js
2026-03-31 18:20:09 +02:00
Rene De Ren
762770a063 Expose output format selectors in editor 2026-03-12 16:39:25 +01:00
Rene De Ren
3ff76228eb fix: guard demo IIFE with require.main check
Prevents demo code from executing when module is required by Node-RED,
which caused crashes due to missing measurement data.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 16:38:08 +01:00
Rene De Ren
f01b0bcb19 fix: rename _calcTimeRemaining to _calcRemainingTime + add tests
Fix method name mismatch in tick() that called non-existent _calcTimeRemaining
instead of _calcRemainingTime. Add 27 unit tests for specificClass.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 16:31:47 +01:00
Rene De Ren
4e098eefaa refactor: adopt POSITIONS constants and fix ESLint warnings
Replace hardcoded position strings with POSITIONS.* constants.
Prefix unused variables with _ to resolve no-unused-vars warnings.
Fix no-prototype-builtins where applicable.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 15:35:28 +01:00
Rene De Ren
90f87bb538 Migrate _loadConfig to use ConfigManager.buildConfig()
Replaces manual base config construction with shared buildConfig() method.
Node now only specifies domain-specific config sections.

Part of #1: Extract base config schema

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 14:59:35 +01:00
Rene De Ren
8fe9c7ec05 Fix ESLint errors and bugs
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 13:39:57 +01:00
5 changed files with 447 additions and 43 deletions

23
CLAUDE.md Normal file
View File

@@ -0,0 +1,23 @@
# pumpingStation — Claude Code context
Wet-well basin model and pump orchestration.
Part of the [EVOLV](https://gitea.wbd-rd.nl/RnD/EVOLV) wastewater-automation platform.
## S88 classification
| Level | Colour | Placement lane |
|---|---|---|
| **Process Cell** | `#0c99d9` | L5 |
## Flow layout rules
When wiring this node into a multi-node demo or production flow, follow the
placement rule set in the **EVOLV superproject**:
> `.claude/rules/node-red-flow-layout.md` (in the EVOLV repo root)
Key points for this node:
- Place on lane **L5** (x-position per the lane table in the rule).
- Stack same-level siblings vertically.
- Parent/children sit on adjacent lanes (children one lane left, parent one lane right).
- Wrap in a Node-RED group box coloured `#0c99d9` (Process Cell).

View File

@@ -30,6 +30,8 @@
dryRunThresholdPercent: { value: 2 },
overfillThresholdPercent: { value: 98 },
minHeightBasedOn: { value: "outlet" }, // basis for minimum height check: inlet or outlet
processOutputFormat: { value: "process" },
dbaseOutputFormat: { value: "influxdb" },
// Advanced reference information
refHeight: { value: "NAP" }, // reference height
@@ -339,7 +341,26 @@
<label for="node-input-overfillThresholdPercent" style="padding-left:20px;">High Volume Threshold (%)</label>
<input type="number" id="node-input-overfillThresholdPercent" min="0" max="100" step="0.1" />
</div>
<hr>
<hr>
<h3>Output Formats</h3>
<div class="form-row">
<label for="node-input-processOutputFormat"><i class="fa fa-random"></i> Process Output</label>
<select id="node-input-processOutputFormat" style="width:60%;">
<option value="process">process</option>
<option value="json">json</option>
<option value="csv">csv</option>
</select>
</div>
<div class="form-row">
<label for="node-input-dbaseOutputFormat"><i class="fa fa-database"></i> Database Output</label>
<select id="node-input-dbaseOutputFormat" style="width:60%;">
<option value="influxdb">influxdb</option>
<option value="json">json</option>
<option value="csv">csv</option>
</select>
</div>
<!-- Shared asset/logger/position menus -->
<div id="asset-fields-placeholder"></div>
<div id="logger-fields-placeholder"></div>

View File

@@ -39,29 +39,16 @@ class nodeClass {
const cfgMgr = new configManager();
this.defaultConfig = cfgMgr.getConfig(this.name);
// Merge UI config over defaults
this.config = {
general: {
name: this.name,
id: node.id, // node.id is for the child registration process
unit: uiConfig.unit, // add converter options later to convert to default units (need like a model that defines this which units we are going to use and then conver to those standards)
logging: {
enabled: uiConfig.enableLog,
logLevel: uiConfig.logLevel
}
},
functionality: {
positionVsParent: uiConfig.positionVsParent,// Default to 'atEquipment' if not specified
distance: uiConfig.hasDistance ? uiConfig.distance : undefined
},
basin:{
// Build config: base sections + pumpingStation-specific domain config
this.config = cfgMgr.buildConfig(this.name, uiConfig, node.id, {
basin: {
volume: uiConfig.basinVolume,
height: uiConfig.basinHeight,
heightInlet: uiConfig.heightInlet,
heightOutlet: uiConfig.heightOutlet,
heightOverflow: uiConfig.heightOverflow,
},
hydraulics:{
hydraulics: {
refHeight: uiConfig.refHeight,
minHeightBasedOn: uiConfig.minHeightBasedOn,
basinBottomRef: uiConfig.basinBottomRef,
@@ -82,9 +69,7 @@ class nodeClass {
overfillThresholdPercent: uiConfig.overfillThresholdPercent,
timeleftToFullOrEmptyThresholdSeconds: uiConfig.timeleftToFullOrEmptyThresholdSeconds
}
};
console.log(`position vs child for ${this.name} is ${this.config.functionality.positionVsParent} the distance is ${this.config.functionality.distance}`);
});
// Utility for formatting outputs
this._output = new outputUtils();
@@ -211,20 +196,23 @@ class nodeClass {
case 'changemode':
this.source.changeMode(msg.payload);
break;
case 'registerChild':
case 'registerChild': {
// Register this node as a child of the parent node
const childId = msg.payload;
const childObj = this.RED.nodes.getNode(childId);
this.source.childRegistrationUtils.registerChild(childObj.source ,msg.positionVsParent);
const childObj = this.RED.nodes.getNode(childId);
this.source.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent);
break;
case 'calibratePredictedVolume':
}
case 'calibratePredictedVolume': {
const injectedVol = parseFloat(msg.payload);
this.source.calibratePredictedVolume(injectedVol);
break;
case 'calibratePredictedLevel':
}
case 'calibratePredictedLevel': {
const injectedLevel = parseFloat(msg.payload);
this.source.calibratePredictedLevel(injectedLevel);
break;
}
case 'q_in': {
// payload can be number or { value, unit, timestamp }
const val = Number(msg.payload);
@@ -233,8 +221,27 @@ class nodeClass {
this.source.setManualInflow(val, ts, unit);
break;
}
case 'Qd': {
// Manual demand: operator sets the target output via a
// dashboard slider. Only accepted when PS is in 'manual'
// mode — mirrors how rotatingMachine gates commands by
// mode (virtualControl vs auto).
const demand = Number(msg.payload);
if (!Number.isFinite(demand)) {
this.source.logger.warn(`Invalid Qd value: ${msg.payload}`);
break;
}
if (this.source.mode === 'manual') {
this.source.forwardDemandToChildren(demand).catch((err) =>
this.source.logger.error(`Failed to forward demand: ${err.message}`)
);
} else {
this.source.logger.debug(
`Qd ignored in ${this.source.mode} mode. Switch to manual to use the demand slider.`
);
}
break;
}
}
done();
});

View File

@@ -6,7 +6,8 @@ const {
childRegistrationUtils,
MeasurementContainer,
coolprop,
interpolation
interpolation,
POSITIONS
} = require('generalFunctions');
class PumpingStation {
@@ -62,10 +63,21 @@ class PumpingStation {
this.stations[child.config.general.id] = child;
} else if (softwareType === 'machinegroup') {
this.machineGroups[child.config.general.id] = child;
this._registerPredictedFlowChild(child);
}
if (softwareType === 'machine' || softwareType === 'pumpingstation' || softwareType === 'machinegroup') {
// Register predicted-flow subscription. Only register the HIGHEST-
// level aggregator: if a machinegroup is present, subscribe to IT
// (its flow.predicted already aggregates all child machines). Do NOT
// also subscribe to individual machines — that would double-count
// because each pump's flow is included in the group total.
//
// Individual machines (softwareType='machine') are only subscribed
// when there is NO machinegroup parent — i.e., pumps wired directly
// to the pumping station without an MGC in between.
if (softwareType === 'machinegroup' || softwareType === 'pumpingstation') {
this._registerPredictedFlowChild(child);
} else if (softwareType === 'machine' && Object.keys(this.machineGroups).length === 0) {
// Direct-child machine, no group above it — register its flow.
this._registerPredictedFlowChild(child);
}
}
@@ -96,18 +108,21 @@ class PumpingStation {
const childId = child.config.general.id ?? childName;
let posKey;
let eventNames;
let eventName;
switch (position) {
case 'downstream':
case 'out':
case 'atequipment':
posKey = 'out';
eventNames = ['flow.predicted.downstream', 'flow.predicted.atequipment'];
// Subscribe to ONE event only. 'downstream' is the most specific
// — avoids double-counting from 'atequipment' which carries the
// same total flow on a different event name.
eventName = 'flow.predicted.downstream';
break;
case 'upstream':
case 'in':
posKey = 'in';
eventNames = ['flow.predicted.upstream', 'flow.predicted.atequipment'];
eventName = 'flow.predicted.upstream';
break;
default:
this.logger.warn(`Unsupported predicted flow position "${position}" from ${childName}`);
@@ -131,7 +146,7 @@ class PumpingStation {
.value(eventData.value, ts, unit);
};
eventNames.forEach((ev) => child.measurements.emitter.on(ev, handler));
child.measurements.emitter.on(eventName, handler);
}
/* --------------------------- Calibration --------------------------- */
@@ -249,10 +264,26 @@ class PumpingStation {
return;
}
if (level > startLevel && direction === 'filling') {
const percControl = this._scaleLevelToFlowPercent(level);
this.logger.debug(`Controllevel based => Level ${level} control applying to pump : ${percControl}`);
await this._applyMachineLevelControl(percControl);
// Continuous proportional control: command pumps whenever level is
// above stopLevel. The percControl ramp gives:
// - 0% at minFlowLevel (= startLevel) → pumps barely running
// - linearly up to 100% at maxFlowLevel → all pumps full
// - Below startLevel but above stopLevel: percControl < 0 → clamp
// to 0 → MGC turns off pumps (graceful ramp-down instead of a
// dead zone where pumps keep running at their last setpoint).
if (level > stopLevel) {
const rawPercControl = this._scaleLevelToFlowPercent(level);
const percControl = Math.max(0, rawPercControl);
this.logger.debug(`Controllevel based => Level ${level} percControl ${percControl}`);
if (percControl > 0) {
await this._applyMachineLevelControl(percControl);
await this._applyMachineGroupLevelControl(percControl);
} else {
// Between stopLevel and startLevel with percControl ≤ 0:
// tell MGC to scale back to 0 rather than leaving pumps
// running at the last commanded setpoint.
await this._applyMachineGroupLevelControl(0);
}
}
if (level < stopLevel && direction === 'draining') {
@@ -271,6 +302,38 @@ class PumpingStation {
// placeholder for flow-based logic
}
/**
* Forward a manual demand value to all child machine groups + direct
* machines. Called from the 'Qd' topic handler when PS is in manual
* mode — mirrors how rotatingMachine gates commands by mode.
* @param {number} demand - the operator-set demand (interpretation
* depends on MGC scaling: 'absolute' = m³/h, 'normalized' = 0-100%)
*/
async forwardDemandToChildren(demand) {
this.logger.info(`Manual demand forwarded: ${demand}`);
// Forward to machine groups (MGC)
if (this.machineGroups && Object.keys(this.machineGroups).length > 0) {
await Promise.all(
Object.values(this.machineGroups).map((group) =>
group.handleInput('parent', demand).catch((err) => {
this.logger.error(`Failed to forward demand to group: ${err.message}`);
})
)
);
}
// Forward to direct machines (if any)
if (this.machines && Object.keys(this.machines).length > 0) {
const perMachine = demand / Object.keys(this.machines).length;
for (const machine of Object.values(this.machines)) {
try {
await machine.handleInput('parent', 'execMovement', perMachine);
} catch (err) {
this.logger.error(`Failed to forward demand to machine: ${err.message}`);
}
}
}
}
async _applyMachineGroupLevelControl(percentControl) {
if (!this.machineGroups || Object.keys(this.machineGroups).length === 0) return;
await Promise.all(
@@ -495,6 +558,24 @@ class PumpingStation {
/* --------------------------- Safety --------------------------- */
/**
* Safety controller — two hard rules:
*
* 1. BELOW stopLevel (dry-run): pumps CANNOT start.
* Shuts down all downstream machines + machine groups.
* Only a manual override or emergency can restart them.
* safetyControllerActive = true → blocks _controlLogic.
*
* 2. ABOVE overflow level (overfill): pumps CANNOT stop.
* Shuts down UPSTREAM equipment only (stop more water coming in).
* Does NOT shut down downstream pumps or machine groups — they
* must keep draining. Does NOT set safetyControllerActive — the
* level-based control keeps running so pumps stay at the demand
* dictated by the current level (which will be >100% near overflow,
* meaning all pumps at maximum via the normal demand curve).
* Only a manual override or emergency stop can shut pumps during
* an overfill event.
*/
_safetyController(remainingTime, direction) {
this.safetyControllerActive = false;
@@ -521,10 +602,12 @@ class PumpingStation {
const triggerHighVol = this.basin.maxVolOverflow * ((Number(overfillThresholdPercent) || 0) / 100);
const triggerLowVol = this.basin.minVol * (1 + ((Number(dryRunThresholdPercent) || 0) / 100));
// Rule 1: DRY-RUN — below stopLevel, pumps cannot run.
if (direction === 'draining') {
const timeTriggered = timeProtectionEnabled && remainingTime != null && remainingTime < timeleftToFullOrEmptyThresholdSeconds;
const dryRunTriggered = dryRunEnabled && vol < triggerLowVol;
if (timeTriggered || dryRunTriggered) {
// Shut down all downstream equipment — pumps must stop.
Object.values(this.machines).forEach((machine) => {
const pos = machine?.config?.functionality?.positionVsParent;
if ((pos === 'downstream' || pos === 'atequipment') && machine._isOperationalState()) {
@@ -534,28 +617,38 @@ class PumpingStation {
Object.values(this.stations).forEach((station) => station.handleInput('parent', 'execSequence', 'shutdown'));
Object.values(this.machineGroups).forEach((group) => group.turnOffAllMachines());
this.logger.warn(
`Safe guard triggered: vol=${vol.toFixed(2)} m3, remainingTime=${remainingTime ? remainingTime.toFixed(1) : 'N/A'} s; shutting down downstream equipment`
`Dry-run safety: vol=${vol.toFixed(2)} m3, remainingTime=${remainingTime ? remainingTime.toFixed(1) : 'N/A'} s; shutting down downstream equipment`
);
// Block _controlLogic so level-based control can't restart pumps.
this.safetyControllerActive = true;
}
}
// Rule 2: OVERFILL — above overflow level, pumps cannot stop.
// Only shut down UPSTREAM equipment. Downstream pumps + machine
// groups keep running at whatever the level control demands
// (which will be >100% near overflow = all pumps at max).
// Do NOT set safetyControllerActive — _controlLogic must keep
// running to maintain pump demand.
if (direction === 'filling') {
const timeTriggered = timeProtectionEnabled && remainingTime != null && remainingTime < timeleftToFullOrEmptyThresholdSeconds;
const overfillTriggered = overfillEnabled && vol > triggerHighVol;
if (timeTriggered || overfillTriggered) {
// Shut down UPSTREAM only — stop more water coming in.
Object.values(this.machines).forEach((machine) => {
const pos = machine?.config?.functionality?.positionVsParent;
if (pos === 'upstream' && machine._isOperationalState()) {
machine.handleInput('parent', 'execSequence', 'shutdown');
}
});
Object.values(this.machineGroups).forEach((group) => group.turnOffAllMachines());
Object.values(this.stations).forEach((station) => station.handleInput('parent', 'execSequence', 'shutdown'));
// NOTE: machine groups (downstream pumps) are NOT shut down.
// They must keep draining to prevent overflow from worsening.
this.logger.warn(
`Safe guard triggered: vol=${vol.toFixed(2)} m3, remainingTime=${remainingTime ? remainingTime.toFixed(1) : 'N/A'} s; shutting down upstream equipment`
`Overfill safety: vol=${vol.toFixed(2)} m3, remainingTime=${remainingTime ? remainingTime.toFixed(1) : 'N/A'} s; shutting down upstream equipment only — pumps keep running`
);
this.safetyControllerActive = true;
// NOTE: safetyControllerActive is NOT set — level control
// keeps commanding pumps at maximum demand.
}
}
}

260
test/specificClass.test.js Normal file
View File

@@ -0,0 +1,260 @@
/**
* Tests for pumpingStation specificClass (domain logic).
*
* The pumpingStation class manages a basin (wet well):
* - initBasinProperties: derives surface area, volumes from config
* - _calcVolumeFromLevel / _calcLevelFromVolume: linear geometry
* - _calcDirection: filling / draining / stable from flow diff
* - _callMeasurementHandler: dispatches to type-specific handlers
* - getOutput: builds an output snapshot
*/
const PumpingStation = require('../src/specificClass');
// --------------- helpers ---------------
function makeConfig(overrides = {}) {
const base = {
general: {
name: 'TestStation',
id: 'ps-test-1',
unit: 'm3/h',
logging: { enabled: false, logLevel: 'error' },
},
functionality: {
softwareType: 'pumpingStation',
role: 'stationcontroller',
positionVsParent: 'atEquipment',
},
basin: {
volume: 50, // m3 (empty basin volume)
height: 5, // m
heightInlet: 0.3, // m
heightOutlet: 0.2, // m
heightOverflow: 4.0, // m
},
hydraulics: {
refHeight: 'NAP',
basinBottomRef: 0,
},
};
for (const key of Object.keys(overrides)) {
if (typeof overrides[key] === 'object' && !Array.isArray(overrides[key]) && base[key]) {
base[key] = { ...base[key], ...overrides[key] };
} else {
base[key] = overrides[key];
}
}
return base;
}
// --------------- tests ---------------
describe('pumpingStation specificClass', () => {
describe('constructor / initialization', () => {
it('should create an instance with the given config', () => {
const ps = new PumpingStation(makeConfig());
expect(ps).toBeDefined();
expect(ps.config.general.name).toBe('teststation');
});
it('should initialize state object with default values', () => {
const ps = new PumpingStation(makeConfig());
expect(ps.state).toEqual({ direction: '', netDownstream: 0, netUpstream: 0, seconds: 0 });
});
it('should initialize empty machines, stations, child, parent objects', () => {
const ps = new PumpingStation(makeConfig());
expect(ps.machines).toEqual({});
expect(ps.stations).toEqual({});
expect(ps.child).toEqual({});
expect(ps.parent).toEqual({});
});
});
describe('initBasinProperties()', () => {
it('should calculate surfaceArea = volume / height', () => {
const ps = new PumpingStation(makeConfig());
// 50 / 5 = 10 m2
expect(ps.basin.surfaceArea).toBe(10);
});
it('should calculate maxVol = height * surfaceArea', () => {
const ps = new PumpingStation(makeConfig());
// 5 * 10 = 50
expect(ps.basin.maxVol).toBe(50);
});
it('should calculate maxVolOverflow = heightOverflow * surfaceArea', () => {
const ps = new PumpingStation(makeConfig());
// 4.0 * 10 = 40
expect(ps.basin.maxVolOverflow).toBe(40);
});
it('should calculate minVol = heightOutlet * surfaceArea', () => {
const ps = new PumpingStation(makeConfig());
// 0.2 * 10 = 2
expect(ps.basin.minVol).toBeCloseTo(2, 5);
});
it('should calculate minVolOut = heightInlet * surfaceArea', () => {
const ps = new PumpingStation(makeConfig());
// 0.3 * 10 = 3
expect(ps.basin.minVolOut).toBeCloseTo(3, 5);
});
it('should store the raw config values on basin', () => {
const ps = new PumpingStation(makeConfig());
expect(ps.basin.volEmptyBasin).toBe(50);
expect(ps.basin.heightBasin).toBe(5);
expect(ps.basin.heightInlet).toBe(0.3);
expect(ps.basin.heightOutlet).toBe(0.2);
expect(ps.basin.heightOverflow).toBe(4.0);
});
});
describe('_calcVolumeFromLevel()', () => {
let ps;
beforeAll(() => { ps = new PumpingStation(makeConfig()); });
it('should return level * surfaceArea', () => {
// surfaceArea = 10, level = 2 => 20
expect(ps._calcVolumeFromLevel(2)).toBe(20);
});
it('should return 0 for level = 0', () => {
expect(ps._calcVolumeFromLevel(0)).toBe(0);
});
it('should clamp negative levels to 0', () => {
expect(ps._calcVolumeFromLevel(-3)).toBe(0);
});
});
describe('_calcLevelFromVolume()', () => {
let ps;
beforeAll(() => { ps = new PumpingStation(makeConfig()); });
it('should return volume / surfaceArea', () => {
// surfaceArea = 10, vol = 20 => 2
expect(ps._calcLevelFromVolume(20)).toBe(2);
});
it('should return 0 for volume = 0', () => {
expect(ps._calcLevelFromVolume(0)).toBe(0);
});
it('should clamp negative volumes to 0', () => {
expect(ps._calcLevelFromVolume(-10)).toBe(0);
});
});
describe('volume/level roundtrip', () => {
it('should roundtrip level -> volume -> level', () => {
const ps = new PumpingStation(makeConfig());
const level = 2.7;
const vol = ps._calcVolumeFromLevel(level);
const levelBack = ps._calcLevelFromVolume(vol);
expect(levelBack).toBeCloseTo(level, 10);
});
});
describe('_calcDirection()', () => {
let ps;
beforeAll(() => { ps = new PumpingStation(makeConfig()); });
it('should return "filling" for positive flow above threshold', () => {
expect(ps._calcDirection(0.01)).toBe('filling');
});
it('should return "draining" for negative flow below negative threshold', () => {
expect(ps._calcDirection(-0.01)).toBe('draining');
});
it('should return "stable" for flow near zero (within threshold)', () => {
expect(ps._calcDirection(0.0005)).toBe('stable');
expect(ps._calcDirection(-0.0005)).toBe('stable');
expect(ps._calcDirection(0)).toBe('stable');
});
});
describe('_callMeasurementHandler()', () => {
it('should not throw for flow and temperature measurement types', () => {
const ps = new PumpingStation(makeConfig());
// flow and temperature handlers are empty stubs, safe to call
expect(() => ps._callMeasurementHandler('flow', 0.5, 'downstream', {})).not.toThrow();
expect(() => ps._callMeasurementHandler('temperature', 15, 'atEquipment', {})).not.toThrow();
});
it('should dispatch to the correct handler based on measurement type', () => {
const ps = new PumpingStation(makeConfig());
// Verify the switch dispatches by checking it does not warn for known types
// pressure handler stores values and attempts coolprop calculation
// level handler stores values and computes volume
// We verify the dispatch logic by calling with type and checking no unhandled error
const spy = jest.spyOn(ps, 'updateMeasuredFlow');
ps._callMeasurementHandler('flow', 0.5, 'downstream', {});
expect(spy).toHaveBeenCalledWith(0.5, 'downstream', {});
spy.mockRestore();
});
});
describe('getOutput()', () => {
it('should return an object containing state and basin', () => {
const ps = new PumpingStation(makeConfig());
const out = ps.getOutput();
expect(out).toHaveProperty('state');
expect(out).toHaveProperty('basin');
expect(out.state).toBe(ps.state);
expect(out.basin).toBe(ps.basin);
});
it('should include measurement keys in the output', () => {
const ps = new PumpingStation(makeConfig());
const out = ps.getOutput();
// After initialization the predicted volume is set
expect(typeof out).toBe('object');
});
});
describe('_calcRemainingTime()', () => {
it('should not throw when called with a level and variant', () => {
const ps = new PumpingStation(makeConfig());
// Should not throw even with no measurement data; it will just find null diffs
expect(() => ps._calcRemainingTime(2, 'predicted')).not.toThrow();
});
});
describe('tick()', () => {
it('should call _updateVolumePrediction and _calcNetFlow', () => {
const ps = new PumpingStation(makeConfig());
const spyVol = jest.spyOn(ps, '_updateVolumePrediction');
const spyNet = jest.spyOn(ps, '_calcNetFlow');
// stub _calcRemainingTime to avoid needing full measurement data
ps._calcRemainingTime = jest.fn();
ps.tick();
expect(spyVol).toHaveBeenCalledWith('out');
expect(spyVol).toHaveBeenCalledWith('in');
expect(spyNet).toHaveBeenCalled();
spyVol.mockRestore();
spyNet.mockRestore();
});
});
describe('edge cases', () => {
it('should handle basin with zero height gracefully', () => {
// surfaceArea = volume / height => division by 0 gives Infinity
const config = makeConfig({ basin: { volume: 50, height: 0, heightInlet: 0, heightOutlet: 0, heightOverflow: 0 } });
const ps = new PumpingStation(config);
expect(ps.basin.surfaceArea).toBe(Infinity);
});
it('should handle basin with very small dimensions', () => {
const config = makeConfig({ basin: { volume: 0.001, height: 0.001, heightInlet: 0, heightOutlet: 0, heightOverflow: 0.0005 } });
const ps = new PumpingStation(config);
expect(ps.basin.surfaceArea).toBeCloseTo(1, 5);
});
});
});