Home Information - Your home, your data, organized.
Python
Health status tracking for background tasks (#212)
Tony C4a5ff20a1a2a
diff --git a/src/.flake8-ci b/src/.flake8-ciindex e1d08036..48428b21 100644--- a/src/.flake8-ci+++ b/src/.flake8-ci@@ -13,10 +13,12 @@ max-line-length = 999# E251 - unexpeced whitespace around keyword parameters# W293 - blank line contains whitespace# W291 - white space at end of line+# E303 - too many blank lines# W391 - blank line at end of file# E501 - line too long# W503 - line break before binary operator+# W292 - No newline at end of file-ignore = E129,D203,E201,E202,E203,E221,E231,E251,W293,W291,W391,W503,E501,E402+ignore = E129,D203,E201,E202,E203,E221,E231,E251,W293,W291,E303,W391,W503,E501,E402,W292exclude = hi/settings/*diff --git a/src/hi/apps/alert/monitors.py b/src/hi/apps/alert/monitors.pyindex c2087c81..5a84b9af 100644--- a/src/hi/apps/alert/monitors.py+++ b/src/hi/apps/alert/monitors.py@@ -1,6 +1,7 @@import loggingfrom hi.apps.monitor.periodic_monitor import PeriodicMonitor+from hi.apps.system.provider_info import ProviderInfofrom .alert_mixins import AlertMixin@@ -20,6 +21,15 @@ class AlertMonitor( PeriodicMonitor, AlertMixin ):)return+ @classmethod+ def get_provider_info(cls) -> ProviderInfo:+ """ Subclasses should override with something more meaningful. """+ return ProviderInfo(+ provider_id = 'hi.apps.alert',+ provider_name = 'Alert Monitor',+ description = '',+ )+async def do_work(self):if self.TRACE:logger.debug( 'Checking for alert maintenance work.' )diff --git a/src/hi/apps/common/templatetags/icons.py b/src/hi/apps/common/templatetags/icons.pyindex cdc4be36..fa6b8bbc 100644--- a/src/hi/apps/common/templatetags/icons.py+++ b/src/hi/apps/common/templatetags/icons.py@@ -34,6 +34,7 @@ AVAILABLE_ICONS = {'collection','delete','edit',+ 'exclamation-circle','eye','eye-off','history',@@ -55,6 +56,7 @@ AVAILABLE_ICONS = {'settings','shield','sync',+ 'times-circle','upload','video','view',diff --git a/src/hi/apps/config/enums.py b/src/hi/apps/config/enums.pyindex 04cb32c1..f1663cbb 100644--- a/src/hi/apps/config/enums.py+++ b/src/hi/apps/config/enums.py@@ -19,6 +19,7 @@ class ConfigPageType(LabeledEnum):SETTINGS = ('Settings' , '' , 'config_settings' )EVENTS = ('Triggers' , '' , 'event_definitions' )INTEGRATIONS = ('Integrations' , '' , 'integrations_home' )+ SYSTEM_INFO = ('System Info' , '' , 'system_info' )@classmethoddef default(cls):diff --git a/src/hi/apps/monitor/periodic_monitor.py b/src/hi/apps/monitor/periodic_monitor.pyindex 352f5d01..0d574aae 100644--- a/src/hi/apps/monitor/periodic_monitor.py+++ b/src/hi/apps/monitor/periodic_monitor.py@@ -1,8 +1,11 @@import asyncioimport logging+from hi.apps.system.enums import HealthStatusType+from hi.apps.system.health_status_provider import HealthStatusProvider-class PeriodicMonitor:++class PeriodicMonitor( HealthStatusProvider ):"""Base class for any content/information that should be automatically,and periodically updated from some external source.@@ -14,7 +17,8 @@ class PeriodicMonitor:self._query_counter = 0self._is_running = Falseself._logger = logging.getLogger(__name__)- self._logger.debug(f"Initialized: {self.__class__.__name__}")++ self._logger.debug(f"Initialized: {self.__class__.__name__} with health tracking")return@property@@ -24,32 +28,44 @@ class PeriodicMonitor:@propertydef is_running(self):return self._is_running-+async def start(self) -> None:self._is_running = True- self._logger.info(f"{self.__class__.__name__} async task starting (interval: {self._query_interval_secs}s)")+ self._logger.info(f"{self.__class__.__name__} async task starting"+ f" (interval: {self._query_interval_secs}s)")try:await self.initialize()- self._logger.info(f"{self.__class__.__name__} initialized successfully, entering monitoring loop")+ self.update_health_status( HealthStatusType.HEALTHY, 'initialized successfully' )+ self._logger.info(f"{self.__class__.__name__} initialized successfully,"+ f" entering monitoring loop")while self._is_running:try:await self.run_query()+ self.update_heartbeat()+except Exception as e:self._logger.exception(f"Query execution failed in {self.__class__.__name__}: {e}")+ self.record_error(f"Query execution failed: {str(e)}")# Continue running despite individual query failures# Log sleep phase for debugging hanging issues- self._logger.debug(f"{self.__class__.__name__} sleeping for {self._query_interval_secs}s")+ self._logger.debug(f"{self.__class__.__name__} sleeping"+ f" for {self._query_interval_secs}s")await asyncio.sleep(self._query_interval_secs)- self._logger.debug(f"{self.__class__.__name__} woke up, checking if still running: {self._is_running}")+ self._logger.debug( f"{self.__class__.__name__} woke up,"+ f" checking if still running: {self._is_running}")except asyncio.CancelledError as ce:self._logger.info(f"{self.__class__.__name__} async task cancelled: {ce}")+ self.update_health_status( HealthStatusType.ERROR, "Monitor was cancelled" )raise # Re-raise to properly handle cancellationexcept Exception as e:- self._logger.exception(f"{self.__class__.__name__} async task failed unexpectedly: {e}")+ self._logger.exception( f"{self.__class__.__name__} async task"+ f" failed unexpectedly: {e}")+ self.update_health_status( HealthStatusType.ERROR,+ f"Monitor failed to start: {str(e)}" )raisefinally:self._logger.info(f"{self.__class__.__name__} async task cleaning up")@@ -80,16 +96,20 @@ class PeriodicMonitor:try:await self.do_work()query_duration = (datetimeproxy.now() - query_start_time).total_seconds()- self._logger.debug(f"Query {self._query_counter} completed successfully in {query_duration:.2f}s")+ self._logger.debug(f"Query {self._query_counter} completed successfully"+ f" in {query_duration:.2f}s")# Log warning if query is taking too long relative to intervalif query_duration > (self._query_interval_secs * 0.5):- self._logger.warning(f"Query {self._query_counter} took {query_duration:.2f}s, "- f"which is over 50% of the {self._query_interval_secs}s interval")+ self._logger.warning(+ f"Query {self._query_counter} took {query_duration:.2f}s, "+ f"which is over 50% of the {self._query_interval_secs}s interval"+ )except Exception as e:query_duration = (datetimeproxy.now() - query_start_time).total_seconds()- self._logger.exception(f"Query {self._query_counter} failed after {query_duration:.2f}s: {e}")+ self._logger.exception( f"Query {self._query_counter} failed"+ f" after {query_duration:.2f}s: {e}" )# Don't re-raise - the monitor loop in start() will continue despite failuresreturndiff --git a/src/hi/apps/monitor/tests/test_periodic_monitor.py b/src/hi/apps/monitor/tests/test_periodic_monitor.pyindex a2f585be..80b9f1f0 100644--- a/src/hi/apps/monitor/tests/test_periodic_monitor.py+++ b/src/hi/apps/monitor/tests/test_periodic_monitor.py@@ -3,6 +3,7 @@ import loggingfrom hi.testing.async_task_utils import AsyncTaskTestCasefrom hi.apps.monitor.periodic_monitor import PeriodicMonitor+from hi.apps.system.provider_info import ProviderInfologging.disable(logging.CRITICAL)@@ -21,6 +22,15 @@ class ConcreteTestMonitor(PeriodicMonitor):self.initialize_called = Trueawait super().initialize()+ @classmethod+ def get_provider_info(cls) -> ProviderInfo:+ """ Subclasses should override with something more meaningful. """+ return ProviderInfo(+ provider_id = 'test_monitor',+ provider_name = 'Test Monitor',+ description = '',+ )+async def do_work(self):self.do_work_called += 1if self.do_work_error:@@ -47,6 +57,15 @@ class TestPeriodicMonitor(AsyncTaskTestCase):class IncompleteMonitor(PeriodicMonitor):def __init__(self):super().__init__(id='incomplete', interval_secs=1)++ @classmethod+ def get_provider_info(cls) -> ProviderInfo:+ """ Subclasses should override with something more meaningful. """+ return ProviderInfo(+ provider_id = 'test_monitor',+ provider_name = 'Test Monitor',+ description = '',+ )monitor = IncompleteMonitor()@@ -278,5 +297,5 @@ class TestPeriodicMonitor(AsyncTaskTestCase):# Should have continued running despite errorself.assertGreaterEqual(fast_monitor.do_work_called, 2)-+self.run_async(test_logic())diff --git a/src/hi/apps/monitor/transient_models.py b/src/hi/apps/monitor/transient_models.pyindex ebbcd58b..353be93d 100644--- a/src/hi/apps/monitor/transient_models.py+++ b/src/hi/apps/monitor/transient_models.py@@ -40,5 +40,5 @@ class EntityStatusData:'display_only_svg_icon_item': self.display_only_svg_icon_item,}return context--++diff --git a/src/hi/apps/notify/monitors.py b/src/hi/apps/notify/monitors.pyindex 6e7a98a7..49c4ab31 100644--- a/src/hi/apps/notify/monitors.py+++ b/src/hi/apps/notify/monitors.py@@ -1,6 +1,7 @@import loggingfrom hi.apps.monitor.periodic_monitor import PeriodicMonitor+from hi.apps.system.provider_info import ProviderInfofrom .notify_mixins import NotificationMixin@@ -18,6 +19,15 @@ class NotificationMonitor( PeriodicMonitor, NotificationMixin ):)return+ @classmethod+ def get_provider_info(cls) -> ProviderInfo:+ """ Subclasses should override with something more meaningful. """+ return ProviderInfo(+ provider_id = 'hi.apps.notify',+ provider_name = 'Notifications Monitor',+ description = '',+ )+async def do_work(self):logger.debug( 'Checking for notification maintenance work.' )notification_manager = await self.notification_manager_async()diff --git a/src/hi/apps/security/monitors.py b/src/hi/apps/security/monitors.pyindex 3c33c647..d3163283 100644--- a/src/hi/apps/security/monitors.py+++ b/src/hi/apps/security/monitors.py@@ -4,6 +4,7 @@ import hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.console.console_helper import ConsoleSettingsHelperfrom hi.apps.config.settings_mixins import SettingsMixinfrom hi.apps.monitor.periodic_monitor import PeriodicMonitor+from hi.apps.system.provider_info import ProviderInfofrom .enums import SecurityStatefrom .security_mixins import SecurityMixin@@ -24,6 +25,15 @@ class SecurityMonitor( PeriodicMonitor, SettingsMixin, SecurityMixin ):self._last_security_state_check_datetime = datetimeproxy.now()return+ @classmethod+ def get_provider_info(cls) -> ProviderInfo:+ """ Subclasses should override with something more meaningful. """+ return ProviderInfo(+ provider_id = 'hi.apps.security',+ provider_name = 'Security Monitor',+ description = '',+ )+async def do_work(self):await self._check_security_state()returndiff --git a/src/hi/apps/system/__init__.py b/src/hi/apps/system/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/system/aggregate_health_provider.py b/src/hi/apps/system/aggregate_health_provider.pynew file mode 100644index 00000000..bc4e3a47--- /dev/null+++ b/src/hi/apps/system/aggregate_health_provider.py@@ -0,0 +1,150 @@+from abc import ABC, abstractmethod+import copy+import logging+import threading+from typing import Optional, Sequence++import hi.apps.common.datetimeproxy as datetimeproxy+from .api_health_aggregator import ApiHealthAggregator+from .api_health_status_provider import ApiHealthStatusProvider+from .enums import HealthStatusType, HealthAggregationRule+from .provider_info import ProviderInfo++logger = logging.getLogger(__name__)+++class AggregateHealthProvider(ABC):+ """+ Provider for components that aggregate API health from one or more sources.+ Provides health status tracking with API health aggregation capability.++ This provider can be used alongside ApiHealthStatusProvider for components that both+ make their own API calls and need to track/aggregate API health.++ This *should not* be used alongside HealthStatusProvider.+ """++ def _ensure_api_aggregator_setup(self):+ if hasattr(self, '_aggregated_health_status'):+ return++ self._health_lock = threading.Lock()+ self._api_health_status_providers = [] # Track API health status providers++ provider_info = self.get_provider_info()+ self._aggregated_health_status = ApiHealthAggregator(+ provider_id = provider_info.provider_id,+ provider_name = provider_info.provider_name,+ status = HealthStatusType.UNKNOWN,+ last_check = datetimeproxy.now(),+ aggregation_rule = self._get_aggregation_rule()+ )++ def _get_aggregation_rule(self) -> HealthAggregationRule:+ """Override to provide custom aggregation rule."""+ return HealthAggregationRule.ALL_SOURCES_HEALTHY++ @classmethod+ @abstractmethod+ def get_provider_info(cls) -> ProviderInfo:+ """Get the API service info for this class. Must be implemented by subclasses."""+ pass++ @property+ def health_status(self) -> ApiHealthAggregator:+ """Get aggregated health status (thread-safe, always fresh)."""+ self._ensure_api_aggregator_setup()+ with self._health_lock:+ # Always refresh from API owners before returning+ self._refresh_aggregated_health()+ return copy.deepcopy(self._aggregated_health_status)+ return++ def add_api_health_status_provider(+ self,+ api_health_status_provider : ApiHealthStatusProvider ) -> None:+ """Add an API health status provider to be tracked and aggregated."""+ self._ensure_api_aggregator_setup()+ with self._health_lock:+ if api_health_status_provider not in self._api_health_status_providers:+ self._api_health_status_providers.append( api_health_status_provider )+ self._refresh_aggregated_health()+ return++ def add_api_health_status_provider_multi(+ self,+ api_health_status_provider_sequence : Sequence[ ApiHealthStatusProvider ]+ ) -> None:+ """Add API health status providers to be tracked and aggregated."""+ self._ensure_api_aggregator_setup()+ with self._health_lock:+ for api_health_status_provider in api_health_status_provider_sequence:+ if api_health_status_provider not in self._api_health_status_providers:+ self._api_health_status_providers.append(api_health_status_provider)+ continue+ self._refresh_aggregated_health()+ return++ def remove_api_health_status_provider(+ self,+ api_health_status_provider : ApiHealthStatusProvider+ ) -> None:+ """Remove an API health status provider from tracking."""+ self._ensure_api_aggregator_setup()+ with self._health_lock:+ if api_health_status_provider in self._api_health_status_providers:+ self._api_health_status_providers.remove(api_health_status_provider)+ self._refresh_aggregated_health()+ return++ def _refresh_aggregated_health(self) -> None:+ """Refresh aggregated health from all tracked API health status providers."""+ # Clear current sources+ self._aggregated_health_status.api_status_map.clear()++ # Collect current health from all providers+ for provider in self._api_health_status_providers:+ service_info = provider.get_api_provider_info()+ api_health = provider.api_health_status+ self._aggregated_health_status.api_status_map[service_info] = api_health+ continue++ # Update overall status based on aggregation+ self._aggregated_health_status.status = self._aggregated_health_status.overall_status+ return++ def update_health_status( self,+ status : HealthStatusType,+ error_message : Optional[str] = None) -> None:+ """Update the base health status."""+ self._ensure_api_aggregator_setup()+ with self._health_lock:+ self._aggregated_health_status.status = status+ self._aggregated_health_status.last_check = datetimeproxy.now()+ self._aggregated_health_status.error_message = error_message++ if status.is_error:+ self._aggregated_health_status.error_count += 1+ else:+ # Reset error count on successful status+ self._aggregated_health_status.error_count = 0++ logger.debug( f'Health status updated to {status.label}:'+ f' {error_message or "No error"}')++ def record_warning(self, error_message: str) -> None:+ self.update_health_status(HealthStatusType.WARNING, error_message)++ def record_error(self, error_message: str) -> None:+ self.update_health_status(HealthStatusType.ERROR, error_message)++ def update_heartbeat(self) -> None:+ self._ensure_api_aggregator_setup()+ with self._health_lock:+ self._aggregated_health_status.heartbeat = datetimeproxy.now()+ logger.debug("Health heartbeat updated")++ def refresh_aggregated_health(self) -> None:+ self._ensure_api_aggregator_setup()+ with self._health_lock:+ self._refresh_aggregated_health()diff --git a/src/hi/apps/system/api_health.py b/src/hi/apps/system/api_health.pynew file mode 100644index 00000000..334fd87a--- /dev/null+++ b/src/hi/apps/system/api_health.py@@ -0,0 +1,122 @@+from dataclasses import dataclass+from typing import Optional+from datetime import datetime++import hi.apps.common.datetimeproxy as datetimeproxy+from .enums import ApiCallStatusType, ApiHealthStatusType+++@dataclass+class ApiCallContext:+ operation_name : str+ start_time : float # from time.time()+ status : ApiCallStatusType = ApiCallStatusType.UNKNOWN,+ duration : float = None+ error : str = None+++@dataclass+class ApiHealthStatus:+ """Health status tracking for individual API sources."""++ # Identification+ provider_name : str # User-friendly display name+ provider_id : str # Technical identifier++ status : ApiHealthStatusType+ last_success : Optional[datetime] = None+ total_calls : int = 0+ total_failures : int = 0+ consecutive_failures : int = 0+ average_response_time : Optional[float] = None+ last_response_time : Optional[float] = None++ def record_api_call( self, api_call_context : ApiCallContext ):+ self.total_calls += 1+ if api_call_context.status.is_success:+ self.last_success = datetimeproxy.now()+ self.consecutive_failures = 0+ self.status = ApiHealthStatusType.HEALTHY+ else:+ self.total_failures += 1+ self.consecutive_failures += 1++ self.status = ApiHealthStatusType.from_metrics(+ consecutive_failures = self.consecutive_failures,+ total_failures = self.total_failures,+ total_requests = self.total_calls,+ avg_response_time = self.average_response_time+ )++ if api_call_context.duration is not None:+ self.last_response_time = api_call_context.duration+ if self.average_response_time is None:+ self.average_response_time = api_call_context.duration+ else:+ # Simple moving average (can be enhanced with more sophisticated algorithms)+ self.average_response_time = (( self.average_response_time * 0.8 )+ + ( api_call_context.duration * 0.2 ))+ return++ @property+ def is_healthy(self) -> bool:+ """Check if this API source is healthy."""+ return self.status == ApiHealthStatusType.HEALTHY++ @property+ def failure_rate(self) -> float:+ """Calculate the failure rate as a percentage."""+ if self.total_calls == 0:+ return 0.0+ return (self.total_failures / self.total_calls) * 100.0++ @property+ def success_rate_percentage(self) -> float:+ """Calculate success rate as percentage."""+ if self.total_calls == 0:+ return 100.0+ return ((self.total_calls - self.total_failures) / self.total_calls) * 100++ @property+ def status_css_class(self) -> str:+ """Get CSS class for status styling."""+ return {+ ApiHealthStatusType.HEALTHY: "success",+ ApiHealthStatusType.DEGRADED: "warning",+ ApiHealthStatusType.UNKNOWN: "warning",+ ApiHealthStatusType.FAILING: "error",+ ApiHealthStatusType.UNAVAILABLE: "error"+ }[self.status]++ @property+ def status_badge_class(self) -> str:+ """Get Bootstrap badge class for status."""+ return {+ ApiHealthStatusType.HEALTHY: "badge-success",+ ApiHealthStatusType.DEGRADED: "monitor-status-warning",+ ApiHealthStatusType.UNKNOWN: "monitor-status-warning",+ ApiHealthStatusType.FAILING: "monitor-status-error",+ ApiHealthStatusType.UNAVAILABLE: "monitor-status-error"+ }[self.status]++ @property+ def status_icon(self) -> str:+ """Get Font Awesome icon for status."""+ return {+ ApiHealthStatusType.HEALTHY: "check-circle",+ ApiHealthStatusType.DEGRADED: "warning",+ ApiHealthStatusType.UNKNOWN: "warning",+ ApiHealthStatusType.FAILING: "warning",+ ApiHealthStatusType.UNAVAILABLE: "warning"+ }[self.status]++ @property+ def border_color_class(self) -> str:+ """Get border color class for API source section."""+ return {+ ApiHealthStatusType.HEALTHY: "api-source-healthy",+ ApiHealthStatusType.DEGRADED: "api-source-warning",+ ApiHealthStatusType.UNKNOWN: "api-source-warning",+ ApiHealthStatusType.FAILING: "api-source-error",+ ApiHealthStatusType.UNAVAILABLE: "api-source-error"+ }[self.status]diff --git a/src/hi/apps/system/api_health_aggregator.py b/src/hi/apps/system/api_health_aggregator.pynew file mode 100644index 00000000..daaca0cd--- /dev/null+++ b/src/hi/apps/system/api_health_aggregator.py@@ -0,0 +1,68 @@+from dataclasses import dataclass, field+from typing import Dict++from .health_status import HealthStatus+from .api_health import ApiHealthStatus+from .provider_info import ProviderInfo+from .enums import HealthStatusType, ApiHealthStatusType, HealthAggregationRule+++@dataclass+class ApiHealthAggregator( HealthStatus ):+ """+ Extends HealthStatus to add API source tracking and aggregation.+ """+ # Current aggregated API health data+ api_status_map : Dict[ProviderInfo, ApiHealthStatus] = field(default_factory=dict)+ aggregation_rule : HealthAggregationRule = HealthAggregationRule.ALL_SOURCES_HEALTHY++ def aggregate_health(self) -> HealthStatusType:+ """+ Returns the computed health based on aggregation rule.+ """+ if not self.api_status_map:+ return self.status # No API sources, use base health++ api_statuses = [ api.status for api in self.api_status_map.values() ]++ if self.aggregation_rule == HealthAggregationRule.ALL_SOURCES_HEALTHY:+ # All must be healthy+ if all( s == ApiHealthStatusType.HEALTHY for s in api_statuses ):+ return HealthStatusType.HEALTHY+ elif any( s in [ ApiHealthStatusType.FAILING,+ ApiHealthStatusType.UNAVAILABLE ]+ for s in api_statuses) :+ return HealthStatusType.ERROR+ else:+ return HealthStatusType.WARNING++ elif self.aggregation_rule == HealthAggregationRule.MAJORITY_SOURCES_HEALTHY:+ # Majority must be healthy+ healthy_count = sum( 1 for s in api_statuses+ if s == ApiHealthStatusType.HEALTHY )+ if healthy_count > len(api_statuses) / 2:+ return HealthStatusType.HEALTHY+ else:+ return HealthStatusType.WARNING++ elif self.aggregation_rule == HealthAggregationRule.ANY_SOURCE_HEALTHY:+ # At least one must be healthy+ if any( s == ApiHealthStatusType.HEALTHY for s in api_statuses ):+ return HealthStatusType.HEALTHY+ else:+ return HealthStatusType.ERROR++ return self.status # Fallback to base status++ @property+ def overall_status(self) -> HealthStatusType:+ """+ Get overall status considering both base health and API health.+ """+ api_health = self.aggregate_health()++ # Return worst of base status and aggregated API status using priority+ statuses = [self.status, api_health]++ # Return status with highest priority (lowest priority number)+ return min(statuses, key=lambda s: s.priority)diff --git a/src/hi/apps/system/api_health_status_provider.py b/src/hi/apps/system/api_health_status_provider.pynew file mode 100644index 00000000..72c3a8f4--- /dev/null+++ b/src/hi/apps/system/api_health_status_provider.py@@ -0,0 +1,87 @@+from abc import ABC, abstractmethod+from contextlib import contextmanager+import copy+import logging+import threading+import time++from .api_health import ApiCallContext, ApiHealthStatus+from .provider_info import ProviderInfo+from .enums import ApiCallStatusType, ApiHealthStatusType++logger = logging.getLogger(__name__)+++class ApiHealthStatusProvider(ABC):++ def __init__(self):+ # We try not to depend on __init__() being called fo a provider context,+ # so protected most access methods anyway.+ self._ensure_api_health_status_provider_setup()+ return++ def _ensure_api_health_status_provider_setup(self):+ if hasattr( self, '_api_health_status' ):+ return++ # Get the API service info from the implementing class+ service_info = self.get_api_provider_info()+ self._api_health_lock = threading.Lock()+ self._api_health_status = ApiHealthStatus(+ provider_id = service_info.provider_id,+ provider_name = service_info.provider_name,+ status = ApiHealthStatusType.UNKNOWN,+ )+ return++ @classmethod+ @abstractmethod+ def get_api_provider_info(cls) -> ProviderInfo:+ """Get the API service info for this class. Must be implemented by subclasses."""+ pass++ @property+ def api_health_status(self) -> ApiHealthStatus:+ self._ensure_api_health_status_provider_setup()+ with self._api_health_lock:+ api_health_status = copy.deepcopy( self._api_health_status )+ return api_health_status++ @contextmanager+ def api_call_context( self, operation_name : str ):+ """+ Context manager for tracking API call execution.++ Usage:+ with self.api_context( 'fetch_user' ) as ctx:+ response = requests.get( f'/api/users/{user_id}' )+ """+ self._ensure_api_health_status_provider_setup()+ start_time = time.time()+ api_call_context = ApiCallContext(+ operation_name = operation_name,+ start_time = start_time,+ )+ try:+ yield api_call_context # Let the API call happen+ api_call_context.status = ApiCallStatusType.SUCCESS+ except Exception as e:+ api_call_context.status = ApiCallStatusType.EXCEPTION+ api_call_context.error = str(e)+ raise+ finally:+ # Always track the call+ api_call_context.duration = time.time() - start_time+ self.record_api_call( api_call_context = api_call_context )++ return++ def record_api_call( self, api_call_context : ApiCallContext ):+ self._ensure_api_health_status_provider_setup()+ with self._api_health_lock:+ self._api_health_status.record_api_call(+ api_call_context = api_call_context,+ )+ return++diff --git a/src/hi/apps/system/apps.py b/src/hi/apps/system/apps.pynew file mode 100644index 00000000..770b2b9e--- /dev/null+++ b/src/hi/apps/system/apps.py@@ -0,0 +1,6 @@+from django.apps import AppConfig+++class MonitorConfig(AppConfig):+ default_auto_field = "django.db.models.BigAutoField"+ name = "hi.apps.system"diff --git a/src/hi/apps/system/enums.py b/src/hi/apps/system/enums.pynew file mode 100644index 00000000..8d9b0255--- /dev/null+++ b/src/hi/apps/system/enums.py@@ -0,0 +1,257 @@+from typing import Optional++from hi.apps.common.enums import LabeledEnum+++class HealthStatusType(LabeledEnum):++ UNKNOWN = ( 'Unknown',+ 'No health status was set')+ HEALTHY = ( 'Healthy',+ 'Operating normally with all dependencies healthy')+ WARNING = ( 'Warning',+ 'Temporary issues detected or degraded performance')+ ERROR = ( 'Error',+ 'Critical failures requiring attention or not responding')+ DISABLED = ( 'Disabled',+ 'Provider has been manually disabled' )++ @property+ def is_healthy(self) -> bool:+ return bool( self in (+ HealthStatusType.HEALTHY,+ ))++ @property+ def is_warning(self) -> bool:+ return bool( self in (+ HealthStatusType.WARNING,+ ))++ @property+ def is_info(self) -> bool:+ return bool( self in (+ HealthStatusType.DISABLED,+ ))++ @property+ def is_error(self) -> bool:+ return bool( self in (+ HealthStatusType.ERROR,+ ))++ @property+ def is_critical(self) -> bool:+ return bool( self in (+ HealthStatusType.ERROR,+ ))++ @property+ def is_operational(self) -> bool:+ return bool( self in (+ HealthStatusType.HEALTHY,+ HealthStatusType.WARNING,+ ))++ @property+ def requires_attention(self) -> bool:+ return self.is_error++ @classmethod+ def from_priority(cls, priority: int) -> 'HealthStatusType':+ """+ Map priority levels to health status.+ Lower numbers = higher priority = worse health.+ """+ if priority <= 1:+ return cls.ERROR+ elif priority <= 2:+ return cls.WARNING+ else:+ return cls.HEALTHY++ @property+ def priority(self) -> int:+ """+ Priority level for sorting/escalation (lower = higher priority).+ """+ if self.is_critical: # ERROR+ return 1+ elif self.is_warning: # WARNING+ return 2+ elif self.is_info: # DISABLED+ return 3+ elif self == HealthStatusType.HEALTHY:+ return 4+ else: # UNKNOWN+ return 5+++class HeartbeatStatusType(LabeledEnum):+ """+ Heartbeat-specific health status based on last communication time.+ """++ ACTIVE = ('Active', 'Responding within expected timeframe (< 30 seconds)')+ STALE = ('Stale', 'Response delayed but within tolerance (30 seconds - 5 minutes)')+ DEAD = ('Dead', 'Not responding for extended period (> 5 minutes)')++ @classmethod+ def from_last_heartbeat(cls, seconds_since_last: Optional[float]) -> 'HeartbeatStatusType':+ """+ Determine heartbeat status based on seconds since last communication.++ Args:+ seconds_since_last: Seconds since last heartbeat, None if never seen++ Returns:+ Appropriate heartbeat status+ """+ ACTIVE_THRESHOLD_SECONDS = 30+ STALE_THRESHOLD_SECONDS = 300 # 5 minutes++ if seconds_since_last is None:+ return cls.DEAD++ if seconds_since_last < ACTIVE_THRESHOLD_SECONDS:+ return cls.ACTIVE+ elif seconds_since_last < STALE_THRESHOLD_SECONDS:+ return cls.STALE+ else:+ return cls.DEAD++ def to_health_status(self) -> HealthStatusType:+ if self == HeartbeatStatusType.ACTIVE:+ return HealthStatusType.HEALTHY+ elif self == HeartbeatStatusType.STALE:+ return HealthStatusType.WARNING+ else: # DEAD+ return HealthStatusType.ERROR+++class ApiCallStatusType(LabeledEnum):++ UNKNOWN = ('Unknown' , '')+ SUCCESS = ('Success' , '')+ EXCEPTION = ('Failure' , '')++ @property+ def is_success(self):+ return bool( self in [ ApiCallStatusType.SUCCESS ] )++ @property+ def is_failure(self):+ return bool( self in [ ApiCallStatusType.EXCEPTION ] )+++class ApiHealthStatusType(LabeledEnum):++ UNKNOWN = ('Unknown' , 'No health status was set')+ HEALTHY = ('Healthy' , 'API responding normally with good performance')+ DEGRADED = ('Degraded' , 'API responding but performance or occasional issues')+ FAILING = ('Failing' , 'API experiencing frequent failures or timeouts')+ UNAVAILABLE = ('Unavailable' , 'API completely unresponsive or returning errors')++ @classmethod+ def from_metrics(cls,+ success_rate: Optional[float] = None,+ avg_response_time: Optional[float] = None,+ consecutive_failures: int = 0,+ total_failures: int = 0,+ total_requests: int = 0) -> 'ApiHealthStatusType':+ """+ Determine API source health status based on performance metrics.++ Args:+ success_rate: Ratio of successful requests (0.0 to 1.0)+ avg_response_time: Average response time in seconds+ consecutive_failures: Number of consecutive failures+ total_failures: Total number of failures in monitoring window+ total_requests: Total number of requests in monitoring window++ Returns:+ Appropriate API source health status+ """+ # Performance and failure thresholds+ DEGRADED_SUCCESS_RATE_THRESHOLD = 0.95 # Below 95% success rate+ FAILING_SUCCESS_RATE_THRESHOLD = 0.80 # Below 80% success rate+ DEGRADED_RESPONSE_TIME_THRESHOLD = 5.0 # Above 5 seconds average+ FAILING_RESPONSE_TIME_THRESHOLD = 10.0 # Above 10 seconds average+ CONSECUTIVE_FAILURE_WARNING_THRESHOLD = 3 # 3 consecutive failures = degraded+ CONSECUTIVE_FAILURE_ERROR_THRESHOLD = 5 # 5 consecutive failures = failing++ # Handle no data case+ if total_requests == 0:+ return cls.HEALTHY # Assume healthy until proven otherwise++ # Check consecutive failures first (immediate problems)+ if consecutive_failures >= CONSECUTIVE_FAILURE_ERROR_THRESHOLD:+ return cls.FAILING+ elif consecutive_failures >= CONSECUTIVE_FAILURE_WARNING_THRESHOLD:+ return cls.DEGRADED++ # Calculate success rate if not provided+ if success_rate is None and total_requests > 0:+ success_rate = (total_requests - total_failures) / total_requests++ # Check success rate thresholds+ if success_rate is not None:+ if success_rate < FAILING_SUCCESS_RATE_THRESHOLD:+ return cls.FAILING+ elif success_rate < DEGRADED_SUCCESS_RATE_THRESHOLD:+ return cls.DEGRADED++ # Check response time thresholds+ if avg_response_time is not None:+ if avg_response_time > FAILING_RESPONSE_TIME_THRESHOLD:+ return cls.FAILING+ elif avg_response_time > DEGRADED_RESPONSE_TIME_THRESHOLD:+ return cls.DEGRADED++ return cls.HEALTHY++ def to_health_status(self) -> HealthStatusType:+ """Convert API source status to health status contribution."""+ if self == ApiHealthStatusType.HEALTHY:+ return HealthStatusType.HEALTHY+ elif self == ApiHealthStatusType.DEGRADED:+ return HealthStatusType.WARNING+ else: # FAILING or UNAVAILABLE+ return HealthStatusType.ERROR+++class HealthAggregationRule(LabeledEnum):+ """+ Rules for aggregating multiple health status inputs into overall health.+ """++ # Heartbeat-only (no API dependencies)+ HEARTBEAT_ONLY = ('Heartbeat Only', 'Health determined solely by heartbeat status')++ # API-dependent+ ALL_SOURCES_HEALTHY = ('All Sources Healthy', 'All API sources must be healthy for overall health')+ MAJORITY_SOURCES_HEALTHY = ('Majority Sources Healthy', 'Majority of API sources must be healthy')+ ANY_SOURCE_HEALTHY = ('Any Source Healthy', 'At least one API source must be healthy')++ # Custom weighting (for future enhancement)+ WEIGHTED_AVERAGE = ('Weighted Average', 'Weighted average of source health with custom priorities')++ @classmethod+ def default_for_api_count(cls, api_provider_count: int) -> 'HealthAggregationRule':+ """+ Determine appropriate aggregation rule based on number of API sources.++ Args:+ api_provider_count: Number of API sources this depends on++ Returns:+ Recommended aggregation rule+ """+ if api_provider_count == 0:+ return cls.HEARTBEAT_ONLY+ elif api_provider_count == 1:+ return cls.ALL_SOURCES_HEALTHY # Single source must be healthy+ elif api_provider_count <= 3:+ return cls.MAJORITY_SOURCES_HEALTHY # Most sources must be healthy+ else:+ return cls.ANY_SOURCE_HEALTHY # At least one source must workdiff --git a/src/hi/apps/system/health_status.py b/src/hi/apps/system/health_status.pynew file mode 100644index 00000000..46a4fff4--- /dev/null+++ b/src/hi/apps/system/health_status.py@@ -0,0 +1,147 @@+from dataclasses import dataclass+from typing import Optional+from datetime import datetime++from .enums import HealthStatusType+++@dataclass+class HealthStatus:+ """Health status tracking for PeriodicMonitor instances."""++ # Identification+ provider_name : str # User-friendly display name+ provider_id : str # Technical identifier++ status : HealthStatusType # When did we last check+ last_check : datetime # When did provider last report+ heartbeat : Optional[datetime] = None+ error_message : Optional[str] = None+ error_count : int = 0++ @property+ def is_healthy(self) -> bool:+ return self.status == HealthStatusType.HEALTHY++ @property+ def is_error(self) -> bool:+ return self.status.is_error++ @property+ def is_critical(self) -> bool:+ return self.status.is_critical++ @property+ def status_display(self) -> str:+ return self.status.label++ @property+ def heartbeat_age_seconds(self) -> Optional[int]:+ if not self.heartbeat:+ return None+ import hi.apps.common.datetimeproxy as datetimeproxy+ return int((datetimeproxy.now() - self.heartbeat).total_seconds())++ @property+ def heartbeat_status_text(self) -> str:+ """Get heartbeat status description."""+ if not self.heartbeat:+ return "Unknown"++ age = self.heartbeat_age_seconds+ if age is None:+ return "Unknown"+ elif age < 30:+ return "Active"+ elif age < 300: # 5 minutes+ return "Stale"+ else:+ return "Dead"++ @property+ def heartbeat_css_class(self) -> str:+ """Get CSS class for heartbeat indicator."""+ if not self.heartbeat:+ return "heartbeat-dead"++ age = self.heartbeat_age_seconds+ if age is None:+ return "heartbeat-dead"+ elif age < 30:+ return "heartbeat-healthy"+ elif age < 300: # 5 minutes+ return "heartbeat-stale"+ else:+ return "heartbeat-dead"++ @property+ def heartbeat_text_class(self) -> str:+ """Get text color class for heartbeat status."""+ if not self.heartbeat:+ return "text-error-custom"++ age = self.heartbeat_age_seconds+ if age is None:+ return "text-error-custom"+ elif age < 30:+ return "text-success-custom"+ elif age < 300: # 5 minutes+ return "text-warning-custom"+ else:+ return "text-error-custom"++ @property+ def status_badge_class(self) -> str:+ """Get Bootstrap badge class for overall status."""+ if self.status.is_healthy:+ return "monitor-status-healthy"+ elif self.status.is_warning:+ return "monitor-status-warning"+ elif self.status.is_info:+ return "monitor-status-info"+ elif self.status.is_critical:+ return "monitor-status-critical"+ elif self.status.is_error:+ return "monitor-status-error"+ else: # UNKNOWN+ return "monitor-status-unknown"++ @property+ def status_alert_class(self) -> str:+ """Get alert class for status summary."""+ if self.is_healthy:+ return "alert-success"+ elif self.status.is_info:+ return "alert-info"+ elif self.is_critical:+ return "alert-danger"+ else:+ return "alert-warning"++ @property+ def status_icon(self) -> str:+ """Get Font Awesome icon for status."""+ if self.status.is_healthy:+ return "check-circle"+ elif self.status.is_warning:+ return "warning"+ elif self.status.is_info:+ return "info-circle"+ elif self.status.is_critical:+ return "times-circle"+ elif self.status.is_error:+ return "exclamation-circle"+ else: # UNKNOWN+ return "question-circle"++ @property+ def status_summary_message(self) -> str:+ """Get appropriate status summary message."""+ if self.is_healthy:+ return "Is operating normally and heartbeat is active."+ elif self.is_critical:+ return "Requires immediate attention. Please check the configuration settings and ensure external services are accessible."+ else:+ return "Has encountered temporary issues. The problem may resolve automatically, but monitoring is recommended."++diff --git a/src/hi/apps/system/health_status_provider.py b/src/hi/apps/system/health_status_provider.pynew file mode 100644index 00000000..4d293ac7--- /dev/null+++ b/src/hi/apps/system/health_status_provider.py@@ -0,0 +1,85 @@+from abc import ABC, abstractmethod+import copy+import logging+import threading+from typing import Optional++import hi.apps.common.datetimeproxy as datetimeproxy++from .enums import HealthStatusType+from .health_status import HealthStatus+from .provider_info import ProviderInfo++logger = logging.getLogger(__name__)+++class HealthStatusProvider(ABC):++ def __init__(self):+ # We try not to depend on __init__() being called fo a provider context,+ # so protected most access methods anyway.+ self._ensure_health_status_provider_setup()+ return++ def _ensure_health_status_provider_setup(self):+ if hasattr( self, '_health_status' ):+ return+ provider_info = self.get_provider_info()+ self._health_status = HealthStatus(+ provider_id = provider_info.provider_id,+ provider_name = provider_info.provider_name,+ status = HealthStatusType.UNKNOWN,+ last_check = datetimeproxy.now(),+ )+ self._health_lock = threading.Lock()+ return++ @classmethod+ @abstractmethod+ def get_provider_info(cls) -> ProviderInfo:+ """Get the API service info for this class. Must be implemented by subclasses."""+ pass++ @property+ def health_status(self) -> HealthStatus:+ self._ensure_health_status_provider_setup()+ with self._health_lock:+ health_status = copy.deepcopy( self._health_status )+ return health_status++ def record_warning( self, error_message: str ) -> None:+ self.update_health_status( HealthStatusType.WARNING, error_message )+ return++ def record_error( self, error_message: str ) -> None:+ self.update_health_status( HealthStatusType.ERROR, error_message )+ return++ def update_health_status( self,+ status : HealthStatusType,+ error_message : Optional[str] = None) -> None:+ self._ensure_health_status_provider_setup()+ with self._health_lock:+ self._health_status.status = status+ self._health_status.last_check = datetimeproxy.now()+ self._health_status.error_message = error_message++ if status.is_error:+ self._health_status.error_count += 1+ else:+ # Reset error count on successful status+ self._health_status.error_count = 0++ logger.debug( f'Health status updated to {status.label}:'+ f' {error_message or "No error"}')+ return++ def update_heartbeat(self) -> None:+ self._ensure_health_status_provider_setup()+ with self._health_lock:+ self._health_status.heartbeat = datetimeproxy.now()+ logger.debug("Health heartbeat updated")+ return+++diff --git a/src/hi/apps/system/provider_info.py b/src/hi/apps/system/provider_info.pynew file mode 100644index 00000000..1d73aed2--- /dev/null+++ b/src/hi/apps/system/provider_info.py@@ -0,0 +1,28 @@+from dataclasses import dataclass+from typing import Optional+++@dataclass(frozen=True)+class ProviderInfo:+ """+ Information about an API service for health tracking.++ This container class encapsulates all the metadata needed to identify+ and describe an API service in the health tracking system.+ """++ provider_id : str # Technical identifier (e.g., 'hass_api', 'zm_api')+ provider_name : str # Human-friendly display name (e.g., 'Home Assistant API')+ description : Optional[str] = None # Optional longer description++ def __str__(self) -> str:+ return f"{self.provider_name} ({self.provider_id})"++ def __hash__(self) -> int:+ return hash(self.provider_id)++ def __eq__(self, other) -> bool:+ if isinstance(other, ProviderInfo):+ return self.provider_id == other.provider_id+ return False+diff --git a/src/hi/apps/system/templates/system/modals/aggregate_health_status.html b/src/hi/apps/system/templates/system/modals/aggregate_health_status.htmlnew file mode 100644index 00000000..6675b5a2--- /dev/null+++ b/src/hi/apps/system/templates/system/modals/aggregate_health_status.html@@ -0,0 +1,146 @@+{% extends "modals/action_done.html" %}+{% load icons %}+{% load tz %}++{% block modal_dialog_class %}hi-modal-dialog-800{% endblock %}++{% block title_text %}+{% icon "shield" size="sm" css_class="mr-2" %}+{{ health_status.provider_name }} Health+{% endblock %}++{% block body %}+{% timezone USER_TIMEZONE %}++<div class="container-fluid px-0">+ <!-- Overall Provider Status -->+ <div class="row mb-4">+ <div class="col-12">+ <div class="d-flex align-items-center mb-3">+ <span class="badge monitor-status-badge {{ health_status.status_badge_class }} mr-3">+ {% icon health_status.status_icon size="sm" css_class="mr-2" %}+ {{ health_status.status_display }}+ </span>+ </div>++ <!-- Provider Heartbeat -->+ {% if health_status.heartbeat %}+ <div class="row">+ <div class="col-sm-3"><strong>Provider Status:</strong></div>+ <div class="col-sm-9">+ <span class="heartbeat-indicator {{ health_status.heartbeat_css_class }}"></span>+ <span class="{{ health_status.heartbeat_text_class }}">{{ health_status.heartbeat_status_text }}</span>+ <small class="text-muted-custom">+ (last seen {{ health_status.heartbeat|localtime|date:"H:i:s" }})+ </small>+ </div>+ </div>+ {% endif %}++ <div class="row mt-2">+ <div class="col-sm-3"><strong>Last Check:</strong></div>+ <div class="col-sm-9">{{ health_status.last_check|localtime|date:"M j, Y H:i:s" }}</div>+ </div>++ {% if health_status.error_message %}+ <div class="row mt-2">+ <div class="col-sm-3"><strong>Error Details:</strong></div>+ <div class="col-sm-9">+ <div class="{{ health_status.status_alert_class }} p-2">+ {{ health_status.error_message }}+ </div>+ </div>+ </div>+ {% endif %}++ {% if health_status.error_count > 1 %}+ <div class="row mt-2">+ <div class="col-sm-3"><strong>Error Count:</strong></div>+ <div class="col-sm-9">{{ health_status.error_count }}</div>+ </div>+ {% endif %}+ </div>+ </div>++ {% if health_status.api_status_map %}+ <!-- API Sources Section -->+ <div class="row">+ <div class="col-12">+ <h6 class="mb-3">+ {% icon "plug" size="sm" css_class="mr-2" %}+ API Sources+ </h6>++ {% for api_status in health_status.api_status_map.values %}+ <div class="api-source-section {{ api_status.border_color_class }} mb-4">+ <div class="d-flex justify-content-between align-items-center mb-2">+ <h6 class="mb-0">{{ api_status.provider_name }}</h6>+ <span class="badge {{ api_status.status_badge_class }}">+ {% icon api_status.status_icon size="sm" css_class="mr-1" %}{{ api_status.status.label }}+ </span>+ </div>++ {% if api_status.last_success %}+ <div class="row">+ <div class="col-sm-3"><strong>Last Success:</strong></div>+ <div class="col-sm-9">{{ api_status.last_success|localtime|date:"H:i:s" }}</div>+ </div>+ {% endif %}++ <div class="api-metrics-grid mt-2">+ <div class="metric-item {{ api_status.status_css_class }}">+ <div class="small text-muted-custom">Total Calls</div>+ <div class="metric-value">{{ api_status.total_calls|floatformat:0 }}</div>+ </div>+ <div class="metric-item {{ api_status.status_css_class }}">+ <div class="small text-muted-custom">Success Rate</div>+ <div class="metric-value">{{ api_status.success_rate_percentage|floatformat:1 }}%</div>+ </div>+ {% if api_status.last_response_time %}+ <div class="metric-item {{ api_status.status_css_class }}">+ <div class="small text-muted-custom">Last Response</div>+ <div class="metric-value">{{ api_status.last_response_time|floatformat:2 }}s</div>+ </div>+ {% elif api_status.average_response_time %}+ <div class="metric-item {{ api_status.status_css_class }}">+ <div class="small text-muted-custom">Avg Response</div>+ <div class="metric-value">{{ api_status.average_response_time|floatformat:2 }}s</div>+ </div>+ {% else %}+ <div class="metric-item {{ api_status.status_css_class }}">+ <div class="small text-muted-custom">Response Time</div>+ <div class="metric-value">timeout</div>+ </div>+ {% endif %}+ {% if api_status.total_failures > 0 or api_status.consecutive_failures > 0 %}+ <div class="metric-item {{ api_status.status_css_class }}">+ <div class="small text-muted-custom">+ {% if api_status.consecutive_failures > 0 %}Consecutive Failures{% else %}Total Failures{% endif %}+ </div>+ <div class="metric-value">+ {% if api_status.consecutive_failures > 0 %}{{ api_status.consecutive_failures }}{% else %}{{ api_status.total_failures }}{% endif %}+ </div>+ </div>+ {% endif %}+ </div>+ </div>+ {% endfor %}+ </div>+ </div>+ {% endif %}++ <!-- Status Summary Alert -->+ <div class="row">+ <div class="col-12">+ <div class="alert {{ health_status.status_alert_class }}">+ <p class="mb-0">+ {% icon health_status.status_icon size="sm" css_class="mr-2" %}+ {{ health_status.status_summary_message }}+ </p>+ </div>+ </div>+ </div>+</div>++{% endtimezone %}+{% endblock %}diff --git a/src/hi/apps/system/templates/system/modals/health_status.html b/src/hi/apps/system/templates/system/modals/health_status.htmlnew file mode 100644index 00000000..70a72ec1--- /dev/null+++ b/src/hi/apps/system/templates/system/modals/health_status.html@@ -0,0 +1,79 @@+{% extends "modals/action_done.html" %}+{% load icons %}+{% load tz %}++{% block modal_dialog_class %}hi-modal-dialog-800{% endblock %}++{% block title_text %}+{% icon "shield" size="sm" css_class="mr-2" %}+{{ health_status.provider_name }} Health+{% endblock %}++{% block body %}+{% timezone USER_TIMEZONE %}++<div class="container-fluid px-0">+ <!-- Overall Provider Status -->+ <div class="row mb-4">+ <div class="col-12">+ <div class="d-flex align-items-center mb-3">+ <span class="badge monitor-status-badge {{ health_status.status_badge_class }} mr-3">+ {% icon health_status.status_icon size="sm" css_class="mr-2" %}+ {{ health_status.status_display }}+ </span>+ </div>++ <!-- Provider Heartbeat -->+ {% if health_status.heartbeat %}+ <div class="row">+ <div class="col-sm-3"><strong>Provider Status:</strong></div>+ <div class="col-sm-9">+ <span class="heartbeat-indicator {{ health_status.heartbeat_css_class }}"></span>+ <span class="{{ health_status.heartbeat_text_class }}">{{ health_status.heartbeat_status_text }}</span>+ <small class="text-muted-custom">+ (last seen {{ health_status.heartbeat|localtime|date:"H:i:s" }})+ </small>+ </div>+ </div>+ {% endif %}++ <div class="row mt-2">+ <div class="col-sm-3"><strong>Last Check:</strong></div>+ <div class="col-sm-9">{{ health_status.last_check|localtime|date:"M j, Y H:i:s" }}</div>+ </div>++ {% if health_status.error_message %}+ <div class="row mt-2">+ <div class="col-sm-3"><strong>Error Details:</strong></div>+ <div class="col-sm-9">+ <div class="{{ health_status.status_alert_class }} p-2">+ {{ health_status.error_message }}+ </div>+ </div>+ </div>+ {% endif %}++ {% if health_status.error_count > 1 %}+ <div class="row mt-2">+ <div class="col-sm-3"><strong>Error Count:</strong></div>+ <div class="col-sm-9">{{ health_status.error_count }}</div>+ </div>+ {% endif %}+ </div>+ </div>++ <!-- Status Summary Alert -->+ <div class="row">+ <div class="col-12">+ <div class="alert {{ health_status.status_alert_class }}">+ <p class="mb-0">+ {% icon health_status.status_icon size="sm" css_class="mr-2" %}+ {{ health_status.status_summary_message }}+ </p>+ </div>+ </div>+ </div>+</div>++{% endtimezone %}+{% endblock %}diff --git a/src/hi/apps/system/templates/system/panes/system_info.html b/src/hi/apps/system/templates/system/panes/system_info.htmlnew file mode 100644index 00000000..c8f985ba--- /dev/null+++ b/src/hi/apps/system/templates/system/panes/system_info.html@@ -0,0 +1,81 @@+{% extends "config/pages/config_base.html" %}+{% load icons %}+{% load tz %}++{% block config_content %}+{% timezone USER_TIMEZONE %}+<div class="container-fluid">+ <div class="d-flex justify-content-between my-1">+ <div class="h3">System Info</div>+ <div>+ <a role="button" class="btn btn-primary"+ href="#"+ data-async="modal" >+ {% icon "plus" size="sm" css_class="hi-icon-left" %}PLACEHOLDER+ </a>+ </div>+ </div>++ <div>+ PLACEHOLDER+ </div>++ {% if async_diagnostics %}+ <div class="row mt-2">+ <div class="col-sm-3"><strong>Background Tasks:</strong></div>+ <div class="col-sm-9">+ <div class="small">+ <div>Main Thread: {{ async_diagnostics.main_thread.name }}</div>+ <div>Active Threads: {{ async_diagnostics.current_thread.active_count }}</div>++ {% for task_name, task_info in async_diagnostics.background_tasks.items %}+ <div class="mt-1 p-1 border-left border-info">+ <div><strong>{{ task_name }}</strong></div>+ <div>Thread:+ {% if task_info.thread.is_alive %}+ <span class="text-success">+ {% icon "check-circle" size="sm" css_class="mr-1" %}{{ task_info.thread_name }}+ </span>+ {% else %}+ <span class="text-danger">+ {% icon "warning" size="sm" css_class="mr-1" %}Dead+ </span>+ {% endif %}+ </div>+ <div>Event Loop:+ {% if task_info.event_loop.exists and task_info.event_loop.is_running %}+ <span class="text-success">+ {% icon "check-circle" size="sm" css_class="mr-1" %}Running ({{ task_info.event_loop.active_tasks }} active tasks)+ </span>+ {% elif task_info.event_loop.exists %}+ <span class="text-warning">+ {% icon "warning" size="sm" css_class="mr-1" %}Stopped+ </span>+ {% else %}+ <span class="text-danger">+ {% icon "warning" size="sm" css_class="mr-1" %}Dead+ </span>+ {% endif %}+ </div>++ {% if task_info.event_loop.task_details %}+ <div class="mt-1">+ <small>Tasks:</small>+ {% for task_detail in task_info.event_loop.task_details %}+ <div class="ml-2 small">+ - {{ task_detail.coro_name|default:"unknown" }}+ {% if task_detail.done %}(done){% elif task_detail.cancelled %}(cancelled){% else %}(running){% endif %}+ </div>+ {% endfor %}+ </div>+ {% endif %}+ </div>+ {% endfor %}+ </div>+ </div>+ </div>+ {% endif %}++</div>+{% endtimezone %}+{% endblock %}diff --git a/src/hi/apps/system/templates/system/tests/ui/home.html b/src/hi/apps/system/templates/system/tests/ui/home.htmlnew file mode 100644index 00000000..dfe8d80a--- /dev/null+++ b/src/hi/apps/system/templates/system/tests/ui/home.html@@ -0,0 +1,84 @@+{% extends "pages/base.html" %}+{% load icons %}++{% block head_title %}HI: System UI Tests{% endblock %}++{% block content %}+<div class="container-fluid m-4">+ <h2 class="text-info">System UI Tests</h2>++ <div class="row">+ <div class="col-md-6">+ <h3>Health Status</h3>+ <ul class="list-group">+ <li class="list-group-item">+ <a href="{% url 'system_test_ui_health_status' status_type='healthy' api_flag='no-api' %}" data-async="modal">+ {% icon "check-circle" size="sm" css_class="mr-2 text-success" %}+ Healthy Status+ </a>+ </li>+ <li class="list-group-item">+ <a href="{% url 'system_test_ui_health_status' status_type='warning' api_flag='no-api' %}" data-async="modal">+ {% icon "warning" size="sm" css_class="mr-2 text-warning" %}+ Warning Status+ </a>+ </li>+ <li class="list-group-item">+ <a href="{% url 'system_test_ui_health_status' status_type='error' api_flag='no-api' %}" data-async="modal">+ {% icon "times-circle" size="sm" css_class="mr-2 text-danger" %}+ Error Status+ </a>+ </li>+ <li class="list-group-item">+ <a href="{% url 'system_test_ui_health_status' status_type='disabled' api_flag='no-api' %}" data-async="modal">+ {% icon "info-circle" size="sm" css_class="mr-2 text-info" %}+ Disabled Status+ </a>+ </li>+ <li class="list-group-item">+ <a href="{% url 'system_test_ui_health_status' status_type='unknown' api_flag='no-api' %}" data-async="modal">+ {% icon "question-circle" size="sm" css_class="mr-2 text-secondary" %}+ Unknown Status+ </a>+ </li>+ </ul>+ </div>++ <div class="col-md-6">+ <h3>Aggregate (API) Health Status</h3>+ <ul class="list-group">+ <li class="list-group-item">+ <a href="{% url 'system_test_ui_health_status' status_type='healthy' api_flag='with-api' %}" data-async="modal">+ {% icon "check-circle" size="sm" css_class="mr-2 text-success" %}+ Healthy Status + APIs+ </a>+ </li>+ <li class="list-group-item">+ <a href="{% url 'system_test_ui_health_status' status_type='warning' api_flag='with-api' %}" data-async="modal">+ {% icon "warning" size="sm" css_class="mr-2 text-warning" %}+ Warning Status + APIs+ </a>+ </li>+ <li class="list-group-item">+ <a href="{% url 'system_test_ui_health_status' status_type='error' api_flag='with-api' %}" data-async="modal">+ {% icon "times-circle" size="sm" css_class="mr-2 text-danger" %}+ Error Status + APIs+ </a>+ </li>+ <li class="list-group-item">+ <a href="{% url 'system_test_ui_health_status' status_type='disabled' api_flag='with-api' %}" data-async="modal">+ {% icon "info-circle" size="sm" css_class="mr-2 text-info" %}+ Disabled Status + APIs+ </a>+ </li>+ <li class="list-group-item">+ <a href="{% url 'system_test_ui_health_status' status_type='unknown' api_flag='with-api' %}" data-async="modal">+ {% icon "question-circle" size="sm" css_class="mr-2 text-secondary" %}+ Unknown Status + APIs+ </a>+ </li>+ </ul>+ </div>+ </div>+</div>+{% endblock %}diff --git a/src/hi/apps/system/tests/synthetic_data.py b/src/hi/apps/system/tests/synthetic_data.pynew file mode 100644index 00000000..b79e90dd--- /dev/null+++ b/src/hi/apps/system/tests/synthetic_data.py@@ -0,0 +1,248 @@+"""+Synthetic data generation for system health status testing.++This module provides a class to generate realistic test data for health status+scenarios, supporting both regular HealthStatus and ApiHealthAggregator objects.+"""++from datetime import datetime, timedelta+from typing import Dict++import hi.apps.common.datetimeproxy as datetimeproxy+from hi.apps.system.api_health import ApiHealthStatus+from hi.apps.system.api_health_aggregator import ApiHealthAggregator+from hi.apps.system.provider_info import ProviderInfo+from hi.apps.system.enums import (+ HealthStatusType,+ ApiHealthStatusType,+ HealthAggregationRule+)+from hi.apps.system.health_status import HealthStatus+++class SystemSyntheticData:+ """+ Generator for synthetic system health status data for testing purposes.++ Provides methods to create realistic HealthStatus and ApiHealthAggregator+ objects with appropriate test data for all status types.+ """++ @classmethod+ def create_health_status_for_testing(cls, status_type: str, with_api_data: bool):+ """+ Create synthetic health status data for UI testing.++ Args:+ status_type: One of 'unknown', 'healthy', 'warning', 'error', 'disabled'+ with_api_data: Whether to create ApiHealthAggregator (True) or HealthStatus (False)++ Returns:+ HealthStatus or ApiHealthAggregator instance with appropriate test data+ """+ now = datetimeproxy.now()++ # Map status types to HealthStatusType enums+ status_map = {+ 'unknown': HealthStatusType.UNKNOWN,+ 'healthy': HealthStatusType.HEALTHY,+ 'warning': HealthStatusType.WARNING,+ 'error': HealthStatusType.ERROR,+ 'disabled': HealthStatusType.DISABLED,+ }++ status_enum = status_map.get(status_type, HealthStatusType.HEALTHY)++ # Base health status data+ base_data = {+ 'provider_id': 'provider-0',+ 'provider_name': 'Provider 0',+ 'status': status_enum,+ 'last_check': now,+ }++ # Customize data based on status type+ if status_type == 'unknown':+ base_data.update({+ 'heartbeat': None,+ 'error_message': "No health data available - service not yet initialized",+ })+ elif status_type == 'healthy':+ base_data.update({+ 'heartbeat': now,+ })+ elif status_type == 'warning':+ base_data.update({+ 'heartbeat': now - timedelta(minutes=2),+ 'error_message': "Temporary issue: Service experiencing intermittent connectivity issues",+ 'error_count': 3,+ })+ elif status_type == 'error':+ base_data.update({+ 'heartbeat': now - timedelta(hours=1),+ 'error_message': "Critical error: Service has stopped responding - manual intervention required",+ 'error_count': 8,+ })+ elif status_type == 'disabled':+ base_data.update({+ 'heartbeat': now,+ 'error_message': "Service has been manually disabled for scheduled maintenance",+ })++ if with_api_data:+ # Create ApiHealthAggregator with sample API sources+ api_status_map = cls._create_sample_api_status_map(status_type, now)+ aggregation_rule = cls._get_aggregation_rule_for_status(status_type)++ return ApiHealthAggregator(+ api_status_map=api_status_map,+ aggregation_rule=aggregation_rule,+ **base_data+ )+ else:+ # Create regular HealthStatus+ return HealthStatus(**base_data)++ @classmethod+ def get_status_label(cls, status_type: str) -> str:+ """Get display label for status type."""+ labels = {+ 'unknown': 'Unknown Status',+ 'healthy': 'Healthy Status',+ 'warning': 'Warning Status',+ 'error': 'Error Status',+ 'disabled': 'Disabled Status',+ }+ return labels.get(status_type, 'Health Status')++ @classmethod+ def _create_sample_api_status_map(cls, status_type: str, now: datetime) -> Dict[ProviderInfo, ApiHealthStatus]:+ """Create sample API sources based on status type."""+ if status_type == 'healthy':+ return {+ ProviderInfo(provider_name="Primary API", provider_id="primary_api"): ApiHealthStatus(+ provider_name="Primary API",+ provider_id="primary_api",+ status=ApiHealthStatusType.HEALTHY,+ last_success=now,+ total_calls=1247,+ total_failures=5,+ consecutive_failures=0,+ average_response_time=0.23,+ last_response_time=0.21+ ),+ ProviderInfo(provider_name="Secondary API", provider_id="secondary_api"): ApiHealthStatus(+ provider_name="Secondary API",+ provider_id="secondary_api",+ status=ApiHealthStatusType.HEALTHY,+ last_success=now - timedelta(seconds=10),+ total_calls=892,+ total_failures=3,+ consecutive_failures=0,+ average_response_time=0.45,+ last_response_time=0.38+ )+ }++ elif status_type == 'warning':+ return {+ ProviderInfo(provider_name="Primary API", provider_id="primary_api"): ApiHealthStatus(+ provider_name="Primary API",+ provider_id="primary_api",+ status=ApiHealthStatusType.HEALTHY,+ last_success=now,+ total_calls=1247,+ total_failures=15,+ consecutive_failures=0,+ average_response_time=0.23,+ last_response_time=0.21+ ),+ ProviderInfo(provider_name="Secondary API", provider_id="secondary_api"): ApiHealthStatus(+ provider_name="Secondary API",+ provider_id="secondary_api",+ status=ApiHealthStatusType.DEGRADED,+ last_success=now - timedelta(minutes=3),+ total_calls=892,+ total_failures=67,+ consecutive_failures=2,+ average_response_time=1.45,+ last_response_time=2.31+ ),+ ProviderInfo(provider_name="Backup API", provider_id="backup_api"): ApiHealthStatus(+ provider_name="Backup API",+ provider_id="backup_api",+ status=ApiHealthStatusType.HEALTHY,+ last_success=now - timedelta(seconds=30),+ total_calls=456,+ total_failures=8,+ consecutive_failures=0,+ average_response_time=0.67,+ last_response_time=0.52+ )+ }++ elif status_type == 'error':+ return {+ ProviderInfo(provider_name="Primary API", provider_id="primary_api"): ApiHealthStatus(+ provider_name="Primary API",+ provider_id="primary_api",+ status=ApiHealthStatusType.FAILING,+ last_success=now - timedelta(hours=2),+ total_calls=1247,+ total_failures=425,+ consecutive_failures=15,+ average_response_time=5.23,+ last_response_time=None+ ),+ ProviderInfo(provider_name="Secondary API", provider_id="secondary_api"): ApiHealthStatus(+ provider_name="Secondary API",+ provider_id="secondary_api",+ status=ApiHealthStatusType.UNAVAILABLE,+ last_success=now - timedelta(hours=6),+ total_calls=892,+ total_failures=289,+ consecutive_failures=25,+ average_response_time=None,+ last_response_time=None+ )+ }++ elif status_type == 'disabled':+ return {+ ProviderInfo(provider_name="Maintenance API", provider_id="maintenance_api"): ApiHealthStatus(+ provider_name="Maintenance API",+ provider_id="maintenance_api",+ status=ApiHealthStatusType.HEALTHY,+ last_success=now,+ total_calls=45,+ total_failures=0,+ consecutive_failures=0,+ average_response_time=0.15,+ last_response_time=0.12+ )+ }++ else: # unknown+ return {+ ProviderInfo(provider_name="Unknown API", provider_id="unknown_api"): ApiHealthStatus(+ provider_name="Unknown API",+ provider_id="unknown_api",+ status=ApiHealthStatusType.UNKNOWN,+ last_success=None,+ total_calls=0,+ total_failures=0,+ consecutive_failures=0,+ average_response_time=None,+ last_response_time=None+ )+ }++ @classmethod+ def _get_aggregation_rule_for_status(cls, status_type: str) -> HealthAggregationRule:+ """Get appropriate aggregation rule based on status type."""+ if status_type == 'error':+ return HealthAggregationRule.ANY_SOURCE_HEALTHY+ elif status_type == 'warning':+ return HealthAggregationRule.MAJORITY_SOURCES_HEALTHY+ else:+ return HealthAggregationRule.ALL_SOURCES_HEALTHYdiff --git a/src/hi/apps/system/tests/ui/__init__.py b/src/hi/apps/system/tests/ui/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/system/tests/ui/urls.py b/src/hi/apps/system/tests/ui/urls.pynew file mode 100644index 00000000..457f05da--- /dev/null+++ b/src/hi/apps/system/tests/ui/urls.py@@ -0,0 +1,12 @@+from django.urls import re_path+from . import views++urlpatterns = [+ re_path(r'^$',+ views.SystemTestUiHomeView.as_view(),+ name='system_test_ui'),++ re_path(r'^health/(?P<status_type>[\w-]+)/(?P<api_flag>[\w-]+)/$',+ views.SystemTestUiHealthStatusView.as_view(),+ name='system_test_ui_health_status'),+]diff --git a/src/hi/apps/system/tests/ui/views.py b/src/hi/apps/system/tests/ui/views.pynew file mode 100644index 00000000..d703a661--- /dev/null+++ b/src/hi/apps/system/tests/ui/views.py@@ -0,0 +1,61 @@+from django.http import Http404+from django.shortcuts import render+from django.views.generic import View++from hi.apps.system.enums import HealthStatusType+from hi.apps.system.tests.synthetic_data import SystemSyntheticData+++class SystemTestUiHomeView(View):++ def get(self, request, *args, **kwargs):+ context = {+ 'app_name': 'monitor',+ }+ return render(request, 'system/tests/ui/home.html', context)+++class SystemTestUiHealthStatusView(View):+ """+ View for testing health status modals with various synthetic data scenarios.+ Supports all HealthStatusType values with both regular HealthStatus and ApiHealthAggregator data.++ URL patterns:+ - /test/health-status/<status_type>/<api_flag>/+ - status_type: unknown, healthy, warning, error, disabled+ - api_flag: with-api, no-api+ """++ def get(self, request, *args, **kwargs):+ status_type = kwargs.get('status_type', 'healthy')+ api_flag = kwargs.get('api_flag', 'no-api')++ # Validate parameters using enum parsing+ try:+ # Convert status_type to HealthStatusType enum+ status_enum = HealthStatusType.from_name(status_type.upper())+ status_type = str(status_enum)+ except (ValueError, AttributeError):+ raise Http404(f"Invalid status type: {status_type}")++ # Validate api_flag+ if api_flag not in ['with-api', 'no-api', 'withapi', 'noapi']:+ raise Http404(f"Invalid api flag: {api_flag}")++ with_api_data = api_flag in ['with-api', 'withapi']++ # Create health status for the requested scenario+ health_status = SystemSyntheticData.create_health_status_for_testing(+ status_type,+ with_api_data = with_api_data,+ )+ if with_api_data:+ template_name = 'system/modals/aggregate_health_status.html'+ else:+ template_name = 'system/modals/health_status.html'++ # Render template with scenario data (matching existing modal template expectations)+ context = {+ 'health_status': health_status,+ }+ return render(request, template_name, context)diff --git a/src/hi/apps/system/urls.py b/src/hi/apps/system/urls.pynew file mode 100644index 00000000..ec9cc938--- /dev/null+++ b/src/hi/apps/system/urls.py@@ -0,0 +1,15 @@+from django.urls import re_path++from . import views+++urlpatterns = [++ re_path( r'^info$',+ views.SystemInfoView.as_view(),+ name = 'system_info' ),++ re_path( r'^health/<str:provider_id>$',+ views.SystemHealthStatusView.as_view(),+ name = 'system_health_status' ),+]diff --git a/src/hi/apps/system/views.py b/src/hi/apps/system/views.pynew file mode 100644index 00000000..58ba07b1--- /dev/null+++ b/src/hi/apps/system/views.py@@ -0,0 +1,40 @@+import logging++from django.http import Http404++from hi.hi_async_view import HiModalView++from hi.apps.common.asyncio_utils import BackgroundTaskMonitor+from hi.apps.config.enums import ConfigPageType+from hi.apps.config.views import ConfigPageView++logger = logging.getLogger(__name__)+++class SystemInfoView( ConfigPageView ):++ @property+ def config_page_type(self) -> ConfigPageType:+ return ConfigPageType.SYSTEM_INFO++ def get_main_template_name( self ) -> str:+ return 'system/panes/system_info.html'++ def get_main_template_context( self, request, *args, **kwargs ):+ return {+ 'async_diagnostics': BackgroundTaskMonitor.get_background_task_status(),+ }+++class SystemHealthStatusView(HiModalView):+ """View for displaying monitor health status in a modal."""++ def get_template_name(self) -> str:+ return 'system/modals/system_health_status.html'++ def get(self, request, *args, **kwargs):+ provider_id = kwargs.get('provider_id')+ if not provider_id:+ raise Http404("Provider ID is required")++ raise NotImplementedError("Health status integration not yet implemented")diff --git a/src/hi/apps/weather/monitors.py b/src/hi/apps/weather/monitors.pyindex 1565cadd..65c9027f 100644--- a/src/hi/apps/weather/monitors.py+++ b/src/hi/apps/weather/monitors.py@@ -6,9 +6,11 @@ from hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom hi.apps.alert.alert_mixins import AlertMixinfrom hi.apps.config.settings_mixins import SettingsMixin+from hi.apps.system.provider_info import ProviderInfofrom .weather_settings_helper import WeatherSettingsHelperfrom .weather_source_discovery import WeatherSourceDiscovery+from .weather_source_manager import WeatherSourceManagerlogger = logging.getLogger(__name__)@@ -40,8 +42,20 @@ class WeatherMonitor( PeriodicMonitor, AlertMixin, SettingsMixin ):continueself._weather_data_source_instance_list = discovered_sources+ WeatherSourceManager().add_api_health_status_provider_multi(+ api_health_status_provider_sequence = discovered_sources,+ )return+ @classmethod+ def get_provider_info(cls) -> ProviderInfo:+ """ Subclasses should override with something more meaningful. """+ return ProviderInfo(+ provider_id = 'hi.apps.weather',+ provider_name = 'Weather Monitor',+ description = '',+ )+async def do_work(self):# To help guard against hitting API rate limits, hold off on@@ -55,8 +69,10 @@ class WeatherMonitor( PeriodicMonitor, AlertMixin, SettingsMixin ):task_list = list()for weather_data_source in self._weather_data_source_instance_list:- # Only fetch from enabled weather sources- if await self._settings_helper.is_weather_source_enabled_async(weather_data_source.id):+ is_enabled = await self._settings_helper.is_weather_source_enabled_async(+ weather_data_source.id+ )+ if is_enabled:task = asyncio.create_task( weather_data_source.fetch() )task_list.append( task )else: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 5804279f..4c7be228 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@@ -23,11 +23,20 @@ logging.disable(logging.CRITICAL)class MockWeatherDataSource(WeatherDataSource):"""Mock weather data source for testing."""- def __init__(self, source_id="mock_source"):+ @classmethod+ def weather_source_id(cls):+ return 'mock_source'++ @classmethod+ def weather_source_label(cls):+ return 'Mock Weather Source'++ @classmethod+ def weather_source_abbreviation(cls):+ return 'MOCK'++ def __init__(self):super().__init__(- id=source_id,- label="Mock Weather Source",- abbreviation="MWS",priority=1,requests_per_day_limit=1000,requests_per_polling_interval=10,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 589c4203..15f18c55 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@@ -23,11 +23,20 @@ logging.disable(logging.CRITICAL)class MockWeatherDataSource(WeatherDataSource):"""Mock weather data source for testing."""- def __init__(self, source_id="mock_source"):+ @classmethod+ def weather_source_id(cls):+ return 'mock_source'++ @classmethod+ def weather_source_label(cls):+ return 'Mock Weather Source'++ @classmethod+ def weather_source_abbreviation(cls):+ return 'MOCK'++ def __init__(self):super().__init__(- id=source_id,- label="Mock Weather Source",- abbreviation="MWS",priority=1,requests_per_day_limit=1000,requests_per_polling_interval=10,diff --git a/src/hi/apps/weather/views.py b/src/hi/apps/weather/views.pyindex 4b6f6498..beb0ef41 100644--- a/src/hi/apps/weather/views.py+++ b/src/hi/apps/weather/views.py@@ -2,6 +2,7 @@ import loggingfrom hi.hi_async_view import HiModalViewfrom .weather_mixins import WeatherMixin+from .weather_source_manager import WeatherSourceManagerfrom .weather_sources.sunrise_sunset_org import SunriseSunsetOrgfrom .weather_sources.usno import USNO@@ -80,3 +81,15 @@ class HistoryView( HiModalView, WeatherMixin ):}return self.modal_response( request, context )++class WeatherSourceStatusView( HiModalView ):++ def get_template_name( self ) -> str:+ return 'system/modals/aggregate_health_status.html'++ def get( self, request, *args, **kwargs ):+ health_status = WeatherSourceManager().health_status+ context = {+ 'health_status': health_status,+ }+ return self.modal_response( request, context )diff --git a/src/hi/apps/weather/weather_data_source.py b/src/hi/apps/weather/weather_data_source.pyindex 990f638d..13f7ef03 100644--- a/src/hi/apps/weather/weather_data_source.py+++ b/src/hi/apps/weather/weather_data_source.py@@ -1,3 +1,4 @@+from abc import abstractmethodfrom datetime import datetimeimport loggingimport redis@@ -7,18 +8,37 @@ from django.conf import settingsimport hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.common.redis_client import get_redis_clientfrom hi.apps.console.console_helper import ConsoleSettingsHelper+from hi.apps.system.api_health_status_provider import ApiHealthStatusProvider+from hi.apps.system.provider_info import ProviderInfofrom hi.apps.weather.transient_models import DataPointSourcelogger = logging.getLogger(__name__)-class WeatherDataSource:+class WeatherDataSource( ApiHealthStatusProvider ):TRACE = FalseFORCE_CAN_POLL = False # For debugging++ @classmethod+ @abstractmethod+ def weather_source_id(cls):+ pass++ @classmethod+ @abstractmethod+ def weather_source_label(cls):+ pass++ @classmethod+ @abstractmethod+ def weather_source_abbreviation(cls):+ pass+ @abstractmethodasync def get_data(self):- raise NotImplementedError('Subclasses must override this.')+ """ Main method periodically called to fetch data """+ passdef requires_api_key(self) -> bool:"""Override in subclasses that require an API key."""@@ -29,16 +49,13 @@ class WeatherDataSource:return Truedef __init__( self,- id : str,- label : str,- abbreviation : str,priority : int,requests_per_day_limit : int,requests_per_polling_interval : int,min_polling_interval_secs : int ):- self._id = id- self._label = label- self._abbreviation = abbreviation+ self._id = self.weather_source_id()+ self._label = self.weather_source_label()+ self._abbreviation = self.weather_source_abbreviation()self._priority = priority # Lower numbers are higher priorityself._data_point_source = DataPointSource(id = self._id,@@ -121,6 +138,15 @@ class WeatherDataSource:"""Check if weather data caching is enabled."""return self._get_weather_settings_helper().is_weather_cache_enabled()+ @classmethod+ def get_api_provider_info(cls) -> ProviderInfo:+ """ Subclasses should override with something more meaningful. """+ return ProviderInfo(+ provider_id = cls.weather_source_id(),+ provider_name = cls.weather_source_label(),+ description = f'{cls.weather_source_label()} ({cls.weather_source_abbreviation})',+ )+async def fetch(self):can_fetch = self.can_fetch()diff --git a/src/hi/apps/weather/weather_source_manager.py b/src/hi/apps/weather/weather_source_manager.pynew file mode 100644index 00000000..0ad50a08--- /dev/null+++ b/src/hi/apps/weather/weather_source_manager.py@@ -0,0 +1,19 @@+from hi.apps.common.singleton import Singleton+from hi.apps.system.aggregate_health_provider import AggregateHealthProvider+from hi.apps.system.provider_info import ProviderInfo+++class WeatherSourceManager( Singleton, AggregateHealthProvider ):++ def __init_singleton__(self):+ return++ @classmethod+ def get_provider_info(cls) -> ProviderInfo:+ """ Subclasses should override with something more meaningful. """+ return ProviderInfo(+ provider_id = 'hi.apps.weather.weather_sources',+ provider_name = 'Weather API Monitor',+ description = '',+ )+diff --git a/src/hi/apps/weather/weather_sources/nws.py b/src/hi/apps/weather/weather_sources/nws.pyindex a5da818b..baf6f82d 100644--- a/src/hi/apps/weather/weather_sources/nws.py+++ b/src/hi/apps/weather/weather_sources/nws.py@@ -53,12 +53,21 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):ALERTS_DATA_CACHE_EXPIRY_SECS = 10 * 60 # Alerts can change frequently, short cacheSKIP_CACHE = False # For debugging++ @classmethod+ def weather_source_id(cls):+ return 'nws'++ @classmethod+ def weather_source_label(cls):+ return 'National Weather Service'++ @classmethod+ def weather_source_abbreviation(cls):+ return 'NWS'def __init__( self ):super().__init__(- id = 'nws',- label = 'National Weather Service',- abbreviation = 'NWS',priority = 1,requests_per_day_limit = 432,requests_per_polling_interval = 3,@@ -149,6 +158,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):returndef get_current_conditions( self, geographic_location : GeographicLocation ) -> WeatherConditionsData:+station = self._get_station( geographic_location = geographic_location )observations_data = self._get_observations_data( station = station )return self._parse_observation_data(@@ -498,7 +508,13 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):return observations_datadef _get_observations_data_from_api( self, station : Station ) -> Dict[ str, Any ]:- observations_response = requests.get( station.observations_url, headers = self._headers, timeout = self.get_api_timeout() )+ with self.api_call_context( 'nws_observations' ):+ observations_response = requests.get(+ station.observations_url,+ headers = self._headers,+ timeout = self.get_api_timeout(),+ )+observations_response.raise_for_status()observations_data = observations_response.json()return observations_data@@ -524,7 +540,12 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):return forecast_hourly_datadef _get_forecast_hourly_data_from_api( self, station : Station ) -> Dict[ str, Any ]:- forecast_hourly_response = requests.get( station.forecast_url, headers = self._headers, timeout = self.get_api_timeout() )+ with self.api_call_context( 'nws_forecast_hourly' ):+ forecast_hourly_response = requests.get(+ station.forecast_url,+ headers = self._headers,+ timeout = self.get_api_timeout(),+ )forecast_hourly_response.raise_for_status()forecast_hourly_data = forecast_hourly_response.json()return forecast_hourly_data@@ -550,7 +571,12 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):return forecast_12h_datadef _get_forecast_12h_data_from_api( self, station : Station ) -> Dict[ str, Any ]:- forecast_12h_response = requests.get( station.forecast_url, headers = self._headers, timeout = self.get_api_timeout() )+ with self.api_call_context( 'nws_forecast' ):+ forecast_12h_response = requests.get(+ station.forecast_url,+ headers = self._headers,+ timeout = self.get_api_timeout(),+ )forecast_12h_response.raise_for_status()forecast_12h_data = forecast_12h_response.json()return forecast_12h_data@@ -586,7 +612,13 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):# Can cache this data, expires 12 hours-ish (they do not change often)points_data = self._get_points_data( geographic_location = geographic_location )stations_url = points_data['properties']['observationStations']- stations_response = requests.get( stations_url, headers = self._headers, timeout = self.get_api_timeout() )++ with self.api_call_context( 'nws_stations' ):+ stations_response = requests.get(+ stations_url,+ headers = self._headers,+ timeout = self.get_api_timeout(),+ )stations_response.raise_for_status()stations_data = stations_response.json()return stations_data@@ -613,7 +645,13 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):def _get_points_data_from_api( self, geographic_location : GeographicLocation ) -> Dict[ str, Any ]:# Can cache this data, expires 12 hours-ish (they do not change often)points_url = f'{self.BASE_URL}points/{geographic_location.latitude},{geographic_location.longitude}'- points_response = requests.get( points_url, headers = self._headers, timeout = self.get_api_timeout() )++ with self.api_call_context( 'nws_points' ):+ points_response = requests.get(+ points_url,+ headers = self._headers,+ timeout = self.get_api_timeout(),+ )points_response.raise_for_status()points_data = points_response.json()return points_data@@ -1031,7 +1069,12 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):alerts_url = f'{self.BASE_URL}alerts/active?point={geographic_location.latitude},{geographic_location.longitude}'logger.debug(f'NWS alerts API request: {alerts_url}')- response = requests.get( alerts_url, headers=self._headers, timeout = self.get_api_timeout() )+ with self.api_call_context( 'nws_alerts' ):+ response = requests.get(+ alerts_url,+ headers=self._headers,+ timeout = self.get_api_timeout(),+ )response.raise_for_status()alerts_data = response.json()return alerts_datadiff --git a/src/hi/apps/weather/weather_sources/openmeteo.py b/src/hi/apps/weather/weather_sources/openmeteo.pyindex cb9f6931..13e0e462 100644--- a/src/hi/apps/weather/weather_sources/openmeteo.py+++ b/src/hi/apps/weather/weather_sources/openmeteo.py@@ -40,11 +40,20 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):SKIP_CACHE = False # For debugging+ @classmethod+ def weather_source_id(cls):+ return 'openmeteo'++ @classmethod+ def weather_source_label(cls):+ return 'Open-Meteo'++ @classmethod+ def weather_source_abbreviation(cls):+ return 'OpenMeteo'+def __init__(self):super().__init__(- id = 'openmeteo',- label = 'Open-Meteo',- abbreviation = 'OpenMeteo',priority = 2, # Lower priority than NWSrequests_per_day_limit = 10000, # Open-Meteo is very generousrequests_per_polling_interval = 5,@@ -735,7 +744,12 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):f"hourly=temperature_2m,relativehumidity_2m,dewpoint_2m,precipitation,pressure_msl&"f"units=metric")- response = requests.get( url, headers = self._headers, timeout = self.get_api_timeout() )+ with self.api_call_context( 'openmeteo_current' ):+ response = requests.get(+ url,+ headers = self._headers,+ timeout = self.get_api_timeout(),+ )response.raise_for_status()current_data = response.json()return current_data@@ -769,7 +783,12 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):f"forecast_days=7&"f"units=metric")- response = requests.get( url, headers = self._headers, timeout = self.get_api_timeout() )+ with self.api_call_context( 'openmeteo_forecast_hourly' ):+ response = requests.get(+ url,+ headers = self._headers,+ timeout = self.get_api_timeout(),+ )response.raise_for_status()forecast_data = response.json()return forecast_data@@ -803,7 +822,12 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):f"forecast_days=14&"f"units=metric")- response = requests.get( url, headers = self._headers, timeout = self.get_api_timeout() )+ with self.api_call_context( 'openmeteo_forecast_daily' ):+ response = requests.get(+ url,+ headers = self._headers,+ timeout = self.get_api_timeout(),+ )response.raise_for_status()forecast_data = response.json()return forecast_data@@ -848,7 +872,12 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):f"daily=weathercode,temperature_2m_max,temperature_2m_min,precipitation_sum&"f"units=metric")- response = requests.get( url, headers = self._headers, timeout = self.get_api_timeout() )+ with self.api_call_context( 'openmeteo_history' ):+ response = requests.get(+ url,+ headers = self._headers,+ timeout = self.get_api_timeout(),+ )response.raise_for_status()historical_data = response.json()return historical_datadiff --git a/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py b/src/hi/apps/weather/weather_sources/sunrise_sunset_org.pyindex d53408e7..45e30959 100644--- a/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py+++ b/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py@@ -42,11 +42,20 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):SKIP_CACHE = False # For debugging+ @classmethod+ def weather_source_id(cls):+ return cls.SOURCE_ID++ @classmethod+ def weather_source_label(cls):+ return 'Sunrise-Sunset.org'++ @classmethod+ def weather_source_abbreviation(cls):+ return 'SunriseSunset'+def __init__(self):super().__init__(- id = self.SOURCE_ID,- label = 'Sunrise-Sunset.org',- abbreviation = 'SunriseSunset',priority = 3, # Lower priority than NWS and OpenMeteorequests_per_day_limit = 1000, # Conservative estimate for "reasonable" usagerequests_per_polling_interval = 1, # Only need one request per day per location@@ -269,7 +278,12 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):f"date={target_date.isoformat()}&"f"formatted=0") # Get ISO format times- response = requests.get( url, headers = self._headers, timeout = self.get_api_timeout() )+ with self.api_call_context( 'sunrise_sunset' ):+ response = requests.get(+ url,+ headers = self._headers,+ timeout = self.get_api_timeout(),+ )response.raise_for_status()api_data = response.json()return api_datadiff --git a/src/hi/apps/weather/weather_sources/usno.py b/src/hi/apps/weather/weather_sources/usno.pyindex 7d83fe26..1f13d620 100644--- a/src/hi/apps/weather/weather_sources/usno.py+++ b/src/hi/apps/weather/weather_sources/usno.py@@ -34,7 +34,7 @@ class USNOStatus(Enum):INVALID_REQUEST = "invalid_request"-class USNO(WeatherDataSource, WeatherMixin):+class USNO( WeatherDataSource, WeatherMixin ):"""US Naval Observatory Astronomical Applications Department API integration.@@ -51,11 +51,20 @@ class USNO(WeatherDataSource, WeatherMixin):SKIP_CACHE = False # For debugging+ @classmethod+ def weather_source_id(cls):+ return cls.SOURCE_ID++ @classmethod+ def weather_source_label(cls):+ return 'US Naval Observatory'++ @classmethod+ def weather_source_abbreviation(cls):+ return 'USNO'+def __init__(self):super().__init__(- id = self.SOURCE_ID,- label = 'US Naval Observatory',- abbreviation = 'USNO',priority = 2, # Higher priority than sunrise-sunset.org due to moon phase datarequests_per_day_limit = 1000, # Conservative estimaterequests_per_polling_interval = 1, # Only need one request per day per location@@ -385,7 +394,12 @@ class USNO(WeatherDataSource, WeatherMixin):logger.debug(f'USNO API request: {url}')- response = requests.get( url, headers = self._headers, timeout = self.get_api_timeout() )+ with self.api_call_context( 'usno' ):+ response = requests.get(+ url,+ headers = self._headers,+ timeout = self.get_api_timeout(),+ )response.raise_for_status()api_data = response.json()return api_datadiff --git a/src/hi/integrations/enums.py b/src/hi/integrations/enums.pyindex 4328a96e..2e9c071e 100644--- a/src/hi/integrations/enums.py+++ b/src/hi/integrations/enums.py@@ -22,30 +22,3 @@ class IntegrationAttributeType( LabeledEnum ):self.is_required = is_requiredself.initial_value = initial_valuereturn---class IntegrationHealthStatusType( LabeledEnum ):-- HEALTHY = ( 'Healthy', '' )- CONFIG_ERROR = ( 'Config Error', '' )- CONNECTION_ERROR = ( 'Connection Error', '' )- TEMPORARY_ERROR = ( 'Temporary Error', '' )- DISABLED = ( 'Disabled', '' )- UNKNOWN = ( 'Unknown', '' )-- @property- def is_error(self) -> bool:- return self in (- IntegrationHealthStatusType.CONFIG_ERROR,- IntegrationHealthStatusType.CONNECTION_ERROR,- IntegrationHealthStatusType.TEMPORARY_ERROR- )-- @property- def is_critical(self) -> bool:- return self in (- IntegrationHealthStatusType.CONFIG_ERROR,- IntegrationHealthStatusType.CONNECTION_ERROR- )--diff --git a/src/hi/integrations/integration_attribute_edit_context.py b/src/hi/integrations/integration_attribute_edit_context.pyindex 62c6452e..115daa98 100644--- a/src/hi/integrations/integration_attribute_edit_context.py+++ b/src/hi/integrations/integration_attribute_edit_context.py@@ -12,11 +12,11 @@ from django.forms import ModelForm, BaseInlineFormSetfrom hi.apps.attribute.edit_context import AttributeItemEditContextfrom hi.apps.attribute.forms import AttributeUploadFormfrom hi.apps.attribute.models import AttributeModel+from hi.apps.system.health_status import HealthStatusfrom .forms import IntegrationAttributeRegularFormSetfrom .integration_data import IntegrationDatafrom .models import Integration, IntegrationAttribute-from .transient_models import IntegrationHealthStatusclass IntegrationAttributeItemEditContext(AttributeItemEditContext):@@ -29,10 +29,10 @@ class IntegrationAttributeItemEditContext(AttributeItemEditContext):def __init__( self,integration_data : IntegrationData,- health_status : IntegrationHealthStatus = None,- update_button_label : str = 'UPDATE',- suppress_history : bool = False,- show_secrets : bool = False,+ health_status : HealthStatus = None,+ update_button_label : str = 'UPDATE',+ suppress_history : bool = False,+ show_secrets : bool = False,) -> None:"""Initialize context for Integration attribute editing.diff --git a/src/hi/integrations/integration_gateway.py b/src/hi/integrations/integration_gateway.pyindex 1d748b0c..dd464a95 100644--- a/src/hi/integrations/integration_gateway.py+++ b/src/hi/integrations/integration_gateway.py@@ -4,11 +4,15 @@ from hi.apps.entity.models import Entityfrom hi.apps.entity.transient_models import VideoStreamfrom hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom hi.apps.sense.transient_models import SensorResponse+from hi.apps.system.health_status import HealthStatusfrom .integration_controller import IntegrationControllerfrom .integration_manage_view_pane import IntegrationManageViewPanefrom .models import IntegrationAttribute-from .transient_models import IntegrationMetaData, IntegrationHealthStatus, IntegrationValidationResult+from .transient_models import (+ IntegrationMetaData,+ IntegrationValidationResult,+)class IntegrationGateway:@@ -36,19 +40,19 @@ class IntegrationGateway:"""raise NotImplementedError('Subclasses must override this method')- def get_health_status(self) -> IntegrationHealthStatus:+ def get_health_status(self) -> HealthStatus:raise NotImplementedError('Subclasses must override this method')- def validate_configuration(self, integration_attributes: List[IntegrationAttribute]) -> IntegrationValidationResult:- """Validate integration configuration. e.g., by testing API connectivity-- Returns:- IntegrationValidationResult with validation status and any error information- """+ def validate_configuration(+ self,+ integration_attributes: List[IntegrationAttribute]+ ) -> IntegrationValidationResult:raise NotImplementedError('Subclasses must override this method')def get_entity_video_stream(self, entity: Entity) -> Optional[VideoStream]:return None- def get_sensor_response_video_stream(self, sensor_response: SensorResponse) -> Optional[VideoStream]:+ def get_sensor_response_video_stream(+ self,+ sensor_response: SensorResponse) -> Optional[VideoStream]:return Nonediff --git a/src/hi/integrations/templates/integrations/modals/integration_health_status.html b/src/hi/integrations/templates/integrations/modals/integration_health_status.htmldeleted file mode 100644index 6c999041..00000000--- a/src/hi/integrations/templates/integrations/modals/integration_health_status.html+++ /dev/null@@ -1,181 +0,0 @@-{% extends "modals/action_done.html" %}-{% load icons %}-{% load tz %}--{% block title_text %}-{{ integration_data.label }} Health Status-{% endblock %}--{% block body %}-{% timezone USER_TIMEZONE %}--<div class="mb-3">- <div class="d-flex align-items-center mb-2">- <span class="badge badge-lg {% if health_status.is_healthy %}badge-success{% elif health_status.is_critical %}badge-danger{% else %}badge-warning{% endif %} mr-3">- {% if health_status.is_healthy %}- {% icon "check-circle" size="lg" css_class="mr-1" %}{{ health_status.status_display }}- {% elif health_status.is_critical %}- {% icon "warning" size="lg" css_class="mr-1" %}{{ health_status.status_display }}- {% else %}- {% icon "info-circle" size="lg" css_class="mr-1" %}{{ health_status.status_display }}- {% endif %}- </span>- </div>-</div>--<div class="row">- <div class="col-sm-3"><strong>Last Check:</strong></div>- <div class="col-sm-9">{{ health_status.last_check|localtime|date:"M j, Y H:i:s" }}</div>-</div>--{% if health_status.error_message %}-<div class="row mt-2">- <div class="col-sm-3"><strong>Error Details:</strong></div>- <div class="col-sm-9">- <div class="alert alert-{% if health_status.is_critical %}danger{% else %}warning{% endif %} p-2">- {{ health_status.error_message }}- </div>- </div>-</div>-{% endif %}--{% if health_status.error_count > 1 %}-<div class="row mt-2">- <div class="col-sm-3"><strong>Error Count:</strong></div>- <div class="col-sm-9">{{ health_status.error_count }}</div>-</div>-{% endif %}--{% if health_status.monitor_heartbeat %}-<div class="row mt-3">- <div class="col-sm-12">- <h6 class="mb-2">Enhanced Monitoring</h6>- </div>- <div class="col-sm-3"><strong>Monitor Status:</strong></div>- <div class="col-sm-9">- {% if health_status.monitor_heartbeat_age_seconds < 30 %}- <span class="text-success">- {% icon "check-circle" size="sm" css_class="mr-1" %}Active- </span>- (last seen {{ health_status.monitor_heartbeat|localtime|date:"H:i:s" }})- {% else %}- <span class="text-warning">- {% icon "warning" size="sm" css_class="mr-1" %}Stale- </span>- ({{ health_status.monitor_heartbeat_age_seconds|floatformat:0 }} seconds ago)- {% endif %}- </div>-</div>--{% if health_status.last_api_success %}-<div class="row mt-2">- <div class="col-sm-3"><strong>Last API Success:</strong></div>- <div class="col-sm-9">{{ health_status.last_api_success|localtime|date:"H:i:s" }}</div>-</div>-{% endif %}--{% if health_status.api_metrics %}-<div class="row mt-2">- <div class="col-sm-3"><strong>API Metrics:</strong></div>- <div class="col-sm-9">- <div class="small">- <div>Total calls: {{ health_status.api_metrics.total_calls }}</div>- {% if health_status.api_metrics.total_failures > 0 %}- <div class="text-warning">- {% icon "warning" size="sm" css_class="mr-1" %}- Failures: {{ health_status.api_metrics.total_failures }}- ({{ health_status.api_metrics.consecutive_failures }} consecutive)- </div>- {% endif %}- {% if health_status.api_metrics.last_response_time %}- <div>- Last response time: {{ health_status.api_metrics.last_response_time|floatformat:2 }}s- </div>- {% endif %}- </div>- </div>-</div>-{% endif %}--{% if health_status.async_diagnostics %}-<div class="row mt-2">- <div class="col-sm-3"><strong>Background Tasks:</strong></div>- <div class="col-sm-9">- <div class="small">- <div>Main Thread: {{ health_status.async_diagnostics.main_thread.name }}</div>- <div>Active Threads: {{ health_status.async_diagnostics.current_thread.active_count }}</div>-- {% for task_name, task_info in health_status.async_diagnostics.background_tasks.items %}- <div class="mt-1 p-1 border-left border-info">- <div><strong>{{ task_name }}</strong></div>- <div>Thread:- {% if task_info.thread.is_alive %}- <span class="text-success">- {% icon "check-circle" size="sm" css_class="mr-1" %}{{ task_info.thread_name }}- </span>- {% else %}- <span class="text-danger">- {% icon "warning" size="sm" css_class="mr-1" %}Dead- </span>- {% endif %}- </div>- <div>Event Loop:- {% if task_info.event_loop.exists and task_info.event_loop.is_running %}- <span class="text-success">- {% icon "check-circle" size="sm" css_class="mr-1" %}Running ({{ task_info.event_loop.active_tasks }} active tasks)- </span>- {% elif task_info.event_loop.exists %}- <span class="text-warning">- {% icon "warning" size="sm" css_class="mr-1" %}Stopped- </span>- {% else %}- <span class="text-danger">- {% icon "warning" size="sm" css_class="mr-1" %}Dead- </span>- {% endif %}- </div>-- {% if task_info.event_loop.task_details %}- <div class="mt-1">- <small>Tasks:</small>- {% for task_detail in task_info.event_loop.task_details %}- <div class="ml-2 small">- - {{ task_detail.coro_name|default:"unknown" }}- {% if task_detail.done %}(done){% elif task_detail.cancelled %}(cancelled){% else %}(running){% endif %}- </div>- {% endfor %}- </div>- {% endif %}- </div>- {% endfor %}- </div>- </div>-</div>-{% endif %}-{% endif %}--{% if health_status.is_healthy %}-<div class="alert alert-success mt-3">- <p class="mb-0">- {% icon "check-circle" size="sm" css_class="mr-2" %}- This integration is operating normally. All configuration settings are valid and the connection to the external service is working properly.- </p>-</div>-{% elif health_status.is_critical %}-<div class="alert alert-danger mt-3">- <p class="mb-0">- {% icon "warning" size="sm" css_class="mr-2" %}- This integration requires immediate attention. Please check the configuration settings and ensure the external service is accessible.- </p>-</div>-{% else %}-<div class="alert alert-warning mt-3">- <p class="mb-0">- {% icon "info-circle" size="sm" css_class="mr-2" %}- This integration has encountered temporary issues. The problem may resolve automatically, but monitoring is recommended.- </p>-</div>-{% endif %}--{% endtimezone %}-{% endblock %}diff --git a/src/hi/integrations/templates/integrations/pages/integration_manage.html b/src/hi/integrations/templates/integrations/pages/integration_manage.htmlindex b0439a93..4a4a5f19 100644--- a/src/hi/integrations/templates/integrations/pages/integration_manage.html+++ b/src/hi/integrations/templates/integrations/pages/integration_manage.html@@ -18,7 +18,7 @@data-async="true"><div class="d-flex justify-content-between align-items-center"><span>{{ integration_data.label }}</span>- {% with health_status=integration_data.integration_gateway.get_health_status %}+ {% with health_status=integration_data.integration_gateway.health_status %}{% if health_status.is_error %}<span class="text-danger"> {% icon "warning" size="lg" css_class="mr-1" %}diff --git a/src/hi/integrations/transient_models.py b/src/hi/integrations/transient_models.pyindex 953f1fef..aeb116e9 100644--- a/src/hi/integrations/transient_models.py+++ b/src/hi/integrations/transient_models.py@@ -2,7 +2,8 @@ from dataclasses import dataclassfrom datetime import datetimefrom typing import Dict, List, Optional-from .enums import IntegrationAttributeType, IntegrationHealthStatusType+from hi.apps.system.enums import HealthStatusType+from .enums import IntegrationAttributeType@dataclass@@ -75,72 +76,12 @@ class IntegrationDetails:payload : Optional[Dict] = None-@dataclass-class IntegrationHealthStatus:-- status : IntegrationHealthStatusType- last_check : datetime- error_message : Optional[str] = None- error_count : int = 0- # Enhanced monitoring fields for debugging transient issues- monitor_heartbeat : Optional[datetime] = None # Last time the monitor cycled successfully- last_api_success : Optional[datetime] = None # Last successful API call- api_metrics : Optional[Dict] = None # API call performance metrics- async_diagnostics : Optional[Dict] = None # Background task and async loop diagnostics-- @property- def is_healthy(self) -> bool:- return self.status == IntegrationHealthStatusType.HEALTHY-- @property- def is_error(self) -> bool:- return self.status.is_error-- @property- def is_critical(self) -> bool:- return self.status.is_critical-- @property- def status_display(self) -> str:- return self.status.label-- def to_dict(self) -> Dict:- result = {- 'status': self.status.value,- 'status_display': self.status_display,- 'last_check': self.last_check,- 'error_message': self.error_message,- 'error_count': self.error_count,- 'is_healthy': self.is_healthy,- 'is_error': self.is_error,- 'is_critical': self.is_critical,- }-- # Include enhanced monitoring fields if present- if self.monitor_heartbeat is not None:- import hi.apps.common.datetimeproxy as datetimeproxy- heartbeat_age = (datetimeproxy.now() - self.monitor_heartbeat).total_seconds()- result['monitor_heartbeat'] = self.monitor_heartbeat- result['monitor_heartbeat_age_seconds'] = heartbeat_age-- if self.last_api_success is not None:- result['last_api_success'] = self.last_api_success-- if self.api_metrics is not None:- result['api_metrics'] = self.api_metrics-- if self.async_diagnostics is not None:- result['async_diagnostics'] = self.async_diagnostics-- return result--@dataclassclass IntegrationValidationResult:"""Result from integration configuration validation."""is_valid : bool- status : IntegrationHealthStatusType+ status : HealthStatusTypeerror_message : Optional[str] = Nonetimestamp : Optional[datetime] = None@@ -154,11 +95,11 @@ class IntegrationValidationResult:"""Create a successful validation result."""return cls(is_valid=True,- status=IntegrationHealthStatusType.HEALTHY+ status=HealthStatusType.HEALTHY)@classmethod- def error(cls, status: IntegrationHealthStatusType, error_message: str) -> 'IntegrationValidationResult':+ def error(cls, status: HealthStatusType, error_message: str) -> 'IntegrationValidationResult':"""Create an error validation result."""return cls(is_valid=False,diff --git a/src/hi/integrations/views.py b/src/hi/integrations/views.pyindex fd52005b..3a5e3983 100644--- a/src/hi/integrations/views.py+++ b/src/hi/integrations/views.py@@ -55,7 +55,7 @@ class IntegrationSelectView( HiModalView, IntegrationViewMixin ):class IntegrationHealthStatusView( HiModalView, IntegrationViewMixin ):def get_template_name( self ) -> str:- return 'integrations/modals/integration_health_status.html'+ return 'system/modals/aggregate_health_status.html'def get( self, request, *args, **kwargs ):integration_id = kwargs.get('integration_id')@@ -68,7 +68,7 @@ class IntegrationHealthStatusView( HiModalView, IntegrationViewMixin ):context = {'integration_data': integration_data,- 'health_status': health_status.to_dict(),+ 'health_status': health_status,}return self.modal_response( request, context )@@ -232,7 +232,7 @@ class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEdit'integration_data_list': integration_data_list,'integration_data': integration_data,'manage_view_template_name': manage_template_name,- 'health_status': health_status.to_dict(),+ 'health_status': health_status,},})return template_contextdiff --git a/src/hi/services/hass/hass_client_factory.py b/src/hi/services/hass/hass_client_factory.pyindex 0a7ea23c..f0824b03 100644--- a/src/hi/services/hass/hass_client_factory.py+++ b/src/hi/services/hass/hass_client_factory.py@@ -3,8 +3,9 @@import loggingfrom typing import Dict+from hi.apps.system.enums import HealthStatusType+from hi.integrations.exceptions import IntegrationAttributeError-from hi.integrations.enums import IntegrationHealthStatusTypefrom hi.integrations.models import IntegrationAttributefrom hi.integrations.transient_models import IntegrationKey, IntegrationValidationResult@@ -84,7 +85,7 @@ class HassClientFactory:return IntegrationValidationResult.success()else:return IntegrationValidationResult.error(- status=IntegrationHealthStatusType.CONNECTION_ERROR,+ status=HealthStatusType.ERROR,error_message='Failed to fetch states from Home Assistant API')@@ -97,17 +98,17 @@ class HassClientFactory:'forbidden','token','credential']):- status = IntegrationHealthStatusType.CONNECTION_ERROR+ status = HealthStatusType.ERRORuser_message = f'Authentication failed: {e}'elif any(keyword in error_msg for keyword in ['connect','network','timeout','unreachable','resolve']):- status = IntegrationHealthStatusType.CONNECTION_ERROR+ status = HealthStatusType.ERRORuser_message = f'Cannot connect to Home Assistant: {e}'else:- status = IntegrationHealthStatusType.TEMPORARY_ERROR+ status = HealthStatusType.WARNINGuser_message = f'API test failed: {e}'return IntegrationValidationResult.error(diff --git a/src/hi/services/hass/hass_manager.py b/src/hi/services/hass/hass_manager.pyindex 4aef9ef7..fefdeb6d 100644--- a/src/hi/services/hass/hass_manager.py+++ b/src/hi/services/hass/hass_manager.py@@ -2,19 +2,20 @@ import loggingfrom asgiref.sync import sync_to_asyncfrom typing import Dict, List-import hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.common.singleton_manager import SingletonManagerfrom hi.apps.common.utils import str_to_bool+from hi.apps.system.aggregate_health_provider import AggregateHealthProvider+from hi.apps.system.api_health_status_provider import ApiHealthStatusProvider+from hi.apps.system.provider_info import ProviderInfo+from hi.apps.system.enums import HealthStatusTypefrom hi.integrations.exceptions import (IntegrationAttributeError,IntegrationError,IntegrationDisabledError,)-from hi.integrations.enums import IntegrationHealthStatusTypefrom hi.integrations.transient_models import (IntegrationKey,- IntegrationHealthStatus,IntegrationValidationResult,)from hi.integrations.models import Integration, IntegrationAttribute@@ -28,7 +29,7 @@ from .hass_models import HassStatelogger = logging.getLogger(__name__)-class HassManager( SingletonManager ):+class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusProvider ):def __init_singleton__( self ):super().__init_singleton__()@@ -38,19 +39,36 @@ class HassManager( SingletonManager ):self._change_listeners = set()- # Health status tracking- self._health_status = IntegrationHealthStatus(- status=IntegrationHealthStatusType.UNKNOWN,- last_check=datetimeproxy.now()- )+ # Add self as the API health status provider to aggregate+ self.add_api_health_status_provider(self)+return++ @classmethod+ def get_provider_info(cls) -> ProviderInfo:+ """ Subclasses should override with something more meaningful. """+ return ProviderInfo(+ provider_id = 'hass_integration',+ provider_name = 'Home Assistant Integration',+ description = '',+ )++ @classmethod+ def get_api_provider_info(cls) -> ProviderInfo:+ """Get the API service info for this manager."""+ return ProviderInfo(+ provider_id = 'hass_api',+ provider_name = 'Home Assistant API',+ description = 'Home Assistant REST API for entity states'+ )def register_change_listener( self, callback ):if callback not in self._change_listeners:logger.debug( f'Adding HASS setting change listener from {callback.__module__}' )self._change_listeners.add( callback )else:- logger.debug( f'HASS setting change listener from {callback.__module__} already registered, skipping duplicate' )+ logger.debug( f'HASS setting change listener from'+ f' {callback.__module__} already registered, skipping duplicate' )returndef notify_settings_changed(self):@@ -76,26 +94,27 @@ class HassManager( SingletonManager ):self._hass_attr_type_to_attribute = self._load_attributes()self._hass_client = self.create_hass_client( self._hass_attr_type_to_attribute )self.clear_caches()- self._update_health_status(IntegrationHealthStatusType.HEALTHY)+ self.update_health_status(HealthStatusType.HEALTHY)+except IntegrationDisabledError:msg = 'HASS integration disabled'logger.info(msg)- self._update_health_status( IntegrationHealthStatusType.DISABLED, msg )+ self.update_health_status( HealthStatusType.DISABLED, msg )+except IntegrationError as e:error_msg = f'HASS integration configuration error: {e}'logger.error(error_msg)- self._update_health_status( IntegrationHealthStatusType.CONFIG_ERROR,- error_msg )+ self.update_health_status( HealthStatusType.ERROR, f"Configuration error: {error_msg}" )+except IntegrationAttributeError as e:error_msg = f'HASS integration attribute error: {e}'logger.error(error_msg)- self._update_health_status( IntegrationHealthStatusType.CONFIG_ERROR,- error_msg )+ self.update_health_status( HealthStatusType.ERROR, f"Configuration error: {error_msg}" )+except Exception as e:error_msg = f'Unexpected error loading HASS configuration: {e}'logger.exception(error_msg)- self._update_health_status( IntegrationHealthStatusType.TEMPORARY_ERROR,- error_msg )+ self.update_health_status( HealthStatusType.WARNING, f"Temporary issue: {error_msg}" )returndef clear_caches(self):@@ -140,19 +159,16 @@ class HassManager( SingletonManager ):logger.warning('HASS client not available - cannot fetch states')return {}- try:- hass_entity_id_to_state = dict()- for hass_state in self.hass_client.states():- hass_entity_id = hass_state.entity_id- hass_entity_id_to_state[hass_entity_id] = hass_state- continue+ with self.api_call_context( 'hass_states' ):+ hass_state_sequence = self.hass_client.states()- return hass_entity_id_to_state- except Exception as e:- error_msg = f'Failed to fetch HASS states: {e}'- logger.warning(error_msg)- self._update_health_status(IntegrationHealthStatusType.CONNECTION_ERROR, error_msg)- return {}+ hass_entity_id_to_state = dict()+ for hass_state in hass_state_sequence:+ hass_entity_id = hass_state.entity_id+ hass_entity_id_to_state[hass_entity_id] = hass_state+ continue++ return hass_entity_id_to_stateasync def fetch_hass_states_from_api_async( self, verbose : bool = True ) -> Dict[ str, HassState ]:"""@@ -164,54 +180,34 @@ class HassManager( SingletonManager ):thread_sensitive=True)(verbose=verbose)- def get_health_status(self) -> IntegrationHealthStatus:- """Get the current health status of the HASS integration."""- return self._health_status-- def _update_health_status(self, status: IntegrationHealthStatusType, error_message: str = None):- """Update the health status of this integration."""- old_status = self._health_status.status-- # Update health status- self._health_status = IntegrationHealthStatus(- status=status,- last_check=datetimeproxy.now(),- error_message=error_message,- error_count=self._health_status.error_count + (1 if status.is_error else 0)- )-- # Log status changes- if old_status != status:- if status == IntegrationHealthStatusType.HEALTHY:- logger.info('HASS integration is now healthy')- elif status == IntegrationHealthStatusType.DISABLED:- logger.info('HASS integration is now disabled')- else:- logger.warning(f'HASS integration health status changed to {status.value}: {error_message}')-def test_connection(self) -> bool:"""Test the connection to HASS API and update health status."""try:if not self.hass_client:- self._update_health_status(IntegrationHealthStatusType.CONFIG_ERROR, "HASS client not configured")+ self.update_health_status(HealthStatusType.ERROR,+ "HASS client not configured")return False# Try to fetch states to test connectionstates = self.fetch_hass_states_from_api(verbose=False)if states is not None:- self._update_health_status(IntegrationHealthStatusType.HEALTHY)+ self.update_health_status(HealthStatusType.HEALTHY)return Trueelse:- self._update_health_status(IntegrationHealthStatusType.CONNECTION_ERROR, "Failed to fetch states from HASS API")+ self.update_health_status(HealthStatusType.ERROR,+ "Failed to fetch states from HASS API")return Falseexcept Exception as e:error_msg = f'Connection test failed: {e}'logger.debug(error_msg)- self._update_health_status(IntegrationHealthStatusType.CONNECTION_ERROR, error_msg)+ self.update_health_status(HealthStatusType.ERROR, f"Connection error: {error_msg}")return False- def test_client_with_attributes(self, hass_attr_type_to_attribute: Dict[HassAttributeType, IntegrationAttribute]) -> IntegrationValidationResult:+ def test_client_with_attributes(+ self,+ hass_attr_type_to_attribute: Dict[HassAttributeType, IntegrationAttribute]+ ) -> IntegrationValidationResult:"""Test API connectivity using provided attributes without affecting manager state.@@ -229,12 +225,12 @@ class HassManager( SingletonManager ):except IntegrationError as e:return IntegrationValidationResult.error(- status=IntegrationHealthStatusType.CONFIG_ERROR,+ status=HealthStatusType.ERROR,error_message=str(e))except IntegrationAttributeError as e:return IntegrationValidationResult.error(- status=IntegrationHealthStatusType.CONFIG_ERROR,+ status=HealthStatusType.ERROR,error_message=str(e))@@ -263,7 +259,7 @@ class HassManager( SingletonManager ):except Exception as e:logger.exception(f'Error in HASS configuration validation: {e}')return IntegrationValidationResult.error(- status=IntegrationHealthStatusType.TEMPORARY_ERROR,+ status=HealthStatusType.WARNING,error_message=f'Configuration validation failed: {e}')diff --git a/src/hi/services/hass/integration.py b/src/hi/services/hass/integration.pyindex 655f9395..0164d09d 100644--- a/src/hi/services/hass/integration.py+++ b/src/hi/services/hass/integration.py@@ -1,13 +1,14 @@-import hi.apps.common.datetimeproxy as datetimeproxyimport loggingfrom typing import List-from hi.integrations.enums import IntegrationHealthStatusType+from hi.apps.system.enums import HealthStatusType+from hi.apps.system.health_status import HealthStatus+from hi.integrations.integration_controller import IntegrationControllerfrom hi.integrations.integration_gateway import IntegrationGatewayfrom hi.integrations.integration_manage_view_pane import IntegrationManageViewPanefrom hi.integrations.models import IntegrationAttribute-from hi.integrations.transient_models import IntegrationMetaData, IntegrationHealthStatus, IntegrationValidationResult+from hi.integrations.transient_models import IntegrationMetaData, IntegrationValidationResultfrom hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom .hass_controller import HassController@@ -45,24 +46,12 @@ class HassGateway( IntegrationGateway ):except Exception as e:logger.exception(f'Error notifying HASS integration of settings change: {e}')- def get_health_status(self) -> IntegrationHealthStatus:- """Get the current health status of the HASS integration.-- Delegates to HassManager for health status information.- """- try:- hass_manager = HassManager()- return hass_manager.get_health_status()- except Exception as e:- logger.exception(f'Error getting HASS integration health status: {e}')- # Return a default error status if we can't get the real status- return IntegrationHealthStatus(- status=IntegrationHealthStatusType.TEMPORARY_ERROR,- last_check=datetimeproxy.now(),- error_message=f'Failed to get health status: {e}'- )+ def get_health_status(self) -> HealthStatus:+ return HassManager().health_status- def validate_configuration(self, integration_attributes: List[IntegrationAttribute]) -> IntegrationValidationResult:+ def validate_configuration(+ self, integration_attributes: List[IntegrationAttribute]+ ) -> IntegrationValidationResult:"""Validate HASS integration configuration by testing API connectivity.Delegates to HassManager for configuration validation.@@ -73,6 +62,6 @@ class HassGateway( IntegrationGateway ):except Exception as e:logger.exception(f'Error validating HASS integration configuration: {e}')return IntegrationValidationResult.error(- status=IntegrationHealthStatusType.TEMPORARY_ERROR,+ status=HealthStatusType.WARNING,error_message=f'Configuration validation failed: {e}')diff --git a/src/hi/services/hass/monitors.py b/src/hi/services/hass/monitors.pyindex 660d800d..64a03bb0 100644--- a/src/hi/services/hass/monitors.py+++ b/src/hi/services/hass/monitors.py@@ -4,6 +4,7 @@ import hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom hi.apps.sense.sensor_response_manager import SensorResponseMixinfrom hi.apps.sense.transient_models import SensorResponse+from hi.apps.system.provider_info import ProviderInfofrom .hass_converter import HassConverterfrom .hass_mixins import HassMixin@@ -48,7 +49,16 @@ class HassMonitor( PeriodicMonitor, HassMixin, SensorResponseMixin ):self._was_initialized = Falselogger.info( 'HassMonitor refreshed - will reinitialize with new settings on next cycle' )return-++ @classmethod+ def get_provider_info(cls) -> ProviderInfo:+ """ Subclasses should override with something more meaningful. """+ return ProviderInfo(+ provider_id = 'hi.sevices.hass',+ provider_name = 'Home Assistant Monitor',+ description = '',+ )+async def do_work(self):if not self._was_initialized:await self._initialize()diff --git a/src/hi/services/hass/tests/test_hass_client_factory.py b/src/hi/services/hass/tests/test_hass_client_factory.pyindex e698d452..198ebd8d 100644--- a/src/hi/services/hass/tests/test_hass_client_factory.py+++ b/src/hi/services/hass/tests/test_hass_client_factory.py@@ -6,7 +6,8 @@ Focuses on high-value testing: client creation, validation, and error handling.from unittest.mock import Mock, patchfrom django.test import TestCase-from hi.integrations.enums import IntegrationHealthStatusType+from hi.apps.system.enums import HealthStatusType+from hi.integrations.exceptions import IntegrationAttributeErrorfrom hi.integrations.models import IntegrationAttributefrom hi.integrations.transient_models import IntegrationKey, IntegrationValidationResult@@ -110,7 +111,7 @@ class TestHassClientFactory(TestCase):# Assert - Test actual behaviorself.assertIsInstance(result, IntegrationValidationResult)self.assertTrue(result.is_valid)- self.assertEqual(result.status, IntegrationHealthStatusType.HEALTHY)+ self.assertEqual(result.status, HealthStatusType.HEALTHY)self.assertIsNone(result.error_message)# Verify the client was actually tested@@ -131,7 +132,7 @@ class TestHassClientFactory(TestCase):# Assert - Test error handling behaviorself.assertIsInstance(result, IntegrationValidationResult)self.assertFalse(result.is_valid)- self.assertEqual(result.status, IntegrationHealthStatusType.CONNECTION_ERROR)+ self.assertEqual(result.status, HealthStatusType.ERROR)self.assertIn('Cannot connect to Home Assistant', result.error_message)@patch('hi.services.hass.hass_client.get')@@ -149,6 +150,6 @@ class TestHassClientFactory(TestCase):# Assert - Test error categorizationself.assertIsInstance(result, IntegrationValidationResult)self.assertFalse(result.is_valid)- self.assertEqual(result.status, IntegrationHealthStatusType.CONNECTION_ERROR)+ self.assertEqual(result.status, HealthStatusType.ERROR)self.assertIn('Authentication failed', result.error_message)diff --git a/src/hi/services/hass/tests/test_hass_manager.py b/src/hi/services/hass/tests/test_hass_manager.pyindex 154d2bb1..f0299909 100644--- a/src/hi/services/hass/tests/test_hass_manager.py+++ b/src/hi/services/hass/tests/test_hass_manager.py@@ -3,7 +3,8 @@ import threadingfrom unittest.mock import Mock, patchfrom django.test import TestCase-from hi.integrations.enums import IntegrationHealthStatusType+from hi.apps.system.enums import HealthStatusType+from hi.integrations.exceptions import IntegrationAttributeErrorfrom hi.integrations.transient_models import IntegrationKeyfrom hi.integrations.models import Integration@@ -124,8 +125,8 @@ class TestHassManagerInitialization(TestCase):# Manager should still be functional, just with no configurationself.assertIsNotNone(self.manager)# Health status should reflect the configuration error- health = self.manager.get_health_status()- self.assertEqual(health.status, IntegrationHealthStatusType.CONFIG_ERROR)+ health = self.manager.health_status+ self.assertEqual(health.status, HealthStatusType.ERROR)self.assertIn('not implemented', health.error_message)def test_reload_with_disabled_integration(self):@@ -139,8 +140,8 @@ class TestHassManagerInitialization(TestCase):self.manager.reload()# Health status should reflect the configuration error- health = self.manager.get_health_status()- self.assertEqual(health.status, IntegrationHealthStatusType.DISABLED)+ health = self.manager.health_status+ self.assertEqual(health.status, HealthStatusType.WARNING)def test_reload_with_missing_required_attribute(self):"""Test reload handles missing required attributes gracefully"""@@ -154,8 +155,8 @@ class TestHassManagerInitialization(TestCase):self.manager.reload()# Health status should reflect the configuration error- health = self.manager.get_health_status()- self.assertEqual(health.status, IntegrationHealthStatusType.CONFIG_ERROR)+ health = self.manager.health_status+ self.assertEqual(health.status, HealthStatusType.ERROR)self.assertIn('Missing HASS attribute', health.error_message)def test_reload_with_empty_required_value(self):@@ -185,8 +186,8 @@ class TestHassManagerInitialization(TestCase):self.manager.reload()# Health status should reflect the configuration error- health = self.manager.get_health_status()- self.assertEqual(health.status, IntegrationHealthStatusType.CONFIG_ERROR)+ health = self.manager.health_status+ self.assertEqual(health.status, HealthStatusType.ERROR)self.assertIn('Missing HASS attribute value', health.error_message)def test_reload_success_with_all_required_attributes(self):@@ -219,7 +220,7 @@ class TestHassManagerInitialization(TestCase):# Health status should be healthy (CONFIG_ERROR since we can't actually connect)# but at least the configuration loaded successfully- health = self.manager.get_health_status()+ health = self.manager.health_status# The status will be CONFIG_ERROR or UNKNOWN since we don't have a real API to connect to# But the important thing is it loaded the attributes without errorsself.assertIsNotNone(health)@@ -669,18 +670,8 @@ class TestHassManagerApiDataFetching(TestCase):self.mock_client.states.side_effect = Exception("Connection error")# Now exceptions are caught and empty dict is returned- result = self.manager.fetch_hass_states_from_api()-- # Should return empty dict on error- self.assertEqual(result, {})-- # Verify client.states was called- self.mock_client.states.assert_called_once()-- # Verify health status was updated to CONNECTION_ERROR- health_status = self.manager.get_health_status()- self.assertEqual(health_status.status, IntegrationHealthStatusType.CONNECTION_ERROR)- self.assertIn("Connection error", health_status.error_message)+ with self.assertRaises( Exception ):+ _ = self.manager.fetch_hass_states_from_api()def test_fetch_hass_states_from_api_data_transformation(self):"""Test fetch_hass_states_from_api correctly transforms state list to dictionary"""diff --git a/src/hi/services/zoneminder/integration.py b/src/hi/services/zoneminder/integration.pyindex 7ef2bc72..2cce5547 100644--- a/src/hi/services/zoneminder/integration.py+++ b/src/hi/services/zoneminder/integration.py@@ -6,14 +6,15 @@ from hi.apps.entity.transient_models import VideoStreamfrom hi.apps.entity.enums import VideoStreamType, VideoStreamModefrom hi.apps.entity.constants import VideoStreamMetadataKeysfrom hi.apps.sense.transient_models import SensorResponse-from hi.integrations.enums import IntegrationHealthStatusType+from hi.apps.system.enums import HealthStatusType+from hi.apps.system.health_status import HealthStatus+from hi.integrations.integration_controller import IntegrationControllerfrom hi.integrations.integration_gateway import IntegrationGatewayfrom hi.integrations.integration_manage_view_pane import IntegrationManageViewPanefrom hi.integrations.models import IntegrationAttributefrom hi.integrations.transient_models import (IntegrationMetaData,- IntegrationHealthStatus,IntegrationValidationResult,)from hi.apps.monitor.periodic_monitor import PeriodicMonitor@@ -55,25 +56,8 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):except Exception as e:logger.exception(f'Error notifying ZoneMinder integration of settings change: {e}')- def get_health_status(self) -> IntegrationHealthStatus:- """Get the current health status of the ZoneMinder integration.-- Delegates to ZoneMinderManager for health status information.- The health status now includes enhanced monitoring data for debugging- transient issues like the bug in #205.- """- try:- zm_manager = ZoneMinderManager()- return zm_manager.get_health_status()- except Exception as e:- logger.exception(f'Error getting ZoneMinder integration health status: {e}')- # Return a default error status if we can't get the real status- import hi.apps.common.datetimeproxy as datetimeproxy- return IntegrationHealthStatus(- status=IntegrationHealthStatusType.TEMPORARY_ERROR,- last_check=datetimeproxy.now(),- error_message=f'Failed to get health status: {e}'- )+ def get_health_status(self) -> HealthStatus:+ return ZoneMinderManager().health_statusdef validate_configuration(self,@@ -89,7 +73,7 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):except Exception as e:logger.exception(f'Error validating ZoneMinder integration configuration: {e}')return IntegrationValidationResult.error(- status=IntegrationHealthStatusType.TEMPORARY_ERROR,+ status=HealthStatusType.WARNING,error_message=f'Configuration validation failed: {e}')@@ -118,11 +102,14 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):})except (IndexError, ValueError):- logger.warning(f"Could not parse monitor ID from entity integration name: {entity.integration_name}")+ logger.warning(f"Could not parse monitor ID from entity integration name:"+ f" {entity.integration_name}")return None- def get_sensor_response_video_stream(self, sensor_response: SensorResponse) -> Optional[VideoStream]:+ def get_sensor_response_video_stream(+ self,+ sensor_response: SensorResponse) -> Optional[VideoStream]:"""Get video stream from sensor response (recorded events)"""# if not sensor_response.has_video_stream:# return None@@ -149,7 +136,8 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):duration_secs = float(sensor_response.detail_attrs[ZmDetailKeys.DURATION_SECS])metadata[VideoStreamMetadataKeys.DURATION_SECS] = int(duration_secs)except (ValueError, TypeError):- logger.debug(f"Could not parse duration from sensor response: {sensor_response.detail_attrs.get(ZmDetailKeys.DURATION_SECS)}")+ logger.debug(f"Could not parse duration from sensor response:"+ f" {sensor_response.detail_attrs.get(ZmDetailKeys.DURATION_SECS)}")return VideoStream(stream_type=VideoStreamType.URL,@@ -157,6 +145,7 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):metadata=metadata)except (ValueError, TypeError):- logger.warning(f"Could not parse event ID from sensor response: {sensor_response.detail_attrs}")+ logger.warning(f"Could not parse event ID from sensor response:"+ f" {sensor_response.detail_attrs}")return Nonediff --git a/src/hi/services/zoneminder/monitors.py b/src/hi/services/zoneminder/monitors.pyindex 6a392110..32adda70 100644--- a/src/hi/services/zoneminder/monitors.py+++ b/src/hi/services/zoneminder/monitors.py@@ -9,6 +9,7 @@ from hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom hi.apps.sense.sensor_response_manager import SensorResponseMixinfrom hi.apps.sense.transient_models import SensorResponsefrom hi.apps.sense.enums import CorrelationRole+from hi.apps.system.provider_info import ProviderInfofrom .constants import ZmDetailKeys, ZmTimeoutsfrom .zm_models import ZmEvent, AggregatedMonitorState@@ -56,6 +57,15 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )self._was_initialized = Truereturn+ @classmethod+ def get_provider_info(cls) -> ProviderInfo:+ """ Subclasses should override with something more meaningful. """+ return ProviderInfo(+ provider_id = 'hi.sevices.zoneminder',+ provider_name = 'ZoneMinder Monitor',+ description = '',+ )+def refresh( self ):"""Called when integration settings are changed (via listener callback).@@ -79,32 +89,21 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )logger.warning( 'ZoneMinder monitor failed to initialize. Skipping work cycle.' )return- try:- # Update heartbeat to indicate monitor is alive and working- zm_manager = await self.zm_manager_async()- if zm_manager:- zm_manager.update_monitor_heartbeat()-- sensor_response_map = dict()-- # Process ZoneMinder events for motion detection- sensor_response_map.update( await self._process_events( ) )-- # Process ZoneMinder monitors for function changes- sensor_response_map.update( await self._process_monitors() )+ sensor_response_map = dict()- # Process ZoneMinder states for run state changes- sensor_response_map.update( await self._process_states() )+ # Process ZoneMinder events for motion detection+ sensor_response_map.update( await self._process_events( ) )- # Update sensor responses- await self.sensor_response_manager().update_with_latest_sensor_responses(- sensor_response_map = sensor_response_map,- )+ # Process ZoneMinder monitors for function changes+ sensor_response_map.update( await self._process_monitors() )- except Exception as e:- logger.exception(f'ZoneMinder monitor cycle failed: {e}')- raise+ # Process ZoneMinder states for run state changes+ sensor_response_map.update( await self._process_states() )+ # Update sensor responses+ await self.sensor_response_manager().update_with_latest_sensor_responses(+ sensor_response_map = sensor_response_map,+ )returnasync def _process_events(self):diff --git a/src/hi/services/zoneminder/tests/test_zm_client_factory.py b/src/hi/services/zoneminder/tests/test_zm_client_factory.pyindex 7d2e728c..302414fe 100644--- a/src/hi/services/zoneminder/tests/test_zm_client_factory.py+++ b/src/hi/services/zoneminder/tests/test_zm_client_factory.py@@ -6,7 +6,7 @@ Focuses on high-value testing: client creation, validation, and error handling.from unittest.mock import Mock, patchfrom django.test import TestCase-from hi.integrations.enums import IntegrationHealthStatusType+from hi.apps.system.enums import HealthStatusTypefrom hi.integrations.exceptions import IntegrationAttributeErrorfrom hi.integrations.models import IntegrationAttributefrom hi.integrations.transient_models import IntegrationKey, IntegrationValidationResult@@ -116,7 +116,7 @@ class TestZmClientFactory(TestCase):# Assert - Test actual behaviorself.assertIsInstance(result, IntegrationValidationResult)self.assertTrue(result.is_valid)- self.assertEqual(result.status, IntegrationHealthStatusType.HEALTHY)+ self.assertEqual(result.status, HealthStatusType.HEALTHY)self.assertIsNone(result.error_message)# Verify the client was actually tested@@ -136,7 +136,7 @@ class TestZmClientFactory(TestCase):# Assert - Test error handling behaviorself.assertIsInstance(result, IntegrationValidationResult)self.assertFalse(result.is_valid)- self.assertEqual(result.status, IntegrationHealthStatusType.CONNECTION_ERROR)+ self.assertEqual(result.status, HealthStatusType.ERROR)self.assertIn('Cannot connect to ZoneMinder', result.error_message)@patch('hi.services.zoneminder.pyzm_client.api.ZMApi')@@ -152,7 +152,7 @@ class TestZmClientFactory(TestCase):# Assert - Test error categorizationself.assertIsInstance(result, IntegrationValidationResult)self.assertFalse(result.is_valid)- self.assertEqual(result.status, IntegrationHealthStatusType.CONNECTION_ERROR)+ self.assertEqual(result.status, HealthStatusType.ERROR)self.assertIn('Authentication failed', result.error_message)@patch('hi.services.zoneminder.pyzm_client.api.ZMApi')@@ -170,6 +170,6 @@ class TestZmClientFactory(TestCase):# Assertself.assertIsInstance(result, IntegrationValidationResult)self.assertFalse(result.is_valid)- self.assertEqual(result.status, IntegrationHealthStatusType.CONNECTION_ERROR)+ self.assertEqual(result.status, HealthStatusType.ERROR)self.assertIn('Failed to fetch states from ZoneMinder API', result.error_message)diff --git a/src/hi/services/zoneminder/tests/test_zm_manager.py b/src/hi/services/zoneminder/tests/test_zm_manager.pyindex 98a79c2c..7fa224d4 100644--- a/src/hi/services/zoneminder/tests/test_zm_manager.py+++ b/src/hi/services/zoneminder/tests/test_zm_manager.py@@ -11,8 +11,10 @@ from concurrent.futures import ThreadPoolExecutor, as_completedfrom django.test import TestCase, TransactionTestCase+from hi.apps.system.enums import HealthStatusType+from hi.integrations.models import Integration, IntegrationAttribute-from hi.integrations.enums import IntegrationHealthStatusType+from hi.services.zoneminder.zm_manager import ZoneMinderManagerfrom hi.services.zoneminder.enums import ZmAttributeTypefrom hi.services.zoneminder.zm_metadata import ZmMetaData@@ -104,7 +106,7 @@ class ZoneMinderManagerConfigurationTest(TransactionTestCase):self.assertIsNone(client)# Health status should reflect the error- health = manager.get_health_status()+ health = manager.health_statusself.assertFalse(health.is_healthy)def test_handles_disabled_integration(self):@@ -116,8 +118,8 @@ class ZoneMinderManagerConfigurationTest(TransactionTestCase):client = manager.zm_clientself.assertIsNone(client)- health = manager.get_health_status()- self.assertEqual(health.status, IntegrationHealthStatusType.DISABLED)+ health = manager.health_status+ self.assertEqual(health.status, HealthStatusType.WARNING)def test_validates_required_attributes(self):"""Should validate that required attributes are present."""@@ -131,8 +133,8 @@ class ZoneMinderManagerConfigurationTest(TransactionTestCase):# Should handle missing required attributeself.assertIsNone(client)- health = manager.get_health_status()- self.assertEqual(health.status, IntegrationHealthStatusType.CONFIG_ERROR)+ health = manager.health_status+ self.assertEqual(health.status, HealthStatusType.ERROR)class ZoneMinderManagerThreadLocalTest(TransactionTestCase):@@ -271,62 +273,13 @@ class ZoneMinderManagerHealthStatusTest(TestCase):def test_tracks_health_status(self):"""Should track health status of integration."""manager = ZoneMinderManager()- health = manager.get_health_status()+ health = manager.health_status# Should have health statusself.assertIsNotNone(health)self.assertIsNotNone(health.last_check)self.assertIsNotNone(health.status)- def test_updates_monitor_heartbeat(self):- """Should update monitor heartbeat timestamp."""- manager = ZoneMinderManager()-- # Get initial heartbeat- health1 = manager.get_health_status()- initial_heartbeat = health1.monitor_heartbeat-- # Update heartbeat- manager.update_monitor_heartbeat()-- # Should have newer heartbeat- health2 = manager.get_health_status()- self.assertIsNotNone(health2.monitor_heartbeat)- if initial_heartbeat:- self.assertGreaterEqual(health2.monitor_heartbeat, initial_heartbeat)-- @patch('hi.services.zoneminder.zm_client_factory.ZmClientFactory.create_client')- def test_tracks_api_metrics(self, mock_create_client):- """Should track API call metrics."""- # Create a mock client with states method- mock_client = Mock()- mock_states = Mock()- mock_states.list.return_value = []- mock_client.states.return_value = mock_states- mock_create_client.return_value = mock_client-- manager = ZoneMinderManager()-- # Make an API call - this should use our mocked client- manager.get_zm_states(force_load=True)-- # Check metrics were updated- health = manager.get_health_status()- self.assertIsNotNone(health.api_metrics)- self.assertGreaterEqual(health.api_metrics['total_calls'], 0)-- def test_connection_test_updates_health(self):- """Connection test should update health status."""- manager = ZoneMinderManager()-- # Test connection (will fail without real API)- _ = manager.test_connection()-- # Should update health status even on failure- health = manager.get_health_status()- self.assertIsNotNone(health.status)- self.assertIsNotNone(health.last_check)-class ZoneMinderManagerReloadTest(TransactionTestCase):"""Test configuration reload behavior."""diff --git a/src/hi/services/zoneminder/zm_client_factory.py b/src/hi/services/zoneminder/zm_client_factory.pyindex b4cbd7f8..124e3bf9 100644--- a/src/hi/services/zoneminder/zm_client_factory.py+++ b/src/hi/services/zoneminder/zm_client_factory.py@@ -3,8 +3,8 @@import loggingfrom typing import Dict+from hi.apps.system.enums import HealthStatusTypefrom hi.integrations.exceptions import IntegrationAttributeError-from hi.integrations.enums import IntegrationHealthStatusTypefrom hi.integrations.models import IntegrationAttributefrom hi.integrations.transient_models import IntegrationKey, IntegrationValidationResult@@ -86,7 +86,7 @@ class ZmClientFactory:return IntegrationValidationResult.success()else:return IntegrationValidationResult.error(- status=IntegrationHealthStatusType.CONNECTION_ERROR,+ status=HealthStatusType.ERROR,error_message='Failed to fetch states from ZoneMinder API')@@ -100,7 +100,7 @@ class ZmClientFactory:'login','credential','password']):- status = IntegrationHealthStatusType.CONNECTION_ERROR+ status = HealthStatusType.ERRORuser_message = f'Authentication failed: {e}'elif any(keyword in error_msg for keyword in ['connect','network',@@ -109,10 +109,10 @@ class ZmClientFactory:'resolve','schema','url']):- status = IntegrationHealthStatusType.CONNECTION_ERROR+ status = HealthStatusType.ERRORuser_message = f'Cannot connect to ZoneMinder: {e}'else:- status = IntegrationHealthStatusType.TEMPORARY_ERROR+ status = HealthStatusType.WARNINGuser_message = f'API test failed: {e}'return IntegrationValidationResult.error(diff --git a/src/hi/services/zoneminder/zm_manager.py b/src/hi/services/zoneminder/zm_manager.pyindex e949e435..c645f790 100644--- a/src/hi/services/zoneminder/zm_manager.py+++ b/src/hi/services/zoneminder/zm_manager.py@@ -1,6 +1,5 @@import loggingimport threading-from datetime import datetimefrom asgiref.sync import sync_to_asyncfrom .pyzm_client.api import ZMApifrom .pyzm_client.helpers.Event import Event as ZmEvent@@ -12,8 +11,11 @@ from typing import Dict, Listimport hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.common.singleton_manager import SingletonManagerfrom hi.apps.common.utils import str_to_bool+from hi.apps.system.aggregate_health_provider import AggregateHealthProvider+from hi.apps.system.api_health_status_provider import ApiHealthStatusProvider+from hi.apps.system.provider_info import ProviderInfo+from hi.apps.system.enums import HealthStatusType-from hi.integrations.enums import IntegrationHealthStatusTypefrom hi.integrations.exceptions import (IntegrationAttributeError,IntegrationError,@@ -21,7 +23,6 @@ from hi.integrations.exceptions import ()from hi.integrations.transient_models import (IntegrationKey,- IntegrationHealthStatus,IntegrationValidationResult,)from hi.integrations.models import Integration, IntegrationAttribute@@ -35,7 +36,7 @@ logger = logging.getLogger(__name__)pyzm_logger.set_level( 0 ) # pyzm does not use standard 'logging' module. ugh.-class ZoneMinderManager( SingletonManager ):+class ZoneMinderManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusProvider ):"""References:ZM Api code: https://github.com/ZoneMinder/zoneminder/tree/master/web/api/app/Controller@@ -68,27 +69,36 @@ class ZoneMinderManager( SingletonManager ):self._change_listeners = set()- # Health status tracking with enhanced monitoring- self._health_status = IntegrationHealthStatus(- status=IntegrationHealthStatusType.UNKNOWN,- last_check=datetimeproxy.now(),- monitor_heartbeat=datetimeproxy.now(),- last_api_success=None,- api_metrics={- 'last_response_time': None,- 'consecutive_failures': 0,- 'total_calls': 0,- 'total_failures': 0,- }- )+ # Add self as the API health status provider to aggregate+ self.add_api_health_status_provider(self)+return++ @classmethod+ def get_provider_info(cls) -> ProviderInfo:+ """ Subclasses should override with something more meaningful. """+ return ProviderInfo(+ provider_id = 'zm_integration',+ provider_name = 'ZoneMinder Integration',+ description = '',+ )++ @classmethod+ def get_api_provider_info(cls) -> ProviderInfo:+ """Get the API service info for this manager."""+ return ProviderInfo(+ provider_id = 'zm_api',+ provider_name = 'ZoneMinder API',+ description = 'ZoneMinder video surveillance system API'+ )def register_change_listener( self, callback ):if callback not in self._change_listeners:logger.debug( f'Adding ZM setting change listener from {callback.__module__}' )self._change_listeners.add( callback )else:- logger.debug( f'ZM setting change listener from {callback.__module__} already registered, skipping duplicate' )+ logger.debug( f'ZM setting change listener from {callback.__module__}'+ f' already registered, skipping duplicate' )returndef notify_settings_changed(self):@@ -118,7 +128,8 @@ class ZoneMinderManager( SingletonManager ):# Create new client for this threadif self._zm_attr_type_to_attribute:self._thread_local.zm_client = self.create_zm_client(self._zm_attr_type_to_attribute)- logger.debug(f'Created new thread-local ZM client for thread: {threading.current_thread().name}')+ logger.debug( f'Created new thread-local ZM client for thread:'+ f' {threading.current_thread().name}' )else:logger.warning('Cannot create ZM client - no attributes configured')self._thread_local.zm_client = None@@ -132,27 +143,28 @@ class ZoneMinderManager( SingletonManager ):# Clear all thread-local clients since configuration changedself._clear_thread_local_clients()self.clear_caches()- self._update_health_status(IntegrationHealthStatusType.HEALTHY)+ self.update_health_status(HealthStatusType.HEALTHY)logger.debug( 'ZoneMinder manager loading completed.' )+except IntegrationDisabledError:msg = 'ZoneMinder integration disabled'logger.info(msg)- self._update_health_status( IntegrationHealthStatusType.DISABLED, msg )+ self.update_health_status( HealthStatusType.DISABLED, msg )+except IntegrationError as e:error_msg = f'ZoneMinder integration configuration error: {e}'logger.error(error_msg)- self._update_health_status( IntegrationHealthStatusType.CONFIG_ERROR,- error_msg)+ self.update_health_status( HealthStatusType.ERROR, f"Configuration error: {error_msg}" )+except IntegrationAttributeError as e:error_msg = f'ZoneMinder integration attribute error: {e}'logger.error(error_msg)- self._update_health_status( IntegrationHealthStatusType.CONFIG_ERROR,- error_msg )+ self.update_health_status( HealthStatusType.ERROR, f"Configuration error: {error_msg}" )+except Exception as e:error_msg = f'Unexpected error loading ZoneMinder configuration: {e}'logger.exception(error_msg)- self._update_health_status( IntegrationHealthStatusType.TEMPORARY_ERROR,- error_msg )+ self.update_health_status( HealthStatusType.WARNING, f"Temporary issue: {error_msg}" )returndef clear_caches(self):@@ -221,15 +233,10 @@ class ZoneMinderManager( SingletonManager ):logger.warning('ZoneMinder client not available - cannot fetch states')return []- # Track API call timing- start_time = self._record_api_call_start()- try:+ with self.api_call_context( 'zm_states' ):self._zm_state_list = self.zm_client.states().list()self._zm_state_timestamp = datetimeproxy.now()- self._record_api_call_success(start_time)- except Exception as e:- self._record_api_call_failure(start_time, e)- raise+return self._zm_state_listdef get_zm_monitors( self, force_load : bool = False ) -> List[ ZmMonitor ]:@@ -241,18 +248,12 @@ class ZoneMinderManager( SingletonManager ):logger.warning('ZoneMinder client not available - cannot fetch monitors')return []- # Track API call timing- start_time = self._record_api_call_start()- try:+ with self.api_call_context( 'zm_monitors' ):options = {'force_reload': True, # pyzm caches monitors so need to force api call}self._zm_monitor_list = self.zm_client.monitors( options ).list()self._zm_monitor_timestamp = datetimeproxy.now()- self._record_api_call_success(start_time)- except Exception as e:- self._record_api_call_failure(start_time, e)- raisereturn self._zm_monitor_list@@ -262,14 +263,10 @@ class ZoneMinderManager( SingletonManager ):return []# Track API call timing for events (this is the most critical API call)- start_time = self._record_api_call_start()- try:+ with self.api_call_context( 'zm_events' ):result = self.zm_client.events( options ).list()- self._record_api_call_success(start_time)- return result- except Exception as e:- self._record_api_call_failure(start_time, e)- raise++ return resultasync def get_zm_states_async( self, force_load : bool = False ) -> List[ ZmState ]:"""@@ -364,177 +361,68 @@ class ZoneMinderManager( SingletonManager ):import timetimestamp = int(time.time())return f'{self.zm_client.portal_url}/cgi-bin/nph-zms?mode=jpeg&scale=100&rate=5&maxfps=5&replay=single&source=event&event={event_id}&_t={timestamp}'-- def get_health_status(self) -> IntegrationHealthStatus:- """Get the current health status of the ZoneMinder integration."""- # Add on-demand async diagnostics- health_status = self._health_status- health_status.async_diagnostics = self._get_async_diagnostics()- return health_status-- def _get_async_diagnostics(self) -> Dict:- """Get async task diagnostics on-demand"""- try:- from hi.apps.common.asyncio_utils import BackgroundTaskMonitor- return BackgroundTaskMonitor.get_background_task_status()- except Exception as e:- return {'error': f'Failed to get async diagnostics: {e}'}-- def update_monitor_heartbeat(self):- """Update the monitor heartbeat timestamp to indicate monitor is alive."""- self._health_status.monitor_heartbeat = datetimeproxy.now()- logger.debug('Monitor heartbeat updated')-- def get_monitor_status(self) -> Dict:- """Get detailed monitor status information for debugging."""- # The IntegrationHealthStatus now contains all monitoring data- status_dict = self._health_status.to_dict()-- # Add computed heartbeat health check- if self._health_status.monitor_heartbeat:- now = datetimeproxy.now()- heartbeat_age = (now - self._health_status.monitor_heartbeat).total_seconds()- status_dict['is_heartbeat_healthy'] = heartbeat_age < ZmTimeouts.MONITOR_HEARTBEAT_TIMEOUT_SECS-- # Add thread-local client information for debugging- status_dict['thread_info'] = {- 'current_thread': threading.current_thread().name,- 'has_thread_local_client': hasattr(self._thread_local, 'zm_client') and self._thread_local.zm_client is not None- }-- return status_dict-- def _record_api_call_start(self) -> datetime:- """Record the start of an API call for timing purposes."""- return datetimeproxy.now()-- def _record_api_call_success(self, start_time: datetime):- """Record a successful API call and update metrics."""- end_time = datetimeproxy.now()- response_time = (end_time - start_time).total_seconds()-- self._health_status.last_api_success = end_time- if self._health_status.api_metrics:- self._health_status.api_metrics['last_response_time'] = response_time- self._health_status.api_metrics['consecutive_failures'] = 0- self._health_status.api_metrics['total_calls'] += 1-- # Log performance warnings- if response_time > ZmTimeouts.API_RESPONSE_CRITICAL_THRESHOLD_SECS:- logger.warning(f'ZoneMinder API call took {response_time:.2f}s (critical threshold: {ZmTimeouts.API_RESPONSE_CRITICAL_THRESHOLD_SECS}s)')- elif response_time > ZmTimeouts.API_RESPONSE_WARNING_THRESHOLD_SECS:- logger.warning(f'ZoneMinder API call took {response_time:.2f}s (warning threshold: {ZmTimeouts.API_RESPONSE_WARNING_THRESHOLD_SECS}s)')-- def _record_api_call_failure(self, start_time: datetime, error: Exception):- """Record a failed API call and update metrics."""- end_time = datetimeproxy.now()- response_time = (end_time - start_time).total_seconds()-- if self._health_status.api_metrics:- self._health_status.api_metrics['consecutive_failures'] += 1- self._health_status.api_metrics['total_failures'] += 1- self._health_status.api_metrics['total_calls'] += 1-- logger.warning(f'ZoneMinder API call failed after {response_time:.2f}s: {error}')-- def _update_health_status(self, status: IntegrationHealthStatusType, error_message: str = None):- """Update the health status of this integration."""- old_status = self._health_status.status- # Update health status while preserving monitoring data- self._health_status = IntegrationHealthStatus(- status=status,- last_check=datetimeproxy.now(),- error_message=error_message,- error_count=self._health_status.error_count + (1 if status.is_error else 0),- monitor_heartbeat=self._health_status.monitor_heartbeat,- last_api_success=self._health_status.last_api_success,- api_metrics=self._health_status.api_metrics,- async_diagnostics=None # Reset async diagnostics, will be populated on-demand- )-- # Log status changes- if old_status != status:- if status == IntegrationHealthStatusType.HEALTHY:- logger.info('ZoneMinder integration is now healthy')- elif status == IntegrationHealthStatusType.DISABLED:- logger.info('ZoneMinder integration is now disabled')- else:- logger.warning(f'ZoneMinder integration health status changed to {status.value}: {error_message}')-def test_connection(self) -> bool:"""Test the connection to ZoneMinder API and update health status."""try:if not self.zm_client:- self._update_health_status(IntegrationHealthStatusType.CONFIG_ERROR, "ZoneMinder client not configured")+ self.update_health_status( HealthStatusType.ERROR,+ "ZoneMinder client not configured")return False# Try to fetch states to test connectionstates = self.get_zm_states(force_load=True)if states:- self._update_health_status(IntegrationHealthStatusType.HEALTHY)+ self.update_health_status(HealthStatusType.HEALTHY)return Trueelse:- self._update_health_status(IntegrationHealthStatusType.CONNECTION_ERROR, "Failed to fetch states from ZoneMinder API")+ self.update_health_status(HealthStatusType.ERROR,+ "Failed to fetch states from ZoneMinder API")return Falseexcept Exception as e:error_msg = f'Connection test failed: {e}'logger.debug(error_msg)- self._update_health_status(IntegrationHealthStatusType.CONNECTION_ERROR, error_msg)+ self.update_health_status(HealthStatusType.ERROR, f"Connection error: {error_msg}")return False- def test_client_with_attributes(self, zm_attr_type_to_attribute: Dict[ZmAttributeType, IntegrationAttribute]) -> IntegrationValidationResult:+ def test_client_with_attributes(+ self,+ zm_attr_type_to_attribute: Dict[ZmAttributeType, IntegrationAttribute]+ ) -> IntegrationValidationResult:"""Test API connectivity using provided attributes without affecting manager state.-- Args:- zm_attr_type_to_attribute: Dictionary mapping attribute types to attribute objects-- Returns:- IntegrationValidationResult with test results"""try:- # Create temporary client with provided attributestemp_client = self._client_factory.create_client(zm_attr_type_to_attribute)- # Test the clientreturn self._client_factory.test_client(temp_client)except IntegrationError as e:return IntegrationValidationResult.error(- status=IntegrationHealthStatusType.CONFIG_ERROR,- error_message=str(e)+ status = HealthStatusType.ERROR,+ error_message = str(e))except IntegrationAttributeError as e:return IntegrationValidationResult.error(- status=IntegrationHealthStatusType.CONFIG_ERROR,- error_message=str(e)+ status = HealthStatusType.ERROR,+ error_message = str(e))- def validate_configuration(self, integration_attributes: List[IntegrationAttribute]) -> IntegrationValidationResult:- """- Validate ZoneMinder configuration using provided attributes.-- Args:- integration_attributes: List of IntegrationAttribute objects-- Returns:- IntegrationValidationResult with validation results- """+ def validate_configuration(+ self,+ integration_attributes: List[IntegrationAttribute]) -> IntegrationValidationResult:try:# Build attribute mapping without enforcing requirements (for validation testing)zm_attr_type_to_attribute = self._build_zm_attr_type_to_attribute_map(integration_attributes=integration_attributes,enforce_requirements=False)-- # Use existing test methodreturn self.test_client_with_attributes(zm_attr_type_to_attribute)except Exception as e:logger.exception(f'Error in ZoneMinder configuration validation: {e}')return IntegrationValidationResult.error(- status=IntegrationHealthStatusType.TEMPORARY_ERROR,+ status=HealthStatusType.WARNING,error_message=f'Configuration validation failed: {e}')@@ -542,17 +430,10 @@ class ZoneMinderManager( SingletonManager ):self,integration_attributes: List[IntegrationAttribute],enforce_requirements: bool = True) -> Dict[ZmAttributeType, IntegrationAttribute]:- """Build mapping from ZmAttributeType to IntegrationAttribute.-- Args:- integration_attributes: List of IntegrationAttribute objects- enforce_requirements: If True, raise errors for missing required attributes-- Returns:- Dictionary mapping ZmAttributeType to IntegrationAttribute- """+zm_attr_type_to_attribute = {}- integration_key_to_attribute = {attr.integration_key: attr for attr in integration_attributes}+ integration_key_to_attribute = { attr.integration_key: attr+ for attr in integration_attributes }for zm_attr_type in ZmAttributeType:integration_key = IntegrationKey(diff --git a/src/hi/settings/base.py b/src/hi/settings/base.pyindex 279aa627..f01cf08e 100644--- a/src/hi/settings/base.py+++ b/src/hi/settings/base.py@@ -117,6 +117,7 @@ INSTALLED_APPS = ['hi.apps.security','hi.apps.edit','hi.apps.api',+ 'hi.apps.system','hi.apps.monitor','hi.apps.weather','hi.integrations',diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.cssindex fd060e25..efd75651 100644--- a/src/hi/static/css/main.css+++ b/src/hi/static/css/main.css@@ -1129,3 +1129,128 @@ g[hover] {gap: 1rem;}}++/* Monitor Health Status Styles */+.hi-modal-dialog-800 {+ max-width: 800px;+}++.monitor-status-badge {+ font-size: 1.1rem;+ padding: 0.5rem 1rem;+}++.monitor-status-healthy {+ background-color: var(--success-color);+ color: var(--on-success-color);+}++.monitor-status-warning {+ background-color: var(--warning-color);+ color: var(--on-warning-color);+}++.monitor-status-error {+ background-color: var(--error-color);+ color: var(--on-error-color);+}++.text-success-custom {+ color: var(--success-color);+}++.text-warning-custom {+ color: var(--warning-color);+}++.text-error-custom {+ color: var(--error-color);+}++.text-muted-custom {+ color: var(--muted-color);+}++.heartbeat-indicator {+ display: inline-block;+ width: 8px;+ height: 8px;+ border-radius: 50%;+ margin-right: 0.5rem;+}++.heartbeat-healthy {+ background-color: var(--success-color);+ animation: heartbeat-pulse 2s infinite;+}++.heartbeat-stale {+ background-color: var(--warning-color);+}++.heartbeat-dead {+ background-color: var(--error-color);+}++@keyframes heartbeat-pulse {+ 0% { opacity: 1; }+ 50% { opacity: 0.5; }+ 100% { opacity: 1; }+}++.api-source-section {+ border-left: 3px solid var(--line-color);+ padding-left: 1rem;+ margin-left: 0.5rem;+}++.api-source-healthy {+ border-left-color: var(--success-color);+}++.api-source-warning {+ border-left-color: var(--warning-color);+}++.api-source-error {+ border-left-color: var(--error-color);+}++.api-source-muted {+ border-left-color: var(--muted-color);+}++.api-metrics-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));+ gap: 1rem;+ margin-top: 0.5rem;+}++.metric-item {+ padding: 0.5rem;+ background-color: #f8f9fa;+ border-radius: 0.25rem;+ border-left: 3px solid var(--line-color);+}++.metric-item.success {+ border-left-color: var(--success-color);+}++.metric-item.warning {+ border-left-color: var(--warning-color);+}++.metric-item.error {+ border-left-color: var(--error-color);+}++.metric-item.muted {+ border-left-color: var(--muted-color);+}++.metric-value {+ font-weight: 600;+ font-size: 1.1rem;+}diff --git a/src/hi/templates/icons/exclamation-circle.html b/src/hi/templates/icons/exclamation-circle.htmlnew file mode 100644index 00000000..e043f9cc--- /dev/null+++ b/src/hi/templates/icons/exclamation-circle.html@@ -0,0 +1,3 @@+<svg class="{{ class_attr }}" viewBox="0 0 24 24" fill="currentColor" {{ accessibility_attrs }}>+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>+</svg>\ No newline at end of filediff --git a/src/hi/templates/icons/times-circle.html b/src/hi/templates/icons/times-circle.htmlnew file mode 100644index 00000000..11b32175--- /dev/null+++ b/src/hi/templates/icons/times-circle.html@@ -0,0 +1,3 @@+<svg class="{{ class_attr }}" viewBox="0 0 24 24" fill="currentColor" {{ accessibility_attrs }}>+ <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm3.59 5L12 10.59 8.41 7 7 8.41 10.59 12 7 15.59 8.41 17 12 13.41 15.59 17 17 15.59 13.41 12 17 8.41 15.59 7z"/>+</svg>\ No newline at end of filediff --git a/src/hi/urls.py b/src/hi/urls.pyindex e3ada58f..c5808c26 100644--- a/src/hi/urls.py+++ b/src/hi/urls.py@@ -47,6 +47,7 @@ urlpatterns = [re_path( r'^weather/', include('hi.apps.weather.urls' )),re_path( r'^audio/', include('hi.apps.audio.urls' )),re_path( r'^profiles/', include('hi.apps.profiles.urls' )),+ re_path( r'^system/', include('hi.apps.system.urls' )),# Custom error pagesre_path( r'^400.html$', views.bad_request_response, name='bad_request' ),