Add support for SCD4X (#2217)

* Initial commit

* clang-format fixes

* Update CODEOWNERS

* clang-format fixes

* Fix merge error

* Fix missing return

Co-authored-by: Otto winter <otto@otto-winter.com>
This commit is contained in:
Stephen Tierney 2021-09-29 06:10:25 +10:00 committed by GitHub
parent 2b9054d3b2
commit af04f565cf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 424 additions and 0 deletions

View file

@ -125,6 +125,7 @@ esphome/components/restart/* @esphome/core
esphome/components/rf_bridge/* @jesserockz
esphome/components/rgbct/* @jesserockz
esphome/components/rtttl/* @glmnet
esphome/components/scd4x/* @sjtrny
esphome/components/script/* @esphome/core
esphome/components/sdm_meter/* @jesserockz @polyfaces
esphome/components/sdp3x/* @Azimath

View file

View file

@ -0,0 +1,259 @@
#include "scd4x.h"
#include "esphome/core/log.h"
namespace esphome {
namespace scd4x {
static const char *const TAG = "scd4x";
static const uint16_t SCD4X_CMD_GET_SERIAL_NUMBER = 0x3682;
static const uint16_t SCD4X_CMD_TEMPERATURE_OFFSET = 0x241d;
static const uint16_t SCD4X_CMD_ALTITUDE_COMPENSATION = 0x2427;
static const uint16_t SCD4X_CMD_AMBIENT_PRESSURE_COMPENSATION = 0xe000;
static const uint16_t SCD4X_CMD_AUTOMATIC_SELF_CALIBRATION = 0x2416;
static const uint16_t SCD4X_CMD_START_CONTINUOUS_MEASUREMENTS = 0x21b1;
static const uint16_t SCD4X_CMD_GET_DATA_READY_STATUS = 0xe4b8;
static const uint16_t SCD4X_CMD_READ_MEASUREMENT = 0xec05;
static const uint16_t SCD4X_CMD_PERFORM_FORCED_CALIBRATION = 0x362f;
static const uint16_t SCD4X_CMD_STOP_MEASUREMENTS = 0x3f86;
static const float SCD4X_TEMPERATURE_OFFSET_MULTIPLIER = (1 << 16) / 175.0f;
void SCD4XComponent::setup() {
ESP_LOGCONFIG(TAG, "Setting up scd4x...");
// the sensor needs 1000 ms to enter the idle state
this->set_timeout(1000, [this]() {
// Check if measurement is ready before reading the value
if (!this->write_command_(SCD4X_CMD_GET_DATA_READY_STATUS)) {
ESP_LOGE(TAG, "Failed to write data ready status command");
this->mark_failed();
return;
}
uint16_t raw_read_status[1];
if (!this->read_data_(raw_read_status, 1)) {
ESP_LOGE(TAG, "Failed to read data ready status");
this->mark_failed();
return;
}
// In order to query the device periodic measurement must be ceased
if (raw_read_status[0]) {
ESP_LOGD(TAG, "Sensor has data available, stopping periodic measurement");
if (!this->write_command_(SCD4X_CMD_STOP_MEASUREMENTS)) {
ESP_LOGE(TAG, "Failed to stop measurements");
this->mark_failed();
return;
}
}
if (!this->write_command_(SCD4X_CMD_GET_SERIAL_NUMBER)) {
ESP_LOGE(TAG, "Failed to write get serial command");
this->error_code_ = COMMUNICATION_FAILED;
this->mark_failed();
return;
}
uint16_t raw_serial_number[3];
if (!this->read_data_(raw_serial_number, 3)) {
ESP_LOGE(TAG, "Failed to read serial number");
this->error_code_ = SERIAL_NUMBER_IDENTIFICATION_FAILED;
this->mark_failed();
return;
}
ESP_LOGD(TAG, "Serial number %02d.%02d.%02d", (uint16_t(raw_serial_number[0]) >> 8),
uint16_t(raw_serial_number[0] & 0xFF), (uint16_t(raw_serial_number[1]) >> 8));
if (!this->write_command_(SCD4X_CMD_TEMPERATURE_OFFSET,
(uint16_t)(temperature_offset_ * SCD4X_TEMPERATURE_OFFSET_MULTIPLIER))) {
ESP_LOGE(TAG, "Error setting temperature offset.");
this->error_code_ = MEASUREMENT_INIT_FAILED;
this->mark_failed();
return;
}
// If pressure compensation available use it
// else use altitude
if (ambient_pressure_compensation_) {
if (!this->write_command_(SCD4X_CMD_AMBIENT_PRESSURE_COMPENSATION, ambient_pressure_compensation_)) {
ESP_LOGE(TAG, "Error setting ambient pressure compensation.");
this->error_code_ = MEASUREMENT_INIT_FAILED;
this->mark_failed();
return;
}
} else {
if (!this->write_command_(SCD4X_CMD_ALTITUDE_COMPENSATION, altitude_compensation_)) {
ESP_LOGE(TAG, "Error setting altitude compensation.");
this->error_code_ = MEASUREMENT_INIT_FAILED;
this->mark_failed();
return;
}
}
if (!this->write_command_(SCD4X_CMD_AUTOMATIC_SELF_CALIBRATION, enable_asc_ ? 1 : 0)) {
ESP_LOGE(TAG, "Error setting automatic self calibration.");
this->error_code_ = MEASUREMENT_INIT_FAILED;
this->mark_failed();
return;
}
// Finally start sensor measurements
if (!this->write_command_(SCD4X_CMD_START_CONTINUOUS_MEASUREMENTS)) {
ESP_LOGE(TAG, "Error starting continuous measurements.");
this->error_code_ = MEASUREMENT_INIT_FAILED;
this->mark_failed();
return;
}
initialized_ = true;
ESP_LOGD(TAG, "Sensor initialized");
});
}
void SCD4XComponent::dump_config() {
ESP_LOGCONFIG(TAG, "scd4x:");
LOG_I2C_DEVICE(this);
if (this->is_failed()) {
switch (this->error_code_) {
case COMMUNICATION_FAILED:
ESP_LOGW(TAG, "Communication failed! Is the sensor connected?");
break;
case MEASUREMENT_INIT_FAILED:
ESP_LOGW(TAG, "Measurement Initialization failed!");
break;
case SERIAL_NUMBER_IDENTIFICATION_FAILED:
ESP_LOGW(TAG, "Unable to read sensor firmware version");
break;
default:
ESP_LOGW(TAG, "Unknown setup error!");
break;
}
}
ESP_LOGCONFIG(TAG, " Automatic self calibration: %s", ONOFF(this->enable_asc_));
if (this->ambient_pressure_compensation_) {
ESP_LOGCONFIG(TAG, " Altitude compensation disabled");
ESP_LOGCONFIG(TAG, " Ambient pressure compensation: %dmBar", this->ambient_pressure_);
} else {
ESP_LOGCONFIG(TAG, " Ambient pressure compensation disabled");
ESP_LOGCONFIG(TAG, " Altitude compensation: %dm", this->altitude_compensation_);
}
ESP_LOGCONFIG(TAG, " Temperature offset: %.2f °C", this->temperature_offset_);
LOG_UPDATE_INTERVAL(this);
LOG_SENSOR(" ", "CO2", this->co2_sensor_);
LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
}
void SCD4XComponent::update() {
if (!initialized_) {
return;
}
// Check if data is ready
if (!this->write_command_(SCD4X_CMD_GET_DATA_READY_STATUS)) {
this->status_set_warning();
return;
}
uint16_t raw_read_status[1];
if (!this->read_data_(raw_read_status, 1) || raw_read_status[0] == 0x00) {
this->status_set_warning();
ESP_LOGW(TAG, "Data not ready yet!");
return;
}
if (!this->write_command_(SCD4X_CMD_READ_MEASUREMENT)) {
ESP_LOGW(TAG, "Error reading measurement!");
this->status_set_warning();
return;
}
// Read off sensor data
uint16_t raw_data[3];
if (!this->read_data_(raw_data, 3)) {
this->status_set_warning();
return;
}
if (this->co2_sensor_ != nullptr)
this->co2_sensor_->publish_state(raw_data[0]);
if (this->temperature_sensor_ != nullptr) {
const float temperature = -45.0f + (175.0f * (raw_data[1])) / (1 << 16);
this->temperature_sensor_->publish_state(temperature);
}
if (this->humidity_sensor_ != nullptr) {
const float humidity = (100.0f * raw_data[2]) / (1 << 16);
this->humidity_sensor_->publish_state(humidity);
}
this->status_clear_warning();
}
uint8_t SCD4XComponent::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 SCD4XComponent::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;
}
bool SCD4XComponent::write_command_(uint16_t command) {
const uint8_t num_bytes = 2;
uint8_t buffer[num_bytes];
buffer[0] = (command >> 8);
buffer[1] = command & 0xff;
return this->write(buffer, num_bytes) == i2c::ERROR_OK;
}
bool SCD4XComponent::write_command_(uint16_t command, uint16_t data) {
uint8_t raw[5];
raw[0] = command >> 8;
raw[1] = command & 0xFF;
raw[2] = data >> 8;
raw[3] = data & 0xFF;
raw[4] = sht_crc_(raw[2], raw[3]);
return this->write(raw, 5) == i2c::ERROR_OK;
}
} // namespace scd4x
} // namespace esphome

View file

@ -0,0 +1,53 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/i2c/i2c.h"
namespace esphome {
namespace scd4x {
enum ERRORCODE { COMMUNICATION_FAILED, SERIAL_NUMBER_IDENTIFICATION_FAILED, MEASUREMENT_INIT_FAILED, UNKNOWN };
class SCD4XComponent : public PollingComponent, public i2c::I2CDevice {
public:
float get_setup_priority() const override { return setup_priority::DATA; }
void setup() override;
void dump_config() override;
void update() override;
void set_automatic_self_calibration(bool asc) { enable_asc_ = asc; }
void set_altitude_compensation(uint16_t altitude) { altitude_compensation_ = altitude; }
void set_ambient_pressure_compensation(float pressure) {
ambient_pressure_compensation_ = true;
ambient_pressure_ = (uint16_t)(pressure * 1000);
}
void set_temperature_offset(float offset) { temperature_offset_ = offset; };
void set_co2_sensor(sensor::Sensor *co2) { co2_sensor_ = co2; }
void set_temperature_sensor(sensor::Sensor *temperature) { temperature_sensor_ = temperature; };
void set_humidity_sensor(sensor::Sensor *humidity) { humidity_sensor_ = humidity; }
protected:
uint8_t sht_crc_(uint8_t data1, uint8_t data2);
bool read_data_(uint16_t *data, uint8_t len);
bool write_command_(uint16_t command);
bool write_command_(uint16_t command, uint16_t data);
ERRORCODE error_code_;
bool initialized_{false};
float temperature_offset_;
uint16_t altitude_compensation_;
bool ambient_pressure_compensation_;
uint16_t ambient_pressure_;
bool enable_asc_;
sensor::Sensor *co2_sensor_{nullptr};
sensor::Sensor *temperature_sensor_{nullptr};
sensor::Sensor *humidity_sensor_{nullptr};
};
} // namespace scd4x
} // namespace esphome

View file

@ -0,0 +1,98 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import i2c, sensor
from esphome.const import (
CONF_ID,
CONF_CO2,
CONF_HUMIDITY,
CONF_TEMPERATURE,
DEVICE_CLASS_CARBON_DIOXIDE,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
STATE_CLASS_MEASUREMENT,
UNIT_PARTS_PER_MILLION,
ICON_MOLECULE_CO2,
ICON_THERMOMETER,
ICON_WATER_PERCENT,
UNIT_CELSIUS,
UNIT_PERCENT,
)
CODEOWNERS = ["@sjtrny"]
DEPENDENCIES = ["i2c"]
scd4x_ns = cg.esphome_ns.namespace("scd4x")
SCD4XComponent = scd4x_ns.class_("SCD4XComponent", cg.PollingComponent, i2c.I2CDevice)
CONF_AUTOMATIC_SELF_CALIBRATION = "automatic_self_calibration"
CONF_ALTITUDE_COMPENSATION = "altitude_compensation"
CONF_AMBIENT_PRESSURE_COMPENSATION = "ambient_pressure_compensation"
CONF_TEMPERATURE_OFFSET = "temperature_offset"
CONFIG_SCHEMA = (
cv.Schema(
{
cv.GenerateID(): cv.declare_id(SCD4XComponent),
cv.Optional(CONF_CO2): sensor.sensor_schema(
unit_of_measurement=UNIT_PARTS_PER_MILLION,
icon=ICON_MOLECULE_CO2,
accuracy_decimals=0,
device_class=DEVICE_CLASS_CARBON_DIOXIDE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_TEMPERATURE): sensor.sensor_schema(
unit_of_measurement=UNIT_CELSIUS,
icon=ICON_THERMOMETER,
accuracy_decimals=2,
device_class=DEVICE_CLASS_TEMPERATURE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_HUMIDITY): sensor.sensor_schema(
unit_of_measurement=UNIT_PERCENT,
icon=ICON_WATER_PERCENT,
accuracy_decimals=2,
device_class=DEVICE_CLASS_HUMIDITY,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_AUTOMATIC_SELF_CALIBRATION, default=True): cv.boolean,
cv.Optional(CONF_ALTITUDE_COMPENSATION, default="0m"): cv.All(
cv.float_with_unit("altitude", "(m|m a.s.l.|MAMSL|MASL)"),
cv.int_range(min=0, max=0xFFFF, max_included=False),
),
cv.Optional(CONF_AMBIENT_PRESSURE_COMPENSATION): cv.pressure,
cv.Optional(CONF_TEMPERATURE_OFFSET, default="4°C"): cv.temperature,
}
)
.extend(cv.polling_component_schema("60s"))
.extend(i2c.i2c_device_schema(0x62))
)
SENSOR_MAP = {
CONF_CO2: "set_co2_sensor",
CONF_TEMPERATURE: "set_temperature_sensor",
CONF_HUMIDITY: "set_humidity_sensor",
}
SETTING_MAP = {
CONF_AUTOMATIC_SELF_CALIBRATION: "set_automatic_self_calibration",
CONF_ALTITUDE_COMPENSATION: "set_altitude_compensation",
CONF_AMBIENT_PRESSURE_COMPENSATION: "set_ambient_pressure_compensation",
CONF_TEMPERATURE_OFFSET: "set_temperature_offset",
}
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
await i2c.register_i2c_device(var, config)
for key, funcName in SETTING_MAP.items():
if key in config:
cg.add(getattr(var, funcName)(config[key]))
for key, funcName in SENSOR_MAP.items():
if key in config:
sens = await sensor.new_sensor(config[key])
cg.add(getattr(var, funcName)(sens))

View file

@ -811,6 +811,19 @@ sensor:
ambient_pressure_compensation: 961mBar
temperature_offset: 4.2C
i2c_id: i2c_bus
- platform: scd4x
co2:
name: "SCD4X CO2"
temperature:
name: "SCD4X Temperature"
humidity:
name: "SCD4X Humidity"
update_interval: 15s
automatic_self_calibration: true
altitude_compensation: 10m
ambient_pressure_compensation: 961mBar
temperature_offset: 4.2C
i2c_id: i2c_bus
- platform: sgp30
eco2:
name: 'Workshop eCO2'