ESPHome 2025.9.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
7
8namespace esphome {
9namespace ltr_als_ps {
10
11static const char *const 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 = -1;
18 while (idx == -1 && i < size) {
19 if (array[i] == val) {
20 idx = i;
21 break;
22 }
23 i++;
24 }
25 if (idx == -1 || 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 = -1;
33 while (idx == -1 && i > 0) {
34 if (array[i] == val) {
35 idx = i;
36 break;
37 }
38 i--;
39 }
40 if (idx == -1 || 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 if (this->is_failed()) {
114 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
115 }
116}
117
119 ESP_LOGV(TAG, "Updating");
120 if (this->is_ready() && this->state_ == State::IDLE) {
121 ESP_LOGV(TAG, "Initiating new data collection");
122
124
125 this->als_readings_.ch0 = 0;
126 this->als_readings_.ch1 = 0;
127 this->als_readings_.gain = this->gain_;
129 this->als_readings_.lux = 0;
131
132 } else {
133 ESP_LOGV(TAG, "Component not ready yet");
134 }
135}
136
139 static uint8_t tries{0};
140
141 switch (this->state_) {
143 err = this->write(nullptr, 0);
144 if (err != i2c::ERROR_OK) {
145 ESP_LOGV(TAG, "i2c connection failed");
146 this->mark_failed();
147 }
148 this->configure_reset_();
149 if (this->is_als_()) {
150 this->configure_als_();
152 }
153 if (this->is_ps_()) {
154 this->configure_ps_();
155 }
156
157 this->state_ = State::IDLE;
158 break;
159
160 case State::IDLE:
161 if (this->is_ps_()) {
163 }
164 break;
165
168 tries = 0;
169 ESP_LOGV(TAG, "Reading sensor data having gain = %.0fx, time = %d ms", get_gain_coeff(this->als_readings_.gain),
170 get_itime_ms(this->als_readings_.integration_time));
171 this->read_sensor_data_(this->als_readings_);
172 this->state_ = State::DATA_COLLECTED;
174 } else if (tries >= MAX_TRIES) {
175 ESP_LOGW(TAG, "Can't get data after several tries.");
176 tries = 0;
177 this->status_set_warning();
178 this->state_ = State::IDLE;
179 return;
180 } else {
181 tries++;
182 }
183 break;
184
187 // first measurement in auto mode (COLLECTING_DATA_AUTO state) require device reconfiguration
188 if (this->state_ == State::COLLECTING_DATA_AUTO || this->are_adjustments_required_(this->als_readings_)) {
189 this->state_ = State::ADJUSTMENT_IN_PROGRESS;
190 ESP_LOGD(TAG, "Reconfiguring sensitivity: gain = %.0fx, time = %d ms", get_gain_coeff(this->als_readings_.gain),
191 get_itime_ms(this->als_readings_.integration_time));
194 // if sensitivity adjustment needed - need to wait for first data samples after setting new parameters
195 this->set_timeout(2 * get_meas_time_ms(this->repeat_rate_),
196 [this]() { this->state_ = State::WAITING_FOR_DATA; });
197 } else {
198 this->state_ = State::READY_TO_PUBLISH;
199 }
200 break;
201
203 // nothing to be done, just waiting for the timeout
204 break;
205
208 this->state_ = State::KEEP_PUBLISHING;
209 break;
210
213 this->status_clear_warning();
214 this->state_ = State::IDLE;
215 break;
216
217 default:
218 break;
219 }
220}
221
223 static uint32_t last_high_trigger_time{0};
224 static uint32_t last_low_trigger_time{0};
225 uint16_t ps_data = this->read_ps_data_();
226 uint32_t now = millis();
227
228 if (ps_data != this->ps_readings_) {
229 this->ps_readings_ = ps_data;
230 // Higher values - object is closer to sensor
231 if (ps_data > this->ps_threshold_high_ && now - last_high_trigger_time >= this->ps_cooldown_time_s_ * 1000) {
232 last_high_trigger_time = now;
233 ESP_LOGV(TAG, "Proximity high threshold triggered. Value = %d, Trigger level = %d", ps_data,
234 this->ps_threshold_high_);
235 this->on_ps_high_trigger_callback_.call();
236 } else if (ps_data < this->ps_threshold_low_ && now - last_low_trigger_time >= this->ps_cooldown_time_s_ * 1000) {
237 last_low_trigger_time = now;
238 ESP_LOGV(TAG, "Proximity low threshold triggered. Value = %d, Trigger level = %d", ps_data,
239 this->ps_threshold_low_);
240 this->on_ps_low_trigger_callback_.call();
241 }
242 }
243}
244
246 uint8_t manuf_id = this->reg((uint8_t) CommandRegisters::MANUFAC_ID).get();
247 if (manuf_id != 0x05) { // 0x05 is Lite-On Semiconductor Corp. ID
248 ESP_LOGW(TAG, "Unknown manufacturer ID: 0x%02X", manuf_id);
249 this->mark_failed();
250 return false;
251 }
252
253 // Things getting not really funny here, we can't identify device type by part number ID
254 // ======================== ========= ===== =================
255 // Device Part ID Rev Capabilities
256 // ======================== ========= ===== =================
257 // Ltr-329/ltr-303 0x0a 0x00 Als 16b
258 // Ltr-553/ltr-556/ltr-556 0x09 0x02 Als 16b + Ps 11b diff nm sens
259 // Ltr-659 0x09 0x02 Ps 11b and ps gain
260 //
261 // There are other devices which might potentially work with default settings,
262 // but registers layout is different and we can't use them properly. For ex. ltr-558
263
264 PartIdRegister part_id{0};
265 part_id.raw = this->reg((uint8_t) CommandRegisters::PART_ID).get();
266 if (part_id.part_number_id != 0x0a && part_id.part_number_id != 0x09) {
267 ESP_LOGW(TAG, "Unknown part number ID: 0x%02X. It might not work properly.", part_id.part_number_id);
268 this->status_set_warning();
269 return true;
270 }
271 return true;
272}
273
275 ESP_LOGV(TAG, "Resetting");
276
277 AlsControlRegister als_ctrl{0};
278 als_ctrl.sw_reset = true;
279 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
280 delay(2);
281
282 uint8_t tries = MAX_TRIES;
283 do {
284 ESP_LOGV(TAG, "Waiting for chip to reset");
285 delay(2);
286 als_ctrl.raw = this->reg((uint8_t) CommandRegisters::ALS_CONTR).get();
287 } while (als_ctrl.sw_reset && tries--); // while sw reset bit is on - keep waiting
288
289 if (als_ctrl.sw_reset) {
290 ESP_LOGW(TAG, "Reset timed out");
291 }
292}
293
295 AlsControlRegister als_ctrl{0};
296
297 als_ctrl.sw_reset = false;
298 als_ctrl.active_mode = true;
299 als_ctrl.gain = this->gain_;
300
301 ESP_LOGV(TAG, "Setting active mode and gain reg 0x%02X", als_ctrl.raw);
302 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
303 delay(5);
304
305 uint8_t tries = MAX_TRIES;
306 do {
307 ESP_LOGV(TAG, "Waiting for device to become active");
308 delay(2);
309 als_ctrl.raw = this->reg((uint8_t) CommandRegisters::ALS_CONTR).get();
310 } while (!als_ctrl.active_mode && tries--); // while active mode is not set - keep waiting
311
312 if (!als_ctrl.active_mode) {
313 ESP_LOGW(TAG, "Failed to activate device");
314 }
315}
316
318 PsMeasurementRateRegister ps_meas{0};
320 this->reg((uint8_t) CommandRegisters::PS_MEAS_RATE) = ps_meas.raw;
321
322 PsControlRegister ps_ctrl{0};
323 ps_ctrl.ps_mode_active = true;
324 ps_ctrl.ps_mode_xxx = true;
325 this->reg((uint8_t) CommandRegisters::PS_CONTR) = ps_ctrl.raw;
326}
327
329 AlsPsStatusRegister als_status{0};
330 als_status.raw = this->reg((uint8_t) CommandRegisters::ALS_PS_STATUS).get();
331 if (!als_status.ps_new_data || als_status.data_invalid) {
332 return this->ps_readings_;
333 }
334
335 uint8_t ps_low = this->reg((uint8_t) CommandRegisters::PS_DATA_0).get();
336 PsData1Register ps_high;
337 ps_high.raw = this->reg((uint8_t) CommandRegisters::PS_DATA_1).get();
338
339 uint16_t val = encode_uint16(ps_high.ps_data_high, ps_low);
340 if (ps_high.ps_saturation_flag) {
341 return 0x7ff; // full 11 bit range
342 }
343 return val;
344}
345
347 AlsControlRegister als_ctrl{0};
348 als_ctrl.active_mode = true;
349 als_ctrl.gain = gain;
350 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
351 delay(2);
352
353 AlsControlRegister read_als_ctrl{0};
354 read_als_ctrl.raw = this->reg((uint8_t) CommandRegisters::ALS_CONTR).get();
355 if (read_als_ctrl.gain != gain) {
356 ESP_LOGW(TAG, "Failed to set gain. We will try one more time.");
357 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
358 delay(2);
359 }
360}
361
365 meas.integration_time = time;
366 this->reg((uint8_t) CommandRegisters::MEAS_RATE) = meas.raw;
367 delay(2);
368
369 MeasurementRateRegister read_meas{0};
370 read_meas.raw = this->reg((uint8_t) CommandRegisters::MEAS_RATE).get();
371 if (read_meas.integration_time != time) {
372 ESP_LOGW(TAG, "Failed to set integration time. We will try one more time.");
373 this->reg((uint8_t) CommandRegisters::MEAS_RATE) = meas.raw;
374 delay(2);
375 }
376}
377
379 AlsPsStatusRegister als_status{0};
380
381 als_status.raw = this->reg((uint8_t) CommandRegisters::ALS_PS_STATUS).get();
382 if (!als_status.als_new_data)
383 return DataAvail::NO_DATA;
384
385 if (als_status.data_invalid) {
386 ESP_LOGW(TAG, "Data available but not valid");
387 return DataAvail::BAD_DATA;
388 }
389 ESP_LOGV(TAG, "Data ready, reported gain is %.0f", get_gain_coeff(als_status.gain));
390 if (data.gain != als_status.gain) {
391 ESP_LOGW(TAG, "Actual gain differs from requested (%.0f)", get_gain_coeff(data.gain));
392 return DataAvail::BAD_DATA;
393 }
394 return DataAvail::DATA_OK;
395}
396
398 data.ch1 = 0;
399 data.ch0 = 0;
400 uint8_t ch1_0 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH1_0).get();
401 uint8_t ch1_1 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH1_1).get();
402 uint8_t ch0_0 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH0_0).get();
403 uint8_t ch0_1 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH0_1).get();
404 data.ch1 = encode_uint16(ch1_1, ch1_0);
405 data.ch0 = encode_uint16(ch0_1, ch0_0);
406
407 ESP_LOGV(TAG, "Got sensor data: CH1 = %d, CH0 = %d", data.ch1, data.ch0);
408}
409
411 if (!this->automatic_mode_enabled_)
412 return false;
413
414 if (data.number_of_adjustments > 15) {
415 // sometimes sensors fail to change sensitivity. this prevents us from infinite loop
416 ESP_LOGW(TAG, "Too many sensitivity adjustments done. Apparently, sensor reconfiguration fails. Stopping.");
417 return false;
418 }
420
421 // Recommended thresholds as per datasheet
422 static const uint16_t LOW_INTENSITY_THRESHOLD = 1000;
423 static const uint16_t HIGH_INTENSITY_THRESHOLD = 30000;
424 static const AlsGain GAINS[GAINS_COUNT] = {GAIN_1, GAIN_2, GAIN_4, GAIN_8, GAIN_48, GAIN_96};
425 static const IntegrationTime INT_TIMES[TIMES_COUNT] = {
428
429 if (data.ch0 <= LOW_INTENSITY_THRESHOLD) {
430 AlsGain next_gain = get_next(GAINS, data.gain);
431 if (next_gain != data.gain) {
432 data.gain = next_gain;
433 ESP_LOGV(TAG, "Low illuminance. Increasing gain.");
434 return true;
435 }
436 IntegrationTime next_time = get_next(INT_TIMES, data.integration_time);
437 if (next_time != data.integration_time) {
438 data.integration_time = next_time;
439 ESP_LOGV(TAG, "Low illuminance. Increasing integration time.");
440 return true;
441 }
442 } else if (data.ch0 >= HIGH_INTENSITY_THRESHOLD) {
443 AlsGain prev_gain = get_prev(GAINS, data.gain);
444 if (prev_gain != data.gain) {
445 data.gain = prev_gain;
446 ESP_LOGV(TAG, "High illuminance. Decreasing gain.");
447 return true;
448 }
449 IntegrationTime prev_time = get_prev(INT_TIMES, data.integration_time);
450 if (prev_time != data.integration_time) {
451 data.integration_time = prev_time;
452 ESP_LOGV(TAG, "High illuminance. Decreasing integration time.");
453 return true;
454 }
455 } else {
456 ESP_LOGD(TAG, "Illuminance is sufficient.");
457 return false;
458 }
459 ESP_LOGD(TAG, "Can't adjust sensitivity anymore.");
460 return false;
461}
462
464 if ((data.ch0 == 0xFFFF) || (data.ch1 == 0xFFFF)) {
465 ESP_LOGW(TAG, "Sensors got saturated");
466 data.lux = 0.0f;
467 return;
468 }
469
470 if ((data.ch0 == 0x0000) && (data.ch1 == 0x0000)) {
471 ESP_LOGW(TAG, "Sensors blacked out");
472 data.lux = 0.0f;
473 return;
474 }
475
476 float ch0 = data.ch0;
477 float ch1 = data.ch1;
478 float ratio = ch1 / (ch0 + ch1);
479 float als_gain = get_gain_coeff(data.gain);
480 float als_time = ((float) get_itime_ms(data.integration_time)) / 100.0f;
481 float inv_pfactor = this->glass_attenuation_factor_;
482 float lux = 0.0f;
483
484 if (ratio < 0.45) {
485 lux = (1.7743 * ch0 + 1.1059 * ch1);
486 } else if (ratio < 0.64 && ratio >= 0.45) {
487 lux = (4.2785 * ch0 - 1.9548 * ch1);
488 } else if (ratio < 0.85 && ratio >= 0.64) {
489 lux = (0.5926 * ch0 + 0.1185 * ch1);
490 } else {
491 ESP_LOGW(TAG, "Impossible ch1/(ch0 + ch1) ratio");
492 lux = 0.0f;
493 }
494 lux = inv_pfactor * lux / als_gain / als_time;
495 data.lux = lux;
496
497 ESP_LOGV(TAG, "Lux calculation: ratio %.3f, gain %.0fx, int time %.1f, inv_pfactor %.3f, lux %.3f", ratio, als_gain,
498 als_time, inv_pfactor, lux);
499}
500
502 if (this->proximity_counts_sensor_ != nullptr) {
504 }
505 if (this->ambient_light_sensor_ != nullptr) {
507 }
508 if (this->infrared_counts_sensor_ != nullptr) {
510 }
511 if (this->full_spectrum_counts_sensor_ != nullptr) {
513 }
514}
515
517 if (this->actual_gain_sensor_ != nullptr) {
518 this->actual_gain_sensor_->publish_state(get_gain_coeff(data.gain));
519 }
520 if (this->actual_integration_time_sensor_ != nullptr) {
522 }
523}
524} // namespace ltr_als_ps
525} // namespace esphome
virtual void mark_failed()
Mark this component as failed.
bool is_failed() const
void status_set_warning(const char *message=nullptr)
bool is_ready() const
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.
ErrorCode write(const uint8_t *data, size_t len, bool stop=true)
writes an array of bytes to a device using an I2CBus
Definition i2c.h:190
I2CRegister reg(uint8_t a_register)
calls the I2CRegister constructor
Definition i2c.h:153
uint8_t get() const
returns the register value
Definition i2c.cpp:75
void publish_data_part_2_(AlsReadings &data)
void configure_integration_time_(IntegrationTime time)
sensor::Sensor * full_spectrum_counts_sensor_
Definition ltr_als_ps.h:138
CallbackManager< void()> on_ps_low_trigger_callback_
Definition ltr_als_ps.h:158
DataAvail is_als_data_ready_(AlsReadings &data)
void read_sensor_data_(AlsReadings &data)
CallbackManager< void()> on_ps_high_trigger_callback_
Definition ltr_als_ps.h:157
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:141
void apply_lux_calculation_(AlsReadings &data)
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:45
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)
T get_next(const T(&array)[size], const T val)
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
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:173
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:28
Gain ALS_GAIN
Definition veml7700.h:9