How to automatically include and sum the values of multiple Utility Meter Sensors

I have multiple Utility Meter sensors that collect from various plugs and devices. They collect total energy usage for each device perfectly, but I want to create a single total value for say all daily sensors.

The naming convention is sensor.daily_devicename_energy where devicename changes based on the source devices the kWh value is collected from in Utility Meter.

I think I need to use some kind of value template filter, to collect all device with the name sensor.daily_*_energy to have an aggregated total energy consumed by multiple devices.

I want to set it up, so when I add a new device, it is automatically identified by name and then added to the usage total without having to manually add each new daily sensor to the list.

What is the best way to filter and aggregate?

Thanks in advance for any help

That’s not possible with template sensors.

Template sensors require entity_id’s to listen to. If you use dynamic entity_ids, the system doesn’t know when to create a ‘listener’, so you end up with no listeners.

You’ll always need to manually add an item to the template sensor.

But you could add sensor.time to the template sensor and it will update once a minute.

That would look like this:

sensor:
- platform: date_time
  display_options:
  - 'time'

- platform: template
  sensors:
    total_daily_energy:
      friendly_name: Total Daily Energy
      entity_id: sensor.time
      value_template: >
        {% set ns = namespace(states=[]) %}
        {% for s in states.sensor %}
          {% if s.object_id.startswith('daily_') and s.object_id.endswith('_energy') %}
            {% set ns.states = ns.states + [ s.state | float ] %}
          {% endif %}
        {% endfor %}
        {{ ns.states | sum }}
2 Likes

:+1: :+1: :+1: :+1:

I thought manually adding might be the case with template sensors.

Thanks for the code, I’ll give that a try when I get back and test it. Really appreciated.

This worked an absolute treat, thank you very much for your help! Have to be honest, doubt I would have figured this out myself calling a time sensor to force new listeners.

Made a couple of small changes

change date_time to time_date
added unit of measurement kWh
Add | round(2) after the sum

sensor:
- platform: time_date
  display_options:
  - 'time'

- platform: template
  sensors:
    total_daily_energy:
      friendly_name: Total Daily Energy
      entity_id: sensor.time
      unit_of_measurement: kWh
      value_template: >
        {% set ns = namespace(states=[]) %}
        {% for s in states.sensor %}
          {% if s.object_id.startswith('daily_') and s.object_id.endswith('_energy') %}
            {% set ns.states = ns.states + [ s.state | float ] %}
          {% endif %}
        {% endfor %}
        {{ ns.states | sum | round(2) }}
1 Like