Skip to content

EMS Protection Framework

This document covers the EMS protection system only. Alarm management and the device command sequence framework have their own documents: accessing-alarms.md, alarms-api.md, alarm-mapping-and-endpoints.md, alarm-code-to-register-relationship.md and DEVICE_COMMAND_SEQUENCE_FRAMEWORK.md. Where protection touches those systems, this document links to them rather than restating them.

Status of this framework. The configuration layer, the rule vocabulary, the settings panel and the seeder synchronisation are implemented and tested. The periodic evaluator that reads measurements and drives alarms from these rules is not implemented; section 4 states exactly which parts exist and which do not. Everything below is labelled accordingly, because a protection document that implies more than the code does is worse than no document.

1. Protection Architecture

The EMS protection system is supervisory. It watches the plant, raises alarms, and coordinates a response across devices. It is not, and must not be used as, the primary means of protection for people or equipment.

Three layers of protection exist in a GESS plant, and they are not interchangeable:

Layer Where it lives Response time Can it be relied on for safety
Hardware protection Relays, breakers, fuses, PCS and BMS internal protection Milliseconds, deterministic Yes, when certified and validated for the application
Device safety functions PCS anti-islanding, BMS cell protection, charger safety Device-defined Yes, per the device's certification
EMS supervisory protection This framework Software evaluation rate No — supervisory coordination only

The EMS layer earns its place by doing what the layers below it cannot: reading plant-wide measurements from meters, acting on conditions that span several devices, coordinating a sequence across PCS, BESS and chargers, and recording what happened for the operator.

Responsibilities:

  • Owns the protection rule vocabulary and its configuration.
  • Owns the association between a protection condition and the command sequences that respond to it.
  • Owns the AUTO/MANUAL reset policy per rule.
  • Does not own alarm definitions or sequence definitions. Both are shared with the alarm management and command sequence systems, so a protection rule and an alarm are never two separate definitions of the same condition.
  • Does not replace any hardware protection function, and clearing an EMS latch never restarts equipment or bypasses a physical protection device.

2. Protection Rule Configuration

The rules live in the protections.protection_rules group of emsConfig/ems/ems_control_setting.json, alongside the eight legacy keys that predate the framework (overvoltage_v, undervoltage_v, overcurrent_a, over_frequency_hz, under_frequency_hz, temperature_thresholds, fire_suppression_integration, ems_bms_comm_timeout_ms). Those keys are left in place and untouched.

Per-rule structure

Each entry in protection_rules.rules is:

Field Meaning
rule_id Unique identifier, [A-Za-z0-9_.-]{1,64}
rule_name Operator-facing name
enabled Whether the rule is armed
measurement_source The device key supplying the measurement
measurement_parameter voltage, frequency, current, power, temperature, soc, rocof
comparison_operator >, >=, <, <=, ==, !=
trigger_threshold Activation threshold
activation_delay_ms How long the condition must hold before it triggers
recovery_threshold Threshold at which the condition is considered cleared
recovery_delay_ms How long recovery must hold before it counts as clear
severity critical, major, minor, warning, info
reset_rule AUTO or MANUAL
command_sequences Multi-device sequences to run (see section 5)
action_execution_interval_sec Periodic action evaluation interval, default 30
status Current state; read-only, not configurable

No threshold has a default

This is deliberate and load-bearing. Every threshold, delay and recovery field is null until an engineer sets it, and every rule ships enabled: false. The only keys carrying a default are enablers (false), selectors (empty), reset rules (MANUAL) and the documented 30-second action interval.

The reason is that a threshold is a property of the equipment, its connection and the applicable grid code. A default would be a number nobody chose for the site it protects, applied silently to every installation. A test walks all 110 category keys and fails if any limit acquires a default.

The 30-second interval

action_execution_interval_sec (default 30) governs periodic re-evaluation of permitted repeated actions — re-issuing a setpoint, re-checking whether a commanded state still holds. It is not the detection rate. Measurements and protection conditions must be processed at the rate their own rule requires, and where a grid code demands a deterministic response time the protective function must be realised in validated hardware, not in periodic software evaluation.

3. Electrical Protection Categories

The vocabulary defines nine sections, mapped to the requirement's ten. Each has its own keys and its own associated sequences.

