Simulation mode¶
A graph can be switched into simulation mode from the engine. Nodes that move hardware, call external services or write to real devices must then stop doing so and answer as if they had. This page shows the hook the SDK calls when the switch flips, what the SDK does and does not do for you, and the pattern for a node that honours the switch. After reading it you can make any node safe to run in a simulated graph and verify that behaviour in a unit test.
What simulation mode is¶
Simulation mode is a graph-wide boolean that the engine pushes to every node. It is not a node setting and not a lifecycle state. The SDK hands you the flag and nothing else: what "simulated" means (log instead of move, return canned data, talk to a simulator) is your decision.
Two things stay exactly the same while a graph is simulated:
- Triggers and dataflow keep flowing, so
on_executeis still called on every incoming trigger. - The lifecycle state (
CONFIGURED,RUNNING, ...) does not change. Simulation is orthogonal to pause and stop.
The hook¶
Override the optional hook on your node class:
def on_toggle_simulation_mode(self, is_simulation: bool) -> None:
...
| Behaviour | |
|---|---|
| Default | No-op. Nodes that never touch the outside world need no change. |
| Argument | True when the graph enters simulation mode, False when it returns to real operation. |
| Return value | None. The SDK reports success to the engine when the hook returns. |
| On exception | Any exception raised in the hook is logged and re-raised as NodeSimulationModeError (error code SIMULATION_MODE_ERROR), and the engine's request fails. |
| Stored state | None. The SDK does not remember the flag and has no getter for it. Keep it on self. |
| Deduplication | None. The same value can arrive more than once; keep the hook idempotent. |
How the toggle reaches your node¶
The engine calls the SetToggleSimulationMode RPC on your node service. The request carries the node id and the boolean flag. The SDK looks up the node instance, logs the new value and calls your hook. A node that has not been initialised cannot be toggled; the request fails with a not-found error.
sequenceDiagram
participant Engine
participant SDK as Node service (SDK)
participant Node as Your node class
Engine->>SDK: SetToggleSimulationMode(nodeId, isSimulation)
SDK->>SDK: find node instance, log value
SDK->>Node: on_toggle_simulation_mode(is_simulation)
Node-->>SDK: return (or raise)
SDK-->>Engine: SUCCESS, or the wrapped error
The whole hook table for your class is in the lifecycle overview; see Node anatomy.
Pattern: store a flag, branch in on_execute¶
Keep the hook tiny. Store the value on the instance and decide in on_execute whether to touch the real device. The tutorial device node does exactly this; the graph-wide switch overrides the node's own simulate configuration toggle:
def on_toggle_simulation_mode(self, is_simulation: bool) -> None:
"""Graph-wide simulation switch; it overrides the node's own 'simulate' setting."""
self._simulate = is_simulation
self.log_info(f"Simulation mode {'enabled' if is_simulation else 'disabled'}")
The execute path reads the flag and either logs the command or sends it:
def on_execute(self, trigger_context: Optional[TriggerContext] = None) -> None:
try:
if self._is_paused():
self.log_info("Paused: ignoring command")
return
msg = self.get_data("command_in")
if msg is None:
self.log_warning("No command received on 'command_in'")
return
command = msg.data
if command not in VALID_COMMANDS:
self.log_warning(f"Ignoring unknown command {command!r}; expected ON or OFF")
return
if self._device is None:
self.send_health_update(False, "Light device handle is missing")
raise NodeExecutionError("Light device is not configured")
if self._simulate:
self.log_info(f"[simulation] would switch light {self._light_ip} {command}")
else:
self._device.set_power(command == "ON")
self.publish("status_out", String(data=command))
except NodeExecutionError:
raise
except Exception as exc:
self.send_health_update(False, f"Light command failed: {exc}")
raise NodeExecutionError(f"Light command failed: {exc}") from exc
Note how the node still publishes status_out while simulating. Downstream nodes see the same outputs in both modes, which is what makes a simulated graph useful for checking wiring and logic.
Re-configure resets your flag
The SDK does not replay the last toggle after on_configure. If your configure hook derives the flag from the node's configuration, a re-configure returns the node to whatever the configuration says. Either accept that (the engine can toggle again) or keep the graph-wide value in a separate attribute that on_configure leaves untouched, and combine both when deciding.
Keep real side effects out of the hook
Do not open or close device connections inside on_toggle_simulation_mode. The hook can arrive at any point after initialisation, so treat it as a pure setter. Open connections in on_configure and release them in on_cleanup.
Do and do not¶
| Do | Do not |
|---|---|
Store the flag on self and check it in on_execute. |
Rely on the SDK to remember or expose the flag. |
| Keep publishing your outputs in simulation so downstream nodes keep working. | Skip publishing because "nothing happened". |
| Make the hook idempotent and fast. | Raise from the hook for expected situations; a raise fails the engine's request. |
| Log clearly that a command was simulated. | Use print(); use self.log_info(). |
Testing the hook¶
The public method that the SDK calls is toggle_simulation_mode(is_simulation). Call it directly in a unit test; it invokes your hook and wraps errors the same way the RPC path does. With the fake dataflow from the examples:
node = SmartLightNode()
node.data_flow = FakeDataFlow()
node.on_configure({}, None)
node.toggle_simulation_mode(True)
node.data_flow.input_ports["command_in"] = String(data="ON")
node.on_execute()
assert node._device.is_on is False # nothing reached the device
assert node.data_flow.published["status_out"][0].data == "ON"
The Mock Runner has no simulation-mode control, so this is a unit-test or on-engine feature. See Testing for the fake dataflow and the stub setup used by the example tests.
Related pages¶
- Device node tutorial: the full
SmartLightNodewith typed configuration, health and pause handling. - Health reporting: report an unhealthy state when a real device is unreachable, independent of simulation.