hue/get-sensors.py

95 lines
3.4 KiB
Python
Executable File

#!/usr/bin/env python3
#
# Copyright 2019-2020, Mischa Peters <mischa AT high5 DOT nl>, High5!.
# Version 1.0 - 20191028
# Version 1.1 - 20191106 - added battery status
# Version 1.2 - 20200507 - added config file support
# Version 1.3 - 20200509 - added dimmer switch
#
# Get all sensor IDs ZZLSwitch, ZLLPresence (+ ZLLLightLevel and ZLLTemperature)
# grouped by ZZLSwitch and ZLLPresence name
#
# For example:
# $ get-sensors.py <bridge name>
#
# Follow the steps at the Hue Developer site to get the username/token
# https://developers.meethue.com/develop/get-started-2/
#
# Requires:
# - Python >3.6
#
import argparse
import ssl
import urllib.request
import json
import re
import collections
import os
import configparser
parser = argparse.ArgumentParser(description="Get all sensor ids from Hue Bridge")
parser.add_argument("bridgename", type=str, help="Hue Bridge name in specified in hue.conf")
parser.add_argument("-b", "--battery", type=int, help="battery check only, threshold, default 20")
parser.add_argument("-v", "--verbose", action='store_true', help="verbose")
try:
args = parser.parse_args()
bridgename = args.bridgename
battery = args.battery
verbose = args.verbose
except argparse.ArgumentError as e:
print(str(e))
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}/sensors"
req = urllib.request.Request(url)
with urllib.request.urlopen(req, context=no_cert_check) as response:
content = response.read()
json_data = json.loads(content)
p = re.compile("([a-fA-F0-9]{2}:?){8}")
sensors = collections.defaultdict(list);
for key in json_data:
if "uniqueid" in json_data[key]:
if p.search(json_data[key]['uniqueid']):
if json_data[key]['type'] == 'ZLLPresence':
sensors[json_data[key]['uniqueid'][:-8]].insert(0, key)
elif json_data[key]['type'] == 'ZGPSwitch':
# Don't add ZGPSwitch, doesn't have a battery component
continue
else:
sensors[json_data[key]['uniqueid'][:-8]].append(key)
for key in sensors:
for i in sensors[key]:
if not battery:
if json_data.get(i)['type'] == 'ZLLSwitch':
print(f"{json_data.get(i)['name']:<32s} ({json_data.get(i)['config']['battery']}%)")
print(f"{i:>5s}: {json_data.get(i)['productname']}")
if json_data.get(i)['type'] == 'ZLLPresence':
print(f"{json_data.get(i)['name']:<32s} ({json_data.get(i)['config']['battery']}%)")
print(f"{i:>5s}: {json_data.get(i)['productname']}")
if json_data.get(i)['type'] == 'ZLLLightLevel':
print(f"{i:>5s}: {json_data.get(i)['productname']}")
if json_data.get(i)['type'] == 'ZLLTemperature':
print(f"{i:>5s}: {json_data.get(i)['productname']}")
else:
if not "battery" in json_data.get(i)['config']:
print(f"Sensor without battery property found: {i}")
print(json.dumps(json_data.get(i), indent=4, sort_keys=True))
quit()
if int(json_data.get(i)['config']['battery']) < battery:
if json_data.get(i)['type'] == 'ZLLPresence':
print(f"{json_data.get(i)['name']:<32s} battery level {json_data.get(i)['config']['battery']}%")