ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
i2c_bus_host.cpp
Go to the documentation of this file.
1#ifdef USE_HOST
2#if defined(__linux__)
3
4#include "i2c_bus_host.h"
6#include "esphome/core/log.h"
7
8#include <fcntl.h>
9#include <linux/i2c-dev.h>
10#include <linux/i2c.h>
11#include <sys/ioctl.h>
12#include <unistd.h>
13#include <cerrno>
14#include <cstdint>
15#include <cstring>
16
17namespace esphome::i2c {
18
19ESPHOME_LOG_TAG(TAG, "i2c");
20
22 if (this->file_descriptor_ != -1) {
23 close(this->file_descriptor_);
24 this->file_descriptor_ = -1;
25 }
26}
27
29 ESP_LOGCONFIG(TAG, "Setting up I2C bus...");
30
31 // Open I2C device file
32 this->file_descriptor_ = open(this->device_.c_str(), O_RDWR);
33 if (this->file_descriptor_ == -1) {
34 int err = errno;
35 if (err == ENOENT) {
36 this->update_error_("not found");
37 } else if (err == EACCES) {
38 this->update_error_("permission denied");
39 } else {
40 this->update_error_(std::string("failed to open: ") + strerror(err));
41 }
42 this->mark_failed();
43 return;
44 }
45
46 this->initialized_ = true;
47 ESP_LOGCONFIG(TAG, " Device: %s", this->device_.c_str());
48
49 // Run bus scan if enabled
50 if (this->scan_) {
51 this->i2c_scan_();
52 }
53}
54
56 ESP_LOGCONFIG(TAG, "I2C Bus:");
57 ESP_LOGCONFIG(TAG, " Device: %s", this->device_.c_str());
58 // Bus frequency cannot be set from userspace via i2c-dev; report it as informational only
59 ESP_LOGCONFIG(TAG, " Frequency: %u Hz (informational; not applied on host)", this->frequency_);
60
61 if (!this->first_error_.empty()) {
62 ESP_LOGE(TAG, " Setup Error: %s", this->first_error_.c_str());
63 }
64
65 this->dump_scan_results_();
66}
67
68ErrorCode HostI2CBus::write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count,
69 uint8_t *read_buffer, size_t read_count) {
70 if (!this->initialized_) {
71 ESP_LOGE(TAG, "I2C bus not initialized");
73 }
74
75 ESP_LOGVV(TAG, "I2C write_readv addr=0x%02X write=%zu read=%zu", address, write_count, read_count);
76
77 // Handle special case: probe (no write data, no read data)
78 // This is used for device detection during bus scanning
79 if (write_count == 0 && read_count == 0) {
80 struct i2c_msg msg;
81 msg.addr = address;
82 msg.flags = 0;
83 msg.len = 0;
84 msg.buf = nullptr;
85
86 struct i2c_rdwr_ioctl_data rdwr_data;
87 rdwr_data.msgs = &msg;
88 rdwr_data.nmsgs = 1;
89
90 int ret = ioctl(this->file_descriptor_, I2C_RDWR, &rdwr_data);
91 if (ret < 0) {
92 int err = errno;
93 // If I2C_RDWR not supported, try SMBus Quick command (what i2cdetect uses)
94 if (err == EOPNOTSUPP || err == ENOSYS) {
95 ESP_LOGVV(TAG, "I2C_RDWR probe failed, trying SMBus Quick for addr=0x%02X", address);
96 if (ioctl(this->file_descriptor_, I2C_SLAVE, address) < 0) { // NOLINT
97 return this->map_errno_to_error_code_(errno);
98 }
99 // Use I2C_SMBUS ioctl with Quick command
100 union i2c_smbus_data data;
101 struct i2c_smbus_ioctl_data args;
102 args.read_write = I2C_SMBUS_WRITE;
103 args.command = 0;
104 args.size = I2C_SMBUS_QUICK;
105 args.data = &data;
106 ret = ioctl(this->file_descriptor_, I2C_SMBUS, &args);
107 if (ret < 0) {
108 return this->map_errno_to_error_code_(errno);
109 }
110 return ERROR_OK;
111 }
112 return this->map_errno_to_error_code_(err);
113 }
114 return ERROR_OK;
115 }
116
117 // i2c_msg.len is a 16-bit field; reject transfers that would silently truncate
118 if (write_count > UINT16_MAX || read_count > UINT16_MAX) {
119 ESP_LOGE(TAG, "I2C transfer too large: write=%zu read=%zu (max %u)", write_count, read_count,
120 (unsigned) UINT16_MAX);
121 return ERROR_TOO_LARGE;
122 }
123
124 // Prepare messages for combined write-read transaction
125 struct i2c_msg msgs[2];
126 int num_msgs = 0;
127
128 // Add write message if write data present
129 if (write_count > 0) {
130 msgs[num_msgs].addr = address;
131 msgs[num_msgs].flags = 0; // Write
132 msgs[num_msgs].len = write_count;
133 msgs[num_msgs].buf = const_cast<uint8_t *>(write_buffer);
134 num_msgs++;
135 }
136
137 // Add read message if read data requested
138 if (read_count > 0) {
139 msgs[num_msgs].addr = address;
140 msgs[num_msgs].flags = I2C_M_RD; // Read
141 msgs[num_msgs].len = read_count;
142 msgs[num_msgs].buf = read_buffer;
143 num_msgs++;
144 }
145
146 // Execute I2C transaction
147 struct i2c_rdwr_ioctl_data rdwr_data;
148 rdwr_data.msgs = msgs;
149 rdwr_data.nmsgs = num_msgs;
150
151 int ret = ioctl(this->file_descriptor_, I2C_RDWR, &rdwr_data);
152 if (ret < 0) {
153 int err = errno;
154 if (err == EOPNOTSUPP || err == ENOSYS) {
155 ESP_LOGV(TAG, "I2C_RDWR not supported, using I2C_SLAVE fallback for addr=0x%02X", address); // NOLINT
156 if (ioctl(this->file_descriptor_, I2C_SLAVE, address) < 0) { // NOLINT
157 ESP_LOGV(TAG, "I2C_SLAVE ioctl failed: %s", strerror(errno)); // NOLINT
158 return this->map_errno_to_error_code_(errno);
159 }
160 // Perform write if needed
161 if (write_count > 0) {
162 ssize_t written = ::write(this->file_descriptor_, write_buffer, write_count);
163 if (written != (ssize_t) write_count) {
164 int write_err = errno;
165 // If write() also fails with EOPNOTSUPP, try I2C_SMBUS as last resort
166 if (write_err == EOPNOTSUPP || write_err == ENOSYS) {
167 ESP_LOGV(TAG, "I2C_SLAVE write not supported, trying I2C_SMBUS for addr=0x%02X", address); // NOLINT
168 // Use I2C_SMBUS_I2C_BLOCK_DATA for writes up to 32 bytes
169 // Standard SMBus mapping: first byte is command, remaining bytes are data
170 if (write_count < 1) {
171 ESP_LOGE(TAG, "Write size too small for I2C_SMBUS");
173 }
174 if (write_count > I2C_SMBUS_BLOCK_MAX + 1) {
175 ESP_LOGE(TAG, "Write size %zu exceeds I2C_SMBUS_BLOCK_MAX+1 (%d)", write_count, I2C_SMBUS_BLOCK_MAX + 1);
177 }
178 union i2c_smbus_data data;
179 // Standard SMBus: first byte = command, rest = data
180 uint8_t command = write_buffer[0];
181 size_t data_len = write_count - 1;
182 data.block[0] = data_len;
183 if (data_len > 0) {
184 memcpy(&data.block[1], write_buffer + 1, data_len);
185 }
186
187 struct i2c_smbus_ioctl_data args;
188 args.read_write = I2C_SMBUS_WRITE;
189 args.command = command;
190 args.size = I2C_SMBUS_I2C_BLOCK_DATA;
191 args.data = &data;
192
193 ret = ioctl(this->file_descriptor_, I2C_SMBUS, &args);
194 if (ret < 0) {
195 ESP_LOGV(TAG, "I2C_SMBUS write failed: %s", strerror(errno));
196 return this->map_errno_to_error_code_(errno);
197 }
198 } else {
199 ESP_LOGV(TAG, "I2C write failed: %s", strerror(write_err));
200 return this->map_errno_to_error_code_(write_err);
201 }
202 }
203 }
204 // Perform read if needed
205 if (read_count > 0) {
206 ssize_t bytes_read = ::read(this->file_descriptor_, read_buffer, read_count);
207 if (bytes_read != (ssize_t) read_count) {
208 int read_err = errno;
209 // If read() also fails with EOPNOTSUPP, try I2C_SMBUS as last resort
210 if (read_err == EOPNOTSUPP || read_err == ENOSYS) {
211 ESP_LOGV(TAG, "I2C_SLAVE read not supported, trying I2C_SMBUS for addr=0x%02X", address); // NOLINT
212 // Use I2C_SMBUS_I2C_BLOCK_DATA for reads up to 32 bytes
213 if (read_count > I2C_SMBUS_BLOCK_MAX) {
214 ESP_LOGE(TAG, "Read size %zu exceeds I2C_SMBUS_BLOCK_MAX (%d)", read_count, I2C_SMBUS_BLOCK_MAX);
216 }
217 union i2c_smbus_data data;
218 data.block[0] = read_count;
219
220 struct i2c_smbus_ioctl_data args;
221 args.read_write = I2C_SMBUS_READ;
222 args.command = 0; // Start register/command
223 args.size = I2C_SMBUS_I2C_BLOCK_DATA;
224 args.data = &data;
225
226 ret = ioctl(this->file_descriptor_, I2C_SMBUS, &args);
227 if (ret < 0) {
228 ESP_LOGV(TAG, "I2C_SMBUS read failed: %s", strerror(errno));
229 return this->map_errno_to_error_code_(errno);
230 }
231 // I2C_SMBUS_I2C_BLOCK_DATA returns the actual byte count in block[0];
232 // a short read means we did not receive all requested bytes
233 if (data.block[0] < read_count) {
234 ESP_LOGV(TAG, "I2C_SMBUS short read: got %u, expected %zu", data.block[0], read_count);
236 }
237 // Copy data from SMBus buffer to output buffer
238 memcpy(read_buffer, &data.block[1], read_count);
239 } else {
240 ESP_LOGV(TAG, "I2C read failed: %s", strerror(read_err));
241 return this->map_errno_to_error_code_(read_err);
242 }
243 }
244 }
245 ESP_LOGVV(TAG, "I2C transaction successful (I2C_SLAVE method)"); // NOLINT
246 return ERROR_OK;
247 }
248 ESP_LOGV(TAG, "I2C transaction failed: %s", strerror(err));
249 return this->map_errno_to_error_code_(err);
250 }
251
252 ESP_LOGVV(TAG, "I2C transaction successful");
253 return ERROR_OK;
254}
255
257 switch (err) {
258 case ENXIO:
260 case ETIMEDOUT:
261 return ERROR_TIMEOUT;
262 case EINVAL:
264 case ENODEV:
265 case ENOTTY:
267 case EOPNOTSUPP:
268 case ENOSYS:
269 // Operation not supported - some I2C adapters don't support zero-length transactions
270 ESP_LOGVV(TAG, "I2C adapter does not support this operation (likely zero-length probe)");
272 default:
273 ESP_LOGV(TAG, "Unmapped error code: %d (%s)", err, strerror(err));
274 return ERROR_UNKNOWN;
275 }
276}
277
278void HostI2CBus::update_error_(const std::string &error) {
279 if (this->first_error_.empty()) {
280 this->first_error_ = error;
281 }
282 ESP_LOGE(TAG, "[%s] %s", this->device_.c_str(), error.c_str());
283}
284
285} // namespace esphome::i2c
286
287#else
288#error "HostI2CBus is only supported on Linux"
289#endif // defined(__linux__)
290#endif // USE_HOST
void mark_failed()
Mark this component as failed.
ErrorCode map_errno_to_error_code_(int err)
void update_error_(const std::string &error)
ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer, size_t read_count) override
void dump_config() override
bool scan_
Should we scan ? Can be set in the yaml.
Definition i2c_bus.h:73
void dump_scan_results_()
Logs the scan results at config level, if the bus was scanned.
Definition i2c.cpp:24
ErrorCode write(uint8_t address, const uint8_t *buffer, size_t len, bool stop=true)
Definition i2c_bus.h:53
void i2c_scan_()
Scans the I2C bus for devices.
Definition i2c.cpp:11
ErrorCode read(uint8_t address, uint8_t *buffer, size_t len)
Definition i2c_bus.h:49
__int64 ssize_t
Definition httplib.h:178
int ret
ErrorCode
Error codes returned by I2CBus and I2CDevice methods.
Definition i2c_bus.h:13
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:15
@ ERROR_TOO_LARGE
requested a transfer larger than buffers can hold
Definition i2c_bus.h:20
@ ERROR_INVALID_ARGUMENT
method called invalid argument(s)
Definition i2c_bus.h:16
@ ERROR_TIMEOUT
timeout while waiting to receive bytes
Definition i2c_bus.h:18
@ ERROR_NOT_ACKNOWLEDGED
I2C bus acknowledgment not received.
Definition i2c_bus.h:17
@ ERROR_NOT_INITIALIZED
call method to a not initialized bus
Definition i2c_bus.h:19
@ ERROR_UNKNOWN
miscellaneous I2C error during execution
Definition i2c_bus.h:21
ESPHOME_LOG_TAG(TAG, "i2c")
int written
Definition helpers.h:1340