Blob


1 #!/usr/bin/env python3
2 #
3 # Copyright 2019-2020, Mischa Peters <mischa AT high5 DOT nl>, High5!.
4 # Version 1.0 - 20191103
5 # Version 1.1 - 20200507 - added config file support
6 #
7 # Get temperaure from all sensors
8 #
9 # For exmaple:
10 # $ temperature.py <bridge name>
11 #
12 # Requires:
13 # - Python 3.x
14 #
15 import argparse
16 import ssl
17 import urllib.request
18 import json
19 import re
20 import collections
21 import math
22 import os
23 import configparser
25 parser = argparse.ArgumentParser(description="Get temperature from Hue Bridge")
26 parser.add_argument("bridgename", type=str, help="Hue Bridge name in specified in hue.conf")
27 parser.add_argument("-v", "--verbose", action='store_true', help="verbose")
28 parser.add_argument("-d", "--debug", action='store_true', help="debug")
30 try:
31 args = parser.parse_args()
32 bridgename = args.bridgename
33 verbose = args.verbose
34 debug = args.debug
36 except argparse.ArgumentError as e:
37 print(str(e))
39 config_files = ['./hue.conf', './.hue.conf', '/etc/hue.conf', '/etc/hue/hue.conf', os.path.expanduser('~/.hue.conf'), os.path.expanduser('~/hue.conf')]
40 config = configparser.RawConfigParser()
41 config.read(config_files)
42 bridge = config.get(bridgename, 'ip')
43 token = config.get(bridgename, 'token')
45 no_cert_check = ssl.create_default_context()
46 no_cert_check.check_hostname=False
47 no_cert_check.verify_mode=ssl.CERT_NONE
49 url = f"https://{bridge}/api/{token}/sensors"
50 req = urllib.request.Request(url)
51 with urllib.request.urlopen(req, context=no_cert_check) as response:
52 content = response.read()
53 json_data = json.loads(content)
55 p = re.compile("([a-fA-F0-9]{2}:?){8}")
56 sensors = collections.defaultdict(list);
58 for key in json_data:
59 if "uniqueid" in json_data[key]:
60 if p.search(json_data[key]['uniqueid']):
61 if json_data[key]['type'] == 'ZLLPresence':
62 sensors[json_data[key]['uniqueid'][:-8]].insert(0, key)
63 else:
64 sensors[json_data[key]['uniqueid'][:-8]].append(key)
66 for key in sensors:
67 for i in sensors[key]:
68 if json_data.get(i)['type'] == 'ZLLPresence':
69 name = json_data.get(i)['name']
70 if json_data.get(i)['type'] == 'ZLLTemperature':
71 updated = json_data.get(i)['state']['lastupdated'][-8:]
72 if json_data.get(i)['state']['temperature']:
73 temperature = round((json_data.get(i)['state']['temperature'] / 100), 1)
74 else:
75 temperature = 0
76 if verbose:
77 print (f"{name:<32s} - {temperature:>4}C (updated: {updated} UTC)")
78 elif debug:
79 print (f"{name:<32s} - {temperature:>4}C (updated: {updated} UTC - sensor: {i})")
80 else:
81 print (f"{name:<32s} - {temperature:>4}C")