ESPHome random color at boot (Athom Light RGBWW)

Hi, new here,

I have been struggling with what I was expecting to be an easy task.

I got an RGBWW led bulb that I would like to just pick a random color every time it is turned on. It needs to be a standalone solution meaning it has to work without wifi or anything outside.

I have tested lots of stuff from around this forum but without “true” success.

So far the best I can achieve is this doing this :

globals:
  - id: random_red
    type: float
    restore_value: no
    initial_value: '0.0'  

  - id: random_green
    type: float
    restore_value: no
    initial_value: '0.0'

  - id: random_blue
    type: float
    restore_value: no
    initial_value: '0.0'


esphome:
  name: ${name}
  name_add_mac_suffix: false
  friendly_name: ${friendly_name}
  on_boot:
  - priority: -100
    then:
      - light.turn_off:
          id: rgbww_light
      - light.turn_on: 
          id: rgbww_light
          cold_white: 0%
          warm_white: 0%
          white: 0%
          color_brightness: 100%
          red:  !lambda |-
            id(random_red) = (rand() % (100 + 1) + 0)/100.0;
            return id(random_red);
          green:  !lambda |-
            id(random_green) = (rand() % (100 + 1) + 0)/100.0;
            return id(random_green);
          blue:  !lambda |-
            id(random_blue) = (rand() % (100 + 1) + 0)/100.0;
            return id(random_blue);

It almost works ! Light pick a color at boot. Sadly this will be the same color every time.

I tried to set the random seed with srand() function but could not get it to use the time of the esp…

Does any body has an idea ?

Another solution, would the random effect allow you to achieve the same result?

Never used it, but I’m wondering that if you don’t specify an update interval, if it just stays at the setting when the effect is turned on. If so, then it would simply be a matter of turning the light on to that effect at boot.

I gave it a try and could not get it to work properly…

Finally got it work, srand was indeed the missing piece
Using micros() function set a “random enough” seed to the random generator

Here is the code for anybody interested

esphome:
  name: ${name}
  name_add_mac_suffix: false
  friendly_name: ${friendly_name}
  on_boot:
  - priority: 600
    then:
      - light.turn_off:
          id: rgbww_light
      - light.turn_on: 
          id: rgbww_light
          cold_white: 0%
          warm_white: 0%
          white: 0%
          color_brightness: 100%
          red: !lambda |-
            srand(micros());
            return (rand() % (100 + 1) + 0)/100.0;
          green:  !lambda return (rand() % (100 + 1) + 0)/100.0;
          blue:  !lambda return (rand() % (100 + 1) + 0)/100.0;