ESPHome 2026.1.0-dev
Loading...
Searching...
No Matches
modbus.cpp
Go to the documentation of this file.
1#include "modbus.h"
4#include "esphome/core/log.h"
5
6namespace esphome {
7namespace modbus {
8
9static const char *const TAG = "modbus";
10
11// Maximum bytes to log for Modbus frames (truncated if larger)
12static constexpr size_t MODBUS_MAX_LOG_BYTES = 64;
13
15 if (this->flow_control_pin_ != nullptr) {
16 this->flow_control_pin_->setup();
17 }
18}
20 const uint32_t now = App.get_loop_component_start_time();
21
22 while (this->available()) {
23 uint8_t byte;
24 this->read_byte(&byte);
25 if (this->parse_modbus_byte_(byte)) {
26 this->last_modbus_byte_ = now;
27 } else {
28 size_t at = this->rx_buffer_.size();
29 if (at > 0) {
30 ESP_LOGV(TAG, "Clearing buffer of %d bytes - parse failed", at);
31 this->rx_buffer_.clear();
32 }
33 }
34 }
35
36 if (now - this->last_modbus_byte_ > 50) {
37 size_t at = this->rx_buffer_.size();
38 if (at > 0) {
39 ESP_LOGV(TAG, "Clearing buffer of %d bytes - timeout", at);
40 this->rx_buffer_.clear();
41 }
42
43 // stop blocking new send commands after sent_wait_time_ ms after response received
44 if (now - this->last_send_ > send_wait_time_) {
45 if (waiting_for_response > 0) {
46 ESP_LOGV(TAG, "Stop waiting for response from %d", waiting_for_response);
47 }
49 }
50 }
51}
52
53bool Modbus::parse_modbus_byte_(uint8_t byte) {
54 size_t at = this->rx_buffer_.size();
55 this->rx_buffer_.push_back(byte);
56 const uint8_t *raw = &this->rx_buffer_[0];
57 ESP_LOGVV(TAG, "Modbus received Byte %d (0X%x)", byte, byte);
58 // Byte 0: modbus address (match all)
59 if (at == 0)
60 return true;
61 uint8_t address = raw[0];
62 uint8_t function_code = raw[1];
63 // Byte 2: Size (with modbus rtu function code 4/3)
64 // See also https://en.wikipedia.org/wiki/Modbus
65 if (at == 2)
66 return true;
67
68 uint8_t data_len = raw[2];
69 uint8_t data_offset = 3;
70
71 // Per https://modbus.org/docs/Modbus_Application_Protocol_V1_1b3.pdf Ch 5 User-Defined function codes
72 if (((function_code >= FUNCTION_CODE_USER_DEFINED_SPACE_1_INIT) &&
73 (function_code <= FUNCTION_CODE_USER_DEFINED_SPACE_1_END)) ||
74 ((function_code >= FUNCTION_CODE_USER_DEFINED_SPACE_2_INIT) &&
75 (function_code <= FUNCTION_CODE_USER_DEFINED_SPACE_2_END))) {
76 // Handle user-defined function, since we don't know how big this ought to be,
77 // ideally we should delegate the entire length detection to whatever handler is
78 // installed, but wait, there is the CRC, and if we get a hit there is a good
79 // chance that this is a complete message ... admittedly there is a small chance is
80 // isn't but that is quite small given the purpose of the CRC in the first place
81
82 // Fewer than 2 bytes can't calc CRC
83 if (at < 2)
84 return true;
85
86 data_len = at - 2;
87 data_offset = 1;
88
89 uint16_t computed_crc = crc16(raw, data_offset + data_len);
90 uint16_t remote_crc = uint16_t(raw[data_offset + data_len]) | (uint16_t(raw[data_offset + data_len + 1]) << 8);
91
92 if (computed_crc != remote_crc)
93 return true;
94
95 ESP_LOGD(TAG, "Modbus user-defined function %02X found", function_code);
96
97 } else {
98 // data starts at 2 and length is 4 for read registers commands
99 if (this->role == ModbusRole::SERVER) {
100 if (function_code == ModbusFunctionCode::READ_COILS ||
105 data_offset = 2;
106 data_len = 4;
107 } else if (function_code == ModbusFunctionCode::WRITE_MULTIPLE_REGISTERS) {
108 if (at < 6) {
109 return true;
110 }
111 data_offset = 2;
112 // starting address (2 bytes) + quantity of registers (2 bytes) + byte count itself (1 byte) + actual byte count
113 data_len = 2 + 2 + 1 + raw[6];
114 }
115 } else {
116 // the response for write command mirrors the requests and data starts at offset 2 instead of 3 for read commands
117 if (function_code == ModbusFunctionCode::WRITE_SINGLE_COIL ||
121 data_offset = 2;
122 data_len = 4;
123 }
124 }
125
126 // Error ( msb indicates error )
127 // response format: Byte[0] = device address, Byte[1] function code | 0x80 , Byte[2] exception code, Byte[3-4] crc
129 data_offset = 2;
130 data_len = 1;
131 }
132
133 // Byte data_offset..data_offset+data_len-1: Data
134 if (at < data_offset + data_len)
135 return true;
136
137 // Byte 3+data_len: CRC_LO (over all bytes)
138 if (at == data_offset + data_len)
139 return true;
140
141 // Byte data_offset+len+1: CRC_HI (over all bytes)
142 uint16_t computed_crc = crc16(raw, data_offset + data_len);
143 uint16_t remote_crc = uint16_t(raw[data_offset + data_len]) | (uint16_t(raw[data_offset + data_len + 1]) << 8);
144 if (computed_crc != remote_crc) {
145 if (this->disable_crc_) {
146 ESP_LOGD(TAG, "Modbus CRC Check failed, but ignored! %02X!=%02X", computed_crc, remote_crc);
147 } else {
148 ESP_LOGW(TAG, "Modbus CRC Check failed! %02X!=%02X", computed_crc, remote_crc);
149 return false;
150 }
151 }
152 }
153 std::vector<uint8_t> data(this->rx_buffer_.begin() + data_offset, this->rx_buffer_.begin() + data_offset + data_len);
154 bool found = false;
155 for (auto *device : this->devices_) {
156 if (device->address_ == address) {
157 found = true;
158 // Is it an error response?
160 ESP_LOGD(TAG, "Modbus error function code: 0x%X exception: %d", function_code, raw[2]);
161 if (waiting_for_response != 0) {
162 device->on_modbus_error(function_code & FUNCTION_CODE_MASK, raw[2]);
163 } else {
164 // Ignore modbus exception not related to a pending command
165 ESP_LOGD(TAG, "Ignoring Modbus error - not expecting a response");
166 }
167 continue;
168 }
169 if (this->role == ModbusRole::SERVER) {
170 if (function_code == ModbusFunctionCode::READ_HOLDING_REGISTERS ||
172 device->on_modbus_read_registers(function_code, uint16_t(data[1]) | (uint16_t(data[0]) << 8),
173 uint16_t(data[3]) | (uint16_t(data[2]) << 8));
174 continue;
175 }
176 if (function_code == ModbusFunctionCode::WRITE_SINGLE_REGISTER ||
178 device->on_modbus_write_registers(function_code, data);
179 continue;
180 }
181 }
182 // fallthrough for other function codes
183 device->on_modbus_data(data);
184 }
185 }
187
188 if (!found) {
189 ESP_LOGW(TAG, "Got Modbus frame from unknown address 0x%02X! ", address);
190 }
191
192 // reset buffer
193 ESP_LOGV(TAG, "Clearing buffer of %d bytes - parse succeeded", at);
194 this->rx_buffer_.clear();
195 return true;
196}
197
199 ESP_LOGCONFIG(TAG, "Modbus:");
200 LOG_PIN(" Flow Control Pin: ", this->flow_control_pin_);
201 ESP_LOGCONFIG(TAG,
202 " Send Wait Time: %d ms\n"
203 " CRC Disabled: %s",
204 this->send_wait_time_, YESNO(this->disable_crc_));
205}
207 // After UART bus
208 return setup_priority::BUS - 1.0f;
209}
210
211void Modbus::send(uint8_t address, uint8_t function_code, uint16_t start_address, uint16_t number_of_entities,
212 uint8_t payload_len, const uint8_t *payload) {
213 static const size_t MAX_VALUES = 128;
214
215 // Only check max number of registers for standard function codes
216 // Some devices use non standard codes like 0x43
217 if (number_of_entities > MAX_VALUES && function_code <= ModbusFunctionCode::WRITE_MULTIPLE_REGISTERS) {
218 ESP_LOGE(TAG, "send too many values %d max=%zu", number_of_entities, MAX_VALUES);
219 return;
220 }
221
222 std::vector<uint8_t> data;
223 data.push_back(address);
224 data.push_back(function_code);
225 if (this->role == ModbusRole::CLIENT) {
226 data.push_back(start_address >> 8);
227 data.push_back(start_address >> 0);
228 if (function_code != ModbusFunctionCode::WRITE_SINGLE_COIL &&
230 data.push_back(number_of_entities >> 8);
231 data.push_back(number_of_entities >> 0);
232 }
233 }
234
235 if (payload != nullptr) {
236 if (this->role == ModbusRole::SERVER || function_code == ModbusFunctionCode::WRITE_MULTIPLE_COILS ||
237 function_code == ModbusFunctionCode::WRITE_MULTIPLE_REGISTERS) { // Write multiple
238 data.push_back(payload_len); // Byte count is required for write
239 } else {
240 payload_len = 2; // Write single register or coil
241 }
242 for (int i = 0; i < payload_len; i++) {
243 data.push_back(payload[i]);
244 }
245 }
246
247 auto crc = crc16(data.data(), data.size());
248 data.push_back(crc >> 0);
249 data.push_back(crc >> 8);
250
251 if (this->flow_control_pin_ != nullptr)
252 this->flow_control_pin_->digital_write(true);
253
254 this->write_array(data);
255 this->flush();
256
257 if (this->flow_control_pin_ != nullptr)
258 this->flow_control_pin_->digital_write(false);
260 last_send_ = millis();
261#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
262 char hex_buf[format_hex_pretty_size(MODBUS_MAX_LOG_BYTES)];
263#endif
264 ESP_LOGV(TAG, "Modbus write: %s", format_hex_pretty_to(hex_buf, data.data(), data.size()));
265}
266
267// Helper function for lambdas
268// Send raw command. Except CRC everything must be contained in payload
269void Modbus::send_raw(const std::vector<uint8_t> &payload) {
270 if (payload.empty()) {
271 return;
272 }
273
274 if (this->flow_control_pin_ != nullptr)
275 this->flow_control_pin_->digital_write(true);
276
277 auto crc = crc16(payload.data(), payload.size());
278 this->write_array(payload);
279 this->write_byte(crc & 0xFF);
280 this->write_byte((crc >> 8) & 0xFF);
281 this->flush();
282 if (this->flow_control_pin_ != nullptr)
283 this->flow_control_pin_->digital_write(false);
284 waiting_for_response = payload[0];
285#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
286 char hex_buf[format_hex_pretty_size(MODBUS_MAX_LOG_BYTES)];
287#endif
288 ESP_LOGV(TAG, "Modbus write raw: %s", format_hex_pretty_to(hex_buf, payload.data(), payload.size()));
289 last_send_ = millis();
290}
291
292} // namespace modbus
293} // namespace esphome
uint8_t address
Definition bl0906.h:4
uint8_t raw[35]
Definition bl0939.h:0
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.
virtual void setup()=0
virtual void digital_write(bool value)=0
bool parse_modbus_byte_(uint8_t byte)
Definition modbus.cpp:53
void send_raw(const std::vector< uint8_t > &payload)
Definition modbus.cpp:269
void setup() override
Definition modbus.cpp:14
uint16_t send_wait_time_
Definition modbus.h:49
uint8_t waiting_for_response
Definition modbus.h:39
uint32_t last_modbus_byte_
Definition modbus.h:52
GPIOPin * flow_control_pin_
Definition modbus.h:46
std::vector< ModbusDevice * > devices_
Definition modbus.h:54
void loop() override
Definition modbus.cpp:19
float get_setup_priority() const override
Definition modbus.cpp:206
void dump_config() override
Definition modbus.cpp:198
std::vector< uint8_t > rx_buffer_
Definition modbus.h:51
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:211
bool read_byte(uint8_t *data)
Definition uart.h:34
void write_byte(uint8_t data)
Definition uart.h:18
void write_array(const uint8_t *data, size_t len)
Definition uart.h:26
const uint8_t FUNCTION_CODE_MASK
const uint8_t FUNCTION_CODE_EXCEPTION_MASK
const uint8_t FUNCTION_CODE_USER_DEFINED_SPACE_2_INIT
const uint8_t FUNCTION_CODE_USER_DEFINED_SPACE_1_INIT
Modbus definitions from specs: https://modbus.org/docs/Modbus_Application_Protocol_V1_1b3....
const uint8_t FUNCTION_CODE_USER_DEFINED_SPACE_2_END
const uint8_t FUNCTION_CODE_USER_DEFINED_SPACE_1_END
const float BUS
For communication buses like i2c/spi.
Definition component.cpp:78
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
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:72
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:331
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:735
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.