Dynamic badge label (text) colours

Hi all,

may I ask again since I am ending up in this topic for the same question.

how may I use the code from the top start to see “entities” coloring from let’s say 0-300. I would love to create a dashboard with my PV panels coloring with the amount off Watts produced.

Is this code strictly for the lovelace dashboard or can it be reused in the sensor: config also?

Adjust the colour stops in the map to cover a bigger range. The map is temperature and colour value pairs, but the temperature keys can really be anything. You can also have fewer or more stops. You’ll need to experiment to get it to your liking, but start by keeping the 4 colors and changing the “temperatures” for those colours (e.g. to 50, 125, 200 and 275).

I like your use case. I might just do the same when my PVs get installed soon.

You can certainly use it in a template sensor, because it’s just Jinja, but I’m not sure how you would use it, since the output is an RGB value. The original idea is to display it on a dashboard, yes.

Do you have an example of yaml?

Of what precisely? What you’re asking isn’t something I do for myself. Have you tried my advice and can you show what you’ve tried? Try to respond in more detail.

HI Pieter, what I am trying to accomplish is a dashboard with some “entities” that color depending on their value. In my case 0-300 (or 400 or whatever). As a start from there I hope I can build out further.

But I am having problems on how to get started. I think I have 2 options basically:

  1. via lovelace (I believe this is what the code above is about).
  2. via a template sensor.

I prefer to created template sensors (for now) as I can create more specific sensors that act consistently in my entire home assistant system and I can reuse in multiple dashboard.

So my detailed question for a start is:
Can you please help me with the correct syntax for a template sensor in YAML to color the icon where I can play with a value from 0-300/400.

I do not have any working example as I truly do not know on how to get started with this (hence my question for an example).

Thanks!

Ok cool, I hear you, so lets see what we can do…

I’m going to assume your PV sensor is called sensor.pv_power.

We’re going to create a template sensor which has the same value, but with an attribute for colour. The attribute will be a piece of text containing a CSS colour.

I’m going to use the new style template sensor format. I’m not testing any of this though, so keep that in mind.

Note that the macro in the template is like an (inline) function – mostly for readability. It’s the line before the endmacro directive that “returns” the value – e.g. rgb(255, 0, 0) which is red or #ff0000. I’m renaming the references from my original post from temp to value to make it more generic.

This line is where we reference the sensor value from your PVs:

          {%- set value = states('sensor.pv_power') | float(0) -%}

This is (one option for) a new map of colours:

          {%- set value_map = {
                                50: "3498db",
                                125: "70a03c",
                                200: "ff9800",
                                275: "e74c3c"
                              }  -%}

The keys are the watt values, so 50 will map to #3498db. Values below that will be the same colour, because this is the lowest value. Between 50 and 125, the colour will be a gradient between #3498db and #70a03c. When you hit the highest value (275) or higher (300), the colour will be #e74c3c.

Here is the full sensor definition:

