ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
apc1.cpp
Go to the documentation of this file.
1#include "apc1.h"
3#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
7
8#include <array>
9#include <cinttypes>
10#include <cmath>
11
12namespace esphome::apc1 {
13
14ESPHOME_LOG_TAG(TAG, "apc1");
15
16static constexpr uint8_t APC1_MEASUREMENT_OFFSET_AQI = 58;
17static constexpr uint8_t APC1_MEASUREMENT_OFFSET_ERROR_CODE = 61;
18
19static constexpr uint8_t APC1_DEVICE_INFO_OFFSET_MODULE = 4;
20static constexpr uint8_t APC1_DEVICE_INFO_OFFSET_SERIAL = 10;
21static constexpr uint8_t APC1_DEVICE_INFO_OFFSET_FW = 19;
22
23// Give a freshly powered sensor time to boot before the first retry
24static constexpr uint32_t APC1_COLD_BOOT_INIT_DELAY_MS = 2000;
25// Re-send the init commands at most this often while no frames arrive
26static constexpr uint32_t APC1_INIT_RETRY_INTERVAL_MS = 10000;
27// Active mode streams a frame every second; this long without one means the sensor stopped
28static constexpr uint32_t APC1_NO_DATA_TIMEOUT_MS = 15000;
29
31 setup_output_pin(this->set_pin_, true);
32 setup_output_pin(this->reset_pin_, true);
33
34 // Attempt initial communication immediately for warm restarts
35 this->initialize_device_();
36
37 // Schedule delayed initialization to catch sensors during cold power-on bootup
38 this->set_timeout(APC1_COLD_BOOT_INIT_DELAY_MS, [this]() { this->initialize_device_(); });
39}
40
43 if (this->active_mode_ && !this->idle_) {
44 this->set_active_mode();
45 }
47}
48
49void APC1Component::dump_config() {
50 ESP_LOGCONFIG(TAG, "APC1:");
51 LOG_PIN(" Set Pin: ", this->set_pin_);
52 LOG_PIN(" Reset Pin: ", this->reset_pin_);
53 LOG_SENSOR(" ", "PM1.0", this->pm_1_0_sensor_);
54 LOG_SENSOR(" ", "PM2.5", this->pm_2_5_sensor_);
55 LOG_SENSOR(" ", "PM10.0", this->pm_10_0_sensor_);
56 LOG_SENSOR(" ", "PM1.0 Standard", this->pm_1_0_std_sensor_);
57 LOG_SENSOR(" ", "PM2.5 Standard", this->pm_2_5_std_sensor_);
58 LOG_SENSOR(" ", "PM10.0 Standard", this->pm_10_0_std_sensor_);
59 LOG_SENSOR(" ", "PM >0.3um", this->pm_0_3um_sensor_);
60 LOG_SENSOR(" ", "PM >0.5um", this->pm_0_5um_sensor_);
61 LOG_SENSOR(" ", "PM >1.0um", this->pm_1_0um_sensor_);
62 LOG_SENSOR(" ", "PM >2.5um", this->pm_2_5um_sensor_);
63 LOG_SENSOR(" ", "PM >5.0um", this->pm_5_0um_sensor_);
64 LOG_SENSOR(" ", "PM >10.0um", this->pm_10_0um_sensor_);
65 LOG_SENSOR(" ", "TVOC", this->tvoc_sensor_);
66 LOG_SENSOR(" ", "eCO2", this->eco2_sensor_);
67 LOG_SENSOR(" ", "AQI", this->aqi_sensor_);
68 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
69 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
70 LOG_SENSOR(" ", "Raw Temperature", this->raw_temperature_sensor_);
71 LOG_SENSOR(" ", "Raw Humidity", this->raw_humidity_sensor_);
72 LOG_SENSOR(" ", "RS0", this->rs0_sensor_);
73 LOG_SENSOR(" ", "RS2", this->rs2_sensor_);
74 LOG_SENSOR(" ", "RS3", this->rs3_sensor_);
75 LOG_SENSOR(" ", "Error Code", this->error_code_sensor_);
76}
77
78void APC1Component::loop() {
80
81 // If in active mode and not idle, retry periodically if no valid data received
82 if (this->active_mode_ && !this->idle_) {
83 if (this->last_valid_frame_ == 0) {
84 if (now - this->last_init_attempt_ >= APC1_INIT_RETRY_INTERVAL_MS) {
85 ESP_LOGD(TAG, "Waiting for APC1 sensor to respond, sending init commands...");
86 this->initialize_device_();
87 }
88 } else if (now - this->last_valid_frame_ > APC1_NO_DATA_TIMEOUT_MS &&
89 now - this->last_init_attempt_ >= APC1_INIT_RETRY_INTERVAL_MS) {
90 ESP_LOGW(TAG, "No data received from APC1 for %" PRIu32 " ms, re-initializing...", now - this->last_valid_frame_);
91 this->initialize_device_();
92 }
93 }
94
95 auto handle = [this](const uint8_t *frame, size_t len) { return this->parse_frame_(frame, len); };
96 this->read_frames(this->reader_, handle, now, this->last_transmission_);
97}
98
99bool APC1Component::parse_frame_(const uint8_t *frame, uint8_t total_len) {
100 uint16_t expected_checksum = encode_uint16(frame[total_len - 2], frame[total_len - 1]);
101 uint16_t calculated_checksum = sum16_bytes(frame, total_len - 2);
102 if (expected_checksum != calculated_checksum) {
103 ESP_LOGW(TAG, "APC1 checksum mismatch: calculated 0x%04X != expected 0x%04X", calculated_checksum,
104 expected_checksum);
105 return false;
106 }
107
108 if (total_len == APC1_FRAME_SIZE_MEASUREMENT) {
109 this->parse_measurement_frame_(frame);
110 } else if (total_len == APC1_FRAME_SIZE_DEVICE_INFO) {
111 this->parse_device_info_frame_(frame);
112 } else if (total_len == APC1_FRAME_SIZE_COMMAND_RESPONSE) {
113 ESP_LOGD(TAG, "APC1 command response: cmd=0x%02X, data=0x%02X", frame[4], frame[5]);
114 } else {
115 ESP_LOGD(TAG, "Received frame of unknown length %u", total_len);
116 }
117 return true;
118}
119
120// One message per error bit, bit 0 first
121PROGMEM_STRING_TABLE(ErrorStrings, "Fan restart error (too many restarts)", "Fan speed low", "Photodiode fault",
122 "Fan stopped / startup error", "Laser fault", "VOC sensor fault", "RHT sensor fault");
123
124void APC1Component::parse_measurement_frame_(const uint8_t *frame) {
126 this->last_valid_frame_ = now;
127
128 uint8_t error_code = frame[APC1_MEASUREMENT_OFFSET_ERROR_CODE];
129 if (error_code != this->last_error_code_) {
130 if (error_code != 0) {
131 for (uint8_t bit = 0; bit < ErrorStrings::COUNT; bit++) {
132 if (error_code & (1 << bit)) {
133 ESP_LOGW(TAG, "APC1: %s", LOG_STR_ARG(ErrorStrings::get_log_str(bit)));
134 }
135 }
136 this->status_set_warning(LOG_STR("Sensor reported hardware error"));
137 } else {
138 ESP_LOGI(TAG, "APC1: Hardware error cleared");
139 this->status_clear_warning();
140 }
141 this->last_error_code_ = error_code;
142 PUBLISH_STATE(this->error_code_sensor_, error_code);
143 }
144
145 uint8_t aqi = frame[APC1_MEASUREMENT_OFFSET_AQI];
146 if (aqi == 0) {
147 if (!this->gas_warming_up_) {
148 this->gas_warming_up_ = true;
149 ESP_LOGI(TAG, "APC1: Gas sensor warming up (AQI=0)");
150 }
151 } else if (this->gas_warming_up_) {
152 this->gas_warming_up_ = false;
153 ESP_LOGI(TAG, "APC1: Gas sensor warm-up complete (AQI=%u)", aqi);
154 }
155
156 // Measurement payload data (bytes 4-57): big-endian sensor readings.
157 // The values below feed the debug summary, so they are always decoded; every
158 // other reading is only decoded when its sensor is configured.
159 uint16_t pm_1_0 = encode_value<uint16_t>(frame + 10);
160 uint16_t pm_2_5 = encode_value<uint16_t>(frame + 12);
161 uint16_t pm_10_0 = encode_value<uint16_t>(frame + 14);
162 uint16_t tvoc = encode_value<uint16_t>(frame + 28);
163 uint16_t eco2 = encode_value<uint16_t>(frame + 30);
164 float temp_comp = encode_value<int16_t>(frame + 34) / 10.0f;
165 float hum_comp = encode_value<uint16_t>(frame + 36) / 10.0f;
166
167 ESP_LOGD(TAG, "APC1: PM1.0: %u, PM2.5: %u, PM10: %u, TVOC: %u, eCO2: %u, AQI: %u, Temp: %.1f°C, Hum: %.1f%%", pm_1_0,
168 pm_2_5, pm_10_0, tvoc, eco2, aqi, temp_comp, hum_comp);
169
170 PUBLISH_STATE(this->pm_1_0_std_sensor_, encode_value<uint16_t>(frame + 4));
171 PUBLISH_STATE(this->pm_2_5_std_sensor_, encode_value<uint16_t>(frame + 6));
172 PUBLISH_STATE(this->pm_10_0_std_sensor_, encode_value<uint16_t>(frame + 8));
173
174 PUBLISH_STATE(this->pm_1_0_sensor_, pm_1_0);
175 PUBLISH_STATE(this->pm_2_5_sensor_, pm_2_5);
176 PUBLISH_STATE(this->pm_10_0_sensor_, pm_10_0);
177
178 PUBLISH_STATE(this->pm_0_3um_sensor_, encode_value<uint16_t>(frame + 16));
179 PUBLISH_STATE(this->pm_0_5um_sensor_, encode_value<uint16_t>(frame + 18));
180 PUBLISH_STATE(this->pm_1_0um_sensor_, encode_value<uint16_t>(frame + 20));
181 PUBLISH_STATE(this->pm_2_5um_sensor_, encode_value<uint16_t>(frame + 22));
182 PUBLISH_STATE(this->pm_5_0um_sensor_, encode_value<uint16_t>(frame + 24));
183 PUBLISH_STATE(this->pm_10_0um_sensor_, encode_value<uint16_t>(frame + 26));
184
185 PUBLISH_STATE(this->tvoc_sensor_, tvoc);
186 PUBLISH_STATE(this->eco2_sensor_, eco2);
187 PUBLISH_STATE(this->aqi_sensor_, aqi > 0 ? aqi : NAN);
188
189 PUBLISH_STATE(this->temperature_sensor_, temp_comp);
190 PUBLISH_STATE(this->humidity_sensor_, hum_comp);
191
192 PUBLISH_STATE(this->raw_temperature_sensor_, encode_value<int16_t>(frame + 38) / 10.0f);
193 PUBLISH_STATE(this->raw_humidity_sensor_, encode_value<uint16_t>(frame + 40) / 10.0f);
194
195 PUBLISH_STATE(this->rs0_sensor_, encode_value<uint32_t>(frame + 42));
196 PUBLISH_STATE(this->rs2_sensor_, encode_value<uint32_t>(frame + 50));
197 PUBLISH_STATE(this->rs3_sensor_, encode_value<uint32_t>(frame + 54));
198}
199
200void APC1Component::parse_device_info_frame_(const uint8_t *frame) {
201 const uint8_t *serial = frame + APC1_DEVICE_INFO_OFFSET_SERIAL;
202 uint16_t fw_version = encode_uint16(frame[APC1_DEVICE_INFO_OFFSET_FW], frame[APC1_DEVICE_INFO_OFFSET_FW + 1]);
203 ESP_LOGI(TAG, "APC1: Module: %.6s, Serial: %08" PRIX32 "%08" PRIX32 ", Firmware: 0x%04X (%u)",
204 reinterpret_cast<const char *>(frame + APC1_DEVICE_INFO_OFFSET_MODULE),
205 encode_uint32(serial[0], serial[1], serial[2], serial[3]),
206 encode_uint32(serial[4], serial[5], serial[6], serial[7]), fw_version, fw_version);
207}
208
213
214void APC1Component::set_active_mode() {
215 if (!this->active_mode_) {
216 this->arm_watchdog_();
217 }
218 this->active_mode_ = true;
219 this->send_command_(APC1Command::APC1_COMMAND_MEASUREMENT_MODE, APC1_MEASUREMENT_MODE_ACTIVE);
220}
221
222void APC1Component::set_passive_mode() {
223 this->active_mode_ = false;
224 this->send_command_(APC1Command::APC1_COMMAND_MEASUREMENT_MODE, APC1_MEASUREMENT_MODE_PASSIVE);
225}
226
227void APC1Component::request_measurement() {
229}
230
231void APC1Component::set_idle_mode() {
232 this->idle_ = true;
233 this->send_command_(APC1Command::APC1_COMMAND_OPERATION_MODE, APC1_OPERATING_MODE_IDLE);
234}
235
236void APC1Component::set_measurement_mode() {
237 this->idle_ = false;
238 this->arm_watchdog_();
239 this->send_command_(APC1Command::APC1_COMMAND_OPERATION_MODE, APC1_OPERATING_MODE_STANDARD);
240}
241
243 // Kept bytes of an earlier reply must not merge into this command's
244 this->reader_.drop_kept();
245 std::array<uint8_t, APC1_COMMAND_FRAME_SIZE> buf{
246 APC1_HEADER_1,
247 APC1_HEADER_2,
248 static_cast<uint8_t>(cmd),
249 static_cast<uint8_t>((data >> 8) & 0xFF),
250 static_cast<uint8_t>(data & 0xFF),
251 0,
252 0,
253 };
254 put_be16(buf.data() + 5, sum16_bytes(buf.data(), 5));
255 this->write_array(buf);
256}
257
258} // namespace esphome::apc1
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:84
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
void parse_device_info_frame_(const uint8_t *frame)
Definition apc1.cpp:200
void parse_measurement_frame_(const uint8_t *frame)
Definition apc1.cpp:124
uint32_t last_transmission_
Definition apc1.h:88
void send_command_(APC1Command cmd, uint16_t data)
Definition apc1.cpp:242
uint32_t last_init_attempt_
Definition apc1.h:90
void arm_watchdog_()
Restarts the no-data watchdog so a mode change gets the same grace period as a cold boot.
Definition apc1.cpp:209
LengthFrameReader< APC1_FRAME_SIZE_MEASUREMENT, Frame > reader_
Definition apc1.h:95
bool parse_frame_(const uint8_t *frame, uint8_t total_len)
Returns false for a frame that fails the checksum.
Definition apc1.cpp:99
void write_array(const uint8_t *data, size_t len)
Definition uart.h:30
bool read_frames(R &reader, F &&handle, uint32_t now, uint32_t &last_rx, uint32_t gap_ms=250)
Feed the waiting bytes to a LengthFrameReader; on a pass with none, gap_ms after last_rx,...
Definition uart.h:96
ESPHOME_LOG_TAG(TAG, "apc1")
PROGMEM_STRING_TABLE(ErrorStrings, "Fan restart error (too many restarts)", "Fan speed low", "Photodiode fault", "Fan stopped / startup error", "Laser fault", "VOC sensor fault", "RHT sensor fault")
const void size_t len
Definition hal.h:68
constexpr T encode_value(const uint8_t *bytes)
Encode a value from its constituent bytes (from most to least significant) in an array with length si...
Definition helpers.h:1248
constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
Encode a 32-bit value given four bytes in most to least significant byte order.
Definition helpers.h:1235
constexpr uint8_t * put_be16(uint8_t *dst, uint16_t value)
Write the low 16, 24 or 32 bits of value to dst, most significant byte first (be) or least significan...
Definition helpers.h:1296
void setup_output_pin(GPIOPin *pin, bool level)
Set up pin and drive it to level. Does nothing when pin is null, so an optional pin needs no check.
Definition gpio.cpp:44
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:1227
Application App
Global storage of Application pointer - only one Application can exist.
constexpr uint16_t sum16_bytes(const uint8_t *data, size_t len, uint16_t sum=0)
Add up the bytes of data with size len, truncated to 16 bits.
Definition helpers.h:1091
static void uint32_t
spi_device_handle_t handle