Pulling my hair out over this one. I’m very new to Jinja2 so trying to get my head around things. I have a bunch of motion sensors placed into groups based on the room they are in. I am trying to get a template to figure out which group was most recently changed, but my results are weird probably due to my IF statement not comparing the two epoch times correctly.
Here’s what I’ve written so far:
{% set currentTime = as_timestamp(now()) %}
Current epoch seconds are {{ currentTime }}
{% set presence = [ states.group.living_presence,
states.group.office_presence,
states.group.kitchen_presence,
states.group.bedroom_presence,
states.group.dining_presence] %}
{% set last_changed = as_timestamp(presence[0].last_changed) %}
{% set difference = currentTime - last_changed %}
{% set most_recent = difference %}
Starting with {{presence[0].entity_id}}, it was last changed {{difference}} seconds ago. It is now the most recently changed.
{% for p in presence %}
{% set last_changed = as_timestamp(p.last_changed) %}
{% set difference = currentTime - last_changed %}
When comparing {{p.entity_id}}, which was last changed {{difference}} seconds ago,
{% if ( difference < most_recent ) %}
{% set most_recent = difference %}
{{p.entity_id}} was more recently changed, therefore {{p.entity_id}} is now the most recent.
{% else %}
It was not more recenty changed and so stays the most recently changed.
{% endif %}
{% endfor %}
The results are:
Current epoch seconds are 1576316187.837726
Starting with group.living_presence, it was last changed 9325.64158821106 seconds ago. It is now the most recently changed.
When comparing group.living_presence, which was last changed 9325.64158821106 seconds ago,
It was not more recenty changed and so stays the most recently changed.
When comparing group.office_presence, which was last changed 414.2968921661377 seconds ago,
group.office_presence was more recently changed, therefore group.office_presence is now the most recent.
When comparing group.kitchen_presence, which was last changed 289.0434319972992 seconds ago,
group.kitchen_presence was more recently changed, therefore group.kitchen_presence is now the most recent.
When comparing group.bedroom_presence, which was last changed 3208.34237909317 seconds ago,
group.bedroom_presence was more recently changed, therefore group.bedroom_presence is now the most recent.
When comparing group.dining_presence, which was last changed 9321.240389108658 seconds ago,
group.dining_presence was more recently changed, therefore group.dining_presence is now the most recent.
Please excuse the very ugly ‘english’ output, which I am using to make the results more human readable.
As you can see the most recently changed group ends up as group.dining_presence, which was changed 9321 seconds ago. The true result should be group.kitchen_presence. For some reason the comparison of {% if ( difference < most_recent ) %} is not evaluating correctly.
Any ideas much appreciated!