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