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