Not getting the states("{{ trigger.entity_id }} correct

I know I am missing something simple but I am dumbfounded to find out what is missing. Trying to get the fan of the specific XiaoMi Air Purifier (I have 4 here) to turn on when its sensor has breached its threshold. No problem in writing 2 automation to achieve what I need but trying to consolidate into 1 instead.

alias: "Air Purifiers Bad AQI State Change"
description: ""
trigger:
  - platform: state
    entity_id:
      - sensor.jtr_mi_air_purifier_3c_pm2_5
      - sensor.ctr_mi_air_purifier_3c_pm2_5
      - sensor.mbr_mi_air_purifier_3c_pm2_5
      - sensor.lvr_mi_air_purifier_3c_pm2_5
    id: Bad_AQI_Change
condition: []
action:
  - service: >-
      fan.turn_{{ 'on' if states("{{ trigger.entity_id }}") | int > 12 else 'off'
      }}
    data: {}
    target:
      entity_id: "{{ trigger.entity_id|replace('sensor', 'fan')|replace('_pm2_5', '') }}"
mode: single

Nothing wrong with the target but the exception is thrown at the service level (fan):
Error: Error rendering service name template: ValueError: Template error: int got invalid input “unknown” when rendering template ‘fan.turn_{{ ‘on’ if states("{{ trigger.entity_id }}")|int > 12 else ‘off’ }}’ but no default was specified.

Any advice on how to unblock this ? Thank you !

action:
  - service: >-
      fan.turn_{{ 'on' if states(trigger.entity_id) | int > 12 else 'off'
      }}
    data: {}
    target:
      entity_id: "{{ trigger.entity_id|replace('sensor', 'fan')|replace('_pm2_5', '') }}"

Another way to do the same thing:

action:
  - service: "fan.turn_{{ iif(trigger.to_state.state | int(0) > 12, 'on', 'off') }}"
    target:
      entity_id: "fan.{{ trigger.to_state.object_id[:-6] }}"
1 Like

Bingo Tom ! Thank you so much. I know its something simple but I didnt know it is even simpler :smile: Thank you once again !

Be advised that if any of those four sensors were to change state to unavailable (or unknown) the template will fail with an error. The reason is because the int filter hasn’t been supplied with a default value. In the example I posted, the int filter’s default is zero.

2 Likes

Thanks for the tip. I really appreciate this !

1 Like