hue/get-lights.py

68 lines
2.1 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
#
2020-05-07 16:13:45 +02:00
# Copyright 2019-2020, Mischa Peters <mischa AT high5 DOT nl>, High5!.
# Version 1.0 - 20191028
# Version 1.1 - 20191103 - added ['state']['on']
2020-05-07 16:13:45 +02:00
# Version 1.2 - 20200507 - added config file support
#
# Get all light ids and state
2019-11-02 10:28:38 +01:00
#
# For example:
2020-05-07 16:13:45 +02:00
# $ get-lights.py <bridge name>
2019-11-02 10:28:38 +01:00
#
# Follow the steps at the Hue Developer site to get the username/token
# https://developers.meethue.com/develop/get-started-2/
2019-11-01 16:07:08 +01:00
#
# Requires:
2019-11-01 16:55:25 +01:00
# - Python >3.6
#
import argparse
import ssl
import urllib.request
import json
2020-05-07 16:13:45 +02:00
import os
import configparser
2019-11-03 14:17:34 +01:00
parser = argparse.ArgumentParser(description="Get all light ids from Hue Bridge")
2020-05-07 16:13:45 +02:00
parser.add_argument("bridgename", type=str, help="Hue Bridge name in specified in hue.conf")
2019-12-27 15:46:43 +01:00
parser.add_argument("-i", "--id", type=int, help="light id#")
try:
args = parser.parse_args()
2020-05-07 16:13:45 +02:00
bridgename = args.bridgename
2019-12-27 15:46:43 +01:00
id = args.id
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')
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}/lights"
req = urllib.request.Request(url)
with urllib.request.urlopen(req, context=no_cert_check) as response:
content = response.read()
json_data = json.loads(content)
2019-12-27 15:46:43 +01:00
if not id:
print(f"{'ID':>3s} {'Name':<32s} {'State':<5s} Type")
print ("################################################################################")
for key in json_data:
if not json_data[key]['state']['reachable']:
continue
state = 'on' if json_data[key]['state']['on'] else 'off'
print(f"{key:>3s}: {json_data[key]['name']:<32s} {state:<5s} {json_data[key]['type']}")
else:
if json_data[str(id)]['state']['reachable']:
state = 'on' if json_data[str(id)]['state']['on'] else 'off'
print(state)
else:
print("unreachable")