CANopen
The canopen component turns an ESPHome device into a CANopen node
(CiA 301) on a CAN bus, using the CANopenNode
stack. The node:
- runs the NMT state machine (it reacts to NMT commands from a master) and sends a heartbeat;
- monitors the heartbeats of other nodes and reports when they go online or offline, restart or change their NMT state, see Heartbeat Monitoring;
- sends NMT commands to other nodes as an NMT master (
canopen.nmt); - answers SDO requests from other nodes and tools, with its identity, device name and versions, see Object Dictionary;
- reads and writes objects of other devices over SDO, from automations
(
canopen.sdo_read,canopen.sdo_write) or lambdas (see SDO Client); - reports the heartbeats and emergency messages of the nodes on the bus (
on_heartbeat,on_emcy); - receives and sends other frames in lambdas, for example PDOs (see Raw Frames).
The node sends emergency (EMCY) messages only for errors the stack detects itself, such as a full CAN transmit queue
or a monitored node’s heartbeat timeout; there is no API to send your own. It has no PDOs of its own, and doesn’t
support SYNC, LSS or EDS files.
Of the NMT commands, Reset Node restarts the whole device, so every canopen component on it boots up again. Reset
Communication is only logged for now: the node doesn’t reset its communication or send a new boot-up message.
Without a node_id the component is no CANopen node, only an SDO client: it reads and writes objects of other
devices, see SDO Client Only.
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: node_id: 0x10Configuration Variables
Section titled “Configuration Variables”- node_id (Optional, int): The node id of this node, from
1to127. It must be unique on the bus. Without it the component is an SDO client only, see SDO Client Only. - canbus_id (Optional, ID): The CAN bus to use. Required if there is more than one bus.
- heartbeat_interval (Optional, Time): How often this node sends its
heartbeat. From
100msto65535ms. Defaults to5s. It’s sent from the main loop, so the actual period is the interval plus up to one loop pass (for example about 1,008 ms for1s). - heartbeat_clients (Optional, list): Other nodes whose heartbeats are monitored, see
Heartbeat Monitoring.
- node_id (Required, int): The node id, from
1to127. It can’t be this node’s own id. - timeout (Required, Time): The node is reported offline when no
heartbeat arrives within this time. Up to
65535ms. Choose it longer than the node’s heartbeat interval.
- node_id (Required, int): The node id, from
- response_timeout (Optional, Time): How long an SDO request waits for an
answer. Up to
65535ms. Defaults to500ms. - sdo_client (Optional, boolean): Whether the SDO client is compiled in. Not set by default: it’s compiled in
when the configuration uses it (the
canopen.sdo_read/canopen.sdo_writeactions, or a component withoutnode_id). Set it totruewhen only lambdas use it (see SDO Client), or tofalseto make sure it isn’t compiled in (an error if something uses it). It’s a build option of the stack: the same for allcanopencomponents of the device. - sdo_block_size (Optional, int): Enables SDO block transfer in the SDO server, for large uploads and downloads
such as firmware images. From
1to127: the number of frames per block the node accepts in a block download, and the most a client may ask for in a block upload (at least 4, see below). Not set by default: expedited and segmented transfers only.- The client sends a whole block back to back, so it must fit the CAN receive queue of the node. On an
ESP32 bus, set
rx_queue_lento at least the block size: the default queue holds 5 frames, and a larger block then loses frames every time and is slower than segmented transfer. With an MCP2515 use2: it has two receive buffers, which ESPHome reads from the main loop. - The node keeps one block in RAM, for each
canopencomponent: 7 bytes per frame plus 2, and at least 32 bytes (114 bytes with16). A client asking for more frames per block in an upload than fit gets the SDO abort “invalid block size” (0x05040002). With1to3, the 32-byte minimum still holds 4 frames, so the node accepts upload blocks of up to 4 frames. - It’s a build option of the stack: if several
canopencomponents set it, they must use the same value. - When the last frame of a block is lost, the node waits 700 ms before it asks for the rest, so the client’s SDO
response timeout must be longer. python-canopen’s default of 300 ms isn’t: set
RESPONSE_TIMEOUTto1.0or more.
- The client sends a whole block back to back, so it must fit the CAN receive queue of the node. On an
ESP32 bus, set
- nmt_master (Optional, boolean): Set it to
trueto compile in the NMT master when only lambdas send NMT commands (see NMT Master). Without it the NMT master is compiled in when the configuration uses acanopen.nmtaction. Likesdo_client, it’s the same for allcanopencomponents of the device. - nmt_startup (Optional, enum): The NMT state after boot. One of
operationalorpre_operational. Defaults tooperational. A node that startspre_operationalstays there until an NMT master starts it, or until it starts itself (see NMT State of This Node). - identity (Optional): The identity object (
0x1018). Vendor IDs are assigned by CiA.- vendor_id (Optional, int): Defaults to
0. - product_code (Optional, int): Defaults to
0. - revision_number (Optional, int): Defaults to
0. - serial_number (Optional, int): Defaults to
0.
- vendor_id (Optional, int): Defaults to
- device_name (Optional, string): The device name (
0x1008). Defaults to the device’snamefrom theesphomeblock (with the MAC suffix whenname_add_mac_suffixis set), the same for everycanopencomponent of the device. - hardware_version (Optional, string): The hardware version (
0x1009). Not present if not set. - software_version (Optional, string): The software version (
0x100A). Defaults to the ESPHome version. - on_nmt_state_change (Optional, Automation): See
on_nmt_state_change. - on_node_event (Optional, Automation): See
on_node_event. - 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.
SDO Client Only
Section titled “SDO Client Only”Without node_id the component reads and writes objects of other CANopen devices (drives, sensors, I/O modules), but
isn’t a node itself: it sends no boot-up message or heartbeat, doesn’t react to NMT commands, has no object dictionary
other devices can read, and sends only its SDO requests (expedited and segmented transfers; no block transfer) and the
frames lambdas send. When no canopen component has a node_id, the node part of the stack isn’t compiled in, so the
firmware is smaller (about 10 KB of flash on an ESP8266).
canopen: id: my_canopen response_timeout: 200ms
interval: - interval: 60s then: - canopen.sdo_read: node_id: 0x20 index: 0x6000 size: 2 on_value: - logger.log: format: "input: 0x%04x" args: ["(unsigned) x"]Available without node_id: canbus_id, response_timeout, sdo_client (not false), on_heartbeat, on_emcy,
the canopen.sdo_read and canopen.sdo_write actions, the
SDO Client and Raw Frames lambdas. The options of a node (heartbeat_interval,
heartbeat_clients, nmt_master, sdo_block_size, nmt_startup, identity, device_name, hardware_version,
software_version, on_nmt_state_change, on_node_event) and the canopen.nmt action are
rejected.
Several Nodes
Section titled “Several Nodes”More than one canopen component can be configured, on different buses or on the same one. Nodes on the same bus must
have different node ids, as on any CANopen bus. They receive each other’s frames as if they were separate devices:
a node can monitor another one’s heartbeat with heartbeat_clients, their on_heartbeat and on_emcy triggers and
frame listeners see the other’s frames, and SDO requests and NMT commands between them work. The frames are also sent
on the bus as usual.
A node gets the frames of the other nodes on the device at the start of its next loop pass, or earlier when a frame from the bus reaches it first (the waiting local frames are handled before it). Either way they come in the order they were sent, and in order with the frames from the bus: a frame another node sends in reply to a bus frame comes after that frame.
Up to 16 frames can wait for a node. When more arrive in between (for example from a long burst of send_frame()
calls in one lambda), the rest are lost, as on a bus; frames from the bus that find the queue full are lost for that
node too. Either way the node logs a warning with the number of lost frames.
A bus can have only one canopen component without node_id (SDO client only): two would share the SDO client’s CAN
IDs.
canopen: - id: node_a node_id: 0x10 heartbeat_clients: - node_id: 0x11 timeout: 7s - id: node_b node_id: 0x11Heartbeat Monitoring
Section titled “Heartbeat Monitoring”Nodes listed in heartbeat_clients are monitored. Each monitored node reports these events (see
on_node_event):
NODE_EVENT_ONLINE: the first heartbeat, or the first one after a timeout or a boot-up message.NODE_EVENT_OFFLINE: no heartbeat withintimeout. A node that never sent a heartbeat isn’t reported offline.NODE_EVENT_NMT_CHANGED: the NMT state in the heartbeat changed. It also followsNODE_EVENT_ONLINE(unknown → state) andNODE_EVENT_OFFLINE(state → unknown), but notNODE_EVENT_RESET.NODE_EVENT_RESET: the node sent a boot-up message, so it restarted and lost any configuration it got at runtime. It counts as online again with its next heartbeat.
Monitoring of a node starts with its first heartbeat, as in CiA 301: a node that never sends one (unpowered, another
node id, miswired) gives no event, no warning and no EMCY. To catch that, check is_node_online() (see below) some
time after boot:
interval: - interval: 30s then: - if: condition: lambda: "return !id(my_canopen).is_node_online(0x01);" then: - logger.log: "Node 0x01 sends no heartbeats"Each event is also logged: offline as a warning, the others at info level. Monitoring goes on in every NMT state of
this node, also while it is STOPPED (CiA 301 keeps heartbeat monitoring running there).
Heartbeat errors are also sent on the bus as emergency (EMCY) messages, which other nodes see, for example in their
on_emcy triggers:
- A heartbeat timeout, or a boot-up message of a monitored node that was online, sends an EMCY with error code
0x8130(heartbeat error) and sets bit 4 (communication) of the error register. Bytes 4-7 of the EMCY (manufacturer-specific, a 32-bit little-endian value) hold the node’s position in the consumer heartbeat list:0x1016sub-index minus 1. - Once all monitored nodes send heartbeats again, it sends an EMCY with error code
0x0000(error reset). - A boot-up of a node that wasn’t online (its first one, or one after a timeout) sends no EMCY, though it still gives a
NODE_EVENT_RESET. - The stack tracks the timeout and the boot-up as one error each, not per node: while one is active, further timeouts
(or boot-ups) of other nodes send no new EMCY, so the EMCY names only the first node. Don’t expect an EMCY for every
node event; use
on_node_eventfor that. - An EMCY that comes while this node is
STOPPEDis sent once it is pre-operational or operational again.
canopen: id: my_canopen node_id: 0x10 heartbeat_clients: - node_id: 0x01 timeout: 7s on_node_event: - if: condition: lambda: "return node_id == 0x01 && event == canopen::NodeEvent::NODE_EVENT_RESET;" then: # the node restarted: configure it again - canopen.sdo_write: node_id: 0x01 index: 0x1017 value: 2000 size: 2The state of a monitored node is also available in lambdas. A node id that isn’t in heartbeat_clients reads like an
offline node, so check the id when a node never shows up:
// true while heartbeats arrive in time (false for a node that isn't monitored)id(my_canopen).is_node_online(0x01);// NMT state from the last heartbeat (UNKNOWN for a node that isn't monitored or is offline)id(my_canopen).get_node_state(0x01) == canopen::NMTState::NMT_STATE_OPERATIONAL;Object Dictionary
Section titled “Object Dictionary”Other nodes and tools read and write the node’s objects with SDO. The node has one SDO server, on the default
COB-IDs 0x600 + node id (requests) and 0x580 + node id (responses), with expedited and segmented transfers,
and block transfers with sdo_block_size.
| Index | Object | Access | Notes |
|---|---|---|---|
0x1000 | Device type | read | 0 |
0x1001 | Error register | read | |
0x1008 | Device name | read | device_name |
0x1009 | Hardware version | read | hardware_version, only if set |
0x100A | Software version | read | software_version |
0x1014 | EMCY COB-ID | read | 0x80 + node id |
0x1016 | Consumer heartbeat time | read | one entry per node in heartbeat_clients, only with them |
0x1017 | Producer heartbeat time | read/write | heartbeat_interval; a write takes effect at once |
0x1018 | Identity | read | identity |
0x1200 | SDO server parameter | read | |
0x1280 | SDO client parameter | read | only with the SDO client |
Automations
Section titled “Automations”on_nmt_state_change Trigger
Section titled “on_nmt_state_change Trigger”Runs when this node’s own NMT state changes: after boot (in the component’s first loop pass), on an NMT command from
a master, or after set_nmt_state().
Variable: state (canopen::NMTState).
canopen: # ... on_nmt_state_change: - logger.log: format: "NMT state: %s" args: ["LOG_STR_ARG(canopen::nmt_state_to_string(state))"]on_node_event Trigger
Section titled “on_node_event Trigger”Runs for every event of a node in heartbeat_clients, see Heartbeat Monitoring. Variables:
node_id(uint8_t): the node.event(canopen::NodeEvent):NODE_EVENT_ONLINE,NODE_EVENT_OFFLINE,NODE_EVENT_NMT_CHANGEDorNODE_EVENT_RESET.state(canopen::NMTState): the node’s NMT state (NMT_STATE_UNKNOWNafterNODE_EVENT_OFFLINE,NMT_STATE_BOOTUPforNODE_EVENT_RESET).
canopen: # ... on_node_event: - logger.log: format: "node 0x%02x: %s, %s" args: - node_id - LOG_STR_ARG(canopen::node_event_to_string(event)) - LOG_STR_ARG(canopen::nmt_state_to_string(state))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.
canopen.nmt Action
Section titled “canopen.nmt Action”Sends an NMT command, as an NMT master. A command to this node’s own id, or to all nodes, applies to this node too;
a reset_node to all nodes restarts this node once the command is sent, waiting at most about 140 ms for it: if the
bus is blocked, this device restarts anyway and the other nodes may not get the command. A command that can’t be sent
is logged as a warning (see NMT Master for when), and the automation goes on: to react to a failure,
call send_nmt() in a lambda and check its return value.
on_...: - canopen.nmt: node_id: 0x01 command: startConfiguration variables:
- node_id (Required, int, templatable): The node, from
1to127, or0for all nodes. - command (Required, enum): One of
start,stop,pre_operational,reset_nodeorreset_communication. - id (Optional, ID): The
canopencomponent to use. Required if there is more than one. It must have anode_id.
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. This includes the other canopen
components of the same device (see Several Nodes): each has its own SDO client, and they all use the
same channel of the node they talk to, so two of them shouldn’t send requests to the same node at the same time.
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 in the NMT state STOPPED sends no SDO frames: requests
running or queued when it stops end with SDO_RESULT_REJECTED, and new ones are rejected until it leaves STOPPED.
A node’s SDO channel is shared with any other client, and late answers can reach a later request; see
Shared SDO Channel. Requests to this node’s own id are served from its own object dictionary,
without CAN frames. The SDO client is compiled in for the whole firmware once any canopen component uses an SDO
action or has no node_id; otherwise a node that only uses it from lambdas needs sdo_client: true.
// 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).
NMT State of This Node
Section titled “NMT State of This Node”get_nmt_state() returns the node’s own NMT state. It is UNKNOWN without node_id, and until the component’s first
loop pass (also in an on_boot automation that runs right after setup).
set_nmt_state() sets it to OPERATIONAL, PRE_OPERATIONAL or STOPPED; no NMT master is needed. It returns:
truewhen the change is accepted. It is applied right away, except when called from an automation the component’s processing runs (on_node_event,on_nmt_state_change): there it is applied in the next pass, soget_nmt_state()still returns the old state just after the call.falsewithoutnode_id, and while a previous command for this node isn’t applied yet (with a warning in the log).
id(my_canopen).get_nmt_state() == canopen::NMTState::NMT_STATE_OPERATIONAL;id(my_canopen).set_nmt_state(canopen::NMTState::NMT_STATE_OPERATIONAL);NMT Master
Section titled “NMT Master”The NMT master is compiled in when the configuration uses a canopen.nmt action, or with
nmt_master: true.
send_nmt() sends an NMT command to a node id, or to all nodes with 0. It returns:
truewhen the command is accepted. A command the CAN controller can’t take at once is resent from the main loop. A command for this node (its own id or0) applies right away, except when called from an automation the component’s processing runs (e.g.on_node_event): there it applies in the next pass.false, with a warning in the log, withoutnode_id, for a node id above 127, while the previous NMT command is still waiting to be sent, or, for this node’s own id or0, while the previous command for this node isn’t applied yet.
id(my_canopen).send_nmt(0x01, canopen::NMTCommand::NMT_COMMAND_PRE_OPERATIONAL);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.