Show 0 if value below 2

Hi. I am using a power measure for my water tank lighting. The controller is consuming 1w is it possible to make a template for this so it show power usage as 0w when the value is below 2?

template:
  - sensor:
      - name: Water Tank Light Power
        unit_of_measurement: W
        device_class: power
        state_class: measurement
        state: >
          {% set power = states('sensor.your_power_sensor_here')|float(0) %}
          {{ 0 if power < 2 else power }}
        availability: "{{ has_value('sensor.your_power_sensor_here') }}"
1 Like

while weā€™re at itā€¦
does a command like ā€œ{{ has_value(ā€˜sensor.your_power_sensor_hereā€™) }}ā€ exist for sensorā€™s attribute, too? Iā€™d need oneā€¦

has_value() will report true as long as the entity exists and its state is not unavailable or unknown.

If you want to check whether an attribute exists you can use

{{ state_attr('sensor.my_sensor', 'my_attribute') != None }}

There are also functions like is_number() that can be used to verify a value is a number (or is a string that represents a number), so if you are expecting the attribute to be a number you could use:

{{ is_number(state_attr('sensor.my_sensor', 'my_attribute')) }}

Iā€™m not sure when youā€™d have a sensor whose attributes can go to unavailable or unknown while the sensor state itself is valid, but if you want to replicate the functionality of the has_value() function for an attribute you could do:

{{ not state_attr('sensor.my_sensor', 'my_attribute') in [None, 'unavailable', 'unknown'] }}
1 Like

YES!! Third one is ā€œthe oneā€! Thanks a lot!
It turned out that two attributes: ā€œcurrent_temperatureā€ and ā€œtemperatureā€ (thatā€™s set temp for climate) can be eihter missing or ā€œNoneā€ so thatā€™s an option for all cases.

I owe you an brief explanation why i need this:
i connected my Mitsubishi climate to wifi via ESP module and esphome. My problem is that when i restart HA it often happens (but not always) that esp module is connected, itā€™s working ( i get IP, MAC, uptimeā€¦), only communication with climate doesnā€™t work (i donā€™t get temps and status). Reboot of esp module helps in this case. I have yet to discover if this is because i donā€™t have level converter (esp has 3.3V, while climate has 5V) or is just my climateā€™s faultā€¦ but in the meantime iā€™ll solve this with automation which will reboot module if needed.
Thanks again!

That or:

{{ state_attr('sensor.my_sensor', 'my_attribute')|is_number }}

Are my preferred methods.

1 Like

I agree, using it as a filter instead of a function is easier to read and you donā€™t have to count parentheses.

1 Like