Template to determine if room is occupied

Hi everyone

So i am new to Home Assistant, Python and Jinja (though have programmed in other languages to varing degrees), and am trying to get my head around how the templating syntax works .

I am trying to create a template that can determine if a room is occupied and how many people are in that room. I have a motion sensor in my hall and one in the “reading room” and am determining direction of travel based on which sensor detected movement last

Here is the code I am popping into the template section of the developer tools:

{% set sensors = [states.binary_sensor.hall_motion, 
				  states.binary_sensor.reading_room_motion] %}
{% set ns = namespace(latest=sensors[0]) %}
{% for s in sensors[1:] %}
  {% if s.last_changed > ns.latest.last_changed %}
    {% set ns.latest = s %}
  {% endif %}
{% endfor %}

{% if ns.latest.entity_id == "binary_sensor.reading_room_motion" %}
  Reading room is occupied
{% else %}
  Reading room is empty
{% endif %}

…so most of the code above was plagiarised from other helpful posts i’ve been reading on here. Sorry, can’t remember who posted it before, but kudos to you if you recognise it.

So the code above will give the correct empty/occupied result depending on where i walk, but then i thought it would be good to include a counter so as more people enter the room it increases, as they leave it decreases, and only when the counter hits 0, meaning everyone has left, can i then turn off things in that room.

I have created a counter under the configuration/helpers section, but am not sure how i can call the service to increment/decrement the counter helper within the template

Anyone out there know how best i can do this?..maybe i’m thinking about it wrong and i should look to do it a different way?

What you’re asking for is near impossible to infer when you have more than 1 person in a room. And it most likely won’t be accurate.

1 Like