EMS alarms — how they map, and how to use the endpoints
Reference for the active-alarm pipeline served by the EMS backend.
- Engine:
ems_alarm_status.py(aggregation, condition evaluation, message building) - HTTP surface:
ems_settings_api.py(serversub-command) - Runtime container:
ems-backend, listening on container port 8080 (not published; only the Modbus port 1540 is mapped to the host) - Verified against deployed
ems_alarm_status.pymd55a844794…andems_settings_api.pymd534e78342…, which are byte-identical to this tree. The live numbers and example payloads below were captured from that deployment.
The endpoint is read-only and stateless. It never writes a queue, never opens
Modbus, and never touches controller state. It reports what is alarming right
now, derived from the current lastValue files — there is no retained alarm
history here. (The frontend's own alarm list is a separate, database-backed path;
see §7.)
1. The mapping chain
Everything comes from four inputs, combined per device:
| # | Input | Location | Supplies |
|---|---|---|---|
| 1 | Register map | emsConfig/<type>/<device>/<stem>_register*.json |
device_id, component_type, field→address |
| 2 | Alarm map | emsConfig/<type>/<device>/<stem>_alarm_code*.json |
the alarm catalogue and its activation rules |
| 3 | Live reading | lastValue/<stem>_lastValue.json |
the measured values |
| 4 | Settings | emsConfig/ems/ems_control_setting.json |
status per device, and the gate that decides whether a device is reported at all |
Per device the chain is:
discover device folder
→ read register map → device_id, component_type, model, address index
→ pick alarm map → entries (rules + display text)
→ resolve reading file → sibling <stem>_lastValue.json
→ settings gate → skip this device type if its group is switched off
→ evaluate each entry → one row per entry whose rule is TRUE
→ sort + serialise
1.1 Device discovery
_iter_devices() walks emsConfig/<type>/:
- Type folders
ems,db,api_portal,api_vpn,bakup,backup,docs,modes,tmpare skipped. - Any sub-folder containing a
*_alarm_code*.jsonor a*register*.jsonis a device (pcs1,pcs2, …pcs12). - If the type folder has no such sub-folder but has the files itself, the type
folder is the single device (
frequency_meter,bmu,ups, …).
1.2 Register map → identity and addresses
The device's register map is the first non-model file matching *register*.json
in the device folder (e.g. pcs_register_full.json).
device_id→ the report'sdevice_id(falls back to the folder name).component_type→component_typeon every row.categories.<category>.<section>.<field> = {scale, address, data_type, registers, value, rw_type}is flattened into afield → definitionindex. That index is the only source ofregister_address.
Real definition, pcs1:
"bc_battery_cluster": { "read_only": {
"soc_state_of_charge_item": {
"scale": 1, "address": 3005, "data_type": "UINT16",
"registers": 1, "value": 0, "rw_type": "read_only" }
}}
1.3 Model resolution
The model selects the alarm map (and any model-specific register map) for a
device. It comes from emsConfig/selected_model.json:
by_register_file[<register file name, lowercased>]- else the
modelkey at the top of that file
The real file (abridged — it also lists solarMeter_register.json,
frequencyMeter_register.json, ac_register.json, cooling_register.json,
fss_register.json, sensorB_register.json and bmu_register_1..10.json):
{
"model": "ME231",
"by_register_file": {
"pcs_register_full.json": "EPCS105",
"gridMeter_register.json": "ME231",
"ups_register.json": "UPS_10K",
"bmu_register_1.json": "BMU100"
}
}
The slug is tried lowercased first, then verbatim, which is why the files on disk
are lowercase (pcs_alarm_code___epcs105.json) while selected_model.json says
EPCS105. A model of default/none/empty is ignored (_model_slugs).
Consequence worth knowing: the two energy meters have no by_register_file
entry, so they fall back to the top-level model and resolve to the default
map — hence bessMeter_alarm_code.json with alarm_map_source: "default" in the
live payload, while every PCS resolves to a model map.
1.4 Alarm-map selection
Inside the device folder, glob("*_alarm_code*.json"):
- first file whose stem ends with
___<model lowercased>→alarm_map_source: "model" - then
___<Model>verbatim →"model" - else the first file without
___→"default" - if the device folder has none, repeat 1–3 in the type folder
The separator is exactly three underscores (___), the same convention as the
model register maps (pcs_register_full___sinexcel_pws1_250k.json).
If nothing is found, the device is still listed with
"note": "no_alarm_map" and alarm_map: null.
1.5 Reading resolution
Which file. The stem is the first candidate that exists as
lastValue/<candidate>_lastValue.json, in this order:
- the register map's
device_id(gridEnergyMeter1) - the config folder name (
grid_energy_meter) - the register-file prefix (
gridMeter_register.json→gridMeter)
Failing all three, a unique prefix match against the files present is used
(case-insensitive, either direction). A prefix matching more than one file
resolves to nothing, so pcs1 is never satisfied by pcs10.
The winner is reported as reading_key (null when nothing matched). Seen live:
gridEnergyMeter1 → gridMeter, ups_unit → ups, Cl1_P1 → null.
Which field. The entry's field (alias register) is resolved in order:
- an exact key in the reading
"<stem>__<field>"— the merged formload_last_values()produces (pcs1__soc)- a unique suffix match:
key == fieldorkey.endswith("_" + field)
Rule 3 exists because devices prefix their readings: frequency_hz finds
gridMeter_frequency_hz, l1_fault finds pcs_l1_fault. Ambiguity resolves to
nothing rather than guessing.
If all of those miss, the value falls back to the register definition's own
value (the last value written into the register map). Verified against the
engine, with a reading containing soc, pcs1__soc, pcs_l1_fault and
gridMeter_frequency_hz, and a register index containing soc at address 3005:
field |
resolved value | register_address |
matched by |
|---|---|---|---|
soc |
55 |
3005 |
exact key |
pcs_l1_fault |
True |
null |
unique suffix |
l1_fault |
True |
null |
unique suffix |
frequency_hz |
50.01 |
null |
unique suffix |
frequency |
None → never fires |
— | nothing (not a suffix) |
| (field absent from the reading) | register definition's value |
its address | register map |
So register_address: null on a firing alarm means only that the field is not in
the register map — the rule still works.
The keys timestamp, device_id, model, meter_key and alarm are stripped
from the reading before evaluation; an entry may not use them as a field.
1.6 The settings gate
The live report only reports devices whose settings block is switched on. Each
emsConfig folder maps to one general_settings group:
emsConfig folder (device_type) |
general_settings group |
|---|---|
pcs |
pcs |
bmu |
bmu_units |
ups |
ups_units |
air_condition_unit |
ac_units |
fire_safety_system |
fss |
liquid_cooling_unit |
cooling_unit |
sensor_block |
sensor_blocks |
grid_energy_meter |
grid_meters |
solar_energy_meter |
solar_meters |
frequency_meter |
frequency_meters |
bess_energy_meter |
bess_energy_meters |
ffr_energy_meter |
ffr_meters |
The rule (_group_is_inactive) is deliberately conservative:
- a device type is skipped only when its group exists, has at least one
statusfield, and none of those statuses isactive; - an unknown type, a missing group, or a group without any
statusfield is reported normally — a status that cannot be read never hides a device.
Skipped devices increment totals.devices_skipped and are absent from devices.
The gate exists because a switched-off device is polled by nobody, so its
lastValue file stops being refreshed and any threshold read from it would be
evaluated against a frozen reading — a permanent phantom alarm.
status on each reported device is that group's status value for the device key
(or the folder name).
1.7 Evaluation
Per entry, in order:
- the
self_testflag must match the report mode (see §4.2); fieldmust be present — otherwise the entry is catalogue-only and never fires;- the condition must parse (§3.1);
- the resolved value must not be
None— a missing reading never alarms; ignore_zero: trueskips the entry while the value is exactly0;- the comparison must be true.
Rows sort by severity rank, then device_id, then alarm_code.
2. Severity and message text
Severity must be one of four known words; anything else sorts last.
| severity | rank |
|---|---|
critical |
0 |
major |
1 |
minor |
2 |
warning |
3 |
| (other / missing) | 99 |
message is not simply the map's text.
For self-test rows it is rewritten per device type and severity from
SELF_TEST_CONDITIONS. Real examples:
| device_type | critical | major | warning |
|---|---|---|---|
pcs |
Battery SOC critically low: below the minimum operating limit. | Cell temperature abnormally high: above the safe operating limit. | Battery SOH below 80%: state of health degraded. |
fire_safety_system |
Fire detected: fire signal active. | Smoke detected above the alarm threshold. | Door open: enclosure unsealed. |
ups |
Mains supply failed: UPS running on battery. | UPS battery low: runtime below the safe limit. | UPS overload: load above rated capacity. |
frequency_meter |
Grid frequency out of range: above the upper limit. | Grid frequency below 49.5 Hz. | Grid power factor below 0.8. |
liquid_cooling_unit |
Coolant flow lost: circulation below the minimum. | Coolant temperature above the safe operating limit. | Coolant level below the warning limit. |
The map's own alarm_display_name is kept regardless.
For live rows the map's message (or description) is used, with the measured
value appended. Verified against the engine — the message is passed through
untouched when the value or the operator is missing, and a boolean flag never gets
a measured clause:
| map message | value / rule | resulting message |
|---|---|---|
| Battery state of charge below 3%, discharge must stop. | 2.0, < 3 |
Battery state of charge below 3%, discharge must stop (measured 2%). |
| Grid frequency above 50.5 Hz. | 51.5, > 50.5 |
Grid frequency above 50.5 Hz (measured 51.5 Hz). |
| Grid frequency above the upper limit. | 51.5, > 50.5 |
Grid frequency above the upper limit (measured 51.5, above the limit of 50.5). |
| Coolant temperature too high, 70 degC limit. | 74.25, > 70 |
Coolant temperature too high, 70 degC limit (measured 74.25 degC). |
| Power factor below the target. | 0.0125, < 0.95 |
Power factor below the target (measured 0.013, below the limit of 0.95). |
| A-phase overvoltage fault: voltage has exceeded the safe operating limit. | True, truthy |
A-phase overvoltage fault: voltage has exceeded the safe operating limit. |
| Alarm count: number of events recorded since the last reset. | 3, > 0 |
Alarm count: number of events recorded since the last reset (measured 3). |
The rules behind those outputs:
- The unit comes from the map's wording, longest alternative first (
kWhbeforeW), and a unit glued to its number still matches (245V,3%). %and°Cbind tight (measured 2%,measured 74.25 degC); other units get a space (measured 51.5 Hz).- When the wording carries no unit, the limit is phrased as
above the limit of 50.5; with a unit it becomesabove the 50.5 Hz limit. - The limit is added only when the wording does not already state that number, so “below 3%” is not repeated as “the 3% limit”.
- A limit of
0is a counter rule (> 0), not a threshold, so it is never phrased: a count of 3 reads(measured 3), never(measured 3, above the limit of 0). - Numbers render as
47,49.2,0.013— never49.200000000000003, and a small non-zero value is never rounded to0. - A trailing
.in the map text is dropped before the clause is appended, and re-added after it.
Because the wording drives the unit and the limit phrasing, write the map's
message as a complete operator sentence that names the condition; the engine
adds the measurement only.
Generated entries are worded the same way: tools/alarm_message_style.py turns a
register field name into <condition>: <what it means>., and
tools/rewrite_alarm_messages.py re-derived the 9,049 generated messages in 81
maps from the old "<Device> reported <Field>." template. Hand-authored wording
was never touched; each rewritten map keeps the previous text in a .bak-msgstyle
file beside it.
3. Authoring an alarm map
3.1 Entry schema
A map is a JSON object keyed by alarm code:
{
"PCS-SOC-LOW": {
"alarm_display_name": "Battery SOC Critically Low",
"message": "Battery state of charge below 3%, discharge must stop.",
"severity": "critical",
"field": "soc_state_of_charge_item",
"condition": "< 3",
"ignore_zero": true
},
"PCS-1004": {
"alarm_display_name": "A Phase Overvoltage Fault Flag",
"message": "A-phase overvoltage fault: voltage has exceeded the safe operating limit.",
"severity": "critical",
"field": "a_phase_overvoltage_fault_flag",
"op": "truthy"
},
"ALM-2100": {
"alarm_display_name": "Hardware status word, bit 3",
"message": "Status word bit 3 latched.",
"severity": "major",
"field": "gridMeter_status_word",
"op": "bit", "value": 3
},
"CAT-0001": {
"alarm_display_name": "Documented but not evaluated",
"message": "No field key: this entry can never fire."
}
}
| key | required | meaning |
|---|---|---|
alarm_display_name |
recommended | falls back to name |
message |
recommended | falls back to description; the measured value is appended |
severity |
recommended | critical / major / minor / warning |
field |
to fire | reading/register name; alias register |
op |
optional | == != < <= > >= truthy falsy bit; alias operator; aliases eq ne lt le gt ge; = means == |
value |
with op |
right-hand operand; for op: "bit" it is the bit index |
condition |
optional | shorthand string "<op> <operand>"; alias active_when |
bit |
optional | legacy shorthand for op: "bit" |
ignore_zero |
optional | skip the rule while the value is exactly 0 |
self_test |
reserved | marks a synthetic entry (§4.2) |
Defaults and shorthands:
- no
field→ catalogue only, never fires. Existing hand-written maps keep working untouched until given rules. fieldpresent but noop/value/bit/condition→ truthy.conditionwith a bare word:truthy/active/alarm/fault→ truthy;falsy/inactive/normal/ok→ falsy; anything else →== <word>.conditionliteral types:"< 3"→('<', 3.0),">= 80"→('>=', 80.0),"== 12"→('==', 12.0),"true"→('==', True),"weird state"→('==', 'weird state'). Numbers always become floats, which is why a stored"< 3"is reported back as"< 3.0"(§4.1).op: "truthy"/"falsy"take their (unused) operand fromvalueorbit.
3.2 Comparison semantics
Verified against _compare():
| value | op | operand | result | why |
|---|---|---|---|---|
"fault" |
== |
"FAULT" |
True |
string compare is case-insensitive |
"FAULT " |
== |
"fault" |
True |
whitespace trimmed |
"25.0" |
> |
20.0 |
True |
numeric strings compare numerically |
"idle" |
> |
20.0 |
False |
non-numeric operand → ordered comparisons are False |
0 |
== |
"0" |
True |
numeric-vs-string resolves numerically |
3 |
bit |
1 |
True |
3 & (1 << 1) |
"" |
truthy |
– | False |
empty string is false |
Truthiness for truthy/falsy: bool as-is; numbers != 0; these strings are
true — 1, true, yes, on, active, alarm, alarm_active, fault,
error, critical, major, minor, warning, high, low; these are
false — "", 0, false, no, off, inactive, none, null,
normal, ok, noerror, no_error, n/a, -, nan; any other numeric string
by value; anything else true.
< <= > >= against a non-numeric value or operand → False (never
fires). That is why a word-valued flag needs truthy, not > 0.
3.3 Why ignore_zero matters
Several devices publish 0 for a value they have not measured yet — an idle BMS
reports SOC and SOH as 0. Without ignore_zero, an "< 3" SOC rule fires the
moment a battery goes idle. All 192 threshold entries in this tree carry it.
3.4 Generating maps
python3 tools/gen_alarm_maps.py # dry run, prints a report
python3 tools/gen_alarm_maps.py --write # apply
python3 tools/gen_alarm_maps.py --write --only pcs # limit to one type
python3 tools/gen_alarm_maps.py --write --refresh # re-roll owned rules
The run is add-only. A code the map already carries is left exactly as it is,
including the codes this generator wrote earlier, so a threshold changed in the
alarm editor (§5) is not reverted by the next generator run. --refresh is the
opt-out: it overwrites every code the generator owns with the rule it computes
now, which is what a deliberate message/rule roll-out wants. A threshold every
model should carry still goes in EXTRA_RULES; a threshold for one device or
model is just edited in that device's own map.
For every device folder it writes the default map plus one map per model variant
(pcs_alarm_code___epcs105.json, ups_alarm_code___ups_10k.json, …), derived
from that model's own register map, and:
- selects fields that describe a real fault, by suffix (
*_fault,*_alarm,*_too_high,*_too_low,*_overload,*_islanding, …) after excluding setpoints, thresholds, modes, counters and status words; - gives each one a rule —
truthyfor boolean flags,> 0for counters; - words its
messageas<condition>: <what it means>.(see §2), so generated alarms read like the hand-authored ones instead of restating the field name; - adds the hand-authored numeric thresholds from
EXTRA_RULESin the same file (PCS/battery SOC and SOH, UPS battery capacity/runtime/temperature, coolant inlet temperature and flow, room temperature and humidity, fire-panel faults and canister charge, …), all withignore_zero: true; - infers severity from the field name (
fire,epo,insulation,overcurrent,overload,islanding, … →critical;too_high,fault,communication,temperature, … →major; elsewarning); - names codes
<PREFIX>-<NNNN>(PCS-1072) or<PREFIX>-<NAME>for thresholds (PCS-SOC-LOW), so generated codes never collide with existingALM-*codes; - preserves existing entries verbatim, and the first time a file is rewritten
copies the original to
<name>.bak-precopilot; - adds the three
SELFTEST-*entries to every map.
A rule is dropped when its field is not present in that model's register map, which is how one rule table serves every model without producing phantom alarms.
Current content of the tree: 86 maps, 9 754 entries — 9 241 carrying a rule,
255 catalogue-only, 258 self-test (3 × 86); 192 entries carry ignore_zero.
4. The endpoints
All three are GET, all read-only, all on the settings API server
(ems_settings_api.py server, default port 8080).
| Path | Purpose |
|---|---|
/api/v1/ems/alarms |
active alarms from live readings |
/api/v1/ems/alarms/self-test |
the same pipeline against synthetic alarms |
/api/v1/ems/alarms/definitions |
the catalogue — every alarm each map defines, firing or not |
4.1 GET /api/v1/ems/alarms
No query parameters are read. ?device_type= has no effect on this path —
filtering exists only on the self-test path below. The module docstring at
ems_settings_api.py:133 claims otherwise; the code does not implement it, and
live /api/v1/ems/alarms and /api/v1/ems/alarms?device_type=pcs return
byte-identical payloads.
docker exec ems-backend curl -s http://127.0.0.1:8080/api/v1/ems/alarms
Response (top-level keys: timestamp, source, self_test, totals, alarms,
devices):
{
"timestamp": 1759279512000,
"source": "ems-backend",
"self_test": false,
"totals": {
"devices_checked": 18,
"devices_skipped": 5,
"devices_with_alarms": 1,
"active_alarms": 1
},
"alarms": [
{
"device_type": "pcs",
"component_type": "pcs",
"device_id": "pcs1",
"reading_key": "pcs1",
"model": "EPCS105",
"alarm_code": "PCS-SOC-LOW",
"alarm_display_name": "Battery SOC Critically Low",
"message": "Battery state of charge below 3%, discharge must stop (measured 2%).",
"severity": "critical",
"field": "soc_state_of_charge_item",
"register_address": 3005,
"value": 2,
"condition": "< 3.0",
"detected_at": "2026-10-01T01:23:22.261000+00:00",
"detected_at_ms": 1759279512000
}
],
"devices": [
{
"device_type": "pcs",
"component_type": "pcs",
"device_id": "pcs1",
"reading_key": "pcs1",
"model": "EPCS105",
"status": "active",
"has_reading": true,
"reading_timestamp_ms": 1759279512000,
"alarm_map": "pcs_alarm_code___epcs105.json",
"alarm_map_source": "model",
"active_alarm_count": 1
}
]
}
Field notes:
timestamp,detected_at_msandreading_timestamp_msare epoch milliseconds;detected_atis UTC ISO-8601 with microseconds, and is the timestamp of the reading that carried the alarm — not the moment the report was built.totals.devices_checkedcounts devices after filtering,devices_skippedcounts devices hidden by the settings gate,devices_with_alarmscounts devices with at least one row.- Every checked device appears in
deviceseven with zero alarms, so the response doubles as a coverage report. conditionis the normalised rule:"< 3.0"(floats, see §3.1),"truthy","falsy","bit 3","== FAULT".- A device whose alarm map is missing carries
"note": "no_alarm_map". statusis the settings group's value for that device key, so it isnullfor devices the group keys differently from the register map'sdevice_id— live examples:Cl1_P1,ups_unit,gridEnergyMeter1,solarEnergyMeter1. It is informational; only the group-level gate in §1.6 acts on statuses.
Real rows observed on the live system (one per device type, showing both map sources and the stem fallback):
| device_type | device_id | reading_key | model | source | alarm_map |
|---|---|---|---|---|---|
pcs |
pcs1 … pcs12 |
pcs1 … pcs12 |
EPCS105 |
model |
pcs_alarm_code___epcs105.json |
bmu |
Cl1_P1 |
null |
BMU100 |
model |
bmu_alarm_code___bmu100.json |
ups |
ups_unit |
ups |
UPS_10K |
model |
ups_alarm_code___ups_10k.json |
grid_energy_meter |
gridEnergyMeter1 |
gridMeter |
ME231 |
model |
gridMeter_alarm_code___me231.json |
solar_energy_meter |
solarEnergyMeter1 |
solarMeter |
ME231 |
model |
solarMeter_alarm_code___me231.json |
bess_energy_meter |
bessEnergyMeter1 |
bessEnergyMeter1 |
ME231 |
default |
bessMeter_alarm_code.json |
ffr_energy_meter |
ffrEnergyMeter1 |
ffrEnergyMeter1 |
ME231 |
default |
ffrMeter_alarm_code.json |
Note reading_key differing from device_id (gridEnergyMeter1 → gridMeter,
ups_unit → ups), and bmu with no reading at all yet still resolving its map.
4.2 GET /api/v1/ems/alarms/self-test
Every alarm map contains three synthetic alarms — SELFTEST-001 (critical),
SELFTEST-002 (major), SELFTEST-003 (warning) — each marked
"self_test": true. They are inert during normal operation (the live report never
returns them) and are returned only here, where the identical pipeline runs:
same discovery, model resolution, map selection, ordering and serialisation.
Query parameters (accepted here, and only here):
| parameter | effect |
|---|---|
?device_type=<type> |
keep only that device_type |
?device=<type> |
alias for the above |
Filtering happens after each device is evaluated, so totals.devices_checked
reflects the filter.
docker exec ems-backend curl -s http://127.0.0.1:8080/api/v1/ems/alarms/self-test
docker exec ems-backend curl -s 'http://127.0.0.1:8080/api/v1/ems/alarms/self-test?device_type=pcs'
docker exec ems-backend curl -s 'http://127.0.0.1:8080/api/v1/ems/alarms/self-test?device=ups'
A real row:
{
"device_type": "air_condition_unit",
"component_type": "airConditionor",
"device_id": "airConditionor1",
"reading_key": "acUnit",
"model": "AC_STD",
"alarm_code": "SELFTEST-001",
"alarm_display_name": "Self-Test Alarm (Critical)",
"severity": "critical",
"message": "Cooling fault active: temperature control lost.",
"field": "__self_test__",
"register_address": null,
"value": null,
"condition": "self-test",
"detected_at": "2026-10-01T01:23:22.261000+00:00",
"detected_at_ms": 1790817802261,
"self_test": true
}
Differences from the live payload:
"self_test": trueat the top level, plus anotestating the alarms are synthetic and reported only by this endpoint;"self_test": trueon every row;"value": null,"register_address": null,"condition": "self-test","field": "__self_test__";detected_atis the moment the report was built (there is no reading);- the settings gate is not applied, so
devices_skippedis always0and every configured device is covered — switching a device off cannot hide a broken alarm map; messagecomes from the per-device-type table in §2, not from the map, so the report reads like that device's real alarm list.
Because the alarms are synthetic, the result is deterministic and works while
every device is offline (reading_key: null in that case).
4.3 Authentication and status codes
_authorized() returns True when no token is configured; otherwise it requires
an exact Authorization: Bearer <token> match.
| condition | status |
|---|---|
| authorised | 200 |
| token configured, header missing or wrong | 401 {"error": "unauthorized"} |
| path outside the known set | 404 {"error": "not_found"} |
| engine raised | 500 {"error": "alarm_report_failed"\|"alarm_self_test_failed", "detail": "…"} |
On this deployment the endpoints are unauthenticated. The server is started
with an empty --bearer-token (the launcher passes the flag with an empty value
and EMS_SETTINGS_API_TOKEN is unset in the container), so _authorized() returns
True for every caller. Verified: a request with
Authorization: Bearer not-the-token returns 200.
The bearer_token in emsConfig/ems/ems_api_config.json →
ems_control_json.bearer_token is a client credential used by the pull/push
helpers, not by this server's authentication. It already includes the Bearer
prefix, and _request_json() detects that and sends it verbatim — do not prepend
a second Bearer.
The practical boundary is the Docker network: the HTTP API listens on container
port 8080 and is not published (only 1540/tcp, the Modbus server, is mapped
to the host). To require a token, start the server with one:
python3 -u ems_settings_api.py server --bearer-token "$EMS_SETTINGS_API_TOKEN"
4.4 Calling it from other places
From the host (the API is not published):
docker exec ems-backend curl -s http://127.0.0.1:8080/api/v1/ems/alarms
From another container on the same network, use the service name — 127.0.0.1
is refused (measured HTTP 000 from ems-frontend, HTTP 200 via the name):
docker exec ems-frontend curl -s http://ems-backend:8080/api/v1/ems/alarms
Both paths can be re-pointed for a test instance with --alarms-path and
--alarms-self-test-path.
4.5 Live values at the time of writing
| Request | devices_checked |
devices_skipped |
active_alarms |
|---|---|---|---|
/api/v1/ems/alarms |
18 | 5 | 0 |
/api/v1/ems/alarms/self-test |
23 | 0 | 69 |
/api/v1/ems/alarms/self-test?device_type=pcs |
12 | 0 | 36 |
/api/v1/ems/alarms/self-test?device=ups |
1 | 0 | 3 |
/api/v1/ems/alarms/definitions |
23 | — | 2 |
The definitions call also reports alarm_definitions: 2345; it has no
devices_skipped, because the settings gate does not apply to it (§4.6).
The 5 skipped types are exactly those whose devices are all inactive in
ems_control_setting.json: air_condition_unit (ac_units, 6 devices),
fire_safety_system (fss), frequency_meter (frequency_meters),
liquid_cooling_unit (cooling_unit), sensor_block (sensor_blocks). The live
report covers pcs (12), bmu, ups, grid_energy_meter, solar_energy_meter,
bess_energy_meter and ffr_energy_meter.
Those five types are absent from the live report by design, not by fault: an inactive device has a frozen reading, and reporting thresholds from it would invent alarms. They remain fully visible through the self-test endpoint.
4.6 GET /api/v1/ems/alarms/definitions
The catalogue. Where the two endpoints above answer what is wrong right now, this answers what can go wrong here: each device's selected alarm map expanded into one row per entry, firing or not, carrying the message text the map defines.
docker exec ems-backend curl -s http://127.0.0.1:8080/api/v1/ems/alarms/definitions
docker exec ems-backend curl -s \
'http://127.0.0.1:8080/api/v1/ems/alarms/definitions?device_type=pcs'
One row (alarms-api.md has the full shape and the device-row fields):
{
"alarm_code": "PCS-1004",
"alarm_display_name": "A Phase Overvoltage Fault Flag",
"message": "A-phase overvoltage fault: voltage has exceeded the safe operating limit.",
"severity": "critical",
"field": "a_phase_overvoltage_fault_flag",
"condition": "truthy",
"active": false
}
Differences from the live report worth knowing when reading it:
messageis the map's wording without the measured clause, because a row that is not firing has no reading to quote; it is the text a map editor edits.- The settings gate of §1.6 is not applied, so a switched-off device type is
still catalogued (the same coverage as the self-test report):
totals.devices_checkedis 23, there is nodevices_skipped, andactive_alarmscan therefore exceed the live report's. Each device row carriesstatus, so a caller can still see which types are off. SELFTEST-*entries are excluded, as in the live report.?device_type=/?device=filter as on the self-test path.- 2,345 rows, roughly 845 KB as served — fetch it once and filter client-side, or
narrow it with
?device_type=.
5. Worked example — adding a new alarm
Goal: alarm when the grid meter frequency is above 50.5 Hz.
-
Find the field. Confirm the name in the device's register map and that the client publishes it:
emsConfig/grid_energy_meter/gridMeter_register.jsoncontainsfrequency_hz, andlastValue/gridMeter_lastValue.jsoncontainsgridMeter_frequency_hz— the unique-suffix rule in §1.5 bridges the two. -
Add the entry to the map the device actually uses. Check the model first:
python3 -c "import json;print(json.load(open('emsConfig/selected_model.json'))['by_register_file'])"
Then append to emsConfig/grid_energy_meter/gridMeter_alarm_code___me231.json:
"GRID-UF": {
"alarm_display_name": "Grid Frequency Above Limit",
"message": "Grid frequency above 50.5 Hz.",
"severity": "major",
"field": "frequency_hz",
"condition": "> 50.5"
}
Name the unit in the wording (Hz): that is what makes the report read
“(measured 51.5 Hz)” rather than “(measured 51.5, above the limit of 50.5)”.
Add the entry to the default map too if every model should carry it, or put it
in EXTRA_RULES in tools/gen_alarm_maps.py so every model whose register map
has that field gets it (it drops rules whose field is absent from that model).
Changing a threshold that already has an entry needs neither: the generator is
add-only, so an edit to the map is the durable home for it.
- Verify the wiring without needing a fault:
docker exec ems-backend curl -s \
'http://127.0.0.1:8080/api/v1/ems/alarms/self-test?device_type=grid_energy_meter'
A device row with alarm_map: gridMeter_alarm_code___me231.json and
alarm_map_source: "model" proves discovery, model resolution and map
selection. A wrong filename shows up as note: "no_alarm_map".
- Verify the rule. Force the value in the lastValue file. It lives inside the backend's bind-mounted tree, so edit it from the host (the client overwrites it on its next poll):
python3 - <<'PY'
import json
p = ("/opt/gess-stack/ems/backend/app/EnergySyc_EMS_ES100Cx12S/"
"lastValue/gridMeter_lastValue.json")
d = json.load(open(p))
d["gridMeter_frequency_hz"] = 51.5
json.dump(d, open(p, "w"))
print("forced", p)
PY
docker exec ems-backend curl -s http://127.0.0.1:8080/api/v1/ems/alarms \
| python3 -c 'import json,sys;d=json.load(sys.stdin);print([a for a in d["alarms"] if a["alarm_code"]=="GRID-UF"])'
Expect one row with "value": 51.5, "condition": "> 50.5", a filled
register_address, and a message ending in “(measured 51.5 Hz)”.
-
Watch the
ignore_zerotrap. A forced0will not fire a threshold rule that carriesignore_zero— by design (§3.3). Test with a non-zero value. -
Restore the reading. The next poll overwrites it; do not leave a hand-edited value behind if the device is offline.
6. Quick reference
Files
emsConfig/<type>/<device>/<stem>_register*.json register map
emsConfig/<type>/<device>/<stem>_alarm_code.json default alarm map
emsConfig/<type>/<device>/<stem>_alarm_code___<model>.json model alarm map
emsConfig/selected_model.json model per register file
emsConfig/ems/ems_control_setting.json status + gate
lastValue/<stem>_lastValue.json live readings
Functions (ems_alarm_status.py)
| function | role |
|---|---|
build_alarm_report() |
whole report; self_test= and device_type= switches |
evaluate_device_alarms() |
one device → rows + summary |
_iter_devices() |
discovery |
_pick_map() |
model/default map lookup |
_model_slugs(), _model_for_device() |
model resolution |
_resolve_lastvalue_stem() |
which reading file |
_read_value() |
field → value and address |
_register_index() |
register map → field index |
_parse_condition(), _compare() |
rule grammar and semantics |
_describe_condition() |
the condition string in the response |
_alarm_message() |
self-test text, or map text + measured value |
_group_is_inactive() |
the settings gate |
Reading the report
active_alarms> 0 and a device missing fromdevices→ checkdevices_skippedand that device'sstatusinems_control_setting.json.- A device present with
reading_key: null→ the client is not writing its lastValue file; check the client log inlogs/, not the alarm map. - A device present with
note: "no_alarm_map"→ filename or model mismatch. - An alarm that never fires → check the
fieldexists in the reading, that the operator suits the value type (truthyfor words, not> 0), and thatignore_zerois not suppressing a0reading. register_address: nullon a firing alarm → the field is not in the register map; the rule still works, only the address is missing.
7. What the frontend uses
The frontend's alarm screens read a database table through
App\Services\EvAlarmService (getAlarms(), getLastAlarms(),
getCriticalAlarms() — pagination, filtering, severity, search), and rows are
created by EvAlarmService::createFromOcpp(). No PHP file in the frontend
references /api/v1/ems/alarms.
The two are separate views of related data:
/api/v1/ems/alarms |
frontend alarm list | |
|---|---|---|
| source | live lastValue files |
alarms DB table |
| history | none — what is true now | retained, paginated |
| write path | read-only | written by OCPP/EMS ingestion |
| callers | scripts, monitoring, SCADA-side checks | the UI |