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);
115 std::vector<uint16_t> sixteen_bit_response;
116 for (uint16_t current_address = start_address; current_address < start_address + number_of_registers;) {
119 if (server_register->address == current_address) {
120 if (!server_register->read_lambda) {
123 int64_t value = server_register->read_lambda();
124 ESP_LOGD(TAG,
"Matched register. Address: 0x%02X. Value type: %zu. Register count: %u. Value: %s.",
125 server_register->address,
static_cast<size_t>(server_register->value_type),
126 server_register->register_count, server_register->format_value(value).c_str());
128 std::vector<uint16_t> payload;
129 payload.reserve(server_register->register_count * 2);
131 sixteen_bit_response.insert(sixteen_bit_response.end(), payload.cbegin(), payload.cend());
132 current_address += server_register->register_count;
139 ESP_LOGW(TAG,
"Could not match any register to address %02X. Sending exception response.", current_address);
145 std::vector<uint8_t> response;
146 for (
auto v : sixteen_bit_response) {
148 response.push_back(decoded_value[0]);
149 response.push_back(decoded_value[1]);
152 this->
send(function_code, start_address, number_of_registers, response.size(), response.data());
156 uint16_t number_of_registers;
157 uint16_t payload_offset;
159 if (function_code == 0x10) {
160 number_of_registers = uint16_t(data[3]) | (uint16_t(data[2]) << 8);
161 if (number_of_registers == 0 || number_of_registers > 0x7B) {
162 ESP_LOGW(TAG,
"Invalid number of registers %d. Sending exception response.", number_of_registers);
168 ESP_LOGW(TAG,
"Payload size of %d bytes is not 2 times the number of registers (%d). Sending exception response.",
174 }
else if (function_code == 0x06) {
175 number_of_registers = 1;
178 ESP_LOGW(TAG,
"Invalid function code 0x%X. Sending exception response.", function_code);
183 uint16_t start_address = uint16_t(data[1]) | (uint16_t(data[0]) << 8);
185 "Received write holding registers for device 0x%X. FC: 0x%X. Start address: 0x%X. Number of registers: "
187 this->
address_, function_code, start_address, number_of_registers);
189 auto for_each_register = [
this, start_address, number_of_registers, payload_offset](
190 const std::function<bool(
ServerRegister *, uint16_t offset)> &callback) ->
bool {
191 uint16_t offset = payload_offset;
192 for (uint16_t current_address = start_address; current_address < start_address + number_of_registers;) {
195 if (server_register->address == current_address) {
196 ok = callback(server_register, offset);
197 current_address += server_register->register_count;
198 offset += server_register->register_count *
sizeof(uint16_t);
211 if (!for_each_register([](
ServerRegister *server_register, uint16_t offset) ->
bool {
219 if (!for_each_register([&data](
ServerRegister *server_register, uint16_t offset) {
227 std::vector<uint8_t> response;
230 response.push_back(function_code);
231 response.insert(response.end(), data.begin(), data.begin() + 4);
236 auto reg_it = std::find_if(
241 ESP_LOGE(TAG,
"No matching range for sensor found - start_address : 0x%X", start_address);
243 return reg_it->sensors;
250 const std::vector<uint8_t> &data) {
251 ESP_LOGV(TAG,
"data for register address : 0x%X : ", start_address);
255 for (
auto *sensor : sensors) {
256 sensor->parse_and_publish(data);
265 if (item->is_equal(command)) {
266 ESP_LOGW(TAG,
"Duplicate modbus command found: type=0x%x address=%u count=%u",
270 item->payload = command.
payload;
275 this->
command_queue_.push_back(make_unique<ModbusCommandItem>(command));
285 if (!sensors.empty()) {
286 auto sensor = sensors.cbegin();
288 this, (*sensor)->custom_data,
289 [
this](
ModbusRegisterType register_type, uint16_t start_address,
const std::vector<uint8_t> &data) {
290 this->on_register_data(ModbusRegisterType::CUSTOM, start_address, data);
292 command_item.register_address = (*sensor)->start_address;
293 command_item.register_count = (*sensor)->register_count;
311 ESP_LOGV(TAG,
"%zu modbus commands already in queue", this->
command_queue_.size());
313 ESP_LOGV(TAG,
"Updating modbus component");
317 ESP_LOGVV(TAG,
"Updating range 0x%X", r.start_address);
326 ESP_LOGW(TAG,
"No sensors registered");
333 uint8_t buffer_offset = 0;
351 ESP_LOGV(TAG,
"Started new range");
371 ESP_LOGV(TAG,
"Re-use previous register - change to register: 0x%X %d offset=%u", curr->
start_address,
380 curr->
offset += buffer_offset;
388 ESP_LOGV(TAG,
"Extend range - change to register: 0x%X %d offset=%u", curr->
start_address,
431 "ModbusController:\n"
433 " Max Command Retries: %d\n"
434 " Offline Skip Updates: %d",
436#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
437 ESP_LOGCONFIG(TAG,
"sensormap");
439 ESP_LOGCONFIG(TAG,
" Sensor type=%zu start=0x%X offset=0x%X count=%d size=%d",
440 static_cast<uint8_t
>(it->register_type), it->start_address, it->offset, it->register_count,
441 it->get_register_size());
443 ESP_LOGCONFIG(TAG,
"ranges");
445 ESP_LOGCONFIG(TAG,
" Range type=%zu start=0x%X count=%d skip_updates=%d",
static_cast<uint8_t
>(it.register_type),
446 it.start_address, it.register_count, it.skip_updates);
448 ESP_LOGCONFIG(TAG,
"server registers");
450 ESP_LOGCONFIG(TAG,
" Address=0x%02X value_type=%zu register_count=%u", r->address,
451 static_cast<uint8_t
>(r->value_type), r->register_count);
460 if (message !=
nullptr)
471 const std::vector<uint8_t> &data) {
476 ESP_LOGV(TAG,
"sensors");
478 ESP_LOGV(TAG,
" Sensor start=0x%X count=%d size=%d offset=%d", it->start_address, it->register_count,
479 it->get_register_size(), it->offset);
485 std::function<
void(
ModbusRegisterType register_type, uint16_t start_address,
const std::vector<uint8_t> &data)>
499 uint16_t register_count) {
507 const std::vector<uint8_t> &data) {
514 uint16_t start_address, uint16_t register_count,
515 const std::vector<uint16_t> &values) {
523 const std::vector<uint8_t> &data) {
526 for (
auto v : values) {
528 cmd.
payload.push_back(decoded_value[0]);
529 cmd.
payload.push_back(decoded_value[1]);
543 const std::vector<uint8_t> &data) {
546 cmd.
payload.push_back(value ? 0xFF : 0);
552 const std::vector<bool> &values) {
560 const std::vector<uint8_t> &data) {
566 for (
auto coil : values) {
568 bitmask |= (1 << bitcounter);
571 if (bitcounter % 8 == 0) {
572 cmd.
payload.push_back(bitmask);
577 if (bitcounter % 8) {
578 cmd.
payload.push_back(bitmask);
592 const std::vector<uint8_t> &data) {
597 cmd.
payload.push_back(decoded_value[0]);
598 cmd.
payload.push_back(decoded_value[1]);
604 std::function<
void(
ModbusRegisterType register_type, uint16_t start_address,
const std::vector<uint8_t> &data)>
609 if (handler ==
nullptr) {
611 ESP_LOGI(TAG,
"Custom Command sent");
623 std::function<
void(
ModbusRegisterType register_type, uint16_t start_address,
const std::vector<uint8_t> &data)>
628 if (handler ==
nullptr) {
630 ESP_LOGI(TAG,
"Custom Command sent");
635 for (
auto v : values) {
636 cmd.
payload.push_back((v >> 8) & 0xFF);
637 cmd.
payload.push_back(v & 0xFF);
646 this->payload.empty() ?
nullptr : &this->payload[0]);
666 switch (value_type) {
669 data.push_back(value & 0xFFFF);
674 data.push_back((value & 0xFFFF0000) >> 16);
675 data.push_back(value & 0xFFFF);
680 data.push_back(value & 0xFFFF);
681 data.push_back((value & 0xFFFF0000) >> 16);
685 data.push_back((value & 0xFFFF000000000000) >> 48);
686 data.push_back((value & 0xFFFF00000000) >> 32);
687 data.push_back((value & 0xFFFF0000) >> 16);
688 data.push_back(value & 0xFFFF);
692 data.push_back(value & 0xFFFF);
693 data.push_back((value & 0xFFFF0000) >> 16);
694 data.push_back((value & 0xFFFF00000000) >> 32);
695 data.push_back((value & 0xFFFF000000000000) >> 48);
698 ESP_LOGE(TAG,
"Invalid data type for modbus number to payload conversation: %d",
699 static_cast<uint16_t
>(value_type));
708 size_t size = data.size() - offset;
710 switch (sensor_value_type) {
731 value =
static_cast<uint32_t
>(value & 0xFFFF) << 16 | (value & 0xFFFF0000) >> 16;
757 uint32_t sign_bit = (value & 0x8000) << 16;
759 static_cast<int32_t
>(((value & 0x7FFF) << 16 | (value & 0xFFFF0000) >> 16) | sign_bit), bitmask);
778 value = (tmp << 48) | (tmp >> 48) | ((tmp & 0xFFFF0000) << 16) | ((tmp >> 16) & 0xFFFF0000);
788 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, uint8_t 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
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.
@ WRITE_MULTIPLE_REGISTERS
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...
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