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