Skip to content

Universal Device Command Sequence Framework

Status: implemented, on the engine (EnergySyc_EMS_ES100Cx12S) and in the EMS frontend (GESS_SCADA2). Nothing in this document is a proposal: every format, path, key and endpoint below was read off the running configuration.

A. Purpose and architecture

Why command sequences

A device operation is rarely one register write. Starting an EPCS105 PCS is a start command followed by ten seconds of waiting before the device will accept anything else; stopping it means dropping power to zero, waiting a second, and then clearing the run bit. Those steps, their order and their timing are properties of the model, not of the EMS operation that asks for them.

Keeping them in device configuration rather than in EMS code is what lets one operational mode drive an Enjoy PCS, a Sinexcel PCS and a Sungrow PCS without knowing that they differ.

The layers

Module Role
pcs_power_sequence.py The execution engine. Runs a list of steps against a device client. Nothing in it is PCS-specific despite the name.
device_command_sequences.py The universal device layer. Resolves a device to its category, manufacturer and model, finds the model's file, and hands the steps to the engine. execute_sequence() is the entry point operational controllers use.
protocol_adapters.py Protocol abstraction. Modbus-TCP and OCPP adapters present the same interface, so the engine drives either without changes.
command_sequence_admin.py Everything an editor needs: locate, load, validate, save, back up, restore.
ems_command_sequences.py HTTP service layer over the admin module.
ems_settings_api.py The HTTP server. Registers the /api/v1/ems/command-sequences/... routes.

The engine was extracted from the existing PCS implementation rather than rewritten. That is deliberate: execute_sequence() is called by the same operation / address / value vocabulary the PCS files already used, so the existing PCS configuration kept working untouched. The end-to-end suite executes the shipped EPCS105, SINEXCEL_PWS1_250K and SUNGROW_SC250UD files through the modified engine.

Where the EMS controllers meet it

An operational controller does not write registers. It resolves a device and asks for a named action with runtime parameters:

execute_sequence(client, device_id=..., action="change_power", params={"power_kw": 150})

The controller says what it wants in engineering units. The model's file says how that device does it. Adding a manufacturer therefore never means editing an operational controller.

B. Multi-manufacturer, multi-model support

How a model is identified

Nothing is hardcoded — no manufacturer list, no model list, no path list. The resolution chain is:

  1. The device is found in the EMS device configuration by its device key.
  2. Its category is one of the registered categories — ac, bess_energy_meter, bmu, cooling, door_sensor, ev_charger, ffr_meter, flood_sensor, frequency_meter, fss, grid_meter, heat_sensor, pcs, sensor_block, smoke_detector, solar_meter, temperature_sensor, ups — which determines where its sequence files live.
  3. Its model comes from that device's configured model field, and may be a name (EPCS105, SUNGROW_SC250UD) or an alias the file declares. A device configured with no model falls back to the model recorded for its own register map in emsConfig/selected_model.json, then to the model the map declares.
  4. The category's sequence directory is searched for a file that declares that model, or that lists it as an alias.

Because the last step is a search of the files, adding a model means adding a file — no code change. Adding a whole new category is the exception, and is covered in section G.

// emsConfig/bmu/sequences/bmu_command_sequences.json — how an alias works
"models": {
  "BMU100": {
    "aliases": ["generic_lfp_bms_v1", "LFP BMS generic"],
    "actions": { "...": "..." }
  }
}

A device configured with model generic_lfp_bms resolves to the BMU100 block without anyone editing code — all ten BMUs in this plant do. Aliases are what let one block serve several configured spellings of the same hardware.

What the inventory reports

list_devices() walks the same configuration and reports, per category, every configured device with its model and protocol, plus whether a sequence file exists for it and which actions it offers. The editor is built on this, which is why the editor cannot offer an operation the engine cannot perform, and why a newly configured model appears in the selector with no frontend change.

C. JSON file structure

Actual directories

emsConfig/
├── pcs/
│   ├── power_sequences/                  <- PCS keeps its historical name
│   │   ├── EPCS105.json
│   │   ├── SINEXCEL_PWS1_250K.json
│   │   ├── SUNGROW_SC250UD.json
│   │   └── MODEL_TEMPLATE.json           <- a copy-me template, not executed
│   ├── sequences/pcs_power_sequences.json
│   └── backup/sequences/                 <- snapshots, written before each save
├── bmu/sequences/bmu_command_sequences.json
├── grid_energy_meter/sequences/grid_meter_command_sequences.json
├── solar_energy_meter/sequences/solar_meter_command_sequences.json
├── frequency_meter/sequences/frequency_meter_command_sequences.json
├── air_condition_unit/sequences/ac_command_sequences.json
├── fire_safety_system/sequences/fss_command_sequences.json
├── liquid_cooling_unit/sequences/cooling_command_sequences.json
├── sensor_block/sequences/sensor_block_command_sequences.json
├── ups/sequences/ups_command_sequences.json
└── ev_charger/sequences/ev_charger_command_sequences.json

Two differences from the original specification are worth stating plainly, since they are the kind of thing that causes confusion later:

  • There is no register_full.json at the category level, and no command_sequences/ directory. The historical PCS name power_sequences/ is kept. Every other category uses sequences/.
  • Register maps are not per category. They live with the device instance as <prefix>_register_full.json. Validation therefore cannot cross-check a sequence address against a single category map, and does not pretend to.

Two file shapes

Both are supported and both are in production. The editor handles either without being told which it is, because the backend reports where the actions live.

Flat — one file per model. Used by PCS.

{
  "model": "EPCS105",
  "notes": ["..."],
  "actions": {
    "mode_pq": [
      { "operation": "write_single", "address": "0x5066", "value": 0,
        "encoding": "u16", "verify": true }
    ]
  }
}

Aggregate — one file per category, one block per model. Used by every other category.

{
  "device_type": "bmu",
  "schema_version": 1,
  "models": {
    "BMU100": {
      "aliases": ["generic_lfp_bms_v1"],
      "actions": { "...": "..." }
    }
  }
}

Step reference

Verified against every shipped sequence file. Keys in parentheses are accepted but rare.

Key Meaning
operation write_single, write_multiple, read_holding, read_input, delay. A protocol step drives an adapter (OCPP) instead of registers.
address Register address. Hex strings ("0x5066") and decimal integers are both in use, and both are accepted.
value The value to write, or "${param}" to take it from the caller.
values Register list for write_multiple.
count Number of registers to read.
encoding u16, signed_i16, and the other encodings the engine's codec understands.
scale Divisor applied between engineering units and registers.
offset, decimals Read-side adjustment. The engine accepts them; they appear in the PCS files.
verify Re-read after writing and compare, so a silently ignored write is caught.
expect A read step's expected value, i.e. a condition rather than a write.
store_as Name to keep a read value under, for later steps and for the caller.
seconds, milliseconds Delay for a delay step.
condition A condition that must hold for the step to run.
timeout_ms, retries, retry_delay_ms Per-step timeout and retry policy.
enabled false skips a step without deleting it.
on_failure What a failed step means for the rest of the sequence: abort (the default) stops there, continue records the failure and runs the remaining steps anyway. Any other value is refused.
reason, note, description Authoring annotations. The engine ignores them; they are accepted so they do not read as mistakes.

Everything except operation is optional, and a step is executed in the order it appears in the list.

Dynamic parameters

"${name}" is substituted from the caller's params at execution time. This is how a controller passes an engineering value without knowing the register:

"change_power": [
  { "operation": "write_single", "address": "0x0D57", "value": "${power_kw}",
    "encoding": "signed_i16", "scale": 10, "verify": true }
]

One register write represents the whole power control operation, because the model file — not the controller — knows the address, the signedness and the scaling.

D. Command execution

execute_sequence() runs one action, synchronously:

  1. Resolve the device to its file, block and action.
  2. Substitute params into "${...}" placeholders.
  3. For each step, in order: check enabled, evaluate condition, then act.
  4. For a write, apply scale and encoding, write, and if verify is set read the register back and compare.
  5. For a read, store the decoded value under store_as.
  6. For a delay, sleep.
  7. Apply the step's timeout and retry policy.
  8. Apply the step's on_failure policy when it fails: abort (the default) stops the sequence there and returns the outcome, continue records the failure and carries on with the remaining steps.
  9. Return the outcome. A run that failed is reported FAIL either way, so continue decides what is attempted, not whether the operator sees the failure.

Response verification is what distinguishes this from "fire and forget": a device that acknowledges a write on the wire but ignores it in its register map is caught at step level, with the step named in the result.

E. Frontend command sequence editor

Access

URL Who
/command-sequence-edit Signed-in Admin / Super Admin
/command-sequence-edit/test, /test/stop The page itself, same session
/command-sequences/{operation} Bearer token (read and write), or an Admin / Super Admin session for reads

The token routes exist so scripts can work without a login form. They are CSRF-exempt, which is safe only because a session may never write: a non-GET request without a token is refused without consulting the session at all.

The editor's own routes are not CSRF-exempt. They carry the session's token, which is only in the page, so a cross-site post cannot drive a sequence test.

Selecting what to edit

The selector is the engine's own inventory, so the workflow the specification describes is real rather than a hardcoded list:

Category → Active device → Manufacturer / model → Sequence file → Action

Choosing a category lists the devices actually configured in it; choosing a model loads the file the engine would execute for it. If no file declares that model, the page says so and offers to create one — which is written only if it validates, like any other save.

Editing

One table per action, one row per step. Columns cover the step vocabulary above; Show/hide advanced columns reveals the rarer ones (value_from, values, count, seconds, encoding, verify, store_as, retry_delay_ms, protocol, parameters) so the common view stays readable.

  • Reorder by dragging a row. Row order is execution order, so dragging is the whole feature.
  • Add a step from the toolbar, or an action from below the tables. A new action starts with one write step, because the engine requires an action to be a non-empty list.
  • Delete a step with its checkbox, an action with its own.
  • Duplicate an action into a new name.
  • Filter rows by any text they contain.
  • On failure collects what a failed step means for the rest of the sequence: abort (the default) or continue. abort is left implicit in the file, so a row that never chose a policy stays byte-identical, and choosing abort on a step that carried continue takes the key back out.

What a save preserves

The editor is a table, but the file is not. Two hidden fields carry the file through the form:

  • The whole document, so top-level keys the table has no control for (model, aliases, notes, schema_version) survive — and so do the other models inside an aggregate file.
  • Each step's own JSON, so keys with no column (offset, decimals, reason) survive.

This was verified against the shipped EPCS105 file, whose read_soc step uses offset and decimals: both come back byte-identical after a save.

Emptied fields are removals, so a key can be taken back out of a file through the editor rather than needing a text editor.

Two traps in that round-trip cost real editing sessions, so they are worth knowing about. Both are fixed, and both are the kind of thing to check again if the step table is ever rebuilt:

  • An absent field must render as an empty box, never as the text null. json_encode(null) is the four characters null; the overlay reads them back as a real null and the file gains a key it never had. generic_lfp_bms carries no verify on its read_status step, so that text became "verify": null and the engine refused every save of the model with Invalid verify at step 1: None. Nothing the operator changed could be written, which reads as an editor that silently does nothing.
  • A boolean must render as true/false. Blade echoes PHP true as 1, so each "verify": true in the same file came back as the integer 1: fourteen silent edits of a shared file, and 42 bytes off its size, from a save that changed nothing.

A refused save also names the finding that caused it. It used to print an empty [error in step: ], because the backend trims its report to {ok, errors, warnings, ...} and the page iterated that structure as if it were the list of findings.

With all of that in place, saving a model without touching anything is byte-identical to the file on disk. That is the strongest round-trip check available and the one to re-run after any edit to the step table: take the file's hash, save, take it again.

Shared files

If several devices use one file, the page names them. EPCS105 reports twelve PCS units, so an edit to its start action is visibly a change to all twelve and not a change to "a file".

Backups and restore

The backend snapshots a file before every save, and the page lists those snapshots with size and time, newest first, each with a restore button. Restoring backs up the current file first, so a restore is itself reversible.

Validation

Shown before the tables, split into errors (saving is refused) and warnings (the engine will read the file, but something looks unintended). Findings name the action and the step, so a problem in step 7 of start is reported as exactly that.

Errors cover the structural rules that would make the file unexecutable: no actions object, an action that is not a list, a step that is not an object, an unknown operation, an unparsable address, bad encodings, non-numeric scaling. Warnings cover things that execute but probably do not mean what the author intended: keys the engine ignores, unreachable conditions, protocol mismatches.

The validator uses the engine's own parsers rather than a second copy of the rules, so it cannot disagree with execution about what is legal. Its strongest test is negative and runs over the real files: every shipped sequence file validates with zero errors.

Protocol compatibility is checked too. A device's transport is read from its configuration (communication.protocol); all configured devices are modbus-tcp. An OCPP step on a Modbus device is refused as an error rather than saved for someone to discover at 3am.

Why the template still warns

MODEL_TEMPLATE.json carries replace_before_use, which no engine code reads — it is an instruction to whoever copies the file. It is the only place in the tree that produces an "unknown key" warning, and that warning is correct: the key does nothing, and the file is a template. Executable files are warning-free.

Testing

Saving and validating are not the same as working. The Test tab runs the selected action against the device's own configured endpoint — the simulator in this plant — and reports every step with its expected value, the value read back, its duration and its outcome. Section F covers it, including the safety rule that physical execution is unreachable from the page.

F. Testing

What is verified today

Engine, pytest — 282 passing:

  • Every shipped sequence file validates with zero errors, and no shipped file reports a key the engine ignores.
  • The shipped EPCS105, SINEXCEL and SUNGROW files execute end to end through the modified engine, which is what proves the PCS behaviour survived generalisation.
  • Delays, timeouts, retries, conditional steps and response verification are covered individually.
  • Both protocol adapters, including that a Modbus device gets its original client object back — so the running fleet is untouched by the abstraction.
  • The test runner over real HTTP: the route, body parsing, job registry, runner and pyModbusTCP client, against a device on loopback. One of those runs the shipped PCS stop sequence — write, wait one second, write — and asserts the second lands on the delay step, which is the only way to catch the engine's emit-before-sleep behaviour turning a 500 ms wait into 0 ms.

Frontend, verified against the real application:

  • The editor renders through real Laravel with real engine payloads for both file shapes (flat EPCS105: 7 actions, 10 steps; aggregate generic_lfp_bms: 6 actions, 15 steps), and the hidden document decodes back to exactly the file the engine returned.
  • Route registration, middleware and authorisation: an admin session can read the sequence API but can never write through it, on any of the write operations.
  • The Blade compiles and its JavaScript parses. Both checks are harnesses rather than committed suites — the repository has no feature test for this view — so re-run them after an edit.

Testing a sequence

The editor's Test tab runs one action against the device's own configured endpoint and reports every configured step, whether or not it was reached:

Column What it shows
Step The configured step number
Command The configured operation
Expected The value the step set, in engineering units and raw counts
Actual The value read back — or no read-back (verify off) if the step does not verify
Time How long the step took, including any delay it waited on
Status PASS, FAIL, ERROR, SKIPPED or RUNNING

Select the category, device and action, put any runtime parameters in the box as JSON ({"power_kw": 150}), and start the run. The page polls until the run leaves RUNNING. A run can be stopped, which is honoured between steps: the step in flight finishes and nothing after it runs, because abandoning a device mid-sequence is worse than waiting for it.

Four outcomes:

  • PASS — every step did what it said it would.
  • FAIL — the sequence ran and a step did not behave. The failing step is named.
  • ERROR — nothing was run: refused, unreachable, or unconfigured. The step table will show every step as not run.
  • SKIPPED — the sequence ran but no step executed, because a condition or enabled: false excluded them all.

Safety: what the Test tab will not do

This is enforced in the backend, not in the page, so a script cannot talk its way past it:

  • A run always targets the endpoint the device is configured with. In this plant that is bess-simulator-backend, so the tab tests against the simulator by construction.
  • A host that is not recognisably a simulator is refused unless the caller passes authorize_physical=True. Clicking a button can never become a write to a real inverter.
  • target="physical" additionally requires that same flag, so asking for physical execution is never enough on its own.

One sequence at a time per device

Two sequences interleaved on one device corrupt both of them: the second one's writes land between the first one's steps, and neither per-step report means anything afterwards.

Starting a run against a device that already has one in flight is therefore refused with 409 and the id of the run that is in the way. Different devices stay independent and run concurrently — the guard is per device, not global. A run that has finished does not block the next one; the check is about overlapping runs, not about a device being busy.

The guard identifies the device the way execution does, resolving the configured endpoint, so a run that names no device key and one that names the device it resolves to are recognised as the same device.

This covers the editor's path, which is where a person can start two runs by clicking twice. The engine holds no cross-process lock, so a sequence started by an EMS controller while someone runs a test against the same device is not prevented — a limitation worth knowing rather than assuming away.

Reading a failure

A failed sequence names the step and the reason: a write the device ignored (verify mismatch), a read that returned an unexpected value, a timeout, or a condition that excluded the step. Start with the named step's address, encoding and scale — those three account for most surprises — then check whether the model's start action really matches the device's manual.

If the table reports every step as not run, the sequence never reached the device: read the error line, which says whether the endpoint was refused, the model's file was not found, or the sequence failed validation.

G. Adding a new device

  1. Configure the device. Add it to the EMS device configuration with its category and model. It now appears in the engine's inventory and in the editor's selector.
  2. Add its register map as <prefix>_register_full.json, alongside the other device maps. This is what polling and last-value processing read.
  3. Add its sequence file. Either add a block to the category's aggregate file under models, or — for PCS — add <MODEL>.json to power_sequences/. Copy MODEL_TEMPLATE.json for the structure. Declare aliases if the configured model name differs from the block name.
  4. Open it in the editor at /command-sequence-edit, select the category and model, and check the validation panel is clean. A model whose file is not found is reported as such, with a create option.
  5. Verify execution from the editor's Test tab, which runs the sequence against the simulated device and reports each step. Where the action takes a dynamic parameter, supply it in the tab's parameter box — change_power with {"power_kw": 150} is the usual first check. A step whose read-back does not match fails by name, which is the point of running it rather than only validating it.
  6. If it is a new category rather than a new model, one code change is needed. Categories are declared in DEVICES in device_command_sequences.py, which maps a category to three things: its sequence directory, the general_settings section that holds its devices, and its display label. Adding a model needs none of this. Adding a category needs one entry, after which every model in it is config-only in turn.

If the device speaks a protocol other than Modbus or OCPP, that is the other case that does need code — a new adapter in protocol_adapters.py, implementing the same interface. The execution engine itself does not change.

Practical examples

All of the following are the real shipped configuration.

1. Start an EPCS105 PCS

"start": [
  { "operation": "write_single", "address": "0x0291", "value": 1,
    "encoding": "u16", "verify": true },
  { "operation": "delay", "seconds": 10 }
]

The ten seconds are part of the model's definition: the device will not accept further commands before then, so the wait belongs here and not in the caller.

2. Stop it

"stop": [
  { "operation": "write_single", "address": "0x0D57", "value": 0,
    "encoding": "signed_i16", "scale": 10, "verify": true },
  { "operation": "delay", "seconds": 1 },
  { "operation": "write_single", "address": "0x0291", "value": 0,
    "encoding": "u16", "verify": true }
]

Power to zero, a second for the device to settle, then clear the run bit. The order is the point: clearing the run bit first would leave the inverter at power into a stopping machine.

3. Active power control

"change_power": [
  { "operation": "write_single", "address": "0x0D57", "value": "${power_kw}",
    "encoding": "signed_i16", "scale": 10, "verify": true }
]

power_kw: 150 becomes 1500 in a signed 16-bit register at 0x0D57. The controller passes kilowatts; the file knows everything else. A negative value is a charge, which is why the encoding is signed.

4. PQ / VF mode switching

"mode_pq": [ { "operation": "write_single", "address": "0x5066", "value": 0,
               "encoding": "u16", "verify": true } ],
"mode_vf": [ { "operation": "write_single", "address": "0x5066", "value": 1,
               "encoding": "u16", "verify": true } ]

Two actions rather than one action with a parameter: "PQ" and "VF" are the words the operational code and the operators use, and a named action is what a sequence list should read as.

5–7. EV charger start, stop, dynamic power limitation

Twelve EV chargers are configured in this plant — ev_charger1 through ev_charger12, each with its own register map, alarm map and Modbus config. All twelve resolve to the EVC1 model, whose block lives in emsConfig/ev_charger/sequences/ev_charger_command_sequences.json and offers 16 actions. The block is reached by any of three aliases, so a charger configured as ev_charging_pile or GESS AC EV Charger 22kW loads the same file.

Starting a session hands control to the EMS and then starts it:

"start_charging": [
  { "operation": "write_single", "address": 4120, "value": 1, "encoding": "u16",
    "verify": true,
    "reason": "charging_enable - hand control of the session to the EMS" },
  { "operation": "delay", "milliseconds": 500 },
  { "operation": "write_single", "address": 4121, "value": 1, "encoding": "u16",
    "verify": true,
    "reason": "start_stop_session - 1 starts a session" },
  { "operation": "read_holding", "address": 4064, "count": 1, "encoding": "u16",
    "store_as": "charging_active",
    "reason": "charging_active is returned to the caller" }
]

Stopping is the same shape with 0 in both registers, and read_status returns the 16-bit status registers without writing anything.

The dynamic-load case the specification cares about is the next action. The Dynamic Load Balancing controller computes a limit and passes it in; the file, not the controller, decides what the charger does with it:

"apply_load_balancing_limit": [
  { "operation": "write_single", "address": 4127, "value": 1, "encoding": "u16",
    "verify": true,
    "reason": "dlb_enable - the DLB controller owns the limit it sets" },
  { "operation": "write_single", "address": 4122, "value": "${power_kw}",
    "encoding": "u16", "scale": 1, "verify": true,
    "reason": "max_power_limit_kw - the setpoint the DLB controller computed" },
  { "operation": "write_single", "address": 4123, "value": "${current_a}",
    "encoding": "u16", "scale": 1, "verify": true,
    "reason": "max_current_limit_a - the same limit expressed as a current" }
]

