Since this thing is on the innerwebs I suppose it should have a
[python_utils.git] / smart_home / thermometers.py
1 #!/usr/bin/env python3
2
3 # © Copyright 2021-2022, Scott Gasch
4
5 """Code involving querying various smart home thermometers."""
6
7 import logging
8 import urllib.request
9 from typing import Optional
10
11 logger = logging.getLogger()
12
13
14 class ThermometerRegistry(object):
15     """A registry of thermometer hosts / names and how to talk with them."""
16
17     def __init__(self):
18         self.thermometers = {
19             'house_outside': ('10.0.0.75', 'outside_temp'),
20             'house_inside_downstairs': ('10.0.0.75', 'inside_downstairs_temp'),
21             'house_inside_upstairs': ('10.0.0.75', 'inside_upstairs_temp'),
22             'house_computer_closet': ('10.0.0.75', 'computer_closet_temp'),
23             'house_crawlspace': ('10.0.0.75', 'crawlspace_temp'),
24             'cabin_outside': ('192.168.0.107', 'outside_temp'),
25             'cabin_inside': ('192.168.0.107', 'inside_temp'),
26             'cabin_crawlspace': ('192.168.0.107', 'crawlspace_temp'),
27             'cabin_hottub': ('192.168.0.107', 'hottub_temp'),
28         }
29
30     def read_temperature(self, location: str, *, convert_to_fahrenheit=False) -> Optional[float]:
31         record = self.thermometers.get(location, None)
32         if record is None:
33             logger.error(
34                 'Location %s is not known.  Valid locations are %s.',
35                 location,
36                 self.thermometers.keys(),
37             )
38             return None
39         url = f'http://{record[0]}/~pi/{record[1]}'
40         logger.debug('Constructed URL: %s', url)
41         try:
42             www = urllib.request.urlopen(url, timeout=3)
43             temp = www.read().decode('utf-8')
44             temp = float(temp)
45             if convert_to_fahrenheit:
46                 temp *= 9 / 5
47                 temp += 32.0
48                 temp = round(temp)
49         except Exception as e:
50             logger.exception(e)
51             logger.error('Failed to read temperature at URL: %s', url)
52             temp = None
53         finally:
54             if www is not None:
55                 www.close()
56         return temp