ESPHome 2025.12.0-dev
Loading...
Searching...
No Matches
modbus.cpp
Go to the documentation of this file.
1#include "modbus.h"
4#include "esphome/core/log.h"
5
6namespace esphome {
7namespace modbus {
8
9static const char *const TAG = "modbus";
10
12 if (this->flow_control_pin_ != nullptr) {
13 this->flow_control_pin_->setup();
14 }
15}
17 const uint32_t now = App.get_loop_component_start_time();
18
19 while (this->available()) {
20 uint8_t byte;
21 this->read_byte(&byte);
22 if (this->parse_modbus_byte_(byte)) {
23 this->last_modbus_byte_ = now;
24 } else {
25 size_t at = this->rx_buffer_.size();
26 if (at > 0) {
27 ESP_LOGV(TAG, "Clearing buffer of %d bytes - parse failed", at);
28 this->rx_buffer_.clear();
29 }
30 }
31 }
32
33 if (now - this->last_modbus_byte_ > 50) {
34 size_t at = this->rx_buffer_.size();
35 if (at > 0) {
36 ESP_LOGV(TAG, "Clearing buffer of %d bytes - timeout", at);
37 this->rx_buffer_.clear();
38 }
39
40 // stop blocking new send commands after sent_wait_time_ ms after response received
41 if (now - this->last_send_ > send_wait_time_) {
42 if (waiting_for_response > 0) {
43 ESP_LOGV(TAG, "Stop waiting for response from %d", waiting_for_response);
44 }
46 }
47 }
48}
49
50bool Modbus::parse_modbus_byte_(uint8_t byte) {
51 size_t at = this->rx_buffer_.size();
52 this->rx_buffer_.push_back(byte);
53 const uint8_t *raw = &this->rx_buffer_[0];
54 ESP_LOGVV(TAG, "Modbus received Byte %d (0X%x)", byte, byte);
55 // Byte 0: modbus address (match all)
56 if (at == 0)
57 return true;
58 uint8_t address = raw[0];
59 uint8_t function_code = raw[1];
60 // Byte 2: Size (with modbus rtu function code 4/3)
61 // See also https://en.wikipedia.org/wiki/Modbus
62 if (at == 2)
63 return true;
64
65 uint8_t data_len = raw[2];
66 uint8_t data_offset = 3;
67
68 // Per https://modbus.org/docs/Modbus_Application_Protocol_V1_1b3.pdf Ch 5 User-Defined function codes
69 if (((function_code >= FUNCTION_CODE_USER_DEFINED_SPACE_1_INIT) &&
70 (function_code <= FUNCTION_CODE_USER_DEFINED_SPACE_1_END)) ||
71 ((function_code >= FUNCTION_CODE_USER_DEFINED_SPACE_2_INIT) &&
72 (function_code <= FUNCTION_CODE_USER_DEFINED_SPACE_2_END))) {
73 // Handle user-defined function, since we don't know how big this ought to be,
74 // ideally we should delegate the entire length detection to whatever handler is
75 // installed, but wait, there is the CRC, and if we get a hit there is a good
76 // chance that this is a complete message ... admittedly there is a small chance is
77 // isn't but that is quite small given the purpose of the CRC in the first place
78
79 // Fewer than 2 bytes can't calc CRC
80 if (at < 2)
81 return true;
82
83 data_len = at - 2;
84 data_offset = 1;
85
86 uint16_t computed_crc = crc16(raw, data_offset + data_len);
87 uint16_t remote_crc = uint16_t(raw[data_offset + data_len]) | (uint16_t(raw[data_offset + data_len + 1]) << 8);
88
89 if (computed_crc != remote_crc)
90 return true;
91
92 ESP_LOGD(TAG, "Modbus user-defined function %02X found", function_code);
93
94 } else {
95 // data starts at 2 and length is 4 for read registers commands
96 if (this->role == ModbusRole::SERVER) {
97 if (function_code == ModbusFunctionCode::READ_COILS ||
102 data_offset = 2;
103 data_len = 4;
104 } else if (function_code == ModbusFunctionCode::WRITE_MULTIPLE_REGISTERS) {
105 if (at < 6) {
106 return true;
107 }
108 data_offset = 2;
109 // starting address (2 bytes) + quantity of registers (2 bytes) + byte count itself (1 byte) + actual byte count
110 data_len = 2 + 2 + 1 + raw[6];
111 }
112 } else {
113 // the response for write command mirrors the requests and data starts at offset 2 instead of 3 for read commands
114 if (function_code == ModbusFunctionCode::WRITE_SINGLE_COIL ||
118 data_offset = 2;
119 data_len = 4;
120 }
121 }
122
123 // Error ( msb indicates error )
124 // response format: Byte[0] = device address, Byte[1] function code | 0x80 , Byte[2] exception code, Byte[3-4] crc
126 data_offset = 2;
127 data_len = 1;
128 }
129
130 // Byte data_offset..data_offset+data_len-1: Data
131 if (at < data_offset + data_len)
132 return true;
133
134 // Byte 3+data_len: CRC_LO (over all bytes)
135 if (at == data_offset + data_len)
136 return true;
137
138 // Byte data_offset+len+1: CRC_HI (over all bytes)
139 uint16_t computed_crc = crc16(raw, data_offset + data_len);
140 uint16_t remote_crc = uint16_t(raw[data_offset + data_len]) | (uint16_t(raw[data_offset + data_len + 1]) << 8);
141 if (computed_crc != remote_crc) {
142 if (this->disable_crc_) {
143 ESP_LOGD(TAG, "Modbus CRC Check failed, but ignored! %02X!=%02X", computed_crc, remote_crc);
144 } else {
145 ESP_LOGW(TAG, "Modbus CRC Check failed! %02X!=%02X", computed_crc, remote_crc);
146 return false;
147 }
148 }
149 }
150 std::vector<uint8_t> data(this->rx_buffer_.begin() + data_offset, this->rx_buffer_.begin() + data_offset + data_len);
151 bool found = false;
152 for (auto *device : this->devices_) {
153 if (device->address_ == address) {
154 found = true;
155 // Is it an error response?
157 ESP_LOGD(TAG, "Modbus error function code: 0x%X exception: %d", function_code, raw[2]);
158 if (waiting_for_response != 0) {
159 device->on_modbus_error(function_code & FUNCTION_CODE_MASK, raw[2]);
160 } else {
161 // Ignore modbus exception not related to a pending command
162 ESP_LOGD(TAG, "Ignoring Modbus error - not expecting a response");
163 }
164 continue;
165 }
166 if (this->role == ModbusRole::SERVER) {
167 if (function_code == ModbusFunctionCode::READ_HOLDING_REGISTERS ||
169 device->on_modbus_read_registers(function_code, uint16_t(data[1]) | (uint16_t(data[0]) << 8),
170 uint16_t(data[3]) | (uint16_t(data[2]) << 8));
171 continue;
172 }
173 if (function_code == ModbusFunctionCode::WRITE_SINGLE_REGISTER ||
175 device->on_modbus_write_registers(function_code, data);
176 continue;
177 }
178 }
179 // fallthrough for other function codes
180 device->on_modbus_data(data);
181 }
182 }
184
185 if (!found) {
186 ESP_LOGW(TAG, "Got Modbus frame from unknown address 0x%02X! ", address);
187 }
188
189 // reset buffer
190 ESP_LOGV(TAG, "Clearing buffer of %d bytes - parse succeeded", at);
191 this->rx_buffer_.clear();
192 return true;
193}
194
196 ESP_LOGCONFIG(TAG, "Modbus:");
197 LOG_PIN(" Flow Control Pin: ", this->flow_control_pin_);
198 ESP_LOGCONFIG(TAG,
199 " Send Wait Time: %d ms\n"
200 " CRC Disabled: %s",
201 this->send_wait_time_, YESNO(this->disable_crc_));
202}
204 // After UART bus
205 return setup_priority::BUS - 1.0f;
206}
207
208void Modbus::send(uint8_t address, uint8_t function_code, uint16_t start_address, uint16_t number_of_entities,
209 uint8_t payload_len, const uint8_t *payload) {
210 static const size_t MAX_VALUES = 128;
211
212 // Only check max number of registers for standard function codes
213 // Some devices use non standard codes like 0x43
214 if (number_of_entities > MAX_VALUES && function_code <= ModbusFunctionCode::WRITE_MULTIPLE_REGISTERS) {
215 ESP_LOGE(TAG, "send too many values %d max=%zu", number_of_entities, MAX_VALUES);
216 return;
217 }
218
219 std::vector<uint8_t> data;
220 data.push_back(address);
221 data.push_back(function_code);
222 if (this->role == ModbusRole::CLIENT) {
223 data.push_back(start_address >> 8);
224 data.push_back(start_address >> 0);
225 if (function_code != ModbusFunctionCode::WRITE_SINGLE_COIL &&
227 data.push_back(number_of_entities >> 8);
228 data.push_back(number_of_entities >> 0);
229 }
230 }
231
232 if (payload != nullptr) {
233 if (this->role == ModbusRole::SERVER || function_code == ModbusFunctionCode::WRITE_MULTIPLE_COILS ||
234 function_code == ModbusFunctionCode::WRITE_MULTIPLE_REGISTERS) { // Write multiple
235 data.push_back(payload_len); // Byte count is required for write
236 } else {
237 payload_len = 2; // Write single register or coil
238 }
239 for (int i = 0; i < payload_len; i++) {
240 data.push_back(payload[i]);
241 }
242 }
243
244 auto crc = crc16(data.data(), data.size());
245 data.push_back(crc >> 0);
246 data.push_back(crc >> 8);
247
248 if (this->flow_control_pin_ != nullptr)
249 this->flow_control_pin_->digital_write(true);
250
251 this->write_array(data);
252 this->flush();
253
254 if (this->flow_control_pin_ != nullptr)
255 this->flow_control_pin_->digital_write(false);
257 last_send_ = millis();
258 ESP_LOGV(TAG, "Modbus write: %s", format_hex_pretty(data).c_str());
259}
260
261// Helper function for lambdas
262// Send raw command. Except CRC everything must be contained in payload
263void Modbus::send_raw(const std::vector<uint8_t> &payload) {
264 if (payload.empty()) {
265 return;
266 }
267
268 if (this->flow_control_pin_ != nullptr)
269 this->flow_control_pin_->digital_write(true);
270
271 auto crc = crc16(payload.data(), payload.size());
272 this->write_array(payload);
273 this->write_byte(crc & 0xFF);
274 this->write_byte((crc >> 8) & 0xFF);
275 this->flush();
276 if (this->flow_control_pin_ != nullptr)
277 this->flow_control_pin_->digital_write(false);
278 waiting_for_response = payload[0];
279 ESP_LOGV(TAG, "Modbus write raw: %s", format_hex_pretty(payload).c_str());
280 last_send_ = millis();
281}
282
283} // namespace modbus
284} // namespace esphome
uint8_t address
Definition bl0906.h:4
uint8_t raw[35]
Definition bl0939.h:0
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
virtual void setup()=0
virtual void digital_write(bool value)=0
bool parse_modbus_byte_(uint8_t byte)
Definition modbus.cpp:50
void send_raw(const std::vector< uint8_t > &payload)
Definition modbus.cpp:263
void setup() override
Definition modbus.cpp:11
uint16_t send_wait_time_
Definition modbus.h:49
uint8_t waiting_for_response
Definition modbus.h:39
uint32_t last_modbus_byte_
Definition modbus.h:52
GPIOPin * flow_control_pin_
Definition modbus.h:46
std::vector< ModbusDevice * > devices_
Definition modbus.h:54
void loop() override
Definition modbus.cpp:16
float get_setup_priority() const override
Definition modbus.cpp:203
void dump_config() override
Definition modbus.cpp:195
std::vector< uint8_t > rx_buffer_
Definition modbus.h:51
void send(uint8_t address, uint8_t function_code, uint16_t start_address, uint16_t number_of_entities, uint8_t payload_len=0, const uint8_t *payload=nullptr)
Definition modbus.cpp:208
bool read_byte(uint8_t *data)
Definition uart.h:35
void write_byte(uint8_t data)
Definition uart.h:19
void write_array(const uint8_t *data, size_t len)
Definition uart.h:27
const uint8_t FUNCTION_CODE_MASK
const uint8_t FUNCTION_CODE_EXCEPTION_MASK
const uint8_t FUNCTION_CODE_USER_DEFINED_SPACE_2_INIT
const uint8_t FUNCTION_CODE_USER_DEFINED_SPACE_1_INIT
Modbus definitions from specs: https://modbus.org/docs/Modbus_Application_Protocol_V1_1b3....
const uint8_t FUNCTION_CODE_USER_DEFINED_SPACE_2_END
const uint8_t FUNCTION_CODE_USER_DEFINED_SPACE_1_END
const float BUS
For communication buses like i2c/spi.
Definition component.cpp:56
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
uint16_t crc16(const uint8_t *data, uint16_t len, uint16_t crc, uint16_t reverse_poly, bool refin, bool refout)
Calculate a CRC-16 checksum of data with size len.
Definition helpers.cpp:72
std::string format_hex_pretty(const uint8_t *data, size_t length, char separator, bool show_length)
Format a byte array in pretty-printed, human-readable hex format.
Definition helpers.cpp:317
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:30
Application App
Global storage of Application pointer - only one Application can exist.