ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
driver_can.cpp
Go to the documentation of this file.
1// CANopenNode driver functions (301/CO_driver.h) on top of ESPHome canbus. CANptr is the CANopenComponent.
2// Everything runs on the main loop: frames are received by CANopenComponent::on_frame_() (the canbus callback),
3// handed to CANopenNode's receive buffers and the frame listeners by receive_(), and sent by transmit(). Frames between
4// local nodes go through each receiver's queue (queue_local_(), deliver_local_()).
5#include "canopen.h"
6
7#include <array>
8#include <cstring>
9
11#include "esphome/core/log.h"
12
13namespace esphome::canopen {
14
15ESPHOME_LOG_TAG(TAG, "canopen");
16
17void discard_pending_tx(CO_CANmodule_t *mod, CO_CANtx_t *buf) {
18 if (buf->bufferFull) {
19 buf->bufferFull = false;
20 mod->CANtxCount--;
21 }
22}
23
24static bool transmit_buffer(CO_CANmodule_t *mod, CO_CANtx_t *buf) {
25 return static_cast<CANopenComponent *>(mod->CANptr)->transmit(buf->ident, buf->data, buf->DLC);
26}
27
29 // CANopen uses classic CAN with 11-bit ids
30#ifdef USE_CANBUS_FD
31 if (frame.fd)
32 return;
33#endif
34 const uint8_t len = frame.payload_length();
35 if (frame.use_extended_id || len > 8)
36 return;
37 const uint16_t ident = (frame.can_id & 0x7FF) | (frame.remote_transmission_request ? 0x800 : 0);
38#ifdef USE_CANOPEN_LOCAL_NODES
39 if (this->bus_frame_staged_) {
40 // an earlier local node queued this frame for us, behind the older local frames and ahead of its replies
41 this->bus_frame_staged_ = false;
42 this->deliver_local_();
43 return;
44 }
45 // queued for the other local nodes before we send anything: what we send while handling our older local frames or
46 // this one is on the bus after it
47 for (CANopenComponent *node = this->next_local_; node != nullptr && node != this; node = node->next_local_)
48 node->stage_bus_frame_(ident, frame.data, len);
49 // frames other local nodes sent before are older: they go first
50 this->deliver_local_();
51#endif
52 this->handle_frame_(ident, frame.data, len);
53}
54
55#ifdef USE_CANOPEN_LOCAL_NODES
56void CANopenComponent::stage_bus_frame_(uint16_t ident, const uint8_t *data, uint8_t len) {
57 if (this->local_queue_.capacity() == 0 || this->is_failed())
58 return; // not set up: no canbus callback either
59 // set even when the queue is full and the frame is lost: otherwise this node would take itself for the first one
60 this->bus_frame_staged_ = true;
61 this->queue_local_(ident, data, len);
62}
63#endif
64
65void CANopenComponent::handle_frame_(uint16_t ident, const uint8_t *data, uint8_t len) {
66 const bool taken = this->receive_(ident, data, len);
67 this->hold_flush_ = true;
68#ifdef USE_CANOPEN_SDO_CLIENT
69 // A reply for the running request is handled right away; CANopenNode restarts its response timer for it (and may
70 // send the next segment), so the time loop() charges starts again here.
71 if (CO_FLAG_READ(this->co_->SDOclient->CANrxNew)) {
72 this->process_sdo_(0);
74 }
75#endif
76 // A node processes every frame a CANopenNode object took before the next one: it keeps one received frame per
77 // object (e.g. an RPDO), so a later frame of a burst would overwrite it.
78 if (taken && !this->is_client_only())
79 this->process_node_();
80 this->hold_flush_ = false;
81}
82
83bool CANopenComponent::receive_(uint16_t ident, const uint8_t *data, uint8_t len) {
84 if (this->co_ == nullptr || this->is_failed())
85 return false;
86 CO_CANmodule_t *mod = this->co_->CANmodule;
87 CO_CANrxMsg_t msg{};
88 bool taken = false;
89 msg.ident = ident;
90 msg.DLC = len;
91 if (len != 0) // an empty frame (SYNC) may come with a null data pointer
92 memcpy(msg.data, data, len);
93 for (uint16_t i = 0; i < mod->rxSize; i++) {
94 CO_CANrx_t *rx = &mod->rxArray[i];
95 if (rx->CANrx_callback == nullptr || ((msg.ident ^ rx->ident) & rx->mask) != 0)
96 continue;
97#ifdef USE_CANOPEN_SDO_CLIENT
98 if (rx->object == this->co_->SDOclient && this->sdo_reply_is_stale_(data, len))
99 continue;
100#endif
101 rx->CANrx_callback(rx->object, &msg);
102 taken = true;
103 }
104 this->dispatch_frame_(msg);
105 return taken;
106}
107
108bool CANopenComponent::transmit(uint16_t ident, const uint8_t *data, uint8_t len) {
109#ifdef USE_CANOPEN_LOCAL_NODES
110 // the caller's buffer may change while send_data() runs (a log handler sending a frame from it): the local nodes get
111 // the bytes the bus got
112 std::array<uint8_t, 8> payload{};
113 if (len != 0)
114 memcpy(payload.data(), data, len);
115 if (this->canbus_->send_data(ident & 0x7FF, false, ident & 0x800, payload.data(), len) != canbus::ERROR_OK)
116 return false;
117 for (CANopenComponent *node = this->next_local_; node != nullptr && node != this; node = node->next_local_)
118 node->queue_local_(ident, payload.data(), len);
119 return true;
120#else
121 return this->canbus_->send_data(ident & 0x7FF, false, ident & 0x800, data, len) == canbus::ERROR_OK;
122#endif
123}
124
125#ifdef USE_CANOPEN_LOCAL_NODES
126
127// Called from another node's transmit(), maybe inside its processing or a log handler: only queues, doesn't log.
128void CANopenComponent::queue_local_(uint16_t ident, const uint8_t *data, uint8_t len) {
129 if (this->local_queue_.capacity() == 0 || this->is_failed())
130 return; // not set up
131 LocalFrame f{ident, len, {}};
132 if (len != 0)
133 memcpy(f.data.data(), data, len);
134 if (!this->local_queue_.push(f)) {
135 this->local_dropped_++;
136 return;
137 }
138 // enable_loop() may log (and is meant for a component's own context): only set the flag, the next pass enables it
140}
141
143 // only the frames queued before this pass: what handling them makes this node send goes to the others' queues
144 for (auto n = this->local_queue_.size(); n > 0; n--) {
145 const LocalFrame f = this->local_queue_.front();
146 this->local_queue_.pop();
147 this->handle_frame_(f.ident, f.data.data(), f.len);
148 }
149 if (this->local_dropped_ != 0) {
150 ESP_LOGW(TAG, "%u received frames lost (queue of %u full)", (unsigned) this->local_dropped_,
151 (unsigned) LOCAL_QUEUE_SIZE);
152 this->local_dropped_ = 0;
153 }
154}
155#endif // USE_CANOPEN_LOCAL_NODES
156
157} // namespace esphome::canopen
158
160using esphome::canopen::transmit_buffer;
161
162extern "C" {
163
164// names and signatures fixed by CO_driver.h
165// NOLINTBEGIN(readability-identifier-naming,readability-non-const-parameter)
166
167void CO_CANsetConfigurationMode(void *CANptr) {}
168
169void CO_CANsetNormalMode(CO_CANmodule_t *CANmodule) { CANmodule->CANnormal = true; }
170
171CO_ReturnError_t CO_CANmodule_init(CO_CANmodule_t *CANmodule, void *CANptr, CO_CANrx_t rxArray[], uint16_t rxSize,
172 CO_CANtx_t txArray[], uint16_t txSize, uint16_t CANbitRate) {
173 CANmodule->CANptr = CANptr;
174 CANmodule->rxArray = rxArray;
175 CANmodule->rxSize = rxSize;
176 CANmodule->txArray = txArray;
177 CANmodule->txSize = txSize;
178 CANmodule->CANerrorStatus = 0;
179 CANmodule->CANnormal = false;
180 CANmodule->useCANrxFilters = false;
181 CANmodule->bufferInhibitFlag = false;
182 CANmodule->firstCANtxMessage = true;
183 CANmodule->CANtxCount = 0;
184 CANmodule->errOld = 0;
185 memset(rxArray, 0, sizeof(CO_CANrx_t) * rxSize);
186 memset(txArray, 0, sizeof(CO_CANtx_t) * txSize);
187 return CO_ERROR_NO;
188}
189
190void CO_CANmodule_disable(CO_CANmodule_t *CANmodule) {
191 if (CANmodule != nullptr)
192 CANmodule->CANnormal = false;
193}
194
195CO_ReturnError_t CO_CANrxBufferInit(CO_CANmodule_t *CANmodule, uint16_t index, uint16_t ident, uint16_t mask,
196 bool_t rtr, void *object, void (*CANrx_callback)(void *object, void *message)) {
197 if (index >= CANmodule->rxSize)
198 return CO_ERROR_ILLEGAL_ARGUMENT;
199 CO_CANrx_t *rx = &CANmodule->rxArray[index];
200 rx->object = object;
201 rx->CANrx_callback = CANrx_callback;
202 rx->ident = (ident & 0x7FF) | (rtr ? 0x800 : 0);
203 rx->mask = (mask & 0x7FF) | 0x800;
204 return CO_ERROR_NO;
205}
206
207CO_CANtx_t *CO_CANtxBufferInit(CO_CANmodule_t *CANmodule, uint16_t index, uint16_t ident, bool_t rtr, uint8_t noOfBytes,
208 bool_t syncFlag) {
209 if (index >= CANmodule->txSize)
210 return nullptr;
211 CO_CANtx_t *tx = &CANmodule->txArray[index];
212 // the SDO client sets its buffer up again for every request
213 discard_pending_tx(CANmodule, tx);
214 tx->ident = (ident & 0x7FF) | (rtr ? 0x800 : 0);
215 tx->DLC = noOfBytes;
216 tx->syncFlag = syncFlag;
217 return tx;
218}
219
220CO_ReturnError_t CO_CANsend(CO_CANmodule_t *CANmodule, CO_CANtx_t *buffer) {
221 if (buffer->bufferFull) {
222 if (!CANmodule->firstCANtxMessage)
223 CANmodule->CANerrorStatus |= CO_CAN_ERRTX_OVERFLOW;
224 return CO_ERROR_TX_OVERFLOW;
225 }
226 if (CANmodule->CANtxCount == 0 && transmit_buffer(CANmodule, buffer)) {
227 CANmodule->firstCANtxMessage = false;
228 return CO_ERROR_NO;
229 }
230 // queued behind the others; CO_CANmodule_process() resends it from loop(). Counted once: a send re-entered from a log
231 // handler inside transmit_buffer() may have queued this buffer already.
232 if (!buffer->bufferFull) {
233 buffer->bufferFull = true;
234 CANmodule->CANtxCount++;
235 }
236 static_cast<esphome::canopen::CANopenComponent *>(CANmodule->CANptr)->enable_loop();
237 return CO_ERROR_NO;
238}
239
240void CO_CANclearPendingSyncPDOs(CO_CANmodule_t *CANmodule) {
241 for (uint16_t i = 0; i < CANmodule->txSize; i++) {
242 CO_CANtx_t *tx = &CANmodule->txArray[i];
243 if (tx->bufferFull && tx->syncFlag) {
244 discard_pending_tx(CANmodule, tx);
245 CANmodule->CANerrorStatus |= CO_CAN_ERRTX_PDO_LATE;
246 }
247 }
248}
249
250void CO_CANmodule_process(CO_CANmodule_t *CANmodule) {
251 // also called by CO_process(); on a received frame the queue waits for loop()
252 if (static_cast<esphome::canopen::CANopenComponent *>(CANmodule->CANptr)->flush_held())
253 return;
254 for (uint16_t i = 0; i < CANmodule->txSize && CANmodule->CANtxCount > 0; i++) {
255 CO_CANtx_t *tx = &CANmodule->txArray[i];
256 if (!tx->bufferFull)
257 continue;
258 if (!transmit_buffer(CANmodule, tx))
259 break;
260 // a log handler inside the send may have dropped this buffer already (an NMT state change discarding the queued
261 // TPDOs, an SDO abort given up), so it is counted out only once
262 discard_pending_tx(CANmodule, tx);
263 CANmodule->firstCANtxMessage = false;
264 }
265}
266
267// NOLINTEND(readability-identifier-naming,readability-non-const-parameter)
268
269} // extern "C"
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.
bool is_failed() const
Definition component.h:288
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
canbus::Error send_data(const CanFrame &frame)
Validates the frame and passes it to the driver.
void process_sdo_(uint32_t dt_us)
bool transmit(uint16_t ident, const uint8_t *data, uint8_t len)
void handle_frame_(uint16_t ident, const uint8_t *data, uint8_t len)
static constexpr uint8_t LOCAL_QUEUE_SIZE
Definition canopen.h:276
FixedRingBuffer< LocalFrame, LOCAL_QUEUE_SIZE > local_queue_
Definition canopen.h:325
void on_frame_(const canbus::CanFrame &frame)
bool receive_(uint16_t ident, const uint8_t *data, uint8_t len)
Returns whether a CANopenNode object took the frame.
void queue_local_(uint16_t ident, const uint8_t *data, uint8_t len)
void stage_bus_frame_(uint16_t ident, const uint8_t *data, uint8_t len)
CANopenComponent * next_local_
Definition canopen.h:324
void dispatch_frame_(const CO_CANrxMsg_t &msg)
Definition frames.cpp:49
const LogString * message
Definition component.cpp:35
void CO_CANmodule_process(CO_CANmodule_t *CANmodule)
CO_ReturnError_t CO_CANrxBufferInit(CO_CANmodule_t *CANmodule, uint16_t index, uint16_t ident, uint16_t mask, bool_t rtr, void *object, void(*CANrx_callback)(void *object, void *message))
CO_ReturnError_t CO_CANmodule_init(CO_CANmodule_t *CANmodule, void *CANptr, CO_CANrx_t rxArray[], uint16_t rxSize, CO_CANtx_t txArray[], uint16_t txSize, uint16_t CANbitRate)
CO_ReturnError_t CO_CANsend(CO_CANmodule_t *CANmodule, CO_CANtx_t *buffer)
void CO_CANsetConfigurationMode(void *CANptr)
CO_CANtx_t * CO_CANtxBufferInit(CO_CANmodule_t *CANmodule, uint16_t index, uint16_t ident, bool_t rtr, uint8_t noOfBytes, bool_t syncFlag)
void CO_CANclearPendingSyncPDOs(CO_CANmodule_t *CANmodule)
void CO_CANmodule_disable(CO_CANmodule_t *CANmodule)
void CO_CANsetNormalMode(CO_CANmodule_t *CANmodule)
uint32_t buffer
Definition gif.cpp:50
ESPHOME_LOG_TAG(TAG, "canopen")
void discard_pending_tx(CO_CANmodule_t *mod, CO_CANtx_t *buf)
const void size_t len
Definition hal.h:68
Application App
Global storage of Application pointer - only one Application can exist.
One CAN frame as passed between the bus and its driver.
Definition canbus.h:143
uint8_t payload_length() const
Payload bytes for the DLC: at most 8 for a classic frame, 0 for an invalid CAN FD DLC.
Definition canbus.h:156