ESPHome 2026.5.0b1
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::modbus {
7
8static const char *const TAG = "modbus";
9
10// Maximum bytes to log for Modbus frames (truncated if larger)
11static constexpr size_t MODBUS_MAX_LOG_BYTES = 64;
12
13// Approximate bits per character on the wire (depends on parity/stop bit config)
14static constexpr uint32_t MODBUS_BITS_PER_CHAR = 11;
15// Milliseconds per second
16static constexpr uint32_t MS_PER_SEC = 1000;
17
19 if (this->flow_control_pin_ != nullptr) {
20 this->flow_control_pin_->setup();
21 }
22
23 this->frame_delay_ms_ =
24 std::max(2, // 1750us minimum per spec - rounded up to 2ms.
25 // 3.5 characters * 11 bits per character * 1000ms/sec / (bits/sec) (Standard modbus frame delay)
26 (uint16_t) (3.5 * MODBUS_BITS_PER_CHAR * MS_PER_SEC / this->parent_->get_baud_rate()) + 1);
27
28 // When rx_full_threshold is configured (non-zero), the UART has a hardware FIFO with a
29 // meaningful threshold (e.g., ESP32 native UART), so we can calculate a precise delay.
30 // Otherwise (e.g., USB UART), use 50ms to handle data arriving in chunks.
31 static constexpr uint16_t DEFAULT_LONG_RX_BUFFER_DELAY_MS = 50;
32 size_t rx_threshold = this->parent_->get_rx_full_threshold();
35 ? (rx_threshold * MODBUS_BITS_PER_CHAR * MS_PER_SEC / this->parent_->get_baud_rate()) + 1
36 : DEFAULT_LONG_RX_BUFFER_DELAY_MS;
37}
38
40 // First process all available incoming data.
42
43 // If the response frame is finished (including interframe delay) - we timeout.
44 // The long_rx_buffer_delay accounts for long responses (larger than the UART rx_full_threshold) to avoid timeouts
45 // when the buffer is filling the back half of the response
46 const uint16_t timeout = std::max(
47 (uint16_t) this->frame_delay_ms_,
48 (uint16_t) (this->rx_buffer_.size() >= this->parent_->get_rx_full_threshold() ? this->long_rx_buffer_delay_ms_
49 : 0));
50 // We use millis() here and elsewhere instead of App.get_loop_component_start_time() to avoid stale timestamps
51 // It's critical in all timestamp comparisons that the left timestamp comes before the right one in time
52 // If we use a cached value in place of millis() and last_modbus_byte_ is updated inside our loop
53 // then the comparison is backwards (small negative which wraps to large positive) and will cause a false timeout
54 // So in this component we don't use any cached timestamp values to avoid these annoying bugs
55 if (millis() - this->last_modbus_byte_ > timeout) {
56 this->clear_rx_buffer_(LOG_STR("timeout after partial response"), true);
57 }
58
59 // If we're past the send_wait_time timeout and response buffer doesn't have the start of the expected response
60 if (this->waiting_for_response_ != 0 &&
61 millis() - this->last_send_ > this->last_send_tx_offset_ + this->send_wait_time_ &&
62 (this->rx_buffer_.empty() || this->rx_buffer_[0] != this->waiting_for_response_)) {
63 ESP_LOGW(TAG, "Stop waiting for response from %" PRIu8 " %" PRIu32 "ms after last send",
64 this->waiting_for_response_, millis() - this->last_send_);
65 this->waiting_for_response_ = 0;
66 }
67
68 // If there's no response pending and there's commands in the buffer
69 this->send_next_frame_();
70}
71
73 const uint32_t now = millis();
74
75 // We block transmission in any of these case:
76 // 1. There are bytes in the UART Rx buffer
77 // 2. There are bytes in our Rx buffer
78 // 3. We're waiting for a response
79 // 4. The last sent byte isn't more than frame_delay ms ago (i.e. wait to tell receivers that our previous Tx is done)
80 // 5. The last received byte isn't more than frame_delay ms ago (i.e. wait to be sure there isn't more Rx coming)
81 // 6. If we're a client - also wait for the turnaround delay, to give the servers time to process the previous message
82 return this->available() || !this->rx_buffer_.empty() || (this->waiting_for_response_ != 0) ||
84 (this->role == ModbusRole::CLIENT ? this->turnaround_delay_ms_ : 0)) ||
85 (now - this->last_modbus_byte_ <
86 this->frame_delay_ms_ + (this->role == ModbusRole::CLIENT ? this->turnaround_delay_ms_ : 0));
87}
88
89bool Modbus::tx_buffer_empty() { return this->tx_buffer_.empty(); }
90
92 // Read all available bytes in batches to reduce UART call overhead.
93 size_t avail = this->available();
94 uint8_t buf[64];
95 while (avail > 0) {
96 size_t to_read = std::min(avail, sizeof(buf));
97 if (!this->read_array(buf, to_read)) {
98 break;
99 }
100 avail -= to_read;
101 for (size_t i = 0; i < to_read; i++) {
102 if (this->rx_buffer_.empty()) {
103 ESP_LOGV(TAG, "Received first byte %" PRIu8 " (0X%x) %" PRIu32 "ms after last send", buf[i], buf[i],
104 millis() - this->last_send_);
105 } else {
106 ESP_LOGVV(TAG, "Received byte %" PRIu8 " (0X%x) %" PRIu32 "ms after last send", buf[i], buf[i],
107 millis() - this->last_send_);
108 }
109
110 // If the bytes in the rx buffer do not parse, clear out the buffer
111 if (!this->parse_modbus_byte_(buf[i])) {
112 this->clear_rx_buffer_(LOG_STR("parse failed"), true);
113 }
114 this->last_modbus_byte_ = millis();
115 }
116 }
117}
118
119bool Modbus::parse_modbus_byte_(uint8_t byte) {
120 size_t at = this->rx_buffer_.size();
121 this->rx_buffer_.push_back(byte);
122 const uint8_t *raw = &this->rx_buffer_[0];
123
124 // Byte 0: modbus address (match all)
125 if (at == 0)
126 return true;
127 // Byte 1: function code
128 if (at == 1)
129 return true;
130 // Byte 2: Size (with modbus rtu function code 4/3)
131 // See also https://en.wikipedia.org/wiki/Modbus
132 if (at == 2)
133 return true;
134
135 uint8_t address = raw[0];
136 uint8_t function_code = raw[1];
137
138 uint8_t data_len = raw[2];
139 uint8_t data_offset = 3;
140
141 // Per https://modbus.org/docs/Modbus_Application_Protocol_V1_1b3.pdf Ch 5 User-Defined function codes
142 if (((function_code >= FUNCTION_CODE_USER_DEFINED_SPACE_1_INIT) &&
143 (function_code <= FUNCTION_CODE_USER_DEFINED_SPACE_1_END)) ||
144 ((function_code >= FUNCTION_CODE_USER_DEFINED_SPACE_2_INIT) &&
145 (function_code <= FUNCTION_CODE_USER_DEFINED_SPACE_2_END))) {
146 // Handle user-defined function, since we don't know how big this ought to be,
147 // ideally we should delegate the entire length detection to whatever handler is
148 // installed, but wait, there is the CRC, and if we get a hit there is a good
149 // chance that this is a complete message ... admittedly there is a small chance is
150 // isn't but that is quite small given the purpose of the CRC in the first place
151
152 data_len = at - 2;
153 data_offset = 1;
154
155 uint16_t computed_crc = crc16(raw, data_offset + data_len);
156 uint16_t remote_crc = uint16_t(raw[data_offset + data_len]) | (uint16_t(raw[data_offset + data_len + 1]) << 8);
157
158 if (computed_crc != remote_crc)
159 return true;
160
161 ESP_LOGD(TAG, "User-defined function %02X found", function_code);
162
163 } else {
164 // data starts at 2 and length is 4 for read registers commands
165 if (this->role == ModbusRole::SERVER) {
166 if (function_code == ModbusFunctionCode::READ_COILS ||
171 data_offset = 2;
172 data_len = 4;
173 } else if (function_code == ModbusFunctionCode::WRITE_MULTIPLE_REGISTERS) {
174 if (at < 6) {
175 return true;
176 }
177 data_offset = 2;
178 // starting address (2 bytes) + quantity of registers (2 bytes) + byte count itself (1 byte) + actual byte count
179 data_len = 2 + 2 + 1 + raw[6];
180 }
181 } else {
182 // the response for write command mirrors the requests and data starts at offset 2 instead of 3 for read commands
183 if (function_code == ModbusFunctionCode::WRITE_SINGLE_COIL ||
187 data_offset = 2;
188 data_len = 4;
189 }
190 }
191
192 // Error ( msb indicates error )
193 // response format: Byte[0] = device address, Byte[1] function code | 0x80 , Byte[2] exception code, Byte[3-4] crc
195 data_offset = 2;
196 data_len = 1;
197 }
198
199 // Byte data_offset..data_offset+data_len-1: Data
200 if (at < data_offset + data_len)
201 return true;
202
203 // Byte 3+data_len: CRC_LO (over all bytes)
204 if (at == data_offset + data_len)
205 return true;
206
207 // Byte data_offset+len+1: CRC_HI (over all bytes)
208 uint16_t computed_crc = crc16(raw, data_offset + data_len);
209 uint16_t remote_crc = uint16_t(raw[data_offset + data_len]) | (uint16_t(raw[data_offset + data_len + 1]) << 8);
210 if (computed_crc != remote_crc) {
211 if (this->disable_crc_) {
212 ESP_LOGD(TAG, "CRC check failed %" PRIu32 "ms after last send; ignoring", millis() - this->last_send_);
213#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
214 char hex_buf[format_hex_pretty_size(MODBUS_MAX_LOG_BYTES)];
215#endif
216 ESP_LOGVV(TAG, " (%02X != %02X) %s", computed_crc, remote_crc,
217 format_hex_pretty_to(hex_buf, this->rx_buffer_.data(), this->rx_buffer_.size()));
218 } else {
219 ESP_LOGW(TAG, "CRC check failed %" PRIu32 "ms after last send", millis() - this->last_send_);
220#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
221 char hex_buf[format_hex_pretty_size(MODBUS_MAX_LOG_BYTES)];
222#endif
223 ESP_LOGVV(TAG, " (%02X != %02X) %s", computed_crc, remote_crc,
224 format_hex_pretty_to(hex_buf, this->rx_buffer_.data(), this->rx_buffer_.size()));
225 return false;
226 }
227 }
228 }
229 std::vector<uint8_t> data(this->rx_buffer_.begin() + data_offset, this->rx_buffer_.begin() + data_offset + data_len);
230 bool found = false;
231 for (auto *device : this->devices_) {
232 if (device->address_ == address) {
233 found = true;
234 if (this->role == ModbusRole::SERVER) {
235 if (function_code == ModbusFunctionCode::READ_HOLDING_REGISTERS ||
237 device->on_modbus_read_registers(function_code, uint16_t(data[1]) | (uint16_t(data[0]) << 8),
238 uint16_t(data[3]) | (uint16_t(data[2]) << 8));
239 } else if (function_code == ModbusFunctionCode::WRITE_SINGLE_REGISTER ||
241 device->on_modbus_write_registers(function_code, data);
242 }
243 } else { // We're a client
244 // Is it an error response?
246 uint8_t exception = raw[2];
247 ESP_LOGW(TAG,
248 "Error function code: 0x%X exception: %" PRIu8 ", address: %" PRIu8 ", %" PRIu32
249 "ms after last send",
250 function_code, exception, address, millis() - this->last_send_);
251 if (this->waiting_for_response_ == address) {
252 device->on_modbus_error(function_code & FUNCTION_CODE_MASK, exception);
253 } else {
254 // Ignore modbus exception not related to a pending command
255 ESP_LOGD(TAG, "Ignoring error - not expecting a response from %" PRIu8 "", address);
256 }
257 } else { // Not an error response
258 if (this->waiting_for_response_ == address) {
259 device->on_modbus_data(data);
260 } else {
261 // Ignore modbus response not related to a pending command
262 ESP_LOGW(TAG, "Ignoring response - not expecting a response from %" PRIu8 ", %" PRIu32 "ms after last send",
263 address, millis() - this->last_send_);
264 }
265 }
266 }
267 }
268 }
269
270 if (!found && this->role == ModbusRole::CLIENT) {
271 ESP_LOGW(TAG, "Got frame from unknown address %" PRIu8 ", %" PRIu32 "ms after last send", address,
272 millis() - this->last_send_);
273 }
274
275 this->clear_rx_buffer_(LOG_STR("parse succeeded"));
276
277 if (this->waiting_for_response_ == address)
278 this->waiting_for_response_ = 0;
279
280 return true;
281}
282
284 if (this->tx_buffer_.empty())
285 return;
286
287 if (this->tx_blocked())
288 return;
289
290 const ModbusDeviceCommand &frame = this->tx_buffer_.front();
291
292 if (this->role == ModbusRole::CLIENT) {
293 this->waiting_for_response_ = frame.data.get()[0];
294 }
295
296 if (this->flow_control_pin_ != nullptr) {
297 this->flow_control_pin_->digital_write(true);
298 this->write_array(frame.data.get(), frame.size);
299 this->flush();
300 this->flow_control_pin_->digital_write(false);
301 this->last_send_tx_offset_ = 0;
302 } else {
303 this->write_array(frame.data.get(), frame.size);
304 this->last_send_tx_offset_ = frame.size * MODBUS_BITS_PER_CHAR * MS_PER_SEC / this->parent_->get_baud_rate() + 1;
305 }
306
307#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
308 char hex_buf[format_hex_pretty_size(MODBUS_MAX_LOG_BYTES)];
309#endif
310 ESP_LOGV(TAG, "Write: %s %" PRIu32 "ms after last send", format_hex_pretty_to(hex_buf, frame.data.get(), frame.size),
311 millis() - this->last_send_);
312 this->last_send_ = millis();
313 this->tx_buffer_.pop_front();
314 if (!this->tx_buffer_.empty()) {
315 ESP_LOGV(TAG, "Write queue contains %zu items.", this->tx_buffer_.size());
316 }
317}
318
320 ESP_LOGCONFIG(TAG,
321 "Modbus:\n"
322 " Send Wait Time: %d ms\n"
323 " Turnaround Time: %d ms\n"
324 " Frame Delay: %d ms\n"
325 " Long Rx Buffer Delay: %d ms\n"
326 " CRC Disabled: %s",
328 this->long_rx_buffer_delay_ms_, YESNO(this->disable_crc_));
329 LOG_PIN(" Flow Control Pin: ", this->flow_control_pin_);
330}
332 // After UART bus
333 return setup_priority::BUS - 1.0f;
334}
335
336void Modbus::send(uint8_t address, uint8_t function_code, uint16_t start_address, uint16_t number_of_entities,
337 uint8_t payload_len, const uint8_t *payload) {
338 static const size_t MAX_VALUES = 128;
339
340 // Only check max number of registers for standard function codes
341 // Some devices use non standard codes like 0x43
342 if (number_of_entities > MAX_VALUES && function_code <= ModbusFunctionCode::WRITE_MULTIPLE_REGISTERS) {
343 ESP_LOGE(TAG, "send too many values %d max=%zu", number_of_entities, MAX_VALUES);
344 return;
345 }
346
347 uint8_t data[MAX_FRAME_SIZE];
348 size_t pos = 0;
349
350 data[pos++] = address;
351 data[pos++] = function_code;
352 if (this->role == ModbusRole::CLIENT) {
353 data[pos++] = start_address >> 8;
354 data[pos++] = start_address >> 0;
355 if (function_code != ModbusFunctionCode::WRITE_SINGLE_COIL &&
357 data[pos++] = number_of_entities >> 8;
358 data[pos++] = number_of_entities >> 0;
359 }
360 }
361
362 if (payload != nullptr) {
363 if (this->role == ModbusRole::SERVER || function_code == ModbusFunctionCode::WRITE_MULTIPLE_COILS ||
364 function_code == ModbusFunctionCode::WRITE_MULTIPLE_REGISTERS) { // Write multiple
365 data[pos++] = payload_len; // Byte count is required for write
366 } else {
367 payload_len = 2; // Write single register or coil
368 }
369 if (payload_len + pos + 2 > MAX_FRAME_SIZE) { // Check if payload fits (accounting for CRC)
370 ESP_LOGE(TAG, "Payload too large to send: %d bytes", payload_len);
371 return;
372 }
373 for (int i = 0; i < payload_len; i++) {
374 data[pos++] = payload[i];
375 }
376 }
377
378 this->queue_raw_(data, pos);
379}
380
381// Helper function for lambdas
382// Send raw command. Except CRC everything must be contained in payload
383void Modbus::send_raw(const std::vector<uint8_t> &payload) {
384 if (payload.empty()) {
385 return;
386 }
387 // Frame size: payload + CRC(2)
388 if (payload.size() + 2 > MAX_FRAME_SIZE) {
389 ESP_LOGE(TAG, "Attempted to send frame larger than max frame size of %d bytes", MAX_FRAME_SIZE);
390 return;
391 }
392 // Use stack buffer - Modbus frames are small and bounded
393 uint8_t data[MAX_FRAME_SIZE];
394
395 std::memcpy(data, payload.data(), payload.size());
396
397 this->queue_raw_(data, payload.size());
398}
399
400// Assume data and length is valid and append CRC, then queue for sending. Used internally to avoid unnecessary copying
401// of data into vectors
402void Modbus::queue_raw_(const uint8_t *data, uint16_t len) {
403 if (this->tx_buffer_.size() < MODBUS_TX_BUFFER_SIZE) {
404 this->tx_buffer_.emplace_back(data, len);
405 } else {
406#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_ERROR
407 char hex_buf[format_hex_pretty_size(MODBUS_MAX_LOG_BYTES)];
408#endif
409 ESP_LOGE(TAG, "Write buffer full, dropped: %s", format_hex_pretty_to(hex_buf, data, len));
410 }
411}
412
413void Modbus::clear_rx_buffer_(const LogString *reason, bool warn) {
414 size_t at = this->rx_buffer_.size();
415 if (at > 0) {
416 if (warn) {
417 ESP_LOGW(TAG, "Clearing buffer of %zu bytes - %s %" PRIu32 "ms after last send", at, LOG_STR_ARG(reason),
418 millis() - this->last_send_);
419 } else {
420 ESP_LOGV(TAG, "Clearing buffer of %zu bytes - %s %" PRIu32 "ms after last send", at, LOG_STR_ARG(reason),
421 millis() - this->last_send_);
422 }
423 this->rx_buffer_.clear();
424 }
425}
426
427} // namespace esphome::modbus
uint8_t address
Definition bl0906.h:4
uint8_t raw[35]
Definition bl0939.h:0
virtual void setup()=0
virtual void digital_write(bool value)=0
std::deque< ModbusDeviceCommand > tx_buffer_
Definition modbus.h:88
bool parse_modbus_byte_(uint8_t byte)
Definition modbus.cpp:119
void send_raw(const std::vector< uint8_t > &payload)
Definition modbus.cpp:383
void setup() override
Definition modbus.cpp:18
uint16_t frame_delay_ms_
Definition modbus.h:74
uint16_t send_wait_time_
Definition modbus.h:76
uint8_t waiting_for_response_
Definition modbus.h:78
uint32_t last_modbus_byte_
Definition modbus.h:71
GPIOPin * flow_control_pin_
Definition modbus.h:81
std::vector< ModbusDevice * > devices_
Definition modbus.h:84
uint32_t last_send_tx_offset_
Definition modbus.h:73
void loop() override
Definition modbus.cpp:39
void queue_raw_(const uint8_t *data, uint16_t len)
Definition modbus.cpp:402
float get_setup_priority() const override
Definition modbus.cpp:331
uint16_t long_rx_buffer_delay_ms_
Definition modbus.h:75
void dump_config() override
Definition modbus.cpp:319
void receive_and_parse_modbus_bytes_()
Definition modbus.cpp:91
std::vector< uint8_t > rx_buffer_
Definition modbus.h:83
void clear_rx_buffer_(const LogString *reason, bool warn=false)
Definition modbus.cpp:413
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:336
uint16_t turnaround_delay_ms_
Definition modbus.h:77
static constexpr size_t RX_FULL_THRESHOLD_UNSET
UARTFlushResult flush()
Definition uart.h:48
optional< std::array< uint8_t, N > > read_array()
Definition uart.h:38
UARTComponent * parent_
Definition uart.h:73
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
constexpr float BUS
For communication buses like i2c/spi.
Definition component.h:37
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:86
std::string size_t len
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:341
size_t size_t pos
Definition helpers.h:1038
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:1386
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:28
static void uint32_t
std::unique_ptr< uint8_t[]> data
Definition modbus.h:26