Blob


1 #!/usr/bin/env python3
2 #
3 # Copyright 2019-2020, Mischa Peters <mischa AT high5 DOT nl>, High5!.
4 # Version 1.0 - 20191028
5 # Version 1.1 - 20191103 - added ['state']['on']
6 # Version 1.2 - 20200507 - added config file support
7 #
8 # Get all light ids and state
9 #
10 # For example:
11 # $ get-lights.py <bridge name>
12 #
13 # Follow the steps at the Hue Developer site to get the username/token
14 # https://developers.meethue.com/develop/get-started-2/
15 #
16 # Requires:
17 # - Python >3.6
18 #
19 import argparse
20 import ssl
21 import urllib.request
22 import json
23 import os
24 import configparser
26 parser = argparse.ArgumentParser(description="Get all light ids from Hue Bridge")
27 parser.add_argument("bridgename", type=str, help="Hue Bridge name in specified in hue.conf")
28 parser.add_argument("-i", "--id", type=int, help="light id#")
30 try:
31 args = parser.parse_args()
32 bridgename = args.bridgename
33 id = args.id
35 except argparse.ArgumentError as e:
36 print(str(e))
38 config_files = ['./hue.conf', './.hue.conf', '/etc/hue.conf', '/etc/hue/hue.conf', os.path.expanduser('~/.hue.conf'), os.path.expanduser('~/hue.conf')]
39 config = configparser.RawConfigParser()
40 config.read(config_files)
41 bridge = config.get(bridgename, 'ip')
42 token = config.get(bridgename, 'token')
44 no_cert_check = ssl.create_default_context()
45 no_cert_check.check_hostname=False
46 no_cert_check.verify_mode=ssl.CERT_NONE
48 url = f"https://{bridge}/api/{token}/lights"
49 req = urllib.request.Request(url)
50 with urllib.request.urlopen(req, context=no_cert_check) as response:
51 content = response.read()
52 json_data = json.loads(content)
54 if not id:
55 print(f"{'ID':>3s} {'Name':<32s} {'State':<5s} Type")
56 print ("################################################################################")
57 for key in json_data:
58 if not json_data[key]['state']['reachable']:
59 continue
60 state = 'on' if json_data[key]['state']['on'] else 'off'
61 print(f"{key:>3s}: {json_data[key]['name']:<32s} {state:<5s} {json_data[key]['type']}")
62 else:
63 if json_data[str(id)]['state']['reachable']:
64 state = 'on' if json_data[str(id)]['state']['on'] else 'off'
65 print(state)
66 else:
67 print("unreachable")