ESPHome  2024.7.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  // data starts at 2 and length is 4 for read registers commands
81  if (this->role == ModbusRole::SERVER && (function_code == 0x3 || function_code == 0x4)) {
82  data_offset = 2;
83  data_len = 4;
84  }
85 
86  // the response for write command mirrors the requests and data starts at offset 2 instead of 3 for read commands
87  if (function_code == 0x5 || function_code == 0x06 || function_code == 0xF || function_code == 0x10) {
88  data_offset = 2;
89  data_len = 4;
90  }
91 
92  // Error ( msb indicates error )
93  // response format: Byte[0] = device address, Byte[1] function code | 0x80 , Byte[2] exception code, Byte[3-4] crc
94  if ((function_code & 0x80) == 0x80) {
95  data_offset = 2;
96  data_len = 1;
97  }
98 
99  // Byte data_offset..data_offset+data_len-1: Data
100  if (at < data_offset + data_len)
101  return true;
102 
103  // Byte 3+data_len: CRC_LO (over all bytes)
104  if (at == data_offset + data_len)
105  return true;
106 
107  // Byte data_offset+len+1: CRC_HI (over all bytes)
108  uint16_t computed_crc = crc16(raw, data_offset + data_len);
109  uint16_t remote_crc = uint16_t(raw[data_offset + data_len]) | (uint16_t(raw[data_offset + data_len + 1]) << 8);
110  if (computed_crc != remote_crc) {
111  if (this->disable_crc_) {
112  ESP_LOGD(TAG, "Modbus CRC Check failed, but ignored! %02X!=%02X", computed_crc, remote_crc);
113  } else {
114  ESP_LOGW(TAG, "Modbus CRC Check failed! %02X!=%02X", computed_crc, remote_crc);
115  return false;
116  }
117  }
118  }
119  std::vector<uint8_t> data(this->rx_buffer_.begin() + data_offset, this->rx_buffer_.begin() + data_offset + data_len);
120  bool found = false;
121  for (auto *device : this->devices_) {
122  if (device->address_ == address) {
123  // Is it an error response?
124  if ((function_code & 0x80) == 0x80) {
125  ESP_LOGD(TAG, "Modbus error function code: 0x%X exception: %d", function_code, raw[2]);
126  if (waiting_for_response != 0) {
127  device->on_modbus_error(function_code & 0x7F, raw[2]);
128  } else {
129  // Ignore modbus exception not related to a pending command
130  ESP_LOGD(TAG, "Ignoring Modbus error - not expecting a response");
131  }
132  } else if (this->role == ModbusRole::SERVER && (function_code == 0x3 || function_code == 0x4)) {
133  device->on_modbus_read_registers(function_code, uint16_t(data[1]) | (uint16_t(data[0]) << 8),
134  uint16_t(data[3]) | (uint16_t(data[2]) << 8));
135  } else {
136  device->on_modbus_data(data);
137  }
138  found = true;
139  }
140  }
142 
143  if (!found) {
144  ESP_LOGW(TAG, "Got Modbus frame from unknown address 0x%02X! ", address);
145  }
146 
147  // return false to reset buffer
148  return false;
149 }
150 
152  ESP_LOGCONFIG(TAG, "Modbus:");
153  LOG_PIN(" Flow Control Pin: ", this->flow_control_pin_);
154  ESP_LOGCONFIG(TAG, " Send Wait Time: %d ms", this->send_wait_time_);
155  ESP_LOGCONFIG(TAG, " CRC Disabled: %s", YESNO(this->disable_crc_));
156 }
158  // After UART bus
159  return setup_priority::BUS - 1.0f;
160 }
161 
162 void Modbus::send(uint8_t address, uint8_t function_code, uint16_t start_address, uint16_t number_of_entities,
163  uint8_t payload_len, const uint8_t *payload) {
164  static const size_t MAX_VALUES = 128;
165 
166  // Only check max number of registers for standard function codes
167  // Some devices use non standard codes like 0x43
168  if (number_of_entities > MAX_VALUES && function_code <= 0x10) {
169  ESP_LOGE(TAG, "send too many values %d max=%zu", number_of_entities, MAX_VALUES);
170  return;
171  }
172 
173  std::vector<uint8_t> data;
174  data.push_back(address);
175  data.push_back(function_code);
176  if (this->role == ModbusRole::CLIENT) {
177  data.push_back(start_address >> 8);
178  data.push_back(start_address >> 0);
179  if (function_code != 0x5 && function_code != 0x6) {
180  data.push_back(number_of_entities >> 8);
181  data.push_back(number_of_entities >> 0);
182  }
183  }
184 
185  if (payload != nullptr) {
186  if (this->role == ModbusRole::SERVER || function_code == 0xF || function_code == 0x10) { // Write multiple
187  data.push_back(payload_len); // Byte count is required for write
188  } else {
189  payload_len = 2; // Write single register or coil
190  }
191  for (int i = 0; i < payload_len; i++) {
192  data.push_back(payload[i]);
193  }
194  }
195 
196  auto crc = crc16(data.data(), data.size());
197  data.push_back(crc >> 0);
198  data.push_back(crc >> 8);
199 
200  if (this->flow_control_pin_ != nullptr)
201  this->flow_control_pin_->digital_write(true);
202 
203  this->write_array(data);
204  this->flush();
205 
206  if (this->flow_control_pin_ != nullptr)
207  this->flow_control_pin_->digital_write(false);
208  waiting_for_response = address;
209  last_send_ = millis();
210  ESP_LOGV(TAG, "Modbus write: %s", format_hex_pretty(data).c_str());
211 }
212 
213 // Helper function for lambdas
214 // Send raw command. Except CRC everything must be contained in payload
215 void Modbus::send_raw(const std::vector<uint8_t> &payload) {
216  if (payload.empty()) {
217  return;
218  }
219 
220  if (this->flow_control_pin_ != nullptr)
221  this->flow_control_pin_->digital_write(true);
222 
223  auto crc = crc16(payload.data(), payload.size());
224  this->write_array(payload);
225  this->write_byte(crc & 0xFF);
226  this->write_byte((crc >> 8) & 0xFF);
227  this->flush();
228  if (this->flow_control_pin_ != nullptr)
229  this->flow_control_pin_->digital_write(false);
230  waiting_for_response = payload[0];
231  ESP_LOGV(TAG, "Modbus write raw: %s", format_hex_pretty(payload).c_str());
232  last_send_ = millis();
233 }
234 
235 } // namespace modbus
236 } // 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:49
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:51
void send_raw(const std::vector< uint8_t > &payload)
Definition: modbus.cpp:215
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:162
std::vector< ModbusDevice * > devices_
Definition: modbus.h:52
float get_setup_priority() const override
Definition: modbus.cpp:157
virtual void setup()=0
GPIOPin * flow_control_pin_
Definition: modbus.h:44
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:151
ModbusRole role
Definition: modbus.h:41
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:47
uint32_t last_modbus_byte_
Definition: modbus.h:50
uint8_t waiting_for_response
Definition: modbus.h:37
void loop() override
Definition: modbus.cpp:15
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
void setup() override
Definition: modbus.cpp:10