Template: Count device_trackers state "home" EXCEPT of those in the template

In a previous topic @Burningstone wrote a sensor that counts device trackers in a list and returns an number saying how many of these device trackers that has the state “home”. A simple “count people at home”-template.

Here’s the template @Burningstone suggested:

sensor:
  - platform: template
    sensors:
      people_home_count:
        value_template: >-
          {{ states.device_tracker | selectattr('state', 'eq', 'home') 
          | selectattr('entity_id', 'in', ['device_tracker.galaxynote8_2','device_tracker.galaxynote8'])
          | list | count}}

But let’s say I would rather like to count how many device.trackers in my HA-installation that has the state “home” except of those in the list. It is easy to refactor the template @Burningstone suggested?

What I would like to achieve is a counter that counts how many persons are connected to my wifi, but instead of listing the device i’d have to count, I’d rather count how many devices are connected except of those devices that are always connected, such as printers, TV etc.

By using this method instead, I could just add people to my wifi without having to edit the template each time someone new connects to my wifi.

Every suggestion is welcome!

If I understood your issue correctly, you should be able to just change the ‘in’ to ‘not in’ and replace the list of the samsungs phones with a list of all the devices you don’t want to count. This way it will count all device trackers that are ‘home’ and not in the list you provided.

1 Like

Hello again @Burningstone . Glad you answered this topic as well. :slight_smile:

I have testet

not ‘in’

as well as

‘not in’

resulting in an err.msg

Here is my current code:

sensor:
  - platform: template
    sensors:
      people_home_count:
        value_template: >-
          {{ states.device_tracker | selectattr('state', 'eq', 'home') 
          | selectattr('entity_id', 'not in', ['device_tracker.device_!','device_tracker.device_2'])
          | list | count}}

I see the not in operator is not supported, however you can use rejectattr with in instead like this:

sensor:
  - platform: template
    sensors:
      people_home_count:
        value_template: >-
          {{ states.device_tracker | selectattr('state', 'eq', 'home') 
          | rejectattr('entity_id', 'in', ['device_tracker.device_!','device_tracker.device_2'])
          | list | count}}

Is one device tracker really named device_tracker.device_! or is this a typo?

That was just a typo, I just entered some random device name. of course you cannot use a ! in a device name.

Besides of that, your template above works flawless, as usual! :slight_smile:

Thanks for your help.

1 Like