- sensor:
    - name: PV With Color
      state: "{{ states('sensor.pv_power') }}"
      attributes:
        color: >-
          {%- macro interpolate(value, start, stop) -%}
            {%- set (start_value, start_color) = start -%}
            {%- set (stop_value, stop_color) = stop -%}
            {%- set (start_r, start_g, start_b) = (int(start_color[0:2], base=16), int(start_color[2:4], base=16), int(start_color[4:6], base=16)) -%}
            {%- set (stop_r, stop_g, stop_b) = (int(stop_color[0:2], base=16), int(stop_color[2:4], base=16), int(stop_color[4:6], base=16)) -%}
            {%- set s = ((value - start_value)/(stop_value - start_value)) -%}
            {# some channels might be negative; most browsers are probably tolerant, but in case not #}
            {%- set r = max(int(start_r + s*(stop_r - start_r)), 0) -%}
            {%- set g = max(int(start_g + s*(stop_g - start_g)), 0) -%}
            {%- set b = max(int(start_b + s*(stop_b - start_b)), 0) -%}
            rgb({{ r }}, {{ g }}, {{ b }});
          {%- endmacro -%}
          {%- set value = states('sensor.pv_power') | float(0) -%}
          {%- set value_map = {
                                50: "3498db",
                                125: "70a03c",
                                200: "ff9800",
                                275: "e74c3c"
                              }  -%}
          {%- set keys = value_map | sort -%}
          {%- set index = keys | select("lt", value) | list | length -%}
          {%- if index == 0 -%}
            #{{ value_map[keys | first] }}
          {%- elif index == keys | length -%}
            #{{ value_map[keys | last] }}
          {%- else -%}
            {%- set start = (keys[index - 1], value_map[keys[index - 1]]) -%}
            {%- set stop = (keys[index], value_map[keys[index]]) -%}
            {{ interpolate(value, start, stop) }}
          {%- endif -%}

Next, if you tell me which card you’re going to use to visualise this, we can look at how to apply that colour, but that might be a topic for a card-mod thread. Either way, you should see the new sensor with it’s attribute in your dev tools or by using a template such as {{ state_attr('sensor.pv_with_color', 'color') }}.

Ok, it was some hassle and it went late before last night. But I have some output…:

now next step is to get this on a dashboard… (the visualisation part). I envsion something like a picture elements card with my sattelit house view where I can add squares with the accompanied colors :slight_smile:

And also here no clue :slight_smile:

Something like this:

I’m glad there’s progress.

You might want to add a device class to that template sensor. I didn’t include that: device_class: power.

Can you show the attributes section too? The colours you see under history and the result of the template sensor’s code: It’s because HA doesn’t see it as numerical data.

As for the visualisation part, I’d be happy to help with something simple like colour an icon on an entity card. From there you should be able to find your way or start a new thread with that specific application to ask for help. Personally I just don’t have the time to design a full picture elements card and I find it just too fiddly and not scalable for mobile displays.

But, for testing, I’d say put a badge on a dashboard, then you can use the code from the first post, tweaked slightly:

badges:
  - entity: sensor.pv_with_color
    name: PV Power
    card_mod:
      style: |
        :host {
          --label-badge-text-color:
              {{ state_attr('sensor.pv_with_color', 'color') }}
        }

Looks good. Perhaps you can try my example in my previous post next.

Not so sure what you mean. But this is my try:

Or this:

Badges - Home Assistant (home-assistant.io)

You need to give more info, like what the status and attributes are for what you’re showing. Is the sensor’s value 18? What’s the colour value?

Example

Entity sensor.pv_with_color (<class ‘homeassistant.components.template.sensor.SensorTemplate’>) is using native unit of measurement ‘None’ which is not a valid unit for the device class (‘power’) it is using; expected one of [‘kW’, ‘W’]; Please update your configuration if your entity is manually configured, otherwise create a bug report at Issues · home-assistant/core · GitHub

Yeah, so add a unit_of_measurement. Do you make any attempt at searching for answers?

This doesn’t help. I can’t see the current state value (or the one at the time of the previous screen shots).

But again, I’ve given you something to test with the badge. Only you would know with the information you have whether the colour and state value is correct. I can’t tell with what I have.

Yes the colours are correct. But later on I can change that.

No. Not if I am “told” something.

T.b.o. I have no clue on how to achieve what I want… this every little tip I take and add it to the total at which I hope I can create it with.

For clarity: what I do bot know is how to create a coloir changing “thing” (entity?) and be able to use that in a picture elements card…

I did not realize I created an entity with unit W (or other). I was thinking the way I created a template entity that just “colours” along with a value.
As that is what I need…

I have serious problems understanding how to achieve that and what the options are in homeassistant.

Can you really not understand that’s what you have when you look at your screen shots? You have a template sensor, which as its main value has the original W value and an attribute for the matching colour. I’m honestly failing to understand at this point how that’s not clear.

I’ve given you a real example, which is the badge. Applying this in other visual ways is a topic for a card-mod thread as previously stated. The badge uses card-mod. You can apply card-mod customisations almost everywhere, but it can take a lot of effort to get right. It’s not reasonable to expect anybody here to build your whole dashboard for you.

The biggest favour you can do yourself at this point is to in detail work through everything I’ve given you and to fully understand it.

You need to work modular: you have a sensor with the right info now. Separately, build the layout of your dashboard or picture elements card without worrying about the dynamic colours: just get your layout right and use static, plain colours. After that, you can combine the pieces.

Pieter, I really appreciate you pointing me in the right direction. And I do understand what I have created, I just said i did not realize it.

It is hard for me to understand how to give “color” to an entity and specially how to display that.

Also I do no expect you to make me a dashboard, of course not! Only thing I hoped to get a real life example of an entity icon/“something” I could place on a picture entity card and so forth I can work thing out further. A badge is not something I can place easily. As you see above I have tried.

My issue is I do not fully understand the combination of a “color” entity combined with an element card (car-mod?).

If I would get it I would already have it running (and share it in this topic).

so I think you are a little too hard for me:

Again, really thanks for all you have pointed me so far, I will try to work from there but I need some more help probably.

Thanks!