Section Key prefix Covers
General Protection Settings protection_actions_* Master enable, interval, default reset rule, clearance mode allow-list
Voltage Protection protection_voltage_* Overvoltage, undervoltage, imbalance, measurement source and reference, reset rule
Frequency Protection protection_frequency_* Overfrequency, underfrequency, RoCoF, source, reset rule
Current Protection protection_current_* Overcurrent, phase imbalance, source, reset rule
Power Protection protection_power_* Grid import limit, grid export limit, reverse flow, PCS overload, BESS charge/discharge limits, source, reset rule
BESS Protection protection_bess_* SOC high/low, battery voltage high/low, overtemperature, charge/discharge current, PCS overload, BMS comms, source, reset rule
EV Charging Protection protection_ev_* Charger overcurrent, overtemperature, excessive power, comms failure, allocation violation, grid connection capacity, max current/power, source, reset rule
Communication and System Protection protection_comm_* Device timeout, reset rule
Protection Actions and Reset Rules protection_actions_* Interval, default reset, clearance allow-list
Protection Status and Monitoring protection_status Read-only runtime state, not configuration

Voltage protection carries protection_voltage_measurement_reference, which selects line-to-line or line-to-neutral measurement, so both are supported where the meter offers them. The reference is "" (not set) by default like every other selector.

Every rule, in every category, supports the same eight things: enable, source, threshold, trigger condition, activation delay, recovery threshold, reset rule, alarm severity and associated sequences. A rule that omits any of them is refused by the validator rather than silently defaulted.

4. Protection Processing

The pipeline a rule is designed for:

  1. Acquire the measurement from measurement_source at the rate the condition requires.
  2. Compare against trigger_threshold using comparison_operator, holding for activation_delay_ms.
  3. On transition to active: activate the alarm, record the event, identify the configured actions, resolve the manufacturer- and model-specific sequences, execute them across the devices, record the results.
  4. On clearance: check recovery_threshold, hold for recovery_delay_ms, then apply the AUTO/MANUAL policy.
  5. Persist state so a restart does not lose a latched protection.

What exists today. protection_rules.py implements the parts of this pipeline that are pure decisions, so the behaviour is testable without a plant:

  • validate_rules() — the configuration contract, including the sequences.
  • release_decision() — the AUTO/MANUAL rule, returning whether a latch may release and why not.
  • rule_status() — derives disabled, armed, active or latched.

What does not exist. The evaluator itself: measurement acquisition, the edge detection that turns a held condition into an active protection, and the call into the alarm action executor. The executor those calls would target does exist and is tested (alarm_actions.py, with the transition detection in ems_alarm_status.py), so the evaluator is the remaining piece, not the machinery beneath it.

One detail the evaluator must respect, already solved in the alarm layer: transitions are recorded as pending work rather than acted on at the moment of observation, because the alarm editor also evaluates. If a transition were consumed by an editor read, the protection action would never fire.

5. Multi-Device Protection Actions

A protection event must be able to fire several sequences across several devices. Rather than invent a second mechanism, a protection rule uses the same command_sequences schema as an alarm map entry, validated by the same code:

{
  "action_id": "reduce_pcs_power",
  "device_category": "pcs",
  "device_key": "pcs1",
  "sequence": "reduce_power",
  "trigger": "active",
  "order": 1,
  "allow_on_clear": false
}

The sequence name is resolved against the device's own model at execution time, which is what makes one rule work across a plant with mixed PCS models: the rule names an intent, the model map names the registers.

Sequences are ordered by order, and a missing order is refused rather than treated as a tie, so execution order is never accidental.

Clearance actions are gated. A sequence marked trigger: "clear" runs only if it also sets allow_on_clear: true, no other alarm is active, and the current operation mode is in protection_actions_clearance_allowed_modes. All three must pass. Restoring power automatically the moment a condition clears is exactly the kind of unattended action this framework exists to prevent.

Where the sequences are defined. On the alarm. A protection rule and its alarm are one definition, so the panel links to the alarm definition editor rather than offering a second place to edit the same thing.

6. Reset Rules

Every rule carries its own reset_rule.

MANUAL (the default): once triggered, the protection stays latched after the condition clears. An authorised operator must reset it. A critical overvoltage protection set to MANUAL remains latched even after voltage returns to normal — that is the point of it.

