ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
canopen.cpp
Go to the documentation of this file.
1// CANopenComponent: setup (building the OD and initialising CANopenNode), processing, our own NMT state. The other
2// features are in their own files, see canopen.h.
3#include "canopen.h"
4
5#include <array>
6
7#ifdef CANOPEN_SDO_BLOCK_SIZE
8#include "301/crc16-ccitt.h"
9#endif
10
12#include "esphome/core/hal.h"
14#include "esphome/core/log.h"
16
17namespace esphome::canopen {
18
19ESPHOME_LOG_TAG(TAG, "canopen");
20
21#ifdef USE_CANOPEN_NODE
22// NMT reset node: once CANopenNode's queue is empty, the CAN controller's time to send what it holds (the canbus API
23// only says a frame was accepted): 4 frames at 10 kbit/s, the lowest CiA 301 rate
24static constexpr uint32_t RESET_TX_GRACE_MS = 60;
25// and the extra time it waits at most for the queue to empty (e.g. our own broadcast reset_node)
26static constexpr uint32_t RESET_FLUSH_EXTRA_MS = 80;
27#endif
28
29// indexed by the state's position in NMT_STATES; the last entry for other values
30PROGMEM_STRING_TABLE(NMTStateStrings, "bootup", "stopped", "operational", "pre-operational", "unknown");
31static_assert(NMT_STATES.size() == NMTStateStrings::LAST_INDEX);
32
34 for (size_t i = 0; i < NMT_STATES.size(); i++) {
35 if (NMT_STATES[i] == state)
36 return NMTStateStrings::get_log_str(static_cast<uint8_t>(i), NMTStateStrings::LAST_INDEX);
37 }
38 return NMTStateStrings::get_log_str(NMTStateStrings::LAST_INDEX, NMTStateStrings::LAST_INDEX);
39}
40
41// to_nmt_state() casts: NMTState uses CANopenNode's values; CO_NMT_UNKNOWN (-1) becomes NMT_STATE_UNKNOWN (255)
42static_assert(static_cast<uint8_t>(CO_NMT_INITIALIZING) == static_cast<uint8_t>(NMTState::NMT_STATE_BOOTUP));
43static_assert(static_cast<uint8_t>(CO_NMT_STOPPED) == static_cast<uint8_t>(NMTState::NMT_STATE_STOPPED));
44static_assert(static_cast<uint8_t>(CO_NMT_OPERATIONAL) == static_cast<uint8_t>(NMTState::NMT_STATE_OPERATIONAL));
45static_assert(static_cast<uint8_t>(CO_NMT_PRE_OPERATIONAL) ==
46 static_cast<uint8_t>(NMTState::NMT_STATE_PRE_OPERATIONAL));
47static_assert(static_cast<uint8_t>(CO_NMT_UNKNOWN) == static_cast<uint8_t>(NMTState::NMT_STATE_UNKNOWN));
48
50 if (this->canbus_->is_failed()) {
51 this->fail_setup_(LOG_STR("CAN bus failed"));
52 return;
53 }
54 // USE_CANOPEN_NODE: some hub has a node id. Without it nothing references CANopenNode's node part, so it isn't
55 // linked. A hub without node id gets only the CAN module and the SDO client, whose 0x1280 is its whole OD.
56 auto &od = this->od_;
57 auto &cfg = this->config_;
58#ifdef USE_CANOPEN_NODE
59 const bool node = !this->is_client_only();
60 if (node) {
61 od.add_var(0x1001, ODA_SDO_R, &this->err_reg_, sizeof(this->err_reg_));
62 // read only: without CO_CONFIG_EM_PROD_CONFIGURABLE a write wouldn't reach the EMCY producer
63 od.add_var(0x1014, ODA_SDO_R, &this->cob_emcy_, sizeof(this->cob_emcy_));
64 od.add_var(0x1017, ODA_SDO_RW, &this->hb_producer_ms_, sizeof(this->hb_producer_ms_));
65 this->add_device_info_od_();
66#ifdef USE_CANOPEN_NODE_MONITOR
68#endif
69#ifdef USE_CANOPEN_PDO
70#ifdef USE_CANOPEN_PDO_STORAGE
71 this->add_pdo_storage_od_();
72#endif
73 this->add_pdo_od_();
74#endif
75 }
76#endif
77#ifdef USE_CANOPEN_SDO_CLIENT
78 this->add_sdo_client_od_();
79#endif
80 if (!od.finalize()) {
81 this->fail_setup_(LOG_STR("invalid object dictionary"));
82 return;
83 }
84#ifdef USE_CANOPEN_PDO
85 if (this->pdo_not_reserved_) {
86 this->fail_setup_(LOG_STR("PDO not reserved"));
87 return;
88 }
89#endif
90#ifdef USE_CANOPEN_NODE
91 if (node) {
92 cfg.CNT_NMT = 1;
93 cfg.ENTRY_H1017 = od.find(0x1017);
94 cfg.CNT_EM = 1;
95 cfg.ENTRY_H1001 = od.find(0x1001);
96 cfg.ENTRY_H1014 = od.find(0x1014);
97 cfg.CNT_ARR_1003 = 8; // EM fifo size, needs >= 1
98 this->config_device_info_(cfg);
99#ifdef USE_CANOPEN_NODE_MONITOR
100 this->config_node_monitor_(cfg);
101#endif
102#ifdef USE_CANOPEN_PDO
103 this->config_pdo_(cfg);
104#endif
105 }
106#endif
107#ifdef USE_CANOPEN_SDO_CLIENT
108 this->config_sdo_client_(cfg);
109#endif
110
111 uint32_t heap = 0;
112 this->co_ = CO_new(&cfg, &heap);
113 if (this->co_ == nullptr) {
114 this->fail_setup_(LOG_STR("CO_new failed"));
115 return;
116 }
117 CO_ReturnError_t err = CO_CANinit(this->co_, this, 0);
118 if (err != CO_ERROR_NO) {
119 ESP_LOGE(TAG, "CO_CANinit failed: %d", err);
120 this->fail_setup_(LOG_STR("CO_CANinit failed"));
121 return;
122 }
123#ifdef USE_CANOPEN_NODE
124 if (node) {
125#ifdef USE_CANOPEN_PDO_STORAGE
126 if (!this->init_pdo_storage_()) {
127 this->fail_setup_(LOG_STR("PDO storage init failed"));
128 return;
129 }
130#endif
131 uint32_t err_info = 0;
132 uint16_t nmt_control = this->start_operational_ ? CO_NMT_STARTUP_TO_OPERATIONAL : 0;
133 err = CO_CANopenInit(this->co_, nullptr, nullptr, od.od(), nullptr, nmt_control, 500 /* first HB, ms */, 1000, 0,
134 false, this->node_id_, &err_info);
135 if (err != CO_ERROR_NO) {
136 ESP_LOGE(TAG, "CO_CANopenInit failed: %d (OD 0x%04" PRIx32 ")", err, err_info);
137 this->fail_setup_(LOG_STR("CO_CANopenInit failed"));
138 return;
139 }
140#ifdef USE_CANOPEN_PDO
141 if (!this->init_pdo_()) {
142 this->fail_setup_(LOG_STR("PDO init failed"));
143 return;
144 }
145#endif
146#ifdef USE_CANOPEN_NODE_MONITOR
147 this->init_node_monitor_();
148#endif
149 this->last_us_ = micros();
150 }
151#endif
152#ifdef USE_CANOPEN_SDO_CLIENT
153 // CO_CANopenInit() sets up the client of a node; without it the client is set up on its own
154 if (this->is_client_only() && !this->init_sdo_client_()) {
155 this->fail_setup_(LOG_STR("SDO client init failed"));
156 return;
157 }
158#endif
159 for (const FrameListener *l = this->frame_listeners_; l != nullptr; l = l->next)
160 this->check_frame_listener_(l->can_id, l->mask);
161
162#ifdef USE_CANOPEN_LOCAL_NODES
163 if (this->next_local_ != nullptr && this->next_local_ != this)
164 this->local_queue_.init(LOCAL_QUEUE_SIZE);
165#endif
166 CO_CANsetNormalMode(this->co_->CANmodule);
167 this->canbus_->add_frame_callback([this](const canbus::CanFrame &frame) { this->on_frame_(frame); });
168 ESP_LOGV(TAG, "CANopenNode initialized, node 0x%02x, heap %" PRIu32 " B", this->node_id_, heap);
169}
170
171void CANopenComponent::fail_setup_(const LogString *reason) {
172 this->mark_failed(reason);
173#ifdef USE_CANOPEN_SDO_CLIENT
174 this->reject_queued_sdo_();
175#endif
176}
177
179 if (this->is_client_only()) {
180#ifdef USE_CANOPEN_SDO_CLIENT
181 ESP_LOGCONFIG(TAG,
182 "CANopen (CANopenNode):\n"
183 " Mode: SDO client only (no node ID)\n"
184 " SDO client: response timeout %u ms",
186#endif
187 return;
188 }
189#ifdef USE_CANOPEN_NODE
190 ESP_LOGCONFIG(TAG,
191 "CANopen (CANopenNode):\n"
192 " Node ID: 0x%02x\n"
193 " Heartbeat interval: %u ms\n"
194 " NMT startup: %s",
195 this->node_id_, this->hb_producer_ms_,
196 this->start_operational_ ? LOG_STR_LITERAL("operational") : LOG_STR_LITERAL("pre-operational"));
197#ifdef CANOPEN_SDO_BLOCK_SIZE
198 ESP_LOGCONFIG(TAG, " SDO server: block transfer, download block size %u", CANOPEN_SDO_BLOCK_SIZE);
199#endif
201 this->od_.dump_usage(TAG);
202#ifdef USE_CANOPEN_PDO
203 ESP_LOGCONFIG(TAG, " PDOs reserved: %u RPDO, %u TPDO", this->rpdo_count_, this->tpdo_count_);
204#endif
205#ifdef USE_CANOPEN_SDO_CLIENT
206 ESP_LOGCONFIG(TAG, " SDO client: response timeout %u ms", this->response_timeout_ms_);
207#endif
208#ifdef USE_CANOPEN_NODE_MONITOR
210#endif
211#endif
212}
213
215#ifdef USE_CANOPEN_SDO_CLIENT
216#ifdef USE_CANOPEN_LOCAL_NODES
217 if (!this->local_queue_.empty())
218 return false;
219#endif
220 return this->is_client_only() && this->co_->CANmodule->CANtxCount == 0 && this->sdo_idle_();
221#else
222 return false;
223#endif
224}
225
226// A client-only hub needs time only for a running request or an unsent frame: queue_sdo_(), cancel_sdo() and
227// CO_CANsend() enable the loop again.
229 if (this->idle_()) {
230 this->disable_loop();
231 return;
232 }
233#ifdef USE_CANOPEN_LOCAL_NODES
234 // frames other local nodes sent since the canbus loop delivered the bus's (on_frame_() delivers the older ones first)
235 this->deliver_local_();
236#endif
237#ifdef USE_CANOPEN_SDO_CLIENT
238 // SDO client first: an unsent frame ends at its deadline, before the flush could send it. Time runs only here,
239 // after the canbus loop delivered its frames: a received frame may come before a queued reply.
240 CO_SDOclient_t *cli = this->co_->SDOclient;
241 const bool unsent = cli->CANtxBuff->bufferFull;
243 const uint32_t elapsed = now - this->sdo_last_ms_;
244 // The reply to a sent frame may still wait in the controller behind a capped canbus pass: the time is charged once it
245 // drained, but held at most one response timeout past the deadline, so a saturated bus still times out.
246 if (!this->sdo_busy_ || this->sdo_cancel_pending_ || unsent || !this->canbus_->rx_capped() ||
247 cli->timeoutTimer / 1000 + elapsed >= 2u * this->response_timeout_ms_) {
248 this->process_sdo_(elapsed * 1000);
249 this->sdo_last_ms_ = now;
250 }
251#endif
252 // The only flush of queued frames, also for a node: CO_process() doesn't flush (hold_flush_).
253 CO_CANmodule_process(this->co_->CANmodule);
254#ifdef USE_CANOPEN_SDO_CLIENT
255 // CANopenNode started the response timeout when it queued the frame: start it again now that the frame is sent
256 if (unsent && !cli->CANtxBuff->bufferFull)
257 cli->timeoutTimer = 0;
258#endif
259 if (!this->is_client_only()) {
260 this->hold_flush_ = true;
261 this->process_node_();
262#if defined(USE_CANOPEN_NODE) && defined(CANOPEN_SDO_BLOCK_SIZE)
263 // here only, not per received frame: one burst, and one time budget, per loop pass; an NMT command a send's
264 // callback issues waits for the next pass, as during processing
265 this->processing_ = true;
266 this->send_upload_block_();
267 this->processing_ = false;
268#endif
269 this->hold_flush_ = false;
270 }
271}
272
274#ifdef USE_CANOPEN_NODE
275 this->processing_ = true;
276 uint32_t now = micros();
277 uint32_t dt = now - this->last_us_;
278 this->last_us_ = now;
279 CO_NMT_reset_cmd_t reset = CO_process(this->co_, false, dt, nullptr);
280#ifdef USE_CANOPEN_NODE_MONITOR
281 this->process_node_monitor_(dt);
282 this->dispatch_node_events_();
283#endif
285 if (reset == CO_RESET_APP && !this->reset_pending_) {
286 ESP_LOGW(TAG, "NMT reset node");
287 this->reset_pending_ = true;
288 this->reset_deadline_ms_ = now_ms + RESET_TX_GRACE_MS + RESET_FLUSH_EXTRA_MS;
289 } else if (reset == CO_RESET_COMM) {
290 ESP_LOGW(TAG, "NMT reset communication (not implemented)");
291 }
292 // The reboot waits for the queued frames (loop() flushes them before it processes the node), then for the controller
293 // to send them: a reset_node to all nodes from us would otherwise reboot us before its frame is on the bus.
294 if (this->reset_pending_) {
295 if (this->co_->CANmodule->CANtxCount == 0 &&
296 static_cast<int32_t>(now_ms + RESET_TX_GRACE_MS - this->reset_deadline_ms_) < 0)
297 this->reset_deadline_ms_ = now_ms + RESET_TX_GRACE_MS;
298 if (static_cast<int32_t>(now_ms - this->reset_deadline_ms_) >= 0)
300 }
301#ifdef USE_CANOPEN_PDO
302 this->process_pdo_(dt);
303#endif
304 // CANopenNode's state change callback has no context pointer, so the state is compared here
305 NMTState state = to_nmt_state(CO_NMT_getInternalState(this->co_->NMT));
306 if (state != this->nmt_state_) {
307 this->nmt_state_ = state;
308#ifdef USE_CANOPEN_PDO
309 // PDOs only in OPERATIONAL: a TPDO the controller refused would otherwise go out with the next flush
312#endif
313 ESP_LOGI(TAG, "NMT state: %s", LOG_STR_ARG(nmt_state_to_string(state)));
314 this->nmt_state_callback_.call(state);
315 }
316 this->processing_ = false;
317#endif // USE_CANOPEN_NODE
318}
319
320#if defined(USE_CANOPEN_NODE) && defined(CANOPEN_SDO_BLOCK_SIZE)
322 // CANopenNode sends one upload segment per call and nothing arrives mid-block: send the rest now, while the bus
323 // takes frames (a segment left queued stops it), the other local nodes' queues are under half full (they can't
324 // drain meanwhile), and for at most UPLOAD_BURST_US (a send may block, e.g. esp32_can's tx_enqueue_timeout)
325 CO_SDOserver_t *srv = this->co_->SDOserver;
326 if (srv->state != CO_SDO_ST_UPLOAD_BLK_SUBBLOCK_SREQ)
327 return;
328 const CO_NMT_internalState_t nmt = CO_NMT_getInternalState(this->co_->NMT);
329 const bool pre_or_operational = nmt == CO_NMT_PRE_OPERATIONAL || nmt == CO_NMT_OPERATIONAL;
330 const uint32_t start = micros();
331 while (srv->state == CO_SDO_ST_UPLOAD_BLK_SUBBLOCK_SREQ && !srv->CANtxBuff->bufferFull) {
332#ifdef USE_CANOPEN_LOCAL_NODES
333 if (this->local_queues_busy_())
334 break;
335#endif
336 if (micros() - start >= UPLOAD_BURST_US)
337 break;
338 CO_SDOserver_process(srv, pre_or_operational, 0, nullptr);
339 }
340}
341#endif
342
343#if defined(USE_CANOPEN_LOCAL_NODES) && defined(CANOPEN_SDO_BLOCK_SIZE)
345 for (CANopenComponent *node = this->next_local_; node != nullptr && node != this; node = node->next_local_) {
346 if (node->local_queue_.capacity() != 0 && node->local_queue_.size() >= LOCAL_QUEUE_SIZE / 2)
347 return true;
348 }
349 return false;
350}
351#endif
352
353#ifdef USE_CANOPEN_NODE
354bool CANopenComponent::nmt_command_pending_() const { return this->co_->NMT->internalCommand != CO_NMT_NO_COMMAND; }
355
357 if (this->processing_)
358 return; // an automation the processing runs: applied by the next one
359 // as everywhere the node is processed, without flushing (also when called while a received frame is handled)
360 const bool held = this->hold_flush_;
361 this->hold_flush_ = true;
362 this->process_node_();
363 this->hold_flush_ = held;
364}
365#endif
366
368#ifdef USE_CANOPEN_NODE
369 if (this->co_ == nullptr || this->is_failed() || this->is_client_only())
370 return false;
371 CO_NMT_command_t command;
372 switch (state) {
374 command = CO_NMT_ENTER_OPERATIONAL;
375 break;
377 command = CO_NMT_ENTER_PRE_OPERATIONAL;
378 break;
380 command = CO_NMT_ENTER_STOPPED;
381 break;
382 default:
383 return false;
384 }
385 if (this->nmt_command_pending_()) {
386 ESP_LOGW(TAG, "NMT state %s rejected: the previous command is still pending",
387 LOG_STR_ARG(nmt_state_to_string(state)));
388 return false;
389 }
390 CO_NMT_sendInternalCommand(this->co_->NMT, command);
391 this->apply_nmt_command_();
392 return true;
393#else
394 return false;
395#endif
396}
397
398} // namespace esphome::canopen
399
400#ifdef CANOPEN_SDO_BLOCK_SIZE
401// CO_CONFIG_CRC16_EXTERNAL: CRC-16-CCITT through crc16be(), without CANopenNode's 512-byte table (RAM on ESP8266).
402// CANopenNode only checksums its server buffer, so the length fits crc16be()'s 16 bits.
403static_assert(CO_CONFIG_SDO_SRV_BUFFER_SIZE <= UINT16_MAX);
404// NOLINTNEXTLINE(readability-identifier-naming): the parameter names of CANopenNode's declaration
405extern "C" uint16_t crc16_ccitt(const uint8_t block[], size_t blockLength, uint16_t crc) {
406 return esphome::crc16be(block, static_cast<uint16_t>(blockLength), crc);
407}
408#endif
uint8_t l
Definition bl0906.h:0
uint16_t crc16_ccitt(const uint8_t block[], size_t blockLength, uint16_t crc)
Definition canopen.cpp:405
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:288
void disable_loop()
Disable this component's loop.
bool rx_capped() const
The last receive pass stopped at max_frames_per_loop; more frames may be waiting.
Definition canbus.h:246
void add_frame_callback(F &&callback)
The frame is only valid during the call.
Definition canbus.h:249
void process_sdo_(uint32_t dt_us)
void process_pdo_(uint32_t dt_us)
Definition pdo.cpp:137
static constexpr uint8_t LOCAL_QUEUE_SIZE
Definition canopen.h:276
LazyCallbackManager< void(NMTState)> nmt_state_callback_
Definition canopen.h:339
void config_pdo_(CO_config_t &cfg)
Definition pdo.cpp:95
static constexpr uint32_t UPLOAD_BURST_US
Definition canopen.h:297
void fail_setup_(const LogString *reason)
Definition canopen.cpp:171
FixedRingBuffer< LocalFrame, LOCAL_QUEUE_SIZE > local_queue_
Definition canopen.h:325
void on_frame_(const canbus::CanFrame &frame)
void check_frame_listener_(uint16_t can_id, uint16_t mask)
Definition frames.cpp:30
void config_sdo_client_(CO_config_t &cfg)
bool set_nmt_state(NMTState state)
Definition canopen.cpp:367
void process_node_monitor_(uint32_t dt_us)
CANopenComponent * next_local_
Definition canopen.h:324
void config_device_info_(CO_config_t &cfg)
void config_node_monitor_(CO_config_t &cfg)
void dump_usage(const char *tag) const
Definition od.cpp:115
void CO_CANmodule_process(CO_CANmodule_t *CANmodule)
void CO_CANsetNormalMode(CO_CANmodule_t *CANmodule)
bool state
Definition fan.h:2
uint16_t reset
Definition ina226.h:5
PROGMEM_STRING_TABLE(NMTStateStrings, "bootup", "stopped", "operational", "pre-operational", "unknown")
ESPHOME_LOG_TAG(TAG, "canopen")
NMTState to_nmt_state(CO_NMT_internalState_t state)
Definition canopen.h:41
const LogString * nmt_state_to_string(NMTState state)
Definition canopen.cpp:33
constexpr std::array< NMTState, 4 > NMT_STATES
Definition types.h:74
uint32_t IRAM_ATTR HOT micros()
Definition hal.cpp:43
uint16_t crc16be(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t poly, bool refin, bool refout)
Definition helpers.cpp:154
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
One CAN frame as passed between the bus and its driver.
Definition canbus.h:143