8static const char *
const TAG =
"modbus_helpers";
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);
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;
25 if (
size < MIN_PDU_SIZE)
36 return 2 + (
size > 1 ? std::min(frame[1], uint8_t(MAX_NUM_OF_REGISTERS_TO_READ * 2)) : 0);
46 return 2 + (
size > 1 ? std::min(frame[1], uint8_t(MAX_PDU_SIZE - 2)) : 0);
51 return 2 + (
size > 1 ? std::min(frame[1], uint8_t(MAX_NUM_OF_REGISTERS_TO_READ * 2)) : 0);
61 if (
size < MIN_PDU_SIZE)
74 return 6 + (
size > 5 ? std::min(frame[5], uint8_t(
packed_bit_bytes(MAX_NUM_OF_COILS_TO_WRITE))) : 0);
77 return 6 + (
size > 5 ? std::min(frame[5], uint8_t(MAX_NUM_OF_REGISTERS_TO_WRITE * 2)) : 0);
82 return 2 + (
size > 1 ? std::min(frame[1], uint8_t(MAX_PDU_SIZE - 2)) : 0);
88 return 10 + (
size > 9 ? std::min(frame[9], uint8_t(MAX_NUM_OF_REGISTERS_TO_WRITE_RW * 2)) : 0);
101 const auto function_code =
static_cast<FunctionCode>(pdu[0]);
102 switch (function_code) {
106 return pdu[1] != 0 && pdu[1] <= uint8_t(
packed_bit_bytes(MAX_NUM_OF_COILS_TO_READ));
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);
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);
127 return is_canonical_coil_value(pdu[3], pdu[4]);
137 const auto function_code =
static_cast<FunctionCode>(pdu[0]);
138 switch (function_code) {
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);
155 const uint16_t max_quantity = bits ? MAX_NUM_OF_COILS_TO_WRITE : MAX_NUM_OF_REGISTERS_TO_WRITE;
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;
162 return pdu[1] <= MAX_PDU_SIZE - 2;
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;
174 return is_canonical_coil_value(pdu[3], pdu[4]);
180static size_t required_payload_size(
SensorValueType sensor_value_type) {
181 switch (sensor_value_type) {
206 ESP_LOGE(TAG,
"Invalid data type for modbus number to payload conversion: %d",
static_cast<uint16_t
>(value_type));
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);
221 const size_t required_size = required_payload_size(sensor_value_type);
222 if (required_size == 0) {
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);
232 switch (sensor_value_type) {
249 value =
static_cast<uint32_t>(value & 0xFFFF) << 16 | (value & 0xFFFF0000) >> 16;
267 uint32_t sign_bit = (value & 0x8000) << 16;
269 static_cast<int32_t
>(((value & 0x7FFF) << 16 | (value & 0xFFFF0000) >> 16) | sign_bit), bitmask);
280 value = (tmp << 48) | (tmp >> 48) | ((tmp & 0xFFFF0000) << 16) | ((tmp >> 16) & 0xFFFF0000);
290 const size_t required_size = required_payload_size(sensor_value_type);
291 if (required_size == 0) {
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);
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);
308 return payload_to_number(bytes, required_size, sensor_value_type, 0, 0xFFFFFFFF);
322 pdu.
push_back(
static_cast<uint8_t
>(function_code));
323 append_pdu_word(pdu, first);
324 append_pdu_word(pdu,
second);
331static void mask_trailing_pad_bits(std::span<uint8_t>
data, uint16_t bit_count) {
332 if (
data.empty() || bit_count % 8 == 0)
334 data.back() &=
static_cast<uint8_t
>((1 << (bit_count % 8)) - 1);
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));
344 ESP_LOGE(TAG,
"Read of %u entities at %u runs past the 16-bit address space, dropping request", number_of_entities,
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));
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));
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));
373 ESP_LOGE(TAG,
"Unsupported function code %02X for read PDU creation",
static_cast<uint8_t
>(function_code));
377 append_pdu_header(pdu, function_code, start_address, number_of_entities);
382 const uint8_t *values,
size_t values_len) {
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));
391 auto read_pdu =
create_read_pdu(function_code, start_address, number_of_entities);
392 pdu.
assign(read_pdu.begin(), read_pdu.end());
397 const bool is_single =
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));
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));
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));
418 const uint16_t max_entities =
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));
426 ESP_LOGE(TAG,
"Write of %u entities at %u runs past the 16-bit address space, dropping request", number_of_entities,
433 if (values_len < 2) {
434 ESP_LOGE(TAG,
"values_len %zu too small for write-single command (need 2), dropping request", values_len);
440 ESP_LOGE(TAG,
"Invalid single-coil value %02X%02X (must be FF00 or 0000), dropping request", values[0],
444 append_pdu_header(pdu, function_code, start_address, uint16_t((values[0] << 8) | values[1]));
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));
459 append_pdu_header(pdu, function_code, start_address, number_of_entities);
461 for (
size_t i = 0; i < values_len; i++)
464 mask_trailing_pad_bits(pdu, number_of_entities);
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);
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);
489 if (!register_block_in_range(LOG_STR(
"Write"), start_address, values.size(), MAX_NUM_OF_REGISTERS_TO_WRITE)) {
493 pdu.
push_back(
static_cast<uint8_t
>(values.size() * 2));
494 for (
auto v : values) {
495 append_pdu_word(pdu, v);
501 uint16_t write_start_address,
502 std::span<const uint16_t> write_values) {
504 if (!register_block_in_range(LOG_STR(
"Read"), read_start_address, read_count, MAX_NUM_OF_REGISTERS_TO_READ)) {
507 if (!register_block_in_range(LOG_STR(
"Write"), write_start_address, write_values.size(),
508 MAX_NUM_OF_REGISTERS_TO_WRITE_RW)) {
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));
519 for (
auto v : write_values) {
520 append_pdu_word(pdu, v);
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();
543 ESP_LOGE(TAG,
"No coils requested for write multiple coils, dropping request");
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);
551 ESP_LOGE(TAG,
"Write of %u coils at %u runs past the 16-bit address space, dropping request", count, start_address);
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(),
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]);
565 mask_trailing_pad_bits(pdu, count);
570 build_write_coils_pdu(pdu, start_address, bits);
575template<
typename BoolContainer>
576static PduBuffer create_write_coils_pdu_from_bools(uint16_t start_address,
const BoolContainer &values) {
578 const size_t count = values.
size();
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);
587 build_write_coils_pdu(pdu, start_address, PackedBits(std::span<const uint8_t>(packed.data(), packed.size()), count));
592 return create_write_coils_pdu_from_bools(start_address, values);
596 return create_write_coils_pdu_from_bools(start_address, values);
Minimal static vector - saves memory by avoiding std::vector overhead.
void push_back(const T &value)
void assign(InputIt first, InputIt last)
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.
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.
@ WRITE_MULTIPLE_REGISTERS
@ READ_WRITE_MULTIPLE_REGISTERS
constexpr size_t packed_bit_bytes(size_t bits)
Bits pack 8 per data byte, rounded up to whole bytes.