How to Execute Command Sequences from Alarms or Python
Run a device command sequence three ways: as an alarm action, from Python, or over the REST API. Each has a different safety posture, and the difference is enforced in code rather than by convention.
Purpose
Configure or trigger execution of a sequence that already exists. For creating sequences, see How to Add a Device Command Sequence; for validating them, How to Test Device Command Sequences.
Prerequisites
| Method | Requires |
|---|---|
| Alarm action | An alarm whose target's model defines the sequence |
| Python | pyModbusTCP, and reachability of the device, the simulator, or a protocol adapter |
| REST | A running EMS backend and its API token |
| Physical execution | authorize_physical, plus the safeguards in the last section |
Relevant Files
| Path | Role |
|---|---|
device_command_sequences.py |
The engine: run_action, run_task, describe |
pcs_power_sequence.py |
The underlying execute_sequence |
alarm_actions.py |
The alarm-triggered executor and its gate_reason |
command_sequence_test.py |
start_test, stop_test, run_test |
ems_settings_api.py |
The REST surface |
protocol_adapters.py |
Modbus / OCPP adapters |
resources/views/alarmActionsEditor.blade.php |
Configuring the alarm-triggered route |
Method A — Alarm-Triggered Execution
The sequence is attached to an alarm; the engine runs it when the alarm fires. Configure it in the alarm action editor (see How to Add an Alarm Action).
- Open the alarm whose action you want, in
/alarm-actions-editor?device_type=…&device_id=…. - Select the target device. It need not be the alarmed device.
- The editor detects the target's model and lists
available_actionsfor it — the sequences you may choose from are exactly those the model defines. - Assign the sequence.
- Enter
parameters— the values for the sequence's${…}placeholders. - Set the
condition,mode,order,delay_ms,timeout_msandfailure_action. - Choose the trigger:
activeto act when the alarm fires,clearedto act when it clears. Aclearedaction additionally requiresallow_on_clear: true. - Save. The engine validates the whole action and refuses a map it could not execute.
- Raise the alarm — with the simulator, or by driving the watched register.
- Monitor execution and confirm the outcome.
What happens on a clearance
A cleared action passes through gate_reason first, and runs only when all three conditions
hold. The refusals are:
allow_on_clear is not set on the action
still active on this device: ALARM-1, ALARM-2
operation mode 'x' does not permit a clearance action
Any one of them leaves the equipment as it is — the deliberate, recoverable outcome.
Method B — Executing from Python
The execution call
run_action(
client,
*,
device_type: str,
action: str,
model: str | None = None,
device_key: str | None = None,
parameters: dict | None = None,
config_path: str | None = None,
control_path: str | None = None,
protocol: str | None = None,
debug: bool = False,
event_logger=None,
allow_during_backup: bool = False,
) -> list[dict]
Returns the per-step results as a list of dicts.
actionis the sequence name — anactionskey in the model's sequence file.modeldefaults to the model configured for the device inems_control_setting.json, so callers normally pass onlydevice_typeandaction.device_keyselects a specific device, which matters for the layer resolution: with a device key the device's own sequence copy is consulted first.allow_during_backupapplies only to PCS grid-mode actions; any other device type raisesallow_during_backup only applies to the PCS grid-mode actions.
run_task(client, device_type=…, task=…, **kwargs) is a thin alias — "a task is simply an
action made of several ordered steps. Kept separate so call sites read as intent."
Discovering what you may run
from device_command_sequences import describe
import json
print(json.dumps(describe("<device_type>"), indent=2))
describe returns, per device type: label, models (each with its file and actions),
protocol, configured_model and configured_devices. It is deliberately fault-tolerant —
"An inventory call must not fail because one device's protocol is unusable" — and reports
protocol_error instead.
Example 1 — Start a BESS
from pyModbusTCP.client import ModbusClient
from device_command_sequences import run_action
client = ModbusClient(host="127.0.0.1", port=502, unit_id=1, timeout=5.0, auto_open=True)
if not client.open():
raise SystemExit("cannot open Modbus connection")
results = run_action(
client,
device_type="pcs", # the engine key, not the config directory name
device_key="PCS1",
action="start", # writes 0x0291 = 1, then waits 10 s
)
for step in results:
print(step)
Example 2 — Set PCS active power to 50 kW
results = run_action(
client,
device_type="pcs",
device_key="PCS1",
action="change_power",
parameters={"power_kw": 50}, # fills ${power_kw} in the step's value
)
model is omitted on purpose: it resolves from the device's own configuration, and passing a
wrong model is the fastest way to address another model's registers. On EPCS105 the step is
write_single 0x0D57, encoding: signed_i16, scale: 10 — pass whole kW and let the step's
own scale do the conversion.
Example 3 — Resolve the model explicitly, then cap an EV charger at 11 kW
from device_command_sequences import model_for, available_actions, run_action
model = model_for("ev_charger", "EV-1")
print("model:", model) # EVC1
print("sequences:", available_actions("ev_charger", model))
results = run_action(
client,
device_type="ev_charger",
device_key="EV-1",
model=model,
action="set_power_limit", # register 4122, reads ${power_kw}
parameters={"power_kw": 11},
)
available_actions() is the authoritative list for a model — the names it returns are the only
ones run_action will accept.
run_action itself validates the model early with a device-worded message plus the model
catalogue, "rather than letting the engine report 'No power sequence file matches PCS
model'". It also proves that the copy the device actually runs can serve the model, so a
stale copy fails before the sequence starts rather than midway through it.
Example 4 — Multi-device alarm response
The alarm-action path is the supported way to run several sequences off one trigger. From Python, the equivalent is to run them explicitly, and to treat the first failure as fatal when the sequence is safety-relevant:
plan = [
("pcs", "PCS1", "change_power", {"power_kw": 0}),
("ev_charger", "EV-1", "set_current_limit", {"current_a": 16}),
("ev_charger", "EV-2", "set_current_limit", {"current_a": 16}),
]
for device_type, device_key, action, params in plan:
try:
results = run_action(client, device_type=device_type,
device_key=device_key, action=action,
parameters=params)
except DeviceSequenceError as exc:
print(f"{device_type}/{device_key} {action} failed: {exc}")
break # abort: do not continue shedding after a failure
print(f"{device_type}/{device_key} {action}: {len(results)} steps")
Example 5 — A read-only sequence, safe to run anywhere
Prefer a sequence made only of read_holding steps when you want to prove the wiring without
moving anything. read_status is exactly that on the live system.
results = run_action(client, device_type="<category>",
device_key="<key>", action="read_status")
Method C — Execution over the REST API
Base path: /api/v1/ems/command-sequences.
| Method | Path | Purpose |
|---|---|---|
| GET | /command-sequences |
List devices and read their sequences |
| GET | /command-sequences/backups |
List backups |
| PUT | /command-sequences/sequences |
Save sequences |
| POST | /command-sequences/validate |
Validate without writing |
| POST | /command-sequences/restore |
Restore a backup |
| POST | /command-sequences/test |
Run a test |
| POST | /command-sequences/test/stop |
Stop a running test |
The safety property
This is the most important thing in this guide, quoted from the handler:
HTTP callers are always simulator-only:
authorize_physicalis deliberately not read from the body, so a request can never write to live equipment. Physical runs stay a deliberate Python-side act.
So over REST, execution is simulator-only, and that is not configurable through the API. A request cannot opt itself into writing to live equipment. Physical execution is only possible from Python, deliberately.
Running a test over REST
curl -s -X POST "http://<ems-host>/api/v1/ems/command-sequences/test" \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{
"device_type": "ev_charger",
"device_key": "EV-1",
"action": "set_current_limit",
"parameters": { "current_a": 16 }
}'
Both device_type and action are required — a request missing either gets
device_type and action are required. This endpoint is the asynchronous one: it calls
start_test and returns the background job record, whose test_id polls
GET /api/v1/ems/command-sequences/test?id=<test_id> and stops the run via
POST /api/v1/ems/command-sequences/test/stop. Note the asymmetry: the job record's key is
test_id, but the stop body's key is id.
Stopping a running test
curl -s -X POST "http://<ems-host>/api/v1/ems/command-sequences/test/stop" \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{"id": "<the id from the start response>"}'
Validating without writing
curl -s -X POST "http://<ems-host>/api/v1/ems/command-sequences/validate" \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{"device_type": "ev_charger", "model": "AC_PRO", "data": {...}}'
stop_test(id) # command_sequence_test
start_test(device_type, action, model=..., device_key=..., parameters=...)
Monitoring and Results
Both paths return per-step outcomes. The test harness maps engine statuses to operator words:
_STEP_RESULT = {"ok": "PASS", "command": "PASS", "skipped": "SKIPPED",
"failed": "FAIL", "timeout": "ERROR", "error": "ERROR"}
The overall report is PASS or FAIL, with FAIL when any row is FAIL or ERROR, and the
report is stamped with elapsed time.
Error Handling
| Exception | Raised when |
|---|---|
DeviceSequenceError |
Device-level failure: unknown device, unresolvable model, sequence path missing |
PowerSequenceError |
The underlying engine failed |
ProtocolError |
The protocol adapter is unusable |
SequenceTestError |
Test-level failure |
TestNotFound |
No such test |
TestConflict |
A conflicting test is already running |
SequenceStopped |
The test was cancelled |
run_action wraps the engine's error, so a caller sees a device-worded message naming the
device label, the model and the action:
<label> [<model>] action '<action>' failed: <detail>
Timeouts and cancellation
- Timeouts come from the Modbus client (
--timeout, default 5.0 s) and from a step's own handling. A timed-out step reportsERROR, notFAIL. - Cancellation is supported on the test path:
stop_test(id)over REST, or a stop flag in Python. There is no cancellation parameter onrun_actionitself — a directrun_actioncall runs to completion or raises. If you need to abort a long physical sequence, drive it through the test path, which is built for that.
Live Device Execution
Physical execution is possible only from Python, and only by opting in explicitly:
- Authorization. The
authorize_physicalflag gates it and is never read from an HTTP body, so a remote caller cannot reach live equipment. - Operation mode. The EMS's operation mode gates clearance actions through
gate_reason'sallowed_modes. - Communication.
client.open()must succeed, andadapter_clientmust resolve a protocol; otherwise you getcannot open Modbus connection to host:port. - Model validation.
run_actionproves the device's own layer can serve the model before the first step, so a stale copy fails up front. - Register validation. None. An address in a sequence is not cross-checked against the register map — a wrong address is accepted and written. This is the sharpest edge in the whole system, and it is an implementation gap.
- Protection status. For clearance actions,
gate_reasonrefuses while anything else is still active on the device. - Confirmation.
verify: trueon a step gives read-back confirmation of the write. - Failure handling.
failure_actiondecides whether a failure aborts, skips, retries, or runs a recovery sequence.
Simulator first, always. Not because it is polite, but because the REST path enforces it and the physical path has no register validation to catch a wrong address.
Troubleshooting
| Symptom | Cause |
|---|---|
device_type and action are required |
Missing field in the REST body |
401 unauthorized |
Missing or bad API token |
cannot open Modbus connection to host:port |
Device or simulator unreachable |
<label> [<model>] action '<x>' failed: … |
The engine failed at a step — read the inner detail |
No power sequence file matches … model |
The model is not defined for that device type |
allow_during_backup only applies to the PCS grid-mode actions |
The flag was used on a non-PCS device |
A cleared action does nothing |
allow_on_clear absent, another alarm still active, or the mode forbids it |
| A REST request never writes to real equipment | By design; the API is simulator-only |
Cancelling a direct run_action has no effect |
No cancellation on that path; use the test path |