ESPHome 2026.8.1
Loading...
Searching...
No Matches
modbus.cpp
Go to the documentation of this file.
1#include "modbus.h"
2
3#include <algorithm>
4
7#include "esphome/core/log.h"
8
9namespace esphome::modbus {
10
11static const char *const TAG = "modbus";
12
13// Maximum bytes to log for Modbus frames (truncated if larger)
14static constexpr size_t MODBUS_MAX_LOG_BYTES = 64;
15
16// Approximate bits per character on the wire (depends on parity/stop bit config)
17static constexpr uint32_t MODBUS_BITS_PER_CHAR = 11;
18// Milliseconds per second
19static constexpr uint32_t MS_PER_SEC = 1000;
20
21// Shortest gap between two "no device accepted broadcast" warnings
22static constexpr uint32_t UNACCEPTED_BROADCAST_WARN_INTERVAL_MS = 60 * MS_PER_SEC;
23
25 if (this->flow_control_pin_ != nullptr) {
26 this->flow_control_pin_->setup();
27 }
28
29 this->frame_delay_ms_ =
30 std::max(2, // 1750us minimum per spec - rounded up to 2ms.
31 // 3.5 characters * 11 bits per character * 1000ms/sec / (bits/sec) (Standard modbus frame delay)
32 (uint16_t) (3.5 * MODBUS_BITS_PER_CHAR * MS_PER_SEC / this->parent_->get_baud_rate()) + 1);
33
34 // When rx_full_threshold is configured (non-zero), the UART has a hardware FIFO with a
35 // meaningful threshold (e.g., ESP32 native UART), so we can calculate a precise delay.
36 // Otherwise (e.g., USB UART), use 50ms to handle data arriving in chunks.
37 static constexpr uint16_t DEFAULT_LONG_RX_BUFFER_DELAY_MS = 50;
38 size_t rx_threshold = this->parent_->get_rx_full_threshold();
41 ? (rx_threshold * MODBUS_BITS_PER_CHAR * MS_PER_SEC / this->parent_->get_baud_rate()) + 1
42 : DEFAULT_LONG_RX_BUFFER_DELAY_MS;
43}
44
46 // Receive any available bytes from UART
47 this->receive_bytes_();
48
49 // Parse bytes into frames and process them
50 this->parse_modbus_frames();
51}
52
54 // Drain anything owed since the last loop (e.g. an external clear) before the watchdog runs, so it
55 // never times out an entry whose pending count has not been drained. No-op when nothing is owed.
56 this->sweep_();
57
58 this->Modbus::loop(); // receive bytes and parse frames
59
60 // Send-wait watchdog: only the cheap time check runs at loop rate; expire_waiting_() looks the
61 // entry up and holds off if the response has started arriving.
62 if (this->waiting_for_response_ &&
64 this->expire_waiting_();
65 }
66
67 this->sweep_(); // deliver owed callbacks with the hub quiescent
68 this->send_next_frame_();
69}
70
73 if (cmd == nullptr) {
74 this->waiting_for_response_ = false;
75 return;
76 }
77 if (!this->rx_buffer_.empty() && this->rx_buffer_[0] == cmd->frame.address()) {
78 // The start of the response is in the buffer: let the frame finish arriving.
79 return;
80 }
81 // Only a genuine WAITING entry warrants the log (a cleared or interrupted shell timing out is expected).
82 if (cmd->state == FrameState::WAITING) {
83 ESP_LOGW(TAG, "Stop waiting for response from %" PRIu8 " %" PRIu32 "ms after last send", cmd->frame.address(),
84 this->last_receive_check_ - this->last_send_);
85 }
86 // Deliver on_no_response directly, the way the parse path delivers response()/error(): the entry
87 // lands in TIMED_OUT and the following sweep reschedules a retry or erases it. Free the
88 // wire first so a resend from inside the callback sees it available.
89 this->waiting_for_response_ = false;
90 this->sweep_needed_ = true;
91 cmd->timed_out();
92}
93
95 // If the response frame is finished (including interframe delay) - we timeout.
96 // The long_rx_buffer_delay accounts for long responses (larger than the UART rx_full_threshold) to avoid timeouts
97 // when the buffer is filling the back half of the response
98 const uint16_t timeout = std::max(
99 (uint16_t) this->frame_delay_ms_,
100 (uint16_t) (this->rx_buffer_.size() >= this->parent_->get_rx_full_threshold() ? this->long_rx_buffer_delay_ms_
101 : 0));
102
103 return this->last_receive_check_ - this->last_modbus_byte_ > timeout;
104}
105
107 // We use millis() here and elsewhere instead of App.get_loop_component_start_time() to avoid stale timestamps
108 // It's critical in all timestamp comparisons that the left timestamp comes before the right one in time
109 // If we use a cached value in place of millis() and last_modbus_byte_ is updated inside our loop
110 // then the comparison is backwards (small negative which wraps to large positive) and will cause a false timeout
111 // So in this component we don't use any cached timestamp values to avoid these annoying bugs
112 const uint32_t now = millis();
113 return std::max({(int32_t) 0,
114 (int32_t) (this->last_send_tx_offset_ + this->frame_delay_ms_ - (now - this->last_send_)),
115 (int32_t) (this->frame_delay_ms_ - (now - this->last_modbus_byte_))});
116}
117
119 const uint32_t now = millis();
120 return std::max({(int32_t) 0,
121 (int32_t) (this->last_send_tx_offset_ + this->frame_delay_ms_ + this->turnaround_delay_ms_ -
122 (now - this->last_send_)),
123 (int32_t) (this->frame_delay_ms_ + this->turnaround_delay_ms_ - (now - this->last_modbus_byte_))});
124}
125
127 // We block transmission in any of these cases:
128 // 1. There are bytes in the UART Rx buffer
129 // 2. There are bytes in our Rx buffer
130 // 3. The last sent byte isn't more than tx_delay ms ago (i.e. wait to tell receivers that our previous Tx is done)
131 // 4. The last received byte isn't more than tx_delay ms ago (i.e. wait to be sure there isn't more Rx coming)
132 // N.B. We allow a small delay (MODBUS_TX_MAX_DELAY_MS) to avoid looping on small delays. This gets handled by
133 // send_frame_.
134 return this->available() || !this->rx_buffer_.empty() || this->tx_delay_remaining() > MODBUS_TX_MAX_DELAY_MS;
135}
136
138 // We block transmission in any of these case:
139 // 1. We're waiting for a response (a waiting entry: WAITING/INTERRUPTED/WAITING_RETIRED/INTERRUPTED_RETIRED)
140 // 2. Any of the base class tx_blocked conditions
141 return this->waiting_for_response_ || this->Modbus::tx_blocked();
142}
143
145 // "Empty" for ready_for_immediate_send(): no one-shot is queued ahead of the caller. Entries in
146 // other states are mid-transaction or owed bookkeeping, not queued sends - and a READY continuous
147 // poll does not count either, since it ranks below every one-shot, so a new send goes out first.
148 for (const auto &cmd : this->tx_buffer_) {
149 if (cmd.state == FrameState::READY && !cmd.continuous)
150 return false;
151 }
152 return true;
153}
154
156 this->last_receive_check_ = millis();
157 size_t bytes = this->available();
158
159 if (bytes) {
160 size_t buffer_size = this->rx_buffer_.size();
162 this->rx_buffer_.resize(buffer_size + bytes);
163 if (!this->read_array(this->rx_buffer_.data() + buffer_size, bytes)) {
164 this->rx_buffer_.resize(buffer_size);
165 return;
166 }
167 if (buffer_size == 0) {
168 ESP_LOGV(TAG, "Received first byte %" PRIu8 " (0X%x) of %zu bytes %" PRIu32 "ms after last send",
169 this->rx_buffer_[0], this->rx_buffer_[0], this->rx_buffer_.size(), millis() - this->last_send_);
170 }
171 }
172}
173
175 if (!this->rx_buffer_.empty()) {
176 size_t size;
177 do {
178 size = this->rx_buffer_.size();
179 if (!this->parse_modbus_server_frame_())
180 this->clear_rx_buffer_(LOG_STR("parse failed"), true);
181 } while (!this->rx_buffer_.empty() && size > this->rx_buffer_.size());
182 if (this->timeout_())
183 this->clear_rx_buffer_(LOG_STR("timeout after partial response"), true);
184 }
185}
186
188 while (!this->rx_buffer_.empty()) {
189 size_t size = this->rx_buffer_.size();
190 ESP_LOGVV(TAG, "Parsing frames buffer size = %" PRIu32, size);
191 bool retry_as_client = false;
192 // A broadcast is a client request, never a peer response; clear any stale expectation (RTU is half-duplex).
193 const bool is_broadcast = this->rx_buffer_[0] == BROADCAST_ADDRESS;
194 if (is_broadcast)
195 this->expecting_peer_response_ = 0;
196 if (this->expecting_peer_response_ != 0) {
197 if (!this->parse_modbus_server_frame_()) {
198 ESP_LOGV(TAG, "Stop expecting peer response from %" PRIu8 " due to parse failure, and retry parse",
200 this->expecting_peer_response_ = 0;
201 retry_as_client = true;
202 } else if (this->timeout_() && size == this->rx_buffer_.size()) {
203 // If we timed out and the above parse attempt did not consume data, stop expecting a response
204 ESP_LOGV(TAG,
205 "Stop expecting peer response from %" PRIu8 " due to timeout after partial response, and retry parse",
207 this->expecting_peer_response_ = 0;
208 retry_as_client = true;
209 }
210 } else {
211 if (!this->parse_modbus_client_frame_())
212 this->clear_rx_buffer_(LOG_STR("parse failed"), true);
213 }
214 // Stop if the buffer didn't shrink (no frame consumed) and no mode switch triggered a retry
215 if (!retry_as_client && size <= this->rx_buffer_.size())
216 break;
217 }
218 if (this->timeout_())
219 this->clear_rx_buffer_(LOG_STR("timeout after partial response"), true);
220}
221
222uint16_t Modbus::find_frame_end_by_crc_(uint16_t min_length) const {
223 // Unknown-length functions (user-defined codes, unimplemented management codes, unassigned values)
224 // could be any length - we have to rely on the CRC to determine completeness.
225 // If a CRC match is never found, the buffer will eventually overflow and be cleared.
226 const uint8_t *raw = &this->rx_buffer_[0];
227 const size_t size = this->rx_buffer_.size();
228 const auto max_len = static_cast<uint16_t>(std::min(size, size_t(MAX_FRAME_SIZE)));
229 if (min_length > max_len)
230 return 0;
231 // The Modbus CRC (poly 0xa001, refin/refout false) keeps its running state in the returned value,
232 // so we seed once over the first min_length bytes and extend one byte at a time instead of
233 // recomputing the whole prefix for every candidate length.
234 uint16_t crc = crc16(raw, min_length);
235 if (crc == 0)
236 return min_length;
237 for (uint16_t len = min_length; len < max_len; len++) {
238 crc = crc16(&raw[len], 1, crc);
239 if (crc == 0)
240 return len + 1;
241 }
242 return 0;
243}
244
246 size_t size = this->rx_buffer_.size();
247 uint16_t frame_length = helpers::server_frame_length(this->rx_buffer_.data(), this->rx_buffer_.size());
248
249 if (size < frame_length)
250 return true;
251
252 uint8_t address = this->rx_buffer_[0];
253 uint8_t function_code = this->rx_buffer_[1];
254
255 if (helpers::is_function_code_unknown_length(function_code)) {
256 frame_length = this->find_frame_end_by_crc_(frame_length);
257 if (frame_length == 0)
258 return size < MAX_FRAME_SIZE; // Continue to parse until we hit max size
259 ESP_LOGD(TAG, "Unknown-length function %02X found", function_code);
260 } else {
261 if (crc16(&this->rx_buffer_[0], frame_length) != 0)
262 return false;
263 }
264
265 // Process before clearing: process_modbus_server_frame (receiving a response or peer message) never sends a reply
266 // synchronously. We can safely point directly into rx_buffer_ and avoid a copy.
267 // The PDU is the frame without the leading address and the trailing CRC.
268 std::span<const uint8_t> pdu(this->rx_buffer_.data() + 1, frame_length - 3);
269
270 this->process_modbus_server_frame(address, pdu);
271 this->clear_rx_buffer_(LOG_STR("parse succeeded"), false, frame_length);
272
273 return true;
274}
275
277 size_t size = this->rx_buffer_.size();
278 uint16_t frame_length = helpers::client_frame_length(this->rx_buffer_.data(), this->rx_buffer_.size());
279
280 if (size < frame_length)
281 return true;
282
283 uint8_t address = this->rx_buffer_[0];
284 uint8_t function_code = this->rx_buffer_[1];
285
286 if (helpers::is_function_code_unknown_length(function_code)) {
287 frame_length = this->find_frame_end_by_crc_(frame_length);
288 if (frame_length == 0)
289 return size < MAX_FRAME_SIZE; // Continue to parse until we hit max size
290 ESP_LOGD(TAG, "Unknown-length function %02X found", function_code);
291 } else {
292 if (crc16(&this->rx_buffer_[0], frame_length) != 0)
293 return false;
294 }
295
296 // Clear before processing: process_modbus_client_frame_ dispatches to a server device which sends
297 // a response immediately. We need to clear the rx buffer first so the response doesn't snag tx_blocked.
298 // This requires copying the frame data to a local buffer beforehand.
299 uint8_t data_offset = helpers::client_frame_data_offset(this->rx_buffer_.data(), this->rx_buffer_.size());
300 uint16_t data_len = frame_length - 2 - data_offset;
301 uint8_t data_buffer[MAX_FRAME_SIZE] = {};
302 std::memcpy(data_buffer, this->rx_buffer_.data() + data_offset, data_len);
303 std::span<const uint8_t> data(data_buffer, data_len);
304 this->clear_rx_buffer_(LOG_STR("parse succeeded"), false, frame_length);
305
306 if (address == BROADCAST_ADDRESS) {
307 // Keep the unicast response buffers out of the broadcast call chain.
308 this->process_broadcast_frame_(function_code, data);
309 } else {
310 this->process_modbus_client_frame_(address, function_code, data);
311 }
312
313 return true;
314}
315
316// The parser (parse_modbus_server_frame_) guarantees the bounds relied on here: pdu is never empty,
317// and an exception-flagged pdu is at least 2 bytes. Keep that in mind when changing server_pdu_length().
318void ModbusClientHub::process_modbus_server_frame(uint8_t address, std::span<const uint8_t> pdu) {
319 const uint8_t function_code = pdu[0];
320 ModbusDeviceCommand *cmd = this->waiting_for_response_ ? this->find_waiting_() : nullptr;
321 if (cmd == nullptr) {
322 ESP_LOGW(TAG,
323 "Received unexpected frame from address %" PRIu8 ", function code 0x%X, %" PRIu32 "ms after last send",
325 return;
326 }
327
328 // Check if the response matches the expected address and function code
329 const uint8_t expected_address = cmd->frame.address();
330 const uint8_t expected_function_code = cmd->frame.pdu()[0];
331 if (expected_address != address || expected_function_code != (function_code & FUNCTION_CODE_MASK)) {
332 ESP_LOGW(TAG,
333 "Received incorrect frame address %" PRIu8 " <> %" PRIu8 " or function code 0x%X <> 0x%X, %" PRIu32
334 "ms after last send",
335 address, expected_address, (function_code & FUNCTION_CODE_MASK), expected_function_code,
336 this->last_modbus_byte_ - this->last_send_);
337 // Unexpected frame: flip a WAITING entry to an INTERRUPTED shell that ignores the rest of this
338 // transaction and blocks tx until the send-wait timeout, where it gets its on_no_response.
339 cmd->interrupt();
340 return;
341 }
342
344 // An interrupted shell keeps blocking until the send-wait timeout; a late response for it is
345 // ignored and does NOT free the wire. The distrust survives a clear (INTERRUPTED_RETIRED), so a
346 // cleared-interrupted frame still ends in on_no_response rather than delivering a late response.
347 ESP_LOGW(TAG,
348 "Ignoring response from %" PRIu8 " - transmission interrupted by previous unexpected response, %" PRIu32
349 "ms after last send",
350 address, this->last_modbus_byte_ - this->last_send_);
351 return;
352 }
353
354 // Deliver at parse time so the response span can point into the rx buffer (zero copy). error()/
355 // response() set the state and consume the request BEFORE the callback, so a clear from inside it
356 // ("stop polling now") wins. A device-less shell runs no callback and the sweep erases it.
357 this->waiting_for_response_ = false;
358 this->sweep_needed_ = true;
359 if (helpers::is_function_code_exception(function_code)) {
360 uint8_t exception = pdu[1]; // exception frames are fixed-length, so the code is always present
361 ESP_LOGW(TAG, "Error function code: 0x%X exception: %" PRIu8 ", address: %" PRIu8 ", %" PRIu32 "ms after last send",
362 function_code, exception, address, this->last_modbus_byte_ - this->last_send_);
363 cmd->error(static_cast<ExceptionCode>(exception));
364 } else if (!cmd->response(pdu)) {
365 ESP_LOGV(TAG, "Ignoring response from %" PRIu8 " - no callback device set, %" PRIu32 "ms after last send", address,
366 this->last_modbus_byte_ - this->last_send_);
367 }
368}
369
370void ModbusServerHub::process_modbus_server_frame(uint8_t address, std::span<const uint8_t>) {
371 if (this->find_device_(address) != nullptr) {
372 ESP_LOGE(TAG, "Unexpected response from address %" PRIu8 ", which is mapped to this device.", address);
373 }
374
375 if (this->expecting_peer_response_ == address) {
376 ESP_LOGV(TAG, "Expected response from peer %" PRIu8 " received", address);
377 } else {
378 ESP_LOGV(TAG, "Unexpected response from peer %" PRIu8 " received", address);
379 }
380
381 // This always resets, even if the address doesn't match.
382 // If an unexpected response is received, we can't trust that a correct response will follow (it shouldn't).
383 this->expecting_peer_response_ = 0;
384}
385
387 for (auto *device : this->devices_) {
388 if (device->get_address() == address) {
389 return device;
390 }
391 }
392 return nullptr;
393}
394
395ResponseStatus ModbusServerHub::check_address_range_(uint16_t start_address, uint16_t count) {
396 if (!helpers::address_range_fits(start_address, count)) {
397 ESP_LOGW(TAG, "Address out of range - start: %" PRIu16 " num: %" PRIu16, start_address, count);
399 }
400 return std::nullopt;
401}
402
403// Write PDU layout after the function code: start address(2) [+ quantity(2) + byte count(1)] + register values.
404// The value subspans taken at these offsets stay in range because client_pdu_length() clamps the byte count to the
405// same maximum the callers' number_of_registers * 2 == number_of_bytes guard enforces.
406static constexpr size_t WRITE_SINGLE_VALUES_OFFSET = 2;
407static constexpr size_t WRITE_MULTIPLE_VALUES_OFFSET = 5;
408// FC 0x17 writes follow read start(2) + read quantity(2) + write start(2) + write quantity(2) + byte count(1).
409static constexpr size_t READ_WRITE_VALUES_OFFSET = 9;
410// A coil write (FC 0x0F) is function(1) + start(2) + quantity(2) + byte count(1) + packed bits. The largest
411// one (MAX_NUM_OF_COILS_TO_WRITE coils) must fit the received request PDU, so the value subspan taken at
412// WRITE_MULTIPLE_VALUES_OFFSET can never run past it.
413static_assert(1 + WRITE_MULTIPLE_VALUES_OFFSET + packed_bit_bytes(MAX_NUM_OF_COILS_TO_WRITE) <= MAX_PDU_SIZE,
414 "the largest FC 0x0F coil write must fit within MAX_PDU_SIZE");
415
416ResponseStatus ModbusServerHub::parse_write_single_(std::span<const uint8_t> data, uint16_t &start_address,
417 RegisterValues &registers) {
418 start_address = helpers::get_data<uint16_t>(data.data(), 0);
419 // No range check needed: one register can never push start_address + 1 past the address space.
420 this->assemble_registers_(data.subspan(WRITE_SINGLE_VALUES_OFFSET, sizeof(uint16_t)), registers);
421 return std::nullopt;
422}
423
424ResponseStatus ModbusServerHub::parse_write_multiple_(std::span<const uint8_t> data, uint16_t &start_address,
425 RegisterValues &registers) {
426 start_address = helpers::get_data<uint16_t>(data.data(), 0);
427 uint16_t number_of_registers = helpers::get_data<uint16_t>(data.data(), 2);
428 uint8_t number_of_bytes = helpers::get_data<uint8_t>(data.data(), 4);
429 if (number_of_registers == 0 || number_of_registers > MAX_NUM_OF_REGISTERS_TO_WRITE ||
430 number_of_registers * 2 != number_of_bytes) {
431 ESP_LOGW(TAG, "Invalid number of registers %" PRIu16 " or bytes %" PRIu8, number_of_registers, number_of_bytes);
433 }
434 if (ResponseStatus status = this->check_address_range_(start_address, number_of_registers); status.has_value()) {
435 return status;
436 }
437 this->assemble_registers_(data.subspan(WRITE_MULTIPLE_VALUES_OFFSET, number_of_bytes), registers);
438 return std::nullopt;
439}
440
441ResponseStatus ModbusServerHub::parse_read_request_(std::span<const uint8_t> data, uint16_t max_entities,
442 const LogString *entity_name, uint16_t &start_address,
443 uint16_t &count) {
444 // Every read request is start address(2) + quantity(2); only the protocol ceiling differs per function
445 // code, so registers and coils/discrete inputs validate through here and cannot drift apart.
446 start_address = helpers::get_data<uint16_t>(data.data(), 0);
447 count = helpers::get_data<uint16_t>(data.data(), 2);
448 if (count == 0 || count > max_entities) {
449 ESP_LOGW(TAG, "Invalid number of %s %" PRIu16, LOG_STR_ARG(entity_name), count);
451 }
452 return this->check_address_range_(start_address, count);
453}
454
455ResponseStatus ModbusServerHub::parse_write_single_coil_(std::span<const uint8_t> data, uint16_t &start_address,
456 bool &value) {
457 start_address = helpers::get_data<uint16_t>(data.data(), 0);
458 const uint16_t raw_value = helpers::get_data<uint16_t>(data.data(), WRITE_SINGLE_VALUES_OFFSET);
459 if (raw_value != 0xFF00 && raw_value != 0x0000) {
460 ESP_LOGW(TAG, "Invalid coil value 0x%04X", raw_value);
462 }
463 // No range check needed: one coil can never push start_address + 1 past the address space.
464 value = raw_value == 0xFF00;
465 return std::nullopt;
466}
467
468ResponseStatus ModbusServerHub::parse_write_multiple_coils_(std::span<const uint8_t> data, uint16_t &start_address,
469 uint16_t &count, std::span<const uint8_t> &packed_bytes) {
470 start_address = helpers::get_data<uint16_t>(data.data(), 0);
471 const uint16_t number_of_bits = helpers::get_data<uint16_t>(data.data(), 2);
472 const uint8_t number_of_bytes = helpers::get_data<uint8_t>(data.data(), 4);
473 if (number_of_bits == 0 || number_of_bits > MAX_NUM_OF_COILS_TO_WRITE ||
474 packed_bit_bytes(number_of_bits) != number_of_bytes) {
475 ESP_LOGW(TAG, "Invalid number of coils %" PRIu16 " or bytes %" PRIu8, number_of_bits, number_of_bytes);
477 }
478 if (ResponseStatus status = this->check_address_range_(start_address, number_of_bits); status.has_value()) {
479 return status;
480 }
481 count = number_of_bits;
482 // coil values follow start(2) + quantity(2) + byte count(1)
483 packed_bytes = data.subspan(WRITE_MULTIPLE_VALUES_OFFSET, number_of_bytes);
484 return std::nullopt;
485}
486
487void ModbusServerHub::assemble_registers_(std::span<const uint8_t> values, RegisterValues &registers) {
488 for (size_t offset = 0; offset + 1 < values.size(); offset += 2) {
489 registers.push_back(helpers::get_data<uint16_t>(values.data(), offset));
490 }
491}
492
493void ModbusServerHub::process_broadcast_frame_(uint8_t function_code, std::span<const uint8_t> data) {
494 // Broadcasts are only meaningful for writes and are never answered (Modbus 4.1 / 6.12), so an unsupported
495 // function code or a validation failure is silently dropped instead of replying with an exception. Both
496 // register writes (FC 0x06/0x10) and coil writes (FC 0x05/0x0F) are broadcastable by spec, and each shares
497 // its parser with the addressed path so a broadcast is validated exactly as the unicast form would be.
498 uint16_t start_address;
499 RegisterValues registers;
500 uint16_t coil_count = 0;
501 std::span<const uint8_t> packed_bytes;
502 uint8_t single_bit = 0; // backs packed_bytes for a single-coil write, so it must outlive the loop below
503 bool coils = false;
505 switch (static_cast<FunctionCode>(function_code)) {
507 status = this->parse_write_single_(data, start_address, registers);
508 break;
510 status = this->parse_write_multiple_(data, start_address, registers);
511 break;
513 coils = true;
514 bool value = false;
515 status = this->parse_write_single_coil_(data, start_address, value);
516 single_bit = value ? 0x01 : 0x00;
517 coil_count = 1;
518 packed_bytes = std::span<const uint8_t>(&single_bit, 1);
519 break;
520 }
522 coils = true;
523 status = this->parse_write_multiple_coils_(data, start_address, coil_count, packed_bytes);
524 break;
525 default:
526 // Reads and read/write require a reply, so they are not valid as broadcasts.
527 ESP_LOGV(TAG, "Ignoring broadcast with unsupported function code %" PRIu8, function_code);
528 return;
529 }
530 if (status.has_value()) {
531 return;
532 }
533 // A broadcast is never answered, so a rejecting device has no other feedback channel: report the
534 // per-device outcome at V, and warn if the write reached nobody at all.
535 bool accepted = false;
536 for (auto *device : this->devices_) {
537 // Same handlers as an addressed write - a device cannot tell a broadcast apart, and does not need
538 // to: the hub owns the difference, which is only that no reply is ever sent.
539 const ResponseStatus device_status =
540 coils ? device->on_write_coils(start_address, PackedBits(packed_bytes, coil_count))
541 : device->on_write_registers(start_address, registers);
542 if (device_status.has_value()) {
543 ESP_LOGV(TAG, "Device %" PRIu8 " rejected broadcast write with exception %" PRIu8, device->get_address(),
544 static_cast<uint8_t>(device_status.value()));
545 } else {
546 accepted = true;
547 }
548 }
549 if (!accepted && !this->devices_.empty()) {
550 const uint16_t entity_count = coils ? coil_count : static_cast<uint16_t>(registers.size());
551 const LogString *const entity_name = coils ? LOG_STR("coils") : LOG_STR("registers");
552 // Warn at most once per interval, then drop to VERBOSE: on a shared bus a broadcast aimed at other nodes
553 // repeats forever, so warning per frame would flood the log.
554 const uint32_t now = millis();
555 if (this->last_unaccepted_broadcast_warn_ == 0 ||
556 now - this->last_unaccepted_broadcast_warn_ > UNACCEPTED_BROADCAST_WARN_INTERVAL_MS) {
558 ESP_LOGW(TAG, "No device accepted broadcast write of %" PRIu16 " %s at 0x%04X", entity_count,
559 LOG_STR_ARG(entity_name), start_address);
560 } else {
561 ESP_LOGV(TAG, "No device accepted broadcast write of %" PRIu16 " %s at 0x%04X", entity_count,
562 LOG_STR_ARG(entity_name), start_address);
563 }
564 }
565}
566
568 uint16_t number_of_registers, const RegisterValues &registers,
569 std::span<uint8_t> response_buffer, uint16_t &response_len) {
570 // A handler that returns an exception leaves registers partially filled, so check the exception
571 // first and forward it before validating the register count on the success path.
572 if (this->rejected_(address, function_code, status)) {
573 return false;
574 }
575
576 if (registers.size() != number_of_registers) {
577 ESP_LOGE(TAG, "Incorrect response %" PRIu16 " requested, %zu returned", number_of_registers, registers.size());
578 this->send_exception_(address, function_code, ExceptionCode::SERVICE_DEVICE_FAILURE);
579 return false;
580 }
581
582 // The byte count is a single byte, so the count must stay within the protocol read limit; above it the
583 // static_cast<uint8_t>(number_of_registers * 2) below would silently truncate the byte count.
584 if (number_of_registers > MAX_NUM_OF_REGISTERS_TO_READ) {
585 ESP_LOGE(TAG, "Read response of %" PRIu16 " registers exceeds the limit of %" PRIu16, number_of_registers,
586 MAX_NUM_OF_REGISTERS_TO_READ);
587 this->send_exception_(address, function_code, ExceptionCode::SERVICE_DEVICE_FAILURE);
588 return false;
589 }
590
591 // Byte count(1) + two bytes per register. Checked here rather than at the call sites so the bound travels with
592 // the write itself: a future caller starting at a non-zero response_len, or passing a smaller buffer, is
593 // rejected instead of overrunning it before send_response_'s size guard can fire.
594 const size_t required = static_cast<size_t>(response_len) + 1 + static_cast<size_t>(number_of_registers) * 2;
595 if (required > response_buffer.size()) {
596 ESP_LOGE(TAG, "Read response needs %zu bytes but only %zu are available", required, response_buffer.size());
597 this->send_exception_(address, function_code, ExceptionCode::SERVICE_DEVICE_FAILURE);
598 return false;
599 }
600
601 response_buffer[response_len++] = static_cast<uint8_t>(number_of_registers * 2); // actual byte count
602 for (auto r : registers) {
603 auto register_bytes = decode_value(r);
604 response_buffer[response_len++] = register_bytes[0];
605 response_buffer[response_len++] = register_bytes[1];
606 }
607 return true;
608}
609
610void ModbusServerHub::process_modbus_client_frame_(uint8_t address, uint8_t function_code,
611 std::span<const uint8_t> data) {
612 ModbusServerDevice *device = this->find_device_(address);
613 if (device == nullptr) {
615 ESP_LOGV(TAG, "Request to peer %" PRIu8 " received", address);
616 return;
617 }
618
620 uint8_t response_buffer[modbus::MAX_RAW_SIZE];
621 const uint8_t *response_data = response_buffer;
622 uint16_t response_len = 0;
623
624 switch (static_cast<FunctionCode>(function_code)) {
627 uint16_t start_address;
628 uint16_t number_of_registers;
629 status = this->parse_read_request_(data, MAX_NUM_OF_REGISTERS_TO_READ, LOG_STR("registers"), start_address,
630 number_of_registers);
631 if (this->rejected_(address, function_code, status)) {
632 return;
633 }
634 RegisterValues registers;
635 if (static_cast<FunctionCode>(function_code) == FunctionCode::READ_HOLDING_REGISTERS) {
636 status = device->on_read_holding_registers(start_address, number_of_registers, registers);
637 } else {
638 status = device->on_read_input_registers(start_address, number_of_registers, registers);
639 }
640
641 if (!this->build_or_reject_read_response_(address, function_code, status, number_of_registers, registers,
642 response_buffer, response_len)) {
643 return;
644 }
645 break;
646 }
649 // Parse and validate the write PDU into host-order register values; reply with an exception on failure.
650 uint16_t start_address;
651 RegisterValues registers;
652 if (static_cast<FunctionCode>(function_code) == FunctionCode::WRITE_SINGLE_REGISTER) {
653 status = this->parse_write_single_(data, start_address, registers);
654 } else {
655 status = this->parse_write_multiple_(data, start_address, registers);
656 }
657 if (this->rejected_(address, function_code, status)) {
658 return;
659 }
660 status = device->on_write_registers(start_address, registers);
661 response_data = data.data(); // echo the request header per Modbus 6.6, 6.12
662 response_len = 4;
663 break;
664 }
667 uint16_t start_address;
668 uint16_t number_of_bits;
669 status =
670 this->parse_read_request_(data, MAX_NUM_OF_COILS_TO_READ, LOG_STR("bits"), start_address, number_of_bits);
671 if (this->rejected_(address, function_code, status)) {
672 return;
673 }
674 // Response: byte count(1) + packed bytes, written straight into the pre-zeroed response buffer. It
675 // always fits: the parse above caps the count, and a static_assert bounds that against MAX_RAW_SIZE.
676 const uint8_t byte_count = static_cast<uint8_t>(packed_bit_bytes(number_of_bits));
677 response_buffer[response_len++] = byte_count;
678 // Take the packed-bytes span off a span that knows response_buffer's real size, so a future non-zero
679 // response_len (e.g. a prefix written before the packed data) is a bounds error, not a silent overrun.
680 std::span<uint8_t> packed_out = std::span<uint8_t>(response_buffer).subspan(response_len, byte_count);
681 std::fill(packed_out.begin(), packed_out.end(), 0);
682 MutablePackedBits bits(packed_out, number_of_bits);
683 if (static_cast<FunctionCode>(function_code) == FunctionCode::READ_COILS) {
684 status = device->on_read_coils(start_address, bits);
685 } else {
686 status = device->on_read_discrete_inputs(start_address, bits);
687 }
688 if (this->rejected_(address, function_code, status)) {
689 return;
690 }
691 response_len += byte_count;
692 break;
693 }
695 // A single coil is handed to the device as a one-bit packed view, the same form a multiple-coil
696 // write takes, so a device only ever implements one coil write handler.
697 uint16_t start_address;
698 bool value = false;
699 status = this->parse_write_single_coil_(data, start_address, value);
700 if (this->rejected_(address, function_code, status)) {
701 return;
702 }
703 const uint8_t single_bit = value ? 0x01 : 0x00;
704 status = device->on_write_coils(start_address, PackedBits(std::span<const uint8_t>(&single_bit, 1), 1));
705 response_data = data.data(); // echo the request header per Modbus 6.5, 6.11
706 response_len = 4;
707 break;
708 }
710 // Parse and validate the coil write PDU into a packed-bit view; reply with an exception on failure.
711 uint16_t start_address;
712 uint16_t count;
713 std::span<const uint8_t> packed_bytes;
714 status = this->parse_write_multiple_coils_(data, start_address, count, packed_bytes);
715 if (this->rejected_(address, function_code, status)) {
716 return;
717 }
718 status = device->on_write_coils(start_address, PackedBits(packed_bytes, count));
719 response_data = data.data(); // echo the request header per Modbus 6.5, 6.11
720 response_len = 4;
721 break;
722 }
724 // PDU data: read start address(2) + read quantity(2) + write start address(2) + write quantity(2) +
725 // write byte count(1) + write register values. Per Modbus 6.17 the write is performed before the read.
726 uint16_t read_start_address = helpers::get_data<uint16_t>(data.data(), 0);
727 uint16_t number_of_registers = helpers::get_data<uint16_t>(data.data(), 2);
728 uint16_t write_start_address = helpers::get_data<uint16_t>(data.data(), 4);
729 uint16_t number_of_write_registers = helpers::get_data<uint16_t>(data.data(), 6);
730 uint8_t number_of_bytes = helpers::get_data<uint8_t>(data.data(), 8);
731 if (number_of_registers == 0 || number_of_registers > MAX_NUM_OF_REGISTERS_TO_READ ||
732 number_of_write_registers == 0 || number_of_write_registers > MAX_NUM_OF_REGISTERS_TO_WRITE_RW ||
733 number_of_write_registers * 2 != number_of_bytes) {
734 ESP_LOGW(TAG, "Invalid number of registers (read %" PRIu16 ", write %" PRIu16 ") or bytes %" PRIu8,
735 number_of_registers, number_of_write_registers, number_of_bytes);
736 this->send_exception_(address, function_code, ExceptionCode::ILLEGAL_DATA_VALUE);
737 return;
738 }
739 status = this->check_address_range_(read_start_address, number_of_registers);
740 if (!status.has_value()) {
741 status = this->check_address_range_(write_start_address, number_of_write_registers);
742 }
743 if (this->rejected_(address, function_code, status)) {
744 return;
745 }
746 // Perform the write first (Modbus 6.17). Scoped so the write values are off the stack before the read
747 // values are allocated, keeping only one RegisterValues buffer live at a time.
748 {
749 RegisterValues write_registers;
750 this->assemble_registers_(data.subspan(READ_WRITE_VALUES_OFFSET, number_of_bytes), write_registers);
751 // Dispatch to the standalone write and read handlers so any device implementing those supports 0x17
752 // without a dedicated handler; a device that maps registers by address reconstructs the read response
753 // from the values it just stored.
754 status = device->on_write_registers(write_start_address, write_registers);
755 }
756 if (this->rejected_(address, function_code, status)) {
757 return;
758 }
759 RegisterValues registers;
760 status = device->on_read_holding_registers(read_start_address, number_of_registers, registers);
761
762 if (!this->build_or_reject_read_response_(address, function_code, status, number_of_registers, registers,
763 response_buffer, response_len)) {
764 return;
765 }
766 break;
767 }
768 default:
769 ESP_LOGW(TAG, "Unsupported function code %" PRIu8, function_code);
770 this->send_exception_(address, function_code, ExceptionCode::ILLEGAL_FUNCTION);
771 return;
772 }
773 if (!this->rejected_(address, function_code, status)) {
774 this->send_response_(address, function_code, response_data, response_len);
775 }
776}
777
778// Callers gate on tx_blocked() first, but the pre-send delay below can span several ms, so re-check
779// after it and refuse (return false) if a byte arrived in that window rather than transmit over it.
781 const int32_t tx_delay_remaining = this->tx_delay_remaining();
782 if (tx_delay_remaining > 0) {
784 }
785
786 // The delay above can span several ms; a byte arriving in that window blocks transmission after the
787 // caller's gate already passed. Don't collide with the incoming frame - leave the entry to retry.
788 if (this->tx_blocked()) {
789 return false;
790 }
791
792 if (this->flow_control_pin_ != nullptr) {
793 this->flow_control_pin_->digital_write(true);
794 this->write_array(frame.data.data(), frame.size());
795 this->flush();
796 this->flow_control_pin_->digital_write(false);
797 this->last_send_tx_offset_ = 0;
798 } else {
799 this->write_array(frame.data.data(), frame.size());
800 this->last_send_tx_offset_ = frame.size() * MODBUS_BITS_PER_CHAR * MS_PER_SEC / this->parent_->get_baud_rate() + 1;
801 }
802
803 uint32_t now = millis();
804#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
805 char hex_buf[format_hex_pretty_size(MODBUS_MAX_LOG_BYTES)];
806#endif
807 ESP_LOGV(TAG, "Write: %s %" PRIu32 "ms after last send, %" PRIu32 "ms after last receive",
808 format_hex_pretty_to(hex_buf, frame.data.data(), frame.size()), now - this->last_send_,
809 now - this->last_modbus_byte_);
810 this->last_send_ = now;
811 return true;
812}
813
815 if (this->tx_blocked())
816 return;
817
819 if (cmd == nullptr)
820 return;
821
822 if (!this->send_frame_(cmd->frame)) {
823 ESP_LOGV(TAG, "Send deferred for %" PRIu8 ": a frame arrived during the send delay, will retry",
824 cmd->frame.address());
825 return;
826 }
827
828 cmd->sent();
829 if (cmd->frame.address() == BROADCAST_ADDRESS) {
830 // A broadcast (address 0) is never answered (Modbus 4.1), so it is fire-and-forget: on_sent above
831 // reports the transmission, and the entry then retires with no terminal callback instead of
832 // occupying the waiting slot until the send-wait timeout expires. The turnaround delay already
833 // spaces the next frame; the following sweep erases the entry.
834 ESP_LOGV(TAG, "Broadcast to address 0 sent; no reply expected (fire-and-forget)");
835 cmd->complete_broadcast();
836 this->sweep_needed_ = true;
837 return;
838 }
839 this->waiting_for_response_ = true;
840}
841
843 ESP_LOGCONFIG(TAG,
844 "Modbus:\n"
845 " Send Wait Time: %" PRIu16 " ms\n"
846 " Turnaround Time: %" PRIu16 " ms\n"
847 " Frame Delay: %" PRIu16 " ms\n"
848 " Long Rx Buffer Delay: %" PRIu16 " ms",
851 LOG_PIN(" Flow Control Pin: ", this->flow_control_pin_);
852}
854 ESP_LOGCONFIG(TAG,
855 "Modbus:\n"
856 " Frame Delay: %" PRIu16 " ms\n"
857 " Long Rx Buffer Delay: %" PRIu16 " ms",
859 LOG_PIN(" Flow Control Pin: ", this->flow_control_pin_);
860}
861
863 // After UART bus
864 return setup_priority::BUS - 1.0f;
865}
866
867void ModbusServerHub::send_response_(uint8_t address, uint8_t function_code, const uint8_t *payload,
868 uint16_t payload_len) {
869 // Build the raw frame (address + function code + payload) in a stack buffer; it's consumed
870 // immediately by send_raw_ and a full raw frame never exceeds MAX_RAW_SIZE.
871 if (payload_len + 2 > MAX_RAW_SIZE) {
872 ESP_LOGE(TAG, "Server response too large (%" PRIu16 " bytes)", static_cast<uint16_t>(payload_len + 2));
873 return;
874 }
875 uint8_t raw_frame[MAX_RAW_SIZE];
876 raw_frame[0] = address;
877 raw_frame[1] = function_code;
878 std::memcpy(raw_frame + 2, payload, payload_len);
879 this->send_raw_(raw_frame, payload_len + 2);
880}
881
882bool ModbusServerHub::rejected_(uint8_t address, uint8_t function_code, ResponseStatus status) {
883 if (!status.has_value())
884 return false;
885 // The one place a rejection becomes an exception reply, so the log carries the transaction context a
886 // device handler never has: which client-facing address and function code drew which exception. DEBUG
887 // rather than WARN because an exception reply is a normal protocol outcome and arrives per frame - a
888 // probing or broken client would otherwise flood the log. The parse helpers still WARN with specifics.
889 ESP_LOGD(TAG, "Exception %" PRIu8 " replied to function 0x%02X for address %" PRIu8,
890 static_cast<uint8_t>(status.value()), function_code, address);
891 this->send_exception_(address, function_code, status.value());
892 return true;
893}
894
895void ModbusServerHub::send_exception_(uint8_t address, uint8_t function_code, ExceptionCode exception_code) {
896 uint8_t raw_frame[3];
897 raw_frame[0] = address;
898 raw_frame[1] = function_code | FUNCTION_CODE_EXCEPTION_MASK;
899 raw_frame[2] = static_cast<uint8_t>(exception_code);
900 this->send_raw_(raw_frame, 3);
901}
902
904 for (auto &cmd : this->tx_buffer_) {
905 if (cmd.waiting_state())
906 return &cmd;
907 }
908 return nullptr;
909}
910
912 // Class first (WRITE, then one-shot READ, then CONTINUOUS), oldest within a class. seq is a
913 // free-running counter, so compare each entry's AGE against it (correct across the full range).
914 const uint16_t now = this->next_seq_;
915 const auto age = [now](const ModbusDeviceCommand &cmd) -> uint16_t { return now - cmd.seq; };
916 const auto older = [&age](const ModbusDeviceCommand &a, const ModbusDeviceCommand &b) { return age(a) > age(b); };
917 ModbusDeviceCommand *best = nullptr;
918 for (auto &cmd : this->tx_buffer_) {
919 if (cmd.state != FrameState::READY)
920 continue;
921 if (best == nullptr || cmd.priority() > best->priority() ||
922 (cmd.priority() == best->priority() && older(cmd, *best))) {
923 best = &cmd;
924 }
925 }
926 return best;
927}
928
931 // on_sent() is not a terminal, so nothing is consumed.
932 if (this->device == nullptr)
933 return false;
934 this->device->on_sent(this->frame.pdu());
935 return true;
936}
937
939 if (!this->decrement_pending())
940 return false; // nothing owed - stop the sweep draining this entry
941 if (this->device != nullptr)
942 this->device->on_not_sent(this->frame.pdu());
943 return true; // consumed one debt (delivered, or silent when device-less) - keep draining to zero
944}
945
946bool ModbusDeviceCommand::response(std::span<const uint8_t> response_pdu) {
948 // A continuous poll is never consumed by its own response; a one-shot consumes one request here.
949 if (!this->continuous)
950 this->decrement_pending();
951 if (this->device == nullptr)
952 return false;
953 this->device->on_response(this->frame.pdu(), response_pdu);
954 return true;
955}
956
959 // An exception ends a continuous poll too, so decrement unconditionally.
960 this->decrement_pending();
961 if (this->device == nullptr)
962 return false;
963 this->device->on_error(this->frame.pdu(), exception_code);
964 return true;
965}
966
968 // An unexpected frame distrusts the transaction. A cleared-but-still-waiting shell distrusts too, so
969 // the interrupt survives the clear in either order (WAITING_RETIRED -> INTERRUPTED_RETIRED).
970 if (this->state == FrameState::WAITING) {
972 return true;
973 }
974 if (this->state == FrameState::WAITING_RETIRED) {
976 return true;
977 }
978 return false;
979}
980
982 this->state = FrameState::TIMED_OUT; // advance BEFORE the callback so a clear from inside it wins
983 this->decrement_pending(); // resolve this request (WAITING-origin, so pending >= 1)
984 if (this->device == nullptr)
985 return false; // resolved, no one to tell
986 if (this->device->on_no_response(this->frame.pdu()))
987 this->increment_pending(); // granted retry = re-request (capped)
988 return true;
989}
990
992 if (!this->sweep_needed_)
993 return;
994 this->sweep_needed_ = false;
995 // Serve only the entries present now: a callback may append (a re-send), but those sit beyond
996 // work_set and are left for the next sweep, which bounds the work and is the termination argument.
997 // Entries leave the container only in the erase pass below, so indices/references stay valid.
998 const size_t work_set = this->tx_buffer_.size();
999 // Restart the walk after every callback: a handler may have moved any entry to any state.
1000 bool callback_ran = true;
1001 while (callback_ran) {
1002 callback_ran = false;
1003 for (size_t i = 0; i != work_set && !callback_ran; i++) {
1004 ModbusDeviceCommand &cmd = this->tx_buffer_[i];
1005 switch (cmd.state) {
1009 // Off the wire, callback already delivered: reschedule what is still pending, else erase.
1010 if (cmd.pending)
1011 cmd.requeue(this->next_seq_++);
1012 break;
1014 // Owes one on_not_sent() per accepted request; notify_retired() consumes one and reports
1015 // whether a debt remained, so the restart loop drains the entry to zero - even a device-less
1016 // shell with pending > 1 (no callback fires, but it still drains rather than stranding).
1017 callback_ran = cmd.notify_retired();
1018 break;
1021 // Cleared shell: drain only the un-run duplicates; the request in flight keeps pending 1
1022 // and gets its usual callback when it resolves.
1023 if (cmd.pending > 1)
1024 callback_ran = cmd.notify_retired();
1025 break;
1026 default: // READY / WAITING / INTERRUPTED: idle or waiting for a response, nothing owed until the timeout
1027 break;
1028 }
1029 }
1030 }
1031 // Erase pass: the only place entries leave the container. Storage order carries no meaning, so a
1032 // finished entry is swap-and-popped; walking backwards means a moved-down entry is already seen.
1033 for (size_t i = this->tx_buffer_.size(); i-- > 0;) {
1034 const ModbusDeviceCommand &cmd = this->tx_buffer_[i];
1035 // pending == 0 is erasable, but shells still waiting for a response are exempt until it resolves.
1036 if (cmd.pending != 0 || cmd.waiting_state())
1037 continue;
1038 if (i + 1 != this->tx_buffer_.size())
1039 this->tx_buffer_[i] = std::move(this->tx_buffer_.back());
1040 this->tx_buffer_.pop_back();
1041 }
1042}
1043
1044// Raw send for client: pushes to tx queue. Everything except the CRC must be contained in payload.
1045bool ModbusClientHub::queue_pdu(uint8_t address, std::span<const uint8_t> pdu, ModbusClientDevice *device,
1047 // Requests refused here never enter the machine and get no callback - the false return is it.
1048 if (pdu.empty()) {
1049 ESP_LOGW(TAG, "Empty PDU refused for address %" PRIu8, address);
1050 return false;
1051 }
1052 // Bound the PDU so the wire frame (address + pdu + CRC) stays within the Modbus RTU 256-byte limit.
1053 if (pdu.size() > MAX_PDU_SIZE) {
1054 ESP_LOGE(TAG, "Frame too large, refused: %" PRIu8 ":%zu bytes", address, pdu.size());
1055 return false;
1056 }
1057 // classify() drives both the broadcast guard and the continuous check below; compute it once.
1059
1060 // A broadcast (address 0) is never answered (Modbus 4.1), so it is only meaningful for a command that
1061 // changes state. Refuse a broadcast that expects a reply - anything but a write or a custom/vendor code -
1062 // as it could never deliver a result, so the caller learns via the false return (and on_not_sent).
1063 // 0x17 (read/write multiple) is a knowing inclusion: classify() treats it as a write, so its write half
1064 // lands on every server and its unanswerable read half is simply discarded. An exception-flagged custom
1065 // code (0x80 bit set) is refused: is_function_code_custom() masks that bit away, so exclude it explicitly
1066 // here to match classify()'s exception-first handling of the write side.
1067 if (address == BROADCAST_ADDRESS && priority != CommandPriority::WRITE &&
1069 ESP_LOGW(TAG, "Broadcast refused for function 0x%X: a broadcast (address 0) is never answered", pdu[0]);
1070 return false;
1071 }
1072
1073 // continuous is ignored for every mutating code (re-writing a value forever is never intended).
1074 const bool mutates = priority == CommandPriority::WRITE;
1075 bool continuous = false;
1076 if (options.continuous) {
1077 if (mutates) {
1078 ESP_LOGV(TAG, "continuous is ignored for a mutating function (0x%X, address %" PRIu8 ")", pdu[0], address);
1079 } else {
1080 continuous = true;
1081 }
1082 }
1083
1084 // A duplicate of a live entry with the same owner is not queued twice; it resolves against that
1085 // entry: anonymous -> dropped; continuous incoming -> convert the entry to a poll; one-shot onto a
1086 // poll -> downgrade the poll to one-shot; both one-shots -> pending++ below the cap, else refused.
1087 for (auto &item : this->tx_buffer_) {
1088 if (item.state == FrameState::RETIRED || item.state == FrameState::WAITING_RETIRED ||
1089 item.state == FrameState::INTERRUPTED_RETIRED)
1090 continue; // cleared, on their way out: a new identical send queues fresh, never absorbs
1091 if (item.device != device || !item.same_frame(address, pdu))
1092 continue;
1093 if (device == nullptr) {
1094 // A dropped read is routine (DEBUG); a dropped write/custom warns (unobservable without a device).
1095 const bool requeueable =
1097 if (requeueable) {
1098 ESP_LOGD(TAG, "Anonymous duplicate of active frame for %" PRIu8 " (function 0x%X), dropped", address, pdu[0]);
1099 } else {
1100 ESP_LOGW(TAG,
1101 "Anonymous duplicate of active frame for %" PRIu8 " (function 0x%X), dropped - register a "
1102 "device for delivery accounting",
1103 address, pdu[0]);
1104 }
1105 return false; // dropped: no entry, no callbacks - the refusal is the return value
1106 }
1107 if (continuous) {
1108 item.make_continuous(true);
1109 ESP_LOGV(TAG, "Frame already active for %" PRIu8 ", now polled continuously", address);
1110 } else if (item.continuous) {
1111 // A one-shot duplicate downgrades the poll to a one-shot: it runs one more cycle to serve this
1112 // request, then stops (mirrors continuous incoming converting a one-shot the other way).
1113 item.make_continuous(false);
1114 ESP_LOGV(TAG, "Frame already active for %" PRIu8 ", downgraded from continuous to one-shot", address);
1115 } else if (!item.increment_pending()) {
1116 // At the servable cap, so refused. (An absorbed duplicate leaves seq alone - the entry keeps
1117 // its place in line, held by its oldest outstanding request.)
1118 ESP_LOGD(TAG, "Frame already active for %" PRIu8 " with %" PRIu8 " requests pending, refused", address,
1119 item.pending);
1120 return false;
1121 } else {
1122 ESP_LOGV(TAG, "Frame already active for %" PRIu8 ", request absorbed (pending %" PRIu8 ")", address,
1123 item.pending);
1124 }
1125 return true;
1126 }
1127
1128 // Backstop counts every entry; dead ones are gone by the sweep's end, so at worst they cost one
1129 // refusal at the very cap for one loop.
1130 if (this->tx_buffer_.size() >= MODBUS_TX_BUFFER_SIZE) {
1131#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_ERROR
1132 char hex_buf[format_hex_pretty_size(MODBUS_MAX_LOG_BYTES)];
1133#endif
1134 ESP_LOGE(TAG, "Write buffer full, refused: %" PRIu8 ":%s", address,
1135 format_hex_pretty_to(hex_buf, pdu.data(), pdu.size()));
1136 return false;
1137 }
1138#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
1139 char hex_buf[format_hex_pretty_size(MODBUS_MAX_LOG_BYTES)];
1140#endif
1141 ESP_LOGV(TAG, "Adding frame to tx queue: %" PRIu8 ":%s", address,
1142 format_hex_pretty_to(hex_buf, pdu.data(), pdu.size()));
1143 this->tx_buffer_.emplace_back(device, address, pdu, continuous, this->next_seq_++);
1144 return true;
1145}
1146
1148 // A clear is a pure state flip; the sweep delivers every owed on_not_sent() from a quiescent hub.
1149 for (auto &cmd : this->tx_buffer_) {
1150 if (cmd.frame.address() != address)
1151 continue;
1152 cmd.retire();
1153 this->sweep_needed_ = true;
1154 }
1155}
1156
1158 // Silent teardown (supersede semantics): the caller's own frames vanish without callbacks; see
1159 // the lifecycle note on ModbusClientDevice.
1160 for (auto &cmd : this->tx_buffer_) {
1161 if (cmd.device != device)
1162 continue;
1163 cmd.silent_retire();
1164 this->sweep_needed_ = true;
1165 }
1166}
1167
1168void ModbusClientHub::send_raw(const std::vector<uint8_t> &payload, ModbusClientDevice *device) {
1169 if (payload.size() < 2) {
1170 ESP_LOGW(TAG, "send_raw() payload too short to contain a PDU, refused");
1171 return;
1172 }
1173 this->queue_pdu(payload[0], std::span<const uint8_t>(payload).subspan(1), device);
1174}
1175
1176// Send raw command for server replies immediately. Except CRC everything must be contained in payload
1177void ModbusServerHub::send_raw_(const uint8_t *payload, uint16_t len) {
1178 if (len == 0) {
1179 return;
1180 }
1181 if (len > MAX_RAW_SIZE) {
1182 ESP_LOGE(TAG, "Server send frame too large (%" PRIu16 " bytes)", len);
1183 return;
1184 }
1185
1186 // If blocked now (frame delay not elapsed at low baud, or a frame arriving), defer rather than
1187 // busy-waiting the loop; send_frame_ itself re-checks after its delay, so the deferred callback
1188 // just reports whatever it returns.
1189 if (this->tx_blocked()) {
1190 // Stash the raw payload in a single member buffer so the deferred callback can rebuild the frame
1191 // without a heap allocation. Only one server reply is ever waiting, so a single buffer suffices.
1192 std::memcpy(this->deferred_payload_.data(), payload, len);
1193 this->deferred_payload_len_ = len;
1194 this->set_timeout("deferred_send", this->tx_delay_remaining(), [this]() {
1195 ModbusFrame frame(this->deferred_payload_[0], this->deferred_payload_.data() + 1,
1196 this->deferred_payload_len_ - 1);
1197 if (!this->send_frame_(frame))
1198 ESP_LOGE(TAG, "Deferred server reply dropped: transmission still blocked");
1199 });
1200 return;
1201 }
1202
1203 ModbusFrame frame(payload[0], payload + 1, len - 1);
1204 if (!this->send_frame_(frame))
1205 ESP_LOGE(TAG, "Server reply dropped: a frame arrived during the send delay");
1206}
1207
1208void Modbus::clear_rx_buffer_(const LogString *reason, bool warn, size_t bytes_to_clear) {
1209 size_t bytes = this->rx_buffer_.size();
1210 if (bytes_to_clear > 0 && bytes >= bytes_to_clear)
1211 bytes = bytes_to_clear;
1212 if (bytes > 0) {
1213 if (warn) {
1214 ESP_LOGW(TAG, "Clearing buffer of %zu bytes - %s %" PRIu32 "ms after last send", bytes, LOG_STR_ARG(reason),
1215 millis() - this->last_send_);
1216 } else {
1217 ESP_LOGV(TAG, "Clearing buffer of %zu bytes - %s %" PRIu32 "ms after last send", bytes, LOG_STR_ARG(reason),
1218 millis() - this->last_send_);
1219 }
1220 if (bytes == this->rx_buffer_.size()) {
1221 this->rx_buffer_.clear();
1222 } else {
1223 this->rx_buffer_.erase(this->rx_buffer_.begin(), this->rx_buffer_.begin() + bytes);
1224 }
1225 }
1226}
1227
1228void ModbusClientDevice::dispatch_response_(std::span<const uint8_t> request_pdu, std::span<const uint8_t> response_pdu,
1229 ResponseStatus status) {
1230 if (request_pdu.empty())
1231 return;
1232 auto function_code = static_cast<FunctionCode>(request_pdu[0]);
1233 // All standard requests handled below are function code + start address + count/value (5 bytes);
1234 // anything shorter cannot be parsed and is handed to the catch-all.
1235 if (request_pdu.size() < READ_PDU_SIZE) {
1236 this->on_custom_response(request_pdu, response_pdu, status);
1237 return;
1238 }
1239 const uint16_t start_address = helpers::get_data<uint16_t>(request_pdu.data(), 1);
1240 // count for reads/multi-writes, value for single writes
1241 const uint16_t count_or_value = helpers::get_data<uint16_t>(request_pdu.data(), 3);
1242
1243 // Gatekeeper for the typed dispatch below: anything that is not a standard-conformant transaction is
1244 // handed to on_custom_response() with the raw PDUs, so the decode cases can trust every length, byte
1245 // count, and quantity field without re-clamping.
1246 // - The REQUEST must be standard: nothing upstream validates a caller-built request PDU, so its
1247 // internal byte count, quantity, and address range are checked here (is_client_pdu_standard()).
1248 // - On success, the RESPONSE must be standard (self-consistent; the frame parser already guarantees
1249 // most of this, but the check keeps the safety proof local), and a read response's length must also
1250 // match the REQUESTED count - the per-PDU checks cannot see that relationship, and a short but
1251 // self-consistent response must be diverted, never silently clamped and delivered as complete.
1252 // - On failure (status engaged) the response is empty by design (see on_error()), so only the request
1253 // is validated.
1254 bool custom = !helpers::is_client_pdu_standard(request_pdu.data(), request_pdu.size());
1255 if (!custom && succeeded(status)) {
1256 custom = !helpers::is_server_pdu_standard(response_pdu.data(), response_pdu.size());
1257 if (!custom && helpers::is_function_code_read(static_cast<uint8_t>(function_code))) {
1258 const bool bits =
1259 function_code == FunctionCode::READ_COILS || function_code == FunctionCode::READ_DISCRETE_INPUTS;
1260 const size_t expected_data_size =
1261 bits ? packed_bit_bytes(count_or_value) : static_cast<size_t>(count_or_value) * 2;
1262 if (response_pdu.size() != expected_data_size + 2) {
1263 ESP_LOGD(TAG, "Response length %zu does not match request (expected %zu) for function code 0x%X",
1264 response_pdu.size(), expected_data_size + 2, static_cast<uint8_t>(function_code));
1265 custom = true;
1266 }
1267 }
1268 }
1269 if (custom) {
1270 this->on_custom_response(request_pdu, response_pdu, status);
1271 return;
1272 }
1273
1274 switch (function_code) {
1277 // FC 0x17 lands here too: its read start address and read quantity sit at the same request offsets as a
1278 // plain read's (bytes 1..2 and 3..4), so start_address and count_or_value already hold the read block; its
1279 // response carries only that read data, and the write half is confirmed by the response arriving at all.
1280 // An exception routes here as well (the gate only validates the request when status is set), delivering
1281 // empty registers with the error in status - so a 0x17 subclass handles success and failure in the one
1282 // on_read_holding_registers() callback and never needs to also override on_error().
1284 // Decode the big-endian register words into host byte order. The gate guarantees a success response
1285 // carries exactly count_or_value registers (and count_or_value <= MAX_NUM_OF_REGISTERS_TO_READ, the
1286 // capacity of RegisterValues); a mismatch was diverted to on_custom_response(), never clamped. On
1287 // failure the registers span is empty.
1288 RegisterValues registers;
1289 if (succeeded(status)) {
1290 for (size_t i = 0; i != count_or_value; i++) {
1291 registers.push_back(helpers::get_data<uint16_t>(response_pdu.data(), 2 + 2 * i));
1292 }
1293 }
1294 std::span<const uint16_t> register_span(registers.data(), registers.size());
1295 if (function_code == FunctionCode::READ_INPUT_REGISTERS) {
1296 this->on_read_input_registers(start_address, register_span, status);
1297 } else if (function_code == FunctionCode::READ_HOLDING_REGISTERS ||
1299 this->on_read_holding_registers(start_address, register_span, status);
1300 } else {
1301 // Unreachable for the current case labels; match explicitly so a function code added to this group
1302 // later is diverted to on_custom_response() rather than silently delivered as a holding read.
1303 this->on_custom_response(request_pdu, response_pdu, status);
1304 }
1305 break;
1306 }
1309 // Deliver the bits packed as on the wire; the gate guarantees a success response carries exactly
1310 // (count_or_value + 7) / 8 data bytes. On failure the view is empty AND the count is zero -
1311 // PackedBits::operator[] is unchecked, so size() must never promise bits with no bytes behind them.
1312 std::span<const uint8_t> packed_bytes;
1313 uint16_t count = 0;
1314 if (succeeded(status)) {
1315 packed_bytes = response_pdu.subspan(2);
1316 count = count_or_value;
1317 }
1318 PackedBits bits(packed_bytes, count);
1319 if (function_code == FunctionCode::READ_COILS) {
1320 this->on_read_coils(start_address, bits, status);
1321 } else {
1322 this->on_read_discrete_inputs(start_address, bits, status);
1323 }
1324 break;
1325 }
1326 // Single-write acks echo the value: on success that echo is device-confirmed state - the one
1327 // write whose acknowledgement carries a real read-back - so it is preferred over the request
1328 // copy. On an exception the response has no value and the request copy is the only one.
1331 const uint16_t value = (succeeded(status) && response_pdu.size() >= WRITE_SINGLE_PDU_SIZE)
1332 ? helpers::get_data<uint16_t>(response_pdu.data(), 3)
1333 : count_or_value;
1334 if (function_code == FunctionCode::WRITE_SINGLE_REGISTER) {
1335 this->on_write_single_register(start_address, value, status);
1336 } else {
1337 this->on_write_single_coil(start_address, value == 0xFF00, status);
1338 }
1339 break;
1340 }
1342 // Request layout: [0] function code, [1..2] start address, [3..4] register count, [5] byte count,
1343 // [6..] register data. The gate guarantees the request carries exactly count_or_value registers
1344 // (<= MAX_NUM_OF_REGISTERS_TO_WRITE, within RegisterValues capacity). Decoded from the request and
1345 // delivered regardless of status - see the write-acknowledgement note in modbus.h.
1346 RegisterValues registers;
1347 for (size_t i = 0; i != count_or_value; i++) {
1348 registers.push_back(helpers::get_data<uint16_t>(request_pdu.data(), 6 + 2 * i));
1349 }
1350 std::span<const uint16_t> register_span(registers.data(), registers.size());
1351 this->on_write_multiple_registers(start_address, register_span, status);
1352 break;
1353 }
1355 // Request layout: [0] function code, [1..2] start address, [3..4] coil count, [5] byte count,
1356 // [6..] packed bits. The gate guarantees the request carries exactly (count_or_value + 7) / 8 packed
1357 // bytes. Decoded from the request and delivered regardless of status - see the write-acknowledgement
1358 // note in modbus.h.
1359 std::span<const uint8_t> packed_bytes = request_pdu.subspan(6);
1360 PackedBits bits(packed_bytes, count_or_value);
1361 this->on_write_multiple_coils(start_address, bits, status);
1362 break;
1363 }
1364 default:
1365 this->on_custom_response(request_pdu, response_pdu, status);
1366 break;
1367 }
1368}
1369
1370// Default on_custom_response handler to warn when responses unexpectedly trigger on_custom_response
1371void ModbusClientDevice::on_custom_response(std::span<const uint8_t> request_pdu, std::span<const uint8_t> response_pdu,
1372 ResponseStatus status) {
1373 // The dispatcher never calls this with an empty request, but this is a public virtual - stay safe.
1374 const uint8_t function_code = request_pdu.empty() ? 0 : request_pdu[0];
1375 // Warn once per device, then drop to VERBOSE: a mildly non-conformant peer answers every poll,
1376 // and an unhandled-response warning per transaction would flood the log permanently.
1377 if (!this->custom_response_warned_) {
1378 this->custom_response_warned_ = true;
1379 ESP_LOGW(TAG, "Non-standard request or response for function code 0x%X. No on_custom_response handler declared",
1380 function_code);
1381 } else {
1382 ESP_LOGV(TAG, "Non-standard request or response for function code 0x%X (unhandled)", function_code);
1383 }
1384}
1385
1386} // namespace esphome::modbus
uint8_t address
Definition bl0906.h:4
uint8_t raw[35]
Definition bl0939.h:0
uint8_t status
Definition bl0942.h:8
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
virtual void setup()=0
virtual void digital_write(bool value)=0
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:227
size_t size() const
Definition helpers.h:292
void push_back(const T &value)
Definition helpers.h:265
virtual void on_response(std::span< const uint8_t > request_pdu, std::span< const uint8_t > response_pdu)
Low-level response hook: called with the request PDU this device sent and the response PDU received T...
Definition modbus.h:458
virtual void on_write_multiple_coils(uint16_t start_address, PackedBits bits, ResponseStatus status)
Definition modbus.h:529
virtual void on_read_holding_registers(uint16_t start_address, std::span< const uint16_t > registers, ResponseStatus status)
Definition modbus.h:498
virtual void on_write_multiple_registers(uint16_t start_address, std::span< const uint16_t > registers, ResponseStatus status)
Definition modbus.h:527
virtual void on_sent(std::span< const uint8_t > request_pdu)
Called when this device's frame is actually written to the wire.
Definition modbus.h:476
virtual void on_write_single_register(uint16_t address, uint16_t value, ResponseStatus status)
Write acknowledgements.
Definition modbus.h:525
virtual bool on_no_response(std::span< const uint8_t > request_pdu)
Called when no matching, uninterrupted response arrived; return true to have the hub re-queue the fra...
Definition modbus.h:479
virtual void on_custom_response(std::span< const uint8_t > request_pdu, std::span< const uint8_t > response_pdu, ResponseStatus status)
Catch-all for custom function codes and anything that is not a standard-conformant transaction (see d...
Definition modbus.cpp:1371
virtual void on_read_discrete_inputs(uint16_t start_address, PackedBits bits, ResponseStatus status)
Definition modbus.h:513
virtual void on_error(std::span< const uint8_t > request_pdu, ExceptionCode exception_code)
Low-level error hook: called with the request PDU and the modbus exception code from the error respon...
Definition modbus.h:464
virtual void on_not_sent(std::span< const uint8_t > request_pdu)
Called when an accepted request was dropped before transmission by clear_tx_queue_for_address().
Definition modbus.h:469
virtual void on_read_coils(uint16_t start_address, PackedBits bits, ResponseStatus status)
Definition modbus.h:510
virtual void on_write_single_coil(uint16_t address, bool value, ResponseStatus status)
Definition modbus.h:526
virtual void on_read_input_registers(uint16_t start_address, std::span< const uint16_t > registers, ResponseStatus status)
Definition modbus.h:502
void clear_tx_queue_for_device(ModbusClientDevice *device)
Definition modbus.cpp:1157
void parse_modbus_frames() override
Definition modbus.cpp:174
ModbusDeviceCommand * find_waiting_()
Definition modbus.cpp:903
std::span< const uint8_t > pdu
Definition modbus.h:294
uint8_t uint16_t uint16_t uint8_t const uint8_t ModbusClientDevice * device
Definition modbus.h:274
ModbusDeviceCommand * select_next_ready_()
Definition modbus.cpp:911
uint8_t uint16_t uint16_t uint8_t const uint8_t * payload
Definition modbus.h:274
int32_t tx_delay_remaining() override
Definition modbus.cpp:118
std::deque< ModbusDeviceCommand > tx_buffer_
Definition modbus.h:332
bool queue_pdu(uint8_t address, std::span< const uint8_t > pdu, ModbusClientDevice *device=nullptr, CommandOptions options={})
Queue a request.
Definition modbus.cpp:1045
void clear_tx_queue_for_address(uint8_t address)
Definition modbus.cpp:1147
void process_modbus_server_frame(uint8_t address, std::span< const uint8_t > pdu) override
Definition modbus.cpp:318
void setup() override
Definition modbus.cpp:24
uint16_t frame_delay_ms_
Definition modbus.h:91
virtual void process_modbus_server_frame(uint8_t address, std::span< const uint8_t > pdu)=0
bool parse_modbus_server_frame_()
Definition modbus.cpp:245
virtual void parse_modbus_frames()=0
bool send_frame_(const ModbusFrame &frame)
Definition modbus.cpp:780
uint32_t last_modbus_byte_
Definition modbus.h:87
GPIOPin * flow_control_pin_
Definition modbus.h:94
uint32_t last_send_tx_offset_
Definition modbus.h:90
virtual bool tx_blocked()
Definition modbus.cpp:126
void clear_rx_buffer_(const LogString *reason, bool warn=false, size_t bytes_to_clear=0)
Definition modbus.cpp:1208
void loop() override
Definition modbus.cpp:45
float get_setup_priority() const override
Definition modbus.cpp:862
uint16_t long_rx_buffer_delay_ms_
Definition modbus.h:92
virtual int32_t tx_delay_remaining()
Definition modbus.cpp:106
uint16_t find_frame_end_by_crc_(uint16_t min_length) const
Definition modbus.cpp:222
std::vector< uint8_t > rx_buffer_
Definition modbus.h:96
uint32_t last_receive_check_
Definition modbus.h:88
virtual ResponseStatus on_read_coils(uint16_t start_address, MutablePackedBits bits)
Definition modbus.h:695
virtual ResponseStatus on_write_registers(uint16_t start_address, const RegisterValues &registers)
Definition modbus.h:686
virtual ResponseStatus on_read_holding_registers(uint16_t start_address, uint16_t number_of_registers, RegisterValues &registers)
Definition modbus.h:682
virtual ResponseStatus on_read_discrete_inputs(uint16_t start_address, MutablePackedBits bits)
Definition modbus.h:698
virtual ResponseStatus on_write_coils(uint16_t start_address, PackedBits bits)
Coil writes deliver the values as a PackedBits view over the hub's receive buffer (only valid during ...
Definition modbus.h:703
virtual ResponseStatus on_read_input_registers(uint16_t start_address, uint16_t number_of_registers, RegisterValues &registers)
Definition modbus.h:678
std::vector< ModbusServerDevice * > devices_
Definition modbus.h:409
ResponseStatus check_address_range_(uint16_t start_address, uint16_t count)
Definition modbus.cpp:395
ResponseStatus parse_read_request_(std::span< const uint8_t > data, uint16_t max_entities, const LogString *entity_name, uint16_t &start_address, uint16_t &count)
Definition modbus.cpp:441
void process_modbus_client_frame_(uint8_t address, uint8_t function_code, std::span< const uint8_t > data)
Definition modbus.cpp:610
void parse_modbus_frames() override
Definition modbus.cpp:187
void process_modbus_server_frame(uint8_t address, std::span< const uint8_t > pdu) override
Definition modbus.cpp:370
ResponseStatus parse_write_multiple_coils_(std::span< const uint8_t > data, uint16_t &start_address, uint16_t &count, std::span< const uint8_t > &packed_bytes)
Definition modbus.cpp:468
void process_broadcast_frame_(uint8_t function_code, std::span< const uint8_t > data)
Definition modbus.cpp:493
ModbusServerDevice * find_device_(uint8_t address)
Definition modbus.cpp:386
ResponseStatus parse_write_single_coil_(std::span< const uint8_t > data, uint16_t &start_address, bool &value)
Definition modbus.cpp:455
bool build_or_reject_read_response_(uint8_t address, uint8_t function_code, ResponseStatus status, uint16_t number_of_registers, const RegisterValues &registers, std::span< uint8_t > response_buffer, uint16_t &response_len)
Definition modbus.cpp:567
void send_exception_(uint8_t address, uint8_t function_code, ExceptionCode exception_code)
Definition modbus.cpp:895
void assemble_registers_(std::span< const uint8_t > values, RegisterValues &registers)
Definition modbus.cpp:487
void send_raw_(const uint8_t *payload, uint16_t len)
Definition modbus.cpp:1177
void send_response_(uint8_t address, uint8_t function_code, const uint8_t *payload, uint16_t payload_len)
Definition modbus.cpp:867
ResponseStatus parse_write_multiple_(std::span< const uint8_t > data, uint16_t &start_address, RegisterValues &registers)
Definition modbus.cpp:424
bool rejected_(uint8_t address, uint8_t function_code, ResponseStatus status)
Definition modbus.cpp:882
ResponseStatus parse_write_single_(std::span< const uint8_t > data, uint16_t &start_address, RegisterValues &registers)
Definition modbus.cpp:416
std::array< uint8_t, MAX_RAW_SIZE > deferred_payload_
Definition modbus.h:417
Mutable counterpart of PackedBits: set() writes bits in place (deliberately no proxy operator[]=).
Read-only view of Modbus-packed bits: bit 0 of byte 0 is the first bit (LSB first),...
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
uint8_t priority
uint8_t options
bool address_range_fits(uint16_t start_address, size_t count)
bool is_function_code_read_only(uint8_t function_code)
uint8_t client_frame_data_offset(const uint8_t *, size_t)
T get_data(const uint8_t *data, size_t buffer_offset)
Extract data from modbus response buffer.
bool is_function_code_read(uint8_t function_code)
uint16_t client_frame_length(const uint8_t *frame, size_t size)
bool is_server_pdu_standard(const uint8_t *pdu, size_t size)
uint16_t server_frame_length(const uint8_t *frame, size_t size)
bool is_function_code_unknown_length(uint8_t function_code)
True for any function code whose frame length the parsers cannot predict - everything the server_pdu_...
bool is_function_code_custom(uint8_t function_code)
bool is_client_pdu_standard(const uint8_t *pdu, size_t size)
bool is_function_code_exception(uint8_t function_code)
const uint8_t FUNCTION_CODE_MASK
StaticVector< uint16_t, MAX_NUM_OF_REGISTERS_TO_READ > RegisterValues
Definition modbus.h:347
const uint8_t FUNCTION_CODE_EXCEPTION_MASK
std::optional< ExceptionCode > ResponseStatus
Definition modbus.h:336
bool succeeded(ResponseStatus status)
True when a transaction carried no exception.
Definition modbus.h:342
constexpr size_t packed_bit_bytes(size_t bits)
Bits pack 8 per data byte, rounded up to whole bytes.
constexpr float BUS
For communication buses like i2c/spi.
Definition component.h:39
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
const void size_t len
Definition hal.h:64
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:406
uint16_t size
Definition helpers.cpp:25
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:1426
void HOT delay(uint32_t ms)
Definition hal.cpp:85
constexpr std::array< uint8_t, sizeof(T)> decode_value(T val)
Decode a value into its constituent bytes (from most to least significant).
Definition helpers.h:912
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:28
static void uint32_t
bool response(std::span< const uint8_t > response_pdu)
Definition modbus.cpp:946
CommandPriority priority() const
Definition modbus.h:147
static CommandPriority classify(uint8_t function_code)
Definition modbus.h:151
bool error(ExceptionCode exception_code)
Definition modbus.cpp:957
ModbusClientDevice * device
Definition modbus.h:127
uint8_t address() const
Definition modbus.h:51
SmallInlineBuffer< MODBUS_FRAME_INLINE_SIZE > data
Definition modbus.h:37
std::span< const uint8_t > pdu() const
The PDU: function code + data, without address or CRC.
Definition modbus.h:55
uint16_t size() const
Definition modbus.h:48