AUTO: the latch may release, but only when all three of these hold:

  1. The condition has cleared, judged against recovery_threshold.
  2. recovery_delay_ms has elapsed with the condition staying clear.
  3. The required safety checks pass.

release_decision() refuses to release on an unrecognised reset rule, so a configuration typo latches rather than releases. The cautious failure is the correct one.

Two limits that follow from section 1:

  • Clearing a software latch does not restart equipment. It permits the coordinated sequences to run; a PCS restart is a sequence a human configured, not a side effect of a latch clearing.
  • Clearing a software latch does not bypass a physical protection device. If a breaker is open, closing it remains a hardware function.

7. Frontend Configuration

The panel is resources/views/partials/emsProtectionRulesPanel.blade.php, included from emsConfigurationOperation.blade.php inside the manual tab, directly after the existing Safety & Protections card. That tab's existing save carries it, because every field binds through data-json-path — the same mechanism every other setting in that view uses.

The panel is generated, not hand-written:

python3 generate_protection_panel.py            # writes the partial
python3 generate_protection_panel.py --check    # exits non-zero if stale

It is generated from protection_rules.py because the panel must name exactly the settings the engine knows about. Two hand-maintained lists would drift, and the drift would be silent: a field an operator can set that the engine ignores, or a rule the engine acts on that no operator can configure. tests/test_protection_panel_in_sync.py asserts the file on disk matches the generator, so adding a rule means editing the Python and re-running the generator.

The panel shows, per category: an enable toggle, the threshold/delay/recovery inputs (empty, with no default), the AUTO/MANUAL reset selector, and the measurement source with the device inventory the controller already passes offered as suggestions. Rule rows are editable with the full documented field set. Each category links to the alarm definition editor for the sequences.

8. Backend APIs

The frontend reads and writes protection settings through the existing EMS settings API. No protection-specific endpoint is needed for configuration.

Method Path Purpose
GET /api/v1/ems/settings Returns the settings with the rule group materialised
PUT /api/v1/ems/settings Merges a save; the rule group is materialised before writing

Both paths apply ensure_protection_rules(). Configuration, status monitoring and manual reset would be added as endpoints on this same server when the evaluator lands; the shapes intended are:

Method Path Purpose
GET /api/v1/ems/protection/status Per-rule state: disabled, armed, active, latched
POST /api/v1/ems/protection/reset Manual reset of a latched rule, authorised and recorded
GET /api/v1/ems/protection/events The recorded protection event log

These are not implemented; they are listed so the contract is not invented later under time pressure.

The configuration does not live in the JSON file

emsConfig/ems/ems_control_setting.json is gitignored (.gitignore:29). It is per-installation state, not source control content. Consequently:

  • The group cannot be shipped inside that file: a fresh checkout would not have it, and a hand edit would be lost on the next settings write.
  • ensure_protection_rules() materialises it on every load and save, via protection_rules.merge_into(), which adds keys without overwriting or removing anything. An installation that predates the framework gains the group and keeps every value it had.
  • database/seeders/EmsSettingTableSeeder.php is tracked and embeds the same settings JSON, so the seeder is how a new install gets the group. It was synchronised with the same vocabulary.

A GET stays a read: the merged copy is served, never written back.

9. Configuration Examples

Thresholds below are illustrative shapes only. The values must come from the equipment rating, the connection agreement and the applicable grid code.

Overvoltage, manual reset, reduce PCS then stop:

{
  "rule_id": "ov_grid_1",
  "rule_name": "Grid overvoltage",
  "enabled": true,
  "measurement_source": "grid_meter1",
  "measurement_parameter": "voltage",
  "comparison_operator": ">",
  "trigger_threshold": 0,
  "activation_delay_ms": 0,
  "recovery_threshold": 0,
  "recovery_delay_ms": 0,
  "severity": "critical",
  "reset_rule": "MANUAL",
  "command_sequences": [
    {"action_id": "reduce", "device_category": "pcs", "device_key": "pcs1",
     "sequence": "reduce_power", "trigger": "active", "order": 1}
  ]
}

Underfrequency, automatic release, no action while active:

{
  "rule_id": "uf_1",
  "measurement_source": "frequency_meter1",
  "measurement_parameter": "frequency",
  "comparison_operator": "<",
  "reset_rule": "AUTO"
}

PCS overload with a clearance action, gated:

