ESPHome 2026.3.0-dev
Loading...
Searching...
No Matches
light_state.cpp
Go to the documentation of this file.
1#include "light_state.h"
5#include "esphome/core/log.h"
6#include "light_output.h"
7#include "transformers.h"
8
9namespace esphome::light {
10
11static const char *const TAG = "light";
12
13LightState::LightState(LightOutput *output) : output_(output) {}
14
20
22 this->output_->setup_state(this);
23 for (auto *effect : this->effects_) {
24 effect->init_internal(this);
25 }
26
27 // Start with loop disabled if idle - respects any effects/transitions set up during initialization
29
30 // When supported color temperature range is known, initialize color temperature setting within bounds.
31 auto traits = this->get_traits();
32 float min_mireds = traits.get_min_mireds();
33 if (min_mireds > 0) {
34 this->remote_values.set_color_temperature(min_mireds);
35 this->current_values.set_color_temperature(min_mireds);
36 }
37
38 auto call = this->make_call();
39 LightStateRTCState recovered{};
40 if (this->initial_state_.has_value()) {
41 recovered = *this->initial_state_;
42 }
43 switch (this->restore_mode_) {
49 // Attempt to load from preferences, else fall back to default values
50 if (!this->rtc_.load(&recovered)) {
51 recovered.state = (this->restore_mode_ == LIGHT_RESTORE_DEFAULT_ON ||
55 // Inverted restore state
56 recovered.state = !recovered.state;
57 }
58 break;
62 this->rtc_.load(&recovered);
63 recovered.state = (this->restore_mode_ == LIGHT_RESTORE_AND_ON);
64 break;
66 recovered.state = false;
67 break;
68 case LIGHT_ALWAYS_ON:
69 recovered.state = true;
70 break;
71 }
72
73 call.set_color_mode_if_supported(recovered.color_mode);
74 call.set_state(recovered.state);
75 call.set_brightness_if_supported(recovered.brightness);
76 call.set_color_brightness_if_supported(recovered.color_brightness);
77 call.set_red_if_supported(recovered.red);
78 call.set_green_if_supported(recovered.green);
79 call.set_blue_if_supported(recovered.blue);
80 call.set_white_if_supported(recovered.white);
81 call.set_color_temperature_if_supported(recovered.color_temp);
82 call.set_cold_white_if_supported(recovered.cold_white);
83 call.set_warm_white_if_supported(recovered.warm_white);
84 if (recovered.effect != 0) {
85 call.set_effect(recovered.effect);
86 } else {
87 call.set_transition_length_if_supported(0);
88 }
89 call.perform();
90}
92 ESP_LOGCONFIG(TAG, "Light '%s'", this->get_name().c_str());
93 auto traits = this->get_traits();
94 if (traits.supports_color_capability(ColorCapability::BRIGHTNESS)) {
95 ESP_LOGCONFIG(TAG,
96 " Default Transition Length: %.1fs\n"
97 " Gamma Correct: %.2f",
98 this->default_transition_length_ / 1e3f, this->gamma_correct_);
99 }
100 if (traits.supports_color_capability(ColorCapability::COLOR_TEMPERATURE)) {
101 ESP_LOGCONFIG(TAG,
102 " Min Mireds: %.1f\n"
103 " Max Mireds: %.1f",
104 traits.get_min_mireds(), traits.get_max_mireds());
105 }
106}
108 // Apply effect (if any)
109 auto *effect = this->get_active_effect_();
110 if (effect != nullptr) {
111 effect->apply();
112 }
113
114 // Apply transformer (if any)
115 if (this->transformer_ != nullptr) {
116 auto values = this->transformer_->apply();
117 this->is_transformer_active_ = true;
118 if (values.has_value()) {
119 this->current_values = *values;
120 this->output_->update_state(this);
121 this->next_write_ = true;
122 }
123
124 if (this->transformer_->is_finished()) {
125 // if the transition has written directly to the output, current_values is outdated, so update it
126 this->current_values = this->transformer_->get_target_values();
127
128 this->transformer_->stop();
129 this->is_transformer_active_ = false;
130 this->transformer_ = nullptr;
132 for (auto *listener : *this->target_state_reached_listeners_) {
133 listener->on_light_target_state_reached();
134 }
135 }
136
137 // Disable loop if idle (no transformer and no effect)
138 this->disable_loop_if_idle_();
139 }
140 }
141
142 // Write state to the light
143 if (this->next_write_) {
144 this->next_write_ = false;
145 this->output_->write_state(this);
146 // Disable loop if idle (no transformer and no effect)
147 this->disable_loop_if_idle_();
148 }
149}
150
152
154 if (this->remote_values_listeners_) {
155 for (auto *listener : *this->remote_values_listeners_) {
156 listener->on_light_remote_values_update();
157 }
158 }
159#if defined(USE_LIGHT) && defined(USE_CONTROLLER_REGISTRY)
161#endif
162}
163
165
166static constexpr auto EFFECT_NONE_REF = StringRef::from_lit("None");
167
169 if (this->active_effect_index_ > 0) {
170 return this->effects_[this->active_effect_index_ - 1]->get_name();
171 }
172 return EFFECT_NONE_REF;
173}
174
176 if (!this->remote_values_listeners_) {
177 this->remote_values_listeners_ = make_unique<std::vector<LightRemoteValuesListener *>>();
178 }
179 this->remote_values_listeners_->push_back(listener);
180}
183 this->target_state_reached_listeners_ = make_unique<std::vector<LightTargetStateReachedListener *>>();
184 }
185 this->target_state_reached_listeners_->push_back(listener);
186}
187
189 this->default_transition_length_ = default_transition_length;
190}
193 this->flash_transition_length_ = flash_transition_length;
194}
197void LightState::set_restore_mode(LightRestoreMode restore_mode) { this->restore_mode_ = restore_mode; }
198void LightState::set_initial_state(const LightStateRTCState &initial_state) { this->initial_state_ = initial_state; }
199bool LightState::supports_effects() { return !this->effects_.empty(); }
201void LightState::add_effects(const std::initializer_list<LightEffect *> &effects) {
202 // Called once from Python codegen during setup with all effects from YAML config
203 this->effects_ = effects;
204}
205
208 this->current_values.as_brightness(brightness);
209 *brightness = this->gamma_correct_lut(*brightness);
210}
211void LightState::current_values_as_rgb(float *red, float *green, float *blue) {
212 this->current_values.as_rgb(red, green, blue);
213 *red = this->gamma_correct_lut(*red);
214 *green = this->gamma_correct_lut(*green);
215 *blue = this->gamma_correct_lut(*blue);
216}
217void LightState::current_values_as_rgbw(float *red, float *green, float *blue, float *white) {
218 this->current_values.as_rgbw(red, green, blue, white);
219 *red = this->gamma_correct_lut(*red);
220 *green = this->gamma_correct_lut(*green);
221 *blue = this->gamma_correct_lut(*blue);
222 *white = this->gamma_correct_lut(*white);
223}
224void LightState::current_values_as_rgbww(float *red, float *green, float *blue, float *cold_white, float *warm_white,
225 bool constant_brightness) {
226 this->current_values.as_rgbww(red, green, blue, cold_white, warm_white, constant_brightness);
227 *red = this->gamma_correct_lut(*red);
228 *green = this->gamma_correct_lut(*green);
229 *blue = this->gamma_correct_lut(*blue);
230 *cold_white = this->gamma_correct_lut(*cold_white);
231 *warm_white = this->gamma_correct_lut(*warm_white);
232}
233void LightState::current_values_as_rgbct(float *red, float *green, float *blue, float *color_temperature,
234 float *white_brightness) {
235 auto traits = this->get_traits();
236 this->current_values.as_rgbct(traits.get_min_mireds(), traits.get_max_mireds(), red, green, blue, color_temperature,
237 white_brightness);
238 *red = this->gamma_correct_lut(*red);
239 *green = this->gamma_correct_lut(*green);
240 *blue = this->gamma_correct_lut(*blue);
241 *white_brightness = this->gamma_correct_lut(*white_brightness);
242}
243void LightState::current_values_as_cwww(float *cold_white, float *warm_white, bool constant_brightness) {
244 this->current_values.as_cwww(cold_white, warm_white, constant_brightness);
245 *cold_white = this->gamma_correct_lut(*cold_white);
246 *warm_white = this->gamma_correct_lut(*warm_white);
247}
248void LightState::current_values_as_ct(float *color_temperature, float *white_brightness) {
249 auto traits = this->get_traits();
250 this->current_values.as_ct(traits.get_min_mireds(), traits.get_max_mireds(), color_temperature, white_brightness);
251 *white_brightness = this->gamma_correct_lut(*white_brightness);
252}
253
254#ifdef USE_LIGHT_GAMMA_LUT
255float LightState::gamma_correct_lut(float value) const {
256 if (value <= 0.0f)
257 return 0.0f;
258 if (value >= 1.0f)
259 return 1.0f;
260 if (this->gamma_table_ == nullptr)
261 return value;
262 float scaled = value * 255.0f;
263 auto idx = static_cast<uint8_t>(scaled);
264 if (idx >= 255)
265 return progmem_read_uint16(&this->gamma_table_[255]) / 65535.0f;
266 float frac = scaled - idx;
267 float a = progmem_read_uint16(&this->gamma_table_[idx]);
268 float b = progmem_read_uint16(&this->gamma_table_[idx + 1]);
269 return (a + frac * (b - a)) / 65535.0f;
270}
271float LightState::gamma_uncorrect_lut(float value) const {
272 if (value <= 0.0f)
273 return 0.0f;
274 if (value >= 1.0f)
275 return 1.0f;
276 if (this->gamma_table_ == nullptr)
277 return value;
278 uint16_t target = static_cast<uint16_t>(value * 65535.0f);
279 uint8_t lo = gamma_table_reverse_search(this->gamma_table_, target);
280 if (lo >= 255)
281 return 1.0f;
282 // Interpolate between lo and lo+1
283 uint16_t a = progmem_read_uint16(&this->gamma_table_[lo]);
284 uint16_t b = progmem_read_uint16(&this->gamma_table_[lo + 1]);
285 if (b == a)
286 return lo / 255.0f;
287 float frac = static_cast<float>(target - a) / static_cast<float>(b - a);
288 return (lo + frac) / 255.0f;
289}
290#endif // USE_LIGHT_GAMMA_LUT
291
293
295 this->stop_effect_();
296 if (effect_index == 0)
297 return;
298
299 this->active_effect_index_ = effect_index;
300 auto *effect = this->get_active_effect_();
301 effect->start_internal();
302 // Enable loop while effect is active
303 this->enable_loop();
304}
306 if (this->active_effect_index_ == 0) {
307 return nullptr;
308 } else {
309 return this->effects_[this->active_effect_index_ - 1];
310 }
311}
313 auto *effect = this->get_active_effect_();
314 if (effect != nullptr) {
315 effect->stop();
316 }
317 this->active_effect_index_ = 0;
318 // Disable loop if idle (no effect and no transformer)
319 this->disable_loop_if_idle_();
320}
321
322void LightState::start_transition_(const LightColorValues &target, uint32_t length, bool set_remote_values) {
324 this->transformer_->setup(this->current_values, target, length);
325
326 if (set_remote_values) {
327 this->remote_values = target;
328 }
329 // Enable loop while transition is active
330 this->enable_loop();
331}
332
333void LightState::start_flash_(const LightColorValues &target, uint32_t length, bool set_remote_values) {
334 LightColorValues end_colors = this->remote_values;
335 // If starting a flash if one is already happening, set end values to end values of current flash
336 // Hacky but works
337 if (this->transformer_ != nullptr)
338 end_colors = this->transformer_->get_start_values();
339
340 this->transformer_ = make_unique<LightFlashTransformer>(*this);
341 this->transformer_->setup(end_colors, target, length);
342
343 if (set_remote_values) {
344 this->remote_values = target;
345 };
346 // Enable loop while flash is active
347 this->enable_loop();
348}
349
350void LightState::set_immediately_(const LightColorValues &target, bool set_remote_values) {
351 this->is_transformer_active_ = false;
352 this->transformer_ = nullptr;
353 this->current_values = target;
354 if (set_remote_values) {
355 this->remote_values = target;
356 }
357 this->output_->update_state(this);
358 this->schedule_write_();
359}
360
362 // Only disable loop if both transformer and effect are inactive, and no pending writes
363 if (this->transformer_ == nullptr && this->get_active_effect_() == nullptr && !this->next_write_) {
364 this->disable_loop();
365 }
366}
367
369 LightStateRTCState saved;
371 switch (this->restore_mode_) {
374 saved.state = (this->restore_mode_ == LIGHT_RESTORE_AND_ON);
375 break;
376 default:
377 saved.state = this->remote_values.is_on();
378 break;
379 }
382 saved.red = this->remote_values.get_red();
383 saved.green = this->remote_values.get_green();
384 saved.blue = this->remote_values.get_blue();
385 saved.white = this->remote_values.get_white();
389 saved.effect = this->active_effect_index_;
390 this->rtc_.save(&saved);
391}
392
393} // namespace esphome::light
void enable_loop()
Enable this component's loop.
void disable_loop()
Disable this component's loop.
static void notify_light_update(light::LightState *obj)
bool save(const T *src)
Definition preferences.h:21
const StringRef & get_name() const
ESPPreferenceObject make_entity_preference(uint32_t version=0)
Create a preference object for storing this entity's state/settings.
Fixed-capacity vector - allocates once at runtime, never reallocates This avoids std::vector template...
Definition helpers.h:299
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
static constexpr StringRef from_lit(const CharT(&s)[N])
Definition string_ref.h:50
This class represents a requested change in a light state.
Definition light_call.h:21
LightCall & set_state(optional< bool > state)
Set the binary ON/OFF state of the light.
This class represents the color state for a light object.
float get_brightness() const
Get the brightness property of these light color values. In range 0.0 to 1.0.
float get_blue() const
Get the blue property of these light color values. In range 0.0 to 1.0.
float get_white() const
Get the white property of these light color values. In range 0.0 to 1.0.
void as_rgbww(float *red, float *green, float *blue, float *cold_white, float *warm_white, bool constant_brightness=false) const
Convert these light color values to an RGBWW representation with the given parameters.
float get_color_temperature() const
Get the color temperature property of these light color values in mired.
void as_cwww(float *cold_white, float *warm_white, bool constant_brightness=false) const
Convert these light color values to an CWWW representation with the given parameters.
float get_cold_white() const
Get the cold white property of these light color values. In range 0.0 to 1.0.
void as_rgbw(float *red, float *green, float *blue, float *white) const
Convert these light color values to an RGBW representation and write them to red, green,...
void as_rgb(float *red, float *green, float *blue) const
Convert these light color values to an RGB representation and write them to red, green,...
bool is_on() const
Get the binary true/false state of these light color values.
float get_green() const
Get the green property of these light color values. In range 0.0 to 1.0.
void set_color_temperature(float color_temperature)
Set the color temperature property of these light color values in mired.
float get_warm_white() const
Get the warm white property of these light color values. In range 0.0 to 1.0.
void as_binary(bool *binary) const
Convert these light color values to a binary representation and write them to binary.
void as_ct(float color_temperature_cw, float color_temperature_ww, float *color_temperature, float *white_brightness) const
Convert these light color values to a CT+BR representation with the given parameters.
ColorMode get_color_mode() const
Get the color mode of these light color values.
void as_rgbct(float color_temperature_cw, float color_temperature_ww, float *red, float *green, float *blue, float *color_temperature, float *white_brightness) const
Convert these light color values to an RGB+CT+BR representation with the given parameters.
float get_red() const
Get the red property of these light color values. In range 0.0 to 1.0.
void as_brightness(float *brightness) const
Convert these light color values to a brightness-only representation and write them to brightness.
float get_color_brightness() const
Get the color brightness property of these light color values. In range 0.0 to 1.0.
Interface to write LightStates to hardware.
virtual void write_state(LightState *state)=0
Called from loop() every time the light state has changed, and should should write the new state to h...
virtual std::unique_ptr< LightTransformer > create_default_transition()
Return the default transformer used for transitions.
virtual LightTraits get_traits()=0
Return the LightTraits of this LightOutput.
virtual void update_state(LightState *state)
Called on every update of the current values of the associated LightState, can optionally be used to ...
virtual void setup_state(LightState *state)
Listener interface for light remote value changes.
Definition light_state.h:31
void add_remote_values_listener(LightRemoteValuesListener *listener)
Add a listener for remote values changes.
float gamma_correct_
Gamma correction factor for the light.
FixedVector< LightEffect * > effects_
List of effects for this light.
StringRef get_effect_name()
Return the name of the current effect, or if no effect is active "None".
void start_effect_(uint32_t effect_index)
Internal method to start an effect with the given index.
void current_values_as_rgb(float *red, float *green, float *blue)
float gamma_correct_lut(float value) const
Apply gamma correction using the pre-computed forward LUT.
void stop_effect_()
Internal method to stop the current effect (if one is active).
void current_values_as_rgbct(float *red, float *green, float *blue, float *color_temperature, float *white_brightness)
void disable_loop_if_idle_()
Disable loop if neither transformer nor effect is active.
std::unique_ptr< LightTransformer > transformer_
The currently active transformer for this light (transition/flash).
void dump_config() override
LightColorValues remote_values
The remote color values reported to the frontend.
LightOutput * get_output() const
Get the light output associated with this object.
void set_flash_transition_length(uint32_t flash_transition_length)
Set the flash transition length.
LightState(LightOutput *output)
void current_values_as_binary(bool *binary)
The result of all the current_values_as_* methods have gamma correction applied.
void save_remote_values_()
Internal method to save the current remote_values to the preferences.
void add_target_state_reached_listener(LightTargetStateReachedListener *listener)
Add a listener for target state reached.
LightCall turn_on()
Make a light state call.
uint32_t get_default_transition_length() const
void set_immediately_(const LightColorValues &target, bool set_remote_values)
Internal method to set the color values to target immediately (with no transition).
optional< LightStateRTCState > initial_state_
Initial state of the light.
uint32_t get_flash_transition_length() const
void current_values_as_ct(float *color_temperature, float *white_brightness)
float gamma_uncorrect_lut(float value) const
Reverse gamma correction by binary-searching the forward LUT.
void current_values_as_cwww(float *cold_white, float *warm_white, bool constant_brightness=false)
uint32_t flash_transition_length_
Transition length to use for flash transitions.
void publish_state()
Publish the currently active state to the frontend.
void current_values_as_rgbww(float *red, float *green, float *blue, float *cold_white, float *warm_white, bool constant_brightness=false)
void set_initial_state(const LightStateRTCState &initial_state)
Set the initial state of this light.
void current_values_as_brightness(float *brightness)
void setup() override
Load state from preferences.
uint32_t active_effect_index_
Value for storing the index of the currently active effect. 0 if no effect is active.
void start_flash_(const LightColorValues &target, uint32_t length, bool set_remote_values)
Internal method to start a flash for the specified amount of time.
LightRestoreMode restore_mode_
Restore mode of the light.
const FixedVector< LightEffect * > & get_effects() const
Get all effects for this light state.
void add_effects(const std::initializer_list< LightEffect * > &effects)
Add effects for this light state.
void schedule_write_()
Schedule a write to the light output and enable the loop to process it.
const uint16_t * gamma_table_
bool supports_effects()
Return whether the light has any effects that meet the trait requirements.
bool next_write_
Whether the light value should be written in the next cycle.
void start_transition_(const LightColorValues &target, uint32_t length, bool set_remote_values)
Internal method to start a transition to the target color with the given length.
float get_setup_priority() const override
Shortly after HARDWARE.
void set_restore_mode(LightRestoreMode restore_mode)
Set the restore mode of this light.
LightOutput * output_
Store the output to allow effects to have more access.
ESPPreferenceObject rtc_
Object used to store the persisted values of the light.
void current_values_as_rgbw(float *red, float *green, float *blue, float *white)
uint32_t default_transition_length_
Default transition length for all transitions in ms.
LightColorValues current_values
The current values of the light as outputted to the light.
LightEffect * get_active_effect_()
Internal method to get the currently active effect.
bool is_transformer_active()
Indicator if a transformer (e.g.
std::unique_ptr< std::vector< LightRemoteValuesListener * > > remote_values_listeners_
Listeners for remote values changes.
std::unique_ptr< std::vector< LightTargetStateReachedListener * > > target_state_reached_listeners_
Listeners for target state reached.
void set_gamma_correct(float gamma_correct)
Set the gamma correction factor.
void set_default_transition_length(uint32_t default_transition_length)
Set the default transition length, i.e. the transition length when no transition is provided.
Listener interface for light target state reached.
Definition light_state.h:42
This class is used to represent the capabilities of a light.
@ LIGHT_RESTORE_INVERTED_DEFAULT_ON
Definition light_state.h:53
@ LIGHT_RESTORE_DEFAULT_OFF
Definition light_state.h:48
@ LIGHT_RESTORE_INVERTED_DEFAULT_OFF
Definition light_state.h:52
uint8_t gamma_table_reverse_search(const uint16_t *table, uint16_t target)
Binary search a monotonically increasing uint16[256] PROGMEM table.
static float float b
@ BRIGHTNESS
Master brightness of the light can be controlled.
@ COLOR_TEMPERATURE
Color temperature can be controlled.
constexpr float HARDWARE
For components that deal with hardware and are very important like GPIO switch.
Definition component.h:29
float gamma_correct(float value, float gamma)
Definition helpers.cpp:703
uint16_t progmem_read_uint16(const uint16_t *addr)
Definition core.cpp:51
uint16_t length
Definition tt21100.cpp:0