Most idiomatic way to trigger only when integer increases (entity can be unavailable)

Hi!

I’m trying to wrap my head around what’s the shortest and most comprehensible way going forward here, perhaps there are some best practices or common ways…?

Problem is simple: I have an entity with a numeric state and want to create an automation that fires only when the state, an integer, increases. The crux here is that the entity can also be unavailable and I want to avoid firing the automation when it goes to or comes back from unavailable.

For example, let’s use my sensor.vacuum_total_clean_count

Approach 1

  trigger:
    entity_id: sensor.vacuum_total_clean_count
    platform: state

This will trigger for all state changes, including 22unavailable22

Approach 2

  trigger:
    entity_id: sensor.vacuum_total_clean_count
    platform: state
  condition: 
    - condition: template
      value_template: >
        {{ trigger.to_state.state | float > trigger.from_state.state | float  }}

Since the float filter defaults to 0,0 this will also trigger when going from unavailable to 22 since the former renders as 0,0… also if I add some other default values I would have to make up an arbitrary huge number for the “from state float” to avoid triggering on unavailable22 which feels bad…

Approach 3

  trigger:
    entity_id: sensor.vacuum_total_clean_count
    platform: state
  condition: 
    - condition: template
      value_template: >
        {{ trigger.from_state.state is not 'unavailable' and
           trigger.to_state.state | float > trigger.from_state.state | float  }}

This is starting to look better but then I’m reading up on templating and I see that I should also cover for undefined values…

Approach 4

  trigger:
    entity_id: sensor.vacuum_total_clean_count
    platform: state
  condition: 
    - condition: template
      value_template: >
        {{ trigger.from_state is not none and
           trigger.to_state is not none and
           trigger.from_state.state is not 'unavailable' and
           trigger.to_state.state | float > trigger.from_state.state | float  }}

Now this is starting to become quite a lot of code that in my opinion reads different from what I’m trying to achieve… so it makes me wonder, is there a more idiomatic approach here? Something else I’m not seeing?

I guess you can throw is_number into the mix too, but you still have to cover for undefined values then as well right?

And I’ve seen that some entities report the state as unknown instead of unavailable… is there some simple way to check for both none, unknown and unavailable (and god knows what else?) or do I need to explicitly check each…?

Thanks in advance for any best practices and help navigating this templating jungle! :smiley:

{{ trigger.from_state.state not in ['none', 'unavailable', 'unknown'] and trigger.to_state.state | float(0) > trigger.from_state.state | float(0)  }}

that should do it…I think…

1 Like