ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
ltr_als_ps.cpp
Go to the documentation of this file.
1#include "ltr_als_ps.h"
4#include "esphome/core/log.h"
5#include <limits>
6
8
10
11ESPHOME_LOG_TAG(TAG, "ltr_als_ps");
12
13static const uint8_t MAX_TRIES = 5;
14
15template<typename T, size_t size> T get_next(const T (&array)[size], const T val) {
16 size_t i = 0;
17 size_t idx = std::numeric_limits<size_t>::max();
18 while (idx == std::numeric_limits<size_t>::max() && i < size) {
19 if (array[i] == val) {
20 idx = i;
21 break;
22 }
23 i++;
24 }
25 if (idx == std::numeric_limits<size_t>::max() || i + 1 >= size)
26 return val;
27 return array[i + 1];
28}
29
30template<typename T, size_t size> T get_prev(const T (&array)[size], const T val) {
31 size_t i = size - 1;
32 size_t idx = std::numeric_limits<size_t>::max();
33 while (idx == std::numeric_limits<size_t>::max() && i > 0) {
34 if (array[i] == val) {
35 idx = i;
36 break;
37 }
38 i--;
39 }
40 if (idx == std::numeric_limits<size_t>::max() || i == 0)
41 return val;
42 return array[i - 1];
43}
44
45static uint16_t get_itime_ms(IntegrationTime time) {
46 static const uint16_t ALS_INT_TIME[8] = {100, 50, 200, 400, 150, 250, 300, 350};
47 return ALS_INT_TIME[time & 0b111];
48}
49
50static uint16_t get_meas_time_ms(MeasurementRepeatRate rate) {
51 static const uint16_t ALS_MEAS_RATE[8] = {50, 100, 200, 500, 1000, 2000, 2000, 2000};
52 return ALS_MEAS_RATE[rate & 0b111];
53}
54
55static float get_gain_coeff(AlsGain gain) {
56 static const float ALS_GAIN[8] = {1, 2, 4, 8, 0, 0, 48, 96};
57 return ALS_GAIN[gain & 0b111];
58}
59
60static float get_ps_gain_coeff(PsGain gain) {
61 static const float PS_GAIN[4] = {16, 0, 32, 64};
62 return PS_GAIN[gain & 0b11];
63}
64
66 // As per datasheet we need to wait at least 100ms after power on to get ALS chip responsive
67 this->set_timeout(100, [this]() { this->state_ = State::DELAYED_SETUP; });
68}
69
71 auto get_device_type = [](LtrType typ) {
72 switch (typ) {
74 return "ALS only";
76 return "PS only";
78 return "ALS + PS";
79 default:
80 return "Unknown";
81 }
82 };
83
84 LOG_I2C_DEVICE(this);
85 ESP_LOGCONFIG(TAG, " Device type: %s", get_device_type(this->ltr_type_));
86 if (this->is_als_()) {
87 ESP_LOGCONFIG(TAG,
88 " Automatic mode: %s\n"
89 " Gain: %.0fx\n"
90 " Integration time: %d ms\n"
91 " Measurement repeat rate: %d ms\n"
92 " Glass attenuation factor: %f",
93 ONOFF(this->automatic_mode_enabled_), get_gain_coeff(this->gain_),
94 get_itime_ms(this->integration_time_), get_meas_time_ms(this->repeat_rate_),
96 LOG_SENSOR(" ", "ALS calculated lux", this->ambient_light_sensor_);
97 LOG_SENSOR(" ", "CH1 Infrared counts", this->infrared_counts_sensor_);
98 LOG_SENSOR(" ", "CH0 Visible+IR counts", this->full_spectrum_counts_sensor_);
99 LOG_SENSOR(" ", "Actual gain", this->actual_gain_sensor_);
100 }
101 if (this->is_ps_()) {
102 ESP_LOGCONFIG(TAG,
103 " Proximity gain: %.0fx\n"
104 " Proximity cooldown time: %d s\n"
105 " Proximity high threshold: %d\n"
106 " Proximity low threshold: %d",
107 get_ps_gain_coeff(this->ps_gain_), this->ps_cooldown_time_s_, this->ps_threshold_high_,
108 this->ps_threshold_low_);
109 LOG_SENSOR(" ", "Proximity counts", this->proximity_counts_sensor_);
110 }
111 LOG_UPDATE_INTERVAL(this);
112}
113
115 ESP_LOGV(TAG, "Updating");
116 if (this->is_ready() && this->state_ == State::IDLE) {
117 ESP_LOGV(TAG, "Initiating new data collection");
118
120
121 this->als_readings_.ch0 = 0;
122 this->als_readings_.ch1 = 0;
123 this->als_readings_.gain = this->gain_;
125 this->als_readings_.lux = 0;
127
128 } else {
129 ESP_LOGV(TAG, "Component not ready yet");
130 }
131}
132
135
136 switch (this->state_) {
138 err = this->write(nullptr, 0);
139 if (err != i2c::ERROR_OK) {
140 ESP_LOGV(TAG, "i2c connection failed");
141 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
142 }
143 this->configure_reset_();
144 if (this->is_als_()) {
145 this->configure_als_();
147 }
148 if (this->is_ps_()) {
149 this->configure_ps_();
150 }
151
152 this->state_ = State::IDLE;
153 break;
154
155 case State::IDLE:
156 if (this->is_ps_()) {
158 }
159 break;
160
163 this->read_data_tries_ = 0;
164 ESP_LOGV(TAG, "Reading sensor data having gain = %.0fx, time = %d ms", get_gain_coeff(this->als_readings_.gain),
165 get_itime_ms(this->als_readings_.integration_time));
166 this->read_sensor_data_(this->als_readings_);
167 this->state_ = State::DATA_COLLECTED;
169 } else if (this->read_data_tries_ >= MAX_TRIES) {
170 ESP_LOGW(TAG, "Can't get data after several tries.");
171 this->read_data_tries_ = 0;
172 this->status_set_warning();
173 this->state_ = State::IDLE;
174 return;
175 } else {
176 this->read_data_tries_++;
177 }
178 break;
179
182 // first measurement in auto mode (COLLECTING_DATA_AUTO state) require device reconfiguration
183 if (this->state_ == State::COLLECTING_DATA_AUTO || this->are_adjustments_required_(this->als_readings_)) {
184 this->state_ = State::ADJUSTMENT_IN_PROGRESS;
185 ESP_LOGD(TAG, "Reconfiguring sensitivity: gain = %.0fx, time = %d ms", get_gain_coeff(this->als_readings_.gain),
186 get_itime_ms(this->als_readings_.integration_time));
189 // if sensitivity adjustment needed - need to wait for first data samples after setting new parameters
190 this->set_timeout(2 * get_meas_time_ms(this->repeat_rate_),
191 [this]() { this->state_ = State::WAITING_FOR_DATA; });
192 } else {
193 this->state_ = State::READY_TO_PUBLISH;
194 }
195 break;
196
198 // nothing to be done, just waiting for the timeout
199 break;
200
203 this->state_ = State::KEEP_PUBLISHING;
204 break;
205
208 this->status_clear_warning();
209 this->state_ = State::IDLE;
210 break;
211
212 default:
213 break;
214 }
215}
216
218 uint16_t ps_data = this->read_ps_data_();
219 uint32_t now = millis();
220
221 if (ps_data != this->ps_readings_) {
222 this->ps_readings_ = ps_data;
223 // Higher values - object is closer to sensor
224 if (ps_data > this->ps_threshold_high_ &&
225 now - this->last_ps_high_trigger_time_ >= this->ps_cooldown_time_s_ * 1000) {
226 this->last_ps_high_trigger_time_ = now;
227 ESP_LOGV(TAG, "Proximity high threshold triggered. Value = %d, Trigger level = %d", ps_data,
228 this->ps_threshold_high_);
229 this->on_ps_high_trigger_callback_.call();
230 } else if (ps_data < this->ps_threshold_low_ &&
231 now - this->last_ps_low_trigger_time_ >= this->ps_cooldown_time_s_ * 1000) {
232 this->last_ps_low_trigger_time_ = now;
233 ESP_LOGV(TAG, "Proximity low threshold triggered. Value = %d, Trigger level = %d", ps_data,
234 this->ps_threshold_low_);
235 this->on_ps_low_trigger_callback_.call();
236 }
237 }
238}
239
241 uint8_t manuf_id = this->reg((uint8_t) CommandRegisters::MANUFAC_ID).get();
242 if (manuf_id != 0x05) { // 0x05 is Lite-On Semiconductor Corp. ID
243 ESP_LOGW(TAG, "Unknown manufacturer ID: 0x%02X", manuf_id);
244 this->mark_failed();
245 return false;
246 }
247
248 // Things getting not really funny here, we can't identify device type by part number ID
249 // ======================== ========= ===== =================
250 // Device Part ID Rev Capabilities
251 // ======================== ========= ===== =================
252 // Ltr-329/ltr-303 0x0a 0x00 Als 16b
253 // Ltr-553/ltr-556/ltr-556 0x09 0x02 Als 16b + Ps 11b diff nm sens
254 // Ltr-659 0x09 0x02 Ps 11b and ps gain
255 //
256 // There are other devices which might potentially work with default settings,
257 // but registers layout is different and we can't use them properly. For ex. ltr-558
258
259 PartIdRegister part_id{0};
260 part_id.raw = this->reg((uint8_t) CommandRegisters::PART_ID).get();
261 if (part_id.part_number_id != 0x0a && part_id.part_number_id != 0x09) {
262 ESP_LOGW(TAG, "Unknown part number ID: 0x%02X. It might not work properly.", part_id.part_number_id);
263 this->status_set_warning();
264 return true;
265 }
266 return true;
267}
268
270 ESP_LOGV(TAG, "Resetting");
271
272 AlsControlRegister als_ctrl{0};
273 als_ctrl.sw_reset = true;
274 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
275 delay(2);
276
277 uint8_t tries = MAX_TRIES;
278 do {
279 ESP_LOGV(TAG, "Waiting for chip to reset");
280 delay(2);
281 als_ctrl.raw = this->reg((uint8_t) CommandRegisters::ALS_CONTR).get();
282 } while (als_ctrl.sw_reset && tries--); // while sw reset bit is on - keep waiting
283
284 if (als_ctrl.sw_reset) {
285 ESP_LOGW(TAG, "Reset timed out");
286 }
287}
288
290 AlsControlRegister als_ctrl{0};
291
292 als_ctrl.sw_reset = false;
293 als_ctrl.active_mode = true;
294 als_ctrl.gain = this->gain_;
295
296 ESP_LOGV(TAG, "Setting active mode and gain reg 0x%02X", als_ctrl.raw);
297 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
298 delay(5);
299
300 uint8_t tries = MAX_TRIES;
301 do {
302 ESP_LOGV(TAG, "Waiting for device to become active");
303 delay(2);
304 als_ctrl.raw = this->reg((uint8_t) CommandRegisters::ALS_CONTR).get();
305 } while (!als_ctrl.active_mode && tries--); // while active mode is not set - keep waiting
306
307 if (!als_ctrl.active_mode) {
308 ESP_LOGW(TAG, "Failed to activate device");
309 }
310}
311
313 PsMeasurementRateRegister ps_meas{0};
315 this->reg((uint8_t) CommandRegisters::PS_MEAS_RATE) = ps_meas.raw;
316
317 PsControlRegister ps_ctrl{0};
318 ps_ctrl.ps_mode_active = true;
319 ps_ctrl.ps_mode_xxx = true;
320 this->reg((uint8_t) CommandRegisters::PS_CONTR) = ps_ctrl.raw;
321}
322
324 AlsPsStatusRegister als_status{0};
325 als_status.raw = this->reg((uint8_t) CommandRegisters::ALS_PS_STATUS).get();
326 if (!als_status.ps_new_data || als_status.data_invalid) {
327 return this->ps_readings_;
328 }
329
330 uint8_t ps_low = this->reg((uint8_t) CommandRegisters::PS_DATA_0).get();
331 PsData1Register ps_high;
332 ps_high.raw = this->reg((uint8_t) CommandRegisters::PS_DATA_1).get();
333
334 uint16_t val = encode_uint16(ps_high.ps_data_high, ps_low);
335 if (ps_high.ps_saturation_flag) {
336 return 0x7ff; // full 11 bit range
337 }
338 return val;
339}
340
342 AlsControlRegister als_ctrl{0};
343 als_ctrl.active_mode = true;
344 als_ctrl.gain = gain;
345 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
346 delay(2);
347
348 AlsControlRegister read_als_ctrl{0};
349 read_als_ctrl.raw = this->reg((uint8_t) CommandRegisters::ALS_CONTR).get();
350 if (read_als_ctrl.gain != gain) {
351 ESP_LOGW(TAG, "Failed to set gain. We will try one more time.");
352 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
353 delay(2);
354 }
355}
356
360 meas.integration_time = time;
361 this->reg((uint8_t) CommandRegisters::MEAS_RATE) = meas.raw;
362 delay(2);
363
364 MeasurementRateRegister read_meas{0};
365 read_meas.raw = this->reg((uint8_t) CommandRegisters::MEAS_RATE).get();
366 if (read_meas.integration_time != time) {
367 ESP_LOGW(TAG, "Failed to set integration time. We will try one more time.");
368 this->reg((uint8_t) CommandRegisters::MEAS_RATE) = meas.raw;
369 delay(2);
370 }
371}
372
374 AlsPsStatusRegister als_status{0};
375
376 als_status.raw = this->reg((uint8_t) CommandRegisters::ALS_PS_STATUS).get();
377 if (!als_status.als_new_data)
379
380 if (als_status.data_invalid) {
381 ESP_LOGW(TAG, "Data available but not valid");
383 }
384 ESP_LOGV(TAG, "Data ready, reported gain is %.0f", get_gain_coeff(als_status.gain));
385 if (data.gain != als_status.gain) {
386 ESP_LOGW(TAG, "Actual gain differs from requested (%.0f)", get_gain_coeff(data.gain));
388 }
390}
391
393 data.ch1 = 0;
394 data.ch0 = 0;
395 uint8_t ch1_0 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH1_0).get();
396 uint8_t ch1_1 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH1_1).get();
397 uint8_t ch0_0 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH0_0).get();
398 uint8_t ch0_1 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH0_1).get();
399 data.ch1 = encode_uint16(ch1_1, ch1_0);
400 data.ch0 = encode_uint16(ch0_1, ch0_0);
401
402 ESP_LOGV(TAG, "Got sensor data: CH1 = %d, CH0 = %d", data.ch1, data.ch0);
403}
404
406 if (!this->automatic_mode_enabled_)
407 return false;
408
409 if (data.number_of_adjustments > 15) {
410 // sometimes sensors fail to change sensitivity. this prevents us from infinite loop
411 ESP_LOGW(TAG, "Too many sensitivity adjustments done. Apparently, sensor reconfiguration fails. Stopping.");
412 return false;
413 }
414 data.number_of_adjustments++;
415
416 // Recommended thresholds as per datasheet
417 static const uint16_t LOW_INTENSITY_THRESHOLD = 1000;
418 static const uint16_t HIGH_INTENSITY_THRESHOLD = 30000;
419 static const AlsGain GAINS[GAINS_COUNT] = {GAIN_1, GAIN_2, GAIN_4, GAIN_8, GAIN_48, GAIN_96};
420 static const IntegrationTime INT_TIMES[TIMES_COUNT] = {
423
424 if (data.ch0 <= LOW_INTENSITY_THRESHOLD) {
425 AlsGain next_gain = get_next(GAINS, data.gain);
426 if (next_gain != data.gain) {
427 data.gain = next_gain;
428 ESP_LOGV(TAG, "Low illuminance. Increasing gain.");
429 return true;
430 }
431 IntegrationTime next_time = get_next(INT_TIMES, data.integration_time);
432 if (next_time != data.integration_time) {
433 data.integration_time = next_time;
434 ESP_LOGV(TAG, "Low illuminance. Increasing integration time.");
435 return true;
436 }
437 } else if (data.ch0 >= HIGH_INTENSITY_THRESHOLD) {
438 AlsGain prev_gain = get_prev(GAINS, data.gain);
439 if (prev_gain != data.gain) {
440 data.gain = prev_gain;
441 ESP_LOGV(TAG, "High illuminance. Decreasing gain.");
442 return true;
443 }
444 IntegrationTime prev_time = get_prev(INT_TIMES, data.integration_time);
445 if (prev_time != data.integration_time) {
446 data.integration_time = prev_time;
447 ESP_LOGV(TAG, "High illuminance. Decreasing integration time.");
448 return true;
449 }
450 } else {
451 ESP_LOGD(TAG, "Illuminance is sufficient.");
452 return false;
453 }
454 ESP_LOGD(TAG, "Can't adjust sensitivity anymore.");
455 return false;
456}
457
459 if ((data.ch0 == 0xFFFF) || (data.ch1 == 0xFFFF)) {
460 ESP_LOGW(TAG, "Sensors got saturated");
461 data.lux = 0.0f;
462 return;
463 }
464
465 if ((data.ch0 == 0x0000) && (data.ch1 == 0x0000)) {
466 ESP_LOGW(TAG, "Sensors blacked out");
467 data.lux = 0.0f;
468 return;
469 }
470
471 float ch0 = data.ch0;
472 float ch1 = data.ch1;
473 float ratio = ch1 / (ch0 + ch1);
474 float als_gain = get_gain_coeff(data.gain);
475 float als_time = ((float) get_itime_ms(data.integration_time)) / 100.0f;
476 float inv_pfactor = this->glass_attenuation_factor_;
477 float lux = 0.0f;
478
479 if (ratio < 0.45f) {
480 lux = (1.7743f * ch0 + 1.1059f * ch1);
481 } else if (ratio < 0.64f && ratio >= 0.45f) {
482 lux = (4.2785f * ch0 - 1.9548f * ch1);
483 } else if (ratio < 0.85f && ratio >= 0.64f) {
484 lux = (0.5926f * ch0 + 0.1185f * ch1);
485 } else {
486 ESP_LOGW(TAG, "Impossible ch1/(ch0 + ch1) ratio");
487 lux = 0.0f;
488 }
489 lux = inv_pfactor * lux / als_gain / als_time;
490 data.lux = lux;
491
492 ESP_LOGV(TAG, "Lux calculation: ratio %.3f, gain %.0fx, int time %.1f, inv_pfactor %.3f, lux %.3f", ratio, als_gain,
493 als_time, inv_pfactor, lux);
494}
495
497 if (this->proximity_counts_sensor_ != nullptr) {
499 }
500 if (this->ambient_light_sensor_ != nullptr) {
502 }
503 if (this->infrared_counts_sensor_ != nullptr) {
505 }
506 if (this->full_spectrum_counts_sensor_ != nullptr) {
508 }
509}
510
512 if (this->actual_gain_sensor_ != nullptr) {
513 this->actual_gain_sensor_->publish_state(get_gain_coeff(data.gain));
514 }
515 if (this->actual_integration_time_sensor_ != nullptr) {
516 this->actual_integration_time_sensor_->publish_state(get_itime_ms(data.integration_time));
517 }
518}
519} // namespace esphome::ltr_als_ps
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:296
ErrorCode write(const uint8_t *data, size_t len) const
writes an array of bytes to a device using an I2CBus
Definition i2c.h:195
I2CRegister reg(uint8_t a_register)
calls the I2CRegister constructor
Definition i2c.h:164
uint8_t get() const
returns the register value
Definition i2c.cpp:126
void publish_data_part_2_(AlsReadings &data)
void configure_integration_time_(IntegrationTime time)
sensor::Sensor * full_spectrum_counts_sensor_
Definition ltr_als_ps.h:148
LtrDataAvail is_als_data_ready_(AlsReadings &data)
CallbackManager< void()> on_ps_low_trigger_callback_
Definition ltr_als_ps.h:162
void read_sensor_data_(AlsReadings &data)
CallbackManager< void()> on_ps_high_trigger_callback_
Definition ltr_als_ps.h:161
void publish_data_part_1_(AlsReadings &data)
bool are_adjustments_required_(AlsReadings &data)
struct esphome::ltr_als_ps::LTRAlsPsComponent::AlsReadings als_readings_
sensor::Sensor * actual_integration_time_sensor_
Definition ltr_als_ps.h:151
void apply_lux_calculation_(AlsReadings &data)
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
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 T(&array)[size], const T val)
T get_next(const T(&array)[size], const T val)
ESPHOME_LOG_TAG(TAG, "ltr_als_ps")
uint16_t size
Definition helpers.cpp:34
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:998
void HOT delay(uint32_t ms)
Definition hal.cpp:85
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
static void uint32_t
Gain ALS_GAIN
Definition veml7700.h:9