ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
stcc4.cpp
Go to the documentation of this file.
1#include <cstdint>
2
3#include "stcc4.h"
4#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
6
7namespace esphome::stcc4 {
8
9ESPHOME_LOG_TAG(TAG, "stcc4");
10
11// I2C Commands
12static constexpr uint16_t STCC4_CMD_START_CONTINUOUS_MEASUREMENT = 0x218b;
13static constexpr uint16_t STCC4_CMD_STOP_CONTINUOUS_MEASUREMENT = 0x3f86;
14static constexpr uint16_t STCC4_CMD_MEASURE_SINGLE_SHOT = 0x219d;
15static constexpr uint16_t STCC4_CMD_READ_MEASUREMENT = 0xec05;
16static constexpr uint16_t STCC4_CMD_GET_PRODUCT_ID = 0x365b;
17static constexpr uint16_t STCC4_CMD_SET_RHT_COMPENSATION = 0xe000;
18static constexpr uint16_t STCC4_CMD_SET_PRESSURE_COMPENSATION = 0xe016;
19
20// Exit sleep is an 8-bit command (single byte 0x00), not 16-bit
21static constexpr uint8_t STCC4_CMD_EXIT_SLEEP_MODE = 0x00;
22
23static constexpr uint32_t STCC4_PRODUCT_ID = 0x0901018a;
24
25// Timeout for determining when the device is ready for use, in milliseconds.
26// While waiting for the previous measurement to finish, the device will NACK all I2C requests
27// and it can take up to 1200 ms for the operation to complete according to the datasheet.
28static constexpr uint32_t READY_TIMEOUT_MS = 1200;
29
30// Poll interval for determining when the device is ready for use, in milliseconds.
31static constexpr uint32_t READY_POLL_INTERVAL_MS = 100;
32
33// Convert units the the device's representation according to the datasheet.
34constexpr uint16_t temperature_in_c_to_ticks(float temperature_in_c) {
35 return uint16_t((std::clamp(temperature_in_c, -45.f, 130.f) + 45.f) * 65535.f / 175.f);
36}
37
38constexpr float temperature_in_ticks_to_c(uint16_t temperature_in_ticks) {
39 return temperature_in_ticks * 175.f / 65535.f - 45.f;
40}
41
42constexpr uint16_t humidity_in_percent_to_ticks(float humidity_in_percent) {
43 return uint16_t((std::clamp(humidity_in_percent, 0.f, 100.f) + 6.f) * 65535.f / 125.f);
44}
45
46constexpr float humidity_in_ticks_to_percent(uint16_t humidity_in_ticks) {
47 return humidity_in_ticks * 125.f / 65535.f - 6.f;
48}
49
50constexpr uint16_t pressure_in_hpa_to_pa_2(float pressure_in_hpa) {
51 return uint16_t(std::clamp(pressure_in_hpa, 400.f, 1100.f) * 50.f);
52}
53
54constexpr float pressure_in_pa_2_to_hpa(uint16_t pressure_in_pa_2) { return pressure_in_pa_2 / 50.f; }
55
57 this->stop_poller(); // not ready yet
58
59 // Wait 100 ms after power up before attempting to communicate with the sensor
60 this->set_timeout(100, [this]() {
61 // Send exit sleep mode command (8-bit, NACK expected), wait 5 ms to exit sleep
62 this->write_command(STCC4_CMD_EXIT_SLEEP_MODE);
63 this->set_timeout(5, [this]() { this->poll_until_ready_for_setup_or_timeout_(millis()); });
64 });
65}
66
68 // Stop continuous measurements in case they were previously running
69 // The device may NACK this request if it is not ready to communicate yet
70 if (this->write_command(STCC4_CMD_STOP_CONTINUOUS_MEASUREMENT)) {
71 // Read product ID to verify communication (6 words: 2 for product_id + 4 for serial)
72 // The device may NACK this request if it is not ready to communicate yet
73 uint16_t raw_product_id[6];
74 if (this->get_register(STCC4_CMD_GET_PRODUCT_ID, raw_product_id, 6, 1)) {
75 uint32_t product_id = (uint32_t(raw_product_id[0]) << 16) | raw_product_id[1];
76 uint64_t serial_number = (uint64_t(raw_product_id[2]) << 48) | (uint64_t(raw_product_id[3]) << 32) |
77 (uint64_t(raw_product_id[4]) << 16) | raw_product_id[5];
78 ESP_LOGD(TAG, "Product ID: 0x%08" PRIX32 ", Serial: 0x%016" PRIX64, product_id, serial_number);
79 if (!this->setup_check(product_id == STCC4_PRODUCT_ID, LOG_STR("Unsupported product ID")))
80 return;
81
82 // Set static ambient pressure compensation if configured
83 if (this->ambient_pressure_in_pa_2_ != 0) {
85 return;
86 }
87
88 // Apply the dynamic compensation sources' current values, if configured
89 if (this->temperature_source_sensor_ != nullptr && this->humidity_source_sensor_ != nullptr) {
91 }
92 if (this->ambient_pressure_source_sensor_ != nullptr) {
94 }
95
97 this->start_poller();
98 this->finish_setup_();
99 return;
100 }
101
102 // Start continuous measurement
103 if (!this->setup_check(this->write_command(STCC4_CMD_START_CONTINUOUS_MEASUREMENT),
104 LOG_STR("Failed to start continuous measurement")))
105 return;
106 this->schedule_continuous_update_(false);
107 this->finish_setup_();
108 return;
109 }
110 }
111
112 if (millis() - start_time < READY_TIMEOUT_MS) {
113 ESP_LOGVV(TAG, "Retry sync");
114 this->set_timeout(READY_POLL_INTERVAL_MS,
115 [this, start_time]() { this->poll_until_ready_for_setup_or_timeout_(start_time); });
116 return;
117 }
118
119 this->mark_failed(LOG_STR("Failed to stop continuous measurements and read product ID"));
120}
121
123 this->ready_ = true;
124 // Follow the sources only once measuring started, so a failed setup stops writing to the device
125 if (this->temperature_source_sensor_ != nullptr && this->humidity_source_sensor_ != nullptr) {
126 this->temperature_source_sensor_->add_on_state_callback(
127 [this](float) { this->update_rht_compensation_from_source_(); });
128 this->humidity_source_sensor_->add_on_state_callback(
129 [this](float) { this->update_rht_compensation_from_source_(); });
130 }
131 if (this->ambient_pressure_source_sensor_ != nullptr) {
132 this->ambient_pressure_source_sensor_->add_on_state_callback(
133 [this](float) { this->update_ambient_pressure_compensation_from_source_(); });
134 }
135}
136
137void STCC4Component::dump_config() {
138 ESP_LOGCONFIG(TAG, "STCC4:");
139 LOG_I2C_DEVICE(this);
140 ESP_LOGCONFIG(TAG, " Measurement mode: %s",
141 this->measurement_mode_ == MeasurementMode::CONTINUOUS ? LOG_STR_LITERAL("Continuous (1s)")
142 : LOG_STR_LITERAL("Single shot"));
143 if (this->ambient_pressure_source_sensor_ != nullptr) {
144 ESP_LOGCONFIG(TAG, " Dynamic ambient pressure compensation using '%s'",
145 LOG_STR_ARG(this->ambient_pressure_source_sensor_->get_log_name()));
146 } else if (this->ambient_pressure_in_pa_2_ != 0) {
147 ESP_LOGCONFIG(TAG, " Ambient pressure compensation: %f hPa",
149 }
150 if (this->temperature_source_sensor_ != nullptr) {
151 ESP_LOGCONFIG(TAG, " Temperature compensation using '%s'",
152 LOG_STR_ARG(this->temperature_source_sensor_->get_log_name()));
153 }
154 if (this->humidity_source_sensor_ != nullptr) {
155 ESP_LOGCONFIG(TAG, " Humidity compensation using '%s'",
156 LOG_STR_ARG(this->humidity_source_sensor_->get_log_name()));
157 }
158 LOG_UPDATE_INTERVAL(this);
159 LOG_SENSOR(" ", "CO2", this->co2_sensor_);
160 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
161 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
162}
163
164void STCC4Component::update() {
166 return;
167
168 // Perform single-shot measurement, wait 500 ms for the measurement to be ready
169 if (!this->write_command(STCC4_CMD_MEASURE_SINGLE_SHOT)) {
170 ESP_LOGW(TAG, "Failed to start single shot measurement");
171 this->status_set_warning();
172 return;
173 }
174 this->set_timeout(500, [this]() {
175 if (this->read_measurement_(0)) {
176 this->status_clear_warning();
177 } else {
178 ESP_LOGW(TAG, "Failed to read measurement data");
179 this->status_set_warning();
180 }
181 });
182}
183
184void STCC4Component::schedule_continuous_update_(bool retry_for_clock_drift) {
185 // In continuous measurement mode, the STCC4 produces a sample every 1000 ms according to its
186 // internal clock. The datasheet recommends retrying 150 ms after a failed read to compensate
187 // for clock drift between the host and the device.
188 this->set_timeout(retry_for_clock_drift ? 150 : 1000, [this, retry_for_clock_drift]() {
189 if (this->read_measurement_(retry_for_clock_drift ? 0 : sensirion_common::SENSIRION_OPTION_READ_MAY_NACK)) {
190 this->status_clear_warning();
191 this->schedule_continuous_update_(false);
192 } else if (!retry_for_clock_drift) {
193 this->schedule_continuous_update_(true);
194 } else {
195 this->status_set_warning();
196 this->schedule_continuous_update_(false);
197 }
198 });
199}
200
201bool STCC4Component::read_measurement_(uint8_t sensirion_options) {
202 // Read measurement data: 4 words (CO2, temperature, humidity, status)
203 uint16_t raw_data[4];
204 if (!this->get_register_(STCC4_CMD_READ_MEASUREMENT, ADDR_16_BIT, raw_data, 4, 1, sensirion_options)) {
205 return false;
206 }
207
208 // CO2 value is in ppm as int16 (ignore negative values during warm-up)
209 const int16_t co2_raw = int16_t(raw_data[0]);
210 if (this->co2_sensor_ != nullptr && co2_raw >= 0) {
211 this->co2_sensor_->publish_state(co2_raw);
212 }
213
214 PUBLISH_STATE(this->temperature_sensor_, temperature_in_ticks_to_c(raw_data[1]));
215
216 PUBLISH_STATE(this->humidity_sensor_, humidity_in_ticks_to_percent(raw_data[2]));
217 return true;
218}
219
221 const float temperature_in_c = this->temperature_source_sensor_->state;
222 const float humidity_in_percent = this->humidity_source_sensor_->state;
223 if (std::isnan(temperature_in_c) || std::isnan(humidity_in_percent))
224 return;
225
226 const uint16_t temperature_in_ticks = temperature_in_c_to_ticks(temperature_in_c);
227 const uint16_t humidity_in_ticks = humidity_in_percent_to_ticks(humidity_in_percent);
228 if ((this->temperature_in_ticks_ != temperature_in_ticks || this->humidity_in_ticks_ != humidity_in_ticks) &&
229 this->write_rht_compensation_(temperature_in_ticks, humidity_in_ticks)) {
230 this->temperature_in_ticks_ = temperature_in_ticks;
231 this->humidity_in_ticks_ = humidity_in_ticks;
232 }
233}
234
235void STCC4Component::set_ambient_pressure_compensation(float pressure_in_hpa) {
236 this->ambient_pressure_in_pa_2_ = pressure_in_hpa_to_pa_2(pressure_in_hpa);
237}
238
240 const float pressure_in_hpa = this->ambient_pressure_source_sensor_->state;
241 if (std::isnan(pressure_in_hpa))
242 return;
243
244 if (pressure_in_hpa < 100.f || pressure_in_hpa > 10000.f) {
245 // Some pressure sensors report values in Pa instead of hPa and there's no way to check at compile time.
246 // Warn if the value seems far outside of the expected range.
249 ESP_LOGW(TAG, "Ambient pressure compensation sensor might have incompatible units: got %f hPa", pressure_in_hpa);
250 }
251 return; // skip this update
252 } else {
254 }
255
256 const uint16_t ambient_pressure_in_pa_2 = pressure_in_hpa_to_pa_2(pressure_in_hpa);
257 if (this->ambient_pressure_in_pa_2_ != ambient_pressure_in_pa_2 &&
258 this->write_ambient_pressure_compensation_(ambient_pressure_in_pa_2)) {
259 this->ambient_pressure_in_pa_2_ = ambient_pressure_in_pa_2;
260 }
261}
262
263bool STCC4Component::write_rht_compensation_(uint16_t temperature_in_ticks, uint16_t humidity_in_ticks) {
264 ESP_LOGVV(TAG, "Set RHT compensation: %f °C, %f %%RH", temperature_in_ticks_to_c(temperature_in_ticks),
265 humidity_in_ticks_to_percent(humidity_in_ticks));
266 const uint16_t data[2] = {temperature_in_ticks, humidity_in_ticks};
267 if (!this->write_command(STCC4_CMD_SET_RHT_COMPENSATION, data, 2)) {
268 ESP_LOGE(TAG, "Failed to set RHT compensation");
269 return false;
270 }
271 return true;
272}
273
275 ESP_LOGVV(TAG, "Set pressure compensation: %f hPa", pressure_in_pa_2_to_hpa(pressure_in_pa_2));
276 if (!this->write_command(STCC4_CMD_SET_PRESSURE_COMPENSATION, pressure_in_pa_2)) {
277 ESP_LOGE(TAG, "Failed to set ambient pressure compensation");
278 return false;
279 }
280 return true;
281}
282
283} // namespace esphome::stcc4
void mark_failed()
Mark this component as failed.
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:84
bool ESPHOME_ALWAYS_INLINE setup_check(bool ok)
Marks the component failed with message (default "Communication failed") unless ok; returns ok.
Definition component.h:236
void status_clear_warning()
Definition component.h:318
void set_timeout(const char *name, uint32_t timeout, SchedulerCallback &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
bool get_register_(uint16_t reg, CommandLen command_len, uint16_t *data, uint8_t len, uint8_t delay, uint8_t sensirion_options=0)
get data words from I2C register.
bool get_register(uint16_t command, uint16_t *data, uint8_t len, uint8_t delay=0)
get data words from I2C register.
bool write_command(T i2c_register)
Write a command to the I2C device.
bool write_rht_compensation_(uint16_t temperature_in_ticks, uint16_t humidity_in_ticks)
Definition stcc4.cpp:263
uint16_t ambient_pressure_in_pa_2_
Definition stcc4.h:45
void schedule_continuous_update_(bool retry_for_clock_drift)
Definition stcc4.cpp:184
bool write_ambient_pressure_compensation_(uint16_t pressure_in_pa_2)
Definition stcc4.cpp:274
void update_rht_compensation_from_source_()
Definition stcc4.cpp:220
void poll_until_ready_for_setup_or_timeout_(uint32_t start_time)
Definition stcc4.cpp:67
bool read_measurement_(uint8_t sensirion_options)
Definition stcc4.cpp:201
MeasurementMode measurement_mode_
Definition stcc4.h:41
bool ambient_pressure_unit_warning_logged_
Definition stcc4.h:46
void update_ambient_pressure_compensation_from_source_()
Definition stcc4.cpp:239
constexpr float temperature_in_ticks_to_c(uint16_t temperature_in_ticks)
Definition stcc4.cpp:38
constexpr uint16_t humidity_in_percent_to_ticks(float humidity_in_percent)
Definition stcc4.cpp:42
constexpr uint16_t pressure_in_hpa_to_pa_2(float pressure_in_hpa)
Definition stcc4.cpp:50
constexpr float humidity_in_ticks_to_percent(uint16_t humidity_in_ticks)
Definition stcc4.cpp:46
ESPHOME_LOG_TAG(TAG, "stcc4")
constexpr float pressure_in_pa_2_to_hpa(uint16_t pressure_in_pa_2)
Definition stcc4.cpp:54
constexpr uint16_t temperature_in_c_to_ticks(float temperature_in_c)
Definition stcc4.cpp:34
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
static void uint32_t
char serial_number[10]
Definition sun_gtil2.cpp:15