Skip to content

Latest commit

 

History

History
144 lines (108 loc) · 4.26 KB

README.md

File metadata and controls

144 lines (108 loc) · 4.26 KB

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 ff0000returns (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