Count people that are home

Wih this it will show the names below the badges, because it is set in friendly_name (used as badge label). If you have a lot of names maybe is better to show in another sensor/a custom state card.

hass.states.set(‘sensor.people_home’, home_count, {
   ‘unit_of_measurement’: ‘people’,
   ‘friendly_name’: home_desc
})

right, thanks, i certainly will try that lateron, but for now it must be correct first just the way it is. Something is still not in order, the indentation is not as straight forward as Yaml i suppose.
do you have a suggestion for a checker?

could i filter from a separate group also? Ive joined the devices to be tracked into a group.family, and it might be simpler to have the original line for entity_id in hass.states.entity_ids('device_tracker') check in this group for entity_id’s with state ‘home’ ?

For syntax errors I just check the error log (it will show the incorrect line numer).
For logic errors I add logger.error(“message”) for debug, like here.
But if is the same as here should be ok.
Yes, you can check the group.family, not sure if is less or more code, I can check it ou later when I’ll be in my setup.

our posts crossed…

making progress, functionality seems to be working now.:

49

have to let it show friendly names below the badge, or indeed maybe a custom card.

do have a look for me please filtering from a group though, that seems to be more robust, and logical somehow, which is always easier to debug if necessary

btw, my phone is off for testing purposes, and still it shows Marijn IC and telefoon MHB… iCloud and HomeAssistant. Strange they’re not gone… been over an hour, so they should have been updated.

anyways,
Thanks!

for the sake of being able to see whats output, ive added the sensor to a badge. So don’t judge the layout yet please…

still ive tried to add the last change of state, halfway successfully. i now need to reformat that to show only H, M, S of the last state change. Any suggestion how to do that please? Here’s my current script and result in the frontend.

