Home Information - Your home, your data, organized.
Python
Fixed bug with min/max temp by better factoring into WeatherStats. (#177)
Tony C41570581a1eb
diff --git a/src/hi/apps/console/console_side.py b/src/hi/apps/console/console_side.pyindex 674966c6..f1255fe2 100644--- a/src/hi/apps/console/console_side.py+++ b/src/hi/apps/console/console_side.py@@ -7,9 +7,10 @@ from .console_mixins import ConsoleMixinclass ConsoleSideHelper( ConsoleMixin, SecurityMixin, WeatherMixin ):def get_side_template_name_and_context( self, request, *args, **kwargs ):+ weather_manager = self.weather_manager()context = {- 'weather_overview_data': self.weather_manager().get_weather_overview_data(),- 'weather_alert_list': self.weather_manager().get_weather_alerts(),+ 'weather_overview_data': weather_manager.get_weather_overview_data(),+ 'weather_alert_list': weather_manager.get_weather_alerts(),'security_status_data': self.security_manager().get_security_status_data(),'camera_control_display_list': self.console_manager().get_camera_control_display_list(),}diff --git a/src/hi/apps/weather/daily_weather_tracker.py b/src/hi/apps/weather/daily_weather_tracker.pyindex 17ec9296..2095606f 100644--- a/src/hi/apps/weather/daily_weather_tracker.py+++ b/src/hi/apps/weather/daily_weather_tracker.py@@ -21,14 +21,21 @@ from typing import Optional, Tuple, Dict, Anyimport hi.apps.common.datetimeproxy as datetimeproxyfrom django.core.cache import cache-from django.utils import timezone-from hi.apps.weather.transient_models import NumericDataPoint, DataPointSource, Station, WeatherConditionsData+from hi.apps.common.singleton import Singleton+from hi.apps.console.console_helper import ConsoleSettingsHelper+from hi.apps.weather.transient_models import (+ NumericDataPoint,+ DataPointSource,+ Station,+ WeatherConditionsData,+ WeatherStats,+)from hi.units import UnitQuantitylogger = logging.getLogger(__name__)-class DailyWeatherTracker:+class DailyWeatherTracker(Singleton):"""Tracks daily weather statistics for fallback values.@@ -52,15 +59,7 @@ class DailyWeatherTracker:# Field namesFIELD_TEMPERATURE = 'temperature'- def __init__(self, user_timezone=None):- """- Initialize the daily weather tracker.-- Args:- user_timezone: Timezone for day boundaries (defaults to Django's TIME_ZONE)- """- self._user_timezone = user_timezone or timezone.get_current_timezone()-+ def __init_singleton__(self):self._fallback_source = DataPointSource(id="daily_weather_tracker",label="Daily Weather Tracker",@@ -104,41 +103,10 @@ class DailyWeatherTracker:# if weather_conditions_data.windspeed:# self._record_wind_speed(weather_conditions_data.windspeed, location_key)- def populate_daily_fallbacks( self,- weather_conditions_data : WeatherConditionsData,- location_key : str = "default") -> None:- """- Populate missing daily weather data with fallback values from tracking.-- Currently supports:- - temperature_min_today / temperature_max_today-- Args:- weather_conditions_data: Weather conditions to populate with fallbacks- location_key: Unique identifier for the location- """- try:- # Populate today's temperature min/max if not already provided by APIs- if ( not weather_conditions_data.temperature_min_today- or not weather_conditions_data.temperature_max_today ):- min_temp, max_temp = self.get_temperature_min_max_today(location_key)-- if min_temp and not weather_conditions_data.temperature_min_today:- weather_conditions_data.temperature_min_today = min_temp-- if max_temp and not weather_conditions_data.temperature_max_today:- weather_conditions_data.temperature_max_today = max_temp-- # Future: Add other fallback population here- # self._populate_humidity_fallbacks(weather_conditions_data, location_key)- # self._populate_wind_fallbacks(weather_conditions_data, location_key)- except Exception as e:- logger.exception(f"Error in populate_daily_fallbacks for location {location_key}: {e}")- # Don't re-raise - this should never break the caller-def get_temperature_min_max_today(self,- location_key: str = "default") -> Tuple[Optional[NumericDataPoint], Optional[NumericDataPoint]]:+ location_key: str = "default"+ ) -> Tuple[Optional[NumericDataPoint], Optional[NumericDataPoint]]:"""Get today's minimum and maximum temperatures.@@ -151,6 +119,7 @@ class DailyWeatherTracker:"""try:field_stats = self._get_field_stats_today(location_key, self.FIELD_TEMPERATURE)+ logger.debug( f'GET field stats [today] = {field_stats}' )min_data = field_stats.get(self.STAT_MIN)max_data = field_stats.get(self.STAT_MAX)@@ -186,6 +155,18 @@ class DailyWeatherTracker:except Exception as e:logger.exception(f"Error getting today's temperature min/max: {e}")return None, None++ def get_weather_stats_today(self, location_key: str = "default") -> WeatherStats:+ try:+ min_temp, max_temp = self.get_temperature_min_max_today(location_key)+ return WeatherStats(+ temperature_min = min_temp,+ temperature_max = max_temp,+ )++ except Exception as e:+ logger.exception(f"Error getting weather stats: {e}")+ return WeatherStats()def _record_field_value( self,location_key : str,@@ -207,11 +188,11 @@ class DailyWeatherTracker:"""try:# Get current date in local timezone- now_local = datetimeproxy.now().astimezone(self._user_timezone)- date_key = now_local.strftime('%Y-%m-%d')+ date_key = self._get_date_key_today()# Get current field statisticsfield_stats = self._get_field_stats(location_key, date_key, field_name)+ logger.debug( f'Start field stats [value={value}] = {field_stats}' )# Update statisticsupdated = False@@ -244,7 +225,7 @@ class DailyWeatherTracker:'last_updated': timestamp.isoformat()}updated = True-+if self.STAT_COUNT in track_stats:count_data = field_stats.get(self.STAT_COUNT, {'value': 0})field_stats[self.STAT_COUNT] = {@@ -253,6 +234,8 @@ class DailyWeatherTracker:}updated = True+ logger.debug( f'End field stats [updated={updated}] = {field_stats}' )+# Store updated statistics if changedif updated:self._store_field_stats(location_key, date_key, field_name, field_stats)@@ -271,6 +254,8 @@ class DailyWeatherTracker:"""Get field statistics from cache."""cache_key = self._get_cache_key(location_key, date_key, field_name)stats_json = cache.get(cache_key)++ logger.debug( f'Retrieve field stats [key={cache_key}] - {stats_json}' )if stats_json:try:@@ -282,8 +267,7 @@ class DailyWeatherTracker:def _get_field_stats_today(self, location_key: str, field_name: str) -> Dict[str, Any]:"""Get today's field statistics."""- today_local = datetimeproxy.now().astimezone(self._user_timezone)- date_key = today_local.strftime('%Y-%m-%d')+ date_key = self._get_date_key_today()return self._get_field_stats(location_key, date_key, field_name)def _store_field_stats( self,@@ -294,9 +278,9 @@ class DailyWeatherTracker:"""Store field statistics to cache."""cache_key = self._get_cache_key(location_key, date_key, field_name)stats_json = json.dumps(stats)- success = cache.set(cache_key, stats_json, timeout=self.CACHE_TIMEOUT_SECONDS)- if not success:- logger.warning(f"Cache set failed for {field_name} stats on {date_key}")+ logger.debug( f'Store field stats [key={cache_key}] - {stats_json}' )+ cache.set(cache_key, stats_json, timeout=self.CACHE_TIMEOUT_SECONDS)+ returndef clear_today(self, location_key: str = "default", field_name: Optional[str] = None) -> None:"""@@ -306,13 +290,11 @@ class DailyWeatherTracker:location_key: Unique identifier for the locationfield_name: Specific field to clear, or None to clear all"""- today_local = datetimeproxy.now().astimezone(self._user_timezone)- date_key = today_local.strftime('%Y-%m-%d')-if field_name:+ date_key = self._get_date_key_today()cache_key = self._get_cache_key(location_key, date_key, field_name)cache.delete(cache_key)- logger.info(f"Cleared today's {field_name} data for {location_key}")+ logger.debug(f"Cleared today's {field_name} data for {location_key}")else:# Clear all fields - would need to iterate through known fields# For now, just clear temperature since that's what we implement@@ -325,12 +307,12 @@ class DailyWeatherTracker:Returns:Dict with field statistics or empty dict if no data"""- today_local = datetimeproxy.now().astimezone(self._user_timezone)- date_key = today_local.strftime('%Y-%m-%d')+ tz_name = ConsoleSettingsHelper().get_tz_name()+ date_key = self._get_date_key_today(tz_name)summary = {'date': date_key,- 'timezone': str(self._user_timezone),+ 'timezone': tz_name,'fields': {}}@@ -345,6 +327,12 @@ class DailyWeatherTracker:return summary+ def _get_date_key_today(self, tz_name: str = None) -> str:+ if not tz_name:+ tz_name = ConsoleSettingsHelper().get_tz_name()+ now_local = datetimeproxy.now(tz_name)+ return now_local.strftime('%Y-%m-%d')+def _get_cache_key(self, location_key: str, date_key: str, field_name: str) -> str:"""Generate cache key for field statistics.diff --git a/src/hi/apps/weather/templates/weather/modals/conditions_details.html b/src/hi/apps/weather/templates/weather/modals/conditions_details.htmlindex a3bb9158..9f8fddf2 100644--- a/src/hi/apps/weather/templates/weather/modals/conditions_details.html+++ b/src/hi/apps/weather/templates/weather/modals/conditions_details.html@@ -11,8 +11,8 @@ Current Conditions<div>{{ weather_conditions_data.description_short.value }}</div>{% endif %}-{% include "weather/panes/conditions.html" with conditions=weather_conditions_data %}-{% include "weather/panes/conditions_extended.html" with conditions=weather_conditions_data %}+{% include "weather/panes/conditions.html" with conditions=weather_conditions_data weather_stats=weather_stats %}+{% include "weather/panes/conditions_extended.html" with conditions=weather_conditions_data weather_stats=weather_stats %}{% with weather_conditions_data.stations as station_list %}{% if station_list %}diff --git a/src/hi/apps/weather/templates/weather/panes/conditions.html b/src/hi/apps/weather/templates/weather/panes/conditions.htmlindex 83c53d85..a42d3198 100644--- a/src/hi/apps/weather/templates/weather/panes/conditions.html+++ b/src/hi/apps/weather/templates/weather/panes/conditions.html@@ -43,18 +43,18 @@<div class="d-flex justify-content-left"><div>Min:- {% if conditions.temperature_min_today is not None %}- {{ conditions.temperature_min_today.quantity|format_magnitude:0 }}- <small>{{ conditions.temperature_min_today.quantity|format_units }}</small>+ {% if weather_stats.temperature is not None %}+ {{ weather_stats.temperature.quantity_min|format_magnitude:0 }}+ <small>{{ weather_stats.temperature.quantity_min|format_units }}</small>{% else %}-- °{% endif %}</div><div class="pl-1">Max:- {% if conditions.temperature_max_today is not None %}- {{ conditions.temperature_max_today.quantity|format_magnitude:0 }}- <small>{{ conditions.temperature_max_today.quantity|format_units }}</small>+ {% if weather_stats.temperature is not None %}+ {{ weather_stats.temperature.quantity_max|format_magnitude:0 }}+ <small>{{ weather_stats.temperature.quantity_max|format_units }}</small>{% else %}-- °{% endif %}diff --git a/src/hi/apps/weather/templates/weather/panes/weather_overview.html b/src/hi/apps/weather/templates/weather/panes/weather_overview.htmlindex 968fe839..bc5a73ec 100644--- a/src/hi/apps/weather/templates/weather/panes/weather_overview.html+++ b/src/hi/apps/weather/templates/weather/panes/weather_overview.html@@ -1,6 +1,6 @@<div id="{{ DIVID.WEATHER_OVERVIEW }}"><a class="clickable-card" href="{% url 'weather_current_conditions_details' %}" data-async="modal">- {% include "weather/panes/conditions.html" with conditions=weather_overview_data.current_conditions_data %}+ {% include "weather/panes/conditions.html" with conditions=weather_overview_data.current_conditions_data weather_stats=weather_overview_data.todays_weather_stats %}</a><div class=""><a class="clickable-card" href="{% url 'weather_todays_astronomical_details' %}" data-async="modal">diff --git a/src/hi/apps/weather/tests/test_daily_weather_tracker.py b/src/hi/apps/weather/tests/test_daily_weather_tracker.pyindex 9629f296..8a345b6d 100644--- a/src/hi/apps/weather/tests/test_daily_weather_tracker.py+++ b/src/hi/apps/weather/tests/test_daily_weather_tracker.py@@ -33,7 +33,13 @@ class TestDailyWeatherTracker(unittest.TestCase):# Use UTC timezone for consistent testingself.test_timezone = pytz.UTC- self.tracker = DailyWeatherTracker(user_timezone=self.test_timezone)++ # Mock ConsoleSettingsHelper to return UTC for consistent testing+ self.console_helper_patcher = patch('hi.apps.weather.daily_weather_tracker.ConsoleSettingsHelper')+ mock_console_helper = self.console_helper_patcher.start()+ mock_console_helper.return_value.get_tz_name.return_value = 'UTC'++ self.tracker = DailyWeatherTracker()# Create test data point source and stationself.test_source = DataPointSource(@@ -52,6 +58,10 @@ class TestDailyWeatherTracker(unittest.TestCase):# Base test time - use timezone-aware datetimeself.base_time = timezone.make_aware(datetime(2024, 3, 15, 12, 0, 0), self.test_timezone)+ def tearDown(self):+ """Clean up test environment."""+ self.console_helper_patcher.stop()+def create_test_temperature_datapoint(self, temp_celsius, timestamp=None):"""Helper to create test temperature data points."""if timestamp is None:@@ -151,7 +161,6 @@ class TestDailyWeatherTracker(unittest.TestCase):"""Test that day boundaries are correctly handled in different timezones."""# Use US/Central timezone for this testcentral_tz = pytz.timezone('US/Central')- tracker_central = DailyWeatherTracker(user_timezone=central_tz)# Create time that's late at night in Central time but next day in UTC# March 15, 2024 11:30 PM Central = March 16, 2024 4:30 AM UTC@@ -160,12 +169,25 @@ class TestDailyWeatherTracker(unittest.TestCase):location_key = "test_location"- with patch('hi.apps.common.datetimeproxy.now', return_value=utc_time):+ # Mock ConsoleSettingsHelper to return Central timezone for this test+ with patch('hi.apps.weather.daily_weather_tracker.ConsoleSettingsHelper') as mock_console, \+ patch('hi.apps.common.datetimeproxy.now') as mock_now:+ mock_console.return_value.get_tz_name.return_value = 'US/Central'++ # Mock datetimeproxy.now() to handle timezone conversion properly+ def mock_now_func(tzname=None):+ if tzname is None:+ return utc_time+ else:+ tz = pytz.timezone(tzname)+ return utc_time.astimezone(tz)+ mock_now.side_effect = mock_now_func+conditions = self.create_test_weather_conditions(20.0, utc_time)- tracker_central.record_weather_conditions(conditions, location_key=location_key)+ self.tracker.record_weather_conditions(conditions, location_key=location_key)# Should be stored under March 15 (Central time), not March 16 (UTC)- summary = tracker_central.get_daily_summary(location_key=location_key)+ summary = self.tracker.get_daily_summary(location_key=location_key)self.assertEqual(summary['date'], '2024-03-15')def test_no_data_scenarios(self):@@ -200,29 +222,6 @@ class TestDailyWeatherTracker(unittest.TestCase):self.assertIsNone(min_temp)self.assertIsNone(max_temp)- def test_populate_daily_fallbacks(self):- """Test populating fallback values in weather conditions data."""- location_key = "test_location"-- with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):- # Record some temperature data- conditions_record = self.create_test_weather_conditions(25.0)- self.tracker.record_weather_conditions(conditions_record, location_key=location_key)-- # Create conditions data without today's min/max- conditions_empty = WeatherConditionsData()- self.assertIsNone(conditions_empty.temperature_min_today)- self.assertIsNone(conditions_empty.temperature_max_today)-- # Populate fallbacks- self.tracker.populate_daily_fallbacks(conditions_empty, location_key=location_key)-- # Should now have fallback values- self.assertIsNotNone(conditions_empty.temperature_min_today)- self.assertIsNotNone(conditions_empty.temperature_max_today)- self.assertEqual(conditions_empty.temperature_min_today.quantity_ave.magnitude, 25.0)- self.assertEqual(conditions_empty.temperature_max_today.quantity_ave.magnitude, 25.0)-def test_fallback_source_properties(self):"""Test that fallback data points have correct source properties."""location_key = "test_location"@@ -355,73 +354,6 @@ class TestDailyWeatherTracker(unittest.TestCase):self.assertEqual(min_temp.quantity_ave.units, 'degree_Celsius')self.assertEqual(max_temp.quantity_ave.units, 'degree_Celsius')- def test_populate_daily_fallbacks_fills_missing_temperature_data(self):- """Test that populate_daily_fallbacks correctly fills missing temperature min/max."""- location_key = "test_location"-- with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):- # First, record some temperature data to establish tracking- weather_data = WeatherConditionsData(- temperature=self.create_test_temperature_datapoint(20.0)- )- self.tracker.record_weather_conditions(weather_data, location_key)-- weather_data2 = WeatherConditionsData(- temperature=self.create_test_temperature_datapoint(25.0)- )- self.tracker.record_weather_conditions(weather_data2, location_key)-- # Create weather data with missing daily min/max- incomplete_weather_data = WeatherConditionsData(- temperature=self.create_test_temperature_datapoint(22.0),- # Note: temperature_min_today and temperature_max_today are None- )-- # Verify fallbacks are initially None- self.assertIsNone(incomplete_weather_data.temperature_min_today)- self.assertIsNone(incomplete_weather_data.temperature_max_today)-- # Use public interface to populate fallbacks- self.tracker.populate_daily_fallbacks(incomplete_weather_data, location_key)-- # Verify fallbacks were populated- self.assertIsNotNone(incomplete_weather_data.temperature_min_today)- self.assertIsNotNone(incomplete_weather_data.temperature_max_today)- self.assertAlmostEqual(- incomplete_weather_data.temperature_min_today.quantity_ave.magnitude, 20.0, places=1)- self.assertAlmostEqual(- incomplete_weather_data.temperature_max_today.quantity_ave.magnitude, 25.0, places=1)-- def test_populate_daily_fallbacks_preserves_existing_data(self):- """Test that populate_daily_fallbacks doesn't overwrite existing min/max data."""- location_key = "test_location"-- with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):- # Record some tracking data- weather_data = WeatherConditionsData(- temperature=self.create_test_temperature_datapoint(20.0)- )- self.tracker.record_weather_conditions(weather_data, location_key)-- # Create weather data that already has min/max values- existing_min = self.create_test_temperature_datapoint(15.0)- existing_max = self.create_test_temperature_datapoint(30.0)-- complete_weather_data = WeatherConditionsData(- temperature=self.create_test_temperature_datapoint(22.0),- temperature_min_today=existing_min,- temperature_max_today=existing_max- )-- # Use public interface - should not overwrite existing data- self.tracker.populate_daily_fallbacks(complete_weather_data, location_key)-- # Verify existing data was preserved- self.assertAlmostEqual(- complete_weather_data.temperature_min_today.quantity_ave.magnitude, 15.0, places=1)- self.assertAlmostEqual(- complete_weather_data.temperature_max_today.quantity_ave.magnitude, 30.0, places=1)-def test_get_daily_summary_provides_debug_information(self):"""Test that get_daily_summary provides useful debugging information."""location_key = "test_location"diff --git a/src/hi/apps/weather/tests/test_weather_manager_daily_tracker_integration.py b/src/hi/apps/weather/tests/test_weather_manager_daily_tracker_integration.pyindex bcda23a2..c22f4cae 100644--- a/src/hi/apps/weather/tests/test_weather_manager_daily_tracker_integration.py+++ b/src/hi/apps/weather/tests/test_weather_manager_daily_tracker_integration.py@@ -122,8 +122,8 @@ class TestWeatherManagerDailyTrackerIntegration(unittest.TestCase):self.assertEqual(temp_stats['min']['value'], 25.0)self.assertEqual(temp_stats['max']['value'], 25.0)- def test_fallback_population_in_getter(self):- """Test that fallback values are populated when getting current conditions."""+ def test_weather_stats_separate_from_conditions(self):+ """Test that weather statistics are retrieved separately from current conditions."""location_key = "30.270,-97.740" # Expected location key from mock sourcewith patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):@@ -141,7 +141,7 @@ class TestWeatherManagerDailyTrackerIntegration(unittest.TestCase):source_datetime=self.base_time,quantity_ave=UnitQuantity(25.0, 'degree_Celsius'))- # Explicitly set today fields to None to test fallback+ # Explicitly set today fields to None to test they stay Nonecurrent_conditions.temperature_min_today = Nonecurrent_conditions.temperature_max_today = None@@ -150,14 +150,20 @@ class TestWeatherManagerDailyTrackerIntegration(unittest.TestCase):# Mock the location key method to return consistent locationwith patch.object(self.weather_manager, '_get_location_key', return_value=location_key):- # Get current conditions (should populate fallbacks)+ # Get current conditions (should NOT populate fallbacks)result_conditions = self.weather_manager.get_current_conditions_data()++ # Get weather stats separately+ weather_stats = self.weather_manager.get_weather_stats_today()- # Should now have fallback values- self.assertIsNotNone(result_conditions.temperature_min_today)- self.assertIsNotNone(result_conditions.temperature_max_today)- self.assertEqual(result_conditions.temperature_min_today.quantity_ave.magnitude, 22.0)- self.assertEqual(result_conditions.temperature_max_today.quantity_ave.magnitude, 22.0)+ # Current conditions should not have fallback values (new architecture)+ self.assertIsNone(result_conditions.temperature_min_today)+ self.assertIsNone(result_conditions.temperature_max_today)++ # But weather stats should have the tracked values+ self.assertIsNotNone(weather_stats.temperature)+ # Note: Currently using max temp as the single temperature datapoint+ self.assertEqual(weather_stats.temperature.quantity_ave.magnitude, 22.0)def test_fallback_does_not_overwrite_existing_data(self):"""Test that fallback values don't overwrite existing API data."""@@ -242,51 +248,52 @@ class TestWeatherManagerDailyTrackerIntegration(unittest.TestCase):self.assertEqual(temp_stats['min']['value'], 18.0) # Lowest recordedself.assertEqual(temp_stats['max']['value'], 30.0) # Highest recorded- def test_fallback_source_priority(self):- """Test that fallback sources have lower priority than real API sources."""+ def test_weather_stats_source_priority(self):+ """Test that weather stats sources have lower priority than real API sources."""location_key = "30.270,-97.740"with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):- # Record temperature for fallback+ # Record temperature for stats trackingconditions_to_record = self.create_test_conditions(20.0, include_today_fields=False)self.weather_manager._daily_weather_tracker.record_weather_conditions(weather_conditions_data=conditions_to_record,location_key=location_key)- # Get fallback values- current_conditions = WeatherConditionsData()- current_conditions.temperature_min_today = None- current_conditions.temperature_max_today = None- self.weather_manager._current_conditions_data = current_conditions-with patch.object(self.weather_manager, '_get_location_key', return_value=location_key):- result_conditions = self.weather_manager.get_current_conditions_data()+ # Get weather stats (new architecture)+ weather_stats = self.weather_manager.get_weather_stats_today()- # Check that fallback sources have high priority numbers (low priority)- fallback_min = result_conditions.temperature_min_today- fallback_max = result_conditions.temperature_max_today-- self.assertEqual(fallback_min.source.priority, 1000) # Low priority- self.assertEqual(fallback_max.source.priority, 1000) # Low priority- self.assertEqual(fallback_min.source.id, "daily_weather_tracker")- self.assertEqual(fallback_max.source.id, "daily_weather_tracker")+ # Check that weather stats sources have high priority numbers (low priority)+ self.assertIsNotNone(weather_stats.temperature)+ self.assertEqual(weather_stats.temperature.source.priority, 1000) # Low priority+ self.assertEqual(weather_stats.temperature.source.id, "daily_weather_tracker")def test_timezone_consistency(self):"""Test that timezone handling is consistent between recording and retrieval."""# Use a different timezone for the daily trackerpacific_tz = pytz.timezone('US/Pacific')- self.weather_manager._daily_weather_tracker = self.weather_manager._daily_weather_tracker.__class__(- user_timezone=pacific_tz- )-location_key = "30.268,-97.743" # This matches what the WeatherManager actually uses# Time that's late in the day Pacific timepacific_late = pacific_tz.localize(datetime(2024, 3, 15, 23, 30, 0))utc_late = pacific_late.astimezone(pytz.UTC)- with patch('hi.apps.common.datetimeproxy.now', return_value=utc_late):+ # Mock ConsoleSettingsHelper to return Pacific timezone+ with patch('hi.apps.weather.daily_weather_tracker.ConsoleSettingsHelper') as mock_console, \+ patch('hi.apps.common.datetimeproxy.now') as mock_now:++ mock_console.return_value.get_tz_name.return_value = 'US/Pacific'++ # Mock datetimeproxy.now() to handle timezone conversion properly+ def mock_now_func(tzname=None):+ if tzname is None:+ return utc_late+ else:+ tz = pytz.timezone(tzname)+ return utc_late.astimezone(tz)+ mock_now.side_effect = mock_now_func+# Record temperatureconditions = self.create_test_conditions(25.0, utc_late, include_today_fields=False)asyncio.run(self.weather_manager.update_current_conditions(diff --git a/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py b/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.pyindex 42f94171..129464dd 100644--- a/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py+++ b/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py@@ -108,29 +108,6 @@ class TestWeatherManagerDefensiveHandling(BaseTestCase):# Verify the mock was called (showing the error path was taken)mock_record.assert_called_once()- def test_daily_tracker_error_during_fallback_population_does_not_break_getter(self):- """Test that errors in fallback population don't break getting current conditions."""-- # Set up some current conditions- conditions = self.create_test_conditions(22.0)- self.weather_manager._current_conditions_data = conditions-- # Mock the daily tracker to raise an exception during fallback population- with patch.object(self.weather_manager._daily_weather_tracker,- 'populate_daily_fallbacks') as mock_populate:- mock_populate.side_effect = Exception("Simulated fallback population error")-- # This should NOT raise an exception despite the daily tracker error- result_conditions = self.weather_manager.get_current_conditions_data()-- # Verify the main weather data is still returned- self.assertIsNotNone(result_conditions)- self.assertIsNotNone(result_conditions.temperature)- self.assertEqual(result_conditions.temperature.quantity_ave.magnitude, 22.0)-- # Verify the mock was called (showing the error path was taken)- mock_populate.assert_called_once()-def test_location_key_generation_error_is_handled(self):"""Test that errors in location key generation are handled gracefully."""@@ -153,30 +130,6 @@ class TestWeatherManagerDefensiveHandling(BaseTestCase):# Verify the mock was called (showing the error path was taken)mock_location_key.assert_called_once()- def test_daily_tracker_internal_error_handling(self):- """Test that the daily tracker itself handles errors gracefully."""-- # Test that populate_daily_fallbacks handles internal errors- conditions = WeatherConditionsData()-- # Mock get_temperature_min_max_today to raise an exception- with patch.object(self.weather_manager._daily_weather_tracker,- 'get_temperature_min_max_today') as mock_get_temp:- mock_get_temp.side_effect = Exception("Simulated internal tracker error")-- # This should NOT raise an exception- self.weather_manager._daily_weather_tracker.populate_daily_fallbacks(- weather_conditions_data=conditions,- location_key="test_location"- )-- # The conditions object should remain unchanged (no fallbacks added)- self.assertIsNone(conditions.temperature_min_today)- self.assertIsNone(conditions.temperature_max_today)-- # Verify the mock was called (showing the error path was taken)- mock_get_temp.assert_called_once()-def test_cache_error_does_not_break_tracking(self):"""Test that Redis/cache errors don't break the tracking functionality."""@@ -201,17 +154,14 @@ class TestWeatherManagerDefensiveHandling(BaseTestCase):# The tracking may fail, but it shouldn't crashself.assertTrue(success or True) # Accept either graceful handling or internal error handling- def test_main_weather_processing_continues_with_multiple_tracker_errors(self):- """Test that multiple errors in daily tracking don't affect main processing."""+ def test_main_weather_processing_continues_with_tracker_errors(self):+ """Test that errors in daily tracking don't affect main processing."""- # Mock multiple parts of the daily tracker to fail+ # Mock the daily tracker recording to failwith patch.object(self.weather_manager._daily_weather_tracker,- 'record_weather_conditions') as mock_record, \- patch.object(self.weather_manager._daily_weather_tracker,- 'populate_daily_fallbacks') as mock_populate:+ 'record_weather_conditions') as mock_record:mock_record.side_effect = Exception("Recording error")- mock_populate.side_effect = Exception("Fallback error")# Update conditionsconditions = self.create_test_conditions(30.0)@@ -220,13 +170,12 @@ class TestWeatherManagerDefensiveHandling(BaseTestCase):weather_conditions_data=conditions))- # Get conditions (will try to populate fallbacks)+ # Get conditionsresult_conditions = self.weather_manager.get_current_conditions_data()# Main weather functionality should work despite tracker errorsself.assertIsNotNone(result_conditions.temperature)self.assertEqual(result_conditions.temperature.quantity_ave.magnitude, 30.0)- # Both error paths should have been taken+ # Recording error path should have been takenmock_record.assert_called_once()- mock_populate.assert_called_once()diff --git a/src/hi/apps/weather/transient_models.py b/src/hi/apps/weather/transient_models.pyindex 78f86fd5..e916aae4 100644--- a/src/hi/apps/weather/transient_models.py+++ b/src/hi/apps/weather/transient_models.py@@ -1,6 +1,6 @@from dataclasses import dataclass, field, fieldsfrom datetime import datetime, time, timedelta-from typing import Dict, Generic, List, Set, TypeVar+from typing import Dict, Generic, List, Optional, Set, TypeVarfrom pint.errors import OffsetUnitCalculusError@@ -410,11 +410,29 @@ class IntervalAstronomical( IntervalEnvironmentalData ):data : AstronomicalData | None = None+@dataclass( kw_only = True )+class WeatherStats:+ temperature_min: Optional[NumericDataPoint] = None+ temperature_max: Optional[NumericDataPoint] = None++ @property+ def temperature(self) -> NumericDataPoint:+ if self.temperature_min and self.temperature_max:+ return NumericDataPoint(+ station = self.temperature_min.station,+ source_datetime = self.temperature_min.source_datetime,+ quantity_min = self.temperature_min.quantity,+ quantity_max = self.temperature_max.quantity,+ )+ return None++@dataclass( kw_only = True )class WeatherOverviewData:current_conditions_data : WeatherConditionsData- todays_astronomical_data : AstronomicalData+ todays_weather_stats : WeatherStats = None+ todays_astronomical_data : AstronomicalData = None@dataclass( kw_only = True )diff --git a/src/hi/apps/weather/views.py b/src/hi/apps/weather/views.pyindex 9ca0cbc4..4b6f6498 100644--- a/src/hi/apps/weather/views.py+++ b/src/hi/apps/weather/views.py@@ -14,8 +14,10 @@ class CurrentConditionsDetailsView( HiModalView, WeatherMixin ):return 'weather/modals/conditions_details.html'def get(self, request, *args, **kwargs):+ weather_overview_data = self.weather_manager().get_weather_overview_data()context = {- 'weather_conditions_data': self.weather_manager().get_current_conditions_data(),+ 'weather_conditions_data': weather_overview_data.current_conditions_data,+ 'weather_stats': weather_overview_data.todays_weather_stats,}return self.modal_response( request, context )diff --git a/src/hi/apps/weather/weather_manager.py b/src/hi/apps/weather/weather_manager.pyindex 0031861c..85519109 100644--- a/src/hi/apps/weather/weather_manager.py+++ b/src/hi/apps/weather/weather_manager.py@@ -32,6 +32,7 @@ from .transient_models import (IntervalWeatherHistory,IntervalAstronomical,WeatherAlert,+ WeatherStats,)from .interval_data_manager import IntervalDataManagerfrom .weather_alert_alarm_mapper import WeatherAlertAlarmMapper@@ -113,16 +114,6 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):def get_current_conditions_data(self) -> WeatherConditionsData:with self._data_sync_lock:- # Populate any missing daily weather data with fallback values (defensive)- try:- location_key = self._get_location_key()- self._daily_weather_tracker.populate_daily_fallbacks(- weather_conditions_data=self._current_conditions_data,- location_key=location_key- )- except Exception as e:- logger.warning(f"Error populating daily weather fallbacks: {e}")-return self._current_conditions_datadef get_todays_astronomical_data(self) -> AstronomicalData:@@ -132,8 +123,13 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):def get_weather_overview_data(self) -> WeatherOverviewData:return WeatherOverviewData(current_conditions_data = self.get_current_conditions_data(),+ todays_weather_stats = self.get_weather_stats_today(),todays_astronomical_data = self.get_todays_astronomical_data(),)++ def get_weather_stats_today(self) -> WeatherStats:+ location_key = self._get_location_key()+ return self._daily_weather_tracker.get_weather_stats_today(location_key)def get_hourly_forecast(self) -> HourlyForecast:with self._data_sync_lock:@@ -424,7 +420,9 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):def get_status_id_replace_map( self, request : HttpRequest ) -> Dict[ str, str ]:weather_overview_data = self.get_weather_overview_data()- context = { 'weather_overview_data': weather_overview_data }+ context = {+ 'weather_overview_data': weather_overview_data,+ }template = get_template( WeatherConstants.WEATHER_OVERVIEW_TEMPLATE_NAME )weather_overview_html_str = template.render( context, request = request )