Template sensor loose value when rebooting

Hi, I have this template sensor:

sensor:
  - platform: template
    sensors:
      cop:
        friendly_name: "COP"
        value_template: 1.0
        unit_of_measurement: "M"
        icon_template: mdi:thermometer-lines

I assign the value in a python_script depending of many factors.

The problem is when i reboot Home Assistant. The sensor is 1.0 again. Is there any way to get the last known value of this sensor before using the 1.0 value?

I try this:

value_template: "{{ 1.0 if value is none else value }}"

But it is not working

That’s not how template sensors are meant to work. Instead, the value_template should have all the instructions and rules to calculate the sensor value.

It is a very complex calculation to do in jinja2

  # Calculamos el valor del COP (Impulsion de 35 en invierno y 14 en verano)
  try:
    tempExterior = float(hass.states.get('sensor.temperatura_patio').state);
  except ValueError:
    tempExterior = -30.0 if modo == 'heat' else 50;
  if modo == 'heat':
    tX = (-15.0, -7.0, 2.0, 7.0, 12.0);
    cX = (1.00, 1.35, 2.36, 4.08, 5.46);
  else:
    tX = (24.0, 35.0, 43.0);
    cX = (6.14, 4.06, 2.91);
  cop = cX[-1];
  if tempExterior <= tX[0]:
    cop = cX[0];
  else:
    for i in range(len(tX) - 1):
      if tempExterior > tX[i] and tempExterior <= tX[i + 1]:
        cop = round((tempExterior - tX[i]) * (cX[i + 1] - cX[i]) / (tX[i + 1] - tX[i]) + cX[i], 2);
        break;

There is a potential workaround (i.e. I cannot guarantee that this will always work in the future):
You could create an automation that triggers when HA starts, and in its action use your Python script to update the sensor value.

Hey, I am new to HA, I am trying to do something similar but much more basic.
If the precipitation of the current day is > 90, I am showing that date (rain_last entity).
When the day changes and precipitation is <= 90, I would like to keep the value of the last day it was >90, but it shows empty because I haven’t put anything on the else condition.
I have looked into old_value but that is used automations. Is there anyway i can keep the old values (especially after a reboot) ? Thanks.

sensor:
  - platform: template
    sensors:
      sunrise:
        value_template: "{{ state_attr('sun.sun', 'next_rising') }}"

      rain_last:
        friendly_name: "Rain last"
        value_template: >-
          {% if state_attr('weather.home', 'forecast')[0].precipitation | float > 90 %}
            {{ state_attr('weather.home', 'forecast')[0].datetime }}
          {% endif %}

My recommendation in this case is to set up an input_datetime entity, and to then implement an automation that regularly checks the precipitation state and updates that input_datetime when precipitation is >90. This entity will restore its value after a reboot.

1 Like

Here, i did it for you. You have to add your modo stuff into it, but it’s pretty much the same. I’m assuming you return cop.

{% set modo = 'heat' %} 
{% set tempExterior = states('sensor.temperatura_patio') %}
{% if tempExterior in ['unknown','unavailable'] %}
  {% set tempExterior = -30 if modo == 'heat' else 50 %}
{% else %}
  {% set tempExterior = tempExterior | float %}
{% endif %}
{% if modo == 'heat' %}
  {% set tX = (-15.0, -7.0, 2.0, 7.0, 12.0) %}
  {% set cX = (1.00, 1.35, 2.36, 4.08, 5.46) %}
{% else %}
  {% set tX = (24.0, 35.0, 43.0) %}
  {% set cX = (6.14, 4.06, 2.91) %}
{% endif %}
{% set ret = namespace(cop=cX[-1], found=False) %}
{% if tempExterior <= tX[0] %}
  {% set ret.cop = cX[0] %}
{% else %}
  {% for i in range(len(tX) - 1) %}
    {% if tX[i] < tempExterior <= tX[i + 1] and not ret.found %}
      {% set ret.cop = ((tempExterior - tX[i]) * (cX[i + 1] - cX[i]) / (tX[i + 1] - tX[i]) + cX[i]) | round(2) %}
      {% set ret.found = True %}
    {% endif %}
  {% endfor %}
{% endif %}
{{ ret.cop }}
2 Likes

Thank you so much for the help!
Here is the core code for the automation in case anyone else has this issue:

  trigger:
  - at: '00:00:00'
    platform: time
  condition:
  - condition: template
    value_template: '{{ (state_attr(''weather.home'', ''forecast'')[0].precipitation|float)
      > 90 }}'
  action:
  - data_template:
      date: '{{ as_timestamp(now())|timestamp_custom(''%Y-%m-%d'') }}'
    entity_id: input_datetime.last_rain_date
    service: input_datetime.set_datetime
2 Likes