ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
sdo_client.cpp
Go to the documentation of this file.
1#include "canopen.h"
2
3#ifdef USE_CANOPEN_SDO_CLIENT
4
5#include <algorithm>
6#include <cstring>
7
8#include "esphome/core/log.h"
10
11namespace esphome::canopen {
12
13ESPHOME_LOG_TAG(TAG, "canopen.sdo");
14
15// after an abort, the next request (to any node) waits this long, so the server has processed the abort
16static constexpr uint32_t ABORT_GUARD_US = 50000;
17
18// indexed by SDOResult; the last entry for other values
19PROGMEM_STRING_TABLE(SDOResultStrings, "success", "abort", "timeout", "size mismatch", "transport error", "rejected",
20 "unknown");
21
23 return SDOResultStrings::get_log_str(static_cast<uint8_t>(result), SDOResultStrings::LAST_INDEX);
24}
25
27 // read only: start_sdo_() sets the channel for every request (CO_SDOclient_setup()), so a write wouldn't take
28 // effect (no CO_CONFIG_FLAG_OD_DYNAMIC)
29 this->od_.add_record(0x1280, {{0, ODA_SDO_R, &this->sdo_cli_highest_sub_, 1},
30 {1, ODA_SDO_R, &this->sdo_cli_cob_tx_, 4},
31 {2, ODA_SDO_R, &this->sdo_cli_cob_rx_, 4},
32 {3, ODA_SDO_R, &this->sdo_cli_node_, 1}});
33}
34
36 cfg.CNT_SDO_CLI = 1;
37 cfg.ENTRY_H1280 = this->od_.find(0x1280);
38}
39
40// Client-only hub; a node's client is set up by CO_CANopenInit(). Without our own node id there are no local
41// transfers, so the client needs no OD.
43 uint32_t err_info = 0;
44 CO_ReturnError_t err =
45 CO_SDOclient_init(this->co_->SDOclient, nullptr, this->od_.find(0x1280), NO_NODE_ID, this->co_->CANmodule,
46 this->co_->RX_IDX_SDO_CLI, this->co_->CANmodule, this->co_->TX_IDX_SDO_CLI, &err_info);
47 if (err != CO_ERROR_NO) {
48 ESP_LOGE(TAG, "CO_SDOclient_init failed: %d (OD 0x%04" PRIx32 ")", err, err_info);
49 return false;
50 }
51 return true;
52}
53
54static void reject(uint8_t node_id, uint16_t index, uint8_t sub, SDOCallback callback, void *context) {
55 ESP_LOGW(TAG, "request to node 0x%02x, 0x%04x:%u rejected", node_id, index, sub);
56 if (callback != nullptr)
57 callback(context, SDOReply{SDOResult::SDO_RESULT_REJECTED, 0, 0, 0, nullptr, 0});
58}
59
60// unsigned or sign-extended, as validate_sdo_value() allows
61static bool value_fits(uint32_t value, uint8_t size) {
62 if (size == 4)
63 return true;
64 const uint32_t high = value >> (8 * size);
65 return high == 0 || (high == (UINT32_MAX >> (8 * size)) && ((value >> (8 * size - 1)) & 1) != 0);
66}
67
68bool CANopenComponent::read_sdo(uint8_t node_id, uint16_t index, uint8_t sub, uint8_t expected_size,
69 SDOCallback callback, void *context) {
70 if (expected_size != 0 && expected_size != 1 && expected_size != 2 && expected_size != 4) {
71 reject(node_id, index, sub, callback, context);
72 return false;
73 }
74 return this->queue_sdo_(
75 SDORequest{node_id, sub, SDOKind::SDO_KIND_READ, expected_size, index, 0, {}, callback, context});
76}
77
78bool CANopenComponent::write_sdo(uint8_t node_id, uint16_t index, uint8_t sub, uint32_t value, uint8_t size,
79 SDOCallback callback, void *context) {
80 if ((size != 1 && size != 2 && size != 4) || !value_fits(value, size)) {
81 reject(node_id, index, sub, callback, context);
82 return false;
83 }
84 if (size < 4)
85 value &= (1u << (8 * size)) - 1; // sign-extended: the reply's value is zero-extended
86 return this->queue_sdo_(
87 SDORequest{node_id, sub, SDOKind::SDO_KIND_WRITE, size, index, 0, {value}, callback, context});
88}
89
90bool CANopenComponent::read_sdo_data(uint8_t node_id, uint16_t index, uint8_t sub, uint8_t *data, size_t capacity,
91 SDOCallback callback, void *context) {
92 if (data == nullptr || capacity == 0) {
93 reject(node_id, index, sub, callback, context);
94 return false;
95 }
96 // a longer reply aborts anyway, so the buffer's first 64 KiB are enough
97 const auto cap = static_cast<uint16_t>(std::min<size_t>(capacity, UINT16_MAX));
98 SDORequest request{node_id, sub, SDOKind::SDO_KIND_READ_DATA, 0, index, cap, {}, callback, context};
99 request.data = data;
100 return this->queue_sdo_(request);
101}
102
103bool CANopenComponent::write_sdo_data(uint8_t node_id, uint16_t index, uint8_t sub, const uint8_t *data, size_t len,
104 SDOCallback callback, void *context) {
105 if (data == nullptr || len == 0 || len > UINT16_MAX) {
106 reject(node_id, index, sub, callback, context);
107 return false;
108 }
109 const auto size = static_cast<uint16_t>(len);
110 SDORequest request{node_id, sub, SDOKind::SDO_KIND_WRITE_DATA, 0, index, size, {}, callback, context};
111 request.data = const_cast<uint8_t *>(data); // a WRITE_DATA request only reads it
112 return this->queue_sdo_(request);
113}
114
116 // before setup() the request waits in the queue
117 if (this->is_failed() || this->sdo_stopped_() || request.node_id == 0 || request.node_id > 127 ||
118 !this->sdo_queue_.push(request)) {
119 reject(request.node_id, request.index, request.sub, request.callback, request.context);
120 return false;
121 }
122 this->enable_loop();
123 return true;
124}
125
127 while (!this->sdo_queue_.empty()) {
128 SDORequest r = this->sdo_queue_.front();
129 this->sdo_queue_.pop();
130 reject(r.node_id, r.index, r.sub, r.callback, r.context);
131 }
132}
133
134// A late reply to an ended request would fail the current one: CANopenNode takes any abort and aborts on an
135// initiate response for another object.
136bool CANopenComponent::sdo_reply_is_stale_(const uint8_t *data, uint8_t len) const {
137 if (!this->sdo_busy_ || len < 4)
138 return false;
139 const CO_SDOclient_t *cli = this->co_->SDOclient;
140 // a request that hasn't gone out yet has no reply
141 if (cli->CANtxBuff->bufferFull)
142 return true;
143 const uint8_t scs = data[0] >> 5; // 0/1: segment responses, 2/3: initiate upload/download responses, 4: abort
144 if (scs < 2) // late while waiting for the initiate response
145 return cli->state == CO_SDO_ST_UPLOAD_INITIATE_RSP || cli->state == CO_SDO_ST_DOWNLOAD_INITIATE_RSP;
146 if (scs > 4)
147 return false;
148 // an initiate response for the other direction, e.g. a late write ack while a read of the object waits
149 if ((scs == 2 && cli->state == CO_SDO_ST_DOWNLOAD_INITIATE_RSP) ||
150 (scs == 3 && cli->state == CO_SDO_ST_UPLOAD_INITIATE_RSP))
151 return true;
152 return encode_uint16(data[2], data[1]) != this->sdo_active_.index || data[3] != this->sdo_active_.sub;
153}
154
155void CANopenComponent::cancel_sdo(void *context) {
156 // one turn of the ring keeps the other requests in order
157 for (size_t n = this->sdo_queue_.size(); n > 0; n--) {
158 SDORequest r = this->sdo_queue_.front();
159 this->sdo_queue_.pop();
160 if (r.context != context)
161 this->sdo_queue_.push(r);
162 }
163 if (this->sdo_busy_ && this->sdo_active_.context == context) {
164 // No callback from now on. The abort goes out in the next process_sdo_() pass: this may run from a callback or a
165 // log handler in the middle of a transmission, which owns the client's TX buffer.
166 this->sdo_active_.callback = nullptr;
167 this->sdo_cancel_pending_ = true;
168 this->enable_loop();
169 }
170}
171
173 CO_SDOclient_t *cli = this->co_->SDOclient;
174 SDORequest &r = this->sdo_active_;
175 uint8_t node = r.node_id;
176 CO_SDO_return_t ret = CO_SDOclient_setup(cli, 0x600 + node, 0x580 + node, node);
177 if (ret != CO_SDO_RT_ok_communicationEnd)
178 return ret;
179 this->sdo_len_ = 0;
180 this->sdo_rx_value_.fill(0); // finish_sdo_() decodes all 4 bytes
181 switch (r.kind) {
184 return CO_SDOclientUploadInitiate(cli, r.index, r.sub, this->response_timeout_ms_, false);
186 uint8_t buf[4];
187 put_le32(buf, r.value);
188 ret = CO_SDOclientDownloadInitiate(cli, r.index, r.sub, r.size, this->response_timeout_ms_, false);
189 if (ret != CO_SDO_RT_ok_communicationEnd)
190 return ret;
191 this->sdo_len_ = CO_SDOclientDownloadBufWrite(cli, buf, r.size);
192 return this->sdo_len_ == r.size ? CO_SDO_RT_ok_communicationEnd : CO_SDO_RT_wrongArguments;
193 }
195 ret = CO_SDOclientDownloadInitiate(cli, r.index, r.sub, r.len, this->response_timeout_ms_, false);
196 if (ret != CO_SDO_RT_ok_communicationEnd)
197 return ret;
198 this->sdo_len_ = CO_SDOclientDownloadBufWrite(cli, r.data, r.len);
199 return ret;
200 }
201 return CO_SDO_RT_wrongArguments;
202}
203
205 if (this->sdo_abort_pending_) {
206 CO_SDOclient_t *cli = this->co_->SDOclient;
207 if (!cli->CANtxBuff->bufferFull) {
208 // The CAN driver took it since the last pass. The guard starts now, whole: the time the driver took to accept it
209 // doesn't count. Taken isn't sent: canbus doesn't tell when a frame is on the bus.
210 this->sdo_abort_pending_ = false;
211 this->sdo_abort_guard_us_ = ABORT_GUARD_US;
212 return;
213 }
214 if (this->sdo_abort_guard_us_ <= dt_us) {
215 // The bus refused it for a whole response timeout: drop it, so it doesn't hold up the queue. The server ends
216 // the transfer at its own timeout.
217 discard_pending_tx(cli->CANdevTx, cli->CANtxBuff);
218 this->sdo_abort_pending_ = false;
219 ESP_LOGW(TAG, "node 0x%02x: abort of a cancelled transfer not sent", cli->nodeIDOfTheSDOServer);
220 }
221 }
222 this->sdo_abort_guard_us_ = this->sdo_abort_guard_us_ > dt_us ? this->sdo_abort_guard_us_ - dt_us : 0;
223}
224
225// CiA 301: a STOPPED node sends only NMT and heartbeat frames, so no SDO: requests end with REJECTED, without a frame,
226// until the node leaves STOPPED. A client-only hub has no NMT state.
228#ifdef USE_CANOPEN_NODE
229 return !this->is_client_only() && this->nmt_state_ == NMTState::NMT_STATE_STOPPED;
230#else
231 return false;
232#endif
233}
234
235// The node entered STOPPED: the running transfer and the queue end with REJECTED. An unsent request or abort is
236// dropped; the server ends the transfer at its own timeout.
238 if (this->sdo_abort_pending_) {
239 CO_SDOclient_t *cli = this->co_->SDOclient;
240 discard_pending_tx(cli->CANdevTx, cli->CANtxBuff);
241 this->sdo_abort_pending_ = false;
242 }
243 this->sdo_abort_guard_us_ = 0;
244 this->sdo_cancel_pending_ = false;
245 if (this->sdo_busy_)
247 this->reject_queued_sdo_();
248}
249
251 if (this->sdo_stopped_()) {
252 this->stop_sdo_();
253 return;
254 }
255 this->process_sdo_abort_(dt_us);
256 if (this->sdo_cancel_pending_) {
257 // after process_sdo_abort_(): the abort's time starts with this pass
258 this->sdo_cancel_pending_ = false;
259 if (this->sdo_busy_)
260 this->abort_sdo_();
261 }
262 if (!this->sdo_busy_) {
263 // The guard holds the client's TX buffer while an abort is pending, then requests to every node: one guard covers
264 // any number of cancelled transfers.
265 if (this->sdo_queue_.empty() || this->sdo_abort_guard_us_ > 0)
266 return;
267 this->sdo_active_ = this->sdo_queue_.front();
268 this->sdo_queue_.pop();
269 this->sdo_busy_ = true;
270 CO_SDO_return_t started = this->start_sdo_();
271 if (started != CO_SDO_RT_ok_communicationEnd) {
272 ESP_LOGD(TAG, "node 0x%02x, 0x%04x:%u: not started (CANopenNode %d)", this->sdo_active_.node_id,
273 this->sdo_active_.index, this->sdo_active_.sub, static_cast<int>(started));
275 return;
276 }
277 dt_us = 0;
278 }
279
280 CO_SDOclient_t *cli = this->co_->SDOclient;
281 SDORequest &r = this->sdo_active_;
282 CO_SDO_abortCode_t abort = CO_SDO_AB_NONE;
283 CO_SDO_return_t ret;
285 if (this->drain_upload_(dt_us, ret, abort))
286 return;
287 } else {
288 if (r.kind == SDOKind::SDO_KIND_WRITE_DATA && this->sdo_len_ < r.len) {
289 this->sdo_len_ += CO_SDOclientDownloadBufWrite(cli, r.data + this->sdo_len_, r.len - this->sdo_len_);
290 }
291 bool partial = r.kind == SDOKind::SDO_KIND_WRITE_DATA && this->sdo_len_ < r.len;
292 ret = CO_SDOclientDownload(cli, dt_us, false, partial, &abort, nullptr, nullptr);
293 }
294
295 if (ret == CO_SDO_RT_ok_communicationEnd) {
297 } else if (ret == CO_SDO_RT_transmittBufferFull && cli->timeoutTimer >= cli->SDOtimeoutTime_us) {
298 // CANopenNode doesn't time out while its frame waits to be sent
300 } else if (ret < 0) {
301 // a server may abort with the timeout code too
302 if (ret != CO_SDO_RT_endedWithServerAbort && abort == CO_SDO_AB_TIMEOUT) {
304 } else if (ret == CO_SDO_RT_endedWithServerAbort || ret == CO_SDO_RT_endedWithClientAbort) {
306 } else {
308 }
309 }
310}
311
312bool CANopenComponent::drain_upload_(uint32_t dt_us, CO_SDO_return_t &ret, CO_SDO_abortCode_t &abort) {
313 CO_SDOclient_t *cli = this->co_->SDOclient;
314 SDORequest &r = this->sdo_active_;
315 const bool value_read = r.kind == SDOKind::SDO_KIND_READ;
316 uint8_t *dst = value_read ? this->sdo_rx_value_.data() : r.data;
317 const size_t cap = value_read ? this->sdo_rx_value_.size() : r.len;
318 // The fifo holds one segment, so a read past capacity ends before the next segment is requested.
319 ret = CO_SDOclientUpload(cli, dt_us, false, &abort, nullptr, nullptr, nullptr);
320 while (ret >= 0) {
321 // our own OD's handler may cancel the request and release the buffer; the next pass aborts
322 if (this->sdo_cancel_pending_)
323 return true;
324 uint8_t buf[8];
325 size_t n;
326 while ((n = CO_SDOclientUploadBufRead(cli, buf, sizeof(buf))) > 0) {
327 if (this->sdo_len_ < cap)
328 std::memcpy(dst + this->sdo_len_, buf, std::min(n, cap - this->sdo_len_));
329 this->sdo_len_ += n;
330 }
331 if (this->sdo_len_ > cap) {
332 abort = value_read ? CO_SDO_AB_DATA_LONG : CO_SDO_AB_OUT_OF_MEM;
333 // a transfer from our own OD has no server on the bus to tell
334 if (!this->sdo_is_local_())
335 CO_SDOclientUpload(cli, 0, true, &abort, nullptr, nullptr, nullptr);
336 // not abort: it is empty when the last frame already ended the transfer
337 if (value_read) {
339 } else {
340 this->finish_sdo_(SDOResult::SDO_RESULT_ABORT, CO_SDO_AB_OUT_OF_MEM);
341 }
342 return true;
343 }
344 if (ret != CO_SDO_RT_uploadDataBufferFull && ret != CO_SDO_RT_waitingLocalTransfer)
345 break;
346 ret = CO_SDOclientUpload(cli, 0, false, &abort, nullptr, nullptr, nullptr);
347 }
348 return false;
349}
350
352 CO_SDOclient_t *cli = this->co_->SDOclient;
353 CO_SDOclientClose(cli);
354 // drop an unsent frame; one the controller took can't be recalled (see types.h)
356 discard_pending_tx(cli->CANdevTx, cli->CANtxBuff);
357 SDORequest r = this->sdo_active_;
358 this->sdo_busy_ = false;
359
360 SDOReply reply{result, abort_code, 0, 0, nullptr, 0};
362 if (r.kind == SDOKind::SDO_KIND_READ) {
363 size_t len = this->sdo_len_;
364 if (len == 0 || (r.size != 0 && len != r.size)) {
366 } else {
367 reply.value = encode_value_le<uint32_t>(this->sdo_rx_value_.data());
368 }
369 reply.size = len;
370 } else if (r.kind == SDOKind::SDO_KIND_READ_DATA) {
371 reply.data = r.data;
372 reply.len = this->sdo_len_;
373 } else if (r.kind == SDOKind::SDO_KIND_WRITE) {
374 reply.value = r.value;
375 reply.size = r.size;
376 }
377 }
378 // the slot is free now, so the callback may queue the next request
379 if (r.callback != nullptr)
380 r.callback(r.context, reply);
381 if (reply.result != SDOResult::SDO_RESULT_SUCCESS) {
382 ESP_LOGW(TAG, "node 0x%02x, 0x%04x:%u: %s (abort 0x%08" PRIx32 ")", r.node_id, r.index, r.sub,
383 LOG_STR_ARG(sdo_result_to_string(reply.result)), abort_code);
384 }
385}
386
388 CO_SDOclient_t *cli = this->co_->SDOclient;
389 // The request ends before anything that may log (the abort's transmission too): a log handler may queue or cancel
390 // requests. sdo_active_ stays as it is until the next request starts.
391 const SDORequest &r = this->sdo_active_;
392 this->sdo_busy_ = false;
393 // Discard only this client's unsent frame before replacing it with an abort.
394 // The driver and the SDO client run on the same main-loop context.
395 discard_pending_tx(cli->CANdevTx, cli->CANtxBuff);
396 if (this->sdo_is_local_()) {
397 // served from our own OD: nothing on the bus to abort or to wait out
398 CO_SDOclientClose(cli);
399 ESP_LOGD(TAG, "node 0x%02x, 0x%04x:%u: cancelled", r.node_id, r.index, r.sub);
400 return;
401 }
402 CO_SDO_abortCode_t abort = CO_SDO_AB_GENERAL;
404 CO_SDOclientUpload(cli, 0, true, &abort, nullptr, nullptr, nullptr);
405 } else {
406 CO_SDOclientDownload(cli, 0, true, false, &abort, nullptr, nullptr);
407 }
408 CO_SDOclientClose(cli);
409 // pending until the next pass, even if the driver took it at once (see process_sdo_abort_()); until then the guard
410 // is the time left to send it
411 this->sdo_abort_pending_ = true;
412 this->sdo_abort_guard_us_ = this->response_timeout_ms_ * 1000u;
413 ESP_LOGD(TAG, "node 0x%02x, 0x%04x:%u: cancelled", r.node_id, r.index, r.sub);
414}
415
416} // namespace esphome::canopen
417
418#endif // USE_CANOPEN_SDO_CLIENT
bool is_failed() const
Definition component.h:288
void enable_loop()
Enable this component's loop.
Definition component.h:262
bool read_sdo(uint8_t node_id, uint16_t index, uint8_t sub, uint8_t expected_size, SDOCallback callback, void *context)
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 process_sdo_(uint32_t dt_us)
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)
void finish_sdo_(SDOResult result, uint32_t abort_code)
bool drain_upload_(uint32_t dt_us, CO_SDO_return_t &ret, CO_SDO_abortCode_t &abort)
bool sdo_reply_is_stale_(const uint8_t *data, uint8_t len) const
std::array< uint8_t, 4 > sdo_rx_value_
Definition canopen.h:467
bool read_sdo_data(uint8_t node_id, uint16_t index, uint8_t sub, uint8_t *data, size_t capacity, SDOCallback callback, void *context)
void config_sdo_client_(CO_config_t &cfg)
StaticRingBuffer< SDORequest, SDO_QUEUE_SIZE > sdo_queue_
Definition canopen.h:456
static constexpr uint8_t NO_NODE_ID
Definition canopen.h:66
void process_sdo_abort_(uint32_t dt_us)
void add_record(uint16_t index, std::initializer_list< RecordSub > subs)
Definition od.h:58
OD_entry_t * find(uint16_t index)
Definition od.h:73
int ret
PROGMEM_STRING_TABLE(NMTStateStrings, "bootup", "stopped", "operational", "pre-operational", "unknown")
ESPHOME_LOG_TAG(TAG, "canopen")
const LogString * sdo_result_to_string(SDOResult result)
void discard_pending_tx(CO_CANmodule_t *mod, CO_CANtx_t *buf)
void(*)(void *context, const SDOReply &reply) SDOCallback
Definition types.h:62
uint32_t value
Definition hal.cpp:59
const void size_t len
Definition hal.h:68
uint16_t size
Definition helpers.cpp:44
constexpr T encode_value_le(const uint8_t *bytes)
Encode a value from its constituent bytes (from least to most significant) in an array with length si...
Definition helpers.h:1268
constexpr uint8_t * put_le32(uint8_t *dst, uint32_t value)
Definition helpers.h:1319
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:1227
uint16_t uint16_t & capacity
Definition helpers.cpp:44
static void uint32_t
esp_err_t result