Create custom sensor with condition

I created a custom sensor in sensor.yaml which works:

- platform: template
  sensors:
    last_illumi_garage:
      entity_id: sensor.hue_motion_sensor_illuminance
      friendly_name: "Last Illuminance Garage"
      unit_of_measurement: 'lx'
      value_template: "{{states('sensor.hue_motion_sensor_illuminance') }}"

How do I add a condition to this (light.signify_garage needs to be off) so it only updates in that case.

You could do it in multiple ways:

  1. Use the ‘if’ condition in the template, so that the value of the sensor only updates how you want it to update. See here for some examples: Template - Home Assistant

  2. You could keep the sensor as is, and use a condition in the automation when you are actually using the sensor. E.g. if you only want to do something when the garage light is off AND this sensor is triggered, then add that as a condition to an automation.

I tried the example in sensor.yaml, but it gives me a syntax error

template:
  - sensor:
      - name: "Light"
        state: >
          {% if is_state('light.signify_garage', 'off') %}
            off
          {% elif is_state('light.signify_garage', 'on') %}
            on
          {% else %}
            failed
          {% endif %}

Tkx, I just managed to get it working myself

- platform: template
  sensors:
    last_illumi_garage:
      friendly_name: "Last Illuminance Garage"
      unit_of_measurement: 'lx'
      value_template: >
        {% if is_state('light.signify_garage', 'off') %}
            {{states('sensor.hue_motion_sensor_illuminance') }}
        {% endif %}

Is it possible to make it keep the value it already has, in case the light is on? Now the value is just empty. I’m guessing I need something in the else part.

- platform: template
  sensors:
    last_illumi_garage:
      friendly_name: "Last Illuminance Garage"
      unit_of_measurement: 'lx'
      value_template: >
        {% if is_state('light.signify_garage', 'off') %}
            {{states('sensor.hue_motion_sensor_illuminance') }}
        {% else %}
            {{states('sensor.last_illumi_garage') }}
        {% endif %}

Just add an else statement that uses the sensor’s original value

1 Like