CANopen
The canopen component reads and writes objects of CANopen
devices (CiA 301), for example drives, sensors and I/O modules, on a CAN bus, using the SDO
client of the CANopenNode stack. Reads and writes are started from
automations (canopen.sdo_read, canopen.sdo_write) or
lambdas (see SDO Client). It also reports the heartbeats and emergency messages of the nodes on the bus
(on_heartbeat, on_emcy), and lambdas can receive and send other
frames, for example PDOs (see Raw Frames).
The ESPHome device isn’t a CANopen node itself: it sends no boot-up message or heartbeat, doesn’t react to NMT commands and has no object dictionary other devices can read. It sends only its SDO requests (expedited and segmented transfers; no block transfer) and the frames lambdas send.
This component requires a CAN bus platform, for example
ESP32 CAN or MCP2515. Set the bus’s bit_rate to the
one used by the CANopen network.
# Example configuration entrycanopen:Configuration Variables
Section titled “Configuration Variables”- canbus_id (Optional, ID): The CAN bus to use. Required
if there is more than one bus. One
canopencomponent per bus. - response_timeout (Optional, Time): How long an SDO request waits for an
answer. Up to
65535ms. Defaults to500ms. - on_heartbeat (Optional, Automation): See
on_heartbeat. - on_emcy (Optional, Automation): See
on_emcy. - id (Optional, ID): Manually specify the ID used for code generation and in lambdas.
Automations
Section titled “Automations”on_heartbeat Trigger
Section titled “on_heartbeat Trigger”Runs for every heartbeat frame on the bus (CAN IDs 0x701 to 0x77F, 1 data byte), from any node. Variables: node_id
(uint8_t) and state (canopen::NMTState: NMT_STATE_BOOTUP, NMT_STATE_STOPPED, NMT_STATE_OPERATIONAL,
NMT_STATE_PRE_OPERATIONAL, or NMT_STATE_UNKNOWN for other values). canopen::nmt_state_to_string(state) gives its
name.
canopen: # ... on_heartbeat: - if: condition: lambda: "return state == canopen::NMTState::NMT_STATE_BOOTUP;" then: - logger.log: format: "node 0x%02x booted" args: [node_id]on_emcy Trigger
Section titled “on_emcy Trigger”Runs for every emergency (EMCY) frame on the bus (CAN IDs 0x081 to 0x0FF, 8 data bytes), from any node, also for an
error reset (error code 0x0000, sent when an error clears). Each one is also logged: an error as a warning, an error
reset at info level. Variables:
node_id(uint8_t): the node that sent it.emergency(canopen::Emergency):error_code(uint16_t),error_register(uint8_t) andmanufacturer_data(5 bytes).
canopen: # ... on_emcy: - logger.log: format: "EMCY from node 0x%02x: 0x%04x" args: [node_id, emergency.error_code]canopen.sdo_read Action
Section titled “canopen.sdo_read Action”Reads a value of up to 4 bytes from an object of a node over SDO. The action starts the transfer and continues;
on_value or on_error runs when it ends. Requests are queued and sent one after another.
on_...: - canopen.sdo_read: node_id: 0x01 index: 0x1018 subindex: 1 size: 4 on_value: - logger.log: format: "vendor id 0x%08x" args: ["(unsigned) x"] on_error: - logger.log: format: "read failed: %s, abort code 0x%08x" args: ["LOG_STR_ARG(canopen::sdo_result_to_string(result))", "(unsigned) abort_code"]Configuration variables:
- node_id (Required, int, templatable): The node, from
1to127. - index (Required, int, templatable): The object index.
- subindex (Optional, int, templatable): The subindex. Defaults to
0. - size (Optional, int): The size of the object in bytes:
1,2or4(a different size givesSDO_RESULT_SIZE_MISMATCH), or0for any size up to 4 bytes (a longer object givesSDO_RESULT_SIZE_MISMATCH). Defaults to0. - on_value (Optional, Automation): Runs with the value read. Variable:
x(uint32_t, little endian bytes as an unsigned number; cast it for signed objects, e.g.(int16_t) x). - on_error (Optional, Automation): Runs when the read failed. Variables:
result(canopen::SDOResult:SDO_RESULT_ABORT,SDO_RESULT_TIMEOUT,SDO_RESULT_SIZE_MISMATCH,SDO_RESULT_TRANSPORT_ERRORorSDO_RESULT_REJECTED) andabort_code(uint32_t, the SDO abort code forSDO_RESULT_ABORTandSDO_RESULT_TIMEOUT). - id (Optional, ID): The
canopencomponent to use. Required if there is more than one.
canopen.sdo_write Action
Section titled “canopen.sdo_write Action”Writes a value of 1, 2 or 4 bytes to an object of a node over SDO. The action starts the transfer and continues;
on_success or on_error runs when it ends. Requests are queued and sent one after another.
on_...: - canopen.sdo_write: node_id: 0x01 index: 0x1017 value: 2000 size: 2 on_error: - logger.log: format: "write failed: %s, abort code 0x%08x" args: ["LOG_STR_ARG(canopen::sdo_result_to_string(result))", "(unsigned) abort_code"]Configuration variables:
- node_id (Required, int, templatable): The node, from
1to127. - index (Required, int, templatable): The object index.
- subindex (Optional, int, templatable): The subindex. Defaults to
0. - value (Required, int, templatable): The value. Negative values are written as
two’s complement. A constant must fit in
sizebytes. - size (Optional, int): The size of the object in bytes:
1,2or4. Defaults to4. - on_success (Optional, Automation): Runs when the node confirmed the write.
- on_error (Optional, Automation): Runs when the write failed. Variables:
result(canopen::SDOResult:SDO_RESULT_ABORT,SDO_RESULT_TIMEOUT,SDO_RESULT_TRANSPORT_ERRORorSDO_RESULT_REJECTED) andabort_code(uint32_t, the SDO abort code forSDO_RESULT_ABORTandSDO_RESULT_TIMEOUT). AfterSDO_RESULT_TIMEOUTorSDO_RESULT_TRANSPORT_ERRORthe write may still have been carried out: the answer may have been lost, or the CAN controller may have sent the frame later. - id (Optional, ID): The
canopencomponent to use. Required if there is more than one.
Shared SDO Channel
Section titled “Shared SDO Channel”These apply to both actions and to the lambda calls.
Another SDO client talking to the same node at the same time (a CANopen master, a PC tool) shares the node’s SDO
channel, so either side’s requests can end with an abort: handle on_error.
SDO frames carry no request id, so a late answer to a request that timed out can be taken as the answer to the next request for the same object of the same node, such as a retry (a late abort by any request, a late write confirmation only by a write, a late read answer only by a read). That request then gets the earlier request’s result.
Lambdas
Section titled “Lambdas”SDO Client
Section titled “SDO Client”The SDO client has one channel; requests are queued (up to 16) and sent one after another. Every request ends in exactly
one call of its callback, if one was given (it may be nullptr) and the request wasn’t cancelled (cancel_sdo()), with
a canopen::SDOReply: result (SDO_RESULT_SUCCESS, SDO_RESULT_ABORT, SDO_RESULT_TIMEOUT,
SDO_RESULT_SIZE_MISMATCH, SDO_RESULT_TRANSPORT_ERROR or SDO_RESULT_REJECTED), abort_code, value / size for a
successful value read or write, and data / len for a successful read_sdo_data() (valid only during the callback;
otherwise nullptr and 0). A rejected request (queue full, invalid arguments, failed component) calls back before the
call returns false. Requests made at boot, before the component is set up, wait in the queue; if the setup fails (for
example on a failed CAN bus), they are rejected then. A node’s SDO channel is shared with any other client, and late
answers can reach a later request; see Shared SDO Channel.
// value read with a width check: a different width gives SIZE_MISMATCHid(my_canopen).read_sdo<uint32_t>(0x01, 0x1018, 1, [](void *context, const canopen::SDOReply &reply) { if (reply.ok()) { ESP_LOGI("main", "vendor id 0x%08x", reply.as<uint32_t>()); } else { ESP_LOGW("main", "read failed: %s, abort code 0x%08x", LOG_STR_ARG(canopen::sdo_result_to_string(reply.result)), (unsigned) reply.abort_code); }}, nullptr);
// value write; a failure also calls the callback, so a rejected request is logged here tooid(my_canopen).write_sdo<uint16_t>(0x01, 0x1017, 0, 2000, [](void *context, const canopen::SDOReply &reply) { if (!reply.ok()) ESP_LOGW("main", "write failed: %s", LOG_STR_ARG(canopen::sdo_result_to_string(reply.result)));}, nullptr);
// buffer read (strings, domains); the buffer must stay valid until the callbackstatic uint8_t name[64];id(my_canopen).read_sdo_data(0x01, 0x1008, 0, name, sizeof(name), [](void *context, const canopen::SDOReply &reply) { if (reply.ok()) ESP_LOGI("main", "name: %.*s", (int) reply.len, (const char *) reply.data); // a name longer than the buffer ends in SDO_RESULT_ABORT}, nullptr);read_sdo<T>(node_id, index, subindex, callback, context)andwrite_sdo<T>(node_id, index, subindex, value, callback, context)for values of 1, 2 or 4 bytes.SDOReply::as<T>()sign-extends for signed types.read_sdo_data(node_id, index, subindex, data, capacity, callback, context)andwrite_sdo_data(node_id, index, subindex, data, len, callback, context)for buffers. The buffer belongs to the caller and must stay valid until the callback, so it can’t be a local variable. A read of an object longer thancapacityis aborted. Transfers are limited to 65,535 bytes: a longer write is rejected, and a read of a longer object is aborted. Requests run one at a time, so queued reads can share a buffer if each callback uses the data before it returns.cancel_sdo(context)drops all queued requests with thatcontextand aborts its transfer in progress (an SDO abort is sent to the node; if the CAN bus doesn’t take it within the response timeout, it’s dropped), without callbacks. The component doesn’t use the request’s buffer after the call, so use it before a buffer orcontextgoes away. The next request (to any node) waits 50 ms after the abort, so a late answer to the cancelled transfer isn’t taken for it. The 50 ms are counted from when the CAN controller took the abort, not from when it was on the bus. A node busy in a slow object handler can answer the cancelled request even later, hundreds of milliseconds after the abort; a request for the same object running then takes that answer as its own (see Shared SDO Channel).
Raw Frames
Section titled “Raw Frames”Frames the component doesn’t handle itself, for example the PDOs of other devices, can be received and sent
directly. A listener is a canopen::FrameListener that you own: {can_id, mask, callback, context}. It must stay
valid for as long as the device runs (make it static), and it can’t be removed. Listeners can be added at any time,
also before the component is set up or from a frame callback. They get standard (11-bit) data frames, including the
SDO answers and heartbeats the component handles. The callback is a plain function, so a lambda can’t capture
anything: it gets what it needs through context, which must stay valid as long as the listener, so for as long as the
device runs. It’s called from the main loop, and the data is valid only during the call.
// every TPDO1 frame (CAN IDs 0x180 to 0x1FF; node ID 0 isn't used)static canopen::FrameListener tpdo1{0x180, 0x780, [](void *context, uint32_t can_id, const uint8_t *data, uint8_t len) { ESP_LOGD("main", "TPDO1 from node 0x%02x", (unsigned) (can_id & 0x7F));}, nullptr};id(my_canopen).add_frame_listener(tpdo1);
// returns false for a CAN ID above 0x7FF, more than 8 bytes, or if the CAN controller can't take the frame now (it// isn't queued)const uint8_t data[2] = {0x0F, 0x00};id(my_canopen).send_frame(0x201, data, sizeof(data));A frame matches a listener when (frame_id ^ can_id) & mask is 0. A listener that can’t match any 11-bit CAN ID
(can_id & mask above 0x7FF) isn’t added, and a warning is logged. Adding a listener again does nothing, and each
canopen component needs its own listener objects. A listener added from a frame callback gets frames from the next
one on.