So execute_sequence(client, device_id="ev_charger1", action="apply_load_balancing_limit", params={"power_kw": 11, "current_a": 16}) is the whole integration. An OCPP charger instead maps the same call to a charging-profile update through the OCPP adapter — the controller's call does not change.

ev_charger is also the worked example of adding a category (section G): it needed one DEVICES entry, because categories themselves are declared in code.

8. BMS control

"commission": [
  { "operation": "write_single", "address": 8702, "value": "${cell_ov}",
    "encoding": "u16", "verify": true },
  { "operation": "write_single", "address": 8703, "value": "${cell_uv}",
    "encoding": "u16", "verify": true },
  { "operation": "write_single", "address": 8704, "value": "${temp_over}",
    "encoding": "u16", "verify": true },
  { "operation": "write_single", "address": 8705, "value": "${temp_under}",
    "encoding": "u16", "verify": true },
  { "operation": "write_single", "address": 8706, "value": "${charge_limit}",
    "encoding": "u16", "verify": true },
  { "operation": "write_single", "address": 8707, "value": "${discharge_limit}",
    "encoding": "u16", "verify": true }
]

Six writes, all parameterised, all verified. set_current_limits is the two-register subset the EMS calls during normal operation; commission is the full set used once. Both live in the BMU100 block, which all ten configured BMUs resolve to through its alias list.

9. Meter configuration

Meter files are aggregate and their actions are mostly reads:

"read_status": [
  { "operation": "read_holding", "address": 3005, "count": 1,
    "encoding": "u16", "scale": 1, "offset": 0, "decimals": 0,
    "store_as": "soc_raw" }
]

store_as is what makes a read useful: the value is available to later steps and to the caller, rather than being read and discarded.

10. Adding a manufacturer or model

Nothing above changes shape. Add a block (or a file) for the new model, declare its addresses, and it is available. The PCS files for Enjoy, Sinexcel and Sungrow sit side by side in power_sequences/ for exactly this reason, and the editor lists all three without knowing any of them by name.

A note on numeric thresholds

An adjacent decision, recorded because it affects how alarm limits are authored: numeric alarm thresholds live in the map files. tools/gen_alarm_maps.py carries EXTRA_RULES as a generation-time seed, but a generator run no longer overwrites an operator's edit — --refresh is required to re-apply generated values. A threshold edited in the UI therefore survives, and the maps remain the only place an edit has effect.

H. The Alarm & Sequence Dashboard

Everything in sections E and F is also reachable from one page:

/alarm-and-sequence-dashboard      route name: alarmAndSequenceDashboard

It is protected by the same auth + admin.or.superadmin middleware as the individual editors, and it is linked from the EMS sidebar (partials/EMSmenu). The standalone routes keep working — the dashboard does not replace them.

What the dashboard is, and is not

It is a shell, not a reimplementation. It owns no editor markup and no execution logic. Every panel it shows is the existing editor, embedded from its own route, and its numbers are read from the same backend the editors use.

That choice is deliberate and was measured. Both full-page editors style body and generic tags (table, button, a, h2), and this editor's advanced-field rule is:

body.show-adv .adv { ... }

its script toggles show-adv on document.body. Inlining two such documents into one page would bleed CSS in both directions and that selector would stop matching, silently disabling the advanced fields. Extracting shared partials was rejected for the same reason. Embedding each editor in its own frame leaves it byte-for-byte as it behaves standalone, while still presenting one surface.

Two details make the frames safe:

  • nginx sends X-Frame-Options: SAMEORIGIN, which permits same-origin framing.
  • Frame sources are generated with route($name, $params, false) — a relative path with no scheme or host — so a deployment whose APP_URL points at a different alias cannot produce a cross-origin frame that renders blank.

Frames are lazy: a src is only assigned when its tab is first shown, so opening the dashboard does not boot every editor at once.

The page itself extends layouts.admin — the layout the EMS settings page uses — so it carries the normal sidebar, theme and shell rather than being a bare page. Two consequences are worth knowing before editing it. Every rule in its stylesheet is scoped to an .as-dash root, and its tab script queries inside .as-dash too: an unscoped body rule or a document-wide [data-tab] lookup would reach the shared chrome, and the layout's own menu uses data-* attributes. And the sidebar entry lives in partials/EMSmenu, which is the EMS navigation — it therefore shows on ems.gess-sweden.com. scada.gess-sweden.com renders partials/scadaMenu instead, where the route works but is not advertised.

The tabs

Tab Hosts
Alarm Management Alarm Map Editor, Alarm Threshold Editor, Alarm Action / Multi-Sequence Editor, Active Alarm Monitoring
Command Sequence Management this editor: device selection, model-specific sequences, create/edit/duplicate, execute
Protection Management the Protection tab of the EMS settings page
Monitoring & Diagnostics alarm and protection state, and sequence execution logs

Each tab is deep-linkable: append #as-tab-alarm, #as-tab-sequence, #as-tab-protect or #as-tab-monitor. The status tiles at the top link to the tab that shows them.

Device selection, model and sequence

This is the same inventory the editor's own selector uses, so the two cannot disagree. Following the requirement's example end to end, against the live system:

  1. Device category → pcs
  2. Device → pcs1
  3. Model → epcs105 (from the device's own configuration, not a list in the UI)
  4. Sequence file → emsConfig/pcs/power_sequences/EPCS105.json
  5. Sequences offered → start, stop, change_power, mode_pq, mode_vf, read_soc, read_soh

Step 5 is worth stating plainly: the names come from the model file. The requirement's illustrative names ("START BESS", "SWITCH TO PQ MODE") are not stored strings — mode_pq is the PQ-mode sequence. Nothing in the frontend hardcodes a manufacturer, a model, a device or a sequence name; a new model file appears in the list as soon as the engine can see it.

At the time of writing the live inventory reports 18 categories / 85 devices: ac, bess_energy_meter, bmu, cooling, door_sensor, ev_charger, ffr_meter, flood_sensor, frequency_meter, fss, grid_meter, heat_sensor, pcs, sensor_block, smoke_detector, solar_meter, temperature_sensor, ups. Every section of general_settings has a category, and the editor lists every device the settings configure.

Which file a change goes to

A model's sequences can live in three places, and the editor has to say which one a save will replace, because the answer decides how many devices the change reaches. Reading already resolved them in this order — most specific first — and the editor now writes to them too:

Layer File Who reads it
A device's own copy emsConfig/<category>/<device folder>/sequences/<MODEL>.json that device only, and only while the file defines the model
The family main files emsConfig/<category>/<prefix>_main/sequences/<MODEL>.json every device of that category that has no copy of its own
The shipped catalogue emsConfig/<category>/…/power_sequences/<file>.json anything the two layers above do not cover

The "Save changes to" selector chooses one, and when it is set to This device only a second selector names the device. The page then lists all three layers with their file and whether it exists, and the effective one is marked. Without a scope the editor behaves exactly as it always did: it replaces whichever file the model already lives in, which is the catalogue in this plant because no pcs_main/sequences/ has been created.

Two details worth knowing before the first save:

  • A device copy that does not exist yet is still selectable. The editor shows the content the device currently reads — from the layer behind it — and says that file does not exist yet, so saving creates it from the content shown here. The first save creates the copy byte-identically to what it was reading, so it can be done to take a device out of the shared file without changing its behaviour. device_duplicate.py --sync seeds a device folder the same way, from the family main files, so a new device starts from them rather than from the catalogue.
  • The warning above the table follows the layer. A device copy says so and names that device; a shared file lists every device that resolves to it. Restoring works the same way: a backup carries the layer it was taken from in its filename, a restore puts it back there, and a backup from another layer is refused rather than written over this one — a stale page cannot move a shared configuration onto a single device or the reverse.

The API underneath takes device_key and scope on every editor route (sequences, validate, sequences PUT, backups, restore), where scope is device, main or catalogue. Both are optional and omitting them keeps the older behaviour. A scope that cannot be acted on is dropped rather than guessed: scope=device without a device falls back to the effective file, so a request can never write to a device it did not name.

The file shapes, as they exist on disk

Per-category file, emsConfig/<category>/sequences/<category>_command_sequences.json:

{
  "schema_version": 1,
  "device_type": "grid_meter",
  "models": {
    "ME231":  { "actions": { ... }, "aliases": [ ... ], "notes": [ ... ] },
    "P8000":  { "actions": { ... }, "aliases": [ ... ], "notes": [ ... ] },
    "PM5560": { "actions": { ... }, "aliases": [ ... ], "notes": [ ... ] }
  }
}

PCS model file, emsConfig/pcs/power_sequences/<MODEL>.json:

{
  "model": "EPCS105",
  "aliases": ["EPCS105-EN", "EPCS105-AM", "EPCS105-AM-F", "EnjoyPCS EPCS105"],
  "notes": ["Addresses and scaling are based on EPCS105-EN Full Detail Spec V1.", "..."],
  "actions": {
    "start": [
      { "operation": "write_single", "address": "0x0291", "value": 1, "encoding": "u16", "verify": true },
      { "operation": "delay", "seconds": 10 }
    ]
  }
}

An action is a list of step objects. The three step kinds seen in the live files, and their union of keys, are:

Kind Example Keys
Write {"operation":"write_single","address":"0x0291","value":1,"encoding":"u16","verify":true} operation, address, value, encoding, verify
Wait {"operation":"delay","seconds":10} operation, seconds
Read {"operation":"read_holding","address":1034,"count":2,"store_as":"active_power_raw"} operation, address, count, store_as

Editing from the dashboard

The Command Sequence Management tab embeds the editor described in section E. Its step fields are address, command, condition, delay_ms, enabled, on_failure, parameters, retries, retry_count, retry_delay_ms, scale, timeout, timeout_ms, value, value_from, values. Steps can be added, duplicated, reordered and disabled; saves go to the model's own file through PUT /api/v1/ems/command-sequences/sequences, which validates the structure, backs the file up and preserves unrelated keys — see sections E and C.

The per-step failure-handling gap is closed. A step may carry an on_failure key: abort (the default, and what every file written before the key existed does) or continue. continue records the failure and runs the remaining steps anyway, for sequences whose later steps do not depend on the one that failed. The run is still reported FAIL, so no setting can hide a failure from the operator. The engine refuses any other value, and the admin validation asks the engine to parse it, which keeps a typo like continue_on_error from being saved as if it meant something. A stop request is not a failure to continue past: it unwinds through a distinct SequenceStopped type that the policy lets through.

Executing a sequence

Execution is asynchronous and identified. POST /api/v1/ems/command-sequences/test starts a run and returns a test id; the caller polls GET .../test/{id} until the job leaves RUNNING. A run against pcs1 uses that device's own configured endpoint.

Two facts constrain who can run what:

  • Over HTTP, runs are simulator-only. authorize_physical is deliberately not read from the request body, so a frontend request can never write to live equipment. Physical execution remains a deliberate backend-side act. This is the requirement's SIMULATOR (default) versus LIVE DEVICE split, enforced in the backend rather than by a dropdown.
  • One run at a time per device. A second start against a device already running raises a conflict, which is the requirement's "prevent conflicting sequences on the same device".

Monitoring, stopping, and history

  • Monitoring. The editor shows the run's steps with their status as the job progresses — the per-step fields in section F. The job record carries its status, device, action and start time.
  • Stopping. POST .../test/stop sets the job's cancellation event. The run ends between steps, never mid-step, so a device is not left part-way through a write sequence.
  • History. GET /api/v1/ems/command-sequences/test (no id) lists every run the backend process remembers, newest first. Be precise about what that means: the registry is in memory and capped (_MAX_JOBS = 50), so this is recent history, not an archive. It does not survive a backend restart, and it is not the long-term history endpoint the requirement's section 7 sketches.

The status indicators, and the two that are not live yet

Indicator Source State
Connected Devices the sequence inventory live
Active Alarms GET /api/v1/ems/alarms/active → active_alarm_count live
Running Sequences job registry, status RUNNING live
Failed Sequences job registry, finished and not PASS/SKIPPED/STOPPED live, recent-only
Active Protections none unavailable
Latched Protections none unavailable

The last two are shown as an em dash rather than a number. protection_rules.py owns the rule vocabulary and rule_status(rule, latched=, active=) exists to label a rule, but nothing in the running system supplies those two flags: there is no endpoint, no stored state, and generate_protection_panel.py only renders the vocabulary into the UI. A number here would be invented, so the tile instead links to the page where the rules are configured. See EMS_PROTECTION_FRAMEWORK.md section 13 for what closing this would require.

Gateway-scoped editors

The protection and alarm-action panels belong to one gateway. The dashboard therefore offers a Site scope selector, populated from the same device_fora_sites.gateway_key values the settings page validates against, and forwarded to those panels as ?gateway_id=<serial>.

A gateway is never chosen for you. With three valid gateways on the live system, defaulting to the first would risk saving settings to the wrong hardware — the same reason the settings controller refuses to guess. Until a gateway is chosen, those two panels stay unloaded and say why. Deep link with a scope:

/alarm-and-sequence-dashboard?gateway_id=GTW-ems100CX#as-tab-protect

An unrecognised gateway_id is rejected and treated as no scope at all.