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:
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.
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.