I want to display these names of birds on the frontend with the total count of the specific bird ‘detected’ on the current day. (from Birdnet-Pi)
At the moment i’m displaying the latest bird detection. But as I said, I want a list of the birds of the current day and their total count that day.
I’m testing with Templates, but i’m stuck. I have this:
{% set entity_id = 'sensor.garden_birds' %}
{% set state_objects = states[entity_id] %}
{% set history_states = state_objects | selectattr('last_changed') | list %}
Historical States of {{ entity_id }}:
{% for state in history_states %}
- Vogel: {{ state.state }}
{% endfor %}
With this Template, I get the error ‘KeyError:’. As of there are no previous states. But that not true. There are lots…
The sensor itself will have a state. That’s what you’d use. At that point, you can do whatever you want with the data. But because you want a list of states, you’ll most likely need to use a template to parse the data in a meaningful way. First step is to get the data though before you can get to that point.
I got the sql working. In phpMyAdmin and the SQL integration. I’ve put it in a sensor.
SELECT state FROM states INNER JOIN states_meta ON states.metadata_id = states_meta.metadata_id WHERE states_meta.entity_id = ‘sensor.garden_birds’ AND last_updated_ts <= UNIX_TIMESTAMP(NOW() - INTERVAL 1 DAY) ORDER BY last_updated_ts DESC;
Solved it. First I had a problem that the sensor was updating to unknown. This was due to the fact an sensor state can only have max. 255 characters.
I solved it with a HACS integration called sql_json.
And than in de configuration yalm:
sensor:
- platform: sql_json
scan_interval: 86400
db_url: mysql://user:pass@core-mariadb/homeassistant?charset=utf8mb4
queries:
- name: "Vogelranglijst"
query: >-
SELECT CONCAT('[', GROUP_CONCAT(vogel_json), ']') AS json
FROM (
WITH states AS (
SELECT state, COUNT(*) AS vogel_count
FROM (
SELECT state FROM states
INNER JOIN states_meta ON states.metadata_id = states_meta.metadata_id
WHERE states_meta.entity_id = 'sensor.garden_birds'
AND last_updated_ts >= UNIX_TIMESTAMP(CURDATE())
) AS states
GROUP BY state
ORDER BY vogel_count DESC
)
SELECT JSON_OBJECT(
'state', state,
'count', vogel_count
) AS vogel_json
FROM states
/*LIMIT 10*/
) AS json_output;
value_template: '{{ value_json[0].count }}'
unit_of_measurement: vogels
column: json
After that I used the example in de documentation to form a front-end flex table card: