ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
sts3x.cpp
Go to the documentation of this file.
1#include "sts3x.h"
2#include "esphome/core/log.h"
3
4namespace esphome::sts3x {
5
6ESPHOME_LOG_TAG(TAG, "sts3x");
7
8static const uint16_t STS3X_COMMAND_READ_SERIAL_NUMBER = 0x3780;
9static const uint16_t STS3X_COMMAND_READ_STATUS = 0xF32D;
10static const uint16_t STS3X_COMMAND_SOFT_RESET = 0x30A2;
11static const uint16_t STS3X_COMMAND_POLLING_H = 0x2400;
12
14static const uint16_t STS3X_COMMAND_CLEAR_STATUS = 0x3041;
15static const uint16_t STS3X_COMMAND_HEATER_ENABLE = 0x306D;
16static const uint16_t STS3X_COMMAND_HEATER_DISABLE = 0x3066;
17static const uint16_t STS3X_COMMAND_FETCH_DATA = 0xE000;
18
20 if (!this->write_command(STS3X_COMMAND_READ_SERIAL_NUMBER)) {
21 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
22 return;
23 }
24
25 uint16_t raw_serial_number[2];
26 if (!this->read_data(raw_serial_number, 1)) {
27 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
28 return;
29 }
30 uint32_t serial_number = (uint32_t(raw_serial_number[0]) << 16);
31 ESP_LOGV(TAG, " Serial Number: 0x%08" PRIX32, serial_number);
32}
34 ESP_LOGCONFIG(TAG, "STS3x:");
35 LOG_I2C_DEVICE(this);
36 LOG_UPDATE_INTERVAL(this);
37
38 LOG_SENSOR(" ", "STS3x", this);
39}
40
42 if (this->status_has_warning()) {
43 ESP_LOGD(TAG, "Retrying to reconnect the sensor.");
44 this->write_command(STS3X_COMMAND_SOFT_RESET);
45 }
46 if (!this->write_command(STS3X_COMMAND_POLLING_H)) {
47 this->status_set_warning();
48 return;
49 }
50
51 this->set_timeout(50, [this]() {
52 uint16_t raw_data[1];
53 if (!this->status_comm_result(this->read_data(raw_data, 1)))
54 return;
55
56 float temperature = 175.0f * float(raw_data[0]) / 65535.0f - 45.0f;
57 ESP_LOGD(TAG, "Got temperature=%.2f°C", temperature);
58 this->publish_state(temperature);
59 });
60}
61
62} // namespace esphome::sts3x
void mark_failed()
Mark this component as failed.
bool status_comm_result(bool ok)
Clears the warning when ok, else sets it with message (default "Communication failed"); returns ok.
bool status_has_warning() const
Definition component.h:280
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
bool write_command(T i2c_register)
Write a command to the I2C device.
bool read_data(uint16_t *data, uint8_t len)
Read data words from I2C device.
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
void dump_config() override
Definition sts3x.cpp:33
ESPHOME_LOG_TAG(TAG, "sts3x")
static void uint32_t
uint16_t temperature
Definition sun_gtil2.cpp:12
char serial_number[10]
Definition sun_gtil2.cpp:15