Template to add values of all sensors with certain name ending

for reference here’s the complete setup including adapted state-card-value_only.html. Save this card in /config/custom_ui and call it in frontend.yaml:

extra_html_url:
  - /local/custom_ui/state-card-value_only.html

copy below code and save as state-card-value_only.html

<!--
https://github.com/home-assistant/home-assistant-polymer/blob/master/src/state-summary/state-card-display.html
https://github.com/home-assistant/home-assistant-polymer/blob/master/src/components/entity/state-badge.html
https://github.com/PolymerElements/paper-styles/blob/master/color.html

# (expanded from original with extra color codes and corrected cases bold/italic)
# paper-brown-500: #795548 and google-grey-500: #9e9e9e, blue, darkbrown, deepbrown, purple
# by @Mariusthvdb
-->

<dom-module id="state-card-value_only">
  <template>


    <style is="custom-style" include="iron-flex iron-flex-alignment"></style>
    <style>
      .bold {
        @apply(--paper-font-body1);
        color: var(--primary-text-color);
        font-weight: bold;
        margin-left: 8px;
        text-align: left;
        line-height: 20px;
      }
      .italic {
        @apply(--paper-font-body1);
        color: var(--primary-text-color);
        font-style: italic;
        margin-left: 8px;
        text-align: left;
        line-height: 20px;
      }
      .red {
        @apply(--paper-font-body1);
        color: var(--google-red-500);
        margin-left: 8px;
        text-align: left;
        line-height: 20px;
      }
      .green {
        @apply(--paper-font-body1);
        color: var(--google-green-500);
        margin-left: 8px;
        text-align: left;
        line-height: 20px;
      }
      .yellow {
        @apply(--paper-font-body1);
        color: var(--google-yellow-500);
        margin-left: 8px;
        text-align: left;
        line-height: 20px;
      }
      .grey {
        @apply(--paper-font-body1);
        color: #9e9e9e;
        margin-left: 8px;
        text-align: left;
        line-height: 20px;
      }
      .brown {
        @apply(--paper-font-body1);
        color: #795548;
        margin-left: 8px;
        text-align: left;
        line-height: 20px;
      }
      .blue {
        @apply(--paper-font-body1);
        color: var(--google-blue-500);
        margin-left: 8px;
        text-align: left;
        line-height: 20px;
      }
      .darkbrown {
        @apply(--paper-font-body1);
        color: #500000;
        margin-left: 8px;
        text-align: left;
        line-height: 20px;
      }
      .deepbrown {
        @apply(--paper-font-body1);
        color: #2d0000;
        margin-left: 8px;
        text-align: left;
        line-height: 20px;
      }
      .purple {
        @apply(--paper-font-body1);
        color: #2d214b;
        margin-left: 8px;
        text-align: left;
        line-height: 20px;
      }
      .normal {
        @apply(--paper-font-body1);
        color: #4b4b4b;
        margin-left: 8px;
        text-align: left;
        line-height: 20px;
      }
    </style>

    <template is="dom-repeat" items="[[computeStateDisplay(stateObj)]]">
      <div class$="[[computeClass(item)]]">[[computeItem(item)]]</div>
    </template>

  </template>
</dom-module>

<script>
Polymer({
  is: 'state-card-value_only',

  properties: {
    hass: {
      type: Object,
    },

    stateObj: {
      type: Object,
    },
  },

  computeStateDisplay: function (stateObj) {
    var text = stateObj.attributes.text;

    if (text == null) { text = stateObj.state };
    return text.split("\n");
  },

  computeItem: function (item) {
      var value = item.trim();

      switch(value.substring(0,1)) {
      case "*":
      case "/":
      case "!":
      case "+":
      case "=":
      case "%":
      case "$":
      case "#":
      case "@":
      case "^":
      case "&":
          return value.substring(1);
      default:
          return value;
      }
  },

  computeClass: function (item) {
      switch(item.trim().substring(0,1)) {
      case "*": return "bold";
      case "/": return "italic";
      case "!": return "red";
      case "+": return "green";
      case "=": return "yellow";
      case "%": return "grey";
      case "$": return "brown";
      case "#": return "blue";
      case "@": return "darkbrown";
      case "^": return "deepbrown";
      case "&": return "purple";
      default:  return "normal";
      }
  },

});
</script>

below automation to run the python_script:

automation:
  - alias: 'Activate Map sensors actueel'
    id: 'Activate Map sensors actueel'
   #hide_entity: True
    initial_state: 'off'
    trigger:
      platform: event
      event_type: state_changed
      event_data:
        domain: sensor
    condition:
      condition: template
        value_template: >
        {{ trigger.event.data.entity_id.endswith('actueel')}}
    action:
      service: python_script.map_sensors_actueel

the group to show it in the frontend

group:
  map_sensors_actueel:
    name: Map sensors actueel
    icon: mdi:power
    entities:
      - sensor.map_sensors_actueel
      - automation.activate_map_sensors_actueel

