ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
modbus_client.h
Go to the documentation of this file.
1#pragma once
2
6
7#include <span>
8#include <vector>
9
11
18template<typename... Ts> class ClientActionBase : public Action<Ts...>, public modbus::ModbusClientDevice {
19 public:
20 TEMPLATABLE_VALUE(uint8_t, target_address) // the modbus device address
21
22 Trigger<uint8_t, std::span<const uint8_t>> *get_sent_trigger() { return &this->sent_trigger_; }
28
32 using retry_func_t = bool (*)(uint8_t, std::span<const uint8_t>);
33 void set_retry(retry_func_t f) { this->retry_func_ = f; }
34
37 void on_sent(uint8_t address, std::span<const uint8_t> request_pdu) override {
38 this->sent_trigger_.trigger(address, request_pdu);
39 }
45 void on_not_sent(uint8_t address, std::span<const uint8_t> request_pdu) override {
46 this->not_sent_trigger_.trigger(address, request_pdu);
47 }
51 void on_error(uint8_t address, std::span<const uint8_t> request_pdu, modbus::ExceptionCode exception_code) override {
52 this->error_trigger_.trigger(address, request_pdu, exception_code);
53 }
57 bool on_no_response(uint8_t address, std::span<const uint8_t> request_pdu) override {
58 this->no_response_trigger_.trigger(address, request_pdu);
59 if (this->retry_func_ != nullptr)
60 return this->retry_func_(address, request_pdu);
61 return false;
62 }
65 void play_complex(const Ts &...x) override {
66 this->set_address(this->target_address_.value(x...));
68 }
69
70 protected:
77 void send_or_resolve_(std::span<const uint8_t> pdu, modbus::CommandOptions options = {}) {
78 if (!this->queue_pdu(pdu, options))
79 this->on_not_sent(this->address_, pdu);
80 }
81
87};
88
95template<typename... Ts> class ReadCommandOptions {
96 public:
97 // Poll: re-queue after each success until downgraded (replay with false) or failed. The hub strips
98 // it for mutating function codes at the door (see modbus::CommandOptions).
99 TEMPLATABLE_VALUE(bool, continuous)
100 TEMPLATABLE_VALUE(bool, allow_broadcast_read)
101
102 protected:
105 return {.continuous = this->continuous_.value(x...),
106 .allow_broadcast_read = this->allow_broadcast_read_.value(x...)};
107 }
108};
109
111template<typename... Ts> class WriteCommandOptions {
112 public:
113 TEMPLATABLE_VALUE(bool, expect_broadcast_write_response)
114
115 protected:
117 void apply_write_command_options_(modbus::CommandOptions &options, const Ts &...x) const {
118 options.expect_broadcast_write_response = this->expect_broadcast_write_response_.value(x...);
119 }
120 modbus::CommandOptions write_command_options_(const Ts &...x) const {
122 this->apply_write_command_options_(options, x...);
123 return options;
124 }
125};
126
135template<typename... Ts>
137 public ReadCommandOptions<Ts...>,
138 public WriteCommandOptions<Ts...> {
139 public:
141
142 Trigger<uint8_t, std::span<const uint8_t>, std::span<const uint8_t>> *get_response_trigger() {
143 return &this->response_trigger_;
144 }
145
146 void play(const Ts &...x) override {
148 this->apply_write_command_options_(options, x...);
149 this->send_or_resolve_(this->pdu_.value(x...), options);
150 }
151
152 void on_response(uint8_t address, std::span<const uint8_t> request_pdu,
153 std::span<const uint8_t> response_pdu) override {
154 this->response_trigger_.trigger(address, request_pdu, response_pdu);
155 }
156
157 protected:
159};
160
171template<typename... Ts> class TypedClientActionBase : public ClientActionBase<Ts...> {
172 public:
174 return &this->custom_response_trigger_;
175 }
179
180 void on_custom_response(std::span<const uint8_t> request_pdu, std::span<const uint8_t> response_pdu,
181 modbus::ResponseStatus status) override {
182 if (!this->custom_response_handled_) {
183 modbus::ModbusClientDevice::on_custom_response(request_pdu, response_pdu, status);
184 return;
185 }
186 this->custom_response_trigger_.trigger(request_pdu, response_pdu);
187 }
188
189 protected:
192};
193
196template<typename... Ts>
198 public:
199 explicit ReadRegistersAction(bool holding) : holding_(holding) {}
201 TEMPLATABLE_VALUE(uint16_t, count)
202
203 Trigger<std::span<const uint16_t>> *get_response_trigger() { return &this->response_trigger_; }
204
205 void play(const Ts &...x) override {
206 const auto function_code =
208 this->send_or_resolve_(
209 modbus::helpers::create_read_pdu(function_code, this->start_address_.value(x...), this->count_.value(x...)),
210 this->command_options_(x...));
211 }
212 void on_read_registers(modbus::EntityType entity_type, uint16_t start_address, std::span<const uint16_t> registers,
213 modbus::ResponseStatus status) override {
215 this->response_trigger_.trigger(registers);
216 }
217
218 protected:
221};
222
225template<typename... Ts> class ReadBitsAction : public TypedClientActionBase<Ts...>, public ReadCommandOptions<Ts...> {
226 public:
227 explicit ReadBitsAction(bool coils) : coils_(coils) {}
229 TEMPLATABLE_VALUE(uint16_t, count)
230
231 Trigger<modbus::PackedBits> *get_response_trigger() { return &this->response_trigger_; }
232
233 void play(const Ts &...x) override {
234 const auto function_code =
236 this->send_or_resolve_(
237 modbus::helpers::create_read_pdu(function_code, this->start_address_.value(x...), this->count_.value(x...)),
238 this->command_options_(x...));
239 }
241 modbus::ResponseStatus status) override {
243 this->response_trigger_.trigger(bits);
244 }
245
246 protected:
248 bool coils_;
249};
250
253template<typename... Ts>
255 public:
257 TEMPLATABLE_VALUE(uint16_t, value)
258
260
261 void play(const Ts &...x) override {
262 this->send_or_resolve_(
263 modbus::helpers::create_write_single_register_pdu(this->start_address_.value(x...), this->value_.value(x...)),
264 this->write_command_options_(x...));
265 }
266 void on_write_single_register(uint16_t address, uint16_t value, modbus::ResponseStatus status) override {
269 }
270
271 protected:
273};
274
277template<typename... Ts>
279 public:
282
284
285 void play(const Ts &...x) override {
286 this->send_or_resolve_(
287 modbus::helpers::create_write_single_coil_pdu(this->start_address_.value(x...), this->value_.value(x...)),
288 this->write_command_options_(x...));
289 }
290 void on_write_single_coil(uint16_t address, bool value, modbus::ResponseStatus status) override {
293 }
294
295 protected:
297};
298
303template<typename... Ts>
305 public:
307
308
309 void set_values_static(const uint16_t *values, size_t len) {
310 this->values_.data = values;
311 this->len_ = static_cast<ssize_t>(len);
312 }
315 void set_values_template(std::vector<uint16_t> (*func)(Ts...)) {
316 this->values_.func = func;
317 this->len_ = -1; // sentinel: template mode
318 }
319
321
322 void play(const Ts &...x) override {
323 const uint16_t start = this->start_address_.value(x...);
324 // An empty or over-long set rejects into an empty PDU inside the builder, which logs the reason;
325 // the empty PDU then resolves via on_not_sent like any refused send.
326 if (this->len_ >= 0) {
328 start, std::span<const uint16_t>(this->values_.data, static_cast<size_t>(this->len_))),
329 this->write_command_options_(x...));
330 return;
331 }
332 const std::vector<uint16_t> values = this->values_.func(x...);
333 this->send_or_resolve_(modbus::helpers::create_write_registers_pdu(start, std::span<const uint16_t>(values)),
334 this->write_command_options_(x...));
335 }
336 void on_write_multiple_registers(uint16_t start_address, std::span<const uint16_t> registers,
337 modbus::ResponseStatus status) override {
340 }
341
342 protected:
344 ssize_t len_{-1}; // -1 = template mode, >= 0 = static mode with this many registers
345 union Values {
346 std::vector<uint16_t> (*func)(Ts...);
347 const uint16_t *data;
349};
350
355template<typename... Ts>
357 public:
359
360
361 void set_values_static(const uint8_t *packed, size_t count) {
362 this->values_.packed = packed;
363 this->count_ = static_cast<ssize_t>(count);
364 }
366 void set_values_template(std::vector<bool> (*func)(Ts...)) {
367 this->values_.func = func;
368 this->count_ = -1; // sentinel: template mode
369 }
370
372
373 void play(const Ts &...x) override {
374 const uint16_t start = this->start_address_.value(x...);
375 if (this->count_ >= 0) {
376 const auto count = static_cast<uint16_t>(this->count_);
377 this->send_or_resolve_(
379 start, modbus::PackedBits(std::span<const uint8_t>(this->values_.packed, modbus::packed_bit_bytes(count)),
380 count)),
381 this->write_command_options_(x...));
382 return;
383 }
384 // The builder packs and bound-checks; an over-long set is rejected and logged there.
386 this->write_command_options_(x...));
387 }
393
394 protected:
396 ssize_t count_{-1}; // -1 = template mode, >= 0 = static mode with this many coils
397 union Values {
398 std::vector<bool> (*func)(Ts...);
399 const uint8_t *packed;
401};
402
405template<typename... Ts>
407 public:
408 TEMPLATABLE_VALUE(uint16_t, read_address)
409 TEMPLATABLE_VALUE(uint16_t, read_count)
410 TEMPLATABLE_VALUE(uint16_t, write_address)
411
413 void set_values_static(const uint16_t *values, size_t len) {
414 this->values_.data = values;
415 this->len_ = static_cast<ssize_t>(len);
416 }
418 void set_values_template(std::vector<uint16_t> (*func)(Ts...)) {
419 this->values_.func = func;
420 this->len_ = -1; // sentinel: template mode
421 }
422
424
425 void play(const Ts &...x) override {
426 const uint16_t read_start = this->read_address_.value(x...);
427 const uint16_t read_count = this->read_count_.value(x...);
428 const uint16_t write_start = this->write_address_.value(x...);
429 // An out-of-range read/write count builds an empty PDU (the builder logs why), resolving via on_not_sent.
430 if (this->len_ >= 0) {
432 read_start, read_count, write_start,
433 std::span<const uint16_t>(this->values_.data, static_cast<size_t>(this->len_))),
434 this->command_options_(x...));
435 return;
436 }
437 const std::vector<uint16_t> values = this->values_.func(x...);
439 read_start, read_count, write_start, std::span<const uint16_t>(values)),
440 this->command_options_(x...));
441 }
442 // The 0x17 response carries only the read block, so the hub dispatch delivers it as a holding-register read.
443 void on_read_registers(modbus::EntityType entity_type, uint16_t start_address, std::span<const uint16_t> registers,
444 modbus::ResponseStatus status) override {
446 this->response_trigger_.trigger(registers);
447 }
448
449 protected:
451 ssize_t len_{-1}; // -1 = template mode, >= 0 = static mode with this many write registers
452 union Values {
453 std::vector<uint16_t> (*func)(Ts...);
454 const uint16_t *data;
456};
457
458} // namespace esphome::modbus_client
uint8_t status
Definition bl0942.h:8
virtual void play_complex(const Ts &...x)
Definition automation.h:585
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:304
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Inform the parent automation that the event has triggered.
Definition automation.h:557
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:1439
void set_address(uint8_t address)
Definition modbus.h:437
Read-only view of Modbus-packed bits: bit 0 of byte 0 is the first bit (LSB first),...
Shared base for the modbus_client actions.
Trigger< uint8_t, std::span< const uint8_t > > no_response_trigger_
Trigger< uint8_t, std::span< const uint8_t >, modbus::ExceptionCode > error_trigger_
void on_not_sent(uint8_t address, std::span< const uint8_t > request_pdu) override
Never reached the wire, from either of two sources.
Trigger< uint8_t, std::span< const uint8_t > > not_sent_trigger_
void play_complex(const Ts &...x) override
Stamp the templated device address before every play(): subclasses cannot forget it,...
void on_sent(uint8_t address, std::span< const uint8_t > request_pdu) override
The frame was written to the wire: fires once per transmission, before any reply, and never for a sen...
void send_or_resolve_(std::span< const uint8_t > pdu, modbus::CommandOptions options={})
The hub refuses some sends at the door with no callback (a duplicate write already pending,...
Trigger< uint8_t, std::span< const uint8_t >, modbus::ExceptionCode > * get_error_trigger()
Trigger< uint8_t, std::span< const uint8_t > > * get_not_sent_trigger()
void on_error(uint8_t address, std::span< const uint8_t > request_pdu, modbus::ExceptionCode exception_code) override
A Modbus exception reply.
Trigger< uint8_t, std::span< const uint8_t > > * get_no_response_trigger()
std::span< const uint8_t > * get_sent_trigger()
TEMPLATABLE_VALUE(uint8_t, target_address) Trigger< uint8_t
bool on_no_response(uint8_t address, std::span< const uint8_t > request_pdu) override
No reply within send_wait_time.
bool(*)(uint8_t, std::span< const uint8_t >) retry_func_t
The retry decision for on_no_response: given the request (address, PDU), return true to have the hub ...
Trigger< uint8_t, std::span< const uint8_t > > sent_trigger_
modbus_client.send: fire a raw PDU (function code + data; the hub adds address and CRC).
TEMPLATABLE_VALUE(modbus::helpers::PduBuffer, pdu) Trigger< uint8_t
Trigger< uint8_t, std::span< const uint8_t >, std::span< const uint8_t > > response_trigger_
void on_response(uint8_t address, std::span< const uint8_t > request_pdu, std::span< const uint8_t > response_pdu) override
std::span< const uint8_t > * get_response_trigger()
modbus_client.read_coils / read_discrete_inputs: on_response delivers the bits as a PackedBits view (...
TEMPLATABLE_VALUE(uint16_t, start_address) TEMPLATABLE_VALUE(uint16_t
void play(const Ts &...x) override
Trigger< modbus::PackedBits > response_trigger_
void on_read_bits(modbus::EntityType entity_type, uint16_t start_address, modbus::PackedBits bits, modbus::ResponseStatus status) override
count Trigger< modbus::PackedBits > * get_response_trigger()
The read-side per-command options (modbus::CommandOptions), declared once for every action that sends...
modbus::CommandOptions command_options_(const Ts &...x) const
The options for this send, with every templatable value resolved against the action's arguments.
TEMPLATABLE_VALUE(bool, continuous) TEMPLATABLE_VALUE(bool
modbus_client.read_holding_registers / read_input_registers: on_response delivers the registers in ho...
count Trigger< std::span< const uint16_t > > * get_response_trigger()
void on_read_registers(modbus::EntityType entity_type, uint16_t start_address, std::span< const uint16_t > registers, modbus::ResponseStatus status) override
TEMPLATABLE_VALUE(uint16_t, start_address) TEMPLATABLE_VALUE(uint16_t
Trigger< std::span< const uint16_t > > response_trigger_
modbus_client.read_write_multiple_registers (FC 0x17): writes one register block and reads another ba...
void on_read_registers(modbus::EntityType entity_type, uint16_t start_address, std::span< const uint16_t > registers, modbus::ResponseStatus status) override
Trigger< std::span< const uint16_t > > response_trigger_
Trigger< std::span< const uint16_t > > * get_response_trigger()
TEMPLATABLE_VALUE(uint16_t, read_address) TEMPLATABLE_VALUE(uint16_t
void set_values_template(std::vector< uint16_t >(*func)(Ts...))
Lambda config: the write registers are only known at play() time.
union esphome::modbus_client::ReadWriteMultipleRegistersAction::Values values_
Typed actions: these do NOT override the raw on_response, so the base ModbusClientDevice default runs...
void on_custom_response(std::span< const uint8_t > request_pdu, std::span< const uint8_t > response_pdu, modbus::ResponseStatus status) override
Trigger< std::span< const uint8_t >, std::span< const uint8_t > > custom_response_trigger_
Trigger< std::span< const uint8_t >, std::span< const uint8_t > > * get_custom_response_trigger()
void set_custom_response_handled()
Set by codegen when the config declares on_custom_response.
The write-side per-command options (command_options_schema(direction="write") adds exactly these keys...
modbus_client.write_multiple_coils: on_response is the acknowledgement (no arguments).
union esphome::modbus_client::WriteMultipleCoilsAction::Values values_
TEMPLATABLE_VALUE(uint16_t, start_address) void set_values_static(const uint8_t *packed
Static config: packed is the wire layout (LSB first) held in flash, count the number of coils.
void on_write_multiple_coils(uint16_t start_address, modbus::PackedBits bits, modbus::ResponseStatus status) override
void set_values_template(std::vector< bool >(*func)(Ts...))
Lambda config: the coils are only known at play() time.
modbus_client.write_multiple_registers: on_response is the acknowledgement (no arguments).
TEMPLATABLE_VALUE(uint16_t, start_address) void set_values_static(const uint16_t *values
Static config: the registers live in flash, so play() neither allocates nor copies.
void set_values_template(std::vector< uint16_t >(*func)(Ts...))
Lambda config: the registers are only known at play() time.
union esphome::modbus_client::WriteMultipleRegistersAction::Values values_
void on_write_multiple_registers(uint16_t start_address, std::span< const uint16_t > registers, modbus::ResponseStatus status) override
modbus_client.write_single_coil: on_response is the acknowledgement (no arguments).
void on_write_single_coil(uint16_t address, bool value, modbus::ResponseStatus status) override
TEMPLATABLE_VALUE(uint16_t, start_address) TEMPLATABLE_VALUE(bool
modbus_client.write_single_register: on_response is the acknowledgement (the ack only echoes the requ...
TEMPLATABLE_VALUE(uint16_t, start_address) TEMPLATABLE_VALUE(uint16_t
void on_write_single_register(uint16_t address, uint16_t value, modbus::ResponseStatus status) override
uint8_t options
unsigned count
Definition gif.cpp:51
__int64 ssize_t
Definition httplib.h:178
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.
WriteSinglePdu create_write_single_coil_pdu(uint16_t address, bool value)
Create modbus write single coil command Function 0x05 Write Single Coil.
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_write_registers_pdu(uint16_t start_address, std::span< const uint16_t > values)
Create modbus write multiple registers command Function 0x10 Write Multiple Registers.
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< ExceptionCode > ResponseStatus
Definition modbus.h:329
bool succeeded(ResponseStatus status)
True when a transaction carried no exception.
Definition modbus.h:332
constexpr size_t packed_bit_bytes(size_t bits)
Bits pack 8 per data byte, rounded up to whole bytes.
uint32_t value
Definition hal.cpp:41
STL namespace.
uint16_t x
Definition tt21100.cpp:5