ESPHome 2025.6.0
Loading...
Searching...
No Matches
veml7700.cpp
Go to the documentation of this file.
1#include "veml7700.h"
3#include "esphome/core/log.h"
4
5namespace esphome {
6namespace veml7700 {
7
8static const char *const TAG = "veml7700";
9static const size_t VEML_REG_SIZE = 2;
10
11static float reduce_to_zero(float a, float b) { return (a > b) ? (a - b) : 0; }
12
13template<typename T, size_t size> T get_next(const T (&array)[size], const T val) {
14 size_t i = 0;
15 size_t idx = -1;
16 while (idx == -1 && i < size) {
17 if (array[i] == val) {
18 idx = i;
19 break;
20 }
21 i++;
22 }
23 if (idx == -1 || i + 1 >= size)
24 return val;
25 return array[i + 1];
26}
27
28template<typename T, size_t size> T get_prev(const T (&array)[size], const T val) {
29 size_t i = size - 1;
30 size_t idx = -1;
31 while (idx == -1 && i > 0) {
32 if (array[i] == val) {
33 idx = i;
34 break;
35 }
36 i--;
37 }
38 if (idx == -1 || i == 0)
39 return val;
40 return array[i - 1];
41}
42
43static uint16_t get_itime_ms(IntegrationTime time) {
44 uint16_t ms = 0;
45 switch (time) {
47 ms = 100;
48 break;
50 ms = 200;
51 break;
53 ms = 400;
54 break;
56 ms = 800;
57 break;
59 ms = 50;
60 break;
62 ms = 25;
63 break;
64 default:
65 ms = 100;
66 }
67 return ms;
68}
69
70static float get_gain_coeff(Gain gain) {
71 static const float GAIN_FLOAT[GAINS_COUNT] = {1.0f, 2.0f, 0.125f, 0.25f};
72 return GAIN_FLOAT[gain & 0b11];
73}
74
75static const char *get_gain_str(Gain gain) {
76 static const char *gain_str[GAINS_COUNT] = {"1x", "2x", "1/8x", "1/4x"};
77 return gain_str[gain & 0b11];
78}
79
81 ESP_LOGCONFIG(TAG, "Running setup");
82
83 auto err = this->configure_();
84 if (err != i2c::ERROR_OK) {
85 ESP_LOGW(TAG, "Sensor configuration failed");
86 this->mark_failed();
87 } else {
88 this->state_ = State::INITIAL_SETUP_COMPLETED;
89 }
90}
91
93 LOG_I2C_DEVICE(this);
94 ESP_LOGCONFIG(TAG, " Automatic gain/time: %s", YESNO(this->automatic_mode_enabled_));
95 if (!this->automatic_mode_enabled_) {
96 ESP_LOGCONFIG(TAG,
97 " Gain: %s\n"
98 " Integration time: %d ms",
99 get_gain_str(this->gain_), get_itime_ms(this->integration_time_));
100 }
101 ESP_LOGCONFIG(TAG,
102 " Lux compensation: %s\n"
103 " Glass attenuation factor: %f",
105 LOG_UPDATE_INTERVAL(this);
106
107 LOG_SENSOR(" ", "ALS channel lux", this->ambient_light_sensor_);
108 LOG_SENSOR(" ", "ALS channel counts", this->ambient_light_counts_sensor_);
109 LOG_SENSOR(" ", "WHITE channel lux", this->white_sensor_);
110 LOG_SENSOR(" ", "WHITE channel counts", this->white_counts_sensor_);
111 LOG_SENSOR(" ", "FAKE_IR channel lux", this->fake_infrared_sensor_);
112 LOG_SENSOR(" ", "Actual gain", this->actual_gain_sensor_);
113 LOG_SENSOR(" ", "Actual integration time", this->actual_integration_time_sensor_);
114
115 if (this->is_failed()) {
116 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
117 }
118}
119
121 if (this->is_ready() && this->state_ == State::IDLE) {
122 ESP_LOGV(TAG, "Update: Initiating new data collection");
123
125
126 this->readings_.als_counts = 0;
127 this->readings_.white_counts = 0;
129 this->readings_.actual_gain = this->gain_;
130 this->readings_.als_lux = 0;
131 this->readings_.white_lux = 0;
133 } else {
134 ESP_LOGV(TAG, "Update: Component not ready yet");
135 }
136}
137
140
141 if (this->state_ == State::INITIAL_SETUP_COMPLETED) {
142 // Datasheet: 2.5 ms before the first measurement is needed, allowing for the correct start of the signal processor
143 // and oscillator.
144 // Reality: wait for couple integration times to have first samples captured
145 this->set_timeout(2 * this->integration_time_, [this]() { this->state_ = State::IDLE; });
146 }
147
148 if (this->is_ready()) {
149 switch (this->state_) {
150 case State::IDLE:
151 // doing nothing, having best time
152 break;
153
155 err = this->read_sensor_output_(this->readings_);
156 this->state_ = (err == i2c::ERROR_OK) ? State::DATA_COLLECTED : State::IDLE;
157 break;
158
159 case State::COLLECTING_DATA_AUTO: // Automatic mode - we start here to reconfigure device first
161 if (!this->are_adjustments_required_(this->readings_)) {
162 this->state_ = State::READY_TO_PUBLISH_PART_1;
163 } else {
164 // if sensitivity adjustment needed -
165 // shutdown device to change config and wait one integration time period
166 this->state_ = State::ADJUSTMENT_IN_PROGRESS;
167 err = this->reconfigure_time_and_gain_(this->readings_.actual_time, this->readings_.actual_gain, true);
168 if (err == i2c::ERROR_OK) {
169 this->set_timeout(1 * get_itime_ms(this->readings_.actual_time),
170 [this]() { this->state_ = State::READY_TO_APPLY_ADJUSTMENTS; });
171 } else {
172 this->state_ = State::IDLE;
173 }
174 }
175 break;
176
178 // nothing to be done, just waiting for the timeout
179 break;
180
182 // second stage of sensitivity adjustment - turn device back on
183 // and wait 2-3 integration time periods to get good data samples
184 this->state_ = State::ADJUSTMENT_IN_PROGRESS;
185 err = this->reconfigure_time_and_gain_(this->readings_.actual_time, this->readings_.actual_gain, false);
186 if (err == i2c::ERROR_OK) {
187 this->set_timeout(3 * get_itime_ms(this->readings_.actual_time),
188 [this]() { this->state_ = State::COLLECTING_DATA; });
189 } else {
190 this->state_ = State::IDLE;
191 }
192 break;
193
195 this->status_clear_warning();
196
200
201 this->publish_data_part_1_(this->readings_);
202 this->state_ = State::READY_TO_PUBLISH_PART_2;
203 break;
204
206 this->publish_data_part_2_(this->readings_);
207 this->state_ = State::READY_TO_PUBLISH_PART_3;
208 break;
209
211 this->publish_data_part_3_(this->readings_);
212 this->state_ = State::IDLE;
213 break;
214
215 default:
216 break;
217 }
218 if (err != i2c::ERROR_OK)
219 this->status_set_warning();
220 }
221}
222
224 ESP_LOGV(TAG, "Configure");
225
226 ConfigurationRegister als_conf{0};
227 als_conf.ALS_INT_EN = false;
228 als_conf.ALS_PERS = Persistence::PERSISTENCE_1;
229 als_conf.ALS_IT = this->integration_time_;
230 als_conf.ALS_GAIN = this->gain_;
231
232 als_conf.ALS_SD = true;
233 ESP_LOGV(TAG, "Shutdown before config. ALS_CONF_0 to 0x%04X", als_conf.raw);
234 auto err = this->write_register((uint8_t) CommandRegisters::ALS_CONF_0, als_conf.raw_bytes, VEML_REG_SIZE);
235 if (err != i2c::ERROR_OK) {
236 ESP_LOGW(TAG, "Failed to shutdown, I2C error %d", err);
237 return err;
238 }
239 delay(3);
240
241 als_conf.ALS_SD = false;
242 ESP_LOGV(TAG, "Turning on. Setting ALS_CONF_0 to 0x%04X", als_conf.raw);
243 err = this->write_register((uint8_t) CommandRegisters::ALS_CONF_0, als_conf.raw_bytes, VEML_REG_SIZE);
244 if (err != i2c::ERROR_OK) {
245 ESP_LOGW(TAG, "Failed to turn on, I2C error %d", err);
246 return err;
247 }
248
249 PSMRegister psm{0};
251 psm.PSM_EN = false;
252 ESP_LOGV(TAG, "Setting PSM to 0x%04X", psm.raw);
253 err = this->write_register((uint8_t) CommandRegisters::PWR_SAVING, psm.raw_bytes, VEML_REG_SIZE);
254 if (err != i2c::ERROR_OK) {
255 ESP_LOGW(TAG, "Failed to set PSM, I2C error %d", err);
256 return err;
257 }
258
259 return err;
260}
261
263 ESP_LOGV(TAG, "Reconfigure time and gain (%d ms, %s) %s", get_itime_ms(time), get_gain_str(gain),
264 shutdown ? "Shutting down" : "Turning back on");
265
266 ConfigurationRegister als_conf{0};
267 als_conf.raw = 0;
268
269 // We have to before changing parameters
270 als_conf.ALS_SD = shutdown;
271 als_conf.ALS_INT_EN = false;
272 als_conf.ALS_PERS = Persistence::PERSISTENCE_1;
273 als_conf.ALS_IT = time;
274 als_conf.ALS_GAIN = gain;
275 auto err = this->write_register((uint8_t) CommandRegisters::ALS_CONF_0, als_conf.raw_bytes, VEML_REG_SIZE);
276 if (err != i2c::ERROR_OK) {
277 ESP_LOGW(TAG, "%s failed", shutdown ? "Shutdown" : "Turn on");
278 }
279
280 return err;
281}
282
284 auto als_err =
285 this->read_register((uint8_t) CommandRegisters::ALS, (uint8_t *) &data.als_counts, VEML_REG_SIZE, false);
286 if (als_err != i2c::ERROR_OK) {
287 ESP_LOGW(TAG, "Error reading ALS register, err = %d", als_err);
288 }
289 auto white_err =
290 this->read_register((uint8_t) CommandRegisters::WHITE, (uint8_t *) &data.white_counts, VEML_REG_SIZE, false);
291 if (white_err != i2c::ERROR_OK) {
292 ESP_LOGW(TAG, "Error reading WHITE register, err = %d", white_err);
293 }
294
295 ConfigurationRegister conf{0};
296 auto err =
297 this->read_register((uint8_t) CommandRegisters::ALS_CONF_0, (uint8_t *) conf.raw_bytes, VEML_REG_SIZE, false);
298 if (err != i2c::ERROR_OK) {
299 ESP_LOGW(TAG, "Error reading ALS_CONF_0 register, err = %d", white_err);
300 }
301 data.actual_time = conf.ALS_IT;
302 data.actual_gain = conf.ALS_GAIN;
303
304 ESP_LOGV(TAG, "Data from sensors: ALS = %d, WHITE = %d, Gain = %s, Time = %d ms", data.als_counts, data.white_counts,
305 get_gain_str(data.actual_gain), get_itime_ms(data.actual_time));
306 return std::max(als_err, white_err);
307}
308
310 // skip first sample in auto mode -
311 // we need to reconfigure device after last measurement
312 if (this->state_ == State::COLLECTING_DATA_AUTO)
313 return true;
314
315 if (!this->automatic_mode_enabled_)
316 return false;
317
318 // Recommended thresholds as per datasheet
319 static constexpr uint16_t LOW_INTENSITY_THRESHOLD = 100;
320 static constexpr uint16_t HIGH_INTENSITY_THRESHOLD = 10000;
321
325 static const Gain GAINS[GAINS_COUNT] = {X_1_8, X_1_4, X_1, X_2};
326
327 if (data.als_counts <= LOW_INTENSITY_THRESHOLD) {
328 Gain next_gain = get_next(GAINS, data.actual_gain);
329 if (next_gain != data.actual_gain) {
330 data.actual_gain = next_gain;
331 return true;
332 }
333 IntegrationTime next_time = get_next(TIMES, data.actual_time);
334 if (next_time != data.actual_time) {
335 data.actual_time = next_time;
336 return true;
337 }
338 } else if (data.als_counts >= HIGH_INTENSITY_THRESHOLD) {
339 Gain prev_gain = get_prev(GAINS, data.actual_gain);
340 if (prev_gain != data.actual_gain) {
341 data.actual_gain = prev_gain;
342 return true;
343 }
344 IntegrationTime prev_time = get_prev(TIMES, data.actual_time);
345 if (prev_time != data.actual_time) {
346 data.actual_time = prev_time;
347 return true;
348 }
349 }
350
351 // Counts are either good (between thresholds)
352 // or there is no room to change sensitivity anymore
353 return false;
354}
355
357 static const float MAX_GAIN = 2.0f;
358 static const float MAX_ITIME_MS = 800.0f;
359 static const float MAX_LX_RESOLUTION = 0.0036f;
360 float lux_resolution = (MAX_ITIME_MS / (float) get_itime_ms(data.actual_time)) *
361 (MAX_GAIN / get_gain_coeff(data.actual_gain)) * MAX_LX_RESOLUTION;
362 ESP_LOGV(TAG, "Lux resolution for (%d, %s) = %.4f ", get_itime_ms(data.actual_time), get_gain_str(data.actual_gain),
363 lux_resolution);
364
365 data.als_lux = lux_resolution * (float) data.als_counts;
366 data.white_lux = lux_resolution * (float) data.white_counts;
367 data.fake_infrared_lux = reduce_to_zero(data.white_lux, data.als_lux);
368
369 ESP_LOGV(TAG, "%s mode - ALS = %.1f lx, WHITE = %.1f lx, FAKE_IR = %.1f lx",
370 this->automatic_mode_enabled_ ? "Automatic" : "Manual", data.als_lux, data.white_lux,
371 data.fake_infrared_lux);
372}
373
375 if (!this->lux_compensation_enabled_)
376 return;
377 auto &local_data = data;
378 // Always apply correction for G1/4 and G1/8
379 // Other Gains G1 and G2 are not supposed to be used for lux > 1000,
380 // corrections may help, but not a lot.
381 //
382 // "Illumination values higher than 1000 lx show non-linearity.
383 // This non-linearity is the same for all sensors, so a compensation formula can be applied
384 // if this light level is exceeded"
385 auto compensate = [&local_data](float &lux) {
386 auto calculate_high_lux_compensation = [](float lux_veml) -> float {
387 return (((6.0135e-13 * lux_veml - 9.3924e-9) * lux_veml + 8.1488e-5) * lux_veml + 1.0023) * lux_veml;
388 };
389
390 if (lux > 1000.0f || local_data.actual_gain == Gain::X_1_8 || local_data.actual_gain == Gain::X_1_4) {
391 lux = calculate_high_lux_compensation(lux);
392 }
393 };
394
395 compensate(data.als_lux);
396 compensate(data.white_lux);
397 data.fake_infrared_lux = reduce_to_zero(data.white_lux, data.als_lux);
398
399 ESP_LOGV(TAG, "Lux compensation - ALS = %.1f lx, WHITE = %.1f lx, FAKE_IR = %.1f lx", data.als_lux, data.white_lux,
400 data.fake_infrared_lux);
401}
402
406 data.fake_infrared_lux = reduce_to_zero(data.white_lux, data.als_lux);
407 ESP_LOGV(TAG, "Glass attenuation - ALS = %.1f lx, WHITE = %.1f lx, FAKE_IR = %.1f lx", data.als_lux, data.white_lux,
408 data.fake_infrared_lux);
409}
410
412 if (this->ambient_light_sensor_ != nullptr) {
414 }
415 if (this->white_sensor_ != nullptr) {
417 }
418}
419
421 if (this->fake_infrared_sensor_ != nullptr) {
423 }
424 if (this->ambient_light_counts_sensor_ != nullptr) {
426 }
427 if (this->white_counts_sensor_ != nullptr) {
429 }
430}
431
433 if (this->actual_gain_sensor_ != nullptr) {
434 this->actual_gain_sensor_->publish_state(get_gain_coeff(data.actual_gain));
435 }
436 if (this->actual_integration_time_sensor_ != nullptr) {
438 }
439}
440} // namespace veml7700
441} // namespace esphome
virtual void mark_failed()
Mark this component as failed.
bool is_failed() const
bool is_ready() const
void status_set_warning(const char *message="unspecified")
void status_clear_warning()
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition component.cpp:75
ErrorCode write_register(uint8_t a_register, const uint8_t *data, size_t len, bool stop=true)
writes an array of bytes to a specific register in the I²C device
Definition i2c.cpp:25
ErrorCode read_register(uint8_t a_register, uint8_t *data, size_t len, bool stop=true)
reads an array of bytes from a specific register in the I²C device
Definition i2c.cpp:10
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:39
void publish_data_part_1_(Readings &data)
Definition veml7700.cpp:411
void publish_data_part_2_(Readings &data)
Definition veml7700.cpp:420
void publish_data_part_3_(Readings &data)
Definition veml7700.cpp:432
sensor::Sensor * white_counts_sensor_
Definition veml7700.h:195
void apply_glass_attenuation_(Readings &data)
Definition veml7700.cpp:403
sensor::Sensor * ambient_light_counts_sensor_
Definition veml7700.h:193
bool are_adjustments_required_(Readings &data)
Definition veml7700.cpp:309
ErrorCode reconfigure_time_and_gain_(IntegrationTime time, Gain gain, bool shutdown)
Definition veml7700.cpp:262
sensor::Sensor * actual_integration_time_sensor_
Definition veml7700.h:198
void apply_lux_calculation_(Readings &data)
Definition veml7700.cpp:356
struct esphome::veml7700::VEML7700Component::Readings readings_
sensor::Sensor * fake_infrared_sensor_
Definition veml7700.h:196
void apply_lux_compensation_(Readings &data)
Definition veml7700.cpp:374
sensor::Sensor * ambient_light_sensor_
Definition veml7700.h:192
ErrorCode read_sensor_output_(Readings &data)
Definition veml7700.cpp:283
AlsGain501 gain
mopeka_std_values val[4]
ErrorCode
Error codes returned by I2CBus and I2CDevice methods.
Definition i2c_bus.h:11
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:13
T get_prev(const T(&array)[size], const T val)
Definition veml7700.cpp:28
T get_next(const T(&array)[size], const T val)
Definition veml7700.cpp:13
const uint8_t INTEGRATION_TIMES_COUNT
Definition veml7700.h:43
const uint8_t GAINS_COUNT
Definition veml7700.h:33
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29