Ive set the automation initial_state: 'off' and placed the automation in the same group, so it doesnt start up by default (seems to take lots of processing effort for the Pi) and switching on/off is always quickly available.

updated and renamed python_script map_sensors_actueel:

##########################################################################################
# map_sensors_actueel.py
# reading all sensors.*_actueel using power (>0), listing and counting them,
# sorted alphabetically, and calculate summed power consumption
# colorcoded by power usage
# by @Mariusthvdb  and big hand Phil, @pnbruckner
# https://community.home-assistant.io/t/template-to-add-values-of-all-sensors-with-certain-name-ending/64488
# august 21 2018
##########################################################################################

sensor_list = []
total_power = 0
count = 0
for entity_id in hass.states.entity_ids('sensor'):
    if entity_id.endswith('_actueel') and not 'sensors' in entity_id:
        state = hass.states.get(entity_id)
        try:
            power = float(state.state)
        except:
            continue
        if power > 0:
            total_power = round(total_power + power,2)
            count = count + 1

            colorCode = '%' if power < 20 else \
                        '=' if power < 100 else \
                        '+' if power < 200 else \
                        '#' if power < 500 else \
                        '$' if power < 1000 else \
                        '@' if power < 1500 else \
                        '^' if power < 2000 else \
                        '!' if power < 2250 else \
                        '&' if power < 2500 else \
                        ''
            colorCodeTotal = '%' if total_power < 200 else \
                             '=' if total_power < 500 else \
                             '+' if total_power < 1000 else \
                             '#' if total_power < 1500 else \
                             '$' if total_power < 2000 else \
                             '@' if total_power < 3000 else \
                             '^' if total_power < 4000 else \
                             '!' if total_power < 5000 else \
                             '&' if total_power < 6000 else \
                             '*'

            sensor = colorCode +'{:22}:'.format(state.name[:-8]) + \
                                '{:>7}\n'.format(state.state)
            sensor_list.append(sensor)

summary = '\n'.join([
          '*=== Sensor ===== Power =======',
          *sorted(sensor_list,key=lambda x: x[1:]),
          '*========== Summary ==========',
          '/Total Sensors consuming power: {}',
          colorCodeTotal +'Total consumed Power: {}',
          '*' +'='*28
          ]).format(count,
                    total_power,
                    total_power)

hass.states.set('sensor.map_sensors_actueel', '', {
        'custom_ui_state_card': 'state-card-value_only',
        'text': summary
        })

hass.states.set('sensor.total_sensors',total_power, {
        'unit_of_measurement': 'Watt',
        'friendly_name': '{} sensors'.format(count),
        'count': count
        })

##########################################################################################
# map_sensors_actueel.py
##########################################################################################
##########################################################################################
# Codes for text_colors declared in 
# Custom card: /custom_ui/state-card-value_only.html (expanded from original with extra
#              color codes and corrected cases bold/italic)
##########################################################################################
#      case "*": return "bold";
#      case "/": return "italic";
#      case "!": return "red";
#      case "+": return "green";
#      case "=": return "yellow";
#      case "%": return "grey";
#      case "$": return "brown";
#      case "#": return "blue";
#      case "@": return "darkbrown";
#      case "^": return "deepbrown";
#      case "&": return "purple";

#      default:  return "normal";
##########################################################################################

##########################################################################################
# lessons learned:
##########################################################################################
#Try. The else doesn’t go with the if, it goes with the try. Notice that it is at the same
#indentation level as try and except. In a try statement, if an exception occurs
#the except clause is executed.
#But if no exception occurs, then the else clause is executed (if there is one.)
#So, in this case, if the conversion to int works, then the else clause it executed,
#which increments the count.

#*iterable means expand the iterable. So *['a','b','c'] is 'a', 'b', 'c'. Used here to 
#expand sensor_list into individual items that then become part of the bigger list.

#sorted. You can give the function sorted a key function that can change what it sorts. 
#So you could change *sorted(sensor_list) to *sorted(sensor_list, key=lambda x: x[1:]). 
#Instead of sorting by the whole strings, it will sort using the strings minus their 
#first characters.
##########################################################################################
# Older snippets
##########################################################################################
#        logger.info('entity_id = {}, state = {}'.format(entity_id, state.state))
#        sensor_id = '{}'.format(entity_id[7:-8].replace('_',' ').title())
#        sensor_power = '\t{}'.format(state.state)
#        sensor = '#{} :'.format(sensor_id) + ' {}\n'.format(sensor_power)


#            sensor_list.append(sensor)
##            sensor_list.append('%{:21}:{:>7.2f}'.format(
#                state.name.replace('actueel','').replace('_',' '),
#                power))

#            sensor_list.append(colorCode +'{:21}: {:>7.2f}'.format(
#               state.name.replace('actueel','').replace('_',' '),
#                power))

#sensor_map = '\n'.join(sensor_list)

#summary = '*{:=^30}\n' \
#          '$----------  Sensor : Power  ----------\n' \
#          '{}\n' \
#          '*=============== Sumary ==============\n' \
#          ' Sensors consuming power: {}\n' \
#          ' Total consumed Power :  {}\n' \
#          '*====================================\n' \
#          .format(' Sensors ',
#                  sensor_map,
#                  count,
#                  total_power)

# complete version @pnbruckner
#sensor_list = []
#total_power = 0
#count = 0
#for entity_id in hass.states.entity_ids('sensor'):
#    if entity_id.endswith('_actueel') and 'sensors' not in entity_id:
#        state = hass.states.get(entity_id)
#        try:
#            power = round(float(state.state), 2)
#        except:
#            continue
#        if power > 0:
#            total_power = total_power + power
#            count = count + 1
#            sensor_list.append('#{:21}: {:>7.2f}'.format(
#                state.object_id.replace('_actueel','').replace('_',' ').title(),
#                power))

#summary = '\n'.join([
#    '*{:=^30}'.format(' Sensors '),
#    '${:-^20} : {:-^7}'.format(' Sensor ', 'Power '),
#    *sensor_list,
#    '*{:=^30}'.format(' Summary '),
#    '$ Total: # {:<4} Power : {:>7.2f}'.format(count, total_power),
#    '*' + '='*30])
#
#hass.states.set('sensor.map_total_sensors', '', {
#    'custom_ui_state_card': 'state-card-value_only',
#    'text': summary})
##########################################################################################
# map_sensors_actueel.py
##########################################################################################

ok, since its my BD :birthday:
I have another request for you @pnbruckner, @petro and @NigelL:

this

        colorCode = '%' if power < 20 else \
                    '=' if power < 100 else \
                    '+' if power < 200 else \
                    '#' if power < 500 else \
                    '$' if power < 1000 else \
                    '@' if power < 1500 else \
                    '^' if power < 2000 else \
                    '!' if power < 2250 else \
                    '&' if power < 2500 else \
                    ''
        colorCodeTotal = '%' if total_power < 200 else \
                         '=' if total_power < 500 else \
                         '+' if total_power < 1000 else \
                         '#' if total_power < 1500 else \
                         '$' if total_power < 2000 else \
                         '@' if total_power < 3000 else \
                         '^' if total_power < 4000 else \
                         '!' if total_power < 5000 else \
                         '&' if total_power < 6000 else \
                         '*'

looks to Un-Pythonesque .

shouldn’t this be coded like:

colorCodeTotal = ['%', '=' , '+' , '#' ,'$','@','^' , '!', '&', '*']

and some logic selecting the colorCodeTotal[logic] base on the value_test ?

I got myself a Python course as a present, but this is a bit further in the semester I fear. Hoped you would point me in the right direction a bit sooner … :wink:

Maybe the List is too complicated for this use-case, and if so, please check if this could be simplified otherwise.

thx!

Happy birthday!

Given the sequence of thresholds is not linear I think what you have might be the best you can do. If a linear sequence was ok, then you could index an array like you created with a simple equation. You’d have to make sure of two things, though. First, you’d want an if statement to return some value if the power value would cause the equation to index outside the range of the array. Second, you’d want to make sure the result of the equation was in int before using it to index into the array.

If a linear sequence doesn’t do what you want, then probably a logarithmic one would. However, since I think you want to run this in the limited python_script environment, I’m not sure you’ll be able to use that.

1 Like

understood, as a matter of fact, i use that in one of my other scripts (much helped by @petro) to select a theme:

    themelist = groups_theme[idx].split('|')
    if len(themelist) > 1:
        try:
            theme = themelist[groups_count[idx]]
        except IndexError:
            theme = 'green_badge' # error badge)
    else:
        theme = 'black_badge' # this will be the default theme

the fact that I now need a non-lineair sequence got me in trouble here… glad you confirm I didn’t solve it too clumsily. you’re invited for a Piece of cake :wink:

Happy birthday! Also, I agree with @pnbruckner

Hey @Mariusthvdb. Hope you had a great birthday.

I can come up with other ways to select the colour based on power, but they wouldn’t qualify as ‘better’. Sometimes the hardest part of the job is knowing when to not do it.

Thanks Guys, for your wishes :wink: and for your advice. I’ll settle it then.

Cool.

I know I’m late to the party here, but newer versions of Jinja provide a method to retain variable scope outside of a loop. I used this to make template sensors for my total network client bandwidth, as in:

{% set ns = namespace(rx=0.0, tx=0.0) %}
{% for state in states.sensor %}
    {%   if state.entity_id.endswith('tx') and state.state|float>0 %}
        {% set ns.tx = ns.tx + state.state|float %}
    {% elif state.entity_id.endswith('rx') and state.state|float>0 %}
        {% set ns.rx = ns.rx + state.state|float %}
    {% endif %}
{% endfor %}
RX Total: {{ ns.rx }}
TX Total: {{ ns.tx }}
1 Like