ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
mics_5524.cpp
Go to the documentation of this file.
1#include "mics_5524.h"
2
3#include <algorithm>
4#include <cinttypes>
5
7#include "esphome/core/log.h"
8
10
11ESPHOME_LOG_TAG(TAG, "mics_5524");
12
14static constexpr uint32_t REFERENCE_PREFERENCE_VERSION = 0x00000010;
15
17struct ModelStrings {
18 const LogString *conversion;
19 const LogString *reference;
20 const LogString *key;
21};
22
23static ModelStrings model_strings(micsmath::ConversionModel model) {
25 return {LOG_STR("dfrobot"), LOG_STR("air reference"), LOG_STR("air_reference")};
26 return {LOG_STR("datasheet"), LOG_STR("R0"), LOG_STR("r0")};
27}
28
30 float ppm = micsmath::ppm_from_vendor_curve(ratio, {this->p0_, this->p1_, this->min_ppm_, this->max_ppm_});
31#ifdef USE_MICS_5524_DATASHEET
32 // One firmware can hold a hub of each model, so the check stays inside the guard
34 ppm =
35 micsmath::clamp_ppm(micsmath::ppm_from_power_law(this->p0_, this->p1_, ratio), this->min_ppm_, this->max_ppm_);
36 }
37#endif
38 ESP_LOGD(TAG, "'%s': ratio=%.4f -> %.1f ppm", LOG_STR_ARG(this->get_log_name()), ratio, ppm);
39 this->publish_state(ppm);
40}
41
43 if (this->persist_) {
44 // Written once per calibration, so flash rather than the RTC memory an ESP8266 loses at power off
46 this->preference_key_ ^ (REFERENCE_PREFERENCE_VERSION + this->conversion_), true);
47 }
48
49 if (this->enable_pin_ != nullptr) {
50 // EN of the breakout is active low; `inverted: true` makes this write switch the module on.
51 this->enable_pin_->setup();
52 this->enable_pin_->digital_write(true);
53 }
54
55 if (this->has_reference_()) {
56 ESP_LOGI(TAG, "using the %s from the configuration (%.4f) - the sensor is not calibrated at boot",
57 LOG_STR_ARG(model_strings(this->conversion_).reference), this->reference_);
58 } else if (this->persist_ && this->load_reference_()) {
59 ESP_LOGI(TAG, "restored the %s from flash (%.4f)", LOG_STR_ARG(model_strings(this->conversion_).reference),
60 this->reference_);
61 }
62
63 if (this->warmup_time_ > 0) {
64 this->warming_up_ = true;
65 this->stop_poller();
66 this->set_timeout(this->warmup_time_, [this]() {
67 this->warming_up_ = false;
68 ESP_LOGI(TAG, "warm-up finished, readings are published from now on");
69 this->start_poller();
70 // A calibration waiting for the warm-up starts when one at boot would have.
71 if (this->calibration_pending_) {
73 this->calibration_delay_ > this->warmup_time_ ? this->calibration_delay_ - this->warmup_time_ : 0);
74 }
75 });
76 ESP_LOGI(TAG, "warm-up of %" PRIu32 " s - no readings published before that", this->warmup_time_ / 1000);
77 }
78
79 if (this->calibrate_at_boot_) {
80 // A fixed or restored reference wins.
81 if (this->has_reference_()) {
82 ESP_LOGI(TAG, "%s already known (%.4f) - automatic calibration skipped",
83 LOG_STR_ARG(model_strings(this->conversion_).reference), this->reference_);
84 } else {
85 const uint32_t boot_delay = std::max(this->calibration_delay_, this->warmup_time_);
86 this->calibration_pending_ = true;
87 // During a warm-up the warm-up timeout starts it, at the same boot_delay.
88 if (!this->warming_up_)
89 this->schedule_calibration_(boot_delay);
90 ESP_LOGI(TAG, "clean-air calibration of the %s in %" PRIu32 " s - the sensor must be in clean air",
91 LOG_STR_ARG(model_strings(this->conversion_).reference), boot_delay / 1000);
92 }
93 } else if (!this->has_reference_()) {
94 ESP_LOGW(TAG,
95 "no %s available, the PPM values stay unknown\n set it in the configuration or enable 'calibration:'",
96 LOG_STR_ARG(model_strings(this->conversion_).reference));
97 }
98
99 // The loop only samples while a clean-air calibration runs; `update()` publishes.
100 this->disable_loop();
101}
102
104 ESP_LOGCONFIG(TAG,
105 "MiCS-5524:\n"
106 " Conversion: %s, VCC: %.2f V, AO multiplier: x%.3f, AO samples per reading: %u\n"
107 " Warm-up: %" PRIu32 " s, calibration: %s, sample spacing: %" PRIu32 " ms",
108 LOG_STR_ARG(model_strings(this->conversion_).conversion), this->vcc_, this->voltage_multiplier_,
109 static_cast<unsigned>(this->samples_), this->warmup_time_ / 1000,
110 this->calibrate_at_boot_ ? LOG_STR_LITERAL("enabled") : LOG_STR_LITERAL("disabled"),
111 this->sample_interval_);
112 LOG_UPDATE_INTERVAL(this);
113 LOG_PIN(" Enable pin: ", this->enable_pin_);
114 if (!this->is_vendor_model_()) {
115 ESP_LOGCONFIG(TAG, " Load resistor: %.1f kOhm", this->rl_);
116 }
117 if (this->has_reference_()) {
118 ESP_LOGCONFIG(TAG, " %s: %.4f", LOG_STR_ARG(model_strings(this->conversion_).reference), this->reference_);
119 } else {
120 ESP_LOGCONFIG(TAG, " %s: not available yet", LOG_STR_ARG(model_strings(this->conversion_).reference));
121 }
122 LOG_SENSOR(" ", "Voltage", this->voltage_sensor_);
123 LOG_SENSOR(" ", "Ratio", this->ratio_sensor_);
124 LOG_SENSOR(" ", "RS", this->rs_sensor_);
125#ifdef MICS_5524_GAS_COUNT
126 for (auto *gas : this->gases_) {
127 LOG_SENSOR(" ", "Gas", gas);
128 ESP_LOGCONFIG(TAG, " Range: %.1f - %.1f ppm", gas->get_min_ppm(), gas->get_max_ppm());
129 }
130#endif
131}
132
133float MiCS5524Component::sample_voltage_() {
134 // Taken back to back; waiting between them would block the main loop.
135 float sum = 0.0f;
136 for (uint8_t i = 0; i < this->samples_; i++)
137 sum += this->source_->sample();
138 return (sum / static_cast<float>(this->samples_)) * this->voltage_multiplier_;
139}
140
142 float value = micsmath::air_value_from_voltage(voltage, this->vcc_);
143#ifdef USE_MICS_5524_DATASHEET
144 if (!this->is_vendor_model_())
145 value = micsmath::rs_from_voltage(voltage, this->vcc_, this->rl_);
146#endif
147 if (!std::isnan(value)) {
148 this->input_fault_ = false;
149 return value;
150 }
151 // Logged once per fault; the status flag cannot tell it from a failed calibration.
152 if (!this->input_fault_) {
153 this->input_fault_ = true;
154 ESP_LOGW(TAG, "analog output reads %.4f V with vcc %.2f V\n check the AO wiring, 'vcc:' and 'voltage_multiplier:'",
155 voltage, this->vcc_);
156 }
157 this->status_set_warning(LOG_STR("analog output out of range"));
158 return NAN;
159}
160
162#ifdef MICS_5524_GAS_COUNT
163 for (auto *gas : this->gases_) {
164 gas->publish_ratio(ratio, this->conversion_);
165 }
166#endif
167}
168
169void MiCS5524Component::publish_diagnostics_(float voltage, float ratio, float rs) {
170 PUBLISH_STATE(this->voltage_sensor_, voltage);
171 PUBLISH_STATE(this->ratio_sensor_, ratio);
172 // Validation rejects `rs_sensor:` under the vendor model.
173 PUBLISH_STATE(this->rs_sensor_, rs);
174}
175
177 if (!this->has_reference_() && this->voltage_sensor_ == nullptr && this->ratio_sensor_ == nullptr &&
178 this->rs_sensor_ == nullptr)
179 return;
180
181 const float voltage = this->sample_voltage_();
182 const float value = this->model_value_(voltage);
183 float ratio = NAN;
184 if (this->has_reference_()) {
185 ratio = this->is_vendor_model_() ? micsmath::ratio_from_air_value(value, this->reference_)
186 : micsmath::ratio_from_rs(value, this->reference_);
187 }
188 this->publish_diagnostics_(voltage, ratio, value);
189
190 // A failed calibration keeps its warning until the retry succeeds.
191 if (!std::isnan(value) && !this->calibrating_ && !this->calibration_pending_)
192 this->status_clear_warning();
193
194 // Every gas starts unknown and the reference is never cleared, so there is nothing to republish.
195 if (!this->has_reference_())
196 return;
197
198 ESP_LOGD(TAG, "V_AO=%.4f V, ratio=%.4f", voltage, ratio);
199 this->publish_ratio_(ratio);
200}
201
202void MiCS5524Component::set_calibration(uint32_t delay, uint32_t samples, uint32_t sample_interval, bool persist,
203 bool at_boot) {
205 this->calibration_samples_ = samples;
206 this->sample_interval_ = sample_interval;
207 this->persist_ = persist;
208 this->calibrate_at_boot_ = at_boot;
209}
210
212 if (this->calibrating_) {
213 ESP_LOGW(TAG, "calibration already running");
214 return;
215 }
216 if (this->calibration_pending_) {
217 ESP_LOGW(TAG, "calibration already requested");
218 return;
219 }
220 this->calibration_pending_ = true;
221 if (this->warming_up_) {
222 // A request must never capture an unstable reading; the warm-up timeout starts it.
223 ESP_LOGI(TAG, "calibration requested - waiting for the warm-up window to end");
224 return;
225 }
226 this->schedule_calibration_(0);
227 ESP_LOGI(TAG, "calibration requested - keep the sensor in clean air");
228}
229
231 if (!this->calibrating_) {
232 // Only a calibration samples here; the deferred start is a timer.
233 this->disable_loop();
234 return;
235 }
236
239 return;
240
241 this->calibration_last_sample_ = now;
242 this->process_calibration_();
243}
244
248
250 this->calibration_pending_ = false;
251 this->calibrating_ = true;
253 this->calibration_count_ = 0;
254 this->calibration_attempts_ = 0;
255 this->calibration_sum_ = 0.0f;
256 this->calibration_min_ = INFINITY;
257 this->calibration_max_ = -INFINITY;
258 this->enable_loop();
259
260 ESP_LOGI(TAG, "calibrating the %s, %" PRIu32 " samples - keep the sensor in clean air",
261 LOG_STR_ARG(model_strings(this->conversion_).reference), this->calibration_samples_);
262}
263
265 this->calibration_attempts_++;
266
267 // The samples are averaged in the units of the active model.
268 const float reference = this->model_value_(this->sample_voltage_());
269 if (!std::isnan(reference)) {
270 this->calibration_min_ = std::min(this->calibration_min_, reference);
271 this->calibration_max_ = std::max(this->calibration_max_, reference);
272 this->calibration_sum_ += reference;
273 this->calibration_count_++;
274 }
275
277 this->finish_calibration_();
278}
279
281 this->calibrating_ = false;
282 this->disable_loop();
283
284 const uint32_t attempts = this->calibration_attempts_;
285 const uint32_t valid = this->calibration_count_;
286 // A majority of the attempts has to have produced a sample, two at least.
287 const uint32_t required = std::max<uint32_t>((attempts + 1) / 2, 2);
288
289 if (valid < required) {
290 ESP_LOGW(TAG, "calibration failed, %" PRIu32 " of %" PRIu32 " samples were valid", valid, attempts);
292 return;
293 }
294
295 const float reference = this->calibration_sum_ / static_cast<float>(valid);
296
297 // A sensor still settling, or not in clean air, varies too much to be the reference.
299 ESP_LOGW(TAG, "clean-air samples spread %.4f around %.4f (%.4f - %.4f)\n the sensor was not settled in clean air",
300 this->calibration_max_ - this->calibration_min_, reference, this->calibration_min_,
301 this->calibration_max_);
303 return;
304 }
305
306 this->reference_ = reference;
307 this->status_clear_warning();
308 const bool stored = this->persist_ && this->save_reference_();
309
310 const ModelStrings strings = model_strings(this->conversion_);
311 ESP_LOGI(TAG,
312 "%s = %.4f (%" PRIu32 "/%" PRIu32 " samples valid)%s\n"
313 " hard-code '%s: %.4f' to skip the calibration at boot",
314 LOG_STR_ARG(strings.reference), this->reference_, valid, attempts,
315 stored ? LOG_STR_LITERAL(", stored in flash")
316 : this->persist_ ? LOG_STR_LITERAL("")
317 : LOG_STR_LITERAL(", kept until reboot"),
318 LOG_STR_ARG(strings.key), this->reference_);
319}
320
322 this->status_set_warning();
323 this->calibration_pending_ = true;
324 // A zero delay would log the same failure about five times per second.
326 this->schedule_calibration_(delay);
327 ESP_LOGW(TAG, "retrying the calibration in %" PRIu32 " s", delay / 1000);
328}
329
331 if (!this->reference_pref_.save(&this->reference_)) {
332 ESP_LOGW(TAG, "could not store the %s in flash", LOG_STR_ARG(model_strings(this->conversion_).reference));
333 return false;
334 }
335 // Once per calibration, so write it out now rather than at the next preferences sync
337 ESP_LOGD(TAG, "%s %.4f saved", LOG_STR_ARG(model_strings(this->conversion_).reference), this->reference_);
338 return true;
339}
340
342 float stored = 0.0f;
343 if (!this->reference_pref_.load(&stored))
344 return false;
345 if (!std::isfinite(stored) || stored <= 0.0f) {
346 ESP_LOGW(TAG, "ignoring the stored %s %.4f, calibrating again",
347 LOG_STR_ARG(model_strings(this->conversion_).reference), stored);
348 return false;
349 }
350 this->reference_ = stored;
351 return true;
352}
353
354} // namespace esphome::mics_5524
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.
void enable_loop()
Enable this component's loop.
Definition component.h:261
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 disable_loop()
Disable this component's loop.
void status_clear_warning()
Definition component.h:309
const LogString * get_log_name() const
Get the name for a "%s" log argument (LOG_STR_ARG).
virtual void setup()=0
virtual void digital_write(bool value)=0
bool input_fault_
The out-of-range warning has been logged; the next usable reading clears it.
Definition mics_5524.h:142
bool warming_up_
Set from setup() until the warm-up timeout fires.
Definition mics_5524.h:137
bool save_reference_()
True when the reference reached the storage.
void publish_diagnostics_(float voltage, float ratio, float rs)
uint32_t sample_interval_
Spacing of the clean-air calibration samples (ms); the ~16 ms loop tick is the floor.
Definition mics_5524.h:107
static constexpr uint32_t CALIBRATION_START_ID
Definition mics_5524.h:109
bool calibration_pending_
A calibration waits for its start time; calibrating_ takes over from there.
Definition mics_5524.h:140
ESPPreferenceObject reference_pref_
Definition mics_5524.h:125
float reference_
Clean-air reference, x_air in volts or R0 in kOhm, 0 while there is none.
Definition mics_5524.h:122
void request_calibration()
Deferred until the warm-up window ends.
StaticVector< MiCS5524GasSensor *, MICS_5524_GAS_COUNT > gases_
Definition mics_5524.h:129
SUB_SENSOR(voltage) SUB_SENSOR(ratio) SUB_SENSOR(rs) protected float model_value_(float voltage)
Value of the active model that the reference is taken from, x = VCC - V_AO (vendor) or RS (datasheet)...
micsmath::ConversionModel conversion_
Definition mics_5524.h:132
void set_calibration(uint32_t delay, uint32_t samples, uint32_t sample_interval, bool persist, bool at_boot)
Calibration parameters: start after delay ms, average samples readings sample_interval ms apart; pers...
voltage_sampler::VoltageSampler * source_
Definition mics_5524.h:97
void schedule_calibration_(uint32_t delay)
Start a calibration after delay ms; every start goes through here.
static constexpr uint32_t CALIBRATION_RETRY_MIN_MS
Floor of the delay between two calibration attempts (ms).
Definition mics_5524.h:111
float calibration_min_
Smallest and largest clean-air sample of the run, see calibration_is_stable().
Definition mics_5524.h:118
void publish_ratio(float ratio, micsmath::ConversionModel model)
Publish the concentration for ratio with the formula of model; NAN publishes unknown.
Definition mics_5524.cpp:29
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
virtual float sample()=0
Get a voltage reading, in V.
bool calibration_is_stable(float min_value, float max_value, float mean)
True when the clean-air samples spread at most MAX_CALIBRATION_SPREAD of their mean.
Definition mics_math.h:122
float ratio_from_rs(float rs, float r0)
ratio = RS / R0 (NaN when either value is unusable); 0 is the saturated end.
Definition mics_math.h:85
float air_value_from_voltage(float voltage, float vcc)
x = VCC - V_ao: 0 at VCC (a saturated sensor, never clean air).
Definition mics_math.h:36
float ppm_from_power_law(float a, float b, float ratio)
ppm = a * ratio^b; NaN for a ratio or coefficient that cannot produce a reading.
Definition mics_math.h:93
float clamp_ppm(float ppm, float min_ppm, float max_ppm)
Clamp to the configured range: below min_ppm counts as not detected and reads 0, 0 itself never chang...
Definition mics_math.h:104
float rs_from_voltage(float voltage, float vcc, float rl)
RS = (VCC * RL) / V - RL in kOhm: 0 at VCC (a saturated sensor).
Definition mics_math.h:77
float ratio_from_air_value(float x, float x_air)
ratio = x / x_air (NaN when either value is unusable).
Definition mics_math.h:43
ConversionModel
Generated through CONVERSION_MODELS in init.py.
Definition mics_math.h:14
float ppm_from_vendor_curve(float ratio, const VendorCurve &curve)
ratio -> ppm as DFRobot_MICS getGasData(): 0 above the threshold or below the vendor range,...
Definition mics_math.h:51
ESPHOME_LOG_TAG(TAG, "mics_5524")
uint32_t value
Definition hal.cpp:41
ESPPreferences * global_preferences
void HOT delay(uint32_t ms)
Definition hal.cpp:85
Application App
Global storage of Application pointer - only one Application can exist.
bool valid
static void uint32_t
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
Definition preferences.h:24
bool sync()
Commit pending writes to flash.
Definition preferences.h:33