I use a template to keep the max value of a sensor (based on a 15 minute utility meter), this works fine, the max value is kept, but when I do a reload of my templates.yaml, the max value is replaced with the current value of sensor and the max value is lost.
# max value and reset
- trigger:
- platform: state
entity_id: sensor.peak_consumption
sensor:
- name: Max kW month
state: >
{% set a = states('sensor.peak_consumption') | float(None) %}
{% set b = states('sensor.max_kw_month') | float(None) %}
{% if a != None and (b == None or a > b) %}
{{ a | float(0) }}
{% else %}
{{ b | float(0) }}
{% endif %}
unit_of_measurement: kW
but when I add a delay to the trigger, the max value is not lost after a reload.
# max value and reset
- trigger:
- platform: state
entity_id: sensor.peak_consumption
for: "00:00:01"
can someone tell me why this is and if there is another solution instead of a delay?
Add not_to to your trigger to avoid the issues “unknown” and “unavailable” are causing at restart… also you don’t have anything to make it start over monthly.
# max value and reset
- trigger:
- platform: state
entity_id: sensor.peak_consumption
not_to:
- unknown
- unavailable
- platform: template
value_template: "{{ now().day == 1 }}"
sensor:
- name: Max kW month
state: >
{% set source = states('sensor.peak_consumption') | float(0) %}
{% set current = this.state | float if (this is defined and this.state is defined) else source %}
{{ source if trigger.platform == 'template' else [source, current] | max }}
unit_of_measurement: kW
I do have a reset trigger too, but did not include it in this code.
and in the sensor.peak_consumption template there is a float(0) to avoid unknown or unavailable.
I did not include all this because it had nothing to do with the reload issue.
- trigger:
- platform: template
value_template: "{{ now().strftime('%d-%H:%M') == '01-00:00' }}"
id: 'reset'
- platform: state
entity_id: sensor.peak_consumption
for: "00:00:01"
sensor:
- name: Max kW month
state: >
{% set a = states('sensor.peak_consumption') | float(None) %}
{% set b = states('sensor.max_kw_month') | float(None) %}
{% if a != None and (b == None or a > b) %} {{ a | float(0) }}
{% elif trigger.id == 'reset' %} {{ '0' }}
{% else %} {{ b | float(0) }}
{% endif %}
unit_of_measurement: kW
That doesn’t avoid “unknown” or “unavailable”, it just gives them a different value. At restart, both sensors can be unknown or ‘unavailable’ which would make both a and b equal to none. In that situation, your if/then will use the else and return 0.
oh ok, I assumed float(0) would fix the unknown or unavailable issue because it returned a 0 instead of unknown or unavailable.
it makes sense now knowing float(0) does not avoid it!
thx for the explanation.