ESPHome 2025.9.0-dev
Loading...
Searching...
No Matches
tsl2591.cpp
Go to the documentation of this file.
1#include "tsl2591.h"
2#include "esphome/core/log.h"
3#include "esphome/core/hal.h"
4
5namespace esphome {
6namespace tsl2591 {
7
8static const char *const TAG = "tsl2591.sensor";
9
10// Various constants used in TSL2591 register manipulation
11#define TSL2591_COMMAND_BIT (0xA0) // 1010 0000: bits 7 and 5 for 'command, normal'
12#define TSL2591_ENABLE_POWERON (0x01) // Flag for ENABLE register, to enable
13#define TSL2591_ENABLE_POWEROFF (0x00) // Flag for ENABLE register, to disable
14#define TSL2591_ENABLE_AEN (0x02) // Flag for ENABLE register, to turn on ADCs
15
16// TSL2591 registers from the datasheet. We only define what we use.
17#define TSL2591_REGISTER_ENABLE (0x00)
18#define TSL2591_REGISTER_CONTROL (0x01)
19#define TSL2591_REGISTER_DEVICE_ID (0x12)
20#define TSL2591_REGISTER_STATUS (0x13)
21#define TSL2591_REGISTER_CHAN0_LOW (0x14)
22#define TSL2591_REGISTER_CHAN0_HIGH (0x15)
23#define TSL2591_REGISTER_CHAN1_LOW (0x16)
24#define TSL2591_REGISTER_CHAN1_HIGH (0x17)
25
27 // Enable the device by setting the control bit to 0x01. Also turn on ADCs.
28 if (!this->write_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_ENABLE, TSL2591_ENABLE_POWERON | TSL2591_ENABLE_AEN)) {
29 ESP_LOGE(TAG, "I2C write failed");
30 }
31}
32
34 if (!this->write_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_ENABLE, TSL2591_ENABLE_POWEROFF)) {
35 ESP_LOGE(TAG, "I2C write failed");
36 }
37}
38
44
46 switch (this->component_gain_) {
48 this->gain_ = TSL2591_GAIN_LOW;
49 break;
51 this->gain_ = TSL2591_GAIN_MED;
52 break;
55 break;
57 this->gain_ = TSL2591_GAIN_MAX;
58 break;
60 this->gain_ = TSL2591_GAIN_MED;
61 break;
62 }
63
64 uint8_t id;
65 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_DEVICE_ID, &id)) {
66 ESP_LOGE(TAG, "I2C read failed");
67 this->mark_failed();
68 return;
69 }
70
71 if (id != 0x50) {
72 ESP_LOGE(TAG, "Unknown chip ID");
73 this->mark_failed();
74 return;
75 }
76
79}
80
82 ESP_LOGCONFIG(TAG, "TSL2591:");
83 LOG_I2C_DEVICE(this);
84
85 if (this->is_failed()) {
86 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
87 return;
88 }
89
90 ESP_LOGCONFIG(TAG, " Name: %s", this->name_);
92 int gain = 0;
93 std::string gain_word = "unknown";
94 switch (raw_gain) {
96 gain = 1;
97 gain_word = "low";
98 break;
100 gain = 25;
101 gain_word = "medium";
102 break;
104 gain = 400;
105 gain_word = "high";
106 break;
108 gain = 9500;
109 gain_word = "maximum";
110 break;
112 gain = -1;
113 gain_word = "auto";
114 break;
115 }
116 TSL2591IntegrationTime raw_timing = this->integration_time_;
117 int timing_ms = (1 + raw_timing) * 100;
118 ESP_LOGCONFIG(TAG,
119 " Gain: %dx (%s)"
120 " Integration Time: %d ms\n"
121 " Power save mode enabled: %s\n"
122 " Device factor: %f\n"
123 " Glass attenuation factor: %f",
124 gain, gain_word.c_str(), timing_ms, ONOFF(this->power_save_mode_enabled_), this->device_factor_,
126 LOG_SENSOR(" ", "Full spectrum:", this->full_spectrum_sensor_);
127 LOG_SENSOR(" ", "Infrared:", this->infrared_sensor_);
128 LOG_SENSOR(" ", "Visible:", this->visible_sensor_);
129 LOG_SENSOR(" ", "Calculated lux:", this->calculated_lux_sensor_);
130 LOG_SENSOR(" ", "Actual gain:", this->actual_gain_sensor_);
131
132 LOG_UPDATE_INTERVAL(this);
133}
134
136 uint32_t combined = this->get_combined_illuminance();
137 uint16_t visible = this->get_illuminance(TSL2591_SENSOR_CHANNEL_VISIBLE, combined);
138 uint16_t infrared = this->get_illuminance(TSL2591_SENSOR_CHANNEL_INFRARED, combined);
139 uint16_t full = this->get_illuminance(TSL2591_SENSOR_CHANNEL_FULL_SPECTRUM, combined);
140 float lux = this->get_calculated_lux(full, infrared);
141 uint16_t actual_gain = this->get_actual_gain();
142 ESP_LOGD(TAG, "Got illuminance: combined 0x%" PRIX32 ", full %d, IR %d, vis %d. Calc lux: %f. Actual gain: %d.",
143 combined, full, infrared, visible, lux, actual_gain);
144 if (this->full_spectrum_sensor_ != nullptr) {
146 }
147 if (this->infrared_sensor_ != nullptr) {
148 this->infrared_sensor_->publish_state(infrared);
149 }
150 if (this->visible_sensor_ != nullptr) {
151 this->visible_sensor_->publish_state(visible);
152 }
153 if (this->calculated_lux_sensor_ != nullptr) {
155 }
156
157 if (this->component_gain_ == TSL2591_CGAIN_AUTO) {
158 this->automatic_gain_update(full);
159 }
160
161 if (this->actual_gain_sensor_ != nullptr) {
162 this->actual_gain_sensor_->publish_state(actual_gain);
163 }
164 this->status_clear_warning();
165}
166
167#define interval_name "tsl2591_interval_for_update"
168
170 if (!this->is_adc_valid()) {
171 uint64_t now = millis();
172 ESP_LOGD(TAG, "Elapsed %3llu ms; still waiting for valid ADC", (now - this->interval_start_));
173 if (now > this->interval_timeout_) {
174 ESP_LOGW(TAG, "Interval timeout for '%s' expired before ADCs became valid", this->name_);
175 this->cancel_interval(interval_name);
176 }
177 return;
178 }
179 this->cancel_interval(interval_name);
180 this->process_update_();
181}
182
184 if (!is_failed()) {
185 if (this->power_save_mode_enabled_) {
186 // we enabled it here, else ADC will never become valid
187 // but actually doing the reads will disable device if needed
188 this->enable();
189 }
190 if (this->is_adc_valid()) {
191 this->process_update_();
192 } else {
193 this->interval_start_ = millis();
194 this->interval_timeout_ = this->interval_start_ + 620;
195 this->set_interval(interval_name, 100, [this] { this->interval_function_for_update_(); });
196 }
197 }
198}
199
201 this->infrared_sensor_ = infrared_sensor;
202}
203
204void TSL2591Component::set_visible_sensor(sensor::Sensor *visible_sensor) { this->visible_sensor_ = visible_sensor; }
205
207 this->full_spectrum_sensor_ = full_spectrum_sensor;
208}
209
211 this->calculated_lux_sensor_ = calculated_lux_sensor;
212}
213
215 this->actual_gain_sensor_ = actual_gain_sensor;
216}
217
221
223
224void TSL2591Component::set_device_and_glass_attenuation_factors(float device_factor, float glass_attenuation_factor) {
225 this->device_factor_ = device_factor;
226 this->glass_attenuation_factor_ = glass_attenuation_factor;
227}
228
230 this->enable();
232 this->gain_ = gain;
233 if (!this->write_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CONTROL,
234 static_cast<uint8_t>(this->integration_time_) | static_cast<uint8_t>(this->gain_))) {
235 ESP_LOGE(TAG, "I2C write failed");
236 }
237 // The ADC values can be confused if gain or integration time are changed in the middle of a cycle.
238 // So, we unconditionally disable the device to turn the ADCs off. When re-enabling, the ADCs
239 // will tell us when they are ready again. That avoids an initial bogus reading.
240 this->disable();
241 if (!this->power_save_mode_enabled_) {
242 this->enable();
243 }
244}
245
247
248void TSL2591Component::set_name(const char *name) { this->name_ = name; }
249
251
253 uint8_t status;
254 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_STATUS, &status)) {
255 ESP_LOGE(TAG, "I2C read failed");
256 return false;
257 }
258 return status & 0x01;
259}
260
262 this->enable();
263 // Wait x ms for ADC to complete and signal valid.
264 // The max integration time is 600ms, so that's our max delay.
265 // (But we use 620ms as a bit of slack.)
266 // We'll do mini-delays and break out as soon as the ADC is good.
267 bool avalid;
268 const uint8_t mini_delay = 100;
269 for (uint16_t d = 0; d < 620; d += mini_delay) {
270 avalid = this->is_adc_valid();
271 if (avalid) {
272 break;
273 }
274 // we only log this if we need any delay, since normally we don't
275 ESP_LOGD(TAG, " after %3d ms: ADC valid? %s", d, avalid ? "true" : "false");
276 delay(mini_delay);
277 }
278 if (!avalid) {
279 // still not valid after a sutiable delay
280 // we don't mark the device as failed since it might come around in the future (probably not :-()
281 ESP_LOGE(TAG, "Device '%s' returned invalid readings", this->name_);
283 return 0;
284 }
285
286 // CHAN0 must be read before CHAN1
287 // See: https://forums.adafruit.com/viewtopic.php?f=19&t=124176
288 // Also, low byte must be read before high byte..
289 // We read the registers in the order described in the datasheet.
290 uint32_t x32;
291 uint8_t ch0low, ch0high, ch1low, ch1high;
292 uint16_t ch0_16;
293 uint16_t ch1_16;
294 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CHAN0_LOW, &ch0low)) {
295 ESP_LOGE(TAG, "I2C read failed");
296 return 0;
297 }
298 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CHAN0_HIGH, &ch0high)) {
299 ESP_LOGE(TAG, "I2C read failed");
300 return 0;
301 }
302 ch0_16 = (ch0high << 8) | ch0low;
303 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CHAN1_LOW, &ch1low)) {
304 ESP_LOGE(TAG, "I2C read failed");
305 return 0;
306 }
307 if (!this->read_byte(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CHAN1_HIGH, &ch1high)) {
308 ESP_LOGE(TAG, "I2C read failed");
309 return 0;
310 }
311 ch1_16 = (ch1high << 8) | ch1low;
312 x32 = (ch1_16 << 16) | ch0_16;
313
315 return x32;
316}
317
319 uint32_t combined = this->get_combined_illuminance();
320 return this->get_illuminance(channel, combined);
321}
322// logic cloned from Adafruit TSL2591 library
323uint16_t TSL2591Component::get_illuminance(TSL2591SensorChannel channel, uint32_t combined_illuminance) {
325 // Reads two byte value from channel 0 (visible + infrared)
326 return (combined_illuminance & 0xFFFF);
327 } else if (channel == TSL2591_SENSOR_CHANNEL_INFRARED) {
328 // Reads two byte value from channel 1 (infrared)
329 return (combined_illuminance >> 16);
330 } else if (channel == TSL2591_SENSOR_CHANNEL_VISIBLE) {
331 // Reads all and subtracts out the infrared
332 return ((combined_illuminance & 0xFFFF) - (combined_illuminance >> 16));
333 }
334 // unknown channel!
335 ESP_LOGE(TAG, "get_illuminance() caller requested an unknown channel: %d", channel);
336 return 0;
337}
338
353float TSL2591Component::get_calculated_lux(uint16_t full_spectrum, uint16_t infrared) {
354 // Check for overflow conditions first
355 uint16_t max_count = (this->integration_time_ == TSL2591_INTEGRATION_TIME_100MS ? 36863 : 65535);
356 if ((full_spectrum == max_count) || (infrared == max_count)) {
357 // Signal an overflow
358 ESP_LOGW(TAG, "Apparent saturation on '%s'; try reducing the gain or integration time", this->name_);
359 return NAN;
360 }
361
362 if ((full_spectrum == 0) && (infrared == 0)) {
363 // trivial conversion; avoids divide by 0
364 ESP_LOGW(TAG, "Zero reading on both '%s' sensors", this->name_);
365 return 0.0F;
366 }
367
368 float atime = 100.F + (this->integration_time_ * 100);
369
370 float again;
371 switch (this->gain_) {
372 case TSL2591_GAIN_LOW:
373 again = 1.0F;
374 break;
375 case TSL2591_GAIN_MED:
376 again = 25.0F;
377 break;
379 again = 400.0F;
380 break;
381 case TSL2591_GAIN_MAX:
382 again = 9500.0F;
383 break;
384 default:
385 again = 1.0F;
386 break;
387 }
388 // This lux equation is copied from the Adafruit TSL2591 v1.4.0 and modified slightly.
389 // See: https://github.com/adafruit/Adafruit_TSL2591_Library/issues/14
390 // and that library code.
391 // They said:
392 // Note: This algorithm is based on preliminary coefficients
393 // provided by AMS and may need to be updated in the future
394 // However, we use gain multipliers that are more in line with the midpoints
395 // of ranges from the datasheet. We don't know why the other libraries
396 // used the values they did for HIGH and MAX.
397 // If cpl or full_spectrum are 0, this will return NaN due to divide by 0.
398 // For the curious "cpl" is counts per lux, a term used in AMS application notes.
399 float cpl = (atime * again) / (this->device_factor_ * this->glass_attenuation_factor_);
400 float lux = (((float) full_spectrum - (float) infrared)) * (1.0F - ((float) infrared / (float) full_spectrum)) / cpl;
401 return std::max(lux, 0.0F);
402}
403
417void TSL2591Component::automatic_gain_update(uint16_t full_spectrum) {
418 TSL2591Gain new_gain = this->gain_;
419 uint fs_divider = (this->integration_time_ == TSL2591_INTEGRATION_TIME_100MS) ? 2 : 1;
420
421 switch (this->gain_) {
422 case TSL2591_GAIN_LOW:
423 if (full_spectrum < 54) { // 1/3 FS / GAIN_HIGH
424 new_gain = TSL2591_GAIN_HIGH;
425 } else if (full_spectrum < 875) { // 1/3 FS / GAIN_MED
426 new_gain = TSL2591_GAIN_MED;
427 }
428 break;
429 case TSL2591_GAIN_MED:
430 if (full_spectrum < 57) { // 1/3 FS / (GAIN_MAX/GAIN_MED)
431 new_gain = TSL2591_GAIN_MAX;
432 } else if (full_spectrum < 1365) { // 1/3 FS / (GAIN_HIGH/GAIN_MED)
433 new_gain = TSL2591_GAIN_HIGH;
434 } else if (full_spectrum > 62000 / fs_divider) { // 2/3 FS / (GAIN_LOW/GAIN_MED) clipped to 95% FS
435 new_gain = TSL2591_GAIN_LOW;
436 }
437 break;
439 if (full_spectrum < 920) { // 1/3 FS / (GAIN_MAX/GAIN_HIGH)
440 new_gain = TSL2591_GAIN_MAX;
441 } else if (full_spectrum > 62000 / fs_divider) { // 2/3 FS / (GAIN_MED/GAIN_HIGH) clipped to 95% FS
442 new_gain = TSL2591_GAIN_LOW;
443 }
444 break;
445 case TSL2591_GAIN_MAX:
446 if (full_spectrum > 62000 / fs_divider) // 2/3 FS / (GAIN_MED/GAIN_HIGH) clipped to 95% FS
447 new_gain = TSL2591_GAIN_MED;
448 break;
449 }
450
451 if (this->gain_ != new_gain) {
452 this->gain_ = new_gain;
454 }
455 ESP_LOGD(TAG, "Gain setting: %d", this->gain_);
456}
457
463 switch (this->gain_) {
464 case TSL2591_GAIN_LOW:
465 return 1.0F;
466 case TSL2591_GAIN_MED:
467 return 25.0F;
469 return 400.0F;
470 case TSL2591_GAIN_MAX:
471 return 9500.0F;
472 default:
473 // Shouldn't get here, but just in case.
474 return NAN;
475 }
476}
477
478} // namespace tsl2591
479} // namespace esphome
uint8_t status
Definition bl0942.h:8
virtual void mark_failed()
Mark this component as failed.
bool is_failed() const
void set_interval(const std::string &name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a unique name.
Definition component.cpp:89
bool cancel_interval(const std::string &name)
Cancel an interval function.
Definition component.cpp:97
void status_clear_warning()
bool write_byte(uint8_t a_register, uint8_t data, bool stop=true)
Definition i2c.h:266
bool read_byte(uint8_t a_register, uint8_t *data, bool stop=true)
Definition i2c.h:239
Base-class for all sensors.
Definition sensor.h:59
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:45
TSL2591IntegrationTime integration_time_
Definition tsl2591.h:262
void dump_config() override
Used by ESPHome framework.
Definition tsl2591.cpp:81
float get_setup_priority() const override
Used by ESPHome framework.
Definition tsl2591.cpp:250
TSL2591ComponentGain component_gain_
Definition tsl2591.h:263
void automatic_gain_update(uint16_t full_spectrum)
Updates the gain setting based on the most recent full spectrum reading.
Definition tsl2591.cpp:417
bool is_adc_valid()
Are the device ADC values valid?
Definition tsl2591.cpp:252
sensor::Sensor * infrared_sensor_
Definition tsl2591.h:258
float get_calculated_lux(uint16_t full_spectrum, uint16_t infrared)
Calculates and returns a lux value based on the ADC readings.
Definition tsl2591.cpp:353
sensor::Sensor * calculated_lux_sensor_
Definition tsl2591.h:260
void set_visible_sensor(sensor::Sensor *visible_sensor)
Used by ESPHome framework.
Definition tsl2591.cpp:204
void set_device_and_glass_attenuation_factors(float device_factor, float glass_attenuation_factor)
Sets the device and glass attenuation factors.
Definition tsl2591.cpp:224
sensor::Sensor * full_spectrum_sensor_
Definition tsl2591.h:257
void set_integration_time(TSL2591IntegrationTime integration_time)
Used by ESPHome framework.
Definition tsl2591.cpp:218
void set_calculated_lux_sensor(sensor::Sensor *calculated_lux_sensor)
Used by ESPHome framework.
Definition tsl2591.cpp:210
uint32_t get_combined_illuminance()
Get the combined illuminance value.
Definition tsl2591.cpp:261
void set_name(const char *name)
Sets the name for this instance of the device.
Definition tsl2591.cpp:248
sensor::Sensor * visible_sensor_
Definition tsl2591.h:259
void set_infrared_sensor(sensor::Sensor *infrared_sensor)
Used by ESPHome framework.
Definition tsl2591.cpp:200
sensor::Sensor * actual_gain_sensor_
Definition tsl2591.h:261
void set_actual_gain_sensor(sensor::Sensor *actual_gain_sensor)
Used by ESPHome framework.
Definition tsl2591.cpp:214
void set_gain(TSL2591ComponentGain gain)
Used by ESPHome framework.
Definition tsl2591.cpp:222
void enable()
Powers on the TSL2591 device and enables its sensors.
Definition tsl2591.cpp:26
void update() override
Used by ESPHome framework.
Definition tsl2591.cpp:183
void set_integration_time_and_gain(TSL2591IntegrationTime integration_time, TSL2591Gain gain)
Set device integration time and gain.
Definition tsl2591.cpp:229
void set_full_spectrum_sensor(sensor::Sensor *full_spectrum_sensor)
Used by ESPHome framework.
Definition tsl2591.cpp:206
void disable()
Powers off the TSL2591 device.
Definition tsl2591.cpp:33
float get_actual_gain()
Reads the actual gain used.
Definition tsl2591.cpp:462
uint16_t get_illuminance(TSL2591SensorChannel channel)
Get an individual sensor channel reading.
Definition tsl2591.cpp:318
void setup() override
Used by ESPHome framework.
Definition tsl2591.cpp:45
void set_power_save_mode(bool enable)
Should the device be powered down between readings?
Definition tsl2591.cpp:246
AlsGain501 gain
IntegrationTime501 integration_time
const float DATA
For components that import data from directly connected sensors like DHT.
Definition component.cpp:50
TSL2591Gain
Enum listing all gain settings for the TSL2591.
Definition tsl2591.h:44
TSL2591ComponentGain
Enum listing all gain settings for the TSL2591 component.
Definition tsl2591.h:31
TSL2591IntegrationTime
Enum listing all conversion/integration time settings for the TSL2591.
Definition tsl2591.h:17
@ TSL2591_INTEGRATION_TIME_100MS
Definition tsl2591.h:18
TSL2591SensorChannel
Enum listing sensor channels.
Definition tsl2591.h:55
@ TSL2591_SENSOR_CHANNEL_INFRARED
Definition tsl2591.h:57
@ TSL2591_SENSOR_CHANNEL_VISIBLE
Definition tsl2591.h:56
@ TSL2591_SENSOR_CHANNEL_FULL_SPECTRUM
Definition tsl2591.h:58
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
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:28
T id(T value)
Helper function to make id(var) known from lambdas work in custom components.
Definition helpers.h:933