There were no built-in way to provide the statistics I wanted to have for tracking when we are home, so here what I came up with:
This display then uses the entities card, with a divider.
Above is a picture elements with black-and-white photos if we’re away, and color photo if we’re home.
The status of our phone-ping and BT-detection is shows.
What I wanted:
Daily Time (hours since midnight, and ratio of time home vs hours up to that time of the day)
Daily Average Time (measured across full day ‘cycles’, so starting at midnight the day of and lasting a number of duration days, and ratio of time)
history_stat components were used for the raw data.
Daily Time:
For daily time, I chose the ‘ratio’ option of history_stat, because a nicely formatted time string is also provided as the ‘value’ attribute. A simple template sensor concatenates the two values.
sensor:
- platform: history_stats
name: Person1 Daily Time Home Raw
entity_id: group.person1_device_trackers
state: 'home'
type: ratio
start: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
end: '{{ now() }}'
- platform: template
sensors:
nicholas_today_stats:
value_template: >-
{{ state_attr('sensor.person1_daily_time_home_raw', 'value') }} / {{ states('sensor.person1_daily_time_home_raw') | round(0) }}%
The kicker (for me):
For Daily Average Time:
This was a little more complex. I expand the history_stat sensor to include data for a whole week, but dividing that by the number of days to get an average and then nicely formatting that again was something I didn’t know how to do with Jinga. My solution was to use a template MQTT sensor in Node-Red and write the function in JavaScript.
Javascript in Node-Red function node:
if (msg.data.old_state.state != msg.data.new_state.state) {
let num_days = 7;
// payload is hours, so convert to minutes
let raw_mins = msg.payload * 60;
// divide by days measured
raw_mins = raw_mins / num_days;
// the calculating
let h = Math.floor(raw_mins / 60);
let m = Math.round(raw_mins % 60);
let percent = Math.floor((msg.payload / (24 * num_days)) * 100);
// set topic
msg.topic = "variables/" + msg.topic;
// pretty format
msg.payload = `${h}h ${m}m / ${percent}%`;
return msg;
}
and then the weekly stats history sensor:
- platform: history_stats
name: Person1 Weekly Time Home Raw
entity_id: group.person1_device_trackers
state: 'home'
type: time
end: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
duration:
days: 7
- platform: mqtt
name: Person1 Weekly Stats
state_topic: "variables/sensor.person1_weekly_time_home_raw"
Note: these template and mqtt sensors are also excluded from the recorder component, as their state is only a measurement of another state, and as such changes all the time, with no useful reason to record.
Credit for the theme I used: