Entities statistics

I’m just sharing a script that creates and updates a statistics related sensor with number of different entities, the state of the sensor being the total number of entities in your system.

Prerequisites:

  • you have to have jq package installed
  • hass_header.txt contains the needed http header together with the long-lived access token

Create then an entry in shell_commands.yaml:

stats: /home/username/homeassistant_conf/scripts/stats"

Create an automation that runs e.g. daily:

alias: "Entities stats"
initial_state: "on"
id: entities_stats
triggers:
  - trigger: time_pattern
    hours: /23
action:
  - service: shell_command.stats

The script:

#!/bin/bash

curl -s -H @$HOME/hass_header.txt http://localhost:8123/api/states | jq -r ".[].entity_id" \
  |sort|awk -F\. '{print $1}'|uniq -c \
  |awk 'BEGIN {print "{\"attributes\": {";t=0} \
     { if (NR == 1) \
         { print "\"" $2 "\": \"" $1 "\""} \
       else { print ",\"" $2 "\": \"" $1 "\"" }; \
       t=t+$1 \
     } END {print "}, \"state\": \"" t "\"}"}'| \
curl -s -H @$HOME/hass_header.txt -X POST http://localhost:8123/api/states/sensor.stats \
  -d @-

The result:

You can do this all inside HA if you want, so that you don’t need external packages and an access token.

template:
  - triggers:
      - trigger: time_pattern
        # This will update every night
        hours: 0
        minutes: 0
    actions:
      - variables:
          entity_dict: >
            {% set my_states = states %}
            {% set my_entities = my_states | map(attribute='entity_id') | unique | sort | list %}
            {% set my_domains = my_states | map(attribute='domain') | unique | sort | list %}
            {% set ns = namespace(my_list=[]) %}
            {% for domain in my_domains %}
              {% set ns.my_list = ns.my_list + [(domain, my_entities | select('match', domain) | list | count)] %}
            {% endfor %}
            {{ dict(ns.my_list) }}
    sensor:
      # Keep track how many entities are in your system
      - name: "Entity Stats"
        state: "{{ entity_dict.values() | sum }}"
        unit_of_measurement: "Count"
        attributes:
          domains: "{{ entity_dict }}"
1 Like