6namespace modbus_controller {
8static const char *
const TAG =
"modbus_controller";
25 if (!command->should_retry(this->max_cmd_retries_)) {
27 ESP_LOGW(TAG,
"Modbus device=%d set offline", this->
address_);
37 this->
offline_callback_.call((
int) command->function_code, command->register_address);
39 ESP_LOGD(TAG,
"Modbus command to device=%d register=0x%02X no response received - removed from send queue",
40 this->
address_, command->register_address);
43 ESP_LOGV(TAG,
"Sending next modbus command to device %d register 0x%02X count %d", this->
address_,
44 command->register_address, command->register_count);
52 if (!command->on_data_func) {
63 if (current_command !=
nullptr) {
65 ESP_LOGW(TAG,
"Modbus device=%d back online", this->
address_);
70 r.skip_updates_counter = 0;
75 this->
online_callback_.call((
int) current_command->function_code, current_command->register_address);
79 current_command->payload = data;
81 ESP_LOGV(TAG,
"Modbus response queued");
88 ESP_LOGV(TAG,
"Process modbus response for address 0x%X size: %zu", response->
register_address,
94 ESP_LOGE(TAG,
"Modbus error function code: 0x%X exception: %d ", function_code, exception_code);
97 if (current_command !=
nullptr) {
99 "Modbus error - last command: function code=0x%X register address = 0x%X "
100 "registers count=%d "
102 function_code, current_command->register_address, current_command->register_count,
103 current_command->payload.size());
109 uint16_t number_of_registers) {
111 "Received read holding/input registers for device 0x%X. FC: 0x%X. Start address: 0x%X. Number of registers: "
113 this->
address_, function_code, start_address, number_of_registers);
116 ESP_LOGW(TAG,
"Invalid number of registers %d. Sending exception response.", number_of_registers);
121 std::vector<uint16_t> sixteen_bit_response;
122 for (uint16_t current_address = start_address; current_address < start_address + number_of_registers;) {
125 if (server_register->address == current_address) {
126 if (!server_register->read_lambda) {
129 int64_t value = server_register->read_lambda();
130 ESP_LOGD(TAG,
"Matched register. Address: 0x%02X. Value type: %zu. Register count: %u. Value: %s.",
131 server_register->address,
static_cast<size_t>(server_register->value_type),
132 server_register->register_count, server_register->format_value(value).c_str());
134 std::vector<uint16_t> payload;
135 payload.reserve(server_register->register_count * 2);
137 sixteen_bit_response.insert(sixteen_bit_response.end(), payload.cbegin(), payload.cend());
138 current_address += server_register->register_count;
148 "Could not match any register to address 0x%02X, but default allowed. "
149 "Returning default value: %d.",
152 current_address += 1;
155 "Could not match any register to address 0x%02X and default not allowed. Sending exception response.",
163 std::vector<uint8_t> response;
164 for (
auto v : sixteen_bit_response) {
166 response.push_back(decoded_value[0]);
167 response.push_back(decoded_value[1]);
170 this->
send(function_code, start_address, number_of_registers, response.size(), response.data());
174 uint16_t number_of_registers;
175 uint16_t payload_offset;
178 number_of_registers = uint16_t(data[3]) | (uint16_t(data[2]) << 8);
180 ESP_LOGW(TAG,
"Invalid number of registers %d. Sending exception response.", number_of_registers);
186 ESP_LOGW(TAG,
"Payload size of %d bytes is not 2 times the number of registers (%d). Sending exception response.",
193 number_of_registers = 1;
196 ESP_LOGW(TAG,
"Invalid function code 0x%X. Sending exception response.", function_code);
201 uint16_t start_address = uint16_t(data[1]) | (uint16_t(data[0]) << 8);
203 "Received write holding registers for device 0x%X. FC: 0x%X. Start address: 0x%X. Number of registers: "
205 this->
address_, function_code, start_address, number_of_registers);
207 auto for_each_register = [
this, start_address, number_of_registers, payload_offset](
208 const std::function<bool(
ServerRegister *, uint16_t offset)> &callback) ->
bool {
209 uint16_t offset = payload_offset;
210 for (uint16_t current_address = start_address; current_address < start_address + number_of_registers;) {
213 if (server_register->address == current_address) {
214 ok = callback(server_register, offset);
215 current_address += server_register->register_count;
216 offset += server_register->register_count *
sizeof(uint16_t);
229 if (!for_each_register([](
ServerRegister *server_register, uint16_t offset) ->
bool {
237 if (!for_each_register([&data](
ServerRegister *server_register, uint16_t offset) {
245 std::vector<uint8_t> response;
248 response.push_back(function_code);
249 response.insert(response.end(), data.begin(), data.begin() + 4);
254 auto reg_it = std::find_if(
259 ESP_LOGE(TAG,
"No matching range for sensor found - start_address : 0x%X", start_address);
261 return reg_it->sensors;
268 const std::vector<uint8_t> &data) {
269 ESP_LOGV(TAG,
"data for register address : 0x%X : ", start_address);
273 for (
auto *sensor : sensors) {
274 sensor->parse_and_publish(data);
283 if (item->is_equal(command)) {
284 ESP_LOGW(TAG,
"Duplicate modbus command found: type=0x%x address=%u count=%u",
288 item->payload = command.
payload;
293 this->
command_queue_.push_back(make_unique<ModbusCommandItem>(command));
303 if (!sensors.empty()) {
304 auto sensor = sensors.cbegin();
306 this, (*sensor)->custom_data,
307 [
this](
ModbusRegisterType register_type, uint16_t start_address,
const std::vector<uint8_t> &data) {
308 this->on_register_data(ModbusRegisterType::CUSTOM, start_address, data);
310 command_item.register_address = (*sensor)->start_address;
311 command_item.register_count = (*sensor)->register_count;
329 ESP_LOGV(TAG,
"%zu modbus commands already in queue", this->
command_queue_.size());
331 ESP_LOGV(TAG,
"Updating modbus component");
335 ESP_LOGVV(TAG,
"Updating range 0x%X", r.start_address);
344 ESP_LOGW(TAG,
"No sensors registered");
351 uint8_t buffer_offset = 0;
369 ESP_LOGV(TAG,
"Started new range");
389 ESP_LOGV(TAG,
"Re-use previous register - change to register: 0x%X %d offset=%u", curr->
start_address,
398 curr->
offset += buffer_offset;
406 ESP_LOGV(TAG,
"Extend range - change to register: 0x%X %d offset=%u", curr->
start_address,
449 "ModbusController:\n"
451 " Max Command Retries: %d\n"
452 " Offline Skip Updates: %d\n"
453 " Server Courtesy Response:\n"
455 " Register Last Address: 0x%02X\n"
456 " Register Value: %d",
459 this->server_courtesy_response_.register_last_address, this->server_courtesy_response_.register_value);
461#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
462 ESP_LOGCONFIG(TAG,
"sensormap");
464 ESP_LOGCONFIG(TAG,
" Sensor type=%zu start=0x%X offset=0x%X count=%d size=%d",
465 static_cast<uint8_t
>(it->register_type), it->start_address, it->offset, it->register_count,
466 it->get_register_size());
468 ESP_LOGCONFIG(TAG,
"ranges");
470 ESP_LOGCONFIG(TAG,
" Range type=%zu start=0x%X count=%d skip_updates=%d",
static_cast<uint8_t
>(it.register_type),
471 it.start_address, it.register_count, it.skip_updates);
473 ESP_LOGCONFIG(TAG,
"server registers");
475 ESP_LOGCONFIG(TAG,
" Address=0x%02X value_type=%zu register_count=%u", r->address,
476 static_cast<uint8_t
>(r->value_type), r->register_count);
496 const std::vector<uint8_t> &data) {
501 ESP_LOGV(TAG,
"sensors");
503 ESP_LOGV(TAG,
" Sensor start=0x%X count=%d size=%d offset=%d", it->start_address, it->register_count,
504 it->get_register_size(), it->offset);
510 std::function<
void(
ModbusRegisterType register_type, uint16_t start_address,
const std::vector<uint8_t> &data)>
524 uint16_t register_count) {
532 const std::vector<uint8_t> &data) {
539 uint16_t start_address, uint16_t register_count,
540 const std::vector<uint16_t> &values) {
548 const std::vector<uint8_t> &data) {
551 for (
auto v : values) {
553 cmd.
payload.push_back(decoded_value[0]);
554 cmd.
payload.push_back(decoded_value[1]);
568 const std::vector<uint8_t> &data) {
571 cmd.
payload.push_back(value ? 0xFF : 0);
577 const std::vector<bool> &values) {
585 const std::vector<uint8_t> &data) {
591 for (
auto coil : values) {
593 bitmask |= (1 << bitcounter);
596 if (bitcounter % 8 == 0) {
597 cmd.
payload.push_back(bitmask);
602 if (bitcounter % 8) {
603 cmd.
payload.push_back(bitmask);
617 const std::vector<uint8_t> &data) {
622 cmd.
payload.push_back(decoded_value[0]);
623 cmd.
payload.push_back(decoded_value[1]);
629 std::function<
void(
ModbusRegisterType register_type, uint16_t start_address,
const std::vector<uint8_t> &data)>
634 if (handler ==
nullptr) {
636 ESP_LOGI(TAG,
"Custom Command sent");
648 std::function<
void(
ModbusRegisterType register_type, uint16_t start_address,
const std::vector<uint8_t> &data)>
653 if (handler ==
nullptr) {
655 ESP_LOGI(TAG,
"Custom Command sent");
660 for (
auto v : values) {
661 cmd.
payload.push_back((v >> 8) & 0xFF);
662 cmd.
payload.push_back(v & 0xFF);
671 this->payload.empty() ?
nullptr : &this->payload[0]);
691 switch (value_type) {
694 data.push_back(value & 0xFFFF);
699 data.push_back((value & 0xFFFF0000) >> 16);
700 data.push_back(value & 0xFFFF);
705 data.push_back(value & 0xFFFF);
706 data.push_back((value & 0xFFFF0000) >> 16);
710 data.push_back((value & 0xFFFF000000000000) >> 48);
711 data.push_back((value & 0xFFFF00000000) >> 32);
712 data.push_back((value & 0xFFFF0000) >> 16);
713 data.push_back(value & 0xFFFF);
717 data.push_back(value & 0xFFFF);
718 data.push_back((value & 0xFFFF0000) >> 16);
719 data.push_back((value & 0xFFFF00000000) >> 32);
720 data.push_back((value & 0xFFFF000000000000) >> 48);
723 ESP_LOGE(TAG,
"Invalid data type for modbus number to payload conversation: %d",
724 static_cast<uint16_t
>(value_type));
733 size_t size = data.size() - offset;
735 switch (sensor_value_type) {
756 value =
static_cast<uint32_t
>(value & 0xFFFF) << 16 | (value & 0xFFFF0000) >> 16;
782 uint32_t sign_bit = (value & 0x8000) << 16;
784 static_cast<int32_t
>(((value & 0x7FFF) << 16 | (value & 0xFFFF0000) >> 16) | sign_bit), bitmask);
803 value = (tmp << 48) | (tmp >> 48) | ((tmp & 0xFFFF0000) << 16) | ((tmp >> 16) & 0xFFFF0000);
813 ESP_LOGE(TAG,
"not enough data for value");
void send_raw(const std::vector< uint8_t > &payload)
void send(uint8_t function, uint16_t start_address, uint16_t number_of_entities, uint8_t payload_len=0, const uint8_t *payload=nullptr)
void send_error(uint8_t function_code, ModbusExceptionCode exception_code)
bool waiting_for_response()
static ModbusCommandItem create_custom_command(ModbusController *modbusdevice, const std::vector< uint8_t > &values, std::function< void(ModbusRegisterType register_type, uint16_t start_address, const std::vector< uint8_t > &data)> &&handler=nullptr)
Create custom modbus command.
bool is_equal(const ModbusCommandItem &other)
static ModbusCommandItem create_write_multiple_coils(ModbusController *modbusdevice, uint16_t start_address, const std::vector< bool > &values)
Create modbus write multiple registers command Function 15 (0Fhex) Write Multiple Coils.
static ModbusCommandItem create_write_single_coil(ModbusController *modbusdevice, uint16_t address, bool value)
Create modbus write single registers command Function 05 (05hex) Write Single Coil.
uint8_t send_count_
How many times this command has been sent.
static ModbusCommandItem create_write_single_command(ModbusController *modbusdevice, uint16_t start_address, uint16_t value)
Create modbus write multiple registers command Function 16 (10hex) Write Multiple Registers.
static ModbusCommandItem create_read_command(ModbusController *modbusdevice, ModbusRegisterType register_type, uint16_t start_address, uint16_t register_count, std::function< void(ModbusRegisterType register_type, uint16_t start_address, const std::vector< uint8_t > &data)> &&handler)
factory methods
ModbusRegisterType register_type
static ModbusCommandItem create_write_multiple_command(ModbusController *modbusdevice, uint16_t start_address, uint16_t register_count, const std::vector< uint16_t > &values)
Create modbus read command Function code 02-04.
uint16_t register_address
ModbusController * modbusdevice
ModbusFunctionCode function_code
std::function< void(ModbusRegisterType register_type, uint16_t start_address, const std::vector< uint8_t > &data)> on_data_func
std::vector< uint8_t > payload
void on_register_data(ModbusRegisterType register_type, uint16_t start_address, const std::vector< uint8_t > &data)
default delegate called by process_modbus_data when a response has retrieved from the incoming queue
void on_modbus_read_registers(uint8_t function_code, uint16_t start_address, uint16_t number_of_registers) final
called when a modbus request (function code 0x03 or 0x04) was parsed without errors
std::queue< std::unique_ptr< ModbusCommandItem > > incoming_queue_
modbus response data waiting to get processed
void add_on_online_callback(std::function< void(int, int)> &&callback)
Set callback for online changes.
uint16_t command_throttle_
min time in ms between sending modbus commands
void on_write_register_response(ModbusRegisterType register_type, uint16_t start_address, const std::vector< uint8_t > &data)
default delegate called by process_modbus_data when a response for a write response has retrieved fro...
bool allow_duplicate_commands_
if duplicate commands can be sent
void add_on_offline_callback(std::function< void(int, int)> &&callback)
Set callback for offline changes.
CallbackManager< void(int, int)> command_sent_callback_
Command sent callback.
std::vector< RegisterRange > register_ranges_
Continuous range of modbus registers.
uint32_t last_command_timestamp_
when was the last send operation
CallbackManager< void(int, int)> offline_callback_
Server offline callback.
void dump_sensors_()
dump the parsed sensormap for diagnostics
std::vector< ServerRegister * > server_registers_
Collection of all server registers for this component.
SensorSet sensorset_
Collection of all sensors for this component.
uint8_t max_cmd_retries_
How many times we will retry a command if we get no response.
bool send_next_command_()
send the next modbus command from the send queue
std::list< std::unique_ptr< ModbusCommandItem > > command_queue_
Hold the pending requests to be sent.
void on_modbus_error(uint8_t function_code, uint8_t exception_code) override
called when a modbus error response was received
void process_modbus_data_(const ModbusCommandItem *response)
parse incoming modbus data
void update_range_(RegisterRange &r)
submit the read command for the address range to the send queue
ServerCourtesyResponse server_courtesy_response_
Server courtesy response.
bool module_offline_
if module didn't respond the last command
size_t create_register_ranges_()
parse sensormap_ and create range of sequential addresses
uint16_t offline_skip_updates_
how many updates to skip if module is offline
void add_on_command_sent_callback(std::function< void(int, int)> &&callback)
Set callback for commands.
void on_modbus_write_registers(uint8_t function_code, const std::vector< uint8_t > &data) final
called when a modbus request (function code 0x06 or 0x10) was parsed without errors
void dump_config() override
void on_modbus_data(const std::vector< uint8_t > &data) override
called when a modbus response was parsed without errors
void queue_command(const ModbusCommandItem &command)
queues a modbus command in the send queue
SensorSet find_sensors_(ModbusRegisterType register_type, uint16_t start_address) const
CallbackManager< void(int, int)> online_callback_
Server online callback.
ModbusRegisterType register_type
virtual size_t get_register_size() const
SensorValueType value_type
void number_to_payload(std::vector< uint16_t > &data, int64_t value, SensorValueType value_type)
Convert float value to vector<uint16_t> suitable for sending.
std::set< SensorItem *, SensorItemsComparator > SensorSet
ModbusFunctionCode modbus_register_read_function(ModbusRegisterType reg_type)
T get_data(const std::vector< uint8_t > &data, size_t buffer_offset)
Extract data from modbus response buffer.
int64_t payload_to_number(const std::vector< uint8_t > &data, SensorValueType sensor_value_type, uint8_t offset, uint32_t bitmask)
Convert vector<uint8_t> response payload to number.
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...
@ WRITE_MULTIPLE_REGISTERS
const uint8_t MAX_NUM_OF_REGISTERS_TO_READ
const uint8_t MAX_NUM_OF_REGISTERS_TO_WRITE
Providing packet encoding functions for exchanging data with a remote host.
constexpr std::array< uint8_t, sizeof(T)> decode_value(T val)
Decode a value into its constituent bytes (from most to least significant).
uint32_t IRAM_ATTR HOT millis()
ModbusRegisterType register_type
uint16_t skip_updates_counter
uint16_t register_last_address