From 5f75cf834725ac26b289cc5f157af0cb71cd5f0e Mon Sep 17 00:00:00 2001 From: Scott Date: Thu, 6 Jan 2022 12:13:34 -0800 Subject: A bunch of changes... --- smart_home/thermometers.py | 50 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 smart_home/thermometers.py (limited to 'smart_home/thermometers.py') diff --git a/smart_home/thermometers.py b/smart_home/thermometers.py new file mode 100644 index 0000000..fe5eed1 --- /dev/null +++ b/smart_home/thermometers.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 + +import logging +from typing import Optional +import urllib.request + +logger = logging.getLogger() + + +class ThermometerRegistry(object): + def __init__(self): + self.thermometers = { + 'house_outside': ('10.0.0.75', 'outside_temp'), + 'house_inside_downstairs': ('10.0.0.75', 'inside_downstairs_temp'), + 'house_inside_upstairs': ('10.0.0.75', 'inside_upstairs_temp'), + 'house_computer_closet': ('10.0.0.75', 'computer_closet_temp'), + 'house_crawlspace': ('10.0.0.75', 'crawlspace_temp'), + 'cabin_outside': ('192.168.0.107', 'outside_temp'), + 'cabin_inside': ('192.168.0.107', 'inside_temp'), + 'cabin_crawlspace': ('192.168.0.107', 'crawlspace_temp'), + 'cabin_hottub': ('192.168.0.107', 'hottub_temp'), + } + + def read_temperature( + self, location: str, *, convert_to_fahrenheit=False + ) -> Optional[float]: + record = self.thermometers.get(location, None) + if record is None: + logger.error( + f'Location {location} is not known. Valid locations are {self.thermometers.keys()}.' + ) + return None + url = f'http://{record[0]}/~pi/{record[1]}' + logger.debug(f'Constructed URL: {url}') + try: + www = urllib.request.urlopen(url, timeout=3) + temp = www.read().decode('utf-8') + temp = float(temp) + if convert_to_fahrenheit: + temp *= (9/5) + temp += 32.0 + temp = round(temp) + except Exception as e: + logger.exception(e) + logger.error(f'Failed to read temperature at URL: {url}') + temp = None + finally: + if www is not None: + www.close() + return temp -- cgit v1.3