Skip to content

Instantly share code, notes, and snippets.

@dglaude
Last active January 6, 2024 14:14
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dglaude/619a9e415e1e34019a6b1f5f274e0d14 to your computer and use it in GitHub Desktop.
Save dglaude/619a9e415e1e34019a6b1f5f274e0d14 to your computer and use it in GitHub Desktop.
Home Assistant Rainbow Loop with Ikea Tradfri RGB light
Please find below the various piece of code that together control my RGB light to loop in Rainbow.
Every two seconds, it change from one colour to another based on the value of the second.
So it compute 30 differents RGB value in a "circle", all with the same Saturation and Brightness both forced to 1.0
The transition from one colour to another is done in one seconds.
The name of my Tradfri RGB light bulb is "light.couleur"
A link to my video on Twitter:
https://twitter.com/DavidGlaude/status/1059596285991366657
Source code for the Hue based RGB computation from last post of this:
https://community.home-assistant.io/t/hue-random-color-autiomation-help/52122/10
PS: I am totally not a Home Assistant expert, so there might be better way to implement this.
Fell free to comment or propose better way to control that.
Such as verifying if the light is on (as a condition) before changing the RGB colour.
Anything really, today I just want it to work, but I am ready to learn.
### ###
### LightsHue - Rotating Hue Every Two Seconds ###
### ###
- alias: LightsHue - Rotating Hue Every Two Seconds
initial_state: True
trigger:
- platform: time
seconds: '/2'
action:
- service: script.change_exterior
### Possibly unrelated and not required piece of code... ###
### This is checking every minute the availability of the light bulb. ###
### By setting the brightness to current brightness it force the gateway to report the unavailable status. ###
### This code was found here: https://github.com/home-assistant/home-assistant/issues/17675 ###
- alias: "unavailable_couleur"
initial_state: 'on'
trigger:
platform: time
minutes: '/1'
seconds: 10
condition:
condition: template
value_template: >
{{ states('light.couleur') != 'unavailable'}}
action:
service: light.turn_on
data_template:
entity_id: light.couleur
brightness: >
{{ state_attr('light.couleur','brightness') | int }}
# Your "configuration.yaml" need to countain a reference to your automations.yaml and your scripts.yaml.
# In my case, I don't use "automations.yaml" but my config is split in various files in "automation" folder.
# YMMV
[...]
automation: !include_dir_merge_list automation/
#automation: !include automations.yaml
script: !include scripts.yaml
change_exterior:
alias: Change Exterior Light
sequence:
- service: script.preprocess_color
data:
id: light.couleur
# this script choses a random color for the lights
preprocess_color:
sequence:
- service: script.set_color
data_template:
id: '{{ id }}'
colors: >-
{%- set h = (now().second|int)/60 %}
{%- set s = 1.0 %}
{%- set v = 1.0 %}
{%- set i = (h * 6)|int %}
{%- set f = h * 6 - i %}
{%- set p = v * (1 - s) %}
{%- set q = v * (1 - f * s) %}
{%- set t = v * (1 - (1 - f) * s) %}
{%- if i % 6 == 0 %}
{% set r = v %}
{% set g = t %}
{% set b = p %}
{%- elif i % 6 == 1 %}
{% set r = q %}
{% set g = v %}
{% set b = p %}
{%- elif i % 6 == 2 %}
{% set r = p %}
{% set g = v %}
{% set b = t %}
{%- elif i % 6 == 3 %}
{% set r = p %}
{% set g = q %}
{% set b = v %}
{%- elif i % 6 == 4 %}
{% set r = t %}
{% set g = p %}
{% set b = v %}
{%- elif i % 6 == 5 %}
{% set r = v %}
{% set g = p %}
{% set b = q %}
{%- endif %}
{{ (255*r)|round(0) }}, {{ (255*g)|round(0) }}, {{ (255*b)|round(0) }}, {{ (360*h)|int }}
transition: 1
set_color:
sequence:
- service: light.turn_on
data_template:
entity_id: '{{ id }}'
rgb_color: [ "{{ colors.split(',')[0]|int }}", "{{ colors.split(',')[1]|int }}", "{{ colors.split(',')[2]|int }}" ]
transition: "{{ transition }}"
@pieterbos
Copy link

pieterbos commented Dec 9, 2020

Thanks, this has been very helpful.
In recent homeassistant, this stopped working. To fix, you probably need to leave out the .split(',') part at the end of scripts.yaml since it now passes a TupleWrapper instead of a string.

I used to do this the relatively complicated way as this one, then changed it to just one script and one automation. Add a script per light, through the UI:

Call Service
light.turn_on
enter your entity id of your light in the field

hs_color:
  - '{{ [0, 23, 45, 77, 90, 103, 135, 225, 250, 270, 300,315] | random }}'
  - '{{ [75, 100] | random }}'
transition: 20
brightness: 180

Then just add an automation through the UI triggering this at a time pattern, mine at minute: /1. Done. It doesn't cycle as yours does, it randomly picks a hue and saturation from the two lists, with a long transition. It's easy to add more colours, or different levels of saturation in the two lists of numbers.

Or, if you prefer full YAML mode, the script:

alias: cycle light
sequence:
  - service: light.turn_on
    data:
      hs_color:
        - '{{ [0, 23, 45, 77, 90, 103, 135, 225, 250, 270, 300,315] | random }}'
        - '{{ [75, 100] | random }}'
      transition: 1
      brightness: 180
    entity_id: light.hoek_woonkamer
mode: single

@dglaude
Copy link
Author

dglaude commented Dec 10, 2020

Thank you very much to you @pieterbos and happy it could help.
I almost totally forgot about this experiment, and I have not played with Home Assistant since years!

But Xmas is here, so maybe I should make that light change color and re-install Home Assistant.

One thing that would be great it so connect a TradFri RGB light to CheerLights IoT API.
Not sure at all how to do that, but it would be great project.

@loic-moriame
Copy link

An other solution: create an array of 24 colors (x-y color format) and select the right element in this array regarding the seconds
Why 24 colors ?
It's the number of colors I've counted in the Home Assistant Lovelace interface :)
image

# script.rainbow_light
alias: rainbow light
mode: single

fields:
  entity:
    description: The entity that will be rainbowed
    example: light.bathroom

variables:
  colors: |-
    {{ [[0.217,0.077], [0.157,0.05], [0.136,0.04], [0.137,0.065],
        [0.141,0.137], [0.146,0.238], [0.151,0.343], [0.157,0.457],
        [0.164,0.591], [0.17,0.703], [0.172,0.747], [0.199,0.724],
        [0.269,0.665], [0.36,0.588], [0.444,0.517], [0.527,0.447],
        [0.612,0.374], [0.677,0.319], [0.701,0.299], [0.667,0.284],
        [0.581,0.245], [0.477,0.196], [0.385,0.155], [0.301,0.116], 
        [0.217,0.077]] }}

sequence:
  - service: light.turn_on
    data_template:
      xy_color: |
        {{  colors[(now().second/2.5)|round(0)] }}
      transition: 1
      entity_id: '{{ entity }}'

Yeah, I cheated for the array of colors, because I don't find how to use a condition in the template to by-pass the 24th element of the array (59/2.5 = 23.6 => 23.6|round(0) = 24)

Then I create an automation for each light I want to have this rainbow effect:

# automation.rainbow_strip_led
alias: Rainbow strip led
description: Rotating color every second
trigger:
  - hours: '*'
    minutes: '*'
    platform: time_pattern
    seconds: /1
condition: []
action:
  - service: script.rainbow_light
    data:
      entity: light.strip_led
mode: single

@bafplus
Copy link

bafplus commented Aug 8, 2021

@loic-moriame I think this is exactly what im looking for for my Tuya RGB bulbs! Im a newby with HA (as in 2 days ;-) ) and i was searching my ass off for this function to select the "relax" scene. Since i'm not very well informed about getting this to work, could you enlighten me with a bit of info on where to put what to make this work?

@loic-moriame
Copy link

@loic-moriame I think this is exactly what im looking for for my Tuya RGB bulbs! Im a newby with HA (as in 2 days ;-) ) and i was searching my ass off for this function to select the "relax" scene. Since i'm not very well informed about getting this to work, could you enlighten me with a bit of info on where to put what to make this work?

Back from holidays!
@bafplus: I will try to check my HA tonight to let you know how to manage this

@kylewilliams321
Copy link

I haven't got this to work as I stumbled upon this from another thread in Home Assistant forum. However, my question for this is I'm trying to set something up for 3 lights on my patio and would like to cycle through colors for certain holidays. For example, Halloween - Purple and Orange... Christmas - Red, Green ....... 4th of July - Red, White, Blue, etc. You get the gist.

A couple modifications: 1) I think I'd prefer RGB color coding & 2) Is it possible for this to run on an endless loop?

THANKS!

@loic-moriame
Copy link

@loic-moriame I think this is exactly what im looking for for my Tuya RGB bulbs! Im a newby with HA (as in 2 days ;-) ) and i was searching my ass off for this function to select the "relax" scene. Since i'm not very well informed about getting this to work, could you enlighten me with a bit of info on where to put what to make this work?

For the script:
image

For the automation:
image

And I have put a switch on/off on my lovelace interface:
image

@bafplus
Copy link

bafplus commented Nov 23, 2021

Thanks!

@loic-moriame
Copy link

I haven't got this to work as I stumbled upon this from another thread in Home Assistant forum. However, my question for this is I'm trying to set something up for 3 lights on my patio and would like to cycle through colors for certain holidays. For example, Halloween - Purple and Orange... Christmas - Red, Green ....... 4th of July - Red, White, Blue, etc. You get the gist.

A couple modifications: 1) I think I'd prefer RGB color coding & 2) Is it possible for this to run on an endless loop?

THANKS!

You can for sure create new scripts with retricted colors and change the frequency in your automation.
To switch between only limited values in the array, I suggest to used HACS custome_component hass-variables

You can find below the details for Christmas light (you can change the frequency in automation if you want)

Script:

alias: christmas light
sequence:
  - service: light.turn_on
    data:
      rgb_color: |
        {% if now().second % 2 == 0 %}
          [255, 0, 0]
        {% else %}
          [0, 255, 0]
        {% endif %}
      transition: 0
    target:
      entity_id: '{{ entity }}'
mode: single
fields:
  entity:
    description: The entity that will be rainbowed
    example: light.bathroom
icon: mdi:pine-tree

Automation:

alias: Christmas strip led
description: Rotating color every second
trigger:
  - hours: '*'
    minutes: '*'
    platform: time_pattern
    seconds: /5
condition: []
action:
  - service: script.1637666266806
    data:
      entity: light.strip_led
mode: single

Lovelace UI:

type: entities
title: bureau
show_header_toggle: false
entities:
  - type: custom:slider-entity-row
    entity: light.strip_led
    toggle: true
    min: 1
    max: 100
  - entity: automation.christmas_strip_led

@loic-moriame
Copy link

and the script for 4th of July (or 14th of July for french people 😉)

Script:

alias: 4th July light
sequence:
  - service: light.turn_on
    data:
      rgb_color: |
        {% if now().second % 3 == 0 %}
          [0, 0, 255]
        {% elif now().second % 3 == 1 %}
          [0, 0, 0]
        {% else %}
          [255, 0, 0]
        {% endif %}
      transition: 0
    target:
      entity_id: '{{ entity }}'
mode: single
fields:
  entity:
    description: The entity that will be rainbowed
    example: light.bathroom
icon: mdi:firework

@willyfog78
Copy link

and the script for 4th of July (or 14th of July for french people 😉)

Script:

alias: 4th July light
sequence:
  - service: light.turn_on
    data:
      rgb_color: |
        {% if now().second % 3 == 0 %}
          [0, 0, 255]
        {% elif now().second % 3 == 1 %}
          [0, 0, 0]
        {% else %}
          [255, 0, 0]
        {% endif %}
      transition: 0
    target:
      entity_id: '{{ entity }}'
mode: single
fields:
  entity:
    description: The entity that will be rainbowed
    example: light.bathroom
icon: mdi:firework

Hi all is working nice. Is there a way to use much more colours (like 6 of them) and make transitions smoother?

@loic-moriame
Copy link

loic-moriame commented Nov 25, 2021

Hi all is working nice. Is there a way to use much more colours (like 6 of them) and make transitions smoother?

Sure!
For transition, just change the value of transition parameter

If you want more colors, just change the modulo value (3 to 6 for example) and add more conditions
Let me know if you want some help

P.S: I try to use an array for RGB colors but without success, that why I switch to multiple conditions inside the script

@Gavergracht
Copy link

My son can come out of bed when the light is green. when the light is red or orange, it is to early to wake up. How do I make such an automation ? And is it possible to enter a "time" when it has to be green ?
so setting the time at 07.00 ( not hard coded) ; starting at 06:40 with red for 10 minutes, 06:50 orange for 10 minutes and than at 07:00 half an our or so green ?

@willyfog78
Copy link

willyfog78 commented Nov 26, 2021

Hi I'm trying to achieve change of colour every 5 minutes with smooth transition of colours.

I cannot figure out function if with modulo. I got this but it only works every 5 seconds set in automation. Any other automation timing results in skipping colours.

`alias: Christmas strip led
description: Rotating color every second
trigger:

  • hours: ''
    platform: time_pattern
    minutes: '
    '
    seconds: /5
    condition: []
    action:
  • service: script.1637668450615
    mode: single
    automation:alias: Christmas strip led
    description: Rotating color every second
    trigger:
  • hours: ''
    platform: time_pattern
    minutes: '
    '
    seconds: /5
    condition: []
    action:
  • service: script.1637668450615
    mode: single
    `

@loic-moriame
Copy link

@Gavergracht : your question is out of the scope of this gist. I suggest you to ask directly on the forum of home-assistant :)
@willyfog78 : you should change the timer to execute it every 5min and in the script, change the condition by something like now().minute % 5 == 1

@hugalafutro
Copy link

@loic-moriame I took your work and created a Home Assistant Blueprint from it (I credited you), I hope it's ok.
https://community.home-assistant.io/t/color-loop-effect-for-any-light-with-color-wheel-selector/389343

@loic-moriame
Copy link

@hugalafutro: this is definitely in the spirit of open source and knowledge sharing.
I more than agree with that 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment