Tutorial 5: Custom Triggers¶
In this tutorial you build two nodes that talk through a trigger type of your own: a watchdog that fires a task_interrupt output while its on_execute is still running, and a worker that reacts to it in a dedicated handler instead of on_execute. You then run both end-to-end over a real MQTT broker with nothing else installed, and learn what the Mock Runner can and cannot check about them.
Prerequisites: the Triggers concept page for the rules, and the schema file reference for the port-key convention. Both example nodes live in examples/custom_triggers/ of the SDK repository.
What you will build¶
flowchart LR
W[WatchdogNode] -- "task_interrupt (TaskInterrupt)" --> K[WorkerNode.special_start]
W -- "start (Start)" --> N[next node]
| Node | Declares | Code side |
|---|---|---|
WatchdogNode |
custom output task_interrupt, rosType TaskInterrupt |
self.fire_trigger("task_interrupt") inside on_execute |
WorkerNode |
custom input special_start, rosType SpecialStart |
@trigger_handler("SpecialStart") on a method |
Both nodes keep the standard set of trigger ports (start and stop inputs, start and error outputs). Custom triggers are additive: after the watchdog's on_execute returns, its start output still fires as usual.
Why a custom trigger instead of a data port¶
- Timing. The built-in
startoutput fires only afteron_executereturns. A custom output fires the moment you callfire_trigger, so downstream nodes wake mid-execution. - Decoupling. The watchdog does not know who listens. A graph author draws the edge
WatchdogNode.task_interrupttoWorkerNode.special_starton the canvas, exactly like any trigger edge, and can connect several listeners. - A separate code path. A handler bound with
@trigger_handlerruns instead ofon_executefor its port. The worker'sstartinput keeps drivingon_execute;special_startdrives the handler. - Concurrency. Handlers run on the transport callback thread, concurrently with an in-flight
on_execute. An interrupt must not queue behind the very execution it interrupts. The price is that the handler has to be fast and non-blocking, the same rule as foron_stop_execution.
Two strings, two meanings¶
Every trigger port has a key (the map key in the schema) and a type (its rosType). The two SDK calls take different ones:
| Call | Takes | In this tutorial |
|---|---|---|
self.fire_trigger(...) |
the port key | fire_trigger("task_interrupt") |
@trigger_handler(...) |
the trigger type | @trigger_handler("SpecialStart") |
Mixing them up is the most common mistake; see Common errors.
Step 1: The watchdog fires a custom output¶
Declare the extra output in watchdog_node_schema.json, next to watchdog_node.py. The only difference from a plain node is the third entry in outputs:
{
"id": "Examples",
"name": "WatchdogNode",
"type": 1,
"description": "Monitors for anomalies and fires a custom TaskInterrupt trigger mid-execution",
"tags": ["example", "custom-triggers"],
"inputs": {
"start": { "rosType": "Start", "edgeType": 2 },
"stop": { "rosType": "Stop", "edgeType": 2 }
},
"outputs": {
"start": { "rosType": "Start", "edgeType": 2 },
"error": { "rosType": "Error", "edgeType": 2 },
"task_interrupt": { "rosType": "TaskInterrupt", "edgeType": 2 }
},
"errorOutputs": {},
"dataFlowEntry": {},
"triggerFlowEntry": {},
"executionContext": {
"type": "EXECUTION_TARGET_TYPE_GRPC",
"target": "",
"className": "WatchdogNode"
},
"configuration": {
"anomalies_to_report": "2"
}
}
In the node code, fire the port by its key from inside on_execute. The full module is examples/custom_triggers/watchdog_node.py; this is the part that matters:
# Fire the custom output port by its schema port KEY (not the
# rosType). Every node wired to WatchdogNode.task_interrupt
# wakes up NOW, while this on_execute is still running.
self.fire_trigger("task_interrupt")
What happens on that call:
- The SDK looks the key up in the outputs it was configured with. An unknown key raises
TriggerFlowException, and the message lists the declared trigger output keys. - If you pass no context, the SDK builds
TriggerContext(source_node="WatchdogNode")for you. To forward provenance, pass the context you received inon_executeinstead. - One small message is published on the node's transport. Every node wired to
task_interruptwakes now; the watchdog keeps running.
Calling fire_trigger before the node has been initialised (no transport yet) also raises TriggerFlowException. If the transport is connected but the publish fails, the SDK logs a warning and nobody downstream wakes, so watch the log when a listener stays silent.
The rest of the watchdog is ordinary: on_configure(config, dynamic_config) reads anomalies_to_report with get_config_value (the typed UI value wins over the schema default of "2"), and on_get_configuration exposes that key as a string entry so the editor renders a field for it.
Step 2: The worker handles a custom input¶
Declare the extra input in worker_node_schema.json:
{
"id": "Examples",
"name": "WorkerNode",
"type": 1,
"description": "Handles a custom SpecialStart trigger with dedicated handler code",
"tags": ["example", "custom-triggers"],
"inputs": {
"start": { "rosType": "Start", "edgeType": 2 },
"stop": { "rosType": "Stop", "edgeType": 2 },
"special_start": { "rosType": "SpecialStart", "edgeType": 2 }
},
"outputs": {
"start": { "rosType": "Start", "edgeType": 2 },
"error": { "rosType": "Error", "edgeType": 2 }
},
"errorOutputs": {},
"dataFlowEntry": {},
"triggerFlowEntry": {},
"executionContext": {
"type": "EXECUTION_TARGET_TYPE_GRPC",
"target": "",
"className": "WorkerNode"
},
"configuration": {}
}
Bind the trigger type to a method with the decorator, imported as from neuraverse_sdk.trigger.i_trigger import TriggerContext, trigger_handler:
# Bind the trigger TYPE (the schema's rosType), not the port key.
@trigger_handler("SpecialStart")
def on_special_start(self, trigger_context: Optional[TriggerContext] = None) -> None:
source = trigger_context.source_node if trigger_context else "unknown"
self.interrupts_received.append(source)
self.log_info(f"SpecialStart received from {source}, switching to priority handling")
Rules the SDK enforces for this handler:
- The handler is mandatory. A schema that declares
special_startof typeSpecialStartwithout a bound handler failsConfigureNodewithTriggerFlowException, even while the port is not connected in the graph. Typos fail at configure time instead of dropping events silently. - Built-in names are off limits.
@trigger_handler("Start")(or any ofStop,Error,IfTrue,IfFalse,InLoop,BreakLoop) raisesNodeConfigurationErrorwhen the node object is created. In a multi-node service that is service startup, so the whole container fails fast. - One handler per type per class. Two decorated methods in the same class claiming
SpecialStartraiseNodeConfigurationErrorat construction. Handlers are inherited, and a subclass may override the base handler by decorating a method with the same type. - Signature is flexible. The method may take one optional
trigger_contextparameter or none; the SDK normalises both.trigger_context.source_nodeis"WatchdogNode"when the watchdog fired it. Guard againstNone, as the example does. - Keep it short. Record the event (append to a list, set a flag, push to a queue) and return. Anything the handler shares with
on_executeneeds the same protection you would giveon_stop_execution.
If the handler is only known at runtime, self.register_trigger_handler("SpecialStart", callback) in __init__ does the same as the decorator. It must run before the node is configured.
Step 3: Run it end-to-end without an engine¶
The Mock Runner does not deliver triggers, so the SDK ships examples/custom_triggers/run_local_demo.py: a script that connects both nodes to a real MQTT broker, wires them the way the engine would, runs the watchdog once and asserts that the worker was woken twice mid-execution.
You need Docker for the broker and an environment where the SDK and its dependencies are installed (the node base image or the SDK dev container). Start one broker container, then run the script from the SDK repository root:
docker run -d --name mosquitto -p 1883:1883 \
eclipse-mosquitto:2 mosquitto -c /mosquitto-no-auth.conf
python examples/custom_triggers/run_local_demo.py
Expected output shape. The two handler lines appear between the watchdog's start and finish lines, which is the whole point:
--- running WatchdogNode.on_execute (fires task_interrupt twice) ---
... Watchdog monitoring started
... Anomaly #1 detected, firing task_interrupt
... SpecialStart received from WatchdogNode, switching to priority handling
... Anomaly #2 detected, firing task_interrupt
... SpecialStart received from WatchdogNode, switching to priority handling
... Watchdog monitoring finished
--- results ---
WorkerNode.interrupts_received = ['WatchdogNode', 'WatchdogNode']
OK: WatchdogNode.task_interrupt woke WorkerNode.special_start mid-execution
Stop the broker with docker rm -f mosquitto when you are done.
What the script wires by hand¶
On an engine you never write this wiring; the engine computes it from the graph and sends it to your node in ConfigureNode. The script builds the same TriggerNodeEntry protos itself, which makes it a good place to see the key/type split at the transport level:
entry.outputTriggers["task_interrupt"] = "TaskInterrupt" # watchdog: key -> type
conn = InputConnection()
conn.rosType = "SpecialStart" # worker: type selects the handler
conn.sourceConnection.append(f"{RUN_PREFIX}/watchdog/task_interrupt")
entry.inputTriggers["special_start"].CopyFrom(conn) # worker: port key
| Proto field | Holds | Example |
|---|---|---|
outputTriggers map key |
port key of an output | task_interrupt |
outputTriggers map value |
trigger type of that output | TaskInterrupt |
inputTriggers map key |
port key of an input | special_start |
InputConnection.rosType |
trigger type, selects on_execute, stop() or your handler |
SpecialStart |
InputConnection.sourceConnection |
topics to listen on, one per connected upstream port | demo-run/watchdog/task_interrupt |
Each output port publishes on <node id>/<port key>; the engine uses the node's runtime id where the script uses demo-run/watchdog. The script also hands the node's @trigger_handler methods to the adapter through set_named_trigger_callbacks(node.trigger_handlers), which NodeBase does for you during Initialize and again during Configure.
To reuse the script for your own nodes, change the two TriggerNodeEntry blocks to your port keys and type names and replace the two imports at the top.
What the Mock Runner checks, and what it cannot¶
The Mock Runner constructs your node when you click Init. That is where the SDK collects @trigger_handler methods, so a built-in name or a duplicate handler turns Init red with the NodeConfigurationError in the backend log.
Everything else about triggers is out of reach for the mock: its trigger adapter is a stand-in, so fire_trigger publishes nothing, no handler ever runs, the missing-handler check at configure never fires, and trigger_context is always None. Use the broker demo above, a unit test that calls the handler method directly, or a real engine. The full matrix is on the Mock Runner site: Mock Runner limitations.
Common errors¶
| Symptom | Cause | Fix |
|---|---|---|
TriggerFlowException: Unknown output trigger port 'TaskInterrupt' |
fire_trigger was given the type, not the key |
Pass "task_interrupt"; the message lists the declared keys |
TriggerFlowException: Cannot fire trigger ... trigger adapter not initialized |
fire_trigger called before Initialize (for example in __init__) |
Fire from on_execute or a thread you start in on_configure |
ConfigureNode fails with TriggerFlowException: Input trigger port 'special_start' declares custom trigger type 'SpecialStart' but no handler is registered |
The schema declares a custom input and the class has no @trigger_handler("SpecialStart") |
Add the handler, or remove the port from the schema |
Service fails at startup with NodeConfigurationError: Cannot register a custom handler for built-in trigger type |
@trigger_handler("Start") or another built-in name |
Choose a custom type name; built-ins keep their routing |
Service fails at startup with NodeConfigurationError: Duplicate @trigger_handler(...) |
Two methods in one class bound to the same type | Keep one handler per type per class |
Handler never runs, log shows Trigger publish dropped |
Transport not connected when fire_trigger ran |
Fire only after the node is configured and running |
| Downstream nodes stop after every run | A Stop output is declared |
Declare only start and error outputs |
ConnectionError: Failed to connect to MQTT broker from the demo |
No broker on 127.0.0.1:1883 |
Start the mosquitto container first |