Small bugfixes; also, add a new machine to the remote executor pool.
[python_utils.git] / cached / weather_forecast.py
index 6e2f5f9ca0ffcc9eae3d2c7d6615549fb222a0db..d1e754025eeaadeee84cfc12b38a1c53e8a547ee 100644 (file)
@@ -4,11 +4,13 @@ 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
@@ -27,7 +29,7 @@ cfg = config.add_commandline_args(
 cfg.add_argument(
     '--weather_forecast_cachefile',
     type=str,
-    default=f'{os.environ["HOME"]}/.weather_forecast_cache',
+    default=f'{os.environ["HOME"]}/cache/.weather_forecast_cache',
     metavar='FILENAME',
     help='File in which to cache weather data'
 )
@@ -49,7 +51,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
@@ -59,15 +61,23 @@ 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 = 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()
+        www = None
+        try:
+            www = urllib.request.urlopen(
+                "http://10.0.0.75/~pi/outside_temp",
+                timeout=2,
+            )
+            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)
+        except Exception:
+            logger.warning('Timed out reading 10.0.0.75/~pi/outside_temp?!')
+            current_temp = None
+        finally:
+            if www is not None:
+                www.close()
 
         # Get a weather forecast for Bellevue.
         www = urllib.request.urlopen(
@@ -102,7 +112,7 @@ class CachedDetailedWeatherForecast(object):
             sunrise = s['sunrise']
             sunset = s['sunset']
 
-            if dt.date() == now.date() and not said_temp:
+            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
@@ -121,7 +131,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(),
@@ -132,7 +143,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(
@@ -140,3 +152,4 @@ class CachedDetailedWeatherForecast(object):
                 wf,
                 pickle.HIGHEST_PROTOCOL,
             )
+        return True