Help needed with custom sensor

Hi, I need a custom template sensor that will create a state based on the attribute and state of the original sensor.

The original sensor is:

However if I set the fan speed to off, the sensor speed attribute actually remains ‘medium’, it just switches the fan off.

What I need is 1 sensor that will display the speed attribute, but not when the fan is off, so what I need is a template sensor with the following states:

Off
Low
Medium
High

I build this template:

sensor:
- platform: template
  sensors:
    comfofan_state:
      friendly_name: "Comfofan status"
      entity_id: fan.esp32_fan_controller_02
      value_template: "{{ state_attr('fan.esp32_fan_controller_02', 'speed') }}"

But that will only give me low, medium and high. but not off.

How to do this?

Try this:

      value_template: "{{ 'off' if states('fan.esp32_fan_controller_02') == 'off' else state_attr('fan.esp32_fan_controller_02', 'speed') }}"

It reports off if the fan’s current state is off otherwise it reports the fan’s current speed attribute.

Hi,

Thank you so much. This works great!

1 Like

You being a fan of shortening code, surprised you didn’t go for is_state :slight_smile:

value_template: "{{ 'off' if is_state('fan.esp32_fan_controller_02', 'off') else state_attr('fan.esp32_fan_controller_02', 'speed') }}"

Wait, I just did a character count. They are identical. Crap.

1 Like

Yup.

is_state('fan.esp32_fan_controller_02', 'off')
states('fan.esp32_fan_controller_02') == 'off'
1234567890123456789012345678901234567890123456
         1         2         3         4      

I’ve used both forms and I’d be hard-pressed to explain why I chose one over the other in a given situation beyond “It seemed like a good idea at the time.” :slight_smile:

I can save a character !!! Do i win a prize ??? can I get the ‘fluffy teddy’ in the back corner ?

states('fan.esp32_fan_controller_02') != 'on'
1234567890123456789012345678901234567890123456
         1         2         3         4      

It’s not error resistant and I wouldn’t use it … but … technically …

Nah it’s still shit !

:rofl: