Refactor Sensirion Sensors (#3374)

Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
This commit is contained in:
Martin
2022-04-13 00:19:48 +02:00
committed by GitHub
parent 99335d986e
commit d620b6dd5e
36 changed files with 484 additions and 718 deletions
+7 -58
View File
@@ -29,14 +29,14 @@ void SHTCXComponent::setup() {
this->wake_up();
this->soft_reset();
if (!this->write_command_(SHTCX_COMMAND_READ_ID_REGISTER)) {
if (!this->write_command(SHTCX_COMMAND_READ_ID_REGISTER)) {
ESP_LOGE(TAG, "Error requesting Device ID");
this->mark_failed();
return;
}
uint16_t device_id_register;
if (!this->read_data_(&device_id_register, 1)) {
if (!this->read_data(&device_id_register, 1)) {
ESP_LOGE(TAG, "Error reading Device ID");
this->mark_failed();
return;
@@ -76,7 +76,7 @@ void SHTCXComponent::update() {
if (this->type_ != SHTCX_TYPE_SHTC1) {
this->wake_up();
}
if (!this->write_command_(SHTCX_COMMAND_POLLING_H)) {
if (!this->write_command(SHTCX_COMMAND_POLLING_H)) {
ESP_LOGE(TAG, "sensor polling failed");
if (this->temperature_sensor_ != nullptr)
this->temperature_sensor_->publish_state(NAN);
@@ -90,7 +90,7 @@ void SHTCXComponent::update() {
float temperature = NAN;
float humidity = NAN;
uint16_t raw_data[2];
if (!this->read_data_(raw_data, 2)) {
if (!this->read_data(raw_data, 2)) {
ESP_LOGE(TAG, "sensor read failed");
this->status_set_warning();
} else {
@@ -110,65 +110,14 @@ void SHTCXComponent::update() {
});
}
bool SHTCXComponent::write_command_(uint16_t command) {
// Warning ugly, trick the I2Ccomponent base by setting register to the first 8 bit.
return this->write_byte(command >> 8, command & 0xFF);
}
uint8_t sht_crc(uint8_t data1, uint8_t data2) {
uint8_t bit;
uint8_t crc = 0xFF;
crc ^= data1;
for (bit = 8; bit > 0; --bit) {
if (crc & 0x80) {
crc = (crc << 1) ^ 0x131;
} else {
crc = (crc << 1);
}
}
crc ^= data2;
for (bit = 8; bit > 0; --bit) {
if (crc & 0x80) {
crc = (crc << 1) ^ 0x131;
} else {
crc = (crc << 1);
}
}
return crc;
}
bool SHTCXComponent::read_data_(uint16_t *data, uint8_t len) {
const uint8_t num_bytes = len * 3;
std::vector<uint8_t> buf(num_bytes);
if (this->read(buf.data(), num_bytes) != i2c::ERROR_OK) {
return false;
}
for (uint8_t i = 0; i < len; i++) {
const uint8_t j = 3 * i;
uint8_t crc = sht_crc(buf[j], buf[j + 1]);
if (crc != buf[j + 2]) {
ESP_LOGE(TAG, "CRC8 Checksum invalid! 0x%02X != 0x%02X", buf[j + 2], crc);
return false;
}
data[i] = (buf[j] << 8) | buf[j + 1];
}
return true;
}
void SHTCXComponent::soft_reset() {
this->write_command_(SHTCX_COMMAND_SOFT_RESET);
this->write_command(SHTCX_COMMAND_SOFT_RESET);
delayMicroseconds(200);
}
void SHTCXComponent::sleep() { this->write_command_(SHTCX_COMMAND_SLEEP); }
void SHTCXComponent::sleep() { this->write_command(SHTCX_COMMAND_SLEEP); }
void SHTCXComponent::wake_up() {
this->write_command_(SHTCX_COMMAND_WAKEUP);
this->write_command(SHTCX_COMMAND_WAKEUP);
delayMicroseconds(200);
}