hass.states.set('sensor.count_people_home', home_count, {
    'unit_of_measurement': state.last_changed,
    'friendly_name':  home_desc

48

as a badge:

47

HI @mviezzer,
can i ask about your alarmclock.yaml. different thread maybe but same person :wink: or would etiquette require a new thread for this.

question short:
copied the alarmclock into a packages dir, and after first restart the alarmclock shows up fine in homepage.
when i move it (both of them) to a separate dedicated Tab (group/view ) the clock disappears, and the selectors showup???

Cheers,
Marius

Hi, I have the group filter and state last change done :grinning:
It’s in my repo… I’ll keep updated as improvments go on…
I went a little further and now you can set a group list to do the summary with different parameters. So I create a device group always on and will alert if anyone is offline.
If the state change yesterday it will show the date too.
Now I’m trying figure out the timezone…


summary

PS; About the alarm clock,I also have in a dedicated tab and working.I had a similar problem in other ocasiations: cache (do a force refresh) or yaml/script syntax (check the log).
Open a new thread or drop me a message.

1 Like

thats cool! your python looks much better than my effort…

copied it and somehow things don’t show up as they should.
Ive put the 3 sensors in a group and tab, and then only this shows up:

55

notice the summary sensor doesn’t do anything here.
If i take that out of the group, the group card remains the same, but this badge (the most left one) is shown in the homepage:

29

i did take out the input_select for developer mode. I have no other modes yet, so that would not have been functional,and it gave me several error messages.

Also took out a typo(?) in line 53 and 54: domnains

btw notice the 2 other badges. These are the template sensors of the alarm clock, which is in its own card. ill do another thread for that indeed,

Cheers,
Marius

just rechecked all and might have found it. would state-card-value_only be the culprit of the summary badge not showing? i don’t have that declared anywhere in the custom ui?

Cheers,
Marius

I have updated my script.
I think that addresses all your issues: there are some flags at the beginning, and if the entity do not exist will not throw error, so now it’s easier to anyone copy the file and start using, with minimun changes.

I also:
Add a summary of the alarm clock (similar to you)
The ‘in use’ is now also doing by group, and the group options to generate the summary are more generic.

summary

In debug mode:

summary_debug

wow,
will try this weekend.
Strangest thing is that the 2 issues (alarm and people count) seem to be related somehow. The alarmclock shows up in the frontend homepage, and when i move it to a separate page in a group, or use the People Home scripts, the alarm splits up in 2 separate inputs…
must have something to with the separate declaration of parts in the scripts or the package itself.

Thanks for developing, and thinking along. will try to be more specific after ive changed into your new script.

Cheers,
Marius

:+1:
After that if the problem persists post your config.

had to edit a bit, but cant find the reason for this error appearing in the log, neither can PythonLint… still HA complains:

Error executing script: list index out of range
Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/homeassistant/components/python_script.py", line 166, in execute
    exec(compiled.code, restricted_globals, local)
  File "summary.py", line 37, in <module>
  File "/usr/lib/python3.6/site-packages/RestrictedPython/Eval.py", line 35, in default_guarded_getitem
    return ob[index]
IndexError: list index out of range

check my summary.py please:

## https://github.com/maattdiy/home-assistant-config

## Resources:
## https://home-assistant.io/components/python_script/
## https://home-assistant.io/docs/configuration/state_object/

debug = False
show_badges = True
show_card = True

group_count = 0
group_desc = ""

summary = ""
idx = 0

##################################################
## Group count (people and devices)
##################################################

# Entities summary by group name
groups = ['group.family', 'group.audio', 'group.video', 'group.media_player' ]
groups_format = ['{} at home: {}', '{} in use: {}', '!{} offline: {}']
groups_filter = ['home', 'on|playing', 'off|not_home']
groups_badge = ['Home', 'In use', 'Alert']
groups_badge_pic = ['', '', 'bug']
groups_desc = ['Nobody in home', '', '']
groups_count = [0, 0, 0]

for group in groups:
    group_count = 0
    group_desc = ''

    for entity_id in hass.states.get(group).attributes['entity_id']:
        state = hass.states.get(entity_id)
        filter = groups_filter[idx]
        
        if (state.state in filter.split('|') or debug):
          dt = state.last_changed
          dt = dt + datetime.timedelta(hours=-2) # For time zone :( How to do native?
          time = '%02d:%02d' % (dt.hour, dt.minute)

          # If state changed in the past days show the date too
          if dt.date() < datetime.datetime.now().date():
              time = '{} {}'.format('%02d/%02d' % (dt.day, dt.month), time)

          group_count = group_count + 1
          group_desc = '{} {} ({}), '.format(group_desc, state.name, time)

    # Final format for this group
    if group_count > 0:
         group_desc = groups_format[idx].format(group_count, group_desc[:-2])
         groups_desc[idx] = group_desc
         groups_count[idx] = group_count

    idx = idx + 1

#hass.states.set('sensor.count_people_home', home_count, {
#    'unit_of_measurement': state.last_changed,
#    'friendly_name':  home_desc
#})

##################################################
## Badges updates
##################################################

idx = 0

if show_badges:
    for badge in groups_badge:
        if (badge != ''):
            entity_id = 'sensor.{}_badge'.format(badge.replace(' ', '').lower());
            hidden = False if (groups_count[idx] > 0 or debug) else True
            fname = groups_desc[idx] if debug else ' '
            picture = '/local/badges/{}.png'.format(groups_badge_pic[idx]) if (groups_badge_pic[idx] != '') else ''
            
            hass.states.set(entity_id, groups_count[idx], {
              'friendly_name': fname,
              'unit_of_measurement': badge, 
              'entity_picture': picture,
              'hidden': hidden
            })
            
        idx = idx + 1

##################################################
## Devices in use count
##################################################

domains = ['switch', 'media_player']
for domain in domains:
    for entity_id in hass.states.entity_ids(domain):
        show = False
        state = hass.states.get(entity_id)
        
        # Media players
        if (state.state == 'playing'):
            show = True
            
        # Switchs with icons
        if (state.state == 'on'):
            ## Only switchs with icons are relevants (ignore internal switchs). Find by tag "icon" in dictionary because "state.attributes.icon" didn't work
            if (str(state.attributes).find("'icon'")) >= 0:
                show = True
        
        if (show):
            if (inuse_desc.find(state.name + ', ') == -1):
                #logger.info("state.attributes = " + str(state.attributes))
                inuse_count = inuse_count + 1
                inuse_desc = inuse_desc + state.name + ', '

if inuse_count > 0:
    inuse_desc = str(inuse_count) + ' in use: ' + inuse_desc[:-2]
    summary = summary + '\n ' + inuse_desc

##################################################
## Alarm clock
##################################################

alarms_prefix = ['alarmclock_wd', 'alarmclock_we']
alarms_wfilter = ['1|2|3|4|5', '6|7']
alarms_desc = ''
idx = 0

for entity_id in alarms_prefix:
    state = hass.states.get('input_boolean.{}_enabled'.format(entity_id))
    if (not state is None):
        if (state.state == 'on'):
            # Show the alarm for the next day
            if (str(datetime.datetime.now().isoweekday()) in alarms_wfilter[idx].split('|')):
                state = hass.states.get('sensor.{}_time_template'.format(entity_id))
                alarms_desc = '{}{}, '.format(alarms_desc, state.state)
    idx = idx + 1

if (alarms_desc == ''):
    alarms_desc = '!Alarm clock is disabled'
else:
    alarms_desc = 'Alarm clock at ' + alarms_desc[:-2]

##################################################
## Profile/mode
##################################################

#state = hass.states.get('input_select.ha_mode')
#if (state.state != 'Normal'):
#    summary = summary + '\n ' + '* ' + state.state + ' profile is activated'
#    hass.states.set('sensor.profile_badge', '', {
#        'entity_picture':  '/local/profiles/{}.png'.format(state.state.lower()),
#        'friendly_name': ' ',
#        'unit_of_measurement': 'Mode'
#    })

##################################################
## Summary updates
##################################################
for group_desc in groups_desc:
    if (group_desc != ''):
        summary = '{}{}\n'.format(summary, group_desc)

summary = '{}\n{}\n{}'.format(summary, alarms_desc, profile_desc)

if show_card:
    hass.states.set('sensor.summary', summary, {
      'custom_ui_state_card': 'state-card-value_only'
    })
# People badge update
#hass.states.set('sensor.people_badge', group_count, {
#    'friendly_name': ' ',
#    'unit_of_measurement': 'Home',
#})

# In use badge update
#hass.states.set('sensor.inuse_badge', inuse_count, {
#    'friendly_name': ' ',
#    'unit_of_measurement': 'In use'
#})

# Summary sensors update
#hass.states.set('sensor.summary', summary, {
#    'custom_ui_state_card': 'state-card-value_only'
#})

took out some empty spaces in that line, and now the error shifts one up:

Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/homeassistant/components/python_script.py", line 166, in execute
    exec(compiled.code, restricted_globals, local)
  File "summary.py", line 36, in <module>
  File "/usr/lib/python3.6/site-packages/RestrictedPython/Eval.py", line 35, in default_guarded_getitem
    return ob[index]
IndexError: list index out of range

Each groups_* needs have the same number of elements (all 3 or all 4)…
For each one it wll create a separate summary…
For example:
groups = [‘group.family’, ‘group.devices_to_show_in_use’, ‘group.devices_to_show_offline’ ]
Or if you really want only 2 summaries (home and in use), use something like this:
groups = [‘group.family’, ‘group.devices_to_show_in_use’]
and remove the 3 element of groups_* below.

thank you! no more errors now. making progress but still some work to do and recheck where things go differently from the expected…
borrowed your Bug, kinda liked it :wink:

10

– edit

took out the older script section Devices in Use, i mistakenly left before and now the result is better. Still don’t get the Mode icon to show up, and cant find it in the developer section.

06

How did you do that? I read your Mode selector, and only see the developer mode being active. Maybe were over complicating things here? How come the Debug mode isn’t available in the mode selector? is that done some other way?
maybe because of the fact the part Scripts is missing in the profile module?
Cheers,
Marius

Hi!
Apologies in advance for my basic question, but I’m still trying to figure out what Mariusthvdb asked a few posts back: how do you display the sensor in the frontend?

I’ve added the original code as a python script in config/custom_components/sensor:

#count people that are home
home = 0
for entity_id in hass.states.entity_ids('device_tracker'):
    state = hass.states.get(entity_id)
    if state.state == 'home':
        home = home + 1

hass.states.set('sensor.people_home', home, {
    'unit_of_measurement': 'people',
    'friendly_name': 'People home'
})

And the following lines in my configuration.yaml

#sensors
  sensor:
#weather  
  - platform: yr
      name: Weather
#count people at home
    - platform: people_home
      name: Home

All this results in is my weather icon not showing up.
Do I declare the sensor in the wrong way? Or should the script be activated first (I can’t call it from ‘services’)?

Any help would be greatly appreciated!

HI!
from what I’ve learned here, is that the sensor.people_home is created on the go through the hass.states.set.
If it is, you should be able to find in the developers section <>, along with its state.

If yes, you can show it in a group.

if it isn’t there, you should get the script to run, since it apparently hasn’t yet. That too you can experiment with in the dev’s section: click services, select python_script, the right script (service) and Call Service.

if all went well, you should be able to see the sensor. If not the script itself isn’t correct (yet)

Hope this helps,
Marius

Your count people at home is indented by 2 spaces to many it should line up with the previous - platform statement.

Thank you for the quick replies!

I have removed the indents. This causes the weather icon to show up again.

Also, the script is moved to /python_scripts and that makes it visible in the developers section:

It’s also added to a group:

  home:
    name: People at home
    entities:
      - sensor.people_home

However, the sensor still doesn’t show up and also is not visible in the ‘states’ overview.

your sure the script actually ran? otherwise the sensor isn’t populated and thus not shown in the frontend.