Template sensors - some help

EDIT: I started with below strike through question. But it turned out to better use a statistics sensor. Thus below code is not used and this post is now going further about using a statistic sensor.

As I am reading through my logging (once in a while it’s cleanup time) I stumble upon one of my favorite topics - template sensors.

I find 3 errors in my log and they refer to 3 template sensors. I am not sure how the ended up in my config, but most probably I added them :slight_smile:. I think I was playing with an accumulated sensor to count the water amount per every last 5 minutes.
in short: they are all “unavailable”. Probably because there is an error (again) in the syntax of them… And there I need some help (please be gentle with me Petro) to find what is causing the error and how I can get such a sensor. Below probably 3 tries:

The sensor config:

</s> <s> - platform: template</s> <s> sensors:</s> <s> accumulated_water_usage_5min:</s> <s> friendly_name: "Accumulated Water Usage (5 min)"</s> <s> value_template: ></s> <s> {% set window_start = now() - timedelta(minutes=5) %}</s> <s> {% set water_consumption = states('sensor.water_consumptie_nu') %}</s> <s> {% set events = state_changes['sensor.water_consumptie_nu'] %}</s> <s> {% set accumulated_usage = 0 %}</s> <s> {% for event in events %}</s> <s> {% if event.state == 'unknown' %}</s> <s> {% set accumulated_usage = 0 %}</s> <s> {% elif event.state | float > 0 and event.last_changed > window_start %}</s> <s> {% set accumulated_usage = accumulated_usage + (event.state | float) %}</s> <s> {% endif %}</s> <s> {% endfor %}</s> <s> {{ accumulated_usage | round(2) }}</s> <s> </s> <s> - platform: template</s> <s> sensors:</s> <s> accumulated_water_usage_5min_2:</s> <s> friendly_name: "Accumulated Water Usage (5 min) 2"</s> <s> unit_of_measurement: "liters" # Adjust as needed</s> <s> value_template: ></s> <s> {% set window_start = now() - timedelta(minutes=5) %}</s> <s> {% set accumulated_usage = 0 %}</s> <s> {% for event in state_attr('sensor.water_consumptie_nu', 'all') %}</s> <s> {% if event.state != 'unknown' and event.last_changed > window_start %}</s> <s> {% set accumulated_usage = accumulated_usage + (event.state | float) %}</s> <s> {% endif %}</s> <s> {% endfor %}</s> <s> {{ accumulated_usage | round(2) }}</s> <s> </s> <s> - platform: template</s> <s> sensors:</s> <s> accumulated_water_usage_5min_3:</s> <s> friendly_name: "Accumulated Water Usage (5 min) 3"</s> <s> unit_of_measurement: "liters" # Adjust as needed</s> <s> value_template: ></s> <s> {% set interval = 5 * 60 %} # 5 minutes in seconds</s> <s> {% set time_threshold = now() - timedelta(seconds=interval) %}</s> <s> {% set accumulated_usage = 0 %}</s> <s> {% for event in state_attr('sensor.water_consumptie_nu', 'all') %}</s> <s> {% if event.state != 'unknown' and event.last_changed >= time_threshold %}</s> <s> {% set accumulated_usage = accumulated_usage + (event.state | float) %}</s> <s> {% endif %}</s> <s> {% endfor %}</s> <s> {{ accumulated_usage | round(2) }}</s> <s>

The error:

```
Logger: homeassistant.components.template.template_entity
Source: components/template/template_entity.py:194
Integration: Template (documentation, issues)
First occurred: 19:47:47 (3 occurrences)
Last logged: 19:47:47

TemplateError(‘UndefinedError: ‘state_changes’ is undefined’) while processing template ‘Template<template=({% set window_start = now() - timedelta(minutes=5) %} {% set water_consumption = states(‘sensor.water_consumptie_nu’) %} {% set events = state_changes[‘sensor.water_consumptie_nu’] %} {% set accumulated_usage = 0 %} {% for event in events %} {% if event.state == ‘unknown’ %} {% set accumulated_usage = 0 %} {% elif event.state | float > 0 and event.last_changed > window_start %} {% set accumulated_usage = accumulated_usage + (event.state | float) %} {% endif %} {% endfor %} {{ accumulated_usage | round(2) }}) renders=4>’ for attribute ‘_attr_native_value’ in entity ‘sensor.accumulated_water_usage_5min’
TemplateError(‘TypeError: ‘NoneType’ object is not iterable’) while processing template ‘Template<template=({% set window_start = now() - timedelta(minutes=5) %} {% set accumulated_usage = 0 %} {% for event in state_attr(‘sensor.water_consumptie_nu’, ‘all’) %} {% if event.state != ‘unknown’ and event.last_changed > window_start %} {% set accumulated_usage = accumulated_usage + (event.state | float) %} {% endif %} {% endfor %} {{ accumulated_usage | round(2) }}) renders=4>’ for attribute ‘_attr_native_value’ in entity ‘sensor.accumulated_water_usage_5min_2’
TemplateError(‘TypeError: ‘NoneType’ object is not iterable’) while processing template ‘Template<template=({% set interval = 5 * 60 %} # 5 minutes in seconds {% set time_threshold = now() - timedelta(seconds=interval) %} {% set accumulated_usage = 0 %} {% for event in state_attr(‘sensor.water_consumptie_nu’, ‘all’) %} {% if event.state != ‘unknown’ and event.last_changed >= time_threshold %} {% set accumulated_usage = accumulated_usage + (event.state | float) %} {% endif %} {% endfor %} {{ accumulated_usage | round(2) }}) renders=4>’ for attribute ‘_attr_native_value’ in entity ‘sensor.accumulated_water_usage_5min_3’
```

Dumb question from me maybe, but is this a physical device and is it available?

Yes physical, and yes available:

Without knowing what data is available from your source sensor and its attributes, it is very unlikely anyone can answer your question… Unless your source provides a database of the consumption values with timestamps, this is not likely a reasonable case for using a state-based template sensor.

Have you tried using a Statistics sensor (sum type)?

Will try Statistic sensor… is that a “sliding” windows statistics? Thus will it always show “the last 5 minutes water total/accumulated usage”?

Yes, if you specify the max_age configuration variable to your desired length of time.

Something like this?

  - platform: statistics
    name: "Accumulated Water Usage (5 min)"
    entity_id: sensor.water_consumptie_nu
    state_characteristic: sum
    max_age:
      minutes: 5

Let’s see if it fills the next hours :slight_smile:

OK, this is weird… I am not getting an entity after the above is in sensor:

Hi, is there any one able to tell me why my statistic sensor is not showing up as an entity?

Are there any errors in the logs?

No, no errors

Anyone able to help out?

If the entity isn’t showing up then it has not been added to the configuration correctly. There are many ways that it could be wrong… but we can’t debug what you don’t share.

What file did you add the statistics sensor configuration too?
If that file isn’t configuration.yaml, are you sure it is being merged properly?
Does the file where it is located have more than one top-level sensor key?
Is everything indented properly?

This is the configuration.yaml:

This is the sensors.yaml:

the sensors.yaml file is 680 lines long and all my sensors declared there are operational…

EDIT: Hmz, after I deleted the "" from name: I get an entity:

That’s weird as the documentation tells to use brackets around the name:.

And readings are not very ok… 5 minutes of water usage sums up to 568.99L (!)?

It looks like all sensors in sensors.yaml are indented one level too much.
Also, you still use a float filter float without a default. That should be something like float(0) or some other default.

I know, but for all ~60 sensors that’s not an issue.

Not sure what you mean here and where…

In the first post not all sensors are indented to the same level, so that may be why others work and some don’t. The float filter I also noticed in the first post. For instance here:

replace float with float(0) so it will use 0 when the state is not a float (e.g. undefined at startup).

You’re right! That’s misleading as in the first post I asked about that config, but soon it turned out to better use a statistics sensor.

The code from the first post is not present anymore thus.

I’ll amend the first post.