ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
sfa30.cpp
Go to the documentation of this file.
1#include "sfa30.h"
2#include "esphome/core/log.h"
3
4namespace esphome::sfa30 {
5
6ESPHOME_LOG_TAG(TAG, "sfa30");
7
8static const uint16_t SFA30_CMD_GET_DEVICE_MARKING = 0xD060;
9static const uint16_t SFA30_CMD_START_CONTINUOUS_MEASUREMENTS = 0x0006;
10static const uint16_t SFA30_CMD_READ_MEASUREMENT = 0x0327;
11
13 // Serial Number identification
14 uint16_t raw_device_marking[16];
15 if (!this->get_register(SFA30_CMD_GET_DEVICE_MARKING, raw_device_marking, 16, 5)) {
16 this->mark_failed(LOG_STR("Unable to read device marking"));
17 return;
18 }
19
20 for (size_t i = 0; i < 16; i++) {
21 this->device_marking_[i * 2] = static_cast<char>(raw_device_marking[i] >> 8);
22 this->device_marking_[i * 2 + 1] = static_cast<char>(raw_device_marking[i] & 0xFF);
23 }
24 ESP_LOGD(TAG, "Device Marking: '%s'", this->device_marking_);
25
26 if (!this->write_command(SFA30_CMD_START_CONTINUOUS_MEASUREMENTS)) {
27 this->mark_failed(LOG_STR("Error starting measurements"));
28 return;
29 }
30}
31
32void SFA30Component::dump_config() {
33 ESP_LOGCONFIG(TAG, "sfa30:");
34 LOG_I2C_DEVICE(this);
35 LOG_UPDATE_INTERVAL(this);
36 ESP_LOGCONFIG(TAG, " Device Marking: '%s'", this->device_marking_);
37 LOG_SENSOR(" ", "Formaldehyde", this->formaldehyde_sensor_);
38 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
39 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
40}
41
42void SFA30Component::update() {
43 if (!this->write_command(SFA30_CMD_READ_MEASUREMENT)) {
44 ESP_LOGW(TAG, "Error reading measurement!");
45 this->status_set_warning();
46 return;
47 }
48
49 this->set_timeout(5, [this]() {
50 uint16_t raw_data[3];
51 if (!this->read_data(raw_data, 3)) {
52 ESP_LOGW(TAG, "Error reading measurement data!");
53 this->status_set_warning();
54 return;
55 }
56
57 PUBLISH_STATE(this->formaldehyde_sensor_, static_cast<int16_t>(raw_data[0]) / 5.0f);
58 PUBLISH_STATE(this->humidity_sensor_, static_cast<int16_t>(raw_data[1]) / 100.0f);
59 PUBLISH_STATE(this->temperature_sensor_, static_cast<int16_t>(raw_data[2]) / 200.0f);
60
62 });
63}
64
65} // namespace esphome::sfa30
void mark_failed()
Mark this component as failed.
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:84
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
void status_clear_warning()
Definition component.h:309
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 read_data(uint16_t *data, uint8_t len)
Read data words from I2C device.
ESPHOME_LOG_TAG(TAG, "sfa30")