ESPHome 2026.8.2
Loading...
Searching...
No Matches
modbus_helpers.cpp
Go to the documentation of this file.
1#include "modbus_helpers.h"
2#include "esphome/core/log.h"
3
4#include <algorithm>
5
7
8static const char *const TAG = "modbus_helpers";
9
10// A quantity/address pair is standard when the quantity is non-zero, within the per-table maximum,
11// and the range [start_address, start_address + quantity) stays inside the 16-bit address space.
12// Non-logging twin of register_block_in_range(): the same three predicates for the parser side, taking a
13// uint16_t quantity. register_block_in_range() is the builder-side variant that also logs which half failed.
14static bool quantity_in_range(uint16_t start_address, uint16_t quantity, uint16_t max_quantity) {
15 return quantity != 0 && quantity <= max_quantity && address_range_fits(start_address, quantity);
16}
17
18// The spec allows exactly ON (0xFF00) and OFF (0x0000) for a single-coil value, on the request and
19// on its echoed response alike.
20static bool is_canonical_coil_value(uint8_t high_byte, uint8_t low_byte) {
21 return (high_byte == 0xFF || high_byte == 0x00) && low_byte == 0x00;
22}
23
24uint16_t server_pdu_length(const uint8_t *frame, size_t size) {
25 if (size < MIN_PDU_SIZE)
26 return MIN_PDU_SIZE;
27 if (is_function_code_exception(frame[0])) {
28 return 2; // function(1) + exception(1)
29 }
30 switch (static_cast<FunctionCode>(frame[0])) {
35 // function(1) + byte count(1) + data
36 return 2 + (size > 1 ? std::min(frame[1], uint8_t(MAX_NUM_OF_REGISTERS_TO_READ * 2)) : 0);
41 return 5; // function(1) + output/register address(2) + value(2)
42 // Unsupported function codes. Included here to prevent parser failures. Excluding Serial Line specific functions.
45 // function(1) + byte count(1) + data
46 return 2 + (size > 1 ? std::min(frame[1], uint8_t(MAX_PDU_SIZE - 2)) : 0);
48 return 7; // function(1) + reference address(2) + AND mask(2) + OR mask(2)
50 // function(1) + byte count(1) + data
51 return 2 + (size > 1 ? std::min(frame[1], uint8_t(MAX_NUM_OF_REGISTERS_TO_READ * 2)) : 0);
53 // function(1) + fifo address(2)
54 return 3;
55 default:
56 return MIN_PDU_SIZE; // unknown length
57 }
58}
59
60uint16_t client_pdu_length(const uint8_t *frame, size_t size) {
61 if (size < MIN_PDU_SIZE)
62 return MIN_PDU_SIZE;
63 switch (static_cast<FunctionCode>(frame[0])) {
68 // function(1) + start address(2) + quantity(2)
71 return 5; // function(1) + output/register address(2) + value(2)
73 // function(1) + start address(2) + quantity(2) + byte count(1) + packed coil data (8 coils per byte).
74 return 6 + (size > 5 ? std::min(frame[5], uint8_t(packed_bit_bytes(MAX_NUM_OF_COILS_TO_WRITE))) : 0);
76 // function(1) + start address(2) + quantity(2) + byte count(1) + register data (2 bytes per register).
77 return 6 + (size > 5 ? std::min(frame[5], uint8_t(MAX_NUM_OF_REGISTERS_TO_WRITE * 2)) : 0);
78 // Unsupported function codes. Included here to prevent parser failures. Excluding Serial Line specific functions.
81 // function(1) + byte count(1) + data
82 return 2 + (size > 1 ? std::min(frame[1], uint8_t(MAX_PDU_SIZE - 2)) : 0);
84 return 7; // function(1) + reference address(2) + AND mask(2) + OR mask(2)
86 // function(1) + read start address(2) + read quantity(2) + write start address(2) +
87 // write quantity(2) + byte count(1) + data
88 return 10 + (size > 9 ? std::min(frame[9], uint8_t(MAX_NUM_OF_REGISTERS_TO_WRITE_RW * 2)) : 0);
90 // function(1) + fifo address(2)
91 return 3;
92 default:
93 return MIN_PDU_SIZE; // unknown length
94 }
95}
96
97bool is_server_pdu_standard(const uint8_t *pdu, size_t size) {
98 if (server_pdu_length(pdu, size) != size)
99 return false;
100
101 const auto function_code = static_cast<FunctionCode>(pdu[0]);
102 switch (function_code) {
105 // A conformant bit-read response carries at least one packed byte (up to 2000 bits = 250 bytes).
106 return pdu[1] != 0 && pdu[1] <= uint8_t(packed_bit_bytes(MAX_NUM_OF_COILS_TO_READ));
109 // Registers are 2 bytes each: the byte count must be a non-zero even count within the read maximum.
110 return pdu[1] != 0 && pdu[1] % 2 == 0 && pdu[1] <= uint8_t(MAX_NUM_OF_REGISTERS_TO_READ * 2);
113 return pdu[1] <= uint8_t(MAX_PDU_SIZE - 2);
115 return pdu[1] != 0 && pdu[1] % 2 == 0 && pdu[1] <= uint8_t(MAX_NUM_OF_REGISTERS_TO_READ * 2);
118 // The response echoes start address and quantity: bound them like the request side does.
119 const bool bits = function_code == FunctionCode::WRITE_MULTIPLE_COILS;
120 const uint16_t start_address = get_data<uint16_t>(pdu, 1);
121 const uint16_t quantity = get_data<uint16_t>(pdu, 3);
122 const uint16_t max_quantity = bits ? MAX_NUM_OF_COILS_TO_WRITE : MAX_NUM_OF_REGISTERS_TO_WRITE;
123 return quantity_in_range(start_address, quantity, max_quantity);
124 }
126 // The response echoes the request, so the same ON/OFF constraint applies.
127 return is_canonical_coil_value(pdu[3], pdu[4]);
128 default:
129 return true; // All other function codes validated by length alone
130 }
131}
132
133bool is_client_pdu_standard(const uint8_t *pdu, size_t size) {
134 if (client_pdu_length(pdu, size) != size)
135 return false;
136
137 const auto function_code = static_cast<FunctionCode>(pdu[0]);
138 switch (function_code) {
143 const bool bits =
144 function_code == FunctionCode::READ_COILS || function_code == FunctionCode::READ_DISCRETE_INPUTS;
145 const uint16_t start_address = get_data<uint16_t>(pdu, 1);
146 const uint16_t quantity = get_data<uint16_t>(pdu, 3);
147 const uint16_t max_quantity = bits ? MAX_NUM_OF_COILS_TO_READ : MAX_NUM_OF_REGISTERS_TO_READ;
148 return quantity_in_range(start_address, quantity, max_quantity);
149 }
152 const bool bits = function_code == FunctionCode::WRITE_MULTIPLE_COILS;
153 const uint16_t start_address = get_data<uint16_t>(pdu, 1);
154 const uint16_t quantity = get_data<uint16_t>(pdu, 3);
155 const uint16_t max_quantity = bits ? MAX_NUM_OF_COILS_TO_WRITE : MAX_NUM_OF_REGISTERS_TO_WRITE;
156 // Coils are packed 8 per data byte; registers are 2 bytes each.
157 const size_t expected_data_bytes = bits ? packed_bit_bytes(quantity) : quantity * 2;
158 return quantity_in_range(start_address, quantity, max_quantity) && pdu[5] == expected_data_bytes;
159 }
162 return pdu[1] <= MAX_PDU_SIZE - 2;
164 const uint16_t start_address_read = get_data<uint16_t>(pdu, 1);
165 const uint16_t quantity_read = get_data<uint16_t>(pdu, 3);
166 const uint16_t start_address_write = get_data<uint16_t>(pdu, 5);
167 const uint16_t quantity_write = get_data<uint16_t>(pdu, 7);
168 return quantity_in_range(start_address_read, quantity_read, MAX_NUM_OF_REGISTERS_TO_READ) &&
169 quantity_in_range(start_address_write, quantity_write, MAX_NUM_OF_REGISTERS_TO_WRITE_RW) &&
170 pdu[9] == quantity_write * 2;
171 }
173 // The one variable field in an otherwise fixed-shape PDU: the spec allows exactly ON/OFF.
174 return is_canonical_coil_value(pdu[3], pdu[4]);
175 default:
176 return true; // All other function codes validated by length alone
177 }
178}
179
180static size_t required_payload_size(SensorValueType sensor_value_type) {
181 switch (sensor_value_type) {
186 return 2;
193 return 4;
198 return 8;
200 default:
201 return 0;
202 }
203}
204
206 ESP_LOGE(TAG, "Invalid data type for modbus number to payload conversion: %d", static_cast<uint16_t>(value_type));
207}
208
209std::optional<int64_t> payload_to_number(const uint8_t *data, size_t size, SensorValueType sensor_value_type,
210 uint8_t offset, uint32_t bitmask) {
211 int64_t value = 0; // int64_t because it can hold signed and unsigned 32 bits
212
213 // Validate offset against the buffer for all types, including RAW/unsupported, so
214 // a malformed or misconfigured frame still produces an error log.
215 if (static_cast<size_t>(offset) > size) {
216 ESP_LOGE(TAG, "not enough data for value type=%u offset=%u size=%zu", static_cast<unsigned int>(sensor_value_type),
217 static_cast<unsigned int>(offset), size);
218 return std::nullopt;
219 }
220
221 const size_t required_size = required_payload_size(sensor_value_type);
222 if (required_size == 0) {
223 return value;
224 }
225
226 if (size - offset < required_size) {
227 ESP_LOGE(TAG, "not enough data for value type=%u offset=%u size=%zu required=%zu",
228 static_cast<unsigned int>(sensor_value_type), static_cast<unsigned int>(offset), size, required_size);
229 return std::nullopt;
230 }
231
232 switch (sensor_value_type) {
234 value = mask_and_shift_by_rightbit(get_data<uint16_t>(data, offset), bitmask); // default is 0xFFFF ;
235 break;
237 uint16_t word = byteswap(get_data<uint16_t>(data, offset));
238 value = mask_and_shift_by_rightbit(word, bitmask);
239 break;
240 }
243 value = get_data<uint32_t>(data, offset);
244 value = mask_and_shift_by_rightbit((uint32_t) value, bitmask);
245 break;
248 value = get_data<uint32_t>(data, offset);
249 value = static_cast<uint32_t>(value & 0xFFFF) << 16 | (value & 0xFFFF0000) >> 16;
250 value = mask_and_shift_by_rightbit((uint32_t) value, bitmask);
251 break;
253 value = mask_and_shift_by_rightbit(get_data<int16_t>(data, offset), bitmask); // default is 0xFFFF ;
254 break;
256 uint16_t word = byteswap(get_data<uint16_t>(data, offset));
257 value = mask_and_shift_by_rightbit(static_cast<int16_t>(word), bitmask);
258 break;
259 }
261 value = mask_and_shift_by_rightbit(get_data<int32_t>(data, offset), bitmask);
262 break;
264 value = get_data<uint32_t>(data, offset);
265 // Currently the high word is at the low position
266 // the sign bit is therefore at low before the switch
267 uint32_t sign_bit = (value & 0x8000) << 16;
269 static_cast<int32_t>(((value & 0x7FFF) << 16 | (value & 0xFFFF0000) >> 16) | sign_bit), bitmask);
270 } break;
273 // Ignore bitmask for QWORD
274 value = get_data<uint64_t>(data, offset);
275 break;
278 // Ignore bitmask for QWORD
279 uint64_t tmp = get_data<uint64_t>(data, offset);
280 value = (tmp << 48) | (tmp >> 48) | ((tmp & 0xFFFF0000) << 16) | ((tmp >> 16) & 0xFFFF0000);
281 } break;
283 default:
284 break;
285 }
286 return value;
287}
288
289std::optional<int64_t> registers_to_number(const uint16_t *registers, size_t count, SensorValueType sensor_value_type) {
290 const size_t required_size = required_payload_size(sensor_value_type);
291 if (required_size == 0) {
292 return 0; // RAW/unsupported: nothing to read
293 }
294 const size_t required_words = required_size / 2;
295 if (required_words > count) {
296 ESP_LOGE(TAG, "not enough registers for value type=%u count=%zu required=%zu",
297 static_cast<unsigned int>(sensor_value_type), count, required_words);
298 return std::nullopt;
299 }
300 // Serialize the needed words back to big-endian bytes and reuse the audited byte decoder so the
301 // sign-extension behaviour stays identical to the wire path.
302 uint8_t bytes[8]; // at most 4 registers (QWORD)
303 for (size_t i = 0; i < required_words; i++) {
304 uint16_t reg = registers[i];
305 bytes[i * 2] = static_cast<uint8_t>(reg >> 8);
306 bytes[i * 2 + 1] = static_cast<uint8_t>(reg & 0xFF);
307 }
308 return payload_to_number(bytes, required_size, sensor_value_type, 0, 0xFFFFFFFF);
309}
310
311// Append a 16-bit value to a PDU in big-endian (wire) byte order.
312template<size_t CAP> static void append_pdu_word(StaticVector<uint8_t, CAP> &pdu, uint16_t value) {
313 pdu.push_back(value >> 8);
314 pdu.push_back(value >> 0);
315}
316
317// Every request PDU opens with the same 5-byte layout: function code, then two big-endian 16-bit
318// fields (start address + quantity for reads and multi-writes, address + value for single writes).
319template<size_t CAP>
320static void append_pdu_header(StaticVector<uint8_t, CAP> &pdu, FunctionCode function_code, uint16_t first,
321 uint16_t second) {
322 pdu.push_back(static_cast<uint8_t>(function_code));
323 append_pdu_word(pdu, first);
324 append_pdu_word(pdu, second);
325}
326
327// Zero the unused bits of a multi-coil write's final data byte, as the spec requires. Kept in one
328// place so the generic and typed coil builders produce identical wire bytes for the same write.
329// The caller must pass a span whose LAST byte is the final packed-bit byte - both builders pass the
330// whole PDU, which qualifies because the coil data is always the PDU's tail.
331static void mask_trailing_pad_bits(std::span<uint8_t> data, uint16_t bit_count) {
332 if (data.empty() || bit_count % 8 == 0)
333 return;
334 data.back() &= static_cast<uint8_t>((1 << (bit_count % 8)) - 1);
335}
336
337ReadPdu create_read_pdu(FunctionCode function_code, uint16_t start_address, uint16_t number_of_entities) {
338 ReadPdu pdu; // declared before every return so NRVO fires (all paths return the same object)
339 if (number_of_entities == 0) {
340 ESP_LOGE(TAG, "Number of entities is zero for function code %02X", static_cast<uint8_t>(function_code));
341 return pdu;
342 }
343 if (!address_range_fits(start_address, number_of_entities)) {
344 ESP_LOGE(TAG, "Read of %u entities at %u runs past the 16-bit address space, dropping request", number_of_entities,
345 start_address);
346 return pdu;
347 }
348
349 switch (function_code) {
351 if (number_of_entities > MAX_NUM_OF_COILS_TO_READ) {
352 ESP_LOGE(TAG, "number_of_entities %u exceeds maximum coils to read %u for function code %02X",
353 number_of_entities, MAX_NUM_OF_COILS_TO_READ, static_cast<uint8_t>(function_code));
354 return pdu;
355 }
356 break;
358 if (number_of_entities > MAX_NUM_OF_DISCRETE_INPUTS_TO_READ) {
359 ESP_LOGE(TAG, "number_of_entities %u exceeds maximum discrete inputs to read %u for function code %02X",
360 number_of_entities, MAX_NUM_OF_DISCRETE_INPUTS_TO_READ, static_cast<uint8_t>(function_code));
361 return pdu;
362 }
363 break;
366 if (number_of_entities > MAX_NUM_OF_REGISTERS_TO_READ) {
367 ESP_LOGE(TAG, "number_of_entities %u exceeds maximum registers to read %u for function code %02X",
368 number_of_entities, MAX_NUM_OF_REGISTERS_TO_READ, static_cast<uint8_t>(function_code));
369 return pdu;
370 }
371 break;
372 default:
373 ESP_LOGE(TAG, "Unsupported function code %02X for read PDU creation", static_cast<uint8_t>(function_code));
374 return pdu;
375 }
376
377 append_pdu_header(pdu, function_code, start_address, number_of_entities);
378 return pdu;
379}
380
381PduBuffer create_client_pdu(FunctionCode function_code, uint16_t start_address, uint16_t number_of_entities,
382 const uint8_t *values, size_t values_len) {
383 PduBuffer pdu; // declared before every return so NRVO fires (all paths return the same object)
384 // Generic entry point; prefer the direction- and type-specific builders (create_read_pdu(),
385 // create_write_registers_pdu(), etc.) which bound their inputs per spec.
386 if (is_function_code_read_only(static_cast<uint8_t>(function_code))) {
387 if (values != nullptr || values_len > 0) {
388 ESP_LOGW(TAG, "Values provided for read function code %02X, but will be ignored",
389 static_cast<uint8_t>(function_code));
390 }
391 auto read_pdu = create_read_pdu(function_code, start_address, number_of_entities);
392 pdu.assign(read_pdu.begin(), read_pdu.end());
393 return pdu;
394 }
395 // Exact codes only: is_function_code_write() masks the exception bit, which would let the
396 // exception-flagged forms (0x85/0x86/0x8F/0x90) build a request announcing itself as an exception.
397 const bool is_single =
398 function_code == FunctionCode::WRITE_SINGLE_COIL || function_code == FunctionCode::WRITE_SINGLE_REGISTER;
399 const bool is_multi =
401 if (!is_single && !is_multi) {
402 ESP_LOGE(TAG, "Unsupported function code %02X for client PDU creation", static_cast<uint8_t>(function_code));
403 return pdu;
404 }
405
406 // Generic write builder: raw caller-supplied bytes, so we can only guard against the PDU byte capacity here.
407 if (values == nullptr || values_len == 0) {
408 ESP_LOGE(TAG, "No values provided for write function code %02X", static_cast<uint8_t>(function_code));
409 return pdu;
410 }
411 if (number_of_entities == 0) {
412 ESP_LOGE(TAG, "Number of entities is zero for function code %02X", static_cast<uint8_t>(function_code));
413 return pdu;
414 }
415 // number_of_entities is ignored for single write, so only validate it for the multiple variants.
416 // The bound is per function code (coils pack 8 per byte, so their quantity limit is far higher) -
417 // the same limits is_client_pdu_standard() accepts, so builder and validator agree.
418 const uint16_t max_entities =
419 function_code == FunctionCode::WRITE_MULTIPLE_COILS ? MAX_NUM_OF_COILS_TO_WRITE : MAX_NUM_OF_REGISTERS_TO_WRITE;
420 if (!is_single && number_of_entities > max_entities) {
421 ESP_LOGE(TAG, "number_of_entities %u exceeds maximum %u for function code %02X", number_of_entities, max_entities,
422 static_cast<uint8_t>(function_code));
423 return pdu;
424 }
425 if (!is_single && !address_range_fits(start_address, number_of_entities)) {
426 ESP_LOGE(TAG, "Write of %u entities at %u runs past the 16-bit address space, dropping request", number_of_entities,
427 start_address);
428 return pdu;
429 }
430
431 if (is_single) {
432 // Write single register or coil: the two value bytes are the header's second field.
433 if (values_len < 2) {
434 ESP_LOGE(TAG, "values_len %zu too small for write-single command (need 2), dropping request", values_len);
435 return pdu;
436 }
437 // The spec allows exactly ON (0xFF00) and OFF (0x0000) for a single-coil write - the same rule
438 // is_client_pdu_standard() enforces, so a built frame cannot be misclassified on reply.
439 if (function_code == FunctionCode::WRITE_SINGLE_COIL && !is_canonical_coil_value(values[0], values[1])) {
440 ESP_LOGE(TAG, "Invalid single-coil value %02X%02X (must be FF00 or 0000), dropping request", values[0],
441 values[1]);
442 return pdu;
443 }
444 append_pdu_header(pdu, function_code, start_address, uint16_t((values[0] << 8) | values[1]));
445 return pdu;
446 }
447 // The quantity is spec-bounded above, so the data length just has to agree with it exactly
448 // (registers are 2 bytes each, coils pack 8 per byte). This is the same consistency the response
449 // dispatch enforces via is_client_pdu_standard(), so a frame built here can never be classified
450 // non-standard on reply, and the spec bound keeps the PDU within capacity by construction.
451 // Checked before the header append: a failed check must return an empty PDU, not a 5-byte partial one.
452 const bool bits = function_code == FunctionCode::WRITE_MULTIPLE_COILS;
453 const size_t expected_len = bits ? packed_bit_bytes(number_of_entities) : static_cast<size_t>(number_of_entities) * 2;
454 if (values_len != expected_len) {
455 ESP_LOGE(TAG, "values_len %zu does not match %u entities (expected %zu) for function code %02X, dropping request",
456 values_len, number_of_entities, expected_len, static_cast<uint8_t>(function_code));
457 return pdu;
458 }
459 append_pdu_header(pdu, function_code, start_address, number_of_entities);
460 pdu.push_back(values_len); // Byte count is required for write multiple
461 for (size_t i = 0; i < values_len; i++)
462 pdu.push_back(values[i]);
463 if (bits)
464 mask_trailing_pad_bits(pdu, number_of_entities);
465 return pdu;
466}
467
468// Validate one register block for a client builder: a non-zero quantity within max_quantity that does not
469// run past the 16-bit address space (register count × 2 stays within MAX_PDU_SIZE as a result). On failure
470// it logs the reason and returns false, on which the caller returns an empty PDU. `role` names the block in
471// the log ("Read"/"Write"). Logging twin of quantity_in_range(): the same three predicates, split so each
472// failure names its reason, and taking size_t so an oversize span is caught before any narrowing.
473static bool register_block_in_range(const LogString *role, uint16_t start_address, size_t quantity,
474 uint16_t max_quantity) {
475 if (quantity == 0 || quantity > max_quantity) {
476 ESP_LOGE(TAG, "%s count %zu out of range [1, %u], dropping request", LOG_STR_ARG(role), quantity, max_quantity);
477 return false;
478 }
479 if (!address_range_fits(start_address, quantity)) {
480 ESP_LOGE(TAG, "%s of %zu registers at %u runs past the 16-bit address space, dropping request", LOG_STR_ARG(role),
481 quantity, start_address);
482 return false;
483 }
484 return true;
485}
486
487PduBuffer create_write_registers_pdu(uint16_t start_address, std::span<const uint16_t> values) {
488 PduBuffer pdu; // declared before every return so NRVO fires (all paths return the same object)
489 if (!register_block_in_range(LOG_STR("Write"), start_address, values.size(), MAX_NUM_OF_REGISTERS_TO_WRITE)) {
490 return pdu;
491 }
492 append_pdu_header(pdu, FunctionCode::WRITE_MULTIPLE_REGISTERS, start_address, values.size());
493 pdu.push_back(static_cast<uint8_t>(values.size() * 2)); // byte count
494 for (auto v : values) {
495 append_pdu_word(pdu, v);
496 }
497 return pdu;
498}
499
500PduBuffer create_read_write_multiple_registers_pdu(uint16_t read_start_address, uint16_t read_count,
501 uint16_t write_start_address,
502 std::span<const uint16_t> write_values) {
503 PduBuffer pdu;
504 if (!register_block_in_range(LOG_STR("Read"), read_start_address, read_count, MAX_NUM_OF_REGISTERS_TO_READ)) {
505 return pdu;
506 }
507 if (!register_block_in_range(LOG_STR("Write"), write_start_address, write_values.size(),
508 MAX_NUM_OF_REGISTERS_TO_WRITE_RW)) {
509 return pdu;
510 }
511 // fc + read start(2) + read qty(2) + write start(2) + write qty(2) + write byte count(1) + write values.
512 const auto write_count = static_cast<uint16_t>(write_values.size());
514 append_pdu_word(pdu, read_start_address);
515 append_pdu_word(pdu, read_count);
516 append_pdu_word(pdu, write_start_address);
517 append_pdu_word(pdu, write_count);
518 pdu.push_back(static_cast<uint8_t>(write_count * 2)); // byte count
519 for (auto v : write_values) {
520 append_pdu_word(pdu, v);
521 }
522 return pdu;
523}
524
525WriteSinglePdu create_write_single_register_pdu(uint16_t start_address, uint16_t value) {
526 WriteSinglePdu pdu;
527 append_pdu_header(pdu, FunctionCode::WRITE_SINGLE_REGISTER, start_address, value);
528 return pdu;
529}
530
532 WriteSinglePdu pdu;
533 append_pdu_header(pdu, FunctionCode::WRITE_SINGLE_COIL, address, value ? 0xFF00 : 0x0000);
534 return pdu;
535}
536
537// Shared core for the two coil-write overloads: validates, then builds into the caller's named
538// pdu (left empty on failure). Each overload's returns all name one local, so NRVO fires.
539static void build_write_coils_pdu(PduBuffer &pdu, uint16_t start_address, PackedBits bits) {
540 const uint16_t count = bits.size();
541 const std::span<const uint8_t> packed_bits = bits.bytes();
542 if (count == 0) {
543 ESP_LOGE(TAG, "No coils requested for write multiple coils, dropping request");
544 return;
545 }
546 if (count > MAX_NUM_OF_COILS_TO_WRITE) {
547 ESP_LOGE(TAG, "count %u exceeds maximum coils to write %u, dropping request", count, MAX_NUM_OF_COILS_TO_WRITE);
548 return;
549 }
550 if (!address_range_fits(start_address, count)) {
551 ESP_LOGE(TAG, "Write of %u coils at %u runs past the 16-bit address space, dropping request", count, start_address);
552 return;
553 }
554 const size_t byte_count = packed_bit_bytes(count);
555 if (packed_bits.size() < byte_count) {
556 ESP_LOGE(TAG, "packed_bits (%zu bytes) does not cover %u coils (%zu bytes), dropping request", packed_bits.size(),
557 count, byte_count);
558 return;
559 }
560 append_pdu_header(pdu, FunctionCode::WRITE_MULTIPLE_COILS, start_address, count);
561 pdu.push_back(static_cast<uint8_t>(byte_count));
562 for (size_t i = 0; i != byte_count; i++) {
563 pdu.push_back(packed_bits[i]);
564 }
565 mask_trailing_pad_bits(pdu, count);
566}
567
568PduBuffer create_write_coils_pdu(uint16_t start_address, PackedBits bits) {
569 PduBuffer pdu;
570 build_write_coils_pdu(pdu, start_address, bits);
571 return pdu;
572}
573
574// Shared by the two bool-container overloads: both index the same way, so the packing is written once.
575template<typename BoolContainer>
576static PduBuffer create_write_coils_pdu_from_bools(uint16_t start_address, const BoolContainer &values) {
577 PduBuffer pdu; // declared before every return so NRVO fires (all paths return the same object)
578 const size_t count = values.size();
579 // Bound before packing so the transient buffer below cannot overflow; the shared core validates the rest.
580 if (count > MAX_NUM_OF_COILS_TO_WRITE) {
581 ESP_LOGE(TAG, "values.size() %zu exceeds maximum coils to write %u, dropping request", count,
582 MAX_NUM_OF_COILS_TO_WRITE);
583 return pdu;
584 }
585 CoilPackBuffer packed;
586 pack_bits(packed, values);
587 build_write_coils_pdu(pdu, start_address, PackedBits(std::span<const uint8_t>(packed.data(), packed.size()), count));
588 return pdu;
589}
590
591PduBuffer create_write_coils_pdu(uint16_t start_address, std::span<const bool> values) {
592 return create_write_coils_pdu_from_bools(start_address, values);
593}
594
595PduBuffer create_write_coils_pdu(uint16_t start_address, const std::vector<bool> &values) {
596 return create_write_coils_pdu_from_bools(start_address, values);
597}
598} // namespace esphome::modbus::helpers
uint8_t address
Definition bl0906.h:4
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
void assign(InputIt first, InputIt last)
Definition helpers.h:275
Read-only view of Modbus-packed bits: bit 0 of byte 0 is the first bit (LSB first),...
std::span< const uint8_t > bytes() const
The underlying packed bytes: exactly ceil(size() / 8) bytes, even when the view was constructed over ...
uint16_t size() const
Number of bits in the view.
uint8_t second
bool address_range_fits(uint16_t start_address, size_t count)
PduBuffer create_write_coils_pdu(uint16_t start_address, PackedBits bits)
Create modbus write multiple coils command (function 0x0F) from bits packed as on the wire.
StaticVector< uint8_t, MAX_PDU_SIZE > PduBuffer
bool is_function_code_read_only(uint8_t function_code)
WriteSinglePdu create_write_single_coil_pdu(uint16_t address, bool value)
Create modbus write single coil command Function 0x05 Write Single Coil.
std::span< const uint8_t > data
void pack_bits(Out &out, const Bits &bits)
Append packed bytes (LSB first) for the given bits onto a growable byte container.
T get_data(const uint8_t *data, size_t buffer_offset)
Extract data from modbus response buffer.
ReadPdu create_read_pdu(FunctionCode function_code, uint16_t start_address, uint16_t number_of_entities)
Create a modbus read request PDU.
WriteSinglePdu create_write_single_register_pdu(uint16_t start_address, uint16_t value)
Create modbus write single register command Function 0x06 Write Single Register.
PduBuffer create_client_pdu(FunctionCode function_code, uint16_t start_address, uint16_t number_of_entities, const uint8_t *values, size_t values_len)
Create a modbus client pdu for reading/writing single/multiple coils/register/inputs.
uint16_t server_pdu_length(const uint8_t *frame, size_t size)
N mask_and_shift_by_rightbit(N data, uint32_t mask)
Extract bits from value and shift right according to the bitmask if the bitmask is 0x00F0 we want the...
bool is_server_pdu_standard(const uint8_t *pdu, size_t size)
void log_unsupported_value_type(SensorValueType value_type)
bool is_client_pdu_standard(const uint8_t *pdu, size_t size)
PduBuffer create_write_registers_pdu(uint16_t start_address, std::span< const uint16_t > values)
Create modbus write multiple registers command Function 0x10 Write Multiple Registers.
StaticVector< uint8_t, packed_bit_bytes(MAX_NUM_OF_COILS_TO_WRITE)> CoilPackBuffer
Scratch space for packing coils into wire layout: one bit per coil, sized for the spec maximum.
PduBuffer create_read_write_multiple_registers_pdu(uint16_t read_start_address, uint16_t read_count, uint16_t write_start_address, std::span< const uint16_t > write_values)
Create modbus read/write multiple registers command Function 0x17 Read/Write Multiple Registers Write...
std::optional< int64_t > registers_to_number(const uint16_t *registers, size_t count, SensorValueType sensor_value_type)
Reconstruct a number from register words (host byte order).
uint16_t client_pdu_length(const uint8_t *frame, size_t size)
bool is_function_code_exception(uint8_t function_code)
std::optional< int64_t > payload_to_number(const uint8_t *data, size_t size, SensorValueType sensor_value_type, uint8_t offset, uint32_t bitmask)
Convert a raw response payload to a number.
constexpr size_t packed_bit_bytes(size_t bits)
Bits pack 8 per data byte, rounded up to whole bytes.
static void uint32_t
void byteswap()