ESPHome 2026.12.0-dev
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 // EN of the breakout is active low; `inverted: true` makes this write switch the module on.
50 setup_output_pin(this->enable_pin_, true);
51
52 if (this->has_reference_()) {
53 ESP_LOGI(TAG, "using the %s from the configuration (%.4f) - the sensor is not calibrated at boot",
54 LOG_STR_ARG(model_strings(this->conversion_).reference), this->reference_);
55 } else if (this->persist_ && this->load_reference_()) {
56 ESP_LOGI(TAG, "restored the %s from flash (%.4f)", LOG_STR_ARG(model_strings(this->conversion_).reference),
57 this->reference_);
58 }
59
60 if (this->warmup_time_ > 0) {
61 this->warming_up_ = true;
62 this->stop_poller();
63 this->set_timeout(this->warmup_time_, [this]() {
64 this->warming_up_ = false;
65 ESP_LOGI(TAG, "warm-up finished, readings are published from now on");
66 this->start_poller();
67 // A calibration waiting for the warm-up starts when one at boot would have.
68 if (this->calibration_pending_) {
70 this->calibration_delay_ > this->warmup_time_ ? this->calibration_delay_ - this->warmup_time_ : 0);
71 }
72 });
73 ESP_LOGI(TAG, "warm-up of %" PRIu32 " s - no readings published before that", this->warmup_time_ / 1000);
74 }
75
76 if (this->calibrate_at_boot_) {
77 // A fixed or restored reference wins.
78 if (this->has_reference_()) {
79 ESP_LOGI(TAG, "%s already known (%.4f) - automatic calibration skipped",
80 LOG_STR_ARG(model_strings(this->conversion_).reference), this->reference_);
81 } else {
82 const uint32_t boot_delay = std::max(this->calibration_delay_, this->warmup_time_);
83 this->calibration_pending_ = true;
84 // During a warm-up the warm-up timeout starts it, at the same boot_delay.
85 if (!this->warming_up_)
86 this->schedule_calibration_(boot_delay);
87 ESP_LOGI(TAG, "clean-air calibration of the %s in %" PRIu32 " s - the sensor must be in clean air",
88 LOG_STR_ARG(model_strings(this->conversion_).reference), boot_delay / 1000);
89 }
90 } else if (!this->has_reference_()) {
91 ESP_LOGW(TAG,
92 "no %s available, the PPM values stay unknown\n set it in the configuration or enable 'calibration:'",
93 LOG_STR_ARG(model_strings(this->conversion_).reference));
94 }
95
96 // The loop only samples while a clean-air calibration runs; `update()` publishes.
97 this->disable_loop();
98}
99
101 ESP_LOGCONFIG(TAG,
102 "MiCS-5524:\n"
103 " Conversion: %s, VCC: %.2f V, AO multiplier: x%.3f, AO samples per reading: %u\n"
104 " Warm-up: %" PRIu32 " s, calibration: %s, sample spacing: %" PRIu32 " ms",
105 LOG_STR_ARG(model_strings(this->conversion_).conversion), this->vcc_, this->voltage_multiplier_,
106 static_cast<unsigned>(this->samples_), this->warmup_time_ / 1000,
107 this->calibrate_at_boot_ ? LOG_STR_LITERAL("enabled") : LOG_STR_LITERAL("disabled"),
108 this->sample_interval_);
109 LOG_UPDATE_INTERVAL(this);
110 LOG_PIN(" Enable pin: ", this->enable_pin_);
111 if (!this->is_vendor_model_()) {
112 ESP_LOGCONFIG(TAG, " Load resistor: %.1f kOhm", this->rl_);
113 }
114 if (this->has_reference_()) {
115 ESP_LOGCONFIG(TAG, " %s: %.4f", LOG_STR_ARG(model_strings(this->conversion_).reference), this->reference_);
116 } else {
117 ESP_LOGCONFIG(TAG, " %s: not available yet", LOG_STR_ARG(model_strings(this->conversion_).reference));
118 }
119 LOG_SENSOR(" ", "Voltage", this->voltage_sensor_);
120 LOG_SENSOR(" ", "Ratio", this->ratio_sensor_);
121 LOG_SENSOR(" ", "RS", this->rs_sensor_);
122#ifdef MICS_5524_GAS_COUNT
123 for (auto *gas : this->gases_) {
124 LOG_SENSOR(" ", "Gas", gas);
125 ESP_LOGCONFIG(TAG, " Range: %.1f - %.1f ppm", gas->get_min_ppm(), gas->get_max_ppm());
126 }
127#endif
128}
129
130float MiCS5524Component::sample_voltage_() {
131 // Taken back to back; waiting between them would block the main loop.
132 float sum = 0.0f;
133 for (uint8_t i = 0; i < this->samples_; i++)
134 sum += this->source_->sample();
135 return (sum / static_cast<float>(this->samples_)) * this->voltage_multiplier_;
136}
137
139 float value = micsmath::air_value_from_voltage(voltage, this->vcc_);
140#ifdef USE_MICS_5524_DATASHEET
141 if (!this->is_vendor_model_())
142 value = micsmath::rs_from_voltage(voltage, this->vcc_, this->rl_);
143#endif
144 if (!std::isnan(value)) {
145 this->input_fault_ = false;
146 return value;
147 }
148 // Logged once per fault; the status flag cannot tell it from a failed calibration.
149 if (!this->input_fault_) {
150 this->input_fault_ = true;
151 ESP_LOGW(TAG, "analog output reads %.4f V with vcc %.2f V\n check the AO wiring, 'vcc:' and 'voltage_multiplier:'",
152 voltage, this->vcc_);
153 }
154 this->status_set_warning(LOG_STR("analog output out of range"));
155 return NAN;
156}
157
159#ifdef MICS_5524_GAS_COUNT
160 for (auto *gas : this->gases_) {
161 gas->publish_ratio(ratio, this->conversion_);
162 }
163#endif
164}
165
166void MiCS5524Component::publish_diagnostics_(float voltage, float ratio, float rs) {
167 PUBLISH_STATE(this->voltage_sensor_, voltage);
168 PUBLISH_STATE(this->ratio_sensor_, ratio);
169 // Validation rejects `rs_sensor:` under the vendor model.
170 PUBLISH_STATE(this->rs_sensor_, rs);
171}
172
174 if (!this->has_reference_() && this->voltage_sensor_ == nullptr && this->ratio_sensor_ == nullptr &&
175 this->rs_sensor_ == nullptr)
176 return;
177
178 const float voltage = this->sample_voltage_();
179 const float value = this->model_value_(voltage);
180 float ratio = NAN;
181 if (this->has_reference_()) {
182 ratio = this->is_vendor_model_() ? micsmath::ratio_from_air_value(value, this->reference_)
183 : micsmath::ratio_from_rs(value, this->reference_);
184 }
185 this->publish_diagnostics_(voltage, ratio, value);
186
187 // A failed calibration keeps its warning until the retry succeeds.
188 if (!std::isnan(value) && !this->calibrating_ && !this->calibration_pending_)
189 this->status_clear_warning();
190
191 // Every gas starts unknown and the reference is never cleared, so there is nothing to republish.
192 if (!this->has_reference_())
193 return;
194
195 ESP_LOGD(TAG, "V_AO=%.4f V, ratio=%.4f", voltage, ratio);
196 this->publish_ratio_(ratio);
197}
198
199void MiCS5524Component::set_calibration(uint32_t delay, uint32_t samples, uint32_t sample_interval, bool persist,
200 bool at_boot) {
202 this->calibration_samples_ = samples;
203 this->sample_interval_ = sample_interval;
204 this->persist_ = persist;
205 this->calibrate_at_boot_ = at_boot;
206}
207
209 if (this->calibrating_) {
210 ESP_LOGW(TAG, "calibration already running");
211 return;
212 }
213 if (this->calibration_pending_) {
214 ESP_LOGW(TAG, "calibration already requested");
215 return;
216 }
217 this->calibration_pending_ = true;
218 if (this->warming_up_) {
219 // A request must never capture an unstable reading; the warm-up timeout starts it.
220 ESP_LOGI(TAG, "calibration requested - waiting for the warm-up window to end");
221 return;
222 }
223 this->schedule_calibration_(0);
224 ESP_LOGI(TAG, "calibration requested - keep the sensor in clean air");
225}
226
228 if (!this->calibrating_) {
229 // Only a calibration samples here; the deferred start is a timer.
230 this->disable_loop();
231 return;
232 }
233
236 return;
237
238 this->calibration_last_sample_ = now;
239 this->process_calibration_();
240}
241
245
247 this->calibration_pending_ = false;
248 this->calibrating_ = true;
250 this->calibration_count_ = 0;
251 this->calibration_attempts_ = 0;
252 this->calibration_sum_ = 0.0f;
253 this->calibration_min_ = INFINITY;
254 this->calibration_max_ = -INFINITY;
255 this->enable_loop();
256
257 ESP_LOGI(TAG, "calibrating the %s, %" PRIu32 " samples - keep the sensor in clean air",
258 LOG_STR_ARG(model_strings(this->conversion_).reference), this->calibration_samples_);
259}
260
262 this->calibration_attempts_++;
263
264 // The samples are averaged in the units of the active model.
265 const float reference = this->model_value_(this->sample_voltage_());
266 if (!std::isnan(reference)) {
267 this->calibration_min_ = std::min(this->calibration_min_, reference);
268 this->calibration_max_ = std::max(this->calibration_max_, reference);
269 this->calibration_sum_ += reference;
270 this->calibration_count_++;
271 }
272
274 this->finish_calibration_();
275}
276
278 this->calibrating_ = false;
279 this->disable_loop();
280
281 const uint32_t attempts = this->calibration_attempts_;
282 const uint32_t valid = this->calibration_count_;
283 // A majority of the attempts has to have produced a sample, two at least.
284 const uint32_t required = std::max<uint32_t>((attempts + 1) / 2, 2);
285
286 if (valid < required) {
287 ESP_LOGW(TAG, "calibration failed, %" PRIu32 " of %" PRIu32 " samples were valid", valid, attempts);
289 return;
290 }
291
292 const float reference = this->calibration_sum_ / static_cast<float>(valid);
293
294 // A sensor still settling, or not in clean air, varies too much to be the reference.
296 ESP_LOGW(TAG, "clean-air samples spread %.4f around %.4f (%.4f - %.4f)\n the sensor was not settled in clean air",
297 this->calibration_max_ - this->calibration_min_, reference, this->calibration_min_,
298 this->calibration_max_);
300 return;
301 }
302
303 this->reference_ = reference;
304 this->status_clear_warning();
305 const bool stored = this->persist_ && this->save_reference_();
306
307 const ModelStrings strings = model_strings(this->conversion_);
308 ESP_LOGI(TAG,
309 "%s = %.4f (%" PRIu32 "/%" PRIu32 " samples valid)%s\n"
310 " hard-code '%s: %.4f' to skip the calibration at boot",
311 LOG_STR_ARG(strings.reference), this->reference_, valid, attempts,
312 stored ? LOG_STR_LITERAL(", stored in flash")
313 : this->persist_ ? LOG_STR_LITERAL("")
314 : LOG_STR_LITERAL(", kept until reboot"),
315 LOG_STR_ARG(strings.key), this->reference_);
316}
317
319 this->status_set_warning();
320 this->calibration_pending_ = true;
321 // A zero delay would log the same failure about five times per second.
323 this->schedule_calibration_(delay);
324 ESP_LOGW(TAG, "retrying the calibration in %" PRIu32 " s", delay / 1000);
325}
326
328 if (!this->reference_pref_.save(&this->reference_)) {
329 ESP_LOGW(TAG, "could not store the %s in flash", LOG_STR_ARG(model_strings(this->conversion_).reference));
330 return false;
331 }
332 // Once per calibration, so write it out now rather than at the next preferences sync
333 this->reference_pref_.sync();
334 ESP_LOGD(TAG, "%s %.4f saved", LOG_STR_ARG(model_strings(this->conversion_).reference), this->reference_);
335 return true;
336}
337
339 float stored = 0.0f;
340 if (!this->reference_pref_.load(&stored))
341 return false;
342 if (!std::isfinite(stored) || stored <= 0.0f) {
343 ESP_LOGW(TAG, "ignoring the stored %s %.4f, calibrating again",
344 LOG_STR_ARG(model_strings(this->conversion_).reference), stored);
345 return false;
346 }
347 this->reference_ = stored;
348 return true;
349}
350
351} // 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:262
void disable_loop()
Disable this component's loop.
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
bool sync()
Write this preference to flash now; ESP8266, RP2040, LibreTiny and host also write the other pending ...
const LogString * get_log_name() const
Get the name for a "%s" log argument (LOG_STR_ARG).
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:59
ESPPreferences * global_preferences
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
void HOT delay(uint32_t ms)
Definition hal.cpp:78
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