ESPHome 2025.6.2
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 ESP_LOGCONFIG(TAG, "Running setup");
67 // As per datasheet we need to wait at least 100ms after power on to get ALS chip responsive
68 this->set_timeout(100, [this]() { this->state_ = State::DELAYED_SETUP; });
69}
70
72 auto get_device_type = [](LtrType typ) {
73 switch (typ) {
75 return "ALS only";
77 return "PS only";
79 return "ALS + PS";
80 default:
81 return "Unknown";
82 }
83 };
84
85 LOG_I2C_DEVICE(this);
86 ESP_LOGCONFIG(TAG, " Device type: %s", get_device_type(this->ltr_type_));
87 if (this->is_als_()) {
88 ESP_LOGCONFIG(TAG,
89 " Automatic mode: %s\n"
90 " Gain: %.0fx\n"
91 " Integration time: %d ms\n"
92 " Measurement repeat rate: %d ms\n"
93 " Glass attenuation factor: %f",
94 ONOFF(this->automatic_mode_enabled_), get_gain_coeff(this->gain_),
95 get_itime_ms(this->integration_time_), get_meas_time_ms(this->repeat_rate_),
97 LOG_SENSOR(" ", "ALS calculated lux", this->ambient_light_sensor_);
98 LOG_SENSOR(" ", "CH1 Infrared counts", this->infrared_counts_sensor_);
99 LOG_SENSOR(" ", "CH0 Visible+IR counts", this->full_spectrum_counts_sensor_);
100 LOG_SENSOR(" ", "Actual gain", this->actual_gain_sensor_);
101 }
102 if (this->is_ps_()) {
103 ESP_LOGCONFIG(TAG,
104 " Proximity gain: %.0fx\n"
105 " Proximity cooldown time: %d s\n"
106 " Proximity high threshold: %d\n"
107 " Proximity low threshold: %d",
108 get_ps_gain_coeff(this->ps_gain_), this->ps_cooldown_time_s_, this->ps_threshold_high_,
109 this->ps_threshold_low_);
110 LOG_SENSOR(" ", "Proximity counts", this->proximity_counts_sensor_);
111 }
112 LOG_UPDATE_INTERVAL(this);
113
114 if (this->is_failed()) {
115 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
116 }
117}
118
120 ESP_LOGV(TAG, "Updating");
121 if (this->is_ready() && this->state_ == State::IDLE) {
122 ESP_LOGV(TAG, "Initiating new data collection");
123
125
126 this->als_readings_.ch0 = 0;
127 this->als_readings_.ch1 = 0;
128 this->als_readings_.gain = this->gain_;
130 this->als_readings_.lux = 0;
132
133 } else {
134 ESP_LOGV(TAG, "Component not ready yet");
135 }
136}
137
140 static uint8_t tries{0};
141
142 switch (this->state_) {
144 err = this->write(nullptr, 0);
145 if (err != i2c::ERROR_OK) {
146 ESP_LOGV(TAG, "i2c connection failed");
147 this->mark_failed();
148 }
149 this->configure_reset_();
150 if (this->is_als_()) {
151 this->configure_als_();
153 }
154 if (this->is_ps_()) {
155 this->configure_ps_();
156 }
157
158 this->state_ = State::IDLE;
159 break;
160
161 case State::IDLE:
162 if (this->is_ps_()) {
164 }
165 break;
166
169 tries = 0;
170 ESP_LOGV(TAG, "Reading sensor data having gain = %.0fx, time = %d ms", get_gain_coeff(this->als_readings_.gain),
171 get_itime_ms(this->als_readings_.integration_time));
172 this->read_sensor_data_(this->als_readings_);
173 this->state_ = State::DATA_COLLECTED;
175 } else if (tries >= MAX_TRIES) {
176 ESP_LOGW(TAG, "Can't get data after several tries.");
177 tries = 0;
178 this->status_set_warning();
179 this->state_ = State::IDLE;
180 return;
181 } else {
182 tries++;
183 }
184 break;
185
188 // first measurement in auto mode (COLLECTING_DATA_AUTO state) require device reconfiguration
189 if (this->state_ == State::COLLECTING_DATA_AUTO || this->are_adjustments_required_(this->als_readings_)) {
190 this->state_ = State::ADJUSTMENT_IN_PROGRESS;
191 ESP_LOGD(TAG, "Reconfiguring sensitivity: gain = %.0fx, time = %d ms", get_gain_coeff(this->als_readings_.gain),
192 get_itime_ms(this->als_readings_.integration_time));
195 // if sensitivity adjustment needed - need to wait for first data samples after setting new parameters
196 this->set_timeout(2 * get_meas_time_ms(this->repeat_rate_),
197 [this]() { this->state_ = State::WAITING_FOR_DATA; });
198 } else {
199 this->state_ = State::READY_TO_PUBLISH;
200 }
201 break;
202
204 // nothing to be done, just waiting for the timeout
205 break;
206
209 this->state_ = State::KEEP_PUBLISHING;
210 break;
211
214 this->status_clear_warning();
215 this->state_ = State::IDLE;
216 break;
217
218 default:
219 break;
220 }
221}
222
224 static uint32_t last_high_trigger_time{0};
225 static uint32_t last_low_trigger_time{0};
226 uint16_t ps_data = this->read_ps_data_();
227 uint32_t now = millis();
228
229 if (ps_data != this->ps_readings_) {
230 this->ps_readings_ = ps_data;
231 // Higher values - object is closer to sensor
232 if (ps_data > this->ps_threshold_high_ && now - last_high_trigger_time >= this->ps_cooldown_time_s_ * 1000) {
233 last_high_trigger_time = now;
234 ESP_LOGV(TAG, "Proximity high threshold triggered. Value = %d, Trigger level = %d", ps_data,
235 this->ps_threshold_high_);
236 this->on_ps_high_trigger_callback_.call();
237 } else if (ps_data < this->ps_threshold_low_ && now - last_low_trigger_time >= this->ps_cooldown_time_s_ * 1000) {
238 last_low_trigger_time = now;
239 ESP_LOGV(TAG, "Proximity low threshold triggered. Value = %d, Trigger level = %d", ps_data,
240 this->ps_threshold_low_);
241 this->on_ps_low_trigger_callback_.call();
242 }
243 }
244}
245
247 uint8_t manuf_id = this->reg((uint8_t) CommandRegisters::MANUFAC_ID).get();
248 if (manuf_id != 0x05) { // 0x05 is Lite-On Semiconductor Corp. ID
249 ESP_LOGW(TAG, "Unknown manufacturer ID: 0x%02X", manuf_id);
250 this->mark_failed();
251 return false;
252 }
253
254 // Things getting not really funny here, we can't identify device type by part number ID
255 // ======================== ========= ===== =================
256 // Device Part ID Rev Capabilities
257 // ======================== ========= ===== =================
258 // Ltr-329/ltr-303 0x0a 0x00 Als 16b
259 // Ltr-553/ltr-556/ltr-556 0x09 0x02 Als 16b + Ps 11b diff nm sens
260 // Ltr-659 0x09 0x02 Ps 11b and ps gain
261 //
262 // There are other devices which might potentially work with default settings,
263 // but registers layout is different and we can't use them properly. For ex. ltr-558
264
265 PartIdRegister part_id{0};
266 part_id.raw = this->reg((uint8_t) CommandRegisters::PART_ID).get();
267 if (part_id.part_number_id != 0x0a && part_id.part_number_id != 0x09) {
268 ESP_LOGW(TAG, "Unknown part number ID: 0x%02X. It might not work properly.", part_id.part_number_id);
269 this->status_set_warning();
270 return true;
271 }
272 return true;
273}
274
276 ESP_LOGV(TAG, "Resetting");
277
278 AlsControlRegister als_ctrl{0};
279 als_ctrl.sw_reset = true;
280 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
281 delay(2);
282
283 uint8_t tries = MAX_TRIES;
284 do {
285 ESP_LOGV(TAG, "Waiting for chip to reset");
286 delay(2);
287 als_ctrl.raw = this->reg((uint8_t) CommandRegisters::ALS_CONTR).get();
288 } while (als_ctrl.sw_reset && tries--); // while sw reset bit is on - keep waiting
289
290 if (als_ctrl.sw_reset) {
291 ESP_LOGW(TAG, "Reset timed out");
292 }
293}
294
296 AlsControlRegister als_ctrl{0};
297
298 als_ctrl.sw_reset = false;
299 als_ctrl.active_mode = true;
300 als_ctrl.gain = this->gain_;
301
302 ESP_LOGV(TAG, "Setting active mode and gain reg 0x%02X", als_ctrl.raw);
303 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
304 delay(5);
305
306 uint8_t tries = MAX_TRIES;
307 do {
308 ESP_LOGV(TAG, "Waiting for device to become active");
309 delay(2);
310 als_ctrl.raw = this->reg((uint8_t) CommandRegisters::ALS_CONTR).get();
311 } while (!als_ctrl.active_mode && tries--); // while active mode is not set - keep waiting
312
313 if (!als_ctrl.active_mode) {
314 ESP_LOGW(TAG, "Failed to activate device");
315 }
316}
317
319 PsMeasurementRateRegister ps_meas{0};
321 this->reg((uint8_t) CommandRegisters::PS_MEAS_RATE) = ps_meas.raw;
322
323 PsControlRegister ps_ctrl{0};
324 ps_ctrl.ps_mode_active = true;
325 ps_ctrl.ps_mode_xxx = true;
326 this->reg((uint8_t) CommandRegisters::PS_CONTR) = ps_ctrl.raw;
327}
328
330 AlsPsStatusRegister als_status{0};
331 als_status.raw = this->reg((uint8_t) CommandRegisters::ALS_PS_STATUS).get();
332 if (!als_status.ps_new_data || als_status.data_invalid) {
333 return this->ps_readings_;
334 }
335
336 uint8_t ps_low = this->reg((uint8_t) CommandRegisters::PS_DATA_0).get();
337 PsData1Register ps_high;
338 ps_high.raw = this->reg((uint8_t) CommandRegisters::PS_DATA_1).get();
339
340 uint16_t val = encode_uint16(ps_high.ps_data_high, ps_low);
341 if (ps_high.ps_saturation_flag) {
342 return 0x7ff; // full 11 bit range
343 }
344 return val;
345}
346
348 AlsControlRegister als_ctrl{0};
349 als_ctrl.active_mode = true;
350 als_ctrl.gain = gain;
351 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
352 delay(2);
353
354 AlsControlRegister read_als_ctrl{0};
355 read_als_ctrl.raw = this->reg((uint8_t) CommandRegisters::ALS_CONTR).get();
356 if (read_als_ctrl.gain != gain) {
357 ESP_LOGW(TAG, "Failed to set gain. We will try one more time.");
358 this->reg((uint8_t) CommandRegisters::ALS_CONTR) = als_ctrl.raw;
359 delay(2);
360 }
361}
362
366 meas.integration_time = time;
367 this->reg((uint8_t) CommandRegisters::MEAS_RATE) = meas.raw;
368 delay(2);
369
370 MeasurementRateRegister read_meas{0};
371 read_meas.raw = this->reg((uint8_t) CommandRegisters::MEAS_RATE).get();
372 if (read_meas.integration_time != time) {
373 ESP_LOGW(TAG, "Failed to set integration time. We will try one more time.");
374 this->reg((uint8_t) CommandRegisters::MEAS_RATE) = meas.raw;
375 delay(2);
376 }
377}
378
380 AlsPsStatusRegister als_status{0};
381
382 als_status.raw = this->reg((uint8_t) CommandRegisters::ALS_PS_STATUS).get();
383 if (!als_status.als_new_data)
384 return DataAvail::NO_DATA;
385
386 if (als_status.data_invalid) {
387 ESP_LOGW(TAG, "Data available but not valid");
388 return DataAvail::BAD_DATA;
389 }
390 ESP_LOGV(TAG, "Data ready, reported gain is %.0f", get_gain_coeff(als_status.gain));
391 if (data.gain != als_status.gain) {
392 ESP_LOGW(TAG, "Actual gain differs from requested (%.0f)", get_gain_coeff(data.gain));
393 return DataAvail::BAD_DATA;
394 }
395 return DataAvail::DATA_OK;
396}
397
399 data.ch1 = 0;
400 data.ch0 = 0;
401 uint8_t ch1_0 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH1_0).get();
402 uint8_t ch1_1 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH1_1).get();
403 uint8_t ch0_0 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH0_0).get();
404 uint8_t ch0_1 = this->reg((uint8_t) CommandRegisters::ALS_DATA_CH0_1).get();
405 data.ch1 = encode_uint16(ch1_1, ch1_0);
406 data.ch0 = encode_uint16(ch0_1, ch0_0);
407
408 ESP_LOGV(TAG, "Got sensor data: CH1 = %d, CH0 = %d", data.ch1, data.ch0);
409}
410
412 if (!this->automatic_mode_enabled_)
413 return false;
414
415 if (data.number_of_adjustments > 15) {
416 // sometimes sensors fail to change sensitivity. this prevents us from infinite loop
417 ESP_LOGW(TAG, "Too many sensitivity adjustments done. Apparently, sensor reconfiguration fails. Stopping.");
418 return false;
419 }
421
422 // Recommended thresholds as per datasheet
423 static const uint16_t LOW_INTENSITY_THRESHOLD = 1000;
424 static const uint16_t HIGH_INTENSITY_THRESHOLD = 30000;
425 static const AlsGain GAINS[GAINS_COUNT] = {GAIN_1, GAIN_2, GAIN_4, GAIN_8, GAIN_48, GAIN_96};
426 static const IntegrationTime INT_TIMES[TIMES_COUNT] = {
429
430 if (data.ch0 <= LOW_INTENSITY_THRESHOLD) {
431 AlsGain next_gain = get_next(GAINS, data.gain);
432 if (next_gain != data.gain) {
433 data.gain = next_gain;
434 ESP_LOGV(TAG, "Low illuminance. Increasing gain.");
435 return true;
436 }
437 IntegrationTime next_time = get_next(INT_TIMES, data.integration_time);
438 if (next_time != data.integration_time) {
439 data.integration_time = next_time;
440 ESP_LOGV(TAG, "Low illuminance. Increasing integration time.");
441 return true;
442 }
443 } else if (data.ch0 >= HIGH_INTENSITY_THRESHOLD) {
444 AlsGain prev_gain = get_prev(GAINS, data.gain);
445 if (prev_gain != data.gain) {
446 data.gain = prev_gain;
447 ESP_LOGV(TAG, "High illuminance. Decreasing gain.");
448 return true;
449 }
450 IntegrationTime prev_time = get_prev(INT_TIMES, data.integration_time);
451 if (prev_time != data.integration_time) {
452 data.integration_time = prev_time;
453 ESP_LOGV(TAG, "High illuminance. Decreasing integration time.");
454 return true;
455 }
456 } else {
457 ESP_LOGD(TAG, "Illuminance is sufficient.");
458 return false;
459 }
460 ESP_LOGD(TAG, "Can't adjust sensitivity anymore.");
461 return false;
462}
463
465 if ((data.ch0 == 0xFFFF) || (data.ch1 == 0xFFFF)) {
466 ESP_LOGW(TAG, "Sensors got saturated");
467 data.lux = 0.0f;
468 return;
469 }
470
471 if ((data.ch0 == 0x0000) && (data.ch1 == 0x0000)) {
472 ESP_LOGW(TAG, "Sensors blacked out");
473 data.lux = 0.0f;
474 return;
475 }
476
477 float ch0 = data.ch0;
478 float ch1 = data.ch1;
479 float ratio = ch1 / (ch0 + ch1);
480 float als_gain = get_gain_coeff(data.gain);
481 float als_time = ((float) get_itime_ms(data.integration_time)) / 100.0f;
482 float inv_pfactor = this->glass_attenuation_factor_;
483 float lux = 0.0f;
484
485 if (ratio < 0.45) {
486 lux = (1.7743 * ch0 + 1.1059 * ch1);
487 } else if (ratio < 0.64 && ratio >= 0.45) {
488 lux = (4.2785 * ch0 - 1.9548 * ch1);
489 } else if (ratio < 0.85 && ratio >= 0.64) {
490 lux = (0.5926 * ch0 + 0.1185 * ch1);
491 } else {
492 ESP_LOGW(TAG, "Impossible ch1/(ch0 + ch1) ratio");
493 lux = 0.0f;
494 }
495 lux = inv_pfactor * lux / als_gain / als_time;
496 data.lux = lux;
497
498 ESP_LOGV(TAG, "Lux calculation: ratio %.3f, gain %.0fx, int time %.1f, inv_pfactor %.3f, lux %.3f", ratio, als_gain,
499 als_time, inv_pfactor, lux);
500}
501
503 if (this->proximity_counts_sensor_ != nullptr) {
505 }
506 if (this->ambient_light_sensor_ != nullptr) {
508 }
509 if (this->infrared_counts_sensor_ != nullptr) {
511 }
512 if (this->full_spectrum_counts_sensor_ != nullptr) {
514 }
515}
516
518 if (this->actual_gain_sensor_ != nullptr) {
519 this->actual_gain_sensor_->publish_state(get_gain_coeff(data.gain));
520 }
521 if (this->actual_integration_time_sensor_ != nullptr) {
523 }
524}
525} // namespace ltr_als_ps
526} // 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(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:139
CallbackManager< void()> on_ps_low_trigger_callback_
Definition ltr_als_ps.h:159
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:158
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:142
void apply_lux_calculation_(AlsReadings &data)
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:39
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:192
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