Template sensor unavailable

Hi

I’ve been trying to use a template sensor based on two different temperature sensors.
The two sensor display the temperature OK.
The “Active room temperature” state is Unavailable.

I am not a programmer and I think I did not get this right. Also searched the forum but couldn’t find something similar. :thinking:

This is the yaml part in configuration.yaml:

sensor:
  - platform: template
    sensors:
      active_room_temperature:
        device_class: temperature
        friendly_name: "Active room temperature"
        unit_of_measurement: '°C'
        value_template: >-
          {% if time('23:00', '08:00') %}
            sensor.bedroom_temperature
          {% else %}
            sensor.living_temperature
          {% endif %}

time() is not a valid function. And if it was, sensor.living_temperature will just be a string. If you want the value of a sensor, you use states('sensor.my_sensor')

value_template: >-
  {% if now().hour >= 23 or now().hour <= 8 $}
    states('sensor.bedroom_temperature')
  {% else %}
    states('sensor.living_temperature')
  {% endif %}

Thanks. Tried it and now the state is a string states(‘sensor.bedroom_temperature’)
I miss something here and searching for an example is difficult as everybody seem to use another formatting that works :sweat_smile:

*replaced the $ with %
Also tried this but the state for entitiy sensor.active_room_temperature is still a string “states(‘sensor.bedroom_temperature’)”:

  - platform: template
    sensors:
      active_room_temperature:
        device_class: temperature
        friendly_name: "Active room temperature"
        unit_of_measurement: '°C'
        value_template: >
          {% if now().strftime('%T') > '23:00:00' or now().strftime('%T') < '8:00:00' %}
            states('sensor.bedroom_temperature')
          {% else %}
              states('sensor.living_temperature')
          {% endif %}
value_template: >-
  {% set room = 'sensor.bedroom_temperature' if now().hour >= 23 or now().hour <= 8 else 'sensor.living_temperature' %}
  {{ states(room) }}

Alternately:

value_template: >-
  {% set room = 'bedroom' if now().hour >= 23 or now().hour <= 8 else 'living' %}
  {{ states('sensor.' ~ room ~ '_temperature') }}

Thanks. Works like a charm. :pray:

1 Like

Glad to hear it works. Please consider marking my post (above) with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic has an accepted solution. This helps other users find answers to similar questions.

just so OP understands why @123’s solution works, please see:

value_template: >-
  {% if now().hour >= 23 or now().hour <= 8 %}
    {{states('sensor.bedroom_temperature')}}
  {% else %}
    {{states('sensor.living_temperature')}}
  {% endif %}

for the verbose version of it. Jim only missed the enclosing double curly brackets {{}}