From 8871f4a8f39ec96b663c8c68f497bb8395cd9b7a Mon Sep 17 00:00:00 2001 From: Dirk-Jan Faber Date: Tue, 1 Dec 2026 12:38:09 +0000 Subject: [PATCH] feat(s2-resource): FRBC as a built-in control type (#125) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A battery, boiler or buffer tank needed s2-rm, s2-frbc and s2-frbc-config wired up by hand, with fill rates worked out in %/s or °C/s. s2-resource now does FRBC the way it does OMBC: pick a preset, enter the capacity and the power of each operation mode. The runtime only reads the system description JSON. The Friendly form is saved next to it and shown only while it would write exactly that JSON. So JSON edited by hand is never overwritten by a form that does not know about the edit, without a flag saying which view was used last. S2 ids must not change on a save: a CEM holds instructions and timer statuses that refer to them. The actuator id and the operation mode ids are saved with the form; timer and transition ids are derived from those. An instruction is confirmed by the flow with ActuatorConfirmation, or by the node itself with the new auto-confirm option of FRBCController. That option is a property of its own, off by default, so a node that used OMBC's auto-confirm does not silently confirm FRBC instructions too. A node without a valid FRBC system description does not start. An RM that advertises FRBC and then has nothing to describe leaves the CEM waiting. Closes #125. --- CHANGELOG.md | 4 + README.md | 5 +- examples/s2-resource-frbc-boiler.json | 126 ++++++++++++ resources/s2-common.js | 14 +- resources/s2-frbc-editor.js | 198 +++++++++++++++++- src/lib/s2/frbc-controller.ts | 9 +- src/nodes/s2-resource/index.html | 277 +++++++++++++++++++++++++- src/nodes/s2-resource/index.ts | 91 +++++++-- test/lib/frbc-controller.test.ts | 37 +++- test/nodes/s2-resource.test.ts | 162 +++++++++++++++ test/resources/s2-common.test.ts | 12 ++ test/resources/s2-frbc-editor.test.ts | 197 ++++++++++++++++++ 12 files changed, 1096 insertions(+), 36 deletions(-) create mode 100644 examples/s2-resource-frbc-boiler.json create mode 100644 test/resources/s2-frbc-editor.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index f28e448..986dd7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [Unreleased] +### Added + +- `s2-resource`: FRBC as a built-in control type, next to OMBC and None. Pick a preset (battery, hot water boiler, heat pump buffer or custom), enter the capacity or tank volume and the power range of each operation mode, and the node works out the fill rates. The fill level goes in as a plain number on the input; instructions come out as in `s2-frbc`, confirmed by the flow or by the new *Auto-confirm instructions* option. More complex setups can edit the JSON, or use `s2-frbc`. New example: `s2-resource-frbc-boiler`. (#125) + ### Fixed - `s2-rm` and `s2-resource` accepted a `RevokeObject` whose `object_type` named another control type than the open instruction with that ID. A queued instruction was then revoked anyway, and one already passed on to the flow got OK without a `REVOKED`. They now answer such a revoke with `PERMANENT_ERROR`. (#123) diff --git a/README.md b/README.md index 7325de3..9fbadb4 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Below, each node's internal type (`s2-resource`, `s2-rm`, ...) is used for ident | Node | Description | |------|-------------| -| **s2-resource** | Composite S2 Resource Manager - combines `s2-rm`, a built-in transport (`WebSocket`, `D-Bus`, or `External`), and a built-in control type (`OMBC` or `None`) behind one tabbed edit dialog. Recommended starting point: a minimal S2 flow needs just this one node instead of wiring the nodes below together. | +| **s2-resource** | Composite S2 Resource Manager - combines `s2-rm`, a built-in transport (`WebSocket`, `D-Bus`, or `External`), and a built-in control type (`OMBC`, `FRBC` or `None`) behind one tabbed edit dialog. Recommended starting point: a minimal S2 flow needs just this one node instead of wiring the nodes below together. | | **s2-rm** | S2 Resource Manager - generic S2 protocol state machine (handshake, control-type selection, instruction ack/routing) for a connected CEM, independent of any specific control type | | **s2-rm-config** | Configuration for RM identity: resource ID, name, roles, control types, serial number, power measurement/forecast | | **s2-ombc** | Operation Mode Based Control - declares the OMBC system description, resolves OMBC instructions, and confirms operation mode changes back to the CEM | @@ -60,7 +60,7 @@ npm install node-red-contrib-s2 ## Quick start -For the simplest possible flow, drag in a single **s2-resource** node instead: pick `Transport: WebSocket`, `D-Bus`, or `External` and `Control type: OMBC` or `None` on its tabbed edit dialog, and it behaves like steps 1-5 below wired together (see the node's own help panel for its full tabbed configuration). The rest of this section covers the fully wired-together model, which `s2-resource` builds on and which you'd still use if you want OMBC/PEBC as separate nodes, or multiple resources sharing one CEM connection. +For the simplest possible flow, drag in a single **s2-resource** node instead: pick `Transport: WebSocket`, `D-Bus`, or `External` and `Control type: OMBC`, `FRBC` or `None` on its tabbed edit dialog, and it behaves like steps 1-5 below wired together (see the node's own help panel for its full tabbed configuration). The rest of this section covers the fully wired-together model, which `s2-resource` builds on and which you'd still use if you want OMBC/PEBC as separate nodes, or multiple resources sharing one CEM connection. 1. Add an **s2-rm-config** node and configure your Resource Manager identity (name, roles, control types). 2. Add an **s2-cem-config** node with the WebSocket URL and credentials of your CEM. @@ -82,6 +82,7 @@ Import any of these from the Node-RED palette manager's "Import Examples" menu ( | Example | Demonstrates | |---------|--------------| +| `s2-resource-frbc-boiler` | A hot water boiler as an FRBC resource in a single **s2-resource** node (`Transport: WebSocket`, `Control type: FRBC`, preset *Hot water boiler*), with a function node simulating the water temperature and confirming each instruction - no real hardware required. | | `s2-resource-quickstart` | The recommended starting point: the same boiler-OMBC scenario below, collapsed to a single **s2-resource** node (`Transport: WebSocket`, `Control type: OMBC`) plus the **s2-cem-config** it shares its CEM connection with. | | `boiler-ombc-demo` | The fully wired-together model: **s2-rm-config** + **s2-cem-config** + **s2-websocket** + **s2-rm** + **s2-ombc-config** + **s2-ombc**, simulating a single-phase electric boiler with two operation modes (Standby/off, Normal 2500W) - no real hardware required. | | `s2-dbus-quickstart` | The same boiler-OMBC scenario as `boiler-ombc-demo`, but over the **s2-dbus** transport (Venus OS D-Bus) instead of WebSocket - for a CEM running on the same GX device. | diff --git a/examples/s2-resource-frbc-boiler.json b/examples/s2-resource-frbc-boiler.json new file mode 100644 index 0000000..4ebb899 --- /dev/null +++ b/examples/s2-resource-frbc-boiler.json @@ -0,0 +1,126 @@ +[ + { + "id": "d8a320bc185dd550", + "type": "tab", + "label": "s2-resource FRBC boiler", + "disabled": false, + "info": "A hot water boiler as an FRBC resource in a single s2-resource node (Control type: FRBC, preset Hot water boiler, 200 l, heat 0-3000 W). A function node simulates the water temperature, so no hardware is needed. Point the s2-cem-config at your CEM.", + "env": [] + }, + { + "id": "dcd1adafe7a95c5e", + "type": "comment", + "z": "d8a320bc185dd550", + "name": "Point \"Demo CEM\" at your CEM, then deploy", + "info": "", + "x": 230, + "y": 60, + "wires": [] + }, + { + "id": "2b89d879ecf750e3", + "type": "s2-cem-config", + "name": "Demo CEM", + "url": "ws://localhost:8080/s2-message-handler", + "apiPrefix": "" + }, + { + "id": "d14f2d7c29405690", + "type": "s2-resource", + "version": "0.9.7", + "z": "d8a320bc185dd550", + "name": "Boiler", + "rmName": "RM: Hot water boiler", + "resourceId": "cc94a3c3-8555-4041-b761-8e2386de06d8", + "roles": "ENERGY_CONSUMER", + "controlTypes": "FILL_RATE_BASED_CONTROL", + "providesPowerMeasurement": "3_PHASE_SYMMETRIC", + "providesForecast": false, + "manufacturer": "Victron Energy", + "model": "Virtual RM", + "serialNumber": "", + "firmwareVersion": "1.0.0", + "instructionPollIntervalMs": 2000, + "skipInstructionStatus": false, + "transport": "websocket", + "cem": "2b89d879ecf750e3", + "reconnectInterval": 5, + "debug": true, + "controlType": "frbc", + "systemDescription": "{\"operationModes\":[{\"id\":\"7c1b2a3d-4e5f-4061-8a9b-0c1d2e3f4a5b\",\"diagnostic_label\":\"Standby/off\",\"power_ranges\":[{\"commodity_quantity\":\"ELECTRIC.POWER.3_PHASE_SYMMETRIC\",\"start_of_range\":0,\"end_of_range\":0}],\"abnormal_condition_only\":false},{\"id\":\"9e2c3b4d-5f60-4172-9b0c-1d2e3f4a5b6c\",\"diagnostic_label\":\"Normal operation\",\"power_ranges\":[{\"commodity_quantity\":\"ELECTRIC.POWER.3_PHASE_SYMMETRIC\",\"start_of_range\":0,\"end_of_range\":2500}],\"abnormal_condition_only\":false}],\"transitions\":[{\"id\":\"a1b2c3d4-e5f6-4283-ac1d-2e3f4a5b6c7d\",\"from\":\"7c1b2a3d-4e5f-4061-8a9b-0c1d2e3f4a5b\",\"to\":\"9e2c3b4d-5f60-4172-9b0c-1d2e3f4a5b6c\",\"start_timers\":[],\"blocking_timers\":[],\"abnormal_condition_only\":false},{\"id\":\"b2c3d4e5-f607-4394-bd2e-3f4a5b6c7d8e\",\"from\":\"9e2c3b4d-5f60-4172-9b0c-1d2e3f4a5b6c\",\"to\":\"7c1b2a3d-4e5f-4061-8a9b-0c1d2e3f4a5b\",\"start_timers\":[],\"blocking_timers\":[],\"abnormal_condition_only\":false}],\"timers\":[]}", + "outputs": 1, + "x": 420, + "y": 200, + "wires": [ + [ + "a3e57e828ee30d59", + "30c1b5ae105df76e" + ] + ], + "frbcForm": "{\"preset\":\"boiler\",\"unit\":\"°C\",\"min\":10,\"max\":80,\"size\":200,\"cop\":null,\"minOn\":0,\"minOff\":0,\"modes\":[{\"id\":\"1df32985-7d4d-4dcf-805c-ff5b9ec1abc0\",\"label\":\"Heat\",\"from\":0,\"to\":3000},{\"id\":\"83ac070f-ba25-4f5e-a708-a3605d1f6b38\",\"label\":\"Idle\",\"from\":0,\"to\":0}],\"actuatorId\":\"7fc657a3-8a73-49e0-ab4d-e90ae82f2c84\"}", + "frbcSystemDescription": "{\"actuators\":[{\"id\":\"7fc657a3-8a73-49e0-ab4d-e90ae82f2c84\",\"diagnostic_label\":\"Heating element\",\"supported_commodities\":[\"ELECTRICITY\"],\"operation_modes\":[{\"id\":\"1df32985-7d4d-4dcf-805c-ff5b9ec1abc0\",\"diagnostic_label\":\"Heat\",\"abnormal_condition_only\":false,\"elements\":[{\"fill_level_range\":{\"start_of_range\":10,\"end_of_range\":80},\"fill_rate\":{\"start_of_range\":0,\"end_of_range\":0.00358337},\"power_ranges\":[{\"commodity_quantity\":\"ELECTRIC.POWER.3_PHASE_SYMMETRIC\",\"start_of_range\":0,\"end_of_range\":3000}]}]},{\"id\":\"83ac070f-ba25-4f5e-a708-a3605d1f6b38\",\"diagnostic_label\":\"Idle\",\"abnormal_condition_only\":false,\"elements\":[{\"fill_level_range\":{\"start_of_range\":10,\"end_of_range\":80},\"fill_rate\":{\"start_of_range\":0,\"end_of_range\":0},\"power_ranges\":[{\"commodity_quantity\":\"ELECTRIC.POWER.3_PHASE_SYMMETRIC\",\"start_of_range\":0,\"end_of_range\":0}]}]}],\"transitions\":[{\"id\":\"1df32985-7d4d-4dcf-805c-a3605d1f6b38\",\"from\":\"1df32985-7d4d-4dcf-805c-ff5b9ec1abc0\",\"to\":\"83ac070f-ba25-4f5e-a708-a3605d1f6b38\",\"start_timers\":[],\"blocking_timers\":[],\"abnormal_condition_only\":false},{\"id\":\"83ac070f-ba25-4f5e-a708-ff5b9ec1abc0\",\"from\":\"83ac070f-ba25-4f5e-a708-a3605d1f6b38\",\"to\":\"1df32985-7d4d-4dcf-805c-ff5b9ec1abc0\",\"start_timers\":[],\"blocking_timers\":[],\"abnormal_condition_only\":false}],\"timers\":[]}],\"storage\":{\"diagnostic_label\":\"Hot water boiler\",\"fill_level_label\":\"°C\",\"provides_leakage_behaviour\":false,\"provides_fill_level_target_profile\":false,\"provides_usage_forecast\":false,\"fill_level_range\":{\"start_of_range\":10,\"end_of_range\":80}}}", + "frbcAutoConfirmInstructions": false + }, + { + "id": "33c4d8ff74eac73a", + "type": "inject", + "z": "d8a320bc185dd550", + "name": "every 10 s", + "props": [ + { + "p": "payload" + } + ], + "repeat": "10", + "crontab": "", + "once": true, + "onceDelay": "1", + "topic": "", + "payload": "", + "payloadType": "date", + "x": 140, + "y": 140, + "wires": [ + [ + "a3e57e828ee30d59" + ] + ] + }, + { + "id": "a3e57e828ee30d59", + "type": "function", + "z": "d8a320bc185dd550", + "name": "Boiler simulator", + "func": "// Simulates a 200 l hot water boiler: integrates the instructed fill rate (°C per second) minus\n// a small hot-water draw, sends the temperature every tick, and confirms each instruction straight\n// away (a real flow would confirm once the heater actually switched).\nconst DRAW_PER_S = 0.0005 // °C per second taken out by hot water use\nconst now = Date.now()\nconst last = context.get('last') ?? now\nconst rate = context.get('rate') ?? 0\nlet temp = context.get('temp') ?? 45\ntemp = Math.min(80, Math.max(10, temp + (rate - DRAW_PER_S) * (now - last) / 1000))\ncontext.set('temp', temp)\ncontext.set('last', now)\n\nif (msg.topic === 'ActuatorInstruction') {\n context.set('rate', msg.payload.fillRate)\n node.status({ fill: 'blue', shape: 'dot', text: `${msg.payload.operationModeLabel} - ${temp.toFixed(1)} °C` })\n return { topic: 'ActuatorConfirmation', payload: msg.payload, cemId: msg.cemId }\n}\nif (msg.topic === 'Selected' || msg.topic === 'Deselected' || msg.topic === 'Revoked') return null\nnode.status({ fill: 'grey', shape: 'ring', text: `${temp.toFixed(1)} °C` })\n// A plain number is the fill level, here the water temperature.\nreturn { payload: Math.round(temp * 10) / 10 }", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 330, + "y": 140, + "wires": [ + [ + "d14f2d7c29405690" + ] + ] + }, + { + "id": "30c1b5ae105df76e", + "type": "debug", + "z": "d8a320bc185dd550", + "name": "debug - instructions", + "active": true, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 660, + "y": 200, + "wires": [] + } +] diff --git a/resources/s2-common.js b/resources/s2-common.js index 3c08380..361c2b6 100644 --- a/resources/s2-common.js +++ b/resources/s2-common.js @@ -112,10 +112,11 @@ window.__s2Common.versionAtLeast = function (version, minimum) { } // Keeps a dialog's Update or Done button $ok disabled until a delayed check of its values passes, -// and shows the check's errors in $err. check(done) calls done({ valid, errors }). Pass the button -// and error box found in oneditprepare, and let check read inputs captured there with val(). The -// timer may fire after the dialog closed, or while the "..." JSON editor has it detached: then a -// lookup by id finds nothing, typedInput() throws, and another dialog's button may have that id. +// and shows the check's errors, if any, in $err. check(done) calls done({ valid, errors }). Pass +// the button and error box found in oneditprepare, and let check read inputs captured there with +// val(). The timer may fire after the dialog closed, or while the "..." JSON editor has it +// detached: then a lookup by id finds nothing, typedInput() throws, and another dialog's button +// may have that id. window.__s2Common.validationGate = function ($ok, $err, check) { let timer = null let seq = 0 @@ -123,11 +124,12 @@ window.__s2Common.validationGate = function ($ok, $err, check) { function set (result) { const valid = !!result.valid $ok.prop('disabled', !valid).toggleClass('ui-state-disabled', !valid) - if (valid) { + const errors = result.errors || [] + if (valid || errors.length === 0) { $err.hide() } else { $err.empty() - ;(result.errors || []).forEach(function (e) { $('
').text(e).appendTo($err) }) + errors.forEach(function (e) { $('
').text(e).appendTo($err) }) $err.show() } } diff --git a/resources/s2-frbc-editor.js b/resources/s2-frbc-editor.js index a35b228..f03a81d 100644 --- a/resources/s2-frbc-editor.js +++ b/resources/s2-frbc-editor.js @@ -2,7 +2,8 @@ // Editor helpers for s2-frbc-config: the example configuration a new node starts with, and the // save-time validation call (served by s2-frbc-config/index.ts - the generated schema validators -// can't run in the browser). +// can't run in the browser). And for s2-resource's FRBC section: the system description its +// Friendly form stands for. window.__s2FrbcEditor = window.__s2FrbcEditor || (function () { // A heat pump heating a buffer tank, fill level in % of the tank's usable heat. Fill rates and @@ -80,9 +81,202 @@ window.__s2FrbcEditor = window.__s2FrbcEditor || (function () { }) } + // -- s2-resource's Friendly form -- + // + // A form is { preset, actuatorId, unit, min, max, size, cop, minOn, minOff, modes }: one storage + // with fill levels min-max in `unit`, and one actuator with per operation mode { id, label, from, + // to } a power range in W. minOn/minOff are in minutes. A number not filled in is null. + + // What a preset fills in, what its `size` is, and the fill level units one watt adds per second + // (no losses; water takes 4186 J per litre per °C). Power ranges are left open on purpose: they + // depend on the device, and a wrong default makes the CEM plan wrong. + const HEAT_OR_IDLE = [{ label: 'Heat', from: 0, to: null }, { label: 'Idle', from: 0, to: 0 }] + const PRESETS = { + battery: { + actuator: 'Battery', + storage: 'Battery', + unit: '%', + min: 0, + max: 100, + sizeLabel: 'Capacity', + sizeUnit: 'kWh', + perWatt: function (form) { return 1 / (form.size * 1000 * 36) }, + minOn: 0, + minOff: 0, + modes: [{ label: 'Charge', from: 0, to: null }, { label: 'Idle', from: 0, to: 0 }, { label: 'Discharge', from: null, to: 0 }] + }, + boiler: { + actuator: 'Heating element', + storage: 'Hot water boiler', + unit: '°C', + min: 10, + max: 80, + sizeLabel: 'Volume', + sizeUnit: 'litres', + perWatt: function (form) { return 1 / (form.size * 4186) }, + minOn: 0, + minOff: 0, + modes: HEAT_OR_IDLE + }, + heatpump: { + actuator: 'Heat pump', + storage: 'Buffer tank', + unit: '°C', + min: 20, + max: 60, + sizeLabel: 'Volume', + sizeUnit: 'litres', + perWatt: function (form) { return form.cop / (form.size * 4186) }, + // Keeps the CEM from cycling the compressor. + minOn: 5, + minOff: 5, + modes: HEAT_OR_IDLE + }, + custom: { + actuator: 'Actuator', + storage: 'Storage', + unit: '', + min: null, + max: null, + sizeLabel: 'Energy per unit', + sizeUnit: 'Wh', + perWatt: function (form) { return 1 / (form.size * 3600) }, + minOn: 0, + minOff: 0, + modes: [] + } + } + + // The form a preset starts with, minus actuatorId. newId() makes the operation mode ids. + function presetForm (name, newId) { + const preset = PRESETS[name] + return { + preset: name, + unit: preset.unit, + min: preset.min, + max: preset.max, + size: null, + cop: null, + minOn: preset.minOn, + minOff: preset.minOff, + modes: preset.modes.map(function (mode) { + return { id: newId(), label: mode.label, from: mode.from, to: mode.to } + }) + } + } + + function isNumber (value) { + return typeof value === 'number' && isFinite(value) + } + + // What still keeps a form from being a system description, in the form's own words. Empty when + // nothing does. + function formProblems (form) { + const preset = PRESETS[form.preset] + const problems = [] + if (!(isNumber(form.min) && isNumber(form.max) && form.min < form.max)) { + problems.push('Fill level: enter a range that starts below its end') + } + if (!(isNumber(form.size) && form.size > 0)) problems.push(preset.sizeLabel + ': enter a value above 0') + if (form.preset === 'heatpump' && !(isNumber(form.cop) && form.cop > 0)) problems.push('COP: enter a value above 0') + if (form.modes.length === 0) problems.push('Add at least one operation mode') + form.modes.forEach(function (mode) { + const label = mode.label || 'Operation mode' + if (!(isNumber(mode.from) && isNumber(mode.to))) problems.push(label + ': enter its power range') + else if (mode.from > mode.to) problems.push(label + ': enter a power range that starts at or below its end') + }) + return problems + } + + // An id that differs from `id` in its last 12 digits only. Timer and transition ids are derived + // from saved ids instead of generated, so they are the same on every save - a CEM may hold timer + // statuses that refer to them - and still UUIDs. Unique because the saved ids are random. + function derivedId (id, tail) { + return id.slice(0, -12) + tail + } + + // The FRBC system description a form stands for: the same form always gives the same one. + function systemDescription (form) { + const preset = PRESETS[form.preset] + const perWatt = preset.perWatt(form) + // Per second, so tiny: six significant digits keep the JSON readable and are far finer than + // any device's power reading. + function fillRate (watts) { return Number((watts * perWatt).toPrecision(6)) } + const fillLevelRange = { start_of_range: form.min, end_of_range: form.max } + + const timers = [] + function timer (label, minutes, tail) { + if (!(minutes > 0)) return null + const id = derivedId(form.actuatorId, tail) + timers.push({ id: id, diagnostic_label: label, duration: Math.round(minutes * 60000) }) + return id + } + const minOnTimer = timer('Minimum on time', form.minOn, '000000000001') + const minOffTimer = timer('Minimum off time', form.minOff, '000000000002') + function isOn (mode) { + return mode.from !== 0 || mode.to !== 0 + } + function timerOf (mode) { + const id = isOn(mode) ? minOnTimer : minOffTimer + return id ? [id] : [] + } + + // Every mode can switch to every other one. Only switching on or off is timed: it starts the + // timer of the state it enters, and waits for the timer of the state it leaves. + const transitions = [] + form.modes.forEach(function (from) { + form.modes.forEach(function (to) { + if (from === to) return + const timed = isOn(from) !== isOn(to) + transitions.push({ + id: derivedId(from.id, to.id.slice(-12)), + from: from.id, + to: to.id, + start_timers: timed ? timerOf(to) : [], + blocking_timers: timed ? timerOf(from) : [], + abnormal_condition_only: false + }) + }) + }) + + return { + actuators: [{ + id: form.actuatorId, + diagnostic_label: preset.actuator, + supported_commodities: ['ELECTRICITY'], + operation_modes: form.modes.map(function (mode) { + return { + id: mode.id, + diagnostic_label: mode.label, + abnormal_condition_only: false, + elements: [{ + fill_level_range: fillLevelRange, + fill_rate: { start_of_range: fillRate(mode.from), end_of_range: fillRate(mode.to) }, + power_ranges: [{ commodity_quantity: 'ELECTRIC.POWER.3_PHASE_SYMMETRIC', start_of_range: mode.from, end_of_range: mode.to }] + }] + } + }), + transitions: transitions, + timers: timers + }], + storage: { + diagnostic_label: preset.storage, + fill_level_label: form.unit, + provides_leakage_behaviour: false, + provides_fill_level_target_profile: false, + provides_usage_forecast: false, + fill_level_range: fillLevelRange + } + } + } + return { exampleSystemDescription: exampleSystemDescription, exampleLeakageBehaviour: exampleLeakageBehaviour, - validateConfig: validateConfig + validateConfig: validateConfig, + presets: PRESETS, + presetForm: presetForm, + formProblems: formProblems, + systemDescription: systemDescription } })() diff --git a/src/lib/s2/frbc-controller.ts b/src/lib/s2/frbc-controller.ts index 4045f7d..375f200 100644 --- a/src/lib/s2/frbc-controller.ts +++ b/src/lib/s2/frbc-controller.ts @@ -62,7 +62,7 @@ const DEVICE_STATE_KEY = 's2FrbcState' const OPEN_INSTRUCTIONS_KEY = 's2FrbcOpenInstructions' // Bounds openInstructions when a CEM keeps instructing without the flow ever confirming. const MAX_OPEN_INSTRUCTIONS = 50 -const FLOW_TOPICS = ['StorageStatus', 'ActuatorConfirmation', 'UsageForecast', 'FillLevelTargetProfile', 'TimerStatus'] +export const FLOW_TOPICS = ['StorageStatus', 'ActuatorConfirmation', 'UsageForecast', 'FillLevelTargetProfile', 'TimerStatus'] function label (item: { id: string, diagnostic_label?: string }): string { return item.diagnostic_label || item.id @@ -259,6 +259,10 @@ export interface FRBCControllerOptions { onWarn: (message: string) => void getContextValue: (key: string) => unknown setContextValue: (key: string, value: unknown) => void + /** Confirm every emitted ActuatorInstruction right away, as if the flow sent an + * ActuatorConfirmation for it. For a device that can't report its own state; a flow that + * confirms what the hardware really did should leave this off. Defaults to false. */ + autoConfirmInstructions?: boolean } /** @@ -606,6 +610,9 @@ export class FRBCController { cemId, rawS2Message: instr }) + if (this.opts.autoConfirmInstructions) { + this.handleActuatorConfirmation({ actuator: actuator.id, operationMode: mode.id, factor }, () => [cemId]) + } } // s2-rm already answers a revoke for an instruction it still holds (execution_time not reached). diff --git a/src/nodes/s2-resource/index.html b/src/nodes/s2-resource/index.html index da893bb..a531715 100644 --- a/src/nodes/s2-resource/index.html +++ b/src/nodes/s2-resource/index.html @@ -1,8 +1,10 @@ + diff --git a/src/nodes/s2-resource/index.ts b/src/nodes/s2-resource/index.ts index 6d78de6..632720e 100644 --- a/src/nodes/s2-resource/index.ts +++ b/src/nodes/s2-resource/index.ts @@ -2,6 +2,7 @@ import { NodeRedApp, NodeConfig, NodeRedNode, NodeMessage, NodeRedStatus } from import { S2CemConfigNode, S2DbusConfigNode } from '../../types/config-nodes' import { S2ResourceManager } from '../../lib/s2/resource-manager' import { OMBCController, DESCRIBED_MODE_REQUEST_SINCE } from '../../lib/s2/ombc-controller' +import { FRBCConfig, FRBCController, FLOW_TOPICS, parseFRBCConfig, validateFRBCConfig } from '../../lib/s2/frbc-controller' import { versionAtLeast } from '../../lib/s2/behaviour-version' import { S2WebSocketTransport } from '../../lib/transport/websocket' import { S2DbusTransport } from '../../lib/transport/dbus' @@ -13,7 +14,7 @@ import { publishToDebugSidebar, parseForDebugSidebar } from '../../lib/node-red- const KNOWN_DBUS_DEVICE_TYPES = ['acload', 'heatpump'] type Transport = 'websocket' | 'dbus' | 'external' -type ControlTypeSetting = 'ombc' | 'none' +type ControlTypeSetting = 'ombc' | 'frbc' | 'none' interface S2ResourceConfig extends NodeConfig { rmName: string @@ -39,6 +40,9 @@ interface S2ResourceConfig extends NodeConfig { systemDescription?: string defaultOperationModeId?: string autoConfirmInstructions?: boolean + /** FRBC.SystemDescription as JSON, like s2-frbc-config's. Absent on nodes saved before FRBC was built in. */ + frbcSystemDescription?: string + frbcAutoConfirmInstructions?: boolean /** Release whose behaviour this node has - see behaviour-version.ts. Absent on nodes deployed before. */ version?: string } @@ -47,8 +51,8 @@ interface S2ResourceConfig extends NodeConfig { * s2-resource node - composite S2 Resource Manager * * Combines s2-rm's session state machine, a built-in transport (WebSocket, - * D-Bus, or none for external wiring), and a built-in control type (OMBC, or - * none for external wiring) behind one tabbed edit dialog. See + * D-Bus, or none for external wiring), and a built-in control type (OMBC, FRBC, + * or none for external wiring) behind one tabbed edit dialog. See * openspec/changes/2026-09-07-s2-resource-composite-node. * * The D-Bus transport reproduces s2-dbus's core session contract @@ -60,17 +64,19 @@ interface S2ResourceConfig extends NodeConfig { * Input (always 1): commands from an external transport and/or external * control-type node, in the exact shapes s2-rm's single input accepts * today, PLUS ModeConfirmation messages for a built-in OMBC control type - * (matching s2-ombc's input contract), PLUS - when Transport: D-Bus - a + * (matching s2-ombc's input contract) or the flow topics of a built-in FRBC + * control type (matching s2-frbc's, and a bare number as the fill level), PLUS - when Transport: D-Bus - a * power-measurement value update at any time (e.g. `{ payload: { 'Ac/Power': 1500 } }` or * `{ payload: { values: 1500 } }`, matching s2-dbus's own input contract). Messages with a `command` field always go * to the RM; a recognized measurement-value update is cached (and relayed if active); - * everything else goes to the built-in OMBC controller, if any. + * everything else goes to the built-in OMBC or FRBC controller, if any. * Output "to transport" (present only when Transport: External): identical * to s2-rm's port 1. * Output "downstream" (always present, last output): raw "from CEM" * messages (identical to s2-rm's port 2) when Control type: None, or * resolved OMBC instructions (identical to s2-ombc's port 1) when - * Control type: OMBC. + * Control type: OMBC, or FRBC ones (identical to s2-frbc's port 1) when + * Control type: FRBC. * * With Transport: External and Control type: None, this is an exact drop-in * replacement for s2-rm (1 input, 2 outputs, identical message shapes). @@ -103,7 +109,8 @@ export = function (RED: NodeRedApp): void { const transportMode: Transport = config.transport || 'dbus' const isWebSocketTransport = transportMode === 'websocket' const isDbusTransport = transportMode === 'dbus' - const isOmbcBuiltIn = config.controlType !== 'none' + const isFrbcBuiltIn = config.controlType === 'frbc' + const isOmbcBuiltIn = config.controlType !== 'none' && !isFrbcBuiltIn // Resolved early (rather than inside the Transport: D-Bus setup block below) because its // measurementType is also the RM's advertised power-measurement capability when Transport: @@ -138,6 +145,24 @@ export = function (RED: NodeRedApp): void { return } + // Checked before anything starts, like s2-frbc: an RM advertising FRBC without a system + // description to send would leave the CEM waiting for one. + let frbcConfig: FRBCConfig | undefined + if (isFrbcBuiltIn) { + let frbcProblems: string[] + try { + frbcConfig = parseFRBCConfig(config.frbcSystemDescription, '') + frbcProblems = validateFRBCConfig(frbcConfig) + } catch (err) { + frbcProblems = [(err as Error).message] + } + if (frbcProblems.length > 0) { + node.error(`s2-resource: invalid FRBC configuration: ${frbcProblems.join('; ')}`) + node.status({ fill: 'red', shape: 'dot', text: 'invalid FRBC config' }) + return + } + } + // A CEM tells resources apart by resource_id only, so a second node with the same ID (e.g. a // copy-pasted one) would be merged with this one on the CEM side - refuse it before it starts. // A built-in transport carries the ID to the CEM too, so it must not collide with an s2-websocket. @@ -241,9 +266,9 @@ export = function (RED: NodeRedApp): void { } } - // -- built-in OMBC control type (Control type: OMBC) -- + // -- built-in control type (Control type: OMBC or FRBC) -- - let ombcController: OMBCController | undefined + let controller: OMBCController | FRBCController | undefined // The connection (RM and transport) and the built-in control type each have a status. Shown // together, so e.g. "Confirmed: Off" can't hide whether a CEM is connected at all. The colour @@ -310,8 +335,8 @@ export = function (RED: NodeRedApp): void { }, onEmitToCem: (msg) => { if (!msg) return - if (ombcController) { - ombcController.handleInput(msg, () => {}) + if (controller) { + controller.handleInput(msg, () => {}) } else { sendDownstream(msg) } @@ -349,7 +374,7 @@ export = function (RED: NodeRedApp): void { node.error('Invalid OMBC System Description JSON: ' + (e as Error).message) } } - ombcController = new OMBCController({ + controller = new OMBCController({ systemDescription, powerMeasurement: isDbusTransport && dbusConfig ? { measurementType: dbusConfig.measurementType, nrOfPhases: dbusConfig.nrOfPhases, phaseSetting: dbusConfig.phaseSetting } @@ -375,12 +400,27 @@ export = function (RED: NodeRedApp): void { // having to wire a separate Inject/Confirm node for the common case of "always start // in this mode". if (config.defaultOperationModeId) { - ombcController.handleInput({ payload: { confirmedOperationModeId: config.defaultOperationModeId } }, (err?: Error) => { + controller.handleInput({ payload: { confirmedOperationModeId: config.defaultOperationModeId } }, (err?: Error) => { if (err) node.error(`s2-resource: default mode: ${err.message}`) }) } } + if (frbcConfig) { + controller = new FRBCController({ + config: frbcConfig, + onEmitInstruction: (msg) => sendDownstream(msg), + onSendCommand: (msg) => rm.handleInput(msg, () => {}), + onStatus: (status) => setControlTypeStatus(status), + onWarn: (message) => node.warn(`[s2-resource] ${message}`), + getContextValue: (key) => node.context().get(key), + setContextValue: (key, value) => node.context().set(key, value), + // Off unless asked for, for the same reason as OMBC's above. + autoConfirmInstructions: config.frbcAutoConfirmInstructions === true + }) + controlTypeConstructed = true + } + if (isWebSocketTransport) { const cemConfig = RED.nodes.getNode(config.cem || '') as S2CemConfigNode | null if (!cemConfig) { @@ -509,22 +549,25 @@ export = function (RED: NodeRedApp): void { const routedPayload = routedMsg.payload as Record | undefined const hasCommand = !!(routedPayload && routedPayload.command) const isModeConfirmation = !!( - ombcController && payloadObj && + isOmbcBuiltIn && payloadObj && (msg.topic === 'ModeConfirmation' || 'confirmedOperationModeId' in payloadObj || 'confirmedOperationModeIndex' in payloadObj || 'confirmedOperationModeLabel' in payloadObj) ) + // An ActuatorInstruction wired back as ActuatorConfirmation carries commodityPower and values + // too: like a ModeConfirmation, it is not a power reading. + const isFrbcFlowInput = isFrbcBuiltIn && FLOW_TOPICS.includes(msg.topic as string) // A `command: 'PowerMeasurement'` (native S2 values: PowerMeasurementValue[]) or a topic // `PowerMeasurement` message already gets its S2 relay below (via rm.handleInput/ - // ombcController, which applies the configured phase shape) - the cache update here only + // controller, which applies the configured phase shape) - the cache update here only // needs to expose the raw values as D-Bus BusItems, not relay them to the CEM a second time. const isPowerMeasurementCommand = !!(routedPayload && routedPayload.command === 'PowerMeasurement') - const isOmbcPowerMeasurement = !!ombcController && msg.topic === 'PowerMeasurement' + const isOmbcPowerMeasurement = isOmbcBuiltIn && msg.topic === 'PowerMeasurement' const relayedElsewhere = isPowerMeasurementCommand || isOmbcPowerMeasurement - if (!isModeConfirmation && measurementCache && payloadObj && (!hasCommand || isPowerMeasurementCommand)) { + if (!isModeConfirmation && !isFrbcFlowInput && measurementCache && payloadObj && (!hasCommand || isPowerMeasurementCommand)) { // command: 'PowerMeasurement' carries native S2 values (PowerMeasurementValue[]), the same // shape PowerMeasurementCache accepts as `commodityPower`, not its `values` convenience shape. const cacheInput = isPowerMeasurementCommand @@ -532,7 +575,7 @@ export = function (RED: NodeRedApp): void { : payloadObj const update = measurementCache.update(cacheInput) if (update) { - // When the message is also relayed below (rm/ombcController), that path runs its own + // When the message is also relayed below (rm/controller), that path runs its own // native S2 validation and warns accordingly - surfacing the cache's warning too would // be redundant at best (duplicate warning) and misleading at worst (worded for the // cache's own `values`/`commodityPower` shapes, not the native command's). @@ -546,10 +589,18 @@ export = function (RED: NodeRedApp): void { } } - if (hasCommand || !ombcController) { + if (hasCommand || !controller) { rm.handleInput(routedMsg, done) + } else if (isFrbcBuiltIn && typeof msg.payload === 'number' && !msg.topic) { + // Shortcut: a bare number is the fill level. + controller.handleInput({ ...msg, topic: 'StorageStatus', payload: { fillLevel: msg.payload } }, done) + } else if (isFrbcBuiltIn && typeof msg.payload === 'number') { + // The controller would drop it without a word, and a topic is easily set by accident (an + // MQTT or Inject node sets one). + node.warn(`[s2-resource] Ignored number ${msg.payload} with msg.topic "${String(msg.topic)}": send the fill level without a topic, or as msg.topic "StorageStatus" with payload { fillLevel }`) + done() } else { - ombcController.handleInput(msg, done) + controller.handleInput(msg, done) } }) diff --git a/test/lib/frbc-controller.test.ts b/test/lib/frbc-controller.test.ts index ba954b2..e041759 100644 --- a/test/lib/frbc-controller.test.ts +++ b/test/lib/frbc-controller.test.ts @@ -56,7 +56,7 @@ function makeConfig (): FRBCConfig { } } -function setup (config: FRBCConfig = makeConfig(), context: Record = {}) { +function setup (config: FRBCConfig = makeConfig(), context: Record = {}, autoConfirmInstructions = false) { const instructions: NodeMessage[] = [] const commands: Array> = [] const statuses: Array> = [] @@ -68,7 +68,8 @@ function setup (config: FRBCConfig = makeConfig(), context: Record statuses.push(s as Record), onWarn: (m) => warnings.push(m), getContextValue: (key) => context[key], - setContextValue: (key, value) => { context[key] = value } + setContextValue: (key, value) => { context[key] = value }, + autoConfirmInstructions }) const input = (msg: NodeMessage): jest.Mock => { const done = jest.fn() @@ -895,3 +896,35 @@ describe('FRBCController - instruction lifecycle (every instruction ends in a fi expect(statuses(commands)).toEqual(['i0:ABORTED']) }) }) + +describe('FRBCController - autoConfirmInstructions', () => { + it('confirms an emitted instruction as if the flow sent ActuatorConfirmation', () => { + const { select, instruct, instructions, commands, context } = setup(makeConfig(), {}, true) + select('cem-1') + commands.length = 0 + instruct('cem-1', { actuator_id: 'hp', operation_mode: 'hp-on', operation_mode_factor: 0.5 }) + + expect(instructions[instructions.length - 1].topic).toBe('ActuatorInstruction') + expect(commands).toEqual([ + { command: 'UpdateStatus', cemId: 'cem-1', controlType: 'FILL_RATE_BASED_CONTROL', frbc: { actuatorStatuses: [{ actuatorId: 'hp', activeOperationModeId: 'hp-on', operationModeFactor: 0.5 }] } }, + { command: 'InstructionStatus', cemId: 'cem-1', instructionId: 'instr-1', status: 'SUCCEEDED' } + ]) + expect(context.s2FrbcOpenInstructions).toEqual({}) + }) + + it('does not confirm an instruction it aborts', () => { + const { select, instruct, commands } = setup(makeConfig(), {}, true) + select('cem-1') + commands.length = 0 + instruct('cem-1', { actuator_id: 'hp', operation_mode: 'hp-turbo' }) + expect(commands).toEqual([{ command: 'InstructionStatus', cemId: 'cem-1', instructionId: 'instr-1', status: 'ABORTED' }]) + }) + + it('waits for the flow by default', () => { + const { select, instruct, commands } = setup() + select('cem-1') + commands.length = 0 + instruct('cem-1', { actuator_id: 'hp', operation_mode: 'hp-on' }) + expect(commands).toEqual([]) + }) +}) diff --git a/test/nodes/s2-resource.test.ts b/test/nodes/s2-resource.test.ts index 6ba01f8..c44d9d3 100644 --- a/test/nodes/s2-resource.test.ts +++ b/test/nodes/s2-resource.test.ts @@ -1,4 +1,7 @@ import { EventEmitter } from 'events' +import { readFileSync } from 'fs' +import { join } from 'path' +import { runInNewContext } from 'vm' import { MessageType, serialize } from '../../src/lib/s2/messages' import registerNode from '../../src/nodes/s2-resource/index' import { S2WebSocketTransport } from '../../src/lib/transport/websocket' @@ -922,6 +925,165 @@ describe('s2-resource - Control type: OMBC', () => { }) }) +describe('s2-resource - Control type: FRBC', () => { + const ACTUATOR = '5f0c3a62-8d1e-4b7a-9c35-2e6f1a7b8c90' + const CHARGE = '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' + const IDLE = '7c9e6679-7425-40de-944b-e07fc1f90ae7' + + // What the dialog's Friendly form saves for a 10 kWh battery, from the shipped editor script. + function batterySystemDescription (): string { + const window: Record = {} + runInNewContext(readFileSync(join(__dirname, '../../resources/s2-frbc-editor.js'), 'utf8'), { window }) + const editor = window.__s2FrbcEditor as { systemDescription: (form: unknown) => unknown } + return JSON.stringify(editor.systemDescription({ + preset: 'battery', + actuatorId: ACTUATOR, + unit: '%', + min: 0, + max: 100, + size: 10, + cop: null, + minOn: 0, + minOff: 0, + modes: [ + { id: CHARGE, label: 'Charge', from: 0, to: 3000 }, + { id: IDLE, label: 'Idle', from: 0, to: 0 }, + { id: 'f47ac10b-58cc-4372-a567-0e02b2c3d479', label: 'Discharge', from: -3000, to: 0 } + ] + })) + } + + function setupFrbc (config: Record = {}) { + const result = setupNode({ transport: 'external', controlType: 'frbc', controlTypes: 'FILL_RATE_BASED_CONTROL', frbcSystemDescription: batterySystemDescription(), ...config }) + const { handlers, node } = result + const fromCem = (message: Record): void => { + handlers.input({ payload: { command: 'Message', cemId: 'cem-1', message: serialize(message) } }, jest.fn(), jest.fn()) + } + handlers.input({ payload: { command: 'Connect', cemId: 'cem-1', keepAliveInterval: 0 } }, jest.fn(), jest.fn()) + fromCem({ message_type: MessageType.HANDSHAKE_RESPONSE, message_id: 'hr1', selected_protocol_version: '0.0.2-beta' }) + fromCem({ message_type: MessageType.SELECT_CONTROL_TYPE, message_id: 'sct1', control_type: 'FILL_RATE_BASED_CONTROL' }) + const instruct = (): void => fromCem({ + message_type: MessageType.FRBC_INSTRUCTION, + message_id: 'msg-1', + id: 'instr-1', + actuator_id: ACTUATOR, + operation_mode: CHARGE, + operation_mode_factor: 0.5, + execution_time: new Date(Date.now() - 1000).toISOString(), + abnormal_condition: false + }) + // S2 messages sent to the CEM, in order. + const toCem = (): Array> => outputAt(node, 0) + .map((m) => (m as { payload?: { message?: Record } }).payload?.message) + .filter((m): m is Record => !!m) + const toCemOfType = (type: string): Array> => toCem().filter(m => m.message_type === type) + return { ...result, instruct, toCemOfType } + } + + it('sends the configured FRBC.SystemDescription once the CEM selects FRBC, and tells the flow', () => { + const { node, toCemOfType } = setupFrbc() + + const [sysDesc] = toCemOfType(MessageType.FRBC_SYSTEM_DESCRIPTION) as Array<{ actuators: Array<{ id: string }> }> + expect(sysDesc.actuators[0].id).toBe(ACTUATOR) + expect(outputAt(node, 1)).toEqual([{ topic: 'Selected', payload: { controlType: 'FILL_RATE_BASED_CONTROL' }, cemId: 'cem-1' }]) + }) + + it('takes a bare number without a topic as the fill level', () => { + const { handlers, toCemOfType } = setupFrbc() + const done = jest.fn() + + handlers.input({ payload: 42 }, jest.fn(), done) + handlers.input({ topic: '', payload: 43 }, jest.fn(), jest.fn()) + + expect(done).toHaveBeenCalledWith() + expect(toCemOfType(MessageType.FRBC_STORAGE_STATUS).map(m => m.present_fill_level)).toEqual([42, 43]) + }) + + it('warns about a number that has a topic, instead of dropping it silently', () => { + const { node, handlers, toCemOfType } = setupFrbc() + const done = jest.fn() + + handlers.input({ topic: 'boiler/temperature', payload: 42 }, jest.fn(), done) + + expect(done).toHaveBeenCalledWith() + expect(node.warn).toHaveBeenCalledWith(expect.stringContaining('Ignored number 42 with msg.topic "boiler/temperature"')) + expect(toCemOfType(MessageType.FRBC_STORAGE_STATUS)).toEqual([]) + }) + + it('takes topic StorageStatus with { fillLevel }, as s2-frbc does', () => { + const { handlers, toCemOfType } = setupFrbc() + + handlers.input({ topic: 'StorageStatus', payload: { fillLevel: 55 } }, jest.fn(), jest.fn()) + + expect(toCemOfType(MessageType.FRBC_STORAGE_STATUS).map(m => m.present_fill_level)).toEqual([55]) + }) + + it('emits an ActuatorInstruction downstream and waits for the flow to confirm it', () => { + const { node, handlers, instruct, toCemOfType } = setupFrbc() + ;(node.send as jest.Mock).mockClear() + + instruct() + + const [instruction] = outputAt(node, 1) as Array<{ topic: string, payload: Record, cemId: string }> + expect(instruction.topic).toBe('ActuatorInstruction') + expect(instruction.payload).toMatchObject({ instructionId: 'instr-1', actuatorId: ACTUATOR, operationModeId: CHARGE, operationModeLabel: 'Charge', factor: 0.5, values: 1500 }) + expect(toCemOfType(MessageType.FRBC_ACTUATOR_STATUS)).toEqual([]) + + handlers.input({ topic: 'ActuatorConfirmation', payload: instruction.payload, cemId: 'cem-1' }, jest.fn(), jest.fn()) + + expect(toCemOfType(MessageType.FRBC_ACTUATOR_STATUS)).toEqual([expect.objectContaining({ actuator_id: ACTUATOR, active_operation_mode_id: CHARGE, operation_mode_factor: 0.5 })]) + expect(toCemOfType(MessageType.INSTRUCTION_STATUS_UPDATE).map(m => m.status_type)).toContain('SUCCEEDED') + }) + + it('confirms the instruction itself with frbcAutoConfirmInstructions', () => { + const { instruct, toCemOfType } = setupFrbc({ frbcAutoConfirmInstructions: true }) + + instruct() + + expect(toCemOfType(MessageType.FRBC_ACTUATOR_STATUS)).toEqual([expect.objectContaining({ active_operation_mode_id: CHARGE })]) + expect(toCemOfType(MessageType.INSTRUCTION_STATUS_UPDATE).map(m => m.status_type)).toContain('SUCCEEDED') + }) + + it('does not take OMBC\'s autoConfirmInstructions for its own', () => { + const { instruct, toCemOfType } = setupFrbc({ autoConfirmInstructions: true }) + + instruct() + + expect(toCemOfType(MessageType.FRBC_ACTUATOR_STATUS)).toEqual([]) + }) + + it('routes an ActuatorInstruction payload wired back as confirmation to FRBC, not to the D-Bus power measurement', () => { + const { handlers } = setupFrbc({ transport: 'dbus' }) + + handlers.input({ + topic: 'ActuatorConfirmation', + payload: { actuatorId: ACTUATOR, operationModeId: IDLE, factor: 1, commodityPower: [{ commodity_quantity: 'ELECTRIC.POWER.3_PHASE_SYMMETRIC', value: 0 }], values: 0 } + }, jest.fn(), jest.fn()) + + expect(mockDbusTransport.setMeasurementValues).not.toHaveBeenCalled() + }) + + it('still caches a power reading for D-Bus', () => { + const { handlers } = setupFrbc({ transport: 'dbus' }) + + handlers.input({ payload: { values: 1500 } }, jest.fn(), jest.fn()) + + expect(mockDbusTransport.setMeasurementValues).toHaveBeenCalled() + }) + + it.each([ + ['is missing, as on a node saved before FRBC was built in', undefined, 'not configured'], + ['is not JSON', '{', 'invalid JSON'], + ['is not a valid system description', '{"actuators":[],"storage":{}}', 'System description'] + ])('refuses to start when the system description %s', (_name, frbcSystemDescription, expected) => { + const { node, handlers } = setupNode({ transport: 'external', controlType: 'frbc', frbcSystemDescription }) + + expect(node.error).toHaveBeenCalledWith(expect.stringContaining(expected)) + expect(node.status).toHaveBeenLastCalledWith({ fill: 'red', shape: 'dot', text: 'invalid FRBC config' }) + expect(handlers.input).toBeUndefined() + }) +}) + describe('s2-resource - Control type: None', () => { it('forwards raw CEM messages on the downstream output, identical in shape to s2-rm\'s "from CEM" output', () => { const { node, handlers } = setupNode({ transport: 'external', controlType: 'none' }) diff --git a/test/resources/s2-common.test.ts b/test/resources/s2-common.test.ts index 21fa179..729887a 100644 --- a/test/resources/s2-common.test.ts +++ b/test/resources/s2-common.test.ts @@ -343,6 +343,18 @@ describe('s2-common - validationGate', () => { expect(err.shown).toBe(false) }) + it('hides the error box for a failed check that names no errors', () => { + const { ok, err, checks, gate } = setup() + gate.schedule() + jest.advanceTimersByTime(400) + checks[0]({ valid: false, errors: ['bad'] }) + gate.schedule() + jest.advanceTimersByTime(400) + checks[1]({ valid: false, errors: [] }) + expect(ok.disabled).toBe(true) + expect(err.shown).toBe(false) + }) + it.each([ ['a newer check', (gate: Gate) => { gate.schedule(); jest.advanceTimersByTime(400) }], ['pass()', (gate: Gate) => gate.pass()] diff --git a/test/resources/s2-frbc-editor.test.ts b/test/resources/s2-frbc-editor.test.ts new file mode 100644 index 0000000..14e9345 --- /dev/null +++ b/test/resources/s2-frbc-editor.test.ts @@ -0,0 +1,197 @@ +import { readdirSync, readFileSync } from 'fs' +import { join } from 'path' +import { runInNewContext } from 'vm' +import { validateFRBCConfig } from '../../src/lib/s2/frbc-controller' + +interface Mode { id: string, label: string, from: number | null, to: number | null } +interface Form { + preset: string + actuatorId: string + unit: string + min: number | null + max: number | null + size: number | null + cop: number | null + minOn: number | null + minOff: number | null + modes: Mode[] +} +interface Element { fill_level_range: { start_of_range: number, end_of_range: number }, fill_rate: { start_of_range: number, end_of_range: number } } +interface SystemDescription { + actuators: Array<{ + id: string + operation_modes: Array<{ id: string, diagnostic_label: string, elements: Element[] }> + transitions: Array<{ id: string, from: string, to: string, start_timers: string[], blocking_timers: string[] }> + timers: Array<{ id: string, duration: number }> + }> + storage: Record +} +interface FrbcEditor { + presetForm: (name: string, newId: () => string) => Omit + formProblems: (form: Form) => string[] + systemDescription: (form: Form) => SystemDescription +} + +// Runs the shipped editor script as the browser would, against a bare window. +function loadEditor (): FrbcEditor { + const window: Record = {} + runInNewContext(readFileSync(join(__dirname, '../../resources/s2-frbc-editor.js'), 'utf8'), { window }) + return window.__s2FrbcEditor as FrbcEditor +} + +const editor = loadEditor() +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ + +// A preset as the dialog leaves it once the user has entered the size and the open power ranges. +function filledIn (preset: string, size: number, power: number, cop: number | null = null): Form { + const ids = ['1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed', '7c9e6679-7425-40de-944b-e07fc1f90ae7', 'f47ac10b-58cc-4372-a567-0e02b2c3d479'] + const newId = (): string => ids.shift()! + const form: Form = { ...editor.presetForm(preset, newId), actuatorId: '5f0c3a62-8d1e-4b7a-9c35-2e6f1a7b8c90', size, cop } + for (const mode of form.modes) { + if (mode.to === null) mode.to = power + if (mode.from === null) mode.from = -power + } + return form +} + +function modeElement (sd: SystemDescription, label: string): Element { + return sd.actuators[0].operation_modes.find(m => m.diagnostic_label === label)!.elements[0] +} + +describe('s2-resource Friendly FRBC form - presets', () => { + it.each([ + ['battery', filledIn('battery', 10, 3000)], + ['boiler', filledIn('boiler', 200, 2000)], + ['heatpump', filledIn('heatpump', 300, 1500, 3.5)], + ['custom', { ...filledIn('custom', 250, 0), unit: 'kWh', min: 0, max: 40, modes: [{ id: '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4b99', label: 'Fill', from: 0, to: 1000 }] }] + ])('the %s preset, filled in, gives a valid FRBC system description', (_name, form) => { + expect(editor.formProblems(form)).toEqual([]) + const systemDescription = JSON.parse(JSON.stringify(editor.systemDescription(form))) + expect(validateFRBCConfig({ systemDescription })).toEqual([]) + expect(systemDescription.storage).toMatchObject({ provides_leakage_behaviour: false, provides_fill_level_target_profile: false, provides_usage_forecast: false }) + }) + + it('leaves every power range of a preset for the user to enter', () => { + const battery = editor.presetForm('battery', () => 'id') + expect(battery.modes.map(m => [m.label, m.from, m.to])).toEqual([['Charge', 0, null], ['Idle', 0, 0], ['Discharge', null, 0]]) + expect(editor.presetForm('boiler', () => 'id').modes.map(m => [m.label, m.from, m.to])).toEqual([['Heat', 0, null], ['Idle', 0, 0]]) + expect(editor.presetForm('custom', () => 'id').modes).toEqual([]) + }) + + it('says what a preset still needs, in the words of the form', () => { + const heatpump: Form = { ...editor.presetForm('heatpump', () => 'id'), actuatorId: 'a' } + expect(editor.formProblems(heatpump)).toEqual(['Volume: enter a value above 0', 'COP: enter a value above 0', 'Heat: enter its power range']) + const custom: Form = { ...editor.presetForm('custom', () => 'id'), actuatorId: 'a' } + expect(editor.formProblems(custom)).toEqual(['Fill level: enter a range that starts below its end', 'Energy per unit: enter a value above 0', 'Add at least one operation mode']) + }) + + it('rejects a power range typed from high to low', () => { + const battery = filledIn('battery', 10, 3000) + battery.modes[0] = { ...battery.modes[0], from: 4000, to: 500 } + expect(editor.formProblems(battery)).toEqual(['Charge: enter a power range that starts at or below its end']) + }) +}) + +describe('s2-resource Friendly FRBC form - fill rate from power', () => { + it('battery: % per second = W / (capacity in Wh x 36)', () => { + const sd = editor.systemDescription(filledIn('battery', 10, 3600)) + expect(modeElement(sd, 'Charge').fill_rate).toEqual({ start_of_range: 0, end_of_range: 3600 / (10000 * 36) }) + expect(modeElement(sd, 'Idle').fill_rate).toEqual({ start_of_range: 0, end_of_range: 0 }) + expect(modeElement(sd, 'Discharge').fill_rate).toEqual({ start_of_range: -3600 / (10000 * 36), end_of_range: 0 }) + expect(modeElement(sd, 'Charge').fill_rate.end_of_range).toBeCloseTo(0.01, 12) + expect(modeElement(sd, 'Charge').fill_level_range).toEqual({ start_of_range: 0, end_of_range: 100 }) + }) + + it('boiler: °C per second = W / (litres x 4186)', () => { + const sd = editor.systemDescription(filledIn('boiler', 200, 2093)) + expect(modeElement(sd, 'Heat').fill_rate.end_of_range).toBeCloseTo(0.0025, 12) + }) + + it('heat pump: °C per second = W x COP / (litres x 4186)', () => { + const sd = editor.systemDescription(filledIn('heatpump', 300, 2093, 3)) + expect(modeElement(sd, 'Heat').fill_rate.end_of_range).toBeCloseTo(0.005, 12) + }) + + it('custom: units per second = W / (Wh per unit x 3600)', () => { + const form: Form = { ...filledIn('custom', 250, 0), min: 0, max: 40, modes: [{ id: '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4b99', label: 'Fill', from: 0, to: 900 }] } + expect(modeElement(editor.systemDescription(form), 'Fill').fill_rate.end_of_range).toBeCloseTo(0.001, 12) + }) + + it('keeps six significant digits', () => { + const sd = editor.systemDescription(filledIn('battery', 100, 40)) + expect(modeElement(sd, 'Charge').fill_rate.end_of_range).toBe(0.0000111111) + }) +}) + +describe('s2-resource Friendly FRBC form - timers and transitions', () => { + it('heat pump: 5 minutes minimum on and off, as the s2-frbc-config example has', () => { + const actuator = editor.systemDescription(filledIn('heatpump', 300, 1500, 3.5)).actuators[0] + const [heat, idle] = actuator.operation_modes.map(m => m.id) + const [minOn, minOff] = actuator.timers + expect(actuator.timers.map(t => t.duration)).toEqual([300000, 300000]) + expect(actuator.transitions.map(({ from, to, start_timers, blocking_timers }) => ({ from, to, start_timers, blocking_timers }))).toEqual([ + { from: heat, to: idle, start_timers: [minOff.id], blocking_timers: [minOn.id] }, + { from: idle, to: heat, start_timers: [minOn.id], blocking_timers: [minOff.id] } + ]) + }) + + it('battery: every mode can switch to every other one, without timers', () => { + const actuator = editor.systemDescription(filledIn('battery', 10, 3000)).actuators[0] + expect(actuator.timers).toEqual([]) + expect(actuator.transitions).toHaveLength(6) + expect(actuator.transitions.every(t => t.start_timers.length === 0 && t.blocking_timers.length === 0)).toBe(true) + }) + + it('does not time a switch between two modes that are both on', () => { + const form = { ...filledIn('battery', 10, 3000), minOn: 2, minOff: 0 } + const actuator = editor.systemDescription(form).actuators[0] + const [charge, idle, discharge] = actuator.operation_modes.map(m => m.id) + const between = (from: string, to: string) => actuator.transitions.find(t => t.from === from && t.to === to)! + expect(actuator.timers).toHaveLength(1) + expect(between(charge, discharge)).toMatchObject({ start_timers: [], blocking_timers: [] }) + expect(between(idle, charge)).toMatchObject({ start_timers: [actuator.timers[0].id], blocking_timers: [] }) + expect(between(discharge, idle)).toMatchObject({ start_timers: [], blocking_timers: [actuator.timers[0].id] }) + }) +}) + +describe('s2-resource Friendly FRBC form - ids', () => { + it('gives the same system description for the same form, ids included', () => { + const form = filledIn('heatpump', 300, 1500, 3.5) + expect(editor.systemDescription(JSON.parse(JSON.stringify(form)))).toEqual(editor.systemDescription(form)) + }) + + it('keeps every id when a value in the form changes', () => { + const ids = (sd: SystemDescription): string[] => { + const a = sd.actuators[0] + return [a.id, ...a.operation_modes.map(m => m.id), ...a.transitions.map(t => t.id), ...a.timers.map(t => t.id)] + } + const before = filledIn('heatpump', 300, 1500, 3.5) + const after = { ...filledIn('heatpump', 500, 2500, 4), minOn: 10, min: 20 } + expect(ids(editor.systemDescription(after))).toEqual(ids(editor.systemDescription(before))) + }) + + it('uses only UUIDs, each once', () => { + const actuator = editor.systemDescription(filledIn('heatpump', 300, 1500, 3.5)).actuators[0] + const ids = [actuator.id, ...actuator.operation_modes.map(m => m.id), ...actuator.transitions.map(t => t.id), ...actuator.timers.map(t => t.id)] + expect(ids).toHaveLength(7) + for (const id of ids) expect(id).toMatch(UUID) + expect(new Set(ids).size).toBe(ids.length) + }) +}) + +describe('s2-resource Friendly FRBC form - examples', () => { + const examplesDir = join(__dirname, '../../examples') + const examples = readdirSync(examplesDir).flatMap(file => { + const flow = JSON.parse(readFileSync(join(examplesDir, file), 'utf8')) as Array> + return flow.filter(n => n.type === 's2-resource' && n.controlType === 'frbc').map(n => [file, n] as const) + }) + + it('has at least one', () => { + expect(examples.length).toBeGreaterThan(0) + }) + + // Otherwise the example opens on the Advanced tab with a warning instead of on the Friendly form. + it.each(examples)('%s: its Friendly form writes exactly its system description', (_file, node) => { + expect(JSON.parse(node.frbcSystemDescription)).toEqual(editor.systemDescription(JSON.parse(node.frbcForm) as Form)) + }) +})