Skip to content

Home Information - Your home, your data, organized.

Python

Helping with min/max temperature tracking bug (#169)

Tony Cd87ee2500bbf
diff --git a/src/hi/apps/console/transient_view_manager.py b/src/hi/apps/console/transient_view_manager.py
index a942c8f4..0b8a5db9 100644
--- a/src/hi/apps/console/transient_view_manager.py
+++ b/src/hi/apps/console/transient_view_manager.py
@@ -42,11 +42,11 @@ class TransientViewManager(Singleton):
if (self._current_suggestion is None
or suggestion.priority >= self._current_suggestion.priority):
self._current_suggestion = suggestion
- logger.info(f"New transient view suggestion: {url} for {duration_seconds}s "
- f"(reason: {trigger_reason}, priority: {priority})")
+ logger.debug( f"New transient view suggestion: {url} for {duration_seconds}s "
+ f"(reason: {trigger_reason}, priority: {priority})")
else:
- logger.debug(f"Ignoring lower priority suggestion: {url} "
- f"(priority {priority} vs current {self._current_suggestion.priority})")
+ logger.debug( f"Ignoring lower priority suggestion: {url} "
+ f"(priority {priority} vs current {self._current_suggestion.priority})")
def get_current_suggestion(self) -> Optional[TransientViewSuggestion]:
"""
@@ -121,7 +121,7 @@ class TransientViewManager(Singleton):
trigger_reason=f"{alert.alarm_source.name.lower()}_alert"
)
- logger.info(f"Created auto-view suggestion for alert {alert.signature}")
+ logger.debug(f"Created auto-view suggestion for alert {alert.signature}")
def _is_auto_view_enabled(self) -> bool:
"""Check if auto-view switching is enabled in console settings."""
diff --git a/src/hi/apps/weather/daily_weather_tracker.py b/src/hi/apps/weather/daily_weather_tracker.py
index a3ad8ac5..17ec9296 100644
--- a/src/hi/apps/weather/daily_weather_tracker.py
+++ b/src/hi/apps/weather/daily_weather_tracker.py
@@ -49,6 +49,9 @@ class DailyWeatherTracker:
STAT_COUNT = 'count'
STAT_AVG = 'avg' # Computed from sum/count
+ # Field names
+ FIELD_TEMPERATURE = 'temperature'
+
def __init__(self, user_timezone=None):
"""
Initialize the daily weather tracker.
@@ -86,12 +89,14 @@ class DailyWeatherTracker:
self._record_field_value(
location_key=location_key,
- field_name='temperature',
+ field_name=self.FIELD_TEMPERATURE,
value=temp_celsius,
units='degree_Celsius',
timestamp=temp_timestamp,
track_stats=[self.STAT_MIN, self.STAT_MAX]
)
+ else:
+ logger.warning(f"record_weather_conditions called for {location_key} but no temperature data available")
# Future: Add other weather field tracking here
# if weather_conditions_data.relative_humidity:
@@ -145,7 +150,7 @@ class DailyWeatherTracker:
or (None, None) if no data available
"""
try:
- field_stats = self._get_field_stats_today(location_key, 'temperature')
+ field_stats = self._get_field_stats_today(location_key, self.FIELD_TEMPERATURE)
min_data = field_stats.get(self.STAT_MIN)
max_data = field_stats.get(self.STAT_MAX)
@@ -173,7 +178,7 @@ class DailyWeatherTracker:
quantity_ave=UnitQuantity(max_data['value'], max_data['units'])
)
- logger.debug(f"Retrieved today's temperature min/max:"
+ logger.debug(f"Retrieved today's temperature min/max for location {location_key}:"
f" {min_data['value']:.1f}°C / {max_data['value']:.1f}°C")
return min_datapoint, max_datapoint
@@ -251,14 +256,20 @@ class DailyWeatherTracker:
# Store updated statistics if changed
if updated:
self._store_field_stats(location_key, date_key, field_name, field_stats)
- logger.debug(f"Updated daily {field_name} stats for {date_key}")
+ logger.debug( f"Updated daily {field_name} stats for {date_key} at location {location_key}: "
+ f"min={field_stats.get('min', {}).get('value', 'None')}°C, "
+ f"max={field_stats.get('max', {}).get('value', 'None')}°C, "
+ f"new_value={value}°C")
+ else:
+ logger.warning(f"Temperature {value}°C not recorded"
+ f" - no min/max update needed for {date_key}")
except Exception as e:
logger.exception(f"Error recording {field_name} value: {e}")
def _get_field_stats(self, location_key: str, date_key: str, field_name: str) -> Dict[str, Any]:
"""Get field statistics from cache."""
- cache_key = f"{self.CACHE_KEY_PREFIX}:{location_key}:{date_key}:{field_name}"
+ cache_key = self._get_cache_key(location_key, date_key, field_name)
stats_json = cache.get(cache_key)
if stats_json:
@@ -281,9 +292,11 @@ class DailyWeatherTracker:
field_name : str,
stats : Dict[str, Any]) -> None:
"""Store field statistics to cache."""
- cache_key = f"{self.CACHE_KEY_PREFIX}:{location_key}:{date_key}:{field_name}"
+ cache_key = self._get_cache_key(location_key, date_key, field_name)
stats_json = json.dumps(stats)
- cache.set(cache_key, stats_json, timeout=self.CACHE_TIMEOUT_SECONDS)
+ 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}")
def clear_today(self, location_key: str = "default", field_name: Optional[str] = None) -> None:
"""
@@ -297,13 +310,13 @@ class DailyWeatherTracker:
date_key = today_local.strftime('%Y-%m-%d')
if field_name:
- cache_key = f"{self.CACHE_KEY_PREFIX}:{location_key}:{date_key}:{field_name}"
+ 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}")
else:
# Clear all fields - would need to iterate through known fields
# For now, just clear temperature since that's what we implement
- self.clear_today(location_key, 'temperature')
+ self.clear_today(location_key, self.FIELD_TEMPERATURE)
def get_daily_summary(self, location_key: str = "default") -> Dict[str, Any]:
"""
@@ -322,12 +335,20 @@ class DailyWeatherTracker:
}
# Add temperature stats if available
- temp_stats = self._get_field_stats(location_key, date_key, 'temperature')
+ temp_stats = self._get_field_stats(location_key, date_key, self.FIELD_TEMPERATURE)
if temp_stats:
- summary['fields']['temperature'] = temp_stats
+ summary['fields'][self.FIELD_TEMPERATURE] = temp_stats
# Return None if no fields have data
if not summary['fields']:
return None
return summary
+
+ def _get_cache_key(self, location_key: str, date_key: str, field_name: str) -> str:
+ """Generate cache key for field statistics.
+
+ Single source of truth for cache key format to ensure consistency
+ between storage and retrieval operations.
+ """
+ return f"{self.CACHE_KEY_PREFIX}:{location_key}:{date_key}:{field_name}"
diff --git a/src/hi/apps/weather/tests/test_daily_weather_tracker.py b/src/hi/apps/weather/tests/test_daily_weather_tracker.py
index ed259bbf..9629f296 100644
--- a/src/hi/apps/weather/tests/test_daily_weather_tracker.py
+++ b/src/hi/apps/weather/tests/test_daily_weather_tracker.py
@@ -12,7 +12,12 @@ from django.utils import timezone
import pytz
from hi.apps.weather.daily_weather_tracker import DailyWeatherTracker
-from hi.apps.weather.transient_models import WeatherConditionsData, NumericDataPoint, DataPointSource, Station
+from hi.apps.weather.transient_models import (
+ WeatherConditionsData,
+ NumericDataPoint,
+ DataPointSource,
+ Station,
+)
from hi.units import UnitQuantity
logging.disable(logging.CRITICAL)
@@ -502,6 +507,92 @@ class TestDailyWeatherTracker(unittest.TestCase):
summary = self.tracker.get_daily_summary(location_key)
self.assertIsNone(summary)
+ def test_bug_reproduction_first_bad_reading_sets_both_min_max(self):
+ """Test case reproducing Issue #166 - first bad reading sets both min and max to same wrong value."""
+ location_key = "test_location"
+
+ with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):
+ # Scenario: First reading of the day is a bad 88°F (31.1°C) value
+ # This sets both min and max to 31.1°C
+ bad_weather_data = WeatherConditionsData(
+ temperature=self.create_test_temperature_datapoint(31.1) # 88°F
+ )
+ self.tracker.record_weather_conditions(bad_weather_data, location_key)
+
+ # Verify both min and max are set to the bad value
+ min_temp, max_temp = self.tracker.get_temperature_min_max_today(location_key)
+ self.assertAlmostEqual(min_temp.quantity_ave.magnitude, 31.1, places=1)
+ self.assertAlmostEqual(max_temp.quantity_ave.magnitude, 31.1, places=1)
+
+ # Simulate the bug: subsequent real readings don't get recorded due to
+ # weather_manager passing incoming data instead of merged data
+ # (so this normal reading would have been missed before the fix)
+ normal_weather_data = WeatherConditionsData(
+ temperature=self.create_test_temperature_datapoint(27.2) # 81°F
+ )
+ self.tracker.record_weather_conditions(normal_weather_data, location_key)
+
+ # After the fix, this should update the min to the lower real value
+ min_temp, max_temp = self.tracker.get_temperature_min_max_today(location_key)
+ self.assertAlmostEqual(min_temp.quantity_ave.magnitude, 27.2, places=1) # Should be updated to real min
+ self.assertAlmostEqual(max_temp.quantity_ave.magnitude, 31.1, places=1) # Should remain the higher value
+
+ # Record even lower reading that should become the new minimum
+ lower_weather_data = WeatherConditionsData(
+ temperature=self.create_test_temperature_datapoint(21.1) # ~70°F
+ )
+ self.tracker.record_weather_conditions(lower_weather_data, location_key)
+
+ # Now min should be the lowest real reading
+ min_temp, max_temp = self.tracker.get_temperature_min_max_today(location_key)
+ self.assertAlmostEqual(min_temp.quantity_ave.magnitude, 21.1, places=1) # New minimum
+ self.assertAlmostEqual(max_temp.quantity_ave.magnitude, 31.1, places=1) # Unchanged max
+
+ def test_current_temperature_outside_cached_range_scenario(self):
+ """Test the specific scenario from Issue #166 - current temp outside min/max range should not occur."""
+ location_key = "test_location"
+
+ with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):
+ # Simulate the problematic scenario: a high temperature gets recorded first
+ high_temp_data = WeatherConditionsData(
+ temperature=self.create_test_temperature_datapoint(31.1) # 88°F - the problematic value
+ )
+ self.tracker.record_weather_conditions(high_temp_data, location_key)
+
+ # Verify both min and max are set to the high value initially
+ min_temp, max_temp = self.tracker.get_temperature_min_max_today(location_key)
+ self.assertIsNotNone(min_temp)
+ self.assertIsNotNone(max_temp)
+ self.assertAlmostEqual(min_temp.quantity_ave.magnitude, 31.1, places=1)
+ self.assertAlmostEqual(max_temp.quantity_ave.magnitude, 31.1, places=1)
+
+ # Now record the actual current temperature (81°F = 27.2°C)
+ current_temp_data = WeatherConditionsData(
+ temperature=self.create_test_temperature_datapoint(27.2) # 81°F - actual current
+ )
+ self.tracker.record_weather_conditions(current_temp_data, location_key)
+
+ # After the fix, min should update to include the current temperature
+ min_temp, max_temp = self.tracker.get_temperature_min_max_today(location_key)
+ self.assertIsNotNone(min_temp)
+ self.assertIsNotNone(max_temp)
+
+ # Critical assertion: current temperature must be within the min/max range
+ current_celsius = 27.2
+ min_celsius = min_temp.quantity_ave.magnitude
+ max_celsius = max_temp.quantity_ave.magnitude
+
+ self.assertLessEqual(
+ min_celsius, current_celsius,
+ f"Min temperature ({min_celsius:.1f}°C) should not be higher than current ({current_celsius:.1f}°C)")
+ self.assertGreaterEqual(
+ max_celsius, current_celsius,
+ f"Max temperature ({max_celsius:.1f}°C) should not be lower than current ({current_celsius:.1f}°C)")
+
+ # Specific values should be correct
+ self.assertAlmostEqual(min_celsius, 27.2, places=1) # Should be updated to current
+ self.assertAlmostEqual(max_celsius, 31.1, places=1) # Should remain the higher value
+
# ============= ORIGINAL TESTS (TO BE DEPRECATED) =============
def test_extensibility_for_future_fields(self):
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.py
index b9e074b0..bcda23a2 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
@@ -6,7 +6,7 @@ import asyncio
import logging
import unittest
from unittest.mock import patch
-from datetime import datetime
+from datetime import datetime, timedelta
from django.core.cache import cache
from django.utils import timezone
@@ -221,11 +221,14 @@ class TestWeatherManagerDailyTrackerIntegration(unittest.TestCase):
location_key = "30.268,-97.743" # This matches what the WeatherManager actually uses
with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):
- # Update with multiple different temperatures
+ # Update with multiple different temperatures using different timestamps
+ # so each update actually gets recorded (otherwise same timestamp prevents overwrite)
temperatures = [20.0, 25.0, 18.0, 30.0, 22.0]
- for temp in temperatures:
- conditions = self.create_test_conditions(temp, include_today_fields=False)
+ for i, temp in enumerate(temperatures):
+ # Use incrementing timestamps so each update actually overwrites the previous
+ timestamp = self.base_time + timedelta(minutes=i * 10)
+ conditions = self.create_test_conditions(temp, timestamp=timestamp, include_today_fields=False)
asyncio.run(self.weather_manager.update_current_conditions(
data_point_source=self.mock_source.data_point_source,
weather_conditions_data=conditions
diff --git a/src/hi/apps/weather/weather_manager.py b/src/hi/apps/weather/weather_manager.py
index 2d04bca1..c0e7c2fe 100644
--- a/src/hi/apps/weather/weather_manager.py
+++ b/src/hi/apps/weather/weather_manager.py
@@ -169,7 +169,7 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
try:
location_key = self._get_location_key()
self._daily_weather_tracker.record_weather_conditions(
- weather_conditions_data=weather_conditions_data,
+ weather_conditions_data=self._current_conditions_data,
location_key=location_key
)
except Exception as e:
diff --git a/src/hi/apps/weather/weather_sources/nws.py b/src/hi/apps/weather/weather_sources/nws.py
index c125574c..a9f9fd51 100644
--- a/src/hi/apps/weather/weather_sources/nws.py
+++ b/src/hi/apps/weather/weather_sources/nws.py
@@ -859,7 +859,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
if cloud_layers_list is None:
return
if not cloud_layers_list:
- logger.info('NWS cloudLayers list is empty; assuming clear skies.')
+ logger.debug('NWS cloudLayers list is empty; assuming clear skies.')
weather_conditions_data.cloud_cover = NumericDataPoint(
station = station,
source_datetime = source_datetime,