ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
canopen.h
Go to the documentation of this file.
1#pragma once
2
3#include <array>
4#include <cstring>
5#include <utility>
6#include <vector>
7
12
13#include "od.h"
14#include "types.h"
15
16#ifdef USE_CANOPEN_PDO_STORAGE
18#include "storage/CO_storage.h"
19#endif
20
21namespace esphome::canopen {
22
23#ifdef USE_CANOPEN_PDO
24// One PDO's parameters, which its OD records point into. Stored as bytes; no member initializers, so the table is in
25// .bss (set_pdo_table() fills it with PDO_DISABLED).
26struct PdoParams {
28 std::array<uint32_t, 8> map;
29 uint16_t inhibit_time; // TPDO only, 100 us
30 uint16_t event_timer; // ms
32 uint8_t map_count;
33};
34// COB-ID bit 31: not valid; event-driven transmission (254)
35static constexpr PdoParams PDO_DISABLED{0x80000000, {}, 0, 0, 254, 0};
36#endif
37
38void discard_pending_tx(CO_CANmodule_t *mod, CO_CANtx_t *buf);
39
40// NMTState uses CANopenNode's values (static_asserts in canopen.cpp)
41inline NMTState to_nmt_state(CO_NMT_internalState_t state) { return static_cast<NMTState>(state); }
42
43// Other components configure the node in two phases:
44// - Build time (Python codegen): enable_sdo_client(), enable_nmt_master(), request_pdos(), enable_sdo_block() and
45// node monitoring (heartbeat_clients, register_node(heartbeat_timeout=...)). These set defines and build flags.
46// - Before the hub's setup(): OD entries and handlers (get_od(), declared with canopen.request_od()),
47// configure_tpdo() / configure_rpdo() (declared with canopen.request_pdos()), identity and
48// device information, from codegen setters or a setup() with priority above the hub's
49// (setup_priority::HARDWARE - 1). Later ones are logged as errors and ignored.
50// The rest is runtime API: add_frame_listener() and the callbacks (any time), send_frame(), SDO requests (they wait for
51// the hub's setup()), send_nmt() and write_od() / read_od() (fail before it) and request_tpdo() (does nothing before
52// it). The hub's setup() runs before most components' setup() and the default on_boot automations.
53//
54// Client-only mode: without a node id (NO_NODE_ID) the hub is no CANopen node, only an SDO client on the bus (plus
55// raw frames). CANopenNode's node part (NMT, heartbeat, EMCY, SDO server) isn't initialised, so it isn't linked either.
56//
57// The implementation is split by feature: canopen.cpp (setup, processing, NMT), driver_can.cpp (CANopenNode's CAN
58// driver, frame reception and transmission), device_info.cpp (identity, device information, SDO server), od.cpp
59// (the object dictionary), od_handler.cpp (OD handlers), node_monitor.cpp (heartbeat consumer), frames.cpp (raw
60// frames, heartbeat / EMCY callbacks), sdo_client.cpp, nmt_master.cpp, pdo.cpp and pdo_storage.cpp (0x1010 / 0x1011,
61// optional). canopen_node.h: base of profile components.
63 public:
64 // CiA 301 node ids are 1..127; 0 is reserved (NMT broadcast), so it can't clash with a real node. It's also
65 // CANopenNode's "no own node" value (CO_SDOclient_init()).
66 static constexpr uint8_t NO_NODE_ID = 0;
67
68 CANopenComponent(canbus::Canbus *canbus, uint8_t node_id) : canbus_(canbus), node_id_(node_id) {}
69 // no node id: SDO client only, see above
70 bool is_client_only() const { return this->node_id_ == NO_NODE_ID; }
71
72 void setup() override;
73 void loop() override;
74 void dump_config() override;
75 // after canbus, before on_boot (600)
76 float get_setup_priority() const override { return setup_priority::HARDWARE - 1.0f; }
77
78#ifdef USE_CANOPEN_LOCAL_NODES
79 // Other canopen nodes on the same canbus, as a ring (codegen; USE_CANOPEN_LOCAL_NODES only when a canbus has two or
80 // more): a frame one of them sends is also received by the others, since a CAN controller doesn't receive its own
81 // frames. nullptr = no other local node.
83#endif
84#ifdef USE_CANOPEN_NODE
85 void set_heartbeat_interval(uint16_t ms) { this->hb_producer_ms_ = ms; }
86 // NMT state after boot: OPERATIONAL (default) or PRE_OPERATIONAL (until an NMT master, or set_nmt_state(), starts
87 // the node)
88 void set_start_operational(bool operational) { this->start_operational_ = operational; }
89#endif
90 void set_response_timeout(uint16_t ms) { this->response_timeout_ms_ = ms; }
91
92 // Our own NMT state (UNKNOWN before setup, and without a node id) and its changes, by an NMT master or
93 // set_nmt_state()
94#ifdef USE_CANOPEN_NODE
95 NMTState get_nmt_state() const { return this->nmt_state_; }
96 template<typename F> void add_on_nmt_state_callback(F &&callback) {
97 this->nmt_state_callback_.add(std::forward<F>(callback));
98 }
99#else
101#endif
102 // Moves our own node to OPERATIONAL, PRE_OPERATIONAL or STOPPED (no NMT master needed), right away (called from an
103 // automation the node's processing runs: after it). False while a previous command for us waits to be applied.
105
106 // Used by the CANopenNode driver (driver_can.cpp) and send_frame(): sends a standard-ID frame (ident bit 11 =
107 // RTR) on the canbus and, once sent, queues it for the other local nodes. Each takes its queued frames in its next
108 // loop(), one at a time and in bus order, like frames from the bus, so no node's processing runs inside another's.
109 bool transmit(uint16_t ident, const uint8_t *data, uint8_t len);
110 // Used by the CANopenNode driver: CO_process() flushes the queued frames too, but the hub flushes them only once,
111 // early in loop(): not while a received frame is processed (on ESP32 a refused frame can block for the controller's
112 // enqueue timeout), nor again in loop()'s CO_process() (the SDO response timer restarts after that one flush).
113 bool flush_held() const { return this->hold_flush_; }
114
115#ifdef USE_CANOPEN_NODE
116 // --- Identity and device information (device_info.cpp) ---
117 // Identity (0x1018) and device information (0x1008 device name, 0x1009 hardware version, 0x100A software
118 // version). Before setup() only; the strings must outlive the component. Defaults: identity 0, the node's name,
119 // no hardware version, ESPHOME_VERSION.
120 void set_identity(uint32_t vendor_id, uint32_t product_code, uint32_t revision_number, uint32_t serial_number) {
121 this->identity_ = {vendor_id, product_code, revision_number, serial_number};
122 }
123 void set_device_name(const char *name) { this->device_name_ = name; }
124 // codegen counts 0x1009 for hardware_version: a component calling this declares it with request_od(hub, vars=1)
125 void set_hardware_version(const char *version) { this->hardware_version_ = version; }
126 void set_software_version(const char *version) { this->software_version_ = version; }
127#endif
128
129 // --- Object dictionary (od.cpp) ---
130 // Entries and handlers (OdObject) are added before setup() only (see above). The storage must outlive the component.
131 ObjectDictionary &get_od() { return this->od_; }
132
133 // --- OD access through the handlers: ObjectDictionary::write() / read() ---
134 OdResult write_od(uint16_t index, uint8_t sub, const void *data, size_t len) {
135 return this->od_.write(index, sub, data, len);
136 }
137 OdResult read_od(uint16_t index, uint8_t sub, void *data, size_t max_len, size_t *len) {
138 return this->od_.read(index, sub, data, max_len, len);
139 }
140
141 // --- Node monitoring (node_monitor.cpp) ---
142 // events of all monitored nodes: (node_id, event, state)
143 template<typename F> void add_on_node_event_callback(F &&callback) {
144 this->node_event_callback_.add(std::forward<F>(callback));
145 }
146#ifdef USE_CANOPEN_NODE_MONITOR
147 // Heartbeat monitoring of another node (CANopenNode heartbeat consumer, OD 0x1016; canopen.enable_node_monitor() in
148 // codegen). Before setup() only, from codegen (cg.slot_list() sizes the storage). Registering a node again keeps the
149 // shortest timeout. Node id 0, above 127, our own, or a timeout of 0 is logged and ignored.
150 SLOT_LIST_REQUIRES(ESPHOME_CANOPEN_HEARTBEAT_CLIENTS)
151 void monitor_node(uint8_t node_id, uint16_t timeout_ms) { this->monitor_node_(node_id, timeout_ms); }
152 // state of a monitored node from its last heartbeat; UNKNOWN / false for nodes that aren't monitored
153 NMTState get_node_state(uint8_t node_id);
154 bool is_node_online(uint8_t node_id);
155#else
156 // no monitored nodes: the heartbeat consumer isn't built
157 NMTState get_node_state(uint8_t /*node_id*/) { return NMTState::NMT_STATE_UNKNOWN; }
158 bool is_node_online(uint8_t /*node_id*/) { return false; }
159#endif
160
161 // --- Raw frames (frames.cpp) ---
162 // every heartbeat / EMCY frame on the bus, from any node (our own frames aren't received; those of other local
163 // nodes are)
164#ifdef USE_CANOPEN_HEARTBEAT
165 template<typename F> void add_on_heartbeat_callback(F &&callback) {
166 this->heartbeat_callback_.add(std::forward<F>(callback));
167 }
168#endif
169#ifdef USE_CANOPEN_EMCY
170 template<typename F> void add_on_emcy_callback(F &&callback) { this->emcy_callback_.add(std::forward<F>(callback)); }
171#endif
172 // Raw frames the OD doesn't describe (e.g. other devices' PDOs). The callback gets every standard-ID data frame
173 // with (can_id ^ id) & mask == 0, after CANopenNode has seen it. Can be called before or after setup(), also from a
174 // frame callback. Adding a listener twice does nothing; each hub needs its own listener object. It can't be removed
175 // and must stay alive (make it static).
176 void add_frame_listener(FrameListener &listener);
177 // Sends a standard-ID data frame now. Returns false for a CAN ID above 0x7FF, more than 8 bytes, or if the canbus
178 // platform refuses it (e.g. TX buffers full); it isn't queued or retried, unlike CANopenNode's own frames.
179 bool send_frame(uint32_t can_id, const uint8_t *data, size_t len);
180
181#ifdef USE_CANOPEN_SDO_CLIENT
182 // --- SDO client (sdo_client.cpp) ---
183 // SDO client (one channel, requests run one after another in FIFO order). Every request ends in exactly one
184 // callback: accepted ones from loop() / frame processing after the transfer, rejected ones (queue full, invalid
185 // arguments, failed hub) synchronously before the call returns false. Requests made before setup() wait in the
186 // queue (e.g. from on_boot); a failed setup() rejects them. Requests to our own node id are served from our object
187 // dictionary, without CAN frames.
188
189 // expected_size 1/2/4 must match the reply's width, 0 accepts any up to 4
190 bool read_sdo(uint8_t node_id, uint16_t index, uint8_t sub, uint8_t expected_size, SDOCallback callback,
191 void *context);
192 template<typename T>
193 bool read_sdo(uint8_t node_id, uint16_t index, uint8_t sub, SDOCallback callback, void *context) {
194 static_assert(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4, "SDO values are 1, 2 or 4 bytes");
195 return this->read_sdo(node_id, index, sub, sizeof(T), callback, context);
196 }
197 // size: 1, 2 or 4 bytes
198 bool write_sdo(uint8_t node_id, uint16_t index, uint8_t sub, uint32_t value, uint8_t size,
199 SDOCallback callback = nullptr, void *context = nullptr);
200 template<typename T>
201 bool write_sdo(uint8_t node_id, uint16_t index, uint8_t sub, T value, SDOCallback callback = nullptr,
202 void *context = nullptr) {
203 static_assert(sizeof(T) <= 4, "SDO values are at most 4 bytes");
204 uint32_t raw = 0;
205 std::memcpy(&raw, &value, sizeof(T));
206 return this->write_sdo(node_id, index, sub, raw, sizeof(T), callback, context);
207 }
208 // buffer transfers (strings, domains): segmented (every server supports it, block transfer is optional);
209 // the buffers are the caller's and must stay valid until the callback (so not on the stack).
210 // read_sdo_data(): an object longer than capacity is aborted; reply.data is data.
211 bool read_sdo_data(uint8_t node_id, uint16_t index, uint8_t sub, uint8_t *data, size_t capacity, SDOCallback callback,
212 void *context);
213 bool write_sdo_data(uint8_t node_id, uint16_t index, uint8_t sub, const uint8_t *data, size_t len,
214 SDOCallback callback = nullptr, void *context = nullptr);
215 // Drops all queued requests of context and aborts its transfer in flight, without callbacks.
216 void cancel_sdo(void *context);
217#endif
218
219#ifdef USE_CANOPEN_NMT_MASTER
220 // --- NMT master (nmt_master.cpp; with a canopen.nmt action or nmt_master: true) ---
221 // NMT command to node_id (0 = all nodes; for our own id or 0 it also applies to us, right away, or after the
222 // processing when called from an automation it runs). False (logged) before the hub's setup(), without node id, for
223 // an id above 127, while the previous command still waits to be sent, for us or all nodes while a command for us
224 // waits to be applied, or when called again from inside its own send (a log handler).
225 bool send_nmt(uint8_t node_id, NMTCommand command);
226#endif
227
228#ifdef USE_CANOPEN_PDO
229 // --- PDOs (pdo.cpp, pdo_storage.cpp) ---
230 // Our own PDOs, on a hub with a node id: canopen.request_pdos() reserves PDO 0..n - 1 of each kind, with their
231 // communication and mapping records (0x1400 / 0x1600 RPDO, 0x1800 / 0x1A00 TPDO, changeable over SDO); configuring
232 // a higher number fails the hub's setup(), PDOs left unconfigured (or without mappings) stay disabled.
233 // COB-IDs are 11-bit IDs outside the ranges CiA 301 restricts; mapped objects need OD_TPDO / OD_RPDO (RPDO data
234 // reaches their handler); transmission types 254 / 255 only (no SYNC); PDOs run only in OPERATIONAL.
235 // False (logged) for an invalid configuration or after setup. A mapping that doesn't match the OD is found at
236 // setup(): CANopenNode disables that PDO, logged as an error. PDO numbers are per hub: configuring one again replaces
237 // it, so components sharing a hub use different numbers.
238 bool configure_tpdo(uint8_t n, uint32_t cob_id, std::initializer_list<PdoMapping> mappings,
239 uint16_t event_timer_ms = 0, uint16_t inhibit_time_100us = 0, uint8_t transmission_type = 254);
240 bool configure_rpdo(uint8_t n, uint32_t cob_id, std::initializer_list<PdoMapping> mappings,
241 uint16_t event_timer_ms = 0, uint8_t transmission_type = 254);
242 // sends TPDO n at the next processing. True means the request is set (a disabled TPDO takes it and sends nothing);
243 // false before setup() or for a TPDO number past the reserved ones.
244 bool request_tpdo(uint8_t n);
245 // sends the TPDO that maps index:sub (an entry with a handler, sub < 32). True means the request flag is set: a frame
246 // goes out only if a TPDO maps the entry; false without TPDOs, before setup() or for another entry. CANopenNode has
247 // one request flag per sub-entry: if several TPDOs map it, only the first one processed is sent.
248 bool request_tpdo(uint16_t index, uint8_t sub);
249 // from codegen, RPDOs first, before any configure_*pdo(): all disabled
250 void set_pdo_table(PdoParams *pdos, uint8_t rpdo_count, uint8_t tpdo_count) {
251 this->pdos_ = pdos;
252 this->rpdo_count_ = rpdo_count;
253 this->tpdo_count_ = tpdo_count;
254 for (size_t i = 0; i < this->pdo_count_(); i++)
255 pdos[i] = PDO_DISABLED;
256 }
257#ifdef USE_CANOPEN_PDO_STORAGE
258 // From codegen (request_pdos(storage=True)): a hash of the hub's id. 0x1010 / 0x1011 "save" stores the PDO
259 // parameters for the next boot, "load" restores the defaults; parameters stored from other defaults or hubs are
260 // ignored.
262#endif
263#endif
264
265 protected:
266 void on_frame_(const canbus::CanFrame &frame);
267 // a received frame, from the bus or another local node: receive_(), then the processing it needs at once
268 void handle_frame_(uint16_t ident, const uint8_t *data, uint8_t len);
270 bool receive_(uint16_t ident, const uint8_t *data, uint8_t len);
271#ifdef USE_CANOPEN_LOCAL_NODES
272 // Frames other local nodes sent, waiting for this node's loop(), oldest first (local_queue_): like a controller's
273 // receive FIFO, so that back-to-back frames to one CANopenNode object (it keeps one per object) don't overwrite each
274 // other. Allocated in setup() when there are other local nodes. A frame that finds it full is lost, as on a bus, and
275 // counted.
276 static constexpr uint8_t LOCAL_QUEUE_SIZE = 16;
277 struct LocalFrame {
278 uint16_t ident;
279 uint8_t len;
280 std::array<uint8_t, 8> data;
281 };
282 void queue_local_(uint16_t ident, const uint8_t *data, uint8_t len);
283 void deliver_local_();
284 // A bus frame reaches the local nodes' canbus callbacks one after another: the first one queues it for the others
285 // before it handles it, so what it sends in reply lands behind the frame in their queues, as on a bus. The others
286 // then take it from their queue instead of handling it directly (bus_frame_staged_).
287 void stage_bus_frame_(uint16_t ident, const uint8_t *data, uint8_t len);
288#endif
289 // A client-only hub with no request queued or running and no frame waiting to be resent. A node always has work
290 // (heartbeat, PDO timers).
291 bool idle_() const;
292 // CO_process() and our node's own processing: per received frame and in loop()
293 void process_node_();
294#ifdef CANOPEN_SDO_BLOCK_SIZE
295 // the rest of an upload block, from loop(): while the bus takes the frames and the other local nodes have room, for
296 // at most UPLOAD_BURST_US
297 static constexpr uint32_t UPLOAD_BURST_US = 10000;
298 void send_upload_block_();
299#ifdef USE_CANOPEN_LOCAL_NODES
300 // another local node's queue is at least half full
301 bool local_queues_busy_() const;
302#endif
303#endif
304#ifdef USE_CANOPEN_NODE
305 // CANopenNode keeps one NMT command for us until CO_process(), where a received NMT frame or another local command
306 // would replace it: our own commands are applied right away (not from inside the processing: there it waits for the
307 // next one)
308 void apply_nmt_command_();
309 bool nmt_command_pending_() const;
310#endif
311 // marks the hub failed and ends the requests queued before setup()
312 void fail_setup_(const LogString *reason);
313 // The features' parts of setup(), called in this order: add_*_od_() add OD entries (before the OD is finalized),
314 // config_*_() fill in their CO_config_t counts and entries, init_*_() run once CANopenNode is initialised.
315
317 CO_t *co_{nullptr};
318 CO_config_t config_{}; // must outlive co_
320 uint16_t response_timeout_ms_{500};
321 uint8_t node_id_;
322 bool hold_flush_{false};
323#ifdef USE_CANOPEN_LOCAL_NODES
326 uint16_t local_dropped_{0}; // local and bus frames lost on a full local_queue_, logged by deliver_local_()
327 // the current bus frame is already in local_queue_ (staged by the local node whose callback ran first); set and
328 // cleared within one frame, since canbus calls all callbacks for a frame before it reads the next
329 bool bus_frame_staged_{false};
330#endif
331
332#ifdef USE_CANOPEN_NODE
333 // --- Identity and device information (device_info.cpp) ---
335 void add_device_info_od_();
336 void config_device_info_(CO_config_t &cfg);
338
340 uint32_t cob_emcy_{0x80}; // 0x1014, CANopenNode adds the node id
341 uint32_t last_us_{0}; // the node's clock (CO_process(), PDOs)
342 uint32_t reset_deadline_ms_{0}; // NMT reset node: reboot time, see reset_pending_
343 uint32_t dev_type_{0}; // 0x1000
344 const char *device_name_{nullptr}; // 0x1008
345 const char *hardware_version_{nullptr}; // 0x1009, only if set
346 const char *software_version_{nullptr}; // 0x100A
347 std::array<uint32_t, 4> identity_{}; // 0x1018:1..4
348 // 0x1200 (SDO server 1): CANopenNode fills in the default COB-IDs 0x600 / 0x580 + node id
351 uint16_t hb_producer_ms_{5000}; // 0x1017
352 uint8_t err_reg_{0}; // 0x1001
353 uint8_t identity_highest_sub_{4}; // 0x1018
354 uint8_t sdo_srv_highest_sub_{2}; // 0x1200
357 // NMT reset node: reboot once the queued frames are sent (and RESET_TX_GRACE_MS later)
358 bool reset_pending_{false};
359 bool processing_{false}; // inside process_node_(), also in the automations it runs
360#ifdef USE_CANOPEN_NMT_MASTER
361 bool nmt_sending_{false}; // inside CO_NMT_sendCommand(): guards send_nmt() against a log handler calling it again
362#endif
363#endif // USE_CANOPEN_NODE
364
365 // --- Node monitoring (node_monitor.cpp) ---
366#ifdef USE_CANOPEN_NODE_MONITOR
367 uint8_t hb_cons_count_{0}; // 0x1016:0; first, so it packs with the node's small members
368#endif
369 void node_event_(uint8_t node_id, NodeEvent event, NMTState state);
371#ifdef USE_CANOPEN_NODE_MONITOR
372 void monitor_node_(uint8_t node_id, uint16_t timeout_ms);
374 void config_node_monitor_(CO_config_t &cfg);
375 void init_node_monitor_();
376 // the heartbeat consumer, in every NMT state after initialisation (see init_node_monitor_())
379 static void on_hb_started(uint8_t node_id, uint8_t idx, void *object);
380 static void on_hb_nmt_changed(uint8_t node_id, uint8_t idx, CO_NMT_internalState_t state, void *object);
381 static void on_hb_timeout(uint8_t node_id, uint8_t idx, void *object);
382 static void on_hb_remote_reset(uint8_t node_id, uint8_t idx, void *object);
383 static void push_node_event(void *object, uint8_t node_id, NodeEvent event, NMTState state);
385 // Consumer callbacks run before CANopenNode stores the new state, so they only record the event for after
386 // from CO_process(): at most 2 per monitored node per pass
393 // 0x1016:1.., (node_id << 16) | timeout_ms
395#endif
396
397 // --- Raw frames (frames.cpp) ---
398 // frame listeners and heartbeat / EMCY callbacks for a received frame, after CANopenNode
399 void dispatch_frame_(const CO_CANrxMsg_t &msg);
400 void check_frame_listener_(uint16_t can_id, uint16_t mask);
402 // Compiled only when on_heartbeat / on_emcy are configured, so never empty: no lazy allocation needed
403#ifdef USE_CANOPEN_HEARTBEAT
405#endif
406#ifdef USE_CANOPEN_EMCY
407 CallbackManager<void(uint8_t, const Emergency &)> emcy_callback_;
408#endif
409
410#ifdef USE_CANOPEN_SDO_CLIENT
411 // --- SDO client (sdo_client.cpp) ---
413 struct SDORequest {
414 uint8_t node_id;
415 uint8_t sub;
417 uint8_t size; // read: expected size (0 = any); write: value size
418 uint16_t index;
419 uint16_t len; // data length (READ_DATA: capacity)
420 union {
421 uint32_t value; // WRITE
422 uint8_t *data; // *_DATA, owned by the caller
423 };
425 void *context;
426 };
427 static constexpr size_t SDO_QUEUE_SIZE = 16;
428 bool sdo_idle_() const {
429 return !this->sdo_busy_ && this->sdo_queue_.empty() && !this->sdo_abort_pending_ && this->sdo_abort_guard_us_ == 0;
430 }
431 void add_sdo_client_od_();
432 void config_sdo_client_(CO_config_t &cfg);
433 // client-only mode; a node's client is initialised by CO_CANopenInit()
434 bool init_sdo_client_();
435 bool queue_sdo_(const SDORequest &request);
436 void reject_queued_sdo_();
437 bool sdo_stopped_() const;
438 // the active request is served from our own OD (CO_CONFIG_SDO_CLI_LOCAL), not over the bus
439 bool sdo_is_local_() const {
440#ifdef USE_CANOPEN_NODE
441 return !this->is_client_only() && this->sdo_active_.node_id == this->node_id_;
442#else
443 return false;
444#endif
445 }
446 void stop_sdo_();
447 bool sdo_reply_is_stale_(const uint8_t *data, uint8_t len) const;
448 void process_sdo_(uint32_t dt_us);
449 // true when an overlong read ended the request
450 bool drain_upload_(uint32_t dt_us, CO_SDO_return_t &ret, CO_SDO_abortCode_t &abort);
451 CO_SDO_return_t start_sdo_();
452 void finish_sdo_(SDOResult result, uint32_t abort_code);
453 void abort_sdo_();
454 // ends an abort the bus refused for a response timeout, then runs down the guard after it (ABORT_GUARD_US)
455 void process_sdo_abort_(uint32_t dt_us);
458 // bytes handed to the fifo (writes) or received, including those past the buffer (reads)
459 size_t sdo_len_{0};
460 uint32_t sdo_last_ms_{0}; // loop time the SDO client was last given
461 // after a cancel: while the abort waits to be sent, the time left to send it; once sent, the time left before a
462 // request may start
464 // OD 0x1280 (SDO client parameter, with sdo_cli_highest_sub_ and sdo_cli_node_), set up per request
467 std::array<uint8_t, 4> sdo_rx_value_{};
469 uint8_t sdo_cli_node_{0};
470 bool sdo_busy_{false};
472 bool sdo_cancel_pending_{false}; // cancel_sdo() hit the active transfer: process_sdo_() aborts it
473#endif
474
475#ifdef USE_CANOPEN_PDO
476 // --- PDOs (pdo.cpp) ---
477 void add_pdo_od_();
478 void config_pdo_(CO_config_t &cfg);
479 bool init_pdo_();
480 // after init: the enabled PDOs CANopenNode disabled (a mapping that doesn't match the OD)
481 void log_invalid_pdos_();
482 void process_pdo_(uint32_t dt_us);
483 bool configure_pdo_(bool tpdo, uint8_t n, uint32_t cob_id, std::initializer_list<PdoMapping> mappings,
484 uint16_t event_timer_ms, uint16_t inhibit_time_100us, uint8_t transmission_type);
485 // drops TPDO frames still queued for the controller (on leaving OPERATIONAL)
487 size_t pdo_count_() const { return this->rpdo_count_ + this->tpdo_count_; }
488 bool has_pdos_() const { return this->pdo_count_() > 0; }
489 // RPDOs, then TPDOs
490 PdoParams *pdos_{nullptr};
491 uint8_t rpdo_count_{0};
492 uint8_t tpdo_count_{0};
493 bool pdo_not_reserved_{false}; // configure_*pdo() for a PDO request_pdos() didn't reserve: setup() fails
494#endif
495
496#ifdef USE_CANOPEN_PDO_STORAGE
497 // --- PDO parameter storage, 0x1010 / 0x1011 (pdo_storage.cpp, request_pdos(storage=True)) ---
498 // add_pdo_storage_od_() loads the stored parameters, so it runs before the PDO records are added
499 void add_pdo_storage_od_();
500 bool init_pdo_storage_();
501 void load_pdos_();
502 bool store_pdos_();
504 static ODR_t storage_store(CO_storage_entry_t *entry, CO_CANmodule_t *module);
505 static ODR_t storage_restore(CO_storage_entry_t *entry, CO_CANmodule_t *module);
506 CO_storage_t storage_{};
507 CO_storage_entry_t storage_entry_{};
508 // the stored PDO table, and a marker that it is valid (cleared by "load")
511 // set_pdo_storage_key() until setup(), then the preference key and the valid marker's value (never
512 // PDO_STORE_INVALID)
514#endif
515};
516
517} // namespace esphome::canopen
uint8_t raw[35]
Definition bl0939.h:0
Fixed-capacity circular buffer - allocates once at runtime, never reallocates.
Definition helpers.h:588
Fixed-size circular buffer with FIFO semantics and iteration support.
Definition helpers.h:468
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:335
bool read_sdo(uint8_t node_id, uint16_t index, uint8_t sub, uint8_t expected_size, SDOCallback callback, void *context)
void set_heartbeat_interval(uint16_t ms)
Definition canopen.h:85
CallbackManager< void(uint8_t, const Emergency &)> emcy_callback_
Definition canopen.h:407
void set_pdo_storage_key(uint32_t key)
Definition canopen.h:261
bool write_sdo_data(uint8_t node_id, uint16_t index, uint8_t sub, const uint8_t *data, size_t len, SDOCallback callback=nullptr, void *context=nullptr)
void set_start_operational(bool operational)
Definition canopen.h:88
void process_sdo_(uint32_t dt_us)
bool transmit(uint16_t ident, const uint8_t *data, uint8_t len)
void node_event_(uint8_t node_id, NodeEvent event, NMTState state)
void handle_frame_(uint16_t ident, const uint8_t *data, uint8_t len)
bool send_nmt(uint8_t node_id, NMTCommand command)
bool queue_sdo_(const SDORequest &request)
bool write_sdo(uint8_t node_id, uint16_t index, uint8_t sub, uint32_t value, uint8_t size, SDOCallback callback=nullptr, void *context=nullptr)
OdResult read_od(uint16_t index, uint8_t sub, void *data, size_t max_len, size_t *len)
Definition canopen.h:137
static constexpr size_t SDO_QUEUE_SIZE
Definition canopen.h:427
void process_pdo_(uint32_t dt_us)
Definition pdo.cpp:137
void finish_sdo_(SDOResult result, uint32_t abort_code)
void add_on_node_event_callback(F &&callback)
Definition canopen.h:143
bool read_sdo(uint8_t node_id, uint16_t index, uint8_t sub, SDOCallback callback, void *context)
Definition canopen.h:193
static constexpr uint8_t LOCAL_QUEUE_SIZE
Definition canopen.h:276
LazyCallbackManager< void(NMTState)> nmt_state_callback_
Definition canopen.h:339
bool configure_pdo_(bool tpdo, uint8_t n, uint32_t cob_id, std::initializer_list< PdoMapping > mappings, uint16_t event_timer_ms, uint16_t inhibit_time_100us, uint8_t transmission_type)
Definition pdo.cpp:27
void config_pdo_(CO_config_t &cfg)
Definition pdo.cpp:95
void add_on_nmt_state_callback(F &&callback)
Definition canopen.h:96
NMTState get_node_state(uint8_t)
Definition canopen.h:157
bool drain_upload_(uint32_t dt_us, CO_SDO_return_t &ret, CO_SDO_abortCode_t &abort)
static void on_hb_nmt_changed(uint8_t node_id, uint8_t idx, CO_NMT_internalState_t state, void *object)
LazyCallbackManager< void(uint8_t, NodeEvent, NMTState)> node_event_callback_
Definition canopen.h:370
SlotList< uint32_t, ESPHOME_CANOPEN_HEARTBEAT_CLIENTS > hb_cons_
Definition canopen.h:394
bool sdo_reply_is_stale_(const uint8_t *data, uint8_t len) const
OdResult write_od(uint16_t index, uint8_t sub, const void *data, size_t len)
Definition canopen.h:134
void set_pdo_table(PdoParams *pdos, uint8_t rpdo_count, uint8_t tpdo_count)
Definition canopen.h:250
void add_frame_listener(FrameListener &listener)
Definition frames.cpp:10
static constexpr uint32_t UPLOAD_BURST_US
Definition canopen.h:297
bool configure_tpdo(uint8_t n, uint32_t cob_id, std::initializer_list< PdoMapping > mappings, uint16_t event_timer_ms=0, uint16_t inhibit_time_100us=0, uint8_t transmission_type=254)
Definition pdo.cpp:17
SLOT_LIST_REQUIRES(ESPHOME_CANOPEN_HEARTBEAT_CLIENTS) void monitor_node(uint8_t node_id
std::array< uint8_t, 4 > sdo_rx_value_
Definition canopen.h:467
void fail_setup_(const LogString *reason)
Definition canopen.cpp:171
ESPPreferenceObject pdo_pref_
Definition canopen.h:509
FixedRingBuffer< LocalFrame, LOCAL_QUEUE_SIZE > local_queue_
Definition canopen.h:325
void add_on_emcy_callback(F &&callback)
Definition canopen.h:170
ESPPreferenceObject pdo_valid_pref_
Definition canopen.h:510
void on_frame_(const canbus::CanFrame &frame)
bool read_sdo_data(uint8_t node_id, uint16_t index, uint8_t sub, uint8_t *data, size_t capacity, SDOCallback callback, void *context)
static ODR_t storage_store(CO_storage_entry_t *entry, CO_CANmodule_t *module)
NMTState get_node_state(uint8_t node_id)
void set_response_timeout(uint16_t ms)
Definition canopen.h:90
bool send_frame(uint32_t can_id, const uint8_t *data, size_t len)
Definition frames.cpp:43
void check_frame_listener_(uint16_t can_id, uint16_t mask)
Definition frames.cpp:30
void add_on_heartbeat_callback(F &&callback)
Definition canopen.h:165
static void on_hb_timeout(uint8_t node_id, uint8_t idx, void *object)
std::array< uint32_t, 4 > identity_
Definition canopen.h:347
NMTState get_nmt_state() const
Definition canopen.h:95
bool receive_(uint16_t ident, const uint8_t *data, uint8_t len)
Returns whether a CANopenNode object took the frame.
void config_sdo_client_(CO_config_t &cfg)
float get_setup_priority() const override
Definition canopen.h:76
void set_identity(uint32_t vendor_id, uint32_t product_code, uint32_t revision_number, uint32_t serial_number)
Definition canopen.h:120
bool set_nmt_state(NMTState state)
Definition canopen.cpp:367
ObjectDictionary & get_od()
Definition canopen.h:131
CO_storage_entry_t storage_entry_
Definition canopen.h:507
void queue_local_(uint16_t ident, const uint8_t *data, uint8_t len)
static void push_node_event(void *object, uint8_t node_id, NodeEvent event, NMTState state)
void process_node_monitor_(uint32_t dt_us)
static void on_hb_started(uint8_t node_id, uint8_t idx, void *object)
void monitor_node_(uint8_t node_id, uint16_t timeout_ms)
void stage_bus_frame_(uint16_t ident, const uint8_t *data, uint8_t len)
StaticRingBuffer< SDORequest, SDO_QUEUE_SIZE > sdo_queue_
Definition canopen.h:456
CANopenComponent * next_local_
Definition canopen.h:324
void set_next_local(CANopenComponent *next)
Definition canopen.h:82
StaticVector< PendingNodeEvent, 2 *ESPHOME_CANOPEN_HEARTBEAT_CLIENTS > pending_node_events_
Definition canopen.h:392
void set_hardware_version(const char *version)
Definition canopen.h:125
bool is_node_online(uint8_t node_id)
void config_device_info_(CO_config_t &cfg)
CANopenComponent(canbus::Canbus *canbus, uint8_t node_id)
Definition canopen.h:68
static void on_hb_remote_reset(uint8_t node_id, uint8_t idx, void *object)
void dispatch_frame_(const CO_CANrxMsg_t &msg)
Definition frames.cpp:49
bool write_sdo(uint8_t node_id, uint16_t index, uint8_t sub, T value, SDOCallback callback=nullptr, void *context=nullptr)
Definition canopen.h:201
static constexpr uint8_t NO_NODE_ID
Definition canopen.h:66
static ODR_t storage_restore(CO_storage_entry_t *entry, CO_CANmodule_t *module)
void set_software_version(const char *version)
Definition canopen.h:126
void config_node_monitor_(CO_config_t &cfg)
void set_device_name(const char *name)
Definition canopen.h:123
bool configure_rpdo(uint8_t n, uint32_t cob_id, std::initializer_list< PdoMapping > mappings, uint16_t event_timer_ms=0, uint8_t transmission_type=254)
Definition pdo.cpp:22
CallbackManager< void(uint8_t, NMTState)> heartbeat_callback_
Definition canopen.h:404
void process_sdo_abort_(uint32_t dt_us)
OdResult write(uint16_t index, uint8_t sub, const void *data, size_t len)
OdResult read(uint16_t index, uint8_t sub, void *data, size_t max_len, size_t *len)
const char * key
NameCopy * next
bool state
Definition fan.h:2
int ret
NMTState to_nmt_state(CO_NMT_internalState_t state)
Definition canopen.h:41
void discard_pending_tx(CO_CANmodule_t *mod, CO_CANtx_t *buf)
void(*)(void *context, const SDOReply &reply) SDOCallback
Definition types.h:62
constexpr float HARDWARE
For components that deal with hardware and are very important like GPIO switch.
Definition component.h:44
uint32_t value
Definition hal.cpp:59
const void size_t len
Definition hal.h:68
std::conditional_t< N==0, EmptyList< T >, StaticVector< T, N > > SlotList
StaticVector<T, N>, or EmptyList<T> when N is 0.
Definition helpers.h:444
uint16_t size
Definition helpers.cpp:44
uint16_t uint16_t & capacity
Definition helpers.cpp:44
static void uint32_t
One CAN frame as passed between the bus and its driver.
Definition canbus.h:143
std::array< uint32_t, 8 > map
Definition canopen.h:28
char serial_number[10]
Definition sun_gtil2.cpp:15
esp_err_t result