{
  "rule_id": "pcs_overload",
  "measurement_source": "pcs1",
  "measurement_parameter": "power",
  "comparison_operator": ">",
  "reset_rule": "AUTO",
  "command_sequences": [
    {"action_id": "limit", "device_category": "pcs", "device_key": "pcs1",
     "sequence": "limit_power", "trigger": "active", "order": 1},
    {"action_id": "restore", "device_category": "pcs", "device_key": "pcs1",
     "sequence": "restore_power", "trigger": "clear", "order": 2,
     "allow_on_clear": true}
  ]
}

EV charging, two devices from one event:

{
  "rule_id": "ev_capacity",
  "measurement_source": "grid_meter1",
  "measurement_parameter": "power",
  "comparison_operator": ">",
  "reset_rule": "AUTO",
  "command_sequences": [
    {"action_id": "a", "device_category": "charger", "device_key": "charger1",
     "sequence": "limit_current", "trigger": "active", "order": 1},
    {"action_id": "b", "device_category": "charger", "device_key": "charger2",
     "sequence": "limit_current", "trigger": "active", "order": 2}
  ]
}

10. Testing and Verification

Against the engine:

cd EnergySyc_EMS_ES100Cx12S
python3 -m pytest tests/test_protection_rules.py -q           # the vocabulary
python3 -m pytest tests/test_protection_settings_e2e.py -q    # HTTP load and save
python3 -m pytest tests/test_protection_panel_in_sync.py -q   # panel drift

test_protection_settings_e2e.py drives the real settings server over a real socket, against a temporary configuration with the group stripped out, so it tests an installation that predates the framework rather than one that already has the group. It asserts that a GET serves the group, that a GET does not rewrite the file, that a save persists it, that a configured threshold survives later saves, that a partial save removes nothing, and that the legacy keys are never disturbed.

What the tests do not cover, and cannot until the evaluator exists: threshold and activation-delay accuracy against live measurements, recovery and hysteresis behaviour, multi-device sequence execution from a protection event, state persistence across an EMS restart, and communication failure handling.

Against the BESS Simulator, once the evaluator lands, the sequence to verify a rule end to end is:

  1. Drive the simulated meter or PCS to the trigger condition and confirm the alarm activates only after activation_delay_ms, not before.
  2. Confirm the configured sequences execute across every named device, in order.
  3. Return the measurement to recovery_threshold and confirm clearance waits for recovery_delay_ms.
  4. For MANUAL, confirm the latch holds after clearance and that a reset releases it; for AUTO, confirm it releases after all three conditions pass.
  5. Restart the EMS and confirm a latched rule is still latched.
  6. Save a protection setting, reload the page, and confirm it round-trips.
  7. Change a protection setting and confirm unrelated device configuration and EMS functions are unaffected.

11. Adding New Protection Rules

Adding a rule to an existing category is configuration only: add the entry to protection_rules.rules. No code change, and the panel picks it up because the rules table is generic.

Adding a new category or a new key:

  1. Add the keys to the category dict in protection_rules.py, with None for anything that is a limit and a sensible default only for enablers, selectors and modes.
  2. Add the category to CATEGORY_LABELS in generate_protection_panel.py if it needs a display name or icon.
  3. Run python3 generate_protection_panel.py to regenerate the panel.
  4. Run python3 -m pytest tests/test_protection_rules.py tests/test_protection_panel_in_sync.py.
  5. Re-run the seeder block generation if the seeder must carry the new key.

No framework redesign is required, and the tests will fail if step 3 is skipped or if a new limit arrives with a default attached.

12. Safety and Limitations

Limitations of EMS software protection.

  • It evaluates periodically. Its response time is not deterministic and must not be relied on where a deterministic response is required.
  • It depends on communication. A device that stops answering cannot be protected by this layer, and a measurement source that fails silently is worse than one that fails loudly — protection_comm_device_timeout exists for that reason.
  • It depends on the measurement source being truthful. It cannot detect a meter that reports a plausible wrong value.
  • It is software on general-purpose hardware. It is not certified, and no certification claim should be inferred from it.
  • A latched protection depends on an operator resetting it. A plant left unattended with a manual latch stays latched.

Required independent hardware protection. Certified protection relays, switchgear, breakers and fuses; PCS internal protection including anti-islanding; BMS cell-level protection; charger safety functions. None of these may be omitted on the grounds that the EMS also watches the condition.

