Query HASS and get all "on" lights and switches?

What I’m looking to do is create a script that I can run which will query all of my lights and switches to see what is turned on. It doesn’t have to be a script, but I know I can accomplish this using python and the API. What I have below works in listing all entities of a certain group and their states in a basic form. What I’d like to do ideally is click a button and get a response of all devices that are currently turned “on” - I’m not sure if there is a better way to do this using the new webhooks or if there is something built in that I’m missing? Any ideas would be helpful, thanks!

from requests import get
from pprint import pprint
from datetime import datetime
from datetime import timedelta
import credentials

timestamp = str(datetime.now())

VAR6 = '/api/states/group.all_switches'

url = credentials.api_url+VAR6
headers = {'x-ha-access': credentials.api_password,
           'content-type': 'application/json'}

response = get(url, headers=headers).json()

for value in response['attributes']['entity_id']:
    url =  credentials.api_url+"/api/states/"+str(value)
    response = get(url, headers=headers).json()
    print(value+": "+response['state'])

There is much better automation code around here on the forum than mine, probably by pedro or pnbruckner, but here is an example of what I use for my door & window sensors - triggered by a changing the input_boolean.security_notification:

- alias: Detailed Security Notification
  trigger:
    platform: state
    entity_id: input_boolean.security_notification
    from: 'off'
    to: 'on'
  action:  
    - service: notify.mypushbullet
      data_template:
        title: "Open are:"
        message: >-
          {%- set entities = [states.binary_sensor.back_deadbolt, states.binary_sensor.back_door, states.binary_sensor.balcony_deadbolt, states.binary_sensor.balcony_door, states.binary_sensor.balcony_window, states.binary_sensor.bedroom_kim, states.binary_sensor.bedroom_werner, states.binary_sensor.downstairs_deadbolt, states.binary_sensor.downstairs_door, states.binary_sensor.downstairs_window, states.binary_sensor.front_deadbolt, states.binary_sensor.front_door, states.binary_sensor.kitchen_door, states.binary_sensor.kitchen_window, states.binary_sensor.laundry_room_door, states.binary_sensor.living_room_motion, states.binary_sensor.living_room_window, states.binary_sensor.master_bath_window, states.binary_sensor.office_window, states.sensor.gardengate_rev ] -%}
          {%- for entity in entities -%}
            {%- if entity.state == 'on' %}
              {{ entity.name }}
            {%- endif %}
          {%- endfor -%}

Or take a look here:

Thanks! I’m not very well versed in the way of writing the templates so this helps a bunch

This is what I figured out, I wish I could state a group of devices and it would list out all of the entities instead of me listing each one (that way the automation is dynamic and I wouldn’t have to think about it again) but this works for now. It also tells you how long the light/switch has been on for which I think is greatly helpful.

- alias: Info
  trigger:
  - platform: webhook
    webhook_id: info
  action:
  - service: notify.pushover
    data_template:
      title: "Currently On:"
      message: >-
        {%- set entities = [states.switch.entryway_switch, states.switch.front_porch_switch, states.switch.shower_light_switch, states.switch.bathroom_fan_switch, states.switch.downstairs_bathroom_fan_switch, states.switch.upstairs_bathroom_light_switch, states.switch.kitchen_overhead, states.switch.downstairs_bathroom_light_switch, states.switch.glass_door, states.switch.hot_water, states.switch.twinkle, states.light.bedroom_1, states.light.bedroom_2, states.light.big_lamp, states.light.cabinets, states.light.desk_lamp, states.light.dresser, states.light.dining_room_dimmer, states.light.guest_room_lamp, states.light.holiday_lights, states.light.nightstand, states.light.sink, states.light.small_lamp, states.light.wall] -%}
        {%- for entity in entities -%}
          {%- if entity.state == 'on' %}
        {{ entity.name }} {{ ( now().timestamp() - entity.last_changed.timestamp() ) | timestamp_custom("%H:%M:%S", 0) }}
          {%- endif %}
        {%- endfor -%}

I’ve seen ways where groups (e.g. group.kitchen_lights) or even domains (e.g. lights) are used - I just can’t find an example at the moment.

Maybe you need to use google to search the forum with an entry like
site:community.home-assistant.io
in the search field

Having the automation use a group of entities is more versatile than listing the entities directly within the automation (i.e. “hard-coding” them in the automation). However, both suffer the same drawback: when creating a new entity, you have to remember to add it (to the group or the automation’s list).

Arguably, when creating a new entity, you might stand a better chance of remembering to include it in one or more important groups than in a long-forgotten automation. Maybe.

Ideally, you’d be able to use a filter to select entities by component and even device_class. For example, get a collection of all binary_sensors whose type/class is door. This is dynamic; it finds all existing entities matching your criteria. I’m not a Home Assistant expert but so far I’ve not seen such a thing in YAML or Jinja. Perhaps it’s possible with AppDaemon (just guessing; I have not tried it).

Perhaps the concept of a filter ought to be added to the Feature Requests.

Here’s an example of using a group:

And here’s the one I was actually looking for, i.e. one base on components:

1 Like