More type annotations.
[python_utils.git] / cached / weather_forecast.py
index ce4725d64a6c43699ab702b85d60d1f070366cf5..b34393832dec04120548aa08fb6822366cfc6ff6 100644 (file)
@@ -3,11 +3,14 @@
 from dataclasses import dataclass
 import datetime
 import logging
+import os
+from typing import Any
 import urllib.request
 
 import astral  # type: ignore
 from astral.sun import sun  # type: ignore
 from bs4 import BeautifulSoup  # type: ignore
+from overrides import overrides
 import pytz
 
 import argparse_utils
@@ -16,6 +19,8 @@ import datetime_utils
 import dateparse.dateparse_utils as dp
 import persistent
 import text_utils
+import smart_home.thermometers as temps
+
 
 logger = logging.getLogger(__name__)
 
@@ -26,7 +31,7 @@ cfg = config.add_commandline_args(
 cfg.add_argument(
     '--weather_forecast_cachefile',
     type=str,
-    default='/home/scott/.weather_forecast_cache',
+    default=f'{os.environ["HOME"]}/cache/.weather_forecast_cache',
     metavar='FILENAME',
     help='File in which to cache weather data'
 )
@@ -48,7 +53,7 @@ class WeatherForecast:
 
 
 @persistent.persistent_autoloaded_singleton()
-class CachedDetailedWeatherForecast(object):
+class CachedDetailedWeatherForecast(persistent.Persistent):
     def __init__(self, forecasts = None):
         if forecasts is not None:
             self.forecasts = forecasts
@@ -58,15 +63,9 @@ class CachedDetailedWeatherForecast(object):
         self.forecasts = {}
 
         # Ask the raspberry pi about the outside temperature.
-        www = urllib.request.urlopen(
-            "http://10.0.0.75/~pi/outside_temp"
+        current_temp = temps.ThermometerRegistry().read_temperature(
+            'house_outside', convert_to_fahrenheit=True
         )
-        current_temp = www.read().decode("utf-8")
-        current_temp = float(current_temp)
-        current_temp *= (9/5)
-        current_temp += 32.0
-        current_temp = round(current_temp)
-        www.close()
 
         # Get a weather forecast for Bellevue.
         www = urllib.request.urlopen(
@@ -79,6 +78,7 @@ class CachedDetailedWeatherForecast(object):
         forecast = soup.find(id='detailed-forecast-body')
         parser = dp.DateParser()
 
+        said_temp = False
         last_dt = now
         dt = now
         for (day, txt) in zip(
@@ -100,8 +100,10 @@ class CachedDetailedWeatherForecast(object):
             sunrise = s['sunrise']
             sunset = s['sunset']
 
-            if dt.date == now.date:
-                blurb = f'{day.get_text()}: The current outside tempterature is {current_temp}.  ' + txt.get_text()
+            if dt.date() == now.date() and not said_temp and current_temp is not None:
+                blurb = f'{day.get_text()}: The current outside tempterature is {current_temp}. '
+                blurb += txt.get_text()
+                said_temp = True
             else:
                 blurb = f'{day.get_text()}: {txt.get_text()}'
             blurb = text_utils.wrap_string(blurb, 80)
@@ -117,7 +119,8 @@ class CachedDetailedWeatherForecast(object):
                 )
 
     @classmethod
-    def load(cls):
+    @overrides
+    def load(cls) -> Any:
         if persistent.was_file_written_within_n_seconds(
                 config.config['weather_forecast_cachefile'],
                 config.config['weather_forecast_stalest_acceptable'].total_seconds(),
@@ -128,7 +131,8 @@ class CachedDetailedWeatherForecast(object):
                 return cls(weather_data)
         return None
 
-    def save(self):
+    @overrides
+    def save(self) -> bool:
         import pickle
         with open(config.config['weather_forecast_cachefile'], 'wb') as wf:
             pickle.dump(
@@ -136,3 +140,4 @@ class CachedDetailedWeatherForecast(object):
                 wf,
                 pickle.HIGHEST_PROTOCOL,
             )
+        return True