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