hue/get-id.py

61 lines
1.8 KiB
Python
Raw Normal View History

2019-11-03 16:55:07 +01:00
#!/usr/bin/env python3
#
2020-05-07 16:13:45 +02:00
# Copyright 2019-2020, Mischa Peters <mischa AT high5 DOT nl>, High5!.
2019-11-03 16:55:07 +01:00
# Version 1.0 - 20191103
2020-05-07 16:13:45 +02:00
# Version 1.1 - 20200507 - added config file support
2019-11-03 16:55:07 +01:00
#
# Collect all information of given id
#
# For example:
2020-05-07 16:13:45 +02:00
# $ get-id.py <bridge name> -t sensors -i 6
2019-11-03 16:55:07 +01:00
#
# Requires:
# - Python 3.x
#
import argparse
import ssl
import urllib.request
import json
2020-05-07 16:13:45 +02:00
import os
import configparser
2019-11-03 16:55:07 +01:00
parser = argparse.ArgumentParser(description="Get id information")
2020-05-07 16:13:45 +02:00
parser.add_argument("bridgename", type=str, help="Hue Bridge name in specified in hue.conf")
2019-11-03 16:55:07 +01:00
parser.add_argument("-i", "--id", type=int, default='1', help="id#")
2019-11-06 22:18:42 +01:00
parser.add_argument("-t", "--type", type=str, default='lights', help="lights|sensors|groups|rules")
2019-11-03 16:55:07 +01:00
parser.add_argument("-v", "--verbose", action='store_true', help="verbose")
try:
args = parser.parse_args()
2020-05-07 16:13:45 +02:00
bridgename = args.bridgename
2019-11-03 16:55:07 +01:00
id = args.id
type = args.type
verbose = args.verbose
except argparse.ArgumentError as e:
print(str(e))
2020-05-07 16:13:45 +02:00
config_files = ['./hue.conf', './.hue.conf', '/etc/hue.conf', '/etc/hue/hue.conf', os.path.expanduser('~/.hue.conf'), os.path.expanduser('~/hue.conf')]
config = configparser.RawConfigParser()
config.read(config_files)
bridge = config.get(bridgename, 'ip')
token = config.get(bridgename, 'token')
2019-11-03 16:55:07 +01:00
no_cert_check = ssl.create_default_context()
no_cert_check.check_hostname=False
no_cert_check.verify_mode=ssl.CERT_NONE
url = f"https://{bridge}/api/{token}/{type}/{id}"
req = urllib.request.Request(url)
with urllib.request.urlopen(req, context=no_cert_check) as response:
content = response.read()
json_data = json.loads(content)
if not 'state' in json_data:
print(f"{type[:-1]} id {id} doesn't exist")
else:
if verbose: print("json dump:")
if verbose: print(json.dumps(json_data, indent=4, sort_keys=True))
if verbose: print("state")
print(json_data['state'])