6 namespace modbus_controller {
8 static 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 float value = server_register->read_lambda();
122 ESP_LOGD(TAG,
"Matched register. Address: 0x%02X. Value type: %zu. Register count: %u. Value: %0.1f.",
123 server_register->address, static_cast<uint8_t>(server_register->value_type),
124 server_register->register_count, value);
125 std::vector<uint16_t> payload =
float_to_payload(value, server_register->value_type);
126 sixteen_bit_response.insert(sixteen_bit_response.end(), payload.cbegin(), payload.cend());
127 current_address += server_register->register_count;
134 ESP_LOGW(TAG,
"Could not match any register to address %02X. Sending exception response.", current_address);
135 std::vector<uint8_t> error_response;
136 error_response.push_back(this->
address_);
137 error_response.push_back(0x81);
138 error_response.push_back(0x02);
144 std::vector<uint8_t> response;
145 for (
auto v : sixteen_bit_response) {
147 response.push_back(decoded_value[0]);
148 response.push_back(decoded_value[1]);
151 this->
send(function_code, start_address, number_of_registers, response.size(), response.data());
160 ESP_LOGE(TAG,
"No matching range for sensor found - start_address : 0x%X", start_address);
162 return reg_it->sensors;
169 const std::vector<uint8_t> &data) {
170 ESP_LOGV(TAG,
"data for register address : 0x%X : ", start_address);
174 for (
auto *
sensor : sensors) {
175 sensor->parse_and_publish(data);
184 if (item->is_equal(command)) {
185 ESP_LOGW(TAG,
"Duplicate modbus command found: type=0x%x address=%u count=%u",
189 item->payload = command.
payload;
194 this->
command_queue_.push_back(make_unique<ModbusCommandItem>(command));
204 if (!sensors.empty()) {
205 auto sensor = sensors.cbegin();
207 this, (*sensor)->custom_data,
208 [
this](
ModbusRegisterType register_type, uint16_t start_address,
const std::vector<uint8_t> &data) {
209 this->on_register_data(ModbusRegisterType::CUSTOM, start_address, data);
211 command_item.register_address = (*sensor)->start_address;
212 command_item.register_count = (*sensor)->register_count;
230 ESP_LOGV(TAG,
"%zu modbus commands already in queue", this->
command_queue_.size());
232 ESP_LOGV(TAG,
"Updating modbus component");
236 ESP_LOGVV(TAG,
"Updating range 0x%X", r.start_address);
245 ESP_LOGW(TAG,
"No sensors registered");
252 uint8_t buffer_offset = 0;
270 ESP_LOGV(TAG,
"Started new range");
290 ESP_LOGV(TAG,
"Re-use previous register - change to register: 0x%X %d offset=%u", curr->
start_address,
299 curr->
offset += buffer_offset;
307 ESP_LOGV(TAG,
"Extend range - change to register: 0x%X %d offset=%u", curr->
start_address,
349 ESP_LOGCONFIG(TAG,
"ModbusController:");
350 ESP_LOGCONFIG(TAG,
" Address: 0x%02X", this->
address_);
353 #if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE 354 ESP_LOGCONFIG(TAG,
"sensormap");
356 ESP_LOGCONFIG(TAG,
" Sensor type=%zu start=0x%X offset=0x%X count=%d size=%d",
357 static_cast<uint8_t>(it->register_type), it->start_address, it->offset, it->register_count,
358 it->get_register_size());
360 ESP_LOGCONFIG(TAG,
"ranges");
362 ESP_LOGCONFIG(TAG,
" Range type=%zu start=0x%X count=%d skip_updates=%d", static_cast<uint8_t>(it.register_type),
363 it.start_address, it.register_count, it.skip_updates);
365 ESP_LOGCONFIG(TAG,
"server registers");
367 ESP_LOGCONFIG(TAG,
" Address=0x%02X value_type=%zu register_count=%u", r->address,
368 static_cast<uint8_t>(r->value_type), r->register_count);
377 if (message !=
nullptr)
388 const std::vector<uint8_t> &data) {
389 ESP_LOGV(TAG,
"Command ACK 0x%X %d ", get_data<uint16_t>(data, 0), get_data<int16_t>(data, 1));
393 ESP_LOGV(TAG,
"sensors");
395 ESP_LOGV(TAG,
" Sensor start=0x%X count=%d size=%d offset=%d", it->start_address, it->register_count,
396 it->get_register_size(), it->offset);
402 std::function<
void(
ModbusRegisterType register_type, uint16_t start_address,
const std::vector<uint8_t> &data)>
416 uint16_t register_count) {
424 const std::vector<uint8_t> &data) {
431 uint16_t start_address, uint16_t register_count,
432 const std::vector<uint16_t> &values) {
440 const std::vector<uint8_t> &data) {
443 for (
auto v : values) {
445 cmd.
payload.push_back(decoded_value[0]);
446 cmd.
payload.push_back(decoded_value[1]);
460 const std::vector<uint8_t> &data) {
463 cmd.
payload.push_back(value ? 0xFF : 0);
469 const std::vector<bool> &values) {
477 const std::vector<uint8_t> &data) {
483 for (
auto coil : values) {
485 bitmask |= (1 << bitcounter);
488 if (bitcounter % 8 == 0) {
489 cmd.
payload.push_back(bitmask);
494 if (bitcounter % 8) {
495 cmd.
payload.push_back(bitmask);
509 const std::vector<uint8_t> &data) {
514 cmd.
payload.push_back(decoded_value[0]);
515 cmd.
payload.push_back(decoded_value[1]);
521 std::function<
void(
ModbusRegisterType register_type, uint16_t start_address,
const std::vector<uint8_t> &data)>
526 if (handler ==
nullptr) {
528 ESP_LOGI(TAG,
"Custom Command sent");
540 std::function<
void(
ModbusRegisterType register_type, uint16_t start_address,
const std::vector<uint8_t> &data)>
545 if (handler ==
nullptr) {
547 ESP_LOGI(TAG,
"Custom Command sent");
552 for (
auto v : values) {
553 cmd.
payload.push_back((v >> 8) & 0xFF);
554 cmd.
payload.push_back(v & 0xFF);
562 modbusdevice->
send(uint8_t(this->function_code), this->register_address, this->register_count, this->payload.size(),
563 this->payload.empty() ? nullptr : &this->payload[0]);
565 modbusdevice->
send_raw(this->payload);
568 ESP_LOGV(TAG,
"Command sent %d 0x%X %d send_count: %d", uint8_t(this->function_code), this->register_address,
569 this->register_count, this->send_count_);
577 ? this->payload == other.
payload 583 switch (value_type) {
586 data.push_back(value & 0xFFFF);
591 data.push_back((value & 0xFFFF0000) >> 16);
592 data.push_back(value & 0xFFFF);
597 data.push_back(value & 0xFFFF);
598 data.push_back((value & 0xFFFF0000) >> 16);
602 data.push_back((value & 0xFFFF000000000000) >> 48);
603 data.push_back((value & 0xFFFF00000000) >> 32);
604 data.push_back((value & 0xFFFF0000) >> 16);
605 data.push_back(value & 0xFFFF);
609 data.push_back(value & 0xFFFF);
610 data.push_back((value & 0xFFFF0000) >> 16);
611 data.push_back((value & 0xFFFF00000000) >> 32);
612 data.push_back((value & 0xFFFF000000000000) >> 48);
615 ESP_LOGE(TAG,
"Invalid data type for modbus number to payload conversation: %d",
616 static_cast<uint16_t>(value_type));
625 switch (sensor_value_type) {
631 value = get_data<uint32_t>(data, offset);
636 value = get_data<uint32_t>(data, offset);
637 value =
static_cast<uint32_t
>(value & 0xFFFF) << 16 | (value & 0xFFFF0000) >> 16;
648 value = get_data<uint32_t>(data, offset);
651 uint32_t sign_bit = (value & 0x8000) << 16;
653 static_cast<int32_t>(((value & 0x7FFF) << 16 | (value & 0xFFFF0000) >> 16) | sign_bit), bitmask);
658 value = get_data<uint64_t>(data, offset);
663 uint64_t tmp = get_data<uint64_t>(data, offset);
664 value = (tmp << 48) | (tmp >> 48) | ((tmp & 0xFFFF0000) << 16) | ((tmp >> 16) & 0xFFFF0000);
void queue_command(const ModbusCommandItem &command)
queues a modbus command in the send 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 3 or 4) was parsed without errors
uint8_t max_cmd_retries_
How many times we will retry a command if we get no response.
void add_on_offline_callback(std::function< void(int, int)> &&callback)
Set callback for offline changes.
bool module_offline_
if module didn't respond the last command
std::vector< ServerRegister * > server_registers_
Collection of all server registers for this component.
CallbackManager< void(int, int)> command_sent_callback_
Command sent callback.
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...
void dump_config() override
ModbusRegisterType register_type
void add_on_online_callback(std::function< void(int, int)> &&callback)
Set callback for online changes.
std::vector< uint16_t > float_to_payload(float value, SensorValueType value_type)
virtual size_t get_register_size() const
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...
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...
uint16_t command_throttle_
min time in ms between sending modbus commands
bool allow_duplicate_commands_
if duplicate commands can be sent
uint32_t last_command_timestamp_
when was the last send operation
std::vector< uint8_t > payload
ModbusRegisterType register_type
uint32_t IRAM_ATTR HOT millis()
bool waiting_for_response()
bool send_next_command_()
send the next modbus command from the send queue
SensorSet sensorset_
Collection of all sensors for this component.
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.
SensorSet find_sensors_(ModbusRegisterType register_type, uint16_t start_address) const
void add_on_command_sent_callback(std::function< void(int, int)> &&callback)
Set callback for commands.
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.
void dump_sensors_()
dump the parsed sensormap for diagnostics
void send_raw(const std::vector< uint8_t > &payload)
constexpr14 std::array< uint8_t, sizeof(T)> decode_value(T val)
Decode a value into its constituent bytes (from most to least significant).
uint16_t skip_updates_counter
void on_modbus_data(const std::vector< uint8_t > &data) override
called when a modbus response was parsed without errors
void on_modbus_error(uint8_t function_code, uint8_t exception_code) override
called when a modbus error response was received
std::function< void(ModbusRegisterType register_type, uint16_t start_address, const std::vector< uint8_t > &data)> on_data_func
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 process_modbus_data_(const ModbusCommandItem *response)
parse incoming modbus data
std::list< std::unique_ptr< ModbusCommandItem > > command_queue_
Hold the pending requests to be sent.
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
ModbusFunctionCode modbus_register_read_function(ModbusRegisterType reg_type)
CallbackManager< void(int, int)> online_callback_
Server online callback.
CallbackManager< void(int, int)> offline_callback_
Server offline callback.
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...
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.
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.
std::vector< RegisterRange > register_ranges_
Continuous range of modbus registers.
Implementation of SPI Controller mode.
uint16_t offline_skip_updates_
how many updates to skip if module is offline
void update_range_(RegisterRange &r)
submit the read command for the address range to the send queue
bool is_equal(const ModbusCommandItem &other)
void send(uint8_t function, uint16_t start_address, uint16_t number_of_entities, uint8_t payload_len=0, const uint8_t *payload=nullptr)
ModbusFunctionCode function_code
std::set< SensorItem *, SensorItemsComparator > SensorSet
std::queue< std::unique_ptr< ModbusCommandItem > > incoming_queue_
modbus response data waiting to get processed
size_t create_register_ranges_()
parse sensormap_ and create range of sequential addresses
ModbusRegisterType register_type
ModbusController * modbusdevice
uint16_t register_address
esphome::sensor::Sensor * sensor
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.