ESPHome  2024.3.2
modbus.cpp
Go to the documentation of this file.
1 #include "modbus.h"
2 #include "esphome/core/log.h"
3 #include "esphome/core/helpers.h"
4 
5 namespace esphome {
6 namespace modbus {
7 
8 static const char *const TAG = "modbus";
9 
10 void Modbus::setup() {
11  if (this->flow_control_pin_ != nullptr) {
12  this->flow_control_pin_->setup();
13  }
14 }
15 void Modbus::loop() {
16  const uint32_t now = millis();
17 
18  if (now - this->last_modbus_byte_ > 50) {
19  this->rx_buffer_.clear();
20  this->last_modbus_byte_ = now;
21  }
22  // stop blocking new send commands after send_wait_time_ ms regardless if a response has been received since then
23  if (now - this->last_send_ > send_wait_time_) {
25  }
26 
27  while (this->available()) {
28  uint8_t byte;
29  this->read_byte(&byte);
30  if (this->parse_modbus_byte_(byte)) {
31  this->last_modbus_byte_ = now;
32  } else {
33  this->rx_buffer_.clear();
34  }
35  }
36 }
37 
38 bool Modbus::parse_modbus_byte_(uint8_t byte) {
39  size_t at = this->rx_buffer_.size();
40  this->rx_buffer_.push_back(byte);
41  const uint8_t *raw = &this->rx_buffer_[0];
42  ESP_LOGV(TAG, "Modbus received Byte %d (0X%x)", byte, byte);
43  // Byte 0: modbus address (match all)
44  if (at == 0)
45  return true;
46  uint8_t address = raw[0];
47  uint8_t function_code = raw[1];
48  // Byte 2: Size (with modbus rtu function code 4/3)
49  // See also https://en.wikipedia.org/wiki/Modbus
50  if (at == 2)
51  return true;
52 
53  uint8_t data_len = raw[2];
54  uint8_t data_offset = 3;
55 
56  // Per https://modbus.org/docs/Modbus_Application_Protocol_V1_1b3.pdf Ch 5 User-Defined function codes
57  if (((function_code >= 65) && (function_code <= 72)) || ((function_code >= 100) && (function_code <= 110))) {
58  // Handle user-defined function, since we don't know how big this ought to be,
59  // ideally we should delegate the entire length detection to whatever handler is
60  // installed, but wait, there is the CRC, and if we get a hit there is a good
61  // chance that this is a complete message ... admittedly there is a small chance is
62  // isn't but that is quite small given the purpose of the CRC in the first place
63 
64  // Fewer than 2 bytes can't calc CRC
65  if (at < 2)
66  return true;
67 
68  data_len = at - 2;
69  data_offset = 1;
70 
71  uint16_t computed_crc = crc16(raw, data_offset + data_len);
72  uint16_t remote_crc = uint16_t(raw[data_offset + data_len]) | (uint16_t(raw[data_offset + data_len + 1]) << 8);
73 
74  if (computed_crc != remote_crc)
75  return true;
76 
77  ESP_LOGD(TAG, "Modbus user-defined function %02X found", function_code);
78 
79  } else {
80  // the response for write command mirrors the requests and data startes at offset 2 instead of 3 for read commands
81  if (function_code == 0x5 || function_code == 0x06 || function_code == 0xF || function_code == 0x10) {
82  data_offset = 2;
83  data_len = 4;
84  }
85 
86  // Error ( msb indicates error )
87  // response format: Byte[0] = device address, Byte[1] function code | 0x80 , Byte[2] exception code, Byte[3-4] crc
88  if ((function_code & 0x80) == 0x80) {
89  data_offset = 2;
90  data_len = 1;
91  }
92 
93  // Byte data_offset..data_offset+data_len-1: Data
94  if (at < data_offset + data_len)
95  return true;
96 
97  // Byte 3+data_len: CRC_LO (over all bytes)
98  if (at == data_offset + data_len)
99  return true;
100 
101  // Byte data_offset+len+1: CRC_HI (over all bytes)
102  uint16_t computed_crc = crc16(raw, data_offset + data_len);
103  uint16_t remote_crc = uint16_t(raw[data_offset + data_len]) | (uint16_t(raw[data_offset + data_len + 1]) << 8);
104  if (computed_crc != remote_crc) {
105  if (this->disable_crc_) {
106  ESP_LOGD(TAG, "Modbus CRC Check failed, but ignored! %02X!=%02X", computed_crc, remote_crc);
107  } else {
108  ESP_LOGW(TAG, "Modbus CRC Check failed! %02X!=%02X", computed_crc, remote_crc);
109  return false;
110  }
111  }
112  }
113  std::vector<uint8_t> data(this->rx_buffer_.begin() + data_offset, this->rx_buffer_.begin() + data_offset + data_len);
114  bool found = false;
115  for (auto *device : this->devices_) {
116  if (device->address_ == address) {
117  // Is it an error response?
118  if ((function_code & 0x80) == 0x80) {
119  ESP_LOGD(TAG, "Modbus error function code: 0x%X exception: %d", function_code, raw[2]);
120  if (waiting_for_response != 0) {
121  device->on_modbus_error(function_code & 0x7F, raw[2]);
122  } else {
123  // Ignore modbus exception not related to a pending command
124  ESP_LOGD(TAG, "Ignoring Modbus error - not expecting a response");
125  }
126  } else {
127  device->on_modbus_data(data);
128  }
129  found = true;
130  }
131  }
133 
134  if (!found) {
135  ESP_LOGW(TAG, "Got Modbus frame from unknown address 0x%02X! ", address);
136  }
137 
138  // return false to reset buffer
139  return false;
140 }
141 
143  ESP_LOGCONFIG(TAG, "Modbus:");
144  LOG_PIN(" Flow Control Pin: ", this->flow_control_pin_);
145  ESP_LOGCONFIG(TAG, " Send Wait Time: %d ms", this->send_wait_time_);
146  ESP_LOGCONFIG(TAG, " CRC Disabled: %s", YESNO(this->disable_crc_));
147 }
149  // After UART bus
150  return setup_priority::BUS - 1.0f;
151 }
152 
153 void Modbus::send(uint8_t address, uint8_t function_code, uint16_t start_address, uint16_t number_of_entities,
154  uint8_t payload_len, const uint8_t *payload) {
155  static const size_t MAX_VALUES = 128;
156 
157  // Only check max number of registers for standard function codes
158  // Some devices use non standard codes like 0x43
159  if (number_of_entities > MAX_VALUES && function_code <= 0x10) {
160  ESP_LOGE(TAG, "send too many values %d max=%zu", number_of_entities, MAX_VALUES);
161  return;
162  }
163 
164  std::vector<uint8_t> data;
165  data.push_back(address);
166  data.push_back(function_code);
167  data.push_back(start_address >> 8);
168  data.push_back(start_address >> 0);
169  if (function_code != 0x5 && function_code != 0x6) {
170  data.push_back(number_of_entities >> 8);
171  data.push_back(number_of_entities >> 0);
172  }
173 
174  if (payload != nullptr) {
175  if (function_code == 0xF || function_code == 0x10) { // Write multiple
176  data.push_back(payload_len); // Byte count is required for write
177  } else {
178  payload_len = 2; // Write single register or coil
179  }
180  for (int i = 0; i < payload_len; i++) {
181  data.push_back(payload[i]);
182  }
183  }
184 
185  auto crc = crc16(data.data(), data.size());
186  data.push_back(crc >> 0);
187  data.push_back(crc >> 8);
188 
189  if (this->flow_control_pin_ != nullptr)
190  this->flow_control_pin_->digital_write(true);
191 
192  this->write_array(data);
193  this->flush();
194 
195  if (this->flow_control_pin_ != nullptr)
196  this->flow_control_pin_->digital_write(false);
197  waiting_for_response = address;
198  last_send_ = millis();
199  ESP_LOGV(TAG, "Modbus write: %s", format_hex_pretty(data).c_str());
200 }
201 
202 // Helper function for lambdas
203 // Send raw command. Except CRC everything must be contained in payload
204 void Modbus::send_raw(const std::vector<uint8_t> &payload) {
205  if (payload.empty()) {
206  return;
207  }
208 
209  if (this->flow_control_pin_ != nullptr)
210  this->flow_control_pin_->digital_write(true);
211 
212  auto crc = crc16(payload.data(), payload.size());
213  this->write_array(payload);
214  this->write_byte(crc & 0xFF);
215  this->write_byte((crc >> 8) & 0xFF);
216  this->flush();
217  if (this->flow_control_pin_ != nullptr)
218  this->flow_control_pin_->digital_write(false);
219  waiting_for_response = payload[0];
220  ESP_LOGV(TAG, "Modbus write raw: %s", format_hex_pretty(payload).c_str());
221  last_send_ = millis();
222 }
223 
224 } // namespace modbus
225 } // namespace esphome
virtual void digital_write(bool value)=0
uint8_t raw[35]
Definition: bl0939.h:19
std::string format_hex_pretty(const uint8_t *data, size_t length)
Format the byte array data of length len in pretty-printed, human-readable hex.
Definition: helpers.cpp:361
void write_array(const uint8_t *data, size_t len)
Definition: uart.h:21
std::vector< uint8_t > rx_buffer_
Definition: modbus.h:41
bool parse_modbus_byte_(uint8_t byte)
Definition: modbus.cpp:38
void write_byte(uint8_t data)
Definition: uart.h:19
uint32_t last_send_
Definition: modbus.h:43
void send_raw(const std::vector< uint8_t > &payload)
Definition: modbus.cpp:204
void send(uint8_t address, uint8_t function_code, uint16_t start_address, uint16_t number_of_entities, uint8_t payload_len=0, const uint8_t *payload=nullptr)
Definition: modbus.cpp:153
std::vector< ModbusDevice * > devices_
Definition: modbus.h:44
float get_setup_priority() const override
Definition: modbus.cpp:148
virtual void setup()=0
GPIOPin * flow_control_pin_
Definition: modbus.h:36
uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t reverse_poly, bool refin, bool refout)
Calculate a CRC-16 checksum of data with size len.
Definition: helpers.cpp:112
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:25
void dump_config() override
Definition: modbus.cpp:142
const float BUS
For communication buses like i2c/spi.
Definition: component.cpp:16
bool read_byte(uint8_t *data)
Definition: uart.h:29
uint16_t send_wait_time_
Definition: modbus.h:39
uint32_t last_modbus_byte_
Definition: modbus.h:42
uint8_t waiting_for_response
Definition: modbus.h:31
void loop() override
Definition: modbus.cpp:15
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7
void setup() override
Definition: modbus.cpp:10