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