Skip to content

Fault injection recipes

Ralf Steinert edited this page Nov 22, 2026 · 2 revisions

Real nodes and buses fail in a handful of typical ways. Each recipe below shows the failure, the canopen-sim fault that reproduces it, and a pytest test for the code that has to cope. They use the canopen library as the master (tested with 2.4.1); all of them run as they are against canopen-sim 0.1.1, on the virtual bus, on any OS. Put the blocks into one file one after another.

import time

import pytest
from canopen.nmt import NmtError
from canopen.sdo.exceptions import SdoAbortedError, SdoCommunicationError

BENCH = {"nodes": [
    {"profile": "generic-drive", "id": 3, "name": "axis", "heartbeat_ms": 100},
    {"profile": "generic-io", "id": 5, "name": "io", "heartbeat_ms": 100},
]}


def wait_until(condition, timeout=2.0):
    deadline = time.monotonic() + timeout
    while not condition():
        assert time.monotonic() < deadline, "condition not met in time"
        time.sleep(0.01)


@pytest.fixture
def bench(canopen_bench_factory):
    return canopen_bench_factory(BENCH)


@pytest.fixture
def network(bench):
    return bench.network()


@pytest.fixture
def axis(bench, network):
    node = bench.remote_node("axis", network=network)
    node.sdo.RESPONSE_TIMEOUT = 0.2
    node.sdo.MAX_RETRIES = 1            # attempts, not retries: 0 would retry forever
    return node


@pytest.fixture
def io(bench, network):
    return bench.remote_node("io", network=network)

Faults are switched with bench.inject(kind, node=…, **params) in tests, or canopen-sim inject KIND key=value … --node NAME against a running serve. The complete list with parameters is in the README. Faults with count=N wear off after N firings; the others stay until cleared.

A node falls silent

Real life: a node lost its supply, a connector came loose, the bus cable was cut behind the node. A master that only notices when the next SDO times out finds out late, and may keep driving the rest of the machine as if nothing happened. Watch the heartbeat.

def node_alive(node, timeout=0.5):
    try:
        node.nmt.wait_for_heartbeat(timeout)
        return True
    except NmtError:
        return False


def test_heartbeat_lost(bench, axis):
    assert node_alive(axis)
    bench.inject("no_heartbeat", node="axis")
    assert not node_alive(axis)
    bench.clear(node="axis")
    assert node_alive(axis)

no_heartbeat suppresses only the heartbeat; mute silences the node completely (no SDO answers, no PDOs, no EMCY).

An SDO request is refused

Real life: the object exists on one firmware and not on the next, a parameter is write-protected in the current state, a value is out of range. The device answers with an SDO abort and a code; code that treats every exception the same cannot tell "try later" from "never works".

def read_or_abort_code(node, index, sub=0):
    try:
        return node.sdo.upload(index, sub), None
    except SdoAbortedError as error:
        return None, error.code


def test_sdo_abort(bench, axis):
    bench.inject("sdo_abort", node="axis", code=0x08000022, index=0x6060)
    assert read_or_abort_code(axis, 0x6060) == (None, 0x08000022)
    value, code = read_or_abort_code(axis, 0x1000)
    assert code is None and value       # other objects still answer

Without index every SDO request is refused with that code. Common codes: 0x06020000 (object does not exist), 0x06010002 (read only), 0x06090030 (value out of range), 0x08000022 (not allowed in the present device state).

An SDO request gets no answer

Real life: a frame lost to a bus error, a node busy with something else, a gateway that swallowed the request. The canopen library raises SdoCommunicationError after RESPONSE_TIMEOUT.

def test_sdo_timeout(bench, axis):
    bench.inject("sdo_drop", node="axis", count=1)
    with pytest.raises(SdoCommunicationError):
        axis.sdo.upload(0x1000, 0)
    assert axis.sdo.upload(0x1000, 0)   # the next request works again


def test_sdo_retry_rides_out_one_lost_answer(bench, axis):
    axis.sdo.MAX_RETRIES = 2
    bench.inject("sdo_drop", node="axis", count=1)
    assert axis.sdo.upload(0x1000, 0)   # first attempt lost, second answered

Careful with MAX_RETRIES in the canopen library (2.4): it counts attempts, not retries. 1 (the default) means no retry, 2 means one retry — and 0 means the client retries forever. sdo_delay seconds=… makes answers late instead of missing; use it to find a timeout that is too tight.

The node restarts behind your back

Real life: a watchdog reset, a brown-out, someone power-cycled the cabinet. The node comes back in PRE-OPERATIONAL with its default PDO mapping and sends a boot-up message; a master that does not react waits forever for PDOs that will never come.

def test_unexpected_restart(bench, axis):
    axis.nmt.state = "OPERATIONAL"
    wait_until(lambda: bench.status()["axis"]["nmt_state"] == "operational")
    bench.inject("restart", node="axis")
    wait_until(lambda: axis.nmt.state == "PRE-OPERATIONAL")
    axis.nmt.state = "OPERATIONAL"      # the master brings it back
    wait_until(lambda: bench.status()["axis"]["nmt_state"] == "operational")

double_bootup sends the next boot-up message twice — a master that runs its configuration on every boot-up should not do it twice in parallel.

An input wire breaks

Real life: a broken sensor cable on an analog input. The I/O module reports it with an EMCY; a master that ignores EMCY keeps using a value of 0 as if it were real.

def test_wire_break_emcy(bench, io):
    bench.inject("wire_break", node="io", channel=2, type="analog")
    error = io.emcy.wait(0xFF01, timeout=1.0)
    assert error is not None and error.register & 0x01
    bench.clear(node="io")
    wait_until(lambda: not io.emcy.active)

short_circuit and over_range work the same way with their own EMCY codes (0x2320, 0x3110). clear sends EMCY 0x0000 and the input follows its output (or its signal) again.

A drive trips

The full commissioning — enable, run a velocity, over_temperature, EMCY 0x4310, clear, fault reset, run again — is the example in the repository: examples/test_example.py. The drive leaves FAULT only on a rising edge of controlword bit 7 after the cause is cleared, like a real one: a fault reset sent while the cause is still there does nothing, and the drive stays in FAULT until the master sends a new rising edge.

More to try

  • pdo_dropout every=3 — every third TPDO is lost: does your master notice a stale value?
  • pdo_freeze — the TPDO keeps coming, but with the data of the moment of injection. Only a plausibility check (a position that should move) catches it.
  • pdo_bad_length length=2 — truncated TPDOs: does your code check the length before it unpacks?
  • sdo_bad_toggle — a segmented upload with a wrong toggle bit; the client has to abort.
  • emcy code=0x8130 — any EMCY you like, active until cleared (here: heartbeat error).