Grid-code considerations. Where a grid code specifies a protection function with a defined response time, that function must operate through suitably designed and validated equipment. Periodic EMS evaluation does not satisfy a deterministic-response requirement, and configuring a rule here does not make one. The applicable grid code, connection agreement and equipment certification govern; the thresholds in this framework must be set to match them.

The rule that follows from all of this. If disabling the EMS protection framework would leave the plant without protection for a condition, then the plant is under-protected and the gap is in hardware, not in configuration.

13. Managing protection through the Alarm & Sequence Dashboard

The protection configuration described above, the alarm rules that can trigger command sequences, and the sequence engine itself are all reachable from one page:

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

It is protected by auth + admin.or.superadmin (the same middleware as the standalone editor routes, which continue to work) and is linked from the EMS sidebar. The dashboard is a shell: it embeds the existing editors from their own routes and reads its numbers from the same backend they use, so there is nothing to keep in sync and no second copy of the protection panel.

Where protection lives in the dashboard

The dashboard carries seven sections. Protection appears in three of them.

Section What it gives you
Alarm Actions & Reset Rules Protection Rules & Reset Behaviour, which links to the Protection tab of the EMS settings page: general settings, voltage, frequency, current / power, BESS and EV charger rules, plus the automatic and manual reset behaviour. And Device Self-Test & Diagnostics, which links to /emsSelfTest
Alarm Management the alarm map editor (/alarm-definition-editor) and the Alarm Definition Catalogue (/emsAlarmDefinitions)
Execution Monitoring & History the live run monitor and the sequence file backups, both pointing at the sequence editor's Test panel

The alarm action editor does not exist. The backend validates an actions list on an alarm entry and alarm_actions.py can execute it, but no route, view or controller exposes it: the module is imported only by its own tests, and neither the alarm map editor nor the Alarm Definitions controller mentions actions. An alarm's command sequences are therefore configured by editing its alarm map JSON today. That is an implementation gap rather than a documented workflow, and the multi-device response described in section 5 cannot be configured from the UI until an editor exists.

Alarm-triggered multi-device sequences are executed by the same engine the Command Sequence Editor section drives. See DEVICE_COMMAND_SEQUENCE_FRAMEWORK.md sections D and H for the execution path, its simulator-only HTTP rule, and the one-run-per-device conflict guard.

Gateway scope, and why nothing is preselected

Every protection and alarm-action panel belongs to a single gateway. The dashboard reads the valid device_fora_sites.gateway_key values and offers them as a Site scope selector, forwarding the chosen value as ?gateway_id=<serial>.

It deliberately does not preselect one. The live system has three active gateways (GTW-ems100CX, gtw-DCU-100F, GTW-ems100CX1), and the settings controller takes the same position for the same reason: saving a protection threshold against the wrong gateway would write it to the wrong hardware. Until a gateway is chosen, those panels are left unloaded with a notice saying why, and an unrecognised gateway_id is treated as no scope at all rather than passed through.

Active and latched protection state is not reported yet

The dashboard's Active Protections and Latched Protections indicators show an em dash, not a number. That is intentional, and the reason is worth recording because it is easy to mistake for an oversight.

protection_rules.py owns the rule vocabulary, and it exposes

rule_status(rule, *, latched: bool, active: bool) -> str

so the notion of a latched or active rule exists as a labelling helper. But nothing in the running system supplies those two flags: no endpoint returns protection state, no component persists a latch, and generate_protection_panel.py only renders the rule vocabulary into the UI (verified: it never calls rule_status). /api/v1/ems/operation-status reports operating mode and power/charge state, not protection state.

Reporting a count would therefore mean inventing one, so the tile links to the page where the rules are configured instead. Closing the gap properly needs three things, in this order:

  1. An evaluation pass that compares current readings against each rule and calls rule_status with real active / latched values.
  2. Somewhere for a latch to live — a latch survives the condition clearing, and the manual reset in section 8 is what clears it, so the state cannot be derived from a single reading alone.
  3. A read-only endpoint exposing the result, which the dashboard then reads exactly as it already reads active_alarm_count.

Until (1) and (2) exist there is no honest number to show. Note the safety direction of this: the protection configuration is fully editable and fully live through the dashboard today. It is only the read-back of triggered state that is missing, and an absent indicator is a smaller risk than a stale one that an operator might trust.