12static constexpr uint8_t MAX_REGISTERS_PER_VALUE = 4;
17static_assert(MAX_REGISTERS_PER_VALUE ==
sizeof(int64_t) /
sizeof(uint16_t),
18 "MAX_REGISTERS_PER_VALUE must match the register span of the widest encodable value");
21template<
typename F>
static auto visit_cpp_type(
SensorValueType value_type, F &&f) {
47 return visit_cpp_type(this->value_type, [
this](
auto tag) {
48 using T =
decltype(
tag);
50 optional<int64_t>
raw;
51 if (
value.has_value()) {
52 if constexpr (std::is_same_v<T, float>) {
55 raw =
static_cast<int64_t
>(*value);
63 return visit_cpp_type(this->value_type, [
this, number](
auto tag) {
64 using T =
decltype(
tag);
66 if constexpr (std::is_same_v<T, float>) {
69 value =
static_cast<T
>(number);
76 visit_cpp_type(this->value_type, [&](
auto tag) {
77 using T =
decltype(
tag);
78 if constexpr (std::is_same_v<T, float>) {
79 buf_append_printf(buf, buf_size, 0,
"%.1f", bit_cast<float>(
static_cast<uint32_t>(
value)));
80 }
else if constexpr (std::is_signed_v<T>) {
81 buf_append_printf(buf, buf_size, 0,
"%" PRId64,
value);
83 buf_append_printf(buf, buf_size, 0,
"%" PRIu64,
static_cast<uint64_t
>(
value));
90 for (
auto *server_register : this->server_registers_) {
91 if (
address >= server_register->address &&
92 address <
static_cast<uint32_t>(server_register->address) + server_register->register_count) {
93 return server_register;
102 "Received read holding/input registers for device 0x%X. Start address: 0x%X. Number of registers: 0x%X.",
103 this->
address_, start_address, number_of_registers);
108 if (this->server_registers_.empty() && !this->server_courtesy_response_.enabled)
111 const uint32_t end_address =
static_cast<uint32_t>(start_address) + number_of_registers;
112 uint32_t current_address = start_address;
113 while (current_address < end_address) {
116 if (server_register ==
nullptr) {
120 ESP_LOGV(TAG,
"No register at 0x%04X; returning courtesy default %" PRIu16
".",
123 current_address += 1;
126 ESP_LOGW(TAG,
"No register at 0x%04X and courtesy default not allowed. Sending exception response.",
127 static_cast<uint16_t
>(current_address));
133 ESP_LOGW(TAG,
"Register at 0x%04X is not readable. Sending exception response.", server_register->
address);
140 const uint16_t value_offset =
static_cast<uint16_t
>(current_address - server_register->
address);
141 const uint16_t words_available =
static_cast<uint16_t
>(server_register->
register_count - value_offset);
142 const uint16_t words_wanted =
static_cast<uint16_t
>(end_address - current_address);
143 const uint16_t take = words_available < words_wanted ? words_available : words_wanted;
144 const bool clipped = value_offset != 0 || take != server_register->
register_count;
147 "Read clips the multi-register value at 0x%04X, which does not allow partial reads. "
148 "Sending exception response.",
153 const optional<int64_t> read_value = server_register->
read();
154 if (!read_value.has_value()) {
155 ESP_LOGW(TAG,
"Register read at 0x%04X declined to produce a value. Sending exception response.",
159 const int64_t
value = *read_value;
161 ESP_LOGV(TAG,
"Matched register. Address: 0x%02X. Value type: %zu. Register count: %u. Value: %s.",
169 if (value_offset + take > value_words.
size()) {
171 ESP_LOGE(TAG,
"Register at 0x%04X did not encode to %u registers", server_register->
address,
175 for (uint16_t i = 0; i < take; i++) {
176 registers.
push_back(value_words[value_offset + i]);
178 current_address += take;
187 ESP_LOGV(TAG,
"Received write registers for device 0x%X. Start address: 0x%X. Number of registers: 0x%zX.",
192 if (this->server_registers_.empty())
195 auto for_each_register =
196 [
this, start_address,
197 ®isters](
const std::function<bool(
ServerRegister *, uint16_t register_offset)> &callback) ->
bool {
198 uint16_t register_offset = 0;
199 for (
uint32_t current_address = start_address; current_address < start_address + registers.
size();) {
201 for (
auto *server_register : this->server_registers_) {
202 if (server_register->address == current_address) {
203 ok = callback(server_register, register_offset);
204 current_address += server_register->register_count;
205 register_offset += server_register->register_count;
222 if (!for_each_register([&precheck, ®isters](
ServerRegister *server_register, uint16_t register_offset) ->
bool {
226 if (!registers_to_number(registers.
data() + register_offset, registers.
size() - register_offset,
236 ESP_LOGV(TAG,
"Write request rejected before applying any register.");
242 if (!for_each_register([®isters](
ServerRegister *server_register, uint16_t register_offset) {
243 int64_t number = registers_to_number(registers.
data() + register_offset, registers.
size() - register_offset,
246 return server_register->
write(number);
248 ESP_LOGW(TAG,
"A register write callback failed mid-sequence; earlier writes were already applied.");
258 if (server_bit->address ==
address) {
266 ESP_LOGV(TAG,
"Received read coils/discrete inputs for device 0x%X. Start address: 0x%X. Count: 0x%X.",
274 for (uint16_t i = 0; i < bits.
size(); i++) {
275 const uint16_t
address =
static_cast<uint16_t
>(start_address + i);
277 if (server_bit ==
nullptr || !server_bit->
read_lambda) {
278 ESP_LOGW(TAG,
"No readable bit at 0x%04X. Sending exception response.",
address);
282 if (!
value.has_value()) {
283 ESP_LOGW(TAG,
"Bit read at 0x%04X declined to produce a value. Sending exception response.",
address);
292 ESP_LOGV(TAG,
"Received write coils for device 0x%X. Start address: 0x%X. Count: 0x%X.", this->
address_,
293 start_address, bits.
size());
302 for (uint16_t i = 0; i < bits.
size(); i++) {
303 const uint16_t
address =
static_cast<uint16_t
>(start_address + i);
305 if (server_bit ==
nullptr || !server_bit->
write_lambda) {
308 ESP_LOGV(TAG,
"No writable bit at 0x%04X; write request rejected before applying any bit.",
address);
318 for (uint16_t i = 0; i < bits.
size(); i++) {
319 const uint16_t
address =
static_cast<uint16_t
>(start_address + i);
321 if (server_bit ==
nullptr || !server_bit->
write_lambda) {
322 ESP_LOGE(TAG,
"Bit at 0x%04X unresolved between pre-flight and commit; aborting write.",
address);
326 ESP_LOGW(TAG,
"Bit write callback failed at 0x%04X mid-sequence; earlier writes were already applied.",
address);
337 " Server Courtesy Response:\n"
339 " Register Last Address: 0x%02X\n"
340 " Register Value: %" PRIu16,
345#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
346 ESP_LOGCONFIG(TAG,
"server registers");
347 for (
auto &r : this->server_registers_) {
348 ESP_LOGCONFIG(TAG,
" Address=0x%02X value_type=%u register_count=%u", r->address,
349 static_cast<uint8_t
>(r->value_type), r->register_count);
351 ESP_LOGCONFIG(TAG,
"server bits");
353 ESP_LOGCONFIG(TAG,
" Address=0x%04X readable=%s writable=%s", b->address,
354 b->read_lambda ? LOG_STR_LITERAL(
"true") : LOG_STR_LITERAL(
"false"),
355 b->write_lambda ? LOG_STR_LITERAL(
"true") : LOG_STR_LITERAL(
"false"));
Minimal static vector - saves memory by avoiding std::vector overhead.
void push_back(const T &value)
Mutable counterpart of PackedBits: set() writes bits in place (deliberately no proxy operator[]=).
void set(size_t bit, bool value)
Set or clear the given bit.
Read-only view of Modbus-packed bits: bit 0 of byte 0 is the first bit (LSB first),...
uint16_t size() const
Number of bits in the view.
void dump_config() override
modbus::ResponseStatus on_write_registers(uint16_t start_address, const modbus::RegisterValues ®isters) final
called when a modbus request (function code 0x06 or 0x10) was parsed without errors
modbus::ResponseStatus on_read_bits(uint16_t start_address, modbus::MutablePackedBits bits) final
called when a modbus request (function code 0x01 or 0x02) was parsed without errors; both are served ...
ServerRegister * find_containing_register_(uint32_t address) const
Find the registered value whose register span contains address, or nullptr if none does.
MODBUS_SERVER_BIT_COUNT modbus::ResponseStatus on_read_registers(uint16_t start_address, uint16_t number_of_registers, modbus::RegisterValues ®isters) final
called when a modbus request (function code 0x03 or 0x04) was parsed without errors
ServerBit * find_bit_(uint16_t address) const
Find the registered bit at address, or nullptr if none is.
modbus::ResponseStatus on_write_coils(uint16_t start_address, modbus::PackedBits bits) final
called when a modbus request (function code 0x05 or 0x0F) was parsed without errors
ServerCourtesyResponse server_courtesy_response_
Server courtesy response.
A single bit in the server's coil/discrete-input table.
bool(*)(uint16_t address, T value) WriteFn
SensorValueType value_type
const char * format_value(int64_t value, char *buf, size_t buf_size) const
optional< T >(*)(uint16_t address) ReadFn
static constexpr size_t FORMAT_VALUE_BUF_SIZE
bool write(int64_t number) const
Converts a raw number (floats as their IEEE 754 bits) to the register's type and calls the write lamb...
optional< int64_t > read() const
Calls the read lambda and returns its value as a raw number (floats as their IEEE 754 bits).
void number_to_payload(Container &data, int64_t value, SensorValueType value_type)
Append the Modbus register words for value to data.
decltype(registers_to_value< VALUE_TYPE >(static_cast< const uint16_t * >(nullptr))) RegisterValueType
The type registers_to_value() yields for a given value type.
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).
ESPHOME_LOG_TAG(TAG, "modbus_server")
std::optional< ExceptionCode > ResponseStatus
ESPHOME_ALWAYS_INLINE To bit_cast(const From &src)
Convert data between types, without aliasing issues or undefined behaviour.
uint16_t register_last_address