Change settings in flake8 and black.
[python_utils.git] / smart_home / thermometers.py
1 #!/usr/bin/env python3
2
3 import logging
4 import urllib.request
5 from typing import Optional
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(self, location: str, *, convert_to_fahrenheit=False) -> Optional[float]:
25         record = self.thermometers.get(location, None)
26         if record is None:
27             logger.error(
28                 f'Location {location} is not known.  Valid locations are {self.thermometers.keys()}.'
29             )
30             return None
31         url = f'http://{record[0]}/~pi/{record[1]}'
32         logger.debug(f'Constructed URL: {url}')
33         try:
34             www = urllib.request.urlopen(url, timeout=3)
35             temp = www.read().decode('utf-8')
36             temp = float(temp)
37             if convert_to_fahrenheit:
38                 temp *= 9 / 5
39                 temp += 32.0
40                 temp = round(temp)
41         except Exception as e:
42             logger.exception(e)
43             logger.error(f'Failed to read temperature at URL: {url}')
44             temp = None
45         finally:
46             if www is not None:
47                 www.close()
48         return temp