How an alarm code gets its value — alarm map ↔ register map
Every active alarm the backend reports comes from two files per device. This
document shows exactly how one points at the other, using PCS-1002 from
emsConfig/pcs/pcs1/ as the worked example.
Companion to alarm-mapping-and-endpoints.md: that document covers the whole pipeline (device discovery, model selection, reading resolution, endpoints). This one zooms in on the single link between an alarm entry and the register it watches.
1. The pair
emsConfig/pcs/pcs1/
├── pcs_register_full___epcs105.json what to read, where, how to decode it
└── pcs_alarm_code___epcs105.json what it means, when it fires
- Same folder = same device (
device_typepcs,device_idpcs1). - Same
___epcs105suffix = same device model (see §1.3 of the companion). - Neither file mentions the other. The device pairing comes from the directory; the field pairing is made at evaluation time.
2. The join key is the field name
An alarm entry's field must equal a register key in the register map. Not an
address, not a register number, not the alarm code — the name string. The alarm
codes (PCS-1001, PCS-1002, …) are the alarm file's own identifiers and mean
nothing to the register file.
Alarm side — emsConfig/pcs/pcs1/pcs_alarm_code___epcs105.json:
"PCS-1002": {
"alarm_display_name": "1 Cell Voltage Too High",
"message": "1 cell voltage too high: the measured value is above the safe operating limit.",
"severity": "major",
"field": "1_cell_voltage_too_high",
"op": "truthy"
}
Register side — emsConfig/pcs/pcs1/pcs_register_full___epcs105.json:
"categories": {
"bc": {
"read_only": {
"1_cell_voltage_too_high": {
"address": 1000,
"data_type": "BOOL",
"registers": 1,
"value": false,
"rw_type": "read_only"
},
The string 1_cell_voltage_too_high appears on both sides. That single string is
the entire relationship: it is how the alarm tells the engine which register to
look at, and it is the only place the register's address (1000) can come from.
| Alarm map | Register map | |
|---|---|---|
| Names the register | field |
the key itself |
| Says what it means | alarm_display_name, message, severity |
— (only a technical name) |
| Says where it is | — | address, data_type, registers, rw_type |
| Says when it fires | op, condition, value, ignore_zero |
— |
| Holds the raw measurement | — | value (last written), and lastValue/pcs1_lastValue.json |
2.1 One register, several alarms (and vice versa)
The link is a name lookup, so it is not one-to-one. The same address is reachable through more than one field name, and one register may be watched by several alarm codes — listing the pcs1 map shows, for example:
| Address | Fields pointing at it | Alarm codes |
|---|---|---|
| 1090 | a_phase_overvoltage_fault_flag, phase_a_overvoltage_fault_flag |
PCS-1004, PCS-1150 |
| 1103 | grid_current_imbalance, grid_current_unbalance |
PCS-1037, PCS-1038 |
| 1138 | ac_main_relay_adhesion_fault, ac_main_relay_welding_fault |
PCS-1007, PCS-1008 |
| 1110 | operating_bus_overvoltage, running_busbar_overvoltage |
PCS-1145, PCS-1174 |
So two spellings of the same condition can both be present and both fire; the
alarm codes, alarm_display_name and wording are what distinguish them to the
operator. Adding an alias is therefore safe, but expect the same physical bit to
appear under each name.
3. Where the link is made, in code
Three places, all in the backend:
a. The register map is flattened into a name index. _register_index()
(ems_alarm_status.py) walks categories → section → name → definition and
builds {register_name: definition}. That is why the alarm file can use the bare
leaf name 1_cell_voltage_too_high even though the register file nests it three
levels deep. First occurrence wins if a name repeats.
b. The link is validated when a map is read or saved. validate_entries()
(ems_alarm_maps.py:206) checks every entry against that index:
- no
fieldat all → error:'field' is required(:254) fieldnot in the model's register map → warning:field 'x' is not in this model's register map, so the alarm can never fire(:257-261)
That warning is what the alarm editor page shows when you type a name the model
does not define, and what register_fields in the API exists to prevent.
c. The value is resolved at runtime. _read_value()
(ems_alarm_status.py) turns field into a live value, in this order:
- the exact key in the device reading (
lastValue/pcs1_lastValue.json) - the merged form
"<stem>__<field>"(e.g.pcs1__soc) - a unique suffix match —
_match_reading_key()acceptskey == field or key.endswith("_" + field), which is how the bare1_cell_voltage_too_highfinds the PCS client's prefixedpcs_1_cell_voltage_too_high. If more than one key matches, it resolves to nothing rather than guess. - failing all of the above, the register definition's own
value
The register_address reported with an alarm always comes from the register
definition — never from the reading.
4. PCS-1002, end to end
pcs client polls the addresses from the register map (read_batches, Modbus)
│
▼
lastValue/pcs1_lastValue.json 304 keys, 303 of them prefixed pcs_*
pcs_1_cell_voltage_too_high = 0
│ (the register map's own "value" is updated too)
▼
evaluate_device_alarms() ems_alarm_status.py:752
│
├─ field "1_cell_voltage_too_high"
├─ value 0 ← exact/suffix match in the reading
├─ ignore_zero not set
├─ rule op = truthy → active only when the value is non-zero
└─ address 1000 ← from the register definition
│
▼
row emitted only when true: message + severity come from the alarm map,
register_address from the register map
Right now pcs_1_cell_voltage_too_high is 0, so PCS-1002 does not fire. Set
that bit to 1 on the device and the row appears with the alarm file's message
(“1 cell voltage too high: the measured value is above the safe operating
limit.”), severity major, and register_address: 1000.
5. The other rule shapes in the same file
| Entry | Field | Rule | Note |
|---|---|---|---|
PCS-1002 |
1_cell_voltage_too_high (addr 1000, BOOL) |
op: truthy |
fires when the bit is non-zero |
PCS-SOC-LOW |
soc_state_of_charge_item (addr 3005, UINT16) |
condition: "< 3", ignore_zero: true |
live value is 50 → no alarm; 0 would mean “not measured yet”, so it is skipped |
PCS-SOH-LOW |
soh_state_of_health_item (addr 3006, UINT16) |
condition: "< 80", ignore_zero: true |
live value is 0 → would fire instantly without ignore_zero; this is exactly why the flag exists |
SELFTEST-001..003 |
__self_test__ |
— (self_test: true) |
synthetic, no register behind it, only surfaced by the self-test endpoint |
any entry with no field |
— | — | catalogue-only, never fires |
op accepts truthy, falsy, bit, ==, !=, <, <=, >, >=, and
condition is the shorthand string form ("< 3") for the numeric ones.
The last row of that table is a classification rather than a live case: the
shipped maps contain no field-less entry any more. 255 of them were retired —
15 per file across 17 maps (the twelve pcs defaults plus the gridMeter,
solarMeter, frequencyMeter, bessMeter and ffrMeter maps). They were spec
imports whose threshold survived only as text inside the message, and because
validate_entries requires field, any map holding them could not be saved
through the editor at all. Retired in commit 84b42b7af; nothing was added and
no entry with a real register binding was touched.
6. How a trigger is identified
An alarm is triggered when one entry's rule evaluates true against the current
reading. Per entry, three gates in this order (evaluate_device_alarms(),
ems_alarm_status.py:848-876):
- Is there a value?
_read_value()must return something. No reading → the entry is skipped, so "unknown" is reported as nothing at all, never as healthy. ignore_zero? If set and the value is0, the entry is skipped —0means "not measured yet" for several devices.- Does the rule hold?
_compare(value, op, operand).
_compare() semantics:
| Rule | True when | Notes |
|---|---|---|
truthy |
the reading is active | _to_active(): booleans pass through, numbers and numeric strings are a non-zero test, anything unrecognised is not active |
falsy |
the reading is inactive | the inverse |
bit |
int(value) & (1 << bit) is non-zero |
operand from value or bit |
==, != |
equal / not equal | string comparison when the operand is a string ("== Fault"), numeric otherwise |
<, <=, >, >= |
numeric comparison | non-numeric value or operand → false, the entry can never fire |
The rule comes from whichever of these is present, first match winning:
op(aliasoperator;=,eq→==,ne→!=,lt→<,le→<=,gt→>,ge→>=)- else
condition, a string parsed by_CONDITION_RE(^\s*(==|!=|<=|>=|<|>|=)\s*(.+?)\s*$), also accepting the wordstruthy active alarm faultandfalsy inactive normal ok - else
bit - else a default of
truthy— an entry with only afieldfires whenever that reading is non-zero
A firing row carries alarm_code, alarm_display_name, severity and message
from the alarm map, and field, value, condition, register_address and
detected_at from the reading and the register map — which is why an operator can
see both the wording and the exact number that tripped it.
Where to see the triggers:
GET /api/v1/ems/alarms— everything firing right now, optionally narrowed with?device_type=pcs&device_id=pcs1. An empty list means nothing is firing; it does not mean the rules are missing.lastValue/pcs1_lastValue.json— the raw inputs to that decision.GET /api/v1/ems/alarms/self-test— synthetic alarms that exercise the message/severity pipeline without touching any register.
The engine is stateless: maps and readings are re-read on every request, so a rule change takes effect on the next request with no restart.
7. How a threshold is decided — is 3005 "ok" or "high"?
The register file never answers that. All it holds is what the number is —
address, data_type, registers, scale, rw_type and the last value. There
is no min, max, warning or trip field anywhere in it. soc_state_of_charge_item at
3005 is UINT16 with scale: 1: the file says "this is a 16-bit unsigned number",
and nothing about whether 50 is acceptable.
The verdict lives on the alarm side, in the operand:
| Register map (addr 3005) | Alarm map (PCS-SOC-LOW) |
|
|---|---|---|
| Contents | UINT16, scale: 1, value: 50 |
"condition": "< 3", "ignore_zero": true |
| Answers | what the number is | 3 is the line: 50 is fine, 2 fires |
| Changeable by | the device / register map | this document's subject — the alarm file |
Two families, and they behave differently:
- Device-decided (
BOOL+truthy).1_cell_voltage_too_highat 1000 is a fault bit the PCS sets itself. The threshold lives inside the device; the alarm file only relays it and supplies wording. You cannot tune it here. - Config-decided (numeric + comparison). SOC and SOH are measurements with no
intrinsic limit, so we choose the number.
< 3for SOC and< 80for SOH are our thresholds — editable, and worth repeating insidemessageso the operator knows where the line was drawn.
Units and scale. The engine compares the value exactly as the client wrote it
and applies no scaling. Clients scale only integer types (apply_scale() in the
pcs client, over SCALED_DATA_TYPES: INT16/INT32/UINT16/UINT32 and the trailing-U
variants; BOOL and FLOAT32 pass through), and skip scale == 1. In the pcs1
map there are currently no registers with a scale other than 1, so every
threshold is already in engineering units — SOC is 0-100, not 0-10000. If you ever
add a register with scale: 0.1, write the threshold in the scaled unit; the
engine will not convert it.
How to choose the number. Take it from the device or BMS specification, then
check it against what the register actually reports (the lastValue file, or the
maps API) before trusting it. A threshold the register can never reach is silently
invisible.
Practical caveats:
ignore_zero: truemeans "0 = not measured". SOH reads0here, so without the flag"< 80"would fire the moment the pack is idle.- A missing reading is not OK — the entry is skipped, so a dead sensor looks quiet. Device-level status (the settings gate, companion §1.6) is what removes offline devices from the report.
data_typebounds the operand: aUINT16can never be negative, so"< 0"is a reliable way to silence an entry, whereas on aBOOLany"< 3"rule is always true.- Mind raw versus scaled direction:
>/<on a register reported in hundredths behaves nothing like the same numbers on a whole-unit register.
| Entry | Register | Live value | Rule | Result now | Fires at |
|---|---|---|---|---|---|
PCS-1002 |
1000, BOOL |
0 |
op: truthy |
not fired | bit 1, set by the device |
PCS-SOC-LOW |
3005, UINT16 |
50 |
condition: "< 3", ignore_zero |
not fired | 1 or 2 |
PCS-SOH-LOW |
3006, UINT16 |
0 |
condition: "< 80", ignore_zero |
skipped (zero) | 1-79 |
8. How to edit an alarm
Two routes, one file:
- UI —
/alarm-definition-editor(Admin / Super Admin only), which posts to the API. - API —
GET/PUT /api/v1/ems/alarms/maps?device_type=pcs&device_id=pcs1; the SCADA app'sEmsAlarmDefinitionsServicereads withGETand writes withPUT.
A save runs this pipeline in write_alarm_map() (ems_alarm_maps.py:378):
- Validate — invalid entries are refused (
400 alarm_map_rejected) with the first 12 problems listed. A missingfieldis an error; an unknownfieldis only a warning. - Optimistic lock — the request carries
expected_hashfrom the read. If the file changed in the meantime the save is refused (409), so you re-read and re-apply instead of silently overwriting someone else's edit. - Back up — the current file is copied to
<map>.bak-<YYYYmmdd_HHMMSS>before anything is written. - Write atomically, prune old backups, then read the file back and verify it matches (a mismatch aborts and names the backup to restore).
- No-op detection — an edit identical to what is on disk returns
changed: falseand writes nothing.
The response reports changed, backup (file name, when one was made), warnings
and the stored entries. Read the warnings: an entry pointing at a register the
model does not define saves successfully but warns "not in this model's register
map, so the alarm can never fire" — it looks accepted and can never trigger.
Edits take effect immediately; the engine re-reads the map per request, so nothing is restarted and no cache is cleared.
What an edit can and cannot do:
- Can — rename
alarm_display_name, rewritemessage, changeseverity, change the comparison and operand, addignore_zero, and repointfieldat another register of the same model. - Cannot — change an address or a reading. Those live in the register map and
in the device. Editing
PCS-SOC-LOWnever changes the value at 3005; it changes what the system says about it. - No enable/disable flag exists. To silence an entry, remove it or give it a
condition that cannot be met (
"< 0"on aUINT16).self_testentries cannot be edited and are preserved across saves.
Undo is the backup file beside the map (re-saving the previous entries restores
it). Hand-editing the JSON also works and the engine will pick it up, but that path
skips validation, the hash check and the backup.
Access: the UI needs Admin or Super Admin; the API itself is unauthenticated on the network, so keep its port off untrusted networks.
9. Pitfalls
An ambiguous name silently loses the live value. PCS-1004's field
a_phase_overvoltage_fault_flag matches two keys in the pcs1 reading —
pcs_a_phase_overvoltage_fault_flag and
pcs_inverter_voltage_a_phase_overvoltage_fault_flag. The suffix rule refuses to
choose, so the engine falls back to the register map's cached value. The alarm
still works, but it is not driven by the live reading. If you want the live value,
the field has to name a register whose suffix match is unique.
Renaming a register orphans alarms. Change a key in
pcs_register_full___epcs105.json and every alarm whose field named it becomes
unfireable — reported as the “can never fire” warning, not an error, so an
existing map keeps loading. Re-check after editing either file.
Names must be unique per model. _register_index() keeps the first definition
it meets for a repeated name, so two registers sharing a name cannot be
distinguished by an alarm entry.
The model suffix couples the files. ___epcs105 on both names is what makes
them the pair for model EPCS105 (selected_model.json maps
pcs_register_full.json → EPCS105). A new PCS model needs its own register and
alarm files, and the alarm entries must reference that model's register names.
An empty field is an error, an unknown field is only a warning. Saving an
entry without field is rejected; an unknown field saves but never fires.
10. Checking the relationship live
- API:
GET /api/v1/ems/alarms/maps?device_type=pcs&device_id=pcs1returns the entries andregister_fields— the flattened allow-list an entry may point at. - UI: the alarm definition editor (
/alarm-definition-editor) shows the same list next to each row and flags entries whose field the model does not define. - Shell, from the repo root:
python3 - <<'EOF'
import json
reg = json.load(open('emsConfig/pcs/pcs1/pcs_register_full___epcs105.json'))
alarm = json.load(open('emsConfig/pcs/pcs1/pcs_alarm_code___epcs105.json'))
index = {}
for cat in reg.get('categories', {}).values():
for group in cat.values():
for name, definition in group.items():
index.setdefault(name, definition)
for code, entry in alarm.items():
field = entry.get('field')
if not field:
print(f'{code:14} catalogue only')
continue
d = index.get(field)
print(f'{code:14} {field:52} {"addr " + str(d["address"]) if d else "NOT IN REGISTER MAP"}')
EOF
11. Which file the editor writes (one file per device)
The editor works on one device at a time, so a save touches exactly one file:
emsConfig/<device_type>/<device_id>/<prefix>_alarm_code___<model-slug>.json
For pcs1 that is emsConfig/pcs/pcs1/pcs_alarm_code___epcs105.json. The choice is
made by _pick_map(folder, "_alarm_code", model) (ems_alarm_status.py:84,775),
which resolves in this order:
- Model-specific — a
*_alarm_code*.jsonwhose name ends with___<model slug>(MODEL_SEPARATOR = "___", lowercased). Wins whenever it exists. - Default — otherwise the first
*_alarm_code*.jsonwith no___variant suffix. - Nothing →
MapNotFound(the 404 for an unknown device).
The model comes from selected_model.json (by_register_file → model). Verified
against the running backend:
| Device queried | map_path returned |
model |
|---|---|---|
device_type=pcs&device_id=pcs1 |
pcs/pcs1/pcs_alarm_code___epcs105.json |
EPCS105 |
device_type=air_condition_unit&device_id=airConditionor1 |
air_condition_unit/ac_alarm_code___ac_std.json |
AC_STD |
sha256sum of that file on disk equals the hash the API reports for the device,
so the mapping is exact. device_id is the folder name or the register map's
device_id — the UPS device is ups (not ups1, which returns 404).
| Device type | Model | File written | Sibling variants left untouched |
|---|---|---|---|
pcs/pcs1…pcs12 |
EPCS105 |
pcs_alarm_code___epcs105.json |
pcs_alarm_code.json, …___sinexcel_pws1_250k.json, …___sungrow_sc250ud.json |
air_condition_unit/* |
AC_STD |
ac_alarm_code___ac_std.json |
ac_alarm_code.json, …___ac_max.json, …___ac_pro.json |
ups/* |
UPS_10K |
ups_alarm_code___ups_10k.json |
ups_alarm_code.json, …___ups_20k.json, …___ups_30k.json |
grid_energy_meter/*, solar_energy_meter/*, frequency_meter/* |
ME231 |
…Meter_alarm_code___me231.json |
the ___p8000 and ___pm5560 variants |
liquid_cooling_unit/* |
COOL_STD |
cooling_alarm_code___cool_std.json |
…___cool_max.json, …___cool_pro.json |
fire_safety_system/* |
FSS_STD |
fss_alarm_code___fss_std.json |
…___fss_max.json, …___fss_pro.json |
sensor_block/* |
SENS_STD |
sensorB_alarm_code___sens_std.json |
…___sens_max.json, …___sens_pro.json |
bmu/bmu1…bmu10 |
BMU100 |
bmu_alarm_code___bmu100.json |
bmu_alarm_code.json, …___bmu200.json, …___bmu300.json |
bess_energy_meter, ffr_energy_meter |
— | bessMeter_alarm_code.json, ffrMeter_alarm_code.json |
only one file exists in each folder, so the default is used |
The sibling variants are inert. In pcs/pcs1/ the live map has 190 entries while
pcs_alarm_code.json has 205; for codes present in both the content is identical,
and the extra 15 exist only in the unused file (ALM-1001, ALM-1002, and numeric
ids such as 1065353216, which look like leftovers from an older import). Because
EPCS105 resolves first, those 15 never load and can never fire for pcs1 — and
editing that file there changes nothing. The map_path in the API response is the
authoritative answer for "which file is live".
On saving, the current file is first copied to <same name>.bak-<YYYYmmdd_HHMMSS>
(pruned over time; the .bak-msgstyle and .bak-precopilot files seen in the
folder came from separate one-off scripts, not from the editor). Files the editor
never writes: *register*.json, selected_model.json,
ems_control_setting.json, lastValue/*.json.
12. There is no separate trigger file
The rule and the wording are ordinary fields of the alarm entry. Nothing else stores them:
"PCS-SOC-LOW": {
"alarm_display_name": "Battery SOC Critically Low",
"message": "Battery state of charge below 3%, discharge must stop.", // wording
"severity": "critical", // wording
"field": "soc_state_of_charge_item", // which register
"condition": "< 3", // the trigger logic
"ignore_zero": true
}
| Role | Fields | Comes from |
|---|---|---|
| Which register | field |
alarm entry (must name a register in the device's register map) |
| Trigger logic | op / condition / value / bit / ignore_zero |
alarm entry |
| Operator wording | alarm_display_name, message, severity |
alarm entry |
| Address and measurement | address, data_type, registers, scale, value |
register map, and the device reading |
The verdict is computed, never stored: on each request _parse_condition() →
_read_value() → _compare() in ems_alarm_status.py decides from the rule plus
the live reading. Run against pcs1 as this was written:
| Code | Register field | Rule | Live value | Verdict |
|---|---|---|---|---|
PCS-1002 |
1_cell_voltage_too_high |
truthy |
0 |
not active |
PCS-1001 |
15v_power_supply_fault_flag |
truthy |
0 |
not active |
PCS-1010 |
air_conditioner_alarm |
truthy |
0.0 |
not active |
PCS-SOC-LOW |
soc_state_of_charge_item |
< 3.0 |
91 |
not active |
PCS-SOH-LOW |
soh_state_of_health_item |
< 80.0 |
95 |
not active |
Those numbers move with the device — the same entries read 50 and 0 earlier in
the day, 91 and 95 here — which is why nothing on disk ever holds "alarm is
active". What the editor saves is precisely these entry fields:
validate_entries() stores alarm_display_name, message, severity, field,
op/condition and ignore_zero (ems_alarm_maps.py:246-249) into the map file
from §11. See §8 for the save pipeline itself.
So when a rule change appears to do nothing, the cause is almost always the wrong
variant of the file: check map_path from the API, or open the device again in the
editor, before concluding the rule was ignored.
13. Code map
| Concern | Where |
|---|---|
| Register name index | ems_alarm_status.py — _register_index() |
| Which alarm map is live (model resolution) | ems_alarm_status.py — _pick_map(), MODEL_SEPARATOR, selected_model.json |
| Field → value resolution | ems_alarm_status.py — _read_value(), _match_reading_key() |
Rule parsing (op, condition, aliases) |
ems_alarm_status.py — _parse_condition() |
Comparison (truthy/falsy/bit/numeric) |
ems_alarm_status.py — _compare(), _to_active() |
Trigger detection, ignore_zero |
ems_alarm_status.py — evaluate_device_alarms() (:752, firing logic :848-876) |
| Client-side scaling of readings | pcs_client_save_data_*.py — apply_scale(), SCALED_DATA_TYPES |
| Map validation (errors vs warnings) | ems_alarm_maps.py — validate_entries() (:206) |
Map read / register_fields |
ems_alarm_maps.py — resolve_device(), read_alarm_map() |
| Map save (validate, lock, back up, atomic write) | ems_alarm_maps.py — write_alarm_map() (:378), _backup_map(), _prune_backups() |
| Endpoint payloads and status codes | ems_settings_api.py (server sub-command; GET/PUT /api/v1/ems/alarms/maps) |
| Admin-only editor UI | SCADA app — /alarm-definition-editor, AlarmDefinitionsController, EmsAlarmDefinitionsService |
Related: alarm-mapping-and-endpoints.md (§1.2 register index, §1.5 reading resolution), alarms-api.md.