Skip to content

Common jinja template color helper functions for @home-assistant - RGB to HEX to HS

License

Notifications You must be signed in to change notification settings

velijv/home-assistant-color-helpers

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

17 Commits
Β 
Β 
Β 
Β 

Home Assistant Color Helpers

Common jinja template color helper functions for Home Assistant

  1. convert RGB to HEX
  2. convert HEX to RGB
  3. convert HS to RGB
  4. convert HS to HEX
  5. convert RGB to HS

Extract colors

πŸ–– Hue and Saturation (state_attr('light.x','hs_color')
{%- set h = (state_attr('light.desk','hs_color') | list )[0] -%}
  # hue : {{ h }}
{%- set s = (state_attr('light.desk','hs_color') | list )[1] -%}
  # saturation : {{ s }}
πŸ– Red, Green and Blue state_attr('light.x','rgb_color')
{%- set r = (state_attr('light.desk','rgb_color') | list )[0] -%}
  # red : {{ r }}
{%- set g = (state_attr('light.desk','rgb_color') | list )[1] -%}
  # green : {{ g }}
{%- set b = (state_attr('light.desk','rgb_color') | list )[2] -%}
  # blue : {{ b }}

Convert colors in Jinja template

RGB to HEX

πŸ‘ˆ example input (0,0,255) β€” returns 0000ff
{%- set r = 0 -%}
{%- set g = 0 -%}
{%- set b = 255 -%}
hex : {{ '%02x%02x%02x' | format(r, g, b) }} - or - {{'%02x'%r+'%02x'%g+'%02x'%b}} 

HEX to RGB

πŸ‘ˆ example input ff0000 β€” returns (255, 0, 0)
{%- set rr = 'ff' -%}
{%- set gg = '00' -%}
{%- set bb = '00' -%}
rgb : {{r | int(base=16), g | int(base=16), b | int(base=16)}}

HS to RGB

πŸ‘ˆ example input hsv(240,100,100) β€” returns (0, 0, 255)
{%- set h = (state_attr('light.desk','hs_color') | list )[0]  -%}
{%- set s = 100 -%}
{%- set v = (state_attr('light.desk','hs_color') | list )[1] -%} 

s stays at 100. Because you only get 2 values from light in HA. An πŸ•―οΈ emitting light does not have saturation, it has πŸ”† brightness.

πŸ‘‰ hs_color(h,s) -> rgb : {{ (r, g, b) | list }} πŸ‘ˆ

{%- set h = 360 -%}
{%- set s = 100 -%}
{%- set v = 100 -%}
{%- set i = (h * 6 ) | round(2,'floor') -%}
{%- 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 | int -%}
  {%- set g = t | int -%} 
  {%- set b = p | int -%}
{%- elif i % 6 == 1 -%}
  {%- set r = q | int -%}
  {%- set g = v | int -%}
  {%- set b = p | int -%}
{%- elif i % 6 == 2 -%}
  {%- set r = p | int -%}
  {%- set g = v | int -%}
  {%- set b = t | int -%}
{%- elif i % 6 == 3 -%}
  {%- set r = p | int -%}
  {%- set g = q | int -%}
  {%- set b = v | int -%}
{%- elif i % 6 == 4 -%}
  {%- set r = t | int -%}
  {%- set g = p | int -%}
  {%- set b = v | int -%}
{%- elif i % 6 == 5 -%}
  {%- set r = v | int -%}
  {%- set g = p | int -%}
  {%- set b = q | int -%}
{%- endif -%}

rgb : {{ (r, g, b) | list }}

Try them out in Open your Home Assistant instance and show your template developer tools. uwu