ESPHome 2026.11.0b6
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 <cinttypes>
9#include <cmath>
10
11namespace esphome::apc1 {
12
13ESPHOME_LOG_TAG(TAG, "apc1");
14
15static constexpr uint8_t APC1_MEASUREMENT_OFFSET_AQI = 58;
16static constexpr uint8_t APC1_MEASUREMENT_OFFSET_ERROR_CODE = 61;
17
18static constexpr uint8_t APC1_DEVICE_INFO_OFFSET_MODULE = 4;
19static constexpr uint8_t APC1_DEVICE_INFO_OFFSET_SERIAL = 10;
20static constexpr uint8_t APC1_DEVICE_INFO_OFFSET_FW = 19;
21
22// Give a freshly powered sensor time to boot before the first retry
23static constexpr uint32_t APC1_COLD_BOOT_INIT_DELAY_MS = 2000;
24// Re-send the init commands at most this often while no frames arrive
25static constexpr uint32_t APC1_INIT_RETRY_INTERVAL_MS = 10000;
26// Active mode streams a frame every second; this long without one means the sensor stopped
27static constexpr uint32_t APC1_NO_DATA_TIMEOUT_MS = 15000;
28// Drop a partial frame when the bytes stop mid-way
29static constexpr uint32_t APC1_RX_IDLE_TIMEOUT_MS = 200;
30
32 if (this->set_pin_ != nullptr) {
33 this->set_pin_->setup();
34 this->set_pin_->digital_write(true);
35 }
36 if (this->reset_pin_ != nullptr) {
37 this->reset_pin_->setup();
38 this->reset_pin_->digital_write(true);
39 }
40
41 // Attempt initial communication immediately for warm restarts
42 this->initialize_device_();
43
44 // Schedule delayed initialization to catch sensors during cold power-on bootup
45 this->set_timeout(APC1_COLD_BOOT_INIT_DELAY_MS, [this]() { this->initialize_device_(); });
46}
47
50 if (this->active_mode_ && !this->idle_) {
51 this->set_active_mode();
52 }
54}
55
56void APC1Component::dump_config() {
57 ESP_LOGCONFIG(TAG, "APC1:");
58 LOG_PIN(" Set Pin: ", this->set_pin_);
59 LOG_PIN(" Reset Pin: ", this->reset_pin_);
60 LOG_SENSOR(" ", "PM1.0", this->pm_1_0_sensor_);
61 LOG_SENSOR(" ", "PM2.5", this->pm_2_5_sensor_);
62 LOG_SENSOR(" ", "PM10.0", this->pm_10_0_sensor_);
63 LOG_SENSOR(" ", "PM1.0 Standard", this->pm_1_0_std_sensor_);
64 LOG_SENSOR(" ", "PM2.5 Standard", this->pm_2_5_std_sensor_);
65 LOG_SENSOR(" ", "PM10.0 Standard", this->pm_10_0_std_sensor_);
66 LOG_SENSOR(" ", "PM >0.3um", this->pm_0_3um_sensor_);
67 LOG_SENSOR(" ", "PM >0.5um", this->pm_0_5um_sensor_);
68 LOG_SENSOR(" ", "PM >1.0um", this->pm_1_0um_sensor_);
69 LOG_SENSOR(" ", "PM >2.5um", this->pm_2_5um_sensor_);
70 LOG_SENSOR(" ", "PM >5.0um", this->pm_5_0um_sensor_);
71 LOG_SENSOR(" ", "PM >10.0um", this->pm_10_0um_sensor_);
72 LOG_SENSOR(" ", "TVOC", this->tvoc_sensor_);
73 LOG_SENSOR(" ", "eCO2", this->eco2_sensor_);
74 LOG_SENSOR(" ", "AQI", this->aqi_sensor_);
75 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
76 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
77 LOG_SENSOR(" ", "Raw Temperature", this->raw_temperature_sensor_);
78 LOG_SENSOR(" ", "Raw Humidity", this->raw_humidity_sensor_);
79 LOG_SENSOR(" ", "RS0", this->rs0_sensor_);
80 LOG_SENSOR(" ", "RS2", this->rs2_sensor_);
81 LOG_SENSOR(" ", "RS3", this->rs3_sensor_);
82 LOG_SENSOR(" ", "Error Code", this->error_code_sensor_);
83}
84
85void APC1Component::loop() {
87
88 // If in active mode and not idle, retry periodically if no valid data received
89 if (this->active_mode_ && !this->idle_) {
90 if (this->last_valid_frame_ == 0) {
91 if (now - this->last_init_attempt_ >= APC1_INIT_RETRY_INTERVAL_MS) {
92 ESP_LOGD(TAG, "Waiting for APC1 sensor to respond, sending init commands...");
93 this->initialize_device_();
94 }
95 } else if (now - this->last_valid_frame_ > APC1_NO_DATA_TIMEOUT_MS &&
96 now - this->last_init_attempt_ >= APC1_INIT_RETRY_INTERVAL_MS) {
97 ESP_LOGW(TAG, "No data received from APC1 for %" PRIu32 " ms, re-initializing...", now - this->last_valid_frame_);
98 this->initialize_device_();
99 }
100 }
101
102 if (this->rx_index_ > 0 && now - this->last_transmission_ > APC1_RX_IDLE_TIMEOUT_MS) {
103 ESP_LOGV(TAG, "Timed out waiting for data, resetting buffer");
104 this->rx_index_ = 0;
105 }
106
107 this->read_available([this, now](uint8_t byte) {
108 this->last_transmission_ = now;
109
110 if (this->rx_index_ == 0) {
111 if (byte == APC1_HEADER_1) {
112 this->rx_buffer_[this->rx_index_++] = byte;
113 }
114 return;
115 }
116
117 if (this->rx_index_ == 1) {
118 if (byte == APC1_HEADER_2) {
119 this->rx_buffer_[this->rx_index_++] = byte;
120 } else if (byte != APC1_HEADER_1) {
121 this->rx_index_ = 0;
122 }
123 return;
124 }
125
126 this->rx_buffer_[this->rx_index_++] = byte;
127 if (this->rx_index_ < APC1_FRAME_HEADER_SIZE) {
128 return;
129 }
130
131 // The payload carries at least the checksum and must fit the buffer; checking it before the sum keeps a
132 // corrupt length from wrapping the total and walking past the buffer
133 const uint16_t payload_len = encode_uint16(this->rx_buffer_[2], this->rx_buffer_[3]);
134 if (payload_len < 2 || payload_len > this->rx_buffer_.size() - APC1_FRAME_HEADER_SIZE) {
135 ESP_LOGW(TAG, "Invalid frame length: %u", payload_len);
136 this->rx_index_ = 0;
137 return;
138 }
139 const uint8_t total_len = payload_len + APC1_FRAME_HEADER_SIZE;
140 if (this->rx_index_ == total_len) {
141 this->parse_frame_(total_len);
142 this->rx_index_ = 0;
143 }
144 });
145}
146
147void APC1Component::parse_frame_(uint16_t total_len) {
148 uint16_t expected_checksum = encode_uint16(this->rx_buffer_[total_len - 2], this->rx_buffer_[total_len - 1]);
149 uint16_t calculated_checksum = sum16_bytes(this->rx_buffer_.data(), total_len - 2);
150 if (expected_checksum != calculated_checksum) {
151 ESP_LOGW(TAG, "APC1 checksum mismatch: calculated 0x%04X != expected 0x%04X", calculated_checksum,
152 expected_checksum);
153 return;
154 }
155
156 if (total_len == APC1_FRAME_SIZE_MEASUREMENT) {
158 } else if (total_len == APC1_FRAME_SIZE_DEVICE_INFO) {
160 } else if (total_len == APC1_FRAME_SIZE_COMMAND_RESPONSE) {
161 ESP_LOGD(TAG, "APC1 command response: cmd=0x%02X, data=0x%02X", this->rx_buffer_[4], this->rx_buffer_[5]);
162 } else {
163 ESP_LOGD(TAG, "Received frame of unknown length %u", total_len);
164 }
165}
166
167// One message per error bit, bit 0 first
168PROGMEM_STRING_TABLE(ErrorStrings, "Fan restart error (too many restarts)", "Fan speed low", "Photodiode fault",
169 "Fan stopped / startup error", "Laser fault", "VOC sensor fault", "RHT sensor fault");
170
173 this->last_valid_frame_ = now;
174
175 uint8_t error_code = this->rx_buffer_[APC1_MEASUREMENT_OFFSET_ERROR_CODE];
176 if (error_code != this->last_error_code_) {
177 if (error_code != 0) {
178 for (uint8_t bit = 0; bit < ErrorStrings::COUNT; bit++) {
179 if (error_code & (1 << bit)) {
180 ESP_LOGW(TAG, "APC1: %s", LOG_STR_ARG(ErrorStrings::get_log_str(bit, ErrorStrings::LAST_INDEX)));
181 }
182 }
183 this->status_set_warning(LOG_STR("Sensor reported hardware error"));
184 } else {
185 ESP_LOGI(TAG, "APC1: Hardware error cleared");
186 this->status_clear_warning();
187 }
188 this->last_error_code_ = error_code;
189 PUBLISH_STATE(this->error_code_sensor_, error_code);
190 }
191
192 uint8_t aqi = this->rx_buffer_[APC1_MEASUREMENT_OFFSET_AQI];
193 if (aqi == 0) {
194 if (!this->gas_warming_up_) {
195 this->gas_warming_up_ = true;
196 ESP_LOGI(TAG, "APC1: Gas sensor warming up (AQI=0)");
197 }
198 } else if (this->gas_warming_up_) {
199 this->gas_warming_up_ = false;
200 ESP_LOGI(TAG, "APC1: Gas sensor warm-up complete (AQI=%u)", aqi);
201 }
202
203 // Measurement payload data (bytes 4-57): big-endian sensor readings.
204 // The values below feed the debug summary, so they are always decoded; every
205 // other reading is only decoded when its sensor is configured.
206 const auto u16 = [this](uint8_t offset) {
207 return encode_uint16(this->rx_buffer_[offset], this->rx_buffer_[offset + 1]);
208 };
209 const auto u32 = [this](uint8_t offset) {
210 return encode_uint32(this->rx_buffer_[offset], this->rx_buffer_[offset + 1], this->rx_buffer_[offset + 2],
211 this->rx_buffer_[offset + 3]);
212 };
213 uint16_t pm_1_0 = u16(10);
214 uint16_t pm_2_5 = u16(12);
215 uint16_t pm_10_0 = u16(14);
216 uint16_t tvoc = u16(28);
217 uint16_t eco2 = u16(30);
218 float temp_comp = static_cast<int16_t>(u16(34)) / 10.0f;
219 float hum_comp = u16(36) / 10.0f;
220
221 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,
222 pm_2_5, pm_10_0, tvoc, eco2, aqi, temp_comp, hum_comp);
223
224 PUBLISH_STATE(this->pm_1_0_std_sensor_, u16(4));
225 PUBLISH_STATE(this->pm_2_5_std_sensor_, u16(6));
226 PUBLISH_STATE(this->pm_10_0_std_sensor_, u16(8));
227
228 PUBLISH_STATE(this->pm_1_0_sensor_, pm_1_0);
229 PUBLISH_STATE(this->pm_2_5_sensor_, pm_2_5);
230 PUBLISH_STATE(this->pm_10_0_sensor_, pm_10_0);
231
232 PUBLISH_STATE(this->pm_0_3um_sensor_, u16(16));
233 PUBLISH_STATE(this->pm_0_5um_sensor_, u16(18));
234 PUBLISH_STATE(this->pm_1_0um_sensor_, u16(20));
235 PUBLISH_STATE(this->pm_2_5um_sensor_, u16(22));
236 PUBLISH_STATE(this->pm_5_0um_sensor_, u16(24));
237 PUBLISH_STATE(this->pm_10_0um_sensor_, u16(26));
238
239 PUBLISH_STATE(this->tvoc_sensor_, tvoc);
240 PUBLISH_STATE(this->eco2_sensor_, eco2);
241 PUBLISH_STATE(this->aqi_sensor_, aqi > 0 ? aqi : NAN);
242
243 PUBLISH_STATE(this->temperature_sensor_, temp_comp);
244 PUBLISH_STATE(this->humidity_sensor_, hum_comp);
245
246 PUBLISH_STATE(this->raw_temperature_sensor_, static_cast<int16_t>(u16(38)) / 10.0f);
247 PUBLISH_STATE(this->raw_humidity_sensor_, u16(40) / 10.0f);
248
249 PUBLISH_STATE(this->rs0_sensor_, u32(42));
250 PUBLISH_STATE(this->rs2_sensor_, u32(50));
251 PUBLISH_STATE(this->rs3_sensor_, u32(54));
252}
253
255 const uint8_t *serial = this->rx_buffer_.data() + APC1_DEVICE_INFO_OFFSET_SERIAL;
256 uint16_t fw_version =
257 encode_uint16(this->rx_buffer_[APC1_DEVICE_INFO_OFFSET_FW], this->rx_buffer_[APC1_DEVICE_INFO_OFFSET_FW + 1]);
258 ESP_LOGI(TAG, "APC1: Module: %.6s, Serial: %08" PRIX32 "%08" PRIX32 ", Firmware: 0x%04X (%u)",
259 reinterpret_cast<const char *>(this->rx_buffer_.data() + APC1_DEVICE_INFO_OFFSET_MODULE),
260 encode_uint32(serial[0], serial[1], serial[2], serial[3]),
261 encode_uint32(serial[4], serial[5], serial[6], serial[7]), fw_version, fw_version);
262}
263
268
269void APC1Component::set_active_mode() {
270 if (!this->active_mode_) {
271 this->arm_watchdog_();
272 }
273 this->active_mode_ = true;
274 this->send_command_(APC1Command::APC1_COMMAND_MEASUREMENT_MODE, APC1_MEASUREMENT_MODE_ACTIVE);
275}
276
277void APC1Component::set_passive_mode() {
278 this->active_mode_ = false;
279 this->send_command_(APC1Command::APC1_COMMAND_MEASUREMENT_MODE, APC1_MEASUREMENT_MODE_PASSIVE);
280}
281
282void APC1Component::request_measurement() {
284}
285
286void APC1Component::set_idle_mode() {
287 this->idle_ = true;
288 this->send_command_(APC1Command::APC1_COMMAND_OPERATION_MODE, APC1_OPERATING_MODE_IDLE);
289}
290
291void APC1Component::set_measurement_mode() {
292 this->idle_ = false;
293 this->arm_watchdog_();
294 this->send_command_(APC1Command::APC1_COMMAND_OPERATION_MODE, APC1_OPERATING_MODE_STANDARD);
295}
296
298 std::array<uint8_t, APC1_COMMAND_FRAME_SIZE> buf{
299 APC1_HEADER_1,
300 APC1_HEADER_2,
301 static_cast<uint8_t>(cmd),
302 static_cast<uint8_t>((data >> 8) & 0xFF),
303 static_cast<uint8_t>(data & 0xFF),
304 0,
305 0,
306 };
307 uint16_t checksum = sum16_bytes(buf.data(), 5);
308 buf[5] = static_cast<uint8_t>((checksum >> 8) & 0xFF);
309 buf[6] = static_cast<uint8_t>(checksum & 0xFF);
310 this->write_array(buf);
311}
312
313} // namespace esphome::apc1
uint8_t checksum
Definition bl0906.h:3
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 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
virtual void setup()=0
virtual void digital_write(bool value)=0
std::array< uint8_t, APC1_FRAME_SIZE_MEASUREMENT > rx_buffer_
Definition apc1.h:91
uint32_t last_transmission_
Definition apc1.h:88
void parse_frame_(uint16_t total_len)
Definition apc1.cpp:147
void send_command_(APC1Command cmd, uint16_t data)
Definition apc1.cpp:297
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:264
bool read_available(F &&on_byte)
Same as read_available_chunks(), calling on_byte(uint8_t) once per byte.
Definition uart.h:77
void write_array(const uint8_t *data, size_t len)
Definition uart.h:30
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")
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:1051
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:1043
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:944
static void uint32_t