ESPHome 2026.12.0-dev
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
10namespace esphome::modbus_client {
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
161// PDU builders for the static values tables, shared by every action instantiation. On ESP8266 the tables
162// are in PROGMEM, which the builders cannot read directly, so these copy them to the stack first.
163modbus::helpers::PduBuffer static_write_registers_pdu(uint16_t start, const uint16_t *values, size_t len);
164modbus::helpers::PduBuffer static_write_coils_pdu(uint16_t start, const uint8_t *packed, uint16_t count);
165modbus::helpers::PduBuffer static_read_write_registers_pdu(uint16_t read_start, uint16_t read_count,
166 uint16_t write_start, const uint16_t *values, size_t len);
167
178template<typename... Ts> class TypedClientActionBase : public ClientActionBase<Ts...> {
179 public:
181 return &this->custom_response_trigger_;
182 }
186
187 void on_custom_response(std::span<const uint8_t> request_pdu, std::span<const uint8_t> response_pdu,
188 modbus::ResponseStatus status) override {
189 if (!this->custom_response_handled_) {
190 modbus::ModbusClientDevice::on_custom_response(request_pdu, response_pdu, status);
191 return;
192 }
193 this->custom_response_trigger_.trigger(request_pdu, response_pdu);
194 }
195
196 protected:
199};
200
203template<typename... Ts>
205 public:
206 explicit ReadRegistersAction(bool holding) : holding_(holding) {}
208 TEMPLATABLE_VALUE(uint16_t, count)
209
210 Trigger<std::span<const uint16_t>> *get_response_trigger() { return &this->response_trigger_; }
211
212 void play(const Ts &...x) override {
213 const auto function_code =
215 this->send_or_resolve_(
216 modbus::helpers::create_read_pdu(function_code, this->start_address_.value(x...), this->count_.value(x...)),
217 this->command_options_(x...));
218 }
219 void on_read_registers(modbus::EntityType entity_type, uint16_t start_address, std::span<const uint16_t> registers,
220 modbus::ResponseStatus status) override {
222 this->response_trigger_.trigger(registers);
223 }
224
225 protected:
228};
229
232template<typename... Ts> class ReadBitsAction : public TypedClientActionBase<Ts...>, public ReadCommandOptions<Ts...> {
233 public:
234 explicit ReadBitsAction(bool coils) : coils_(coils) {}
236 TEMPLATABLE_VALUE(uint16_t, count)
237
238 Trigger<modbus::PackedBits> *get_response_trigger() { return &this->response_trigger_; }
239
240 void play(const Ts &...x) override {
241 const auto function_code =
243 this->send_or_resolve_(
244 modbus::helpers::create_read_pdu(function_code, this->start_address_.value(x...), this->count_.value(x...)),
245 this->command_options_(x...));
246 }
248 modbus::ResponseStatus status) override {
250 this->response_trigger_.trigger(bits);
251 }
252
253 protected:
255 bool coils_;
256};
257
260template<typename... Ts>
262 public:
264 TEMPLATABLE_VALUE(uint16_t, value)
265
267
268 void play(const Ts &...x) override {
269 this->send_or_resolve_(
270 modbus::helpers::create_write_single_register_pdu(this->start_address_.value(x...), this->value_.value(x...)),
271 this->write_command_options_(x...));
272 }
273 void on_write_single_register(uint16_t address, uint16_t value, modbus::ResponseStatus status) override {
276 }
277
278 protected:
280};
281
284template<typename... Ts>
286 public:
289
291
292 void play(const Ts &...x) override {
293 this->send_or_resolve_(
294 modbus::helpers::create_write_single_coil_pdu(this->start_address_.value(x...), this->value_.value(x...)),
295 this->write_command_options_(x...));
296 }
297 void on_write_single_coil(uint16_t address, bool value, modbus::ResponseStatus status) override {
300 }
301
302 protected:
304};
305
310template<typename... Ts>
312 public:
314
315
316 void set_values_static(const uint16_t *values, size_t len) {
317 this->values_.data = values;
318 this->len_ = static_cast<ssize_t>(len);
319 }
322 void set_values_template(std::vector<uint16_t> (*func)(Ts...)) {
323 this->values_.func = func;
324 this->len_ = -1; // sentinel: template mode
325 }
326
328
329 void play(const Ts &...x) override {
330 const uint16_t start = this->start_address_.value(x...);
331 // An empty or over-long set rejects into an empty PDU inside the builder, which logs the reason;
332 // the empty PDU then resolves via on_not_sent like any refused send.
333 this->send_or_resolve_(this->len_ >= 0
334 ? static_write_registers_pdu(start, this->values_.data, static_cast<size_t>(this->len_))
335 : modbus::helpers::create_write_registers_pdu(start, this->values_.func(x...)),
336 this->write_command_options_(x...));
337 }
338 void on_write_multiple_registers(uint16_t start_address, std::span<const uint16_t> registers,
339 modbus::ResponseStatus status) override {
342 }
343
344 protected:
346 ssize_t len_{-1}; // -1 = template mode, >= 0 = static mode with this many registers
347 union Values {
348 std::vector<uint16_t> (*func)(Ts...);
349 const uint16_t *data;
351};
352
357template<typename... Ts>
359 public:
361
362
363 void set_values_static(const uint8_t *packed, size_t count) {
364 this->values_.packed = packed;
365 this->count_ = static_cast<ssize_t>(count);
366 }
368 void set_values_template(std::vector<bool> (*func)(Ts...)) {
369 this->values_.func = func;
370 this->count_ = -1; // sentinel: template mode
371 }
372
374
375 void play(const Ts &...x) override {
376 const uint16_t start = this->start_address_.value(x...);
377 // For a lambda the builder packs and bound-checks; an over-long set is rejected and logged there.
378 this->send_or_resolve_(
379 this->count_ >= 0 ? static_write_coils_pdu(start, this->values_.packed, static_cast<uint16_t>(this->count_))
380 : modbus::helpers::create_write_coils_pdu(start, this->values_.func(x...)),
381 this->write_command_options_(x...));
382 }
388
389 protected:
391 ssize_t count_{-1}; // -1 = template mode, >= 0 = static mode with this many coils
392 union Values {
393 std::vector<bool> (*func)(Ts...);
394 const uint8_t *packed;
396};
397
400template<typename... Ts>
402 public:
403 TEMPLATABLE_VALUE(uint16_t, read_address)
404 TEMPLATABLE_VALUE(uint16_t, read_count)
405 TEMPLATABLE_VALUE(uint16_t, write_address)
406
408 void set_values_static(const uint16_t *values, size_t len) {
409 this->values_.data = values;
410 this->len_ = static_cast<ssize_t>(len);
411 }
413 void set_values_template(std::vector<uint16_t> (*func)(Ts...)) {
414 this->values_.func = func;
415 this->len_ = -1; // sentinel: template mode
416 }
417
419
420 void play(const Ts &...x) override {
421 const uint16_t read_start = this->read_address_.value(x...);
422 const uint16_t read_count = this->read_count_.value(x...);
423 const uint16_t write_start = this->write_address_.value(x...);
424 // An out-of-range read/write count builds an empty PDU (the builder logs why), resolving via on_not_sent.
425 this->send_or_resolve_(this->len_ >= 0
426 ? static_read_write_registers_pdu(read_start, read_count, write_start,
427 this->values_.data, static_cast<size_t>(this->len_))
429 read_start, read_count, write_start, this->values_.func(x...)),
430 this->command_options_(x...));
431 }
432 // The 0x17 response carries only the read block, so the hub dispatch delivers it as a holding-register read.
433 void on_read_registers(modbus::EntityType entity_type, uint16_t start_address, std::span<const uint16_t> registers,
434 modbus::ResponseStatus status) override {
436 this->response_trigger_.trigger(registers);
437 }
438
439 protected:
441 ssize_t len_{-1}; // -1 = template mode, >= 0 = static mode with this many write registers
442 union Values {
443 std::vector<uint16_t> (*func)(Ts...);
444 const uint16_t *data;
446};
447
448} // namespace esphome::modbus_client
uint8_t status
Definition bl0942.h:8
virtual void play_complex(const Ts &...x)
Definition automation.h:618
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:335
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Inform the parent automation that the event has triggered.
Definition automation.h:588
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:435
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 are a shared flash table.
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...
PduBuffer static_write_registers_pdu(uint16_t start, const uint16_t *values, size_t len)
PduBuffer static_read_write_registers_pdu(uint16_t read_start, uint16_t read_count, uint16_t write_start, const uint16_t *values, size_t len)
PduBuffer static_write_coils_pdu(uint16_t start, const uint8_t *packed, uint16_t count)
std::optional< ExceptionCode > ResponseStatus
Definition modbus.h:327
bool succeeded(ResponseStatus status)
True when a transaction carried no exception.
Definition modbus.h:330
uint32_t value
Definition hal.cpp:59
const void size_t len
Definition hal.h:68
STL namespace.
uint16_t x
Definition tt21100.cpp:5