diff --git a/esphome/components/i2c/i2c.cpp b/esphome/components/i2c/i2c.cpp index 82ab7bd09a..fdc9fd1ddf 100644 --- a/esphome/components/i2c/i2c.cpp +++ b/esphome/components/i2c/i2c.cpp @@ -7,6 +7,30 @@ namespace i2c { static const char *const TAG = "i2c"; +ErrorCode I2CDevice::read_register(uint8_t a_register, uint8_t *data, size_t len, bool stop) { + ErrorCode err = this->write(&a_register, 1, stop); + if (err != ERROR_OK) + return err; + return bus_->read(address_, data, len); +} + +ErrorCode I2CDevice::write_register(uint8_t a_register, const uint8_t *data, size_t len, bool stop) { + WriteBuffer buffers[2]; + buffers[0].data = &a_register; + buffers[0].len = 1; + buffers[1].data = data; + buffers[1].len = len; + return bus_->writev(address_, buffers, 2, stop); +} + +bool I2CDevice::read_bytes_16(uint8_t a_register, uint16_t *data, uint8_t len) { + if (read_register(a_register, reinterpret_cast(data), len * 2) != ERROR_OK) + return false; + for (size_t i = 0; i < len; i++) + data[i] = i2ctohs(data[i]); + return true; +} + bool I2CDevice::write_bytes_16(uint8_t a_register, const uint16_t *data, uint8_t len) { // we have to copy in order to be able to change byte order std::unique_ptr temp{new uint16_t[len]}; diff --git a/esphome/components/i2c/i2c.h b/esphome/components/i2c/i2c.h index ffc0dadf81..780528a5c7 100644 --- a/esphome/components/i2c/i2c.h +++ b/esphome/components/i2c/i2c.h @@ -46,22 +46,10 @@ class I2CDevice { I2CRegister reg(uint8_t a_register) { return {this, a_register}; } ErrorCode read(uint8_t *data, size_t len) { return bus_->read(address_, data, len); } - ErrorCode read_register(uint8_t a_register, uint8_t *data, size_t len, bool stop = true) { - ErrorCode err = this->write(&a_register, 1, stop); - if (err != ERROR_OK) - return err; - return this->read(data, len); - } + ErrorCode read_register(uint8_t a_register, uint8_t *data, size_t len, bool stop = true); ErrorCode write(const uint8_t *data, uint8_t len, bool stop = true) { return bus_->write(address_, data, len, stop); } - ErrorCode write_register(uint8_t a_register, const uint8_t *data, size_t len, bool stop = true) { - WriteBuffer buffers[2]; - buffers[0].data = &a_register; - buffers[0].len = 1; - buffers[1].data = data; - buffers[1].len = len; - return bus_->writev(address_, buffers, 2, stop); - } + ErrorCode write_register(uint8_t a_register, const uint8_t *data, size_t len, bool stop = true); // Compat APIs @@ -85,13 +73,7 @@ class I2CDevice { return res; } - bool read_bytes_16(uint8_t a_register, uint16_t *data, uint8_t len) { - if (read_register(a_register, reinterpret_cast(data), len * 2) != ERROR_OK) - return false; - for (size_t i = 0; i < len; i++) - data[i] = i2ctohs(data[i]); - return true; - } + bool read_bytes_16(uint8_t a_register, uint16_t *data, uint8_t len); bool read_byte(uint8_t a_register, uint8_t *data, bool stop = true) { return read_register(a_register, data, 1, stop) == ERROR_OK;