ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
modbus_server.cpp
Go to the documentation of this file.
1#include "modbus_server.h"
3#include "esphome/core/log.h"
4
8
9ESPHOME_LOG_TAG(TAG, "modbus_server");
10
11// The widest Modbus value type (QWORD) spans four registers.
12static constexpr uint8_t MAX_REGISTERS_PER_VALUE = 4;
13// number_to_payload() encodes the 64-bit value returned by read() into 16-bit registers, so the
14// widest possible value spans exactly sizeof(int64_t) / sizeof(uint16_t) registers. Tie the bound to that
15// source so a future wider value type -- which would require widening the encoded value itself -- can't
16// silently overflow the value_words buffer below (StaticVector::push_back drops words past capacity).
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");
19
20// Calls f with a value of the C++ type that holds value_type, as registers_to_value() decodes it.
21template<typename F> static auto visit_cpp_type(SensorValueType value_type, F &&f) {
22 switch (value_type) {
41 default: // U_WORD and U_WORD_S
43 }
44}
45
46optional<int64_t> ServerRegister::read() const {
47 return visit_cpp_type(this->value_type, [this](auto tag) {
48 using T = decltype(tag);
49 const optional<T> value = reinterpret_cast<ReadFn<T>>(this->read_fn_)(this->address);
50 optional<int64_t> raw;
51 if (value.has_value()) {
52 if constexpr (std::is_same_v<T, float>) {
54 } else {
55 raw = static_cast<int64_t>(*value);
56 }
57 }
58 return raw;
59 });
60}
61
62bool ServerRegister::write(int64_t number) const {
63 return visit_cpp_type(this->value_type, [this, number](auto tag) {
64 using T = decltype(tag);
65 T value;
66 if constexpr (std::is_same_v<T, float>) {
67 value = bit_cast<float>(static_cast<uint32_t>(number));
68 } else {
69 value = static_cast<T>(number);
70 }
71 return reinterpret_cast<WriteFn<T>>(this->write_fn_)(this->address, value);
72 });
73}
74
75const char *ServerRegister::format_value(int64_t value, char *buf, size_t buf_size) const {
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);
82 } else {
83 buf_append_printf(buf, buf_size, 0, "%" PRIu64, static_cast<uint64_t>(value));
84 }
85 });
86 return buf;
87}
88
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;
94 }
95 }
96 return nullptr;
97}
98
99modbus::ResponseStatus ModbusServer::on_read_registers(uint16_t start_address, uint16_t number_of_registers,
100 modbus::RegisterValues &registers) {
101 ESP_LOGV(TAG,
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);
104
105 // No registers configured (e.g. a bits-only server) and no courtesy default: this device does not implement
106 // the register-read function, so answer ILLEGAL_FUNCTION. A populated map with a wrong address answers
107 // ILLEGAL_DATA_ADDRESS below.
108 if (this->server_registers_.empty() && !this->server_courtesy_response_.enabled)
110
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) {
114 ServerRegister *server_register = this->find_containing_register_(current_address);
115
116 if (server_register == nullptr) {
117 // Unregistered address: optionally answer with the courtesy default, otherwise reject.
119 current_address <= this->server_courtesy_response_.register_last_address) {
120 ESP_LOGV(TAG, "No register at 0x%04X; returning courtesy default %" PRIu16 ".",
121 static_cast<uint16_t>(current_address), this->server_courtesy_response_.register_value);
123 current_address += 1; // the courtesy default is always a single register
124 continue;
125 }
126 ESP_LOGW(TAG, "No register at 0x%04X and courtesy default not allowed. Sending exception response.",
127 static_cast<uint16_t>(current_address));
129 }
130
131 if (!server_register->is_readable()) {
132 // Registered but not readable (write-only); don't mask it with the courtesy default.
133 ESP_LOGW(TAG, "Register at 0x%04X is not readable. Sending exception response.", server_register->address);
135 }
136
137 // A multi-register value is normally atomic: the request must start at its first register and cover all of
138 // it. A value may opt in to partial reads, in which case the request may start inside it or stop short of
139 // its end and we return only the covered words.
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;
145 if (clipped && !server_register->allow_partial_read) {
146 ESP_LOGW(TAG,
147 "Read clips the multi-register value at 0x%04X, which does not allow partial reads. "
148 "Sending exception response.",
149 server_register->address);
151 }
152
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.",
156 server_register->address);
158 }
159 const int64_t value = *read_value;
161 ESP_LOGV(TAG, "Matched register. Address: 0x%02X. Value type: %zu. Register count: %u. Value: %s.",
162 server_register->address, static_cast<size_t>(server_register->value_type),
163 server_register->register_count, server_register->format_value(value, value_buf, sizeof(value_buf)));
164
165 // Encode the whole value once (wire word order) and emit only the covered words. Slicing the encoded words
166 // handles the reversed value types for free, since number_to_payload already emits in wire order.
168 modbus::helpers::number_to_payload(value_words, value, server_register->value_type);
169 if (value_offset + take > value_words.size()) {
170 // The value encoded to fewer words than its register span (e.g. a RAW register); treat as a device fault.
171 ESP_LOGE(TAG, "Register at 0x%04X did not encode to %u registers", server_register->address,
172 server_register->register_count);
174 }
175 for (uint16_t i = 0; i < take; i++) {
176 registers.push_back(value_words[value_offset + i]);
177 }
178 current_address += take;
179 }
180
181 return {};
182}
183
185 const modbus::RegisterValues &registers) {
186 // registers holds the values to write in host byte order; its size is the register count.
187 ESP_LOGV(TAG, "Received write registers for device 0x%X. Start address: 0x%X. Number of registers: 0x%zX.",
188 this->address_, start_address, registers.size());
189
190 // No registers configured (e.g. a bits-only server): this device does not implement the register-write
191 // function, so answer ILLEGAL_FUNCTION rather than ILLEGAL_DATA_ADDRESS.
192 if (this->server_registers_.empty())
194
195 auto for_each_register =
196 [this, start_address,
197 &registers](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();) {
200 bool ok = false;
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;
206 break;
207 }
208 }
209
210 if (!ok) {
211 return false;
212 }
213 }
214 return true;
215 };
216
217 // Pre-flight: every targeted register must be writable AND have its full value present in the request,
218 // so we never apply a partial write before discovering a problem. The commit pass below re-runs
219 // registers_to_number rather than caching the decoded values: using the same function for the check and
220 // the write keeps a single source of truth for the decode bound, independent of how register_count was set.
221 ExceptionCode precheck = ExceptionCode::ILLEGAL_DATA_ADDRESS; // unmatched or unwritable register
222 if (!for_each_register([&precheck, &registers](ServerRegister *server_register, uint16_t register_offset) -> bool {
223 if (!server_register->is_writable()) {
224 return false; // unwritable -> ILLEGAL_DATA_ADDRESS
225 }
226 if (!registers_to_number(registers.data() + register_offset, registers.size() - register_offset,
227 server_register->value_type)
228 .has_value()) {
229 precheck = ExceptionCode::ILLEGAL_DATA_VALUE; // request doesn't supply the full value
230 return false;
231 }
232 return true;
233 })) {
234 // Only VERBOSE: one handler serves both addressed and broadcast writes, and rejecting a broadcast for
235 // registers this device does not map is routine. The hub logs the outcome with the context it has.
236 ESP_LOGV(TAG, "Write request rejected before applying any register.");
237 return precheck;
238 }
239
240 // Commit: every value is known writable and decodable, so the only failure now is a user write callback
241 // rejecting the value at runtime -- which cannot be rolled back.
242 if (!for_each_register([&registers](ServerRegister *server_register, uint16_t register_offset) {
243 int64_t number = registers_to_number(registers.data() + register_offset, registers.size() - register_offset,
244 server_register->value_type)
245 .value_or(0);
246 return server_register->write(number);
247 })) {
248 ESP_LOGW(TAG, "A register write callback failed mid-sequence; earlier writes were already applied.");
250 }
251
252 // Success: the caller builds the write response (an echo of the request header).
253 return {};
254}
255
257 for (auto *server_bit : this->server_bits_) {
258 if (server_bit->address == address) {
259 return server_bit;
260 }
261 }
262 return nullptr;
263}
264
266 ESP_LOGV(TAG, "Received read coils/discrete inputs for device 0x%X. Start address: 0x%X. Count: 0x%X.",
267 this->address_, start_address, bits.size());
268
269 // No bits configured: this device does not implement the coil/discrete-input function, so answer
270 // ILLEGAL_FUNCTION. A populated table with a wrong address answers ILLEGAL_DATA_ADDRESS below.
271 if (this->server_bits_.empty())
273
274 for (uint16_t i = 0; i < bits.size(); i++) {
275 const uint16_t address = static_cast<uint16_t>(start_address + i); // range pre-checked by the hub
276 ServerBit *server_bit = this->find_bit_(address);
277 if (server_bit == nullptr || !server_bit->read_lambda) {
278 ESP_LOGW(TAG, "No readable bit at 0x%04X. Sending exception response.", address);
280 }
281 const optional<bool> value = server_bit->read_lambda(address);
282 if (!value.has_value()) {
283 ESP_LOGW(TAG, "Bit read at 0x%04X declined to produce a value. Sending exception response.", address);
285 }
286 bits.set(i, *value);
287 }
288 return {};
289}
290
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());
294
295 // No bits configured: this device does not implement the coil function, so answer ILLEGAL_FUNCTION rather
296 // than ILLEGAL_DATA_ADDRESS.
297 if (this->server_bits_.empty())
299
300 // Pre-flight: every targeted bit must exist and be writable, so we never apply a partial write
301 // before discovering a problem (mirrors the register write's two passes).
302 for (uint16_t i = 0; i < bits.size(); i++) {
303 const uint16_t address = static_cast<uint16_t>(start_address + i);
304 ServerBit *server_bit = this->find_bit_(address);
305 if (server_bit == nullptr || !server_bit->write_lambda) {
306 // Only VERBOSE: one handler serves both addressed and broadcast writes, and rejecting a broadcast for
307 // bits this device does not map is routine. The hub logs the outcome with the context it has.
308 ESP_LOGV(TAG, "No writable bit at 0x%04X; write request rejected before applying any bit.", address);
310 }
311 }
312
313 // Commit: the pre-flight above proved every address resolves to a writable bit. Re-resolve here rather
314 // than caching up to MAX_NUM_OF_COILS_TO_WRITE pointers (a per-request heap allocation), matching the
315 // register write's two-pass shape -- but guard the pointer anyway, so a future change to the pre-flight
316 // can never turn this into a silent null dereference. The only expected failure is a write callback
317 // rejecting the value at runtime, which cannot be rolled back.
318 for (uint16_t i = 0; i < bits.size(); i++) {
319 const uint16_t address = static_cast<uint16_t>(start_address + i);
320 ServerBit *server_bit = this->find_bit_(address);
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);
324 }
325 if (!server_bit->write_lambda(address, bits[i])) {
326 ESP_LOGW(TAG, "Bit write callback failed at 0x%04X mid-sequence; earlier writes were already applied.", address);
328 }
329 }
330 return {};
331}
332
334 ESP_LOGCONFIG(TAG,
335 "ModbusServer:\n"
336 " Address: 0x%02X\n"
337 " Server Courtesy Response:\n"
338 " Enabled: %s\n"
339 " Register Last Address: 0x%02X\n"
340 " Register Value: %" PRIu16,
341 this->address_,
342 this->server_courtesy_response_.enabled ? LOG_STR_LITERAL("true") : LOG_STR_LITERAL("false"),
343 this->server_courtesy_response_.register_last_address, this->server_courtesy_response_.register_value);
344
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);
350 }
351 ESP_LOGCONFIG(TAG, "server bits");
352 for (auto &b : this->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"));
356 }
357#endif
358}
359
360} // namespace esphome::modbus_server
uint8_t raw[35]
Definition bl0939.h:0
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:335
size_t size() const
Definition helpers.h:404
void push_back(const T &value)
Definition helpers.h:374
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.
modbus::ResponseStatus on_write_registers(uint16_t start_address, const modbus::RegisterValues &registers) 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 &registers) 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
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
Definition modbus.h:327
uint32_t value
Definition hal.cpp:59
void const char * tag
Definition log.h:110
ESPHOME_ALWAYS_INLINE To bit_cast(const From &src)
Convert data between types, without aliasing issues or undefined behaviour.
Definition helpers.h:104
static void uint32_t