ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
nmt_master.cpp
Go to the documentation of this file.
1// NMT master: NMT commands to other nodes.
2#include "canopen.h"
3
4#ifdef USE_CANOPEN_NMT_MASTER
5
6#include "esphome/core/log.h"
7
8namespace esphome::canopen {
9
10ESPHOME_LOG_TAG(TAG, "canopen");
11
12// NMTCommand uses CANopenNode's values: send_nmt() casts it
13static_assert(static_cast<uint8_t>(CO_NMT_ENTER_OPERATIONAL) == static_cast<uint8_t>(NMTCommand::NMT_COMMAND_START));
14static_assert(static_cast<uint8_t>(CO_NMT_ENTER_STOPPED) == static_cast<uint8_t>(NMTCommand::NMT_COMMAND_STOP));
15static_assert(static_cast<uint8_t>(CO_NMT_ENTER_PRE_OPERATIONAL) ==
16 static_cast<uint8_t>(NMTCommand::NMT_COMMAND_PRE_OPERATIONAL));
17static_assert(static_cast<uint8_t>(CO_NMT_RESET_NODE) == static_cast<uint8_t>(NMTCommand::NMT_COMMAND_RESET_NODE));
18static_assert(static_cast<uint8_t>(CO_NMT_RESET_COMMUNICATION) ==
20
21bool CANopenComponent::send_nmt(uint8_t node_id, NMTCommand command) {
22 // A log handler inside our own send (canbus logs a frame) calling us again would overwrite the frame being sent
23 // before CANopenNode marks its buffer: refused, without logging (we are inside a log call)
24 if (this->nmt_sending_)
25 return false;
26 // no NMT object in client-only mode
27 if (this->co_ == nullptr || this->co_->NMT == nullptr || this->is_failed() || node_id > 127) {
28 ESP_LOGW(TAG, "NMT command %u to node 0x%02x rejected", (unsigned) command, node_id);
29 return false;
30 }
31 ESP_LOGD(TAG, "NMT command %u to node 0x%02x", (unsigned) command, node_id);
32 CO_NMT_t *nmt = this->co_->NMT;
33 const bool for_us = node_id == 0 || node_id == this->node_id_;
34 // CANopenNode writes the frame (and, for us or all nodes, the command it applies to us) before it checks its TX
35 // buffer, and keeps one command for us until the next CO_process(): a command while the previous one waits would
36 // replace it
37 if (nmt->NMT_TXbuff->bufferFull || (for_us && this->nmt_command_pending_())) {
38 ESP_LOGW(TAG, "NMT command %u to node 0x%02x rejected: the previous command is still pending", (unsigned) command,
39 node_id);
40 return false;
41 }
42 this->nmt_sending_ = true;
43 CO_ReturnError_t err = CO_NMT_sendCommand(nmt, static_cast<CO_NMT_command_t>(command), node_id);
44 this->nmt_sending_ = false;
45 if (err != CO_ERROR_NO) {
46 ESP_LOGW(TAG, "NMT command %u to node 0x%02x failed: %d", (unsigned) command, node_id, err);
47 return false;
48 }
49 if (for_us)
50 this->apply_nmt_command_();
51 return true;
52}
53
54} // namespace esphome::canopen
55
56#endif // USE_CANOPEN_NMT_MASTER
bool send_nmt(uint8_t node_id, NMTCommand command)
ESPHOME_LOG_TAG(TAG, "canopen")