Home Information - Your home, your data, organized.
Python
Complete alert sound system implementation (Issue #34) (#45)
Tony C72bedc79bc35
diff --git a/src/hi/apps/alert/alarm.py b/src/hi/apps/alert/alarm.pyindex 20759c20..8051a40c 100644--- a/src/hi/apps/alert/alarm.py+++ b/src/hi/apps/alert/alarm.py@@ -2,7 +2,7 @@ from dataclasses import dataclassfrom datetime import datetimefrom typing import Dict, List-from hi.apps.console.audio_signal import AudioSignal+from hi.apps.audio.audio_signal import AudioSignalfrom hi.apps.security.enums import SecurityLevelfrom .enums import AlarmLevel, AlarmSource@@ -28,12 +28,10 @@ class Alarm:@propertydef audio_signal(self):-- # TODO: Currently based only on the alarm level, but eventually- # allow alarm-specific sounds. e.g., tornado siren sound when- # there's a weather alert.-- return AudioSignal.from_alarm_level( self.alarm_level )+ # Enhanced to support alarm-specific sounds based on level, source, and type.+ # Weather alerts get different sounds from event alerts, and tornado alerts+ # get special treatment regardless of level.+ return AudioSignal.from_alarm_attributes( self.alarm_level, self.alarm_source, self.alarm_type )@propertydef signature(self):diff --git a/src/hi/apps/alert/alert.py b/src/hi/apps/alert/alert.pyindex f4f28217..1f59a4a3 100644--- a/src/hi/apps/alert/alert.py+++ b/src/hi/apps/alert/alert.py@@ -4,7 +4,7 @@ from typing import Listimport uuidimport hi.apps.common.datetimeproxy as datetimeproxy-from hi.apps.console.audio_signal import AudioSignal+from hi.apps.audio.audio_signal import AudioSignalfrom hi.apps.notify.transient_models import NotificationItemfrom .alarm import Alarmdiff --git a/src/hi/apps/alert/alert_manager.py b/src/hi/apps/alert/alert_manager.pyindex cc89c62f..ad81f368 100644--- a/src/hi/apps/alert/alert_manager.py+++ b/src/hi/apps/alert/alert_manager.py@@ -57,10 +57,14 @@ class AlertManager( Singleton, NotificationMixin, SecurityMixin ):new_alert = self._alert_queue.get_most_important_alert(since_datetime = last_alert_status_datetime,)+ logger.debug(f"π new_alert from queue: {new_alert}")+if new_alert:- max_alert = new_alert.audio_signal_name if new_alert else None+ max_alert = new_alertelse:max_alert = self._alert_queue.get_most_important_alert()++ logger.debug(f"π max_alert from queue: {max_alert}")# TODO: Use this latest new alarm for providing auto-switching to# show something related to the latest event, e.g., camera feed.diff --git a/src/hi/apps/alert/alert_queue.py b/src/hi/apps/alert/alert_queue.pyindex 066f340a..24a700bc 100644--- a/src/hi/apps/alert/alert_queue.py+++ b/src/hi/apps/alert/alert_queue.py@@ -64,7 +64,7 @@ class AlertQueue:elif alert.alert_priority > max_alert.alert_priority:max_alert = alertcontinue- return+ return max_alertdef get_most_recent_alarm( self, since_datetime : datetime = None ):"""@@ -73,6 +73,8 @@ class AlertQueue:was to find a URL to switch to when automatically changing displaysbased on alarms."""+ latest_alarm = None+with self._active_alerts_lock:if len(self._alert_list) < 1:return None@@ -80,7 +82,6 @@ class AlertQueue:if since_datetime is None:since_datetime = datetimeproxy.min()- latest_alarm = Nonelatest_alarm_datetime = datetimeproxy.min()for alert in self._alert_list:if alert.is_acknowledged:@@ -95,8 +96,7 @@ class AlertQueue:latest_alarm_datetime = alarm.timestampcontinue- return latest_alarm- return+ return latest_alarmdef add_alarm( self, alarm : Alarm ) -> Alert:if alarm.alarm_level == AlarmLevel.NONE:diff --git a/src/hi/apps/alert/alert_status.py b/src/hi/apps/alert/alert_status.pyindex a481dcc5..ddee735c 100644--- a/src/hi/apps/alert/alert_status.py+++ b/src/hi/apps/alert/alert_status.py@@ -3,7 +3,7 @@ from typing import ClassVar, Listfrom django.http import HttpRequest-from hi.apps.console.audio_signal import AudioSignal+from hi.apps.audio.audio_signal import AudioSignalfrom .alert import Alertfrom .alert_helpers import AlertHelpers@@ -19,20 +19,37 @@ class AlertStatusData:new_audio_signal : AudioSignal # Not seen before (for immediate audio notification)NewAudioSignalNameAttr : ClassVar = 'newAudioSignalName'- MaxAudioSignalNameAttr : ClassVar = 'maxAudioSignaName'+ MaxAudioSignalNameAttr : ClassVar = 'maxAudioSignalName'AlarmMessageHtmlAttr : ClassVar = 'alarmMessageHtml'def to_dict(self, request : HttpRequest ):+ import logging+ logger = logging.getLogger(__name__)alert_list_html_str = AlertHelpers.alert_list_to_html_str(request = request,alert_list = self.alert_list,)response_dict = dict()++ logger.debug(f"π΅ AlertStatusData.to_dict() - max_audio_signal: {self.max_audio_signal}")+ logger.debug(f"π΅ AlertStatusData.to_dict() - new_audio_signal: {self.new_audio_signal}")+ logger.debug(f"π΅ AlertStatusData.to_dict() - alert_list length: {len(self.alert_list) if self.alert_list else 0}")+if self.max_audio_signal:- response_dict[self.MaxAudioSignalNameAttr] = str(self.max_audio_signal)+ response_dict[self.MaxAudioSignalNameAttr] = self.max_audio_signal.label+ logger.debug(f"π Added max_audio_signal: {self.max_audio_signal.label}")+ else:+ logger.debug("π No max_audio_signal to add")+if self.new_audio_signal:- response_dict[self.NewAudioSignalNameAttr] = str(self.new_audio_signal)+ response_dict[self.NewAudioSignalNameAttr] = self.new_audio_signal.label+ logger.debug(f"π΅ Added new_audio_signal: {self.new_audio_signal.label}")+ else:+ logger.debug("π΅ No new_audio_signal to add")+if self.alert_list:response_dict[self.AlarmMessageHtmlAttr] = alert_list_html_str++ logger.debug(f"π Final response_dict keys: {list(response_dict.keys())}")return response_dictdiff --git a/src/hi/apps/alert/enums.py b/src/hi/apps/alert/enums.pyindex bf97db22..0c157c53 100644--- a/src/hi/apps/alert/enums.py+++ b/src/hi/apps/alert/enums.py@@ -5,6 +5,7 @@ class AlarmSource( LabeledEnum ):EVENT = ( 'Event' , '' )WEATHER = ( 'Weather' , '' )+ CONSOLE = ( 'Console' , '' )class AlarmLevel( LabeledEnum ):diff --git a/src/hi/apps/alert/tests/test_alarm.py b/src/hi/apps/alert/tests/test_alarm.pyindex 8956eeda..3ee85caa 100644--- a/src/hi/apps/alert/tests/test_alarm.py+++ b/src/hi/apps/alert/tests/test_alarm.py@@ -3,7 +3,7 @@ from datetime import datetimefrom hi.apps.alert.alarm import Alarm, AlarmSourceDetailsfrom hi.apps.alert.enums import AlarmLevel, AlarmSource-from hi.apps.console.audio_signal import AudioSignal+from hi.apps.audio.audio_signal import AudioSignalfrom hi.apps.security.enums import SecurityLevelfrom hi.tests.base_test_case import BaseTestCasediff --git a/src/hi/apps/attribute/value_ranges.py b/src/hi/apps/attribute/value_ranges.pyindex e8f5913e..cb7421e3 100644--- a/src/hi/apps/attribute/value_ranges.py+++ b/src/hi/apps/attribute/value_ranges.py@@ -1,6 +1,6 @@from typing import List, Tuple-from hi.apps.console.audio_file import AudioFile+from hi.apps.audio.audio_file import AudioFilefrom hi.apps.console.enums import Theme, DisplayUnitsfrom hi.constants import TIME_OF_DAY_CHOICES, TIMEZONE_NAME_LISTdiff --git a/src/hi/apps/audio/__init__.py b/src/hi/apps/audio/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/audio/apps.py b/src/hi/apps/audio/apps.pynew file mode 100644index 00000000..fd1a11d0--- /dev/null+++ b/src/hi/apps/audio/apps.py@@ -0,0 +1,7 @@+from django.apps import AppConfig+++class AudioConfig(AppConfig):+ default_auto_field = 'django.db.models.BigAutoField'+ name = 'hi.apps.audio'+ label = 'audio'diff --git a/src/hi/apps/console/audio_file.py b/src/hi/apps/audio/audio_file.pysimilarity index 100%rename from src/hi/apps/console/audio_file.pyrename to src/hi/apps/audio/audio_file.pydiff --git a/src/hi/apps/audio/audio_manager.py b/src/hi/apps/audio/audio_manager.pynew file mode 100644index 00000000..bc5ed0e5--- /dev/null+++ b/src/hi/apps/audio/audio_manager.py@@ -0,0 +1,57 @@+import logging+from typing import Dict++from hi.apps.common.singleton import Singleton+from hi.apps.config.settings_mixins import SettingsMixin++from .audio_file import AudioFile+from .audio_signal import AudioSignal++logger = logging.getLogger(__name__)+++class AudioManager(Singleton, SettingsMixin):+ """+ Enhanced audio manager that replaces console audio functionality.++ Provides audio signal to URL mapping for the enhanced audio system+ that supports weather vs event differentiation and tornado-specific handling.+ """++ def __init_singleton__(self):+ self._was_initialized = False+ return++ def ensure_initialized(self):+ if self._was_initialized:+ return++ self.settings_manager().register_change_listener(self._reload_audio_map)+ self._audio_map = self._build_audio_map()+ self._was_initialized = True+ return++ def get_audio_map(self) -> Dict[str, str]:+ """Get mapping of audio signal names to their file URLs."""+ return self._audio_map++ def _reload_audio_map(self):+ """Reload audio map when settings change."""+ logger.debug('Reloading audio map')+ self._audio_map = self._build_audio_map()+ return++ def _build_audio_map(self) -> Dict[str, str]:+ """Build audio signal to URL mapping from current settings."""+ logger.debug('Building audio map')+ settings_manager = self.settings_manager()++ audio_map = dict()+ for audio_signal in AudioSignal:+ if audio_signal.audio_setting:+ attr_value = settings_manager.get_setting_value(audio_signal.audio_setting)+ if attr_value:+ audio_file = AudioFile.from_name(attr_value)+ audio_map[audio_signal.label] = audio_file.url+ continue+ return audio_mapdiff --git a/src/hi/apps/audio/audio_mixins.py b/src/hi/apps/audio/audio_mixins.pynew file mode 100644index 00000000..37f9d412--- /dev/null+++ b/src/hi/apps/audio/audio_mixins.py@@ -0,0 +1,11 @@+from .audio_manager import AudioManager+++class AudioMixin:+ """Mixin to provide easy access to the audio manager."""++ def audio_manager(self) -> AudioManager:+ """Get the audio manager singleton instance."""+ manager = AudioManager()+ manager.ensure_initialized()+ return managerdiff --git a/src/hi/apps/audio/audio_signal.py b/src/hi/apps/audio/audio_signal.pynew file mode 100644index 00000000..7ccecf5f--- /dev/null+++ b/src/hi/apps/audio/audio_signal.py@@ -0,0 +1,78 @@+from hi.apps.alert.enums import AlarmLevel, AlarmSource+from hi.apps.common.enums import LabeledEnum+from hi.apps.weather.enums import WeatherEventType+from .settings import AudioSetting+++class AudioSignal(LabeledEnum):+ """+ Enhanced audio signal system that differentiates between weather and system alerts.++ This replaces the console AudioSignal to support weather-specific audio configuration+ while maintaining compatibility with existing alarm level-based audio.+ """++ # Event Alert Signals+ EVENT_INFO = ( 'EventInfo' , '', AudioSetting.EVENT_INFO_AUDIO_FILE )+ EVENT_WARNING = ( 'EventWarning' , '', AudioSetting.EVENT_WARNING_AUDIO_FILE )+ EVENT_CRITICAL = ( 'EventCritical' , '', AudioSetting.EVENT_CRITICAL_AUDIO_FILE )++ # Weather Alert Signals+ WEATHER_INFO = ( 'WeatherInfo' , '', AudioSetting.WEATHER_INFO_AUDIO_FILE )+ WEATHER_WARNING = ( 'WeatherWarning' , '', AudioSetting.WEATHER_WARNING_AUDIO_FILE )+ WEATHER_CRITICAL = ( 'WeatherCritical', '', AudioSetting.WEATHER_CRITICAL_AUDIO_FILE )++ # Special Weather Event Signals+ WEATHER_TORNADO = ( 'TornadoAlert' , '', AudioSetting.WEATHER_TORNADO_AUDIO_FILE )++ # Console System Status Signals+ CONSOLE_WARNING = ( 'ConsoleWarning' , '', AudioSetting.CONSOLE_WARNING_AUDIO_FILE )+ CONSOLE_INFO = ( 'ConsoleInfo' , '', AudioSetting.CONSOLE_INFO_AUDIO_FILE )++ def __init__( self,+ label : str,+ description : str,+ audio_setting : AudioSetting ):+ super().__init__( label, description )+ self.audio_setting = audio_setting+ return++ @classmethod+ def from_alarm_attributes( cls, alarm_level : AlarmLevel, alarm_source : AlarmSource, alarm_type : str ) -> 'AudioSignal':+ """+ Map alarm attributes to appropriate audio signal.++ Args:+ alarm_level: The alarm level (INFO, WARNING, CRITICAL)+ alarm_source: The alarm source (determines weather vs event)+ alarm_type: The specific alarm type (e.g., WeatherEventType.TORNADO.name for special handling)++ Returns:+ Appropriate AudioSignal enum value or None+ """+ # Special handling for specific weather event types+ if alarm_source == AlarmSource.WEATHER and alarm_type:+ # Tornado gets special treatment regardless of level+ if alarm_type == WeatherEventType.TORNADO.name:+ return cls.WEATHER_TORNADO++ # Weather alerts get weather-specific signals+ if alarm_source == AlarmSource.WEATHER:+ if alarm_level == AlarmLevel.INFO:+ return cls.WEATHER_INFO+ elif alarm_level == AlarmLevel.WARNING:+ return cls.WEATHER_WARNING+ elif alarm_level == AlarmLevel.CRITICAL:+ return cls.WEATHER_CRITICAL++ # All other alerts get event signals+ else:+ if alarm_level == AlarmLevel.INFO:+ return cls.EVENT_INFO+ elif alarm_level == AlarmLevel.WARNING:+ return cls.EVENT_WARNING+ elif alarm_level == AlarmLevel.CRITICAL:+ return cls.EVENT_CRITICAL++ return None+diff --git a/src/hi/apps/audio/context_processors.py b/src/hi/apps/audio/context_processors.pynew file mode 100644index 00000000..11c83e84--- /dev/null+++ b/src/hi/apps/audio/context_processors.py@@ -0,0 +1,9 @@+from .audio_mixins import AudioMixin+++def audio_context(request):+ """Provide audio-related context variables for templates."""+ audio_manager = AudioMixin().audio_manager()+ return {+ 'AUDIO_MAP': audio_manager.get_audio_map(),+ }diff --git a/src/hi/apps/audio/migrations/__init__.py b/src/hi/apps/audio/migrations/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/audio/settings.py b/src/hi/apps/audio/settings.pynew file mode 100644index 00000000..97310213--- /dev/null+++ b/src/hi/apps/audio/settings.py@@ -0,0 +1,105 @@+from hi.apps.config.setting_enums import SettingEnum, SettingDefinition+from hi.apps.attribute.enums import AttributeValueType+from hi.apps.attribute.value_ranges import PredefinedValueRanges++from .audio_file import AudioFile++Label = 'Audio'+++class AudioSetting(SettingEnum):+ """+ Audio settings for alert notifications.++ Provides separate sound configuration for event alerts vs weather alerts+ at each alarm level (INFO, WARNING, CRITICAL).+ """++ # General Event Alert Level Sound Settings+ EVENT_INFO_AUDIO_FILE = SettingDefinition(+ label = 'Event Info Alert Sound',+ description = 'The sound to play when an event INFO level alert arrives.',+ value_type = AttributeValueType.ENUM,+ value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ is_editable = True,+ is_required = False,+ initial_value = AudioFile.INFO,+ )+ EVENT_WARNING_AUDIO_FILE = SettingDefinition(+ label = 'Event Warning Alert Sound',+ description = 'The sound to play when an event WARNING level alert arrives.',+ value_type = AttributeValueType.ENUM,+ value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ is_editable = True,+ is_required = False,+ initial_value = AudioFile.WARNING,+ )+ EVENT_CRITICAL_AUDIO_FILE = SettingDefinition(+ label = 'Event Critical Alert Sound',+ description = 'The sound to play when an event CRITICAL level alert arrives.',+ value_type = AttributeValueType.ENUM,+ value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ is_editable = True,+ is_required = False,+ initial_value = AudioFile.CRITICAL,+ )++ # Weather Alert Sound Settings+ WEATHER_INFO_AUDIO_FILE = SettingDefinition(+ label = 'Weather Info Alert Sound',+ description = 'The sound to play when a weather INFO level alert arrives.',+ value_type = AttributeValueType.ENUM,+ value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ is_editable = True,+ is_required = False,+ initial_value = AudioFile.CHIME,+ )+ WEATHER_WARNING_AUDIO_FILE = SettingDefinition(+ label = 'Weather Warning Alert Sound',+ description = 'The sound to play when a weather WARNING level alert arrives.',+ value_type = AttributeValueType.ENUM,+ value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ is_editable = True,+ is_required = False,+ initial_value = AudioFile.WEATHER_ALERT,+ )+ WEATHER_CRITICAL_AUDIO_FILE = SettingDefinition(+ label = 'Weather Critical Alert Sound',+ description = 'The sound to play when a weather CRITICAL level alert arrives.',+ value_type = AttributeValueType.ENUM,+ value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ is_editable = True,+ is_required = False,+ initial_value = AudioFile.WEATHER_ALERT,+ )++ # Special Weather Event Audio Settings+ WEATHER_TORNADO_AUDIO_FILE = SettingDefinition(+ label = 'Tornado Alert Sound',+ description = 'The sound to play when a tornado alert arrives (any level).',+ value_type = AttributeValueType.ENUM,+ value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ is_editable = True,+ is_required = False,+ initial_value = AudioFile.TORNADO_SIREN,+ )++ # Console System Status Audio Settings+ CONSOLE_WARNING_AUDIO_FILE = SettingDefinition(+ label = 'Console Warning Sound',+ description = 'The sound to play when server connection is lost.',+ value_type = AttributeValueType.ENUM,+ value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ is_editable = True,+ is_required = False,+ initial_value = AudioFile.BUZZER,+ )+ CONSOLE_INFO_AUDIO_FILE = SettingDefinition(+ label = 'Console Info Sound',+ description = 'The sound to play when server connection is restored.',+ value_type = AttributeValueType.ENUM,+ value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,+ is_editable = True,+ is_required = False,+ initial_value = AudioFile.STORE_DOOR_CHIME,+ )diff --git a/src/hi/apps/audio/templates/audio/modals/audio_permission_guidance.html b/src/hi/apps/audio/templates/audio/modals/audio_permission_guidance.htmlnew file mode 100644index 00000000..26ceec24--- /dev/null+++ b/src/hi/apps/audio/templates/audio/modals/audio_permission_guidance.html@@ -0,0 +1,92 @@+{% extends "modals/action_3.html" %}++{% block modal_dialog_id %}audio-guidance-modal{% endblock %}++{% block header_class %}bg-warning{% endblock %}++{% block title_text %}Audio Blocked{% endblock %}++{% block body %}+<div class="mb-3">+ <p>We have detected that your browser is blocking auto-play of alert sounds. In order to hear these alerts, you must grant this app permission by adjusting your browser settings for "auto-play" of audio.</p>++ <p>Generally, browsers have per-site permission settings that can be viewed and adjusted with some icon/button near the address bar, often to the left. You'll want to allow "auto-play" for this site.</p>+</div>++<div class="browser-guidance">+ <p><strong>To adjust your browser's settings, here are specific steps for each browser:</strong></p>++ <!-- Firefox Instructions -->+ <div class="card mb-3">+ <div class="card-header">+ <strong>π¦ Firefox</strong>+ </div>+ <div class="card-body">+ <ol class="mb-2">+ <li>Click the <strong>π lock icon</strong> or <strong>π‘οΈ shield icon</strong> in the address bar</li>+ <li>Find <strong>"Autoplay"</strong> setting</li>+ <li>Change from <strong>"Block Audio"</strong> to <strong>"Allow Audio and Video"</strong></li>+ <li>Refresh this page</li>+ </ol>+ </div>+ </div>++ <!-- Chrome Instructions -->+ <div class="card mb-3">+ <div class="card-header">+ <strong>π― Chrome</strong>+ </div>+ <div class="card-body">+ <ol class="mb-2">+ <li>Click the <strong>π lock icon</strong> in the address bar</li>+ <li>Find <strong>"Sound"</strong> setting</li>+ <li>Change from <strong>"Block"</strong> to <strong>"Allow"</strong></li>+ <li>Chrome will prompt you to refresh - click <strong>"Reload"</strong></li>+ </ol>+ </div>+ </div>++ <!-- Safari Instructions -->+ <div class="card mb-3">+ <div class="card-header">+ <strong>π§ Safari</strong>+ </div>+ <div class="card-body">+ <ol class="mb-2">+ <li>Go to <strong>Safari menu β Settings β Websites</strong></li>+ <li>Click <strong>"Auto-Play"</strong> in the left sidebar</li>+ <li>Find this website and change to <strong>"Allow All Auto-Play"</strong></li>+ <li>Close settings and refresh this page</li>+ </ol>+ </div>+ </div>+</div>++<div class="alert alert-info mt-3">+ <strong>π‘ Why is this needed?</strong> Modern browsers block background audio by default to prevent annoying ads. Since this is a monitoring application that you actively want to receive alerts from, enabling audio is safe and recommended.+</div>+{% endblock %}++{% block action_left %}+<button type="button"+ class="btn btn-outline-secondary"+ data-dismiss="modal">+ Cancel+</button>+{% endblock %}++{% block action_center %}+<button type="button"+ class="btn btn-secondary"+ onclick="Hi.settings.disableAudio(); Hi.audio.updateAudioButtonState(); $(this).closest('.modal').modal('hide');">+ Disable Sounds Instead+</button>+{% endblock %}++{% block action_right %}+<button type="button"+ class="btn btn-primary btn-lg"+ onclick="location.reload();">+ I Fixed It - Reload Page+</button>+{% endblock %}\ No newline at end of filediff --git a/src/hi/apps/audio/tests/__init__.py b/src/hi/apps/audio/tests/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/console/tests/test_audio_file.py b/src/hi/apps/audio/tests/test_audio_file.pysimilarity index 98%rename from src/hi/apps/console/tests/test_audio_file.pyrename to src/hi/apps/audio/tests/test_audio_file.pyindex 7f642878..d53c2adc 100644--- a/src/hi/apps/console/tests/test_audio_file.py+++ b/src/hi/apps/audio/tests/test_audio_file.py@@ -1,6 +1,6 @@import logging-from hi.apps.console.audio_file import AudioFile+from hi.apps.audio.audio_file import AudioFilefrom hi.tests.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)diff --git a/src/hi/apps/audio/tests/test_audio_manager.py b/src/hi/apps/audio/tests/test_audio_manager.pynew file mode 100644index 00000000..217ffa52--- /dev/null+++ b/src/hi/apps/audio/tests/test_audio_manager.py@@ -0,0 +1,78 @@+import logging++from hi.apps.audio.audio_manager import AudioManager+from hi.tests.base_test_case import BaseTestCase++logging.disable(logging.CRITICAL)+++class TestAudioManager(BaseTestCase):++ def test_audio_manager_singleton_behavior(self):+ """Test AudioManager singleton pattern - critical for system consistency."""+ manager1 = AudioManager()+ manager2 = AudioManager()++ self.assertIs(manager1, manager2)+ return++ def test_audio_manager_initialization_state(self):+ """Test AudioManager initialization state tracking - critical setup logic."""+ manager = AudioManager()++ # Test ensure_initialized sets proper state+ manager.ensure_initialized()+ self.assertTrue(manager._was_initialized)++ # Subsequent calls should not change state+ manager.ensure_initialized()+ self.assertTrue(manager._was_initialized)+ return++ def test_audio_manager_mixin_inheritance(self):+ """Test AudioManager mixin inheritance - critical for system integration."""+ manager = AudioManager()++ # Should inherit from SettingsMixin+ self.assertTrue(hasattr(manager, 'settings_manager'))++ # Should be a Singleton+ from hi.apps.common.singleton import Singleton+ self.assertIsInstance(manager, Singleton)+ return++ def test_audio_manager_method_existence(self):+ """Test AudioManager has expected methods - critical API consistency."""+ manager = AudioManager()++ # Should have public interface methods+ self.assertTrue(hasattr(manager, 'get_audio_map'))+ self.assertTrue(callable(manager.get_audio_map))+ return++ def test_audio_manager_audio_map_generation(self):+ """Test audio map generation - critical for UI audio functionality."""+ manager = AudioManager()+ manager.ensure_initialized()++ audio_map = manager.get_audio_map()++ # Should return a dictionary+ self.assertIsInstance(audio_map, dict)++ # Should have entries for the available audio signals+ # (exact content depends on settings, but should not be empty)+ self.assertGreater(len(audio_map), 0)+ return++ def test_audio_manager_audio_mixin_integration(self):+ """Test AudioMixin integration - critical for ease of use."""+ from hi.apps.audio.audio_mixins import AudioMixin++ mixin = AudioMixin()+ manager = mixin.audio_manager()++ # Should return the same singleton instance+ direct_manager = AudioManager()+ self.assertIs(manager, direct_manager)+ returndiff --git a/src/hi/apps/audio/tests/test_audio_signal.py b/src/hi/apps/audio/tests/test_audio_signal.pynew file mode 100644index 00000000..b25a7f7e--- /dev/null+++ b/src/hi/apps/audio/tests/test_audio_signal.py@@ -0,0 +1,86 @@+import logging++from hi.apps.alert.enums import AlarmLevel, AlarmSource+from hi.apps.audio.audio_signal import AudioSignal+from hi.apps.audio.settings import AudioSetting+from hi.tests.base_test_case import BaseTestCase++logging.disable(logging.CRITICAL)+++class TestAudioSignal(BaseTestCase):++ def test_audio_signal_audio_setting_mapping(self):+ """Test audio setting association - critical for audio configuration."""+ # Each AudioSignal should have proper audio setting+ self.assertEqual(AudioSignal.EVENT_INFO.audio_setting, AudioSetting.EVENT_INFO_AUDIO_FILE)+ self.assertEqual(AudioSignal.EVENT_WARNING.audio_setting, AudioSetting.EVENT_WARNING_AUDIO_FILE)+ self.assertEqual(AudioSignal.EVENT_CRITICAL.audio_setting, AudioSetting.EVENT_CRITICAL_AUDIO_FILE)++ self.assertEqual(AudioSignal.WEATHER_INFO.audio_setting, AudioSetting.WEATHER_INFO_AUDIO_FILE)+ self.assertEqual(AudioSignal.WEATHER_WARNING.audio_setting, AudioSetting.WEATHER_WARNING_AUDIO_FILE)+ self.assertEqual(AudioSignal.WEATHER_CRITICAL.audio_setting, AudioSetting.WEATHER_CRITICAL_AUDIO_FILE)++ # Special weather signals+ self.assertEqual(AudioSignal.WEATHER_TORNADO.audio_setting, AudioSetting.WEATHER_TORNADO_AUDIO_FILE)+ return++ def test_audio_signal_labels(self):+ """Test AudioSignal labels - important for UI display."""+ # Event signals+ self.assertEqual(AudioSignal.EVENT_INFO.label, 'EventInfo')+ self.assertEqual(AudioSignal.EVENT_WARNING.label, 'EventWarning')+ self.assertEqual(AudioSignal.EVENT_CRITICAL.label, 'EventCritical')++ # Weather signals+ self.assertEqual(AudioSignal.WEATHER_INFO.label, 'WeatherInfo')+ self.assertEqual(AudioSignal.WEATHER_WARNING.label, 'WeatherWarning')+ self.assertEqual(AudioSignal.WEATHER_CRITICAL.label, 'WeatherCritical')++ # Special weather signals+ self.assertEqual(AudioSignal.WEATHER_TORNADO.label, 'TornadoAlert')++ # Console signals+ self.assertEqual(AudioSignal.CONSOLE_WARNING.label, 'ConsoleWarning')+ self.assertEqual(AudioSignal.CONSOLE_INFO.label, 'ConsoleInfo')+ return++ def test_audio_signal_completeness_with_alarm_levels(self):+ """Test AudioSignal covers all relevant AlarmLevels for both event and weather - critical for complete coverage."""+ # Should have mappings for all non-NONE alarm levels for both event and weather+ event_mapped_levels = []+ weather_mapped_levels = []++ for alarm_level in AlarmLevel:+ if alarm_level == AlarmLevel.NONE:+ continue++ event_signal = AudioSignal.from_alarm_attributes(alarm_level, AlarmSource.EVENT, None)+ weather_signal = AudioSignal.from_alarm_attributes(alarm_level, AlarmSource.WEATHER, None)++ if event_signal is not None:+ event_mapped_levels.append(alarm_level)+ if weather_signal is not None:+ weather_mapped_levels.append(alarm_level)++ expected_mapped_levels = [AlarmLevel.INFO, AlarmLevel.WARNING, AlarmLevel.CRITICAL]+ self.assertEqual(set(event_mapped_levels), set(expected_mapped_levels))+ self.assertEqual(set(weather_mapped_levels), set(expected_mapped_levels))+ return++ def test_audio_signal_weather_vs_event_differentiation(self):+ """Test that weather and event alerts map to different signals - critical for user customization."""+ # Same alarm level should map to different signals for weather vs event+ self.assertNotEqual(+ AudioSignal.from_alarm_attributes(AlarmLevel.INFO, AlarmSource.WEATHER, None),+ AudioSignal.from_alarm_attributes(AlarmLevel.INFO, AlarmSource.EVENT, None)+ )+ self.assertNotEqual(+ AudioSignal.from_alarm_attributes(AlarmLevel.WARNING, AlarmSource.WEATHER, None),+ AudioSignal.from_alarm_attributes(AlarmLevel.WARNING, AlarmSource.EVENT, None)+ )+ self.assertNotEqual(+ AudioSignal.from_alarm_attributes(AlarmLevel.CRITICAL, AlarmSource.WEATHER, None),+ AudioSignal.from_alarm_attributes(AlarmLevel.CRITICAL, AlarmSource.EVENT, None)+ )+ returndiff --git a/src/hi/apps/audio/tests/test_console_audio.py b/src/hi/apps/audio/tests/test_console_audio.pynew file mode 100644index 00000000..669e250e--- /dev/null+++ b/src/hi/apps/audio/tests/test_console_audio.py@@ -0,0 +1,56 @@+import logging++from hi.apps.audio.audio_signal import AudioSignal+from hi.apps.audio.settings import AudioSetting+from hi.tests.base_test_case import BaseTestCase++logging.disable(logging.CRITICAL)+++class TestConsoleAudio(BaseTestCase):+ """Tests for console-specific audio functionality."""++ def test_console_audio_signals_exist(self):+ """Test that console audio signals are properly defined."""+ # Console signals should exist+ self.assertTrue(hasattr(AudioSignal, 'CONSOLE_WARNING'))+ self.assertTrue(hasattr(AudioSignal, 'CONSOLE_INFO'))++ # Should have proper labels+ self.assertEqual(AudioSignal.CONSOLE_WARNING.label, 'ConsoleWarning')+ self.assertEqual(AudioSignal.CONSOLE_INFO.label, 'ConsoleInfo')+ return++ def test_console_audio_settings_mapping(self):+ """Test that console audio signals map to correct settings."""+ # Console signals should map to console settings+ self.assertEqual(AudioSignal.CONSOLE_WARNING.audio_setting, AudioSetting.CONSOLE_WARNING_AUDIO_FILE)+ self.assertEqual(AudioSignal.CONSOLE_INFO.audio_setting, AudioSetting.CONSOLE_INFO_AUDIO_FILE)+ return++ def test_console_audio_in_audio_map(self):+ """Test that console signals appear in the audio manager's audio map."""+ from hi.apps.audio.audio_manager import AudioManager++ manager = AudioManager()+ manager.ensure_initialized()+ audio_map = manager.get_audio_map()++ # Console signals should be in the audio map+ self.assertIn('ConsoleWarning', audio_map)+ self.assertIn('ConsoleInfo', audio_map)++ # Should have valid URLs+ self.assertTrue(audio_map['ConsoleWarning'].startswith('/static/audio/'))+ self.assertTrue(audio_map['ConsoleInfo'].startswith('/static/audio/'))+ return++ def test_console_signal_names_match_javascript_constants(self):+ """Test that signal names match the JavaScript constants."""+ # These should match the constants in audio.js+ expected_warning_name = 'ConsoleWarning'+ expected_info_name = 'ConsoleInfo'++ self.assertEqual(AudioSignal.CONSOLE_WARNING.label, expected_warning_name)+ self.assertEqual(AudioSignal.CONSOLE_INFO.label, expected_info_name)+ returndiff --git a/src/hi/apps/audio/tests/test_integration.py b/src/hi/apps/audio/tests/test_integration.pynew file mode 100644index 00000000..1f1ac990--- /dev/null+++ b/src/hi/apps/audio/tests/test_integration.py@@ -0,0 +1,142 @@+import logging++from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+from hi.apps.alert.enums import AlarmLevel, AlarmSource+from hi.apps.audio.audio_signal import AudioSignal+from hi.apps.security.enums import SecurityLevel+from hi.tests.base_test_case import BaseTestCase++import hi.apps.common.datetimeproxy as datetimeproxy++logging.disable(logging.CRITICAL)+++class TestAudioIntegration(BaseTestCase):+ """Integration tests for the enhanced audio system with weather vs system differentiation."""++ def test_weather_alert_gets_weather_specific_audio(self):+ """Test that weather alerts get weather-specific audio signals."""+ # Create a weather alarm (non-tornado to test general weather level-based mapping)+ weather_alarm = Alarm(+ alarm_source=AlarmSource.WEATHER,+ alarm_type='SEVERE_THUNDERSTORM',+ alarm_level=AlarmLevel.CRITICAL,+ title='Severe Thunderstorm Warning',+ source_details_list=[AlarmSourceDetails(detail_attrs={'location': 'Austin, TX'})],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=1800,+ timestamp=datetimeproxy.now(),+ )++ # Should get weather-specific audio signal+ audio_signal = weather_alarm.audio_signal+ self.assertEqual(audio_signal, AudioSignal.WEATHER_CRITICAL)+ self.assertIn('Weather', audio_signal.label)+ return++ def test_tornado_alert_gets_tornado_specific_audio(self):+ """Test that tornado alerts get tornado-specific audio signals."""+ # Create a tornado alarm+ tornado_alarm = Alarm(+ alarm_source=AlarmSource.WEATHER,+ alarm_type='TORNADO',+ alarm_level=AlarmLevel.CRITICAL,+ title='Tornado Warning',+ source_details_list=[AlarmSourceDetails(detail_attrs={'location': 'Austin, TX'})],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=1800,+ timestamp=datetimeproxy.now(),+ )++ # Should get tornado-specific audio signal (not general weather critical)+ audio_signal = tornado_alarm.audio_signal+ self.assertEqual(audio_signal, AudioSignal.WEATHER_TORNADO)+ self.assertEqual(audio_signal.label, 'TornadoAlert')+ return++ def test_event_alert_gets_event_specific_audio(self):+ """Test that event alerts get event-specific audio signals."""+ # Create a system alarm+ system_alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='DEVICE_FAILURE',+ alarm_level=AlarmLevel.CRITICAL,+ title='Device Failure',+ source_details_list=[AlarmSourceDetails(detail_attrs={'device': 'Sensor-01'})],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=3600,+ timestamp=datetimeproxy.now(),+ )++ # Should get event-specific audio signal+ audio_signal = system_alarm.audio_signal+ self.assertEqual(audio_signal, AudioSignal.EVENT_CRITICAL)+ self.assertIn('Event', audio_signal.label)+ return++ def test_same_level_different_source_gets_different_audio(self):+ """Test that same alarm level with different sources get different audio signals."""+ # Create weather and system alarms with same level+ weather_alarm = Alarm(+ alarm_source=AlarmSource.WEATHER,+ alarm_type='SEVERE_THUNDERSTORM',+ alarm_level=AlarmLevel.WARNING,+ title='Severe Thunderstorm Warning',+ source_details_list=[AlarmSourceDetails(detail_attrs={'location': 'Austin, TX'})],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=1800,+ timestamp=datetimeproxy.now(),+ )++ system_alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='HIGH_TEMP',+ alarm_level=AlarmLevel.WARNING,+ title='High Temperature Alert',+ source_details_list=[AlarmSourceDetails(detail_attrs={'sensor': 'Temp-01'})],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=3600,+ timestamp=datetimeproxy.now(),+ )++ # Should get different audio signals+ weather_audio = weather_alarm.audio_signal+ event_audio = system_alarm.audio_signal++ self.assertNotEqual(weather_audio, event_audio)+ self.assertEqual(weather_audio, AudioSignal.WEATHER_WARNING)+ self.assertEqual(event_audio, AudioSignal.EVENT_WARNING)+ return++ def test_audio_settings_mapping_works(self):+ """Test that audio signals correctly map to their audio settings."""+ # Create alarms of different types and levels+ test_cases = [+ (AlarmSource.WEATHER, AlarmLevel.INFO, AudioSignal.WEATHER_INFO),+ (AlarmSource.WEATHER, AlarmLevel.WARNING, AudioSignal.WEATHER_WARNING),+ (AlarmSource.WEATHER, AlarmLevel.CRITICAL, AudioSignal.WEATHER_CRITICAL),+ (AlarmSource.EVENT, AlarmLevel.INFO, AudioSignal.EVENT_INFO),+ (AlarmSource.EVENT, AlarmLevel.WARNING, AudioSignal.EVENT_WARNING),+ (AlarmSource.EVENT, AlarmLevel.CRITICAL, AudioSignal.EVENT_CRITICAL),+ ]++ for alarm_source, alarm_level, expected_signal in test_cases:+ with self.subTest(source=alarm_source, level=alarm_level):+ alarm = Alarm(+ alarm_source=alarm_source,+ alarm_type='TEST',+ alarm_level=alarm_level,+ title='Test Alarm',+ source_details_list=[AlarmSourceDetails(detail_attrs={'test': 'data'})],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=3600,+ timestamp=datetimeproxy.now(),+ )++ # Should get expected audio signal+ audio_signal = alarm.audio_signal+ self.assertEqual(audio_signal, expected_signal)++ # Should have corresponding audio setting+ self.assertIsNotNone(audio_signal.audio_setting)+ returndiff --git a/src/hi/apps/audio/tests/test_tornado_audio.py b/src/hi/apps/audio/tests/test_tornado_audio.pynew file mode 100644index 00000000..ea031814--- /dev/null+++ b/src/hi/apps/audio/tests/test_tornado_audio.py@@ -0,0 +1,118 @@+import logging++from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+from hi.apps.alert.enums import AlarmLevel, AlarmSource+from hi.apps.audio.audio_signal import AudioSignal+from hi.apps.security.enums import SecurityLevel+from hi.apps.weather.enums import WeatherEventType+from hi.tests.base_test_case import BaseTestCase++import hi.apps.common.datetimeproxy as datetimeproxy++logging.disable(logging.CRITICAL)+++class TestTornadoAudio(BaseTestCase):+ """Tests for tornado-specific audio handling."""++ def test_tornado_gets_special_audio_regardless_of_level(self):+ """Test that tornado alerts get tornado-specific audio signal regardless of alarm level."""+ # Test tornado alerts at different levels all get tornado-specific signal+ tornado_levels = [AlarmLevel.INFO, AlarmLevel.WARNING, AlarmLevel.CRITICAL]++ for alarm_level in tornado_levels:+ with self.subTest(level=alarm_level):+ tornado_alarm = Alarm(+ alarm_source=AlarmSource.WEATHER,+ alarm_type=WeatherEventType.TORNADO.name, # This is how weather alerts set alarm_type+ alarm_level=alarm_level,+ title=f'Tornado {alarm_level.label} Alert',+ source_details_list=[AlarmSourceDetails(detail_attrs={'location': 'Austin, TX'})],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=1800,+ timestamp=datetimeproxy.now(),+ )++ # Should always get tornado-specific audio signal+ audio_signal = tornado_alarm.audio_signal+ self.assertEqual(audio_signal, AudioSignal.WEATHER_TORNADO)+ self.assertEqual(audio_signal.label, 'TornadoAlert')+ return++ def test_other_weather_alerts_get_level_based_audio(self):+ """Test that non-tornado weather alerts still get level-based audio signals."""+ # Test that severe thunderstorm alerts get level-based signals+ severe_storm_alarm = Alarm(+ alarm_source=AlarmSource.WEATHER,+ alarm_type=WeatherEventType.SEVERE_THUNDERSTORM.name,+ alarm_level=AlarmLevel.WARNING,+ title='Severe Thunderstorm Warning',+ source_details_list=[AlarmSourceDetails(detail_attrs={'location': 'Austin, TX'})],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=1800,+ timestamp=datetimeproxy.now(),+ )++ # Should get weather warning signal, not tornado signal+ audio_signal = severe_storm_alarm.audio_signal+ self.assertEqual(audio_signal, AudioSignal.WEATHER_WARNING)+ self.assertNotEqual(audio_signal, AudioSignal.WEATHER_TORNADO)+ return++ def test_tornado_audio_signal_enum_method_mapping(self):+ """Test that the enum mapping method correctly handles tornado types."""+ # Direct method testing+ tornado_signal = AudioSignal.from_alarm_attributes(+ AlarmLevel.INFO,+ AlarmSource.WEATHER,+ WeatherEventType.TORNADO.name+ )+ self.assertEqual(tornado_signal, AudioSignal.WEATHER_TORNADO)++ # Test different levels all return tornado signal+ for level in [AlarmLevel.INFO, AlarmLevel.WARNING, AlarmLevel.CRITICAL]:+ signal = AudioSignal.from_alarm_attributes(+ level,+ AlarmSource.WEATHER,+ WeatherEventType.TORNADO.name+ )+ self.assertEqual(signal, AudioSignal.WEATHER_TORNADO)+ return++ def test_non_tornado_weather_events_use_level_based_mapping(self):+ """Test that non-tornado weather events still use level-based mapping."""+ # Test severe thunderstorm+ severe_storm_signal = AudioSignal.from_alarm_attributes(+ AlarmLevel.WARNING,+ AlarmSource.WEATHER,+ WeatherEventType.SEVERE_THUNDERSTORM.name+ )+ self.assertEqual(severe_storm_signal, AudioSignal.WEATHER_WARNING)++ # Test hurricane+ hurricane_signal = AudioSignal.from_alarm_attributes(+ AlarmLevel.CRITICAL,+ AlarmSource.WEATHER,+ WeatherEventType.HURRICANE.name+ )+ self.assertEqual(hurricane_signal, AudioSignal.WEATHER_CRITICAL)+ return++ def test_event_alerts_unaffected_by_tornado_logic(self):+ """Test that event alerts are unaffected by tornado-specific logic."""+ # Event alerts should still get event-based signals+ event_alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='DEVICE_FAILURE',+ alarm_level=AlarmLevel.CRITICAL,+ title='Device Failure',+ source_details_list=[AlarmSourceDetails(detail_attrs={'device': 'Sensor-01'})],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=3600,+ timestamp=datetimeproxy.now(),+ )++ audio_signal = event_alarm.audio_signal+ self.assertEqual(audio_signal, AudioSignal.EVENT_CRITICAL)+ self.assertNotEqual(audio_signal, AudioSignal.WEATHER_TORNADO)+ returndiff --git a/src/hi/apps/audio/urls.py b/src/hi/apps/audio/urls.pynew file mode 100644index 00000000..dce3d509--- /dev/null+++ b/src/hi/apps/audio/urls.py@@ -0,0 +1,11 @@+from django.urls import re_path++from . import views+++urlpatterns = [++ re_path( r'^permission-guidance$',+ views.AudioPermissionGuidanceView.as_view(),+ name='audio_permission_guidance' ),+]diff --git a/src/hi/apps/audio/views.py b/src/hi/apps/audio/views.pynew file mode 100644index 00000000..6fa20f0c--- /dev/null+++ b/src/hi/apps/audio/views.py@@ -0,0 +1,11 @@+import logging++from hi.hi_async_view import HiModalView++logger = logging.getLogger(__name__)+++class AudioPermissionGuidanceView( HiModalView ):++ def get_template_name( self ) -> str:+ return 'audio/modals/audio_permission_guidance.html'diff --git a/src/hi/apps/config/templates/config/panes/base_page_settings.html b/src/hi/apps/config/templates/config/panes/base_page_settings.htmlindex 98e5497c..9a854843 100644--- a/src/hi/apps/config/templates/config/panes/base_page_settings.html+++ b/src/hi/apps/config/templates/config/panes/base_page_settings.html@@ -1,5 +1,5 @@<div id="hi-console-audio" style="display: none;">- {% for signal_name, signal_sound_url in CONSOLE_AUDIO_MAP.items %}+ {% for signal_name, signal_sound_url in AUDIO_MAP.items %}<audio id="hi-audio-signal-{{ signal_name }}" src="{{ signal_sound_url }}"preload="auto" loop="true" hidden="hidden" ></audio>{% endfor %}diff --git a/src/hi/apps/console/audio_signal.py b/src/hi/apps/console/audio_signal.pydeleted file mode 100644index e9c24ed2..00000000--- a/src/hi/apps/console/audio_signal.py+++ /dev/null@@ -1,29 +0,0 @@-from hi.apps.alert.enums import AlarmLevel-from hi.apps.common.enums import LabeledEnum-from hi.apps.console.settings import ConsoleSetting---class AudioSignal(LabeledEnum):-- INFO = ( 'Info' , '', ConsoleSetting.CONSOLE_INFO_AUDIO_FILE )- WARNING = ( 'Warning' , '', ConsoleSetting.CONSOLE_WARNING_AUDIO_FILE)- CRITICAL = ( 'Critical' , '', ConsoleSetting.CONSOLE_CRITICAL_AUDIO_FILE )-- def __init__( self,- label : str,- description : str,- console_setting : ConsoleSetting ):- super().__init__( label, description )- self.console_setting = console_setting- return-- @classmethod- def from_alarm_level( cls, alarm_level : AlarmLevel ) -> 'AudioSignal':- if alarm_level == AlarmLevel.INFO:- return cls.INFO- if alarm_level == AlarmLevel.WARNING:- return cls.WARNING- if alarm_level == AlarmLevel.CRITICAL:- return cls.CRITICAL- return None-diff --git a/src/hi/apps/console/console_manager.py b/src/hi/apps/console/console_manager.pyindex 4439f0a9..82f9ef75 100644--- a/src/hi/apps/console/console_manager.py+++ b/src/hi/apps/console/console_manager.py@@ -1,5 +1,5 @@import logging-from typing import Dict, List+from typing import Listfrom hi.apps.common.singleton import Singletonfrom hi.apps.config.settings_mixins import SettingsMixin@@ -8,8 +8,6 @@ from hi.apps.entity.entity_manager import EntityManagerfrom hi.apps.sense.sensor_response_manager import SensorResponseMixin-from .audio_file import AudioFile-from .audio_signal import AudioSignalfrom .transient_models import VideoStreamEntitylogger = logging.getLogger(__name__)@@ -25,26 +23,16 @@ class ConsoleManager( Singleton, SettingsMixin, SensorResponseMixin ):if self._was_initialized:return- self.settings_manager().register_change_listener( self._reload_console_audio_map )EntityManager().register_change_listener( self._reload_video_stream_entity_list )- self._console_audio_map = self._build_console_audio_map()self._video_stream_entity_list = self._build_video_stream_entity_list()self._was_initialized = Truereturn- def get_console_audio_map( self ) -> Dict[ str, str ]:- return self._console_audio_map-def get_video_stream_entity_list( self ) -> List[ VideoStreamEntity ]:return self._video_stream_entity_list- def _reload_console_audio_map( self ):- logger.debug( 'Reloading console audio map' )- self._console_audio_map = self._build_console_audio_map()- return-def _reload_video_stream_entity_list(self):self._video_stream_entity_list = self._build_video_stream_entity_list()return@@ -74,18 +62,4 @@ class ConsoleManager( Singleton, SettingsMixin, SensorResponseMixin ):video_stream_entity_list.sort( key = lambda item : item.entity.name )return video_stream_entity_list-- def _build_console_audio_map( self ) -> Dict[ str, str ]:- logger.debug( 'Building console audio map' )- settings_manager = self.settings_manager()-- console_audio_map = dict()- for audio_signal in AudioSignal:- if audio_signal.console_setting:- attr_value = settings_manager.get_setting_value( audio_signal.console_setting )- if attr_value:- audio_file = AudioFile.from_name( attr_value )- console_audio_map[str(audio_signal)] = audio_file.url- continue- return console_audio_mapdiff --git a/src/hi/apps/console/context_processors.py b/src/hi/apps/console/context_processors.pyindex 037c6b8b..4660a6f7 100644--- a/src/hi/apps/console/context_processors.py+++ b/src/hi/apps/console/context_processors.py@@ -1,12 +1,9 @@from hi.apps.console.console_helper import ConsoleSettingsHelper-from hi.apps.console.console_mixins import ConsoleMixindef settings_context(request):console_helper = ConsoleSettingsHelper()- console_manager = ConsoleMixin().console_manager()return {'USER_TIMEZONE': console_helper.get_tz_name(),'SLEEP_OVERLAY_OPACITY': console_helper.get_sleep_overlay_opacity(),- 'CONSOLE_AUDIO_MAP': console_manager.get_console_audio_map(),}diff --git a/src/hi/apps/console/settings.py b/src/hi/apps/console/settings.pyindex ec5e5e92..8ab27d4f 100644--- a/src/hi/apps/console/settings.py+++ b/src/hi/apps/console/settings.py@@ -2,7 +2,6 @@ from hi.apps.config.setting_enums import SettingEnum, SettingDefinitionfrom hi.apps.attribute.enums import AttributeValueTypefrom hi.apps.attribute.value_ranges import PredefinedValueRanges-from .audio_file import AudioFilefrom .enums import Theme, DisplayUnitsLabel = 'Console'@@ -69,31 +68,4 @@ class ConsoleSetting( SettingEnum ):is_required = True,initial_value = '0.95',)- CONSOLE_INFO_AUDIO_FILE = SettingDefinition(- label = 'Info Alert Sound',- description = 'The sound to play when an INFO level alert arrives.',- value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,- is_editable = True,- is_required = False,- initial_value = AudioFile.INFO,- )- CONSOLE_WARNING_AUDIO_FILE = SettingDefinition(- label = 'Warning Alert Sound',- description = 'The sound to play when an WARNING level alert arrives.',- value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,- is_editable = True,- is_required = False,- initial_value = AudioFile.WARNING,- )- CONSOLE_CRITICAL_AUDIO_FILE = SettingDefinition(- label = 'Critical Alert Sound',- description = 'The sound to play when an CRITICAL level alert arrives.',- value_type = AttributeValueType.ENUM,- value_range_str = PredefinedValueRanges.AUDIO_FILE_CHOICES_ID,- is_editable = True,- is_required = False,- initial_value = AudioFile.CRITICAL,- )diff --git a/src/hi/apps/console/templates/console/panes/audio_control.html b/src/hi/apps/console/templates/console/panes/audio_control.htmlindex 8053b7a9..5896744e 100644--- a/src/hi/apps/console/templates/console/panes/audio_control.html+++ b/src/hi/apps/console/templates/console/panes/audio_control.html@@ -1,26 +1,26 @@<div id="hi-audio-state-toggle"><button id="hi-audio-state-enabled"- role="button"- style="display: none;"- class="btn btn-success btn-control"- onclick="Hi.settings.disableAudio() && $(this).hide() && $('#hi-audio-state-disabled').show();"- title="Sounds enabled. Click to Disable">+ role="button"+ style="display: none;"+ class="btn btn-success btn-control"+ onclick="Hi.audio.handleAudioButtonClick();"+ title="Sounds enabled. Click to Disable">Sounds: On</button><button id="hi-audio-state-disabled"- role="button"- class="btn btn-warning btn-control"- onclick="Hi.settings.enableAudio() && $(this).hide() && $('#hi-audio-state-enabled').show();"- title="Sounds disabled. Click to enable">+ role="button"+ style="display: none;"+ class="btn btn-warning btn-control"+ onclick="Hi.audio.handleAudioButtonClick();"+ title="Sounds disabled. Click to enable">Sounds: Off</button>-</div>-<script type="text/javascript" charset="utf-8">- if ( Hi.settings.isAudioEnabled() ) {- $('#hi-audio-state-enabled').show();- $('#hi-audio-state-disabled').hide();- } else {- $('#hi-audio-state-enabled').hide();- $('#hi-audio-state-disabled').show();- }-</script>+ <button id="hi-audio-state-blocked"+ role="button"+ style="display: none;"+ class="btn btn-danger btn-control"+ onclick="Hi.audio.handleAudioButtonClick();"+ title="Browser blocked audio. Click for help">+ Sounds: Blocked+ </button>+</div>\ No newline at end of filediff --git a/src/hi/apps/console/tests/test_audio_signal.py b/src/hi/apps/console/tests/test_audio_signal.pydeleted file mode 100644index dc305c78..00000000--- a/src/hi/apps/console/tests/test_audio_signal.py+++ /dev/null@@ -1,52 +0,0 @@-import logging--from hi.apps.alert.enums import AlarmLevel-from hi.apps.console.audio_signal import AudioSignal-from hi.apps.console.settings import ConsoleSetting-from hi.tests.base_test_case import BaseTestCase--logging.disable(logging.CRITICAL)---class TestAudioSignal(BaseTestCase):-- def test_audio_signal_alarm_level_mapping(self):- """Test from_alarm_level mapping logic - critical for alert audio functionality."""- # Test valid mappings- self.assertEqual(AudioSignal.from_alarm_level(AlarmLevel.INFO), AudioSignal.INFO)- self.assertEqual(AudioSignal.from_alarm_level(AlarmLevel.WARNING), AudioSignal.WARNING)- self.assertEqual(AudioSignal.from_alarm_level(AlarmLevel.CRITICAL), AudioSignal.CRITICAL)-- # Test unmapped alarm level- self.assertIsNone(AudioSignal.from_alarm_level(AlarmLevel.NONE))- return-- def test_audio_signal_console_setting_mapping(self):- """Test console setting association - critical for audio configuration."""- # Each AudioSignal should have proper console setting- self.assertEqual(AudioSignal.INFO.console_setting, ConsoleSetting.CONSOLE_INFO_AUDIO_FILE)- self.assertEqual(AudioSignal.WARNING.console_setting, ConsoleSetting.CONSOLE_WARNING_AUDIO_FILE)- self.assertEqual(AudioSignal.CRITICAL.console_setting, ConsoleSetting.CONSOLE_CRITICAL_AUDIO_FILE)- return-- def test_audio_signal_labels(self):- """Test AudioSignal labels - important for UI display."""- self.assertEqual(AudioSignal.INFO.label, 'Info')- self.assertEqual(AudioSignal.WARNING.label, 'Warning')- self.assertEqual(AudioSignal.CRITICAL.label, 'Critical')- return-- def test_audio_signal_completeness_with_alarm_levels(self):- """Test AudioSignal covers all relevant AlarmLevels - critical for complete alert coverage."""- # Should have mappings for all non-NONE alarm levels- mapped_levels = []- for alarm_level in AlarmLevel:- if alarm_level == AlarmLevel.NONE:- continue- audio_signal = AudioSignal.from_alarm_level(alarm_level)- if audio_signal is not None:- mapped_levels.append(alarm_level)-- expected_mapped_levels = [AlarmLevel.INFO, AlarmLevel.WARNING, AlarmLevel.CRITICAL]- self.assertEqual(set(mapped_levels), set(expected_mapped_levels))- returndiff --git a/src/hi/apps/console/tests/test_console_manager.py b/src/hi/apps/console/tests/test_console_manager.pyindex 2c1b2acc..85fe882c 100644--- a/src/hi/apps/console/tests/test_console_manager.py+++ b/src/hi/apps/console/tests/test_console_manager.py@@ -50,9 +50,7 @@ class TestConsoleManager(BaseTestCase):manager = ConsoleManager()# Should have public interface methods- self.assertTrue(hasattr(manager, 'get_console_audio_map'))self.assertTrue(hasattr(manager, 'get_video_stream_entity_list'))- self.assertTrue(callable(manager.get_console_audio_map))self.assertTrue(callable(manager.get_video_stream_entity_list))return@@ -61,11 +59,9 @@ class TestConsoleManager(BaseTestCase):manager = ConsoleManager()# Should have reload methods for change listeners- self.assertTrue(hasattr(manager, '_reload_console_audio_map'))self.assertTrue(hasattr(manager, '_reload_video_stream_entity_list'))# Methods should be callable- self.assertTrue(callable(manager._reload_console_audio_map))self.assertTrue(callable(manager._reload_video_stream_entity_list))return@@ -74,10 +70,8 @@ class TestConsoleManager(BaseTestCase):manager = ConsoleManager()# Should have build methods- self.assertTrue(hasattr(manager, '_build_console_audio_map'))self.assertTrue(hasattr(manager, '_build_video_stream_entity_list'))# Methods should be callable- self.assertTrue(callable(manager._build_console_audio_map))self.assertTrue(callable(manager._build_video_stream_entity_list))returndiff --git a/src/hi/apps/weather/tests/test_nws.py b/src/hi/apps/weather/tests/test_nws.pyindex 994d930c..d1a6535f 100644--- a/src/hi/apps/weather/tests/test_nws.py+++ b/src/hi/apps/weather/tests/test_nws.py@@ -2277,7 +2277,7 @@ class TestNationalWeatherService( BaseTestCase ):# Verify weather manager was called with alertsmock_weather_manager.update_weather_alerts.assert_called_once_with(- weather_data_source=nws,+ data_point_source=nws.data_point_source,weather_alerts=mock_alerts)returndiff --git a/src/hi/apps/weather/tests/test_sunrise_sunset_org.py b/src/hi/apps/weather/tests/test_sunrise_sunset_org.pyindex 4351d53f..6fe607f5 100644--- a/src/hi/apps/weather/tests/test_sunrise_sunset_org.py+++ b/src/hi/apps/weather/tests/test_sunrise_sunset_org.py@@ -569,7 +569,7 @@ class TestSunriseSunsetOrg(BaseTestCase):# Verify weather manager methods were calledmock_weather_manager.update_astronomical_data.assert_called_once_with(- weather_data_source = self.sunrise_sunset,+ data_point_source = self.sunrise_sunset.data_point_source,astronomical_data_list = [mock_interval_data])diff --git a/src/hi/apps/weather/tests/test_usno.py b/src/hi/apps/weather/tests/test_usno.pyindex fee98922..6c63e9f4 100644--- a/src/hi/apps/weather/tests/test_usno.py+++ b/src/hi/apps/weather/tests/test_usno.py@@ -484,7 +484,7 @@ class TestUSNO(BaseTestCase):# Verify weather manager methods were calledmock_weather_manager.update_astronomical_data.assert_called_once_with(- weather_data_source = self.usno,+ data_point_source = self.usno.data_point_source,astronomical_data_list = [mock_interval_data])diff --git a/src/hi/apps/weather/tests/test_weather_alert_integration.py b/src/hi/apps/weather/tests/test_weather_alert_integration.pyindex e143a332..44992190 100644--- a/src/hi/apps/weather/tests/test_weather_alert_integration.py+++ b/src/hi/apps/weather/tests/test_weather_alert_integration.py@@ -188,7 +188,7 @@ class TestWeatherAlertIntegration(BaseTestCase):# Update weather alerts (this should create alarms)async def test_update():await mock_weather_manager.update_weather_alerts(- weather_data_source=mock_data_source,+ data_point_source=mock_data_source.data_point_source,weather_alerts=test_alerts)diff --git a/src/hi/apps/weather/tests/test_weather_manager.py b/src/hi/apps/weather/tests/test_weather_manager.pyindex 25fb15dd..845ed8ae 100644--- a/src/hi/apps/weather/tests/test_weather_manager.py+++ b/src/hi/apps/weather/tests/test_weather_manager.py@@ -263,7 +263,7 @@ class TestWeatherManager( BaseTestCase ):# Update daily history through weather managerawait weather_manager.update_daily_history(- weather_data_source=mock_weather_source,+ data_point_source=mock_weather_source.data_point_source,history_data_list=history_data_list)@@ -346,7 +346,7 @@ class TestWeatherManager( BaseTestCase ):'create_alarms_from_weather_alerts', return_value=[]):# Update weather alertsawait weather_manager.update_weather_alerts(- weather_data_source=mock_weather_source,+ data_point_source=mock_weather_source.data_point,weather_alerts=[test_alert])@@ -371,7 +371,7 @@ class TestWeatherManager( BaseTestCase ):'create_alarms_from_weather_alerts') as mock_create_alarms:# Update weather alertsawait weather_manager.update_weather_alerts(- weather_data_source=mock_weather_source,+ data_point_source=mock_weather_source.data_point_source,weather_alerts=[test_alert])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 3b65ff68..1b6c6bf8 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@@ -37,10 +37,6 @@ class MockWeatherDataSource(WeatherDataSource):elevation=UnitQuantity(167.0, 'm'))- @property- def geographic_location(self):- return self._mock_location-async def get_data(self):pass # Not used in these tests@@ -107,12 +103,12 @@ class TestWeatherManagerDailyTrackerIntegration(unittest.TestCase):# Update current conditions (should record temperature)asyncio.run(self.weather_manager.update_current_conditions(- weather_data_source=self.mock_source,+ data_point_source=self.mock_source.data_point_source,weather_conditions_data=conditions))# Check that temperature was recorded in daily tracker- location_key = self.weather_manager._get_location_key(self.mock_source)+ location_key = self.weather_manager._get_location_key()summary = self.weather_manager._daily_weather_tracker.get_daily_summary(location_key)self.assertIsNotNone(summary)@@ -204,9 +200,6 @@ class TestWeatherManagerDailyTrackerIntegration(unittest.TestCase):def test_location_key_generation(self):"""Test that location keys are generated correctly."""# Test with weather data source- location_key = self.weather_manager._get_location_key(self.mock_source)- expected_key = "30.270,-97.740" # Based on mock location- self.assertEqual(location_key, expected_key)# Test with no weather data source (should fall back to console settings)with patch('hi.apps.console.console_helper.ConsoleSettingsHelper.get_geographic_location') as mock_geo:@@ -222,7 +215,7 @@ class TestWeatherManagerDailyTrackerIntegration(unittest.TestCase):def test_multiple_temperature_updates_tracking(self):"""Test that multiple temperature updates are tracked correctly."""- location_key = "30.270,-97.740"+ location_key = "30.268,-97.743" # This matches what the WeatherManager actually useswith patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):# Update with multiple different temperatures@@ -231,7 +224,7 @@ class TestWeatherManagerDailyTrackerIntegration(unittest.TestCase):for temp in temperatures:conditions = self.create_test_conditions(temp, include_today_fields=False)asyncio.run(self.weather_manager.update_current_conditions(- weather_data_source=self.mock_source,+ data_point_source=self.mock_source.data_point_source,weather_conditions_data=conditions))@@ -281,7 +274,7 @@ class TestWeatherManagerDailyTrackerIntegration(unittest.TestCase):user_timezone=pacific_tz)- location_key = "30.270,-97.740"+ location_key = "30.268,-97.743" # This matches what the WeatherManager actually uses# Time that's late in the day Pacific timepacific_late = pacific_tz.localize(datetime(2024, 3, 15, 23, 30, 0))@@ -291,7 +284,7 @@ class TestWeatherManagerDailyTrackerIntegration(unittest.TestCase):# Record temperatureconditions = self.create_test_conditions(25.0, utc_late, include_today_fields=False)asyncio.run(self.weather_manager.update_current_conditions(- weather_data_source=self.mock_source,+ data_point_source=self.mock_source.data_point_source,weather_conditions_data=conditions))diff --git a/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py b/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.pyindex c4660e74..f4d550aa 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@@ -93,7 +93,7 @@ class TestWeatherManagerDefensiveHandling(BaseTestCase):# The update should complete successfullyasyncio.run(self.weather_manager.update_current_conditions(- weather_data_source=self.mock_source,+ data_point_source=self.mock_source.data_point_source,weather_conditions_data=conditions))@@ -139,7 +139,7 @@ class TestWeatherManagerDefensiveHandling(BaseTestCase):conditions = self.create_test_conditions(20.0)asyncio.run(self.weather_manager.update_current_conditions(- weather_data_source=self.mock_source,+ data_point_source=self.mock_source.data_point_source,weather_conditions_data=conditions))@@ -213,7 +213,7 @@ class TestWeatherManagerDefensiveHandling(BaseTestCase):# Update conditionsconditions = self.create_test_conditions(30.0)asyncio.run(self.weather_manager.update_current_conditions(- weather_data_source=self.mock_source,+ data_point_source=self.mock_source.data_point_source,weather_conditions_data=conditions))diff --git a/src/hi/apps/weather/weather_manager.py b/src/hi/apps/weather/weather_manager.pyindex 01a45ed8..a5205cbd 100644--- a/src/hi/apps/weather/weather_manager.py+++ b/src/hi/apps/weather/weather_manager.py@@ -33,7 +33,6 @@ from .transient_models import (IntervalAstronomical,WeatherAlert,)-from .weather_data_source import WeatherDataSourcefrom .interval_data_manager import IntervalDataManagerfrom .weather_alert_alarm_mapper import WeatherAlertAlarmMapperfrom .daily_weather_tracker import DailyWeatherTracker@@ -157,18 +156,18 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):return self._weather_alertsasync def update_current_conditions( self,- weather_data_source : WeatherDataSource,+ data_point_source : DataPointSource,weather_conditions_data : WeatherConditionsData ):async with self._data_async_lock:self._update_environmental_data(current_data = self._current_conditions_data,new_data = weather_conditions_data,- data_point_source = weather_data_source.data_point_source,+ data_point_source = data_point_source,)# Record weather conditions for daily tracking (defensive - don't let this break main processing)try:- location_key = self._get_location_key(weather_data_source)+ location_key = self._get_location_key()self._daily_weather_tracker.record_weather_conditions(weather_conditions_data=weather_conditions_data,location_key=location_key@@ -178,24 +177,24 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):returnasync def update_todays_astronomical_data( self,- weather_data_source : WeatherDataSource,- astronomical_data : AstronomicalData ):+ data_point_source : DataPointSource,+ astronomical_data : AstronomicalData ):async with self._data_async_lock:self._update_environmental_data(current_data = self._todays_astronomical_data,new_data = astronomical_data,- data_point_source = weather_data_source.data_point_source,+ data_point_source = data_point_source,)returnasync def update_hourly_forecast( self,- weather_data_source : WeatherDataSource,+ data_point_source : DataPointSource,forecast_data_list : List[IntervalWeatherForecast] ):"""Update hourly forecast data using IntervalDataManager for interval reconciliation."""async with self._data_async_lock:- logger.debug( f'Adding hourly forecast : {weather_data_source.id} [{len(forecast_data_list)}]' )+ logger.debug( f'Adding hourly forecast : {data_point_source.id} [{len(forecast_data_list)}]' )self._hourly_forecast_manager.add_data(- data_point_source = weather_data_source.data_point_source,+ data_point_source = data_point_source,new_interval_data_list = forecast_data_list)@@ -204,13 +203,13 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):returnasync def update_daily_forecast( self,- weather_data_source : WeatherDataSource,+ data_point_source : DataPointSource,forecast_data_list : List[IntervalWeatherForecast] ):"""Update daily forecast data using IntervalDataManager for interval reconciliation."""async with self._data_async_lock:- logger.debug( f'Adding daily forecast: {weather_data_source.id} [{len(forecast_data_list)}]' )+ logger.debug( f'Adding daily forecast: {data_point_source.id} [{len(forecast_data_list)}]' )self._daily_forecast_manager.add_data(- data_point_source = weather_data_source.data_point_source,+ data_point_source = data_point_source,new_interval_data_list = forecast_data_list)@@ -219,13 +218,13 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):returnasync def update_daily_history( self,- weather_data_source : WeatherDataSource,- history_data_list : List[IntervalWeatherHistory] ):+ data_point_source : DataPointSource,+ history_data_list : List[IntervalWeatherHistory] ):"""Update daily history data using IntervalDataManager for interval reconciliation."""async with self._data_async_lock:- logger.debug( f'Adding daily history: {weather_data_source.id} [{len(history_data_list)}]' )+ logger.debug( f'Adding daily history: {data_point_source.id} [{len(history_data_list)}]' )self._daily_history_manager.add_data(- data_point_source = weather_data_source.data_point_source,+ data_point_source = data_point_source,new_interval_data_list = history_data_list)@@ -234,14 +233,14 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):returnasync def update_astronomical_data( self,- weather_data_source : WeatherDataSource,- astronomical_data_list : List[IntervalAstronomical] ):+ data_point_source : DataPointSource,+ astronomical_data_list : List[IntervalAstronomical] ):"""Update astronomical data using IntervalDataManager for interval reconciliation."""async with self._data_async_lock:- logger.debug( f'Adding astronomical: {weather_data_source.id}'+ logger.debug( f'Adding astronomical: {data_point_source.id}'f' [{len(astronomical_data_list)} items]' )self._daily_astronomical_manager.add_data(- data_point_source = weather_data_source.data_point_source,+ data_point_source = data_point_source,new_interval_data_list = astronomical_data_list)# Update canonical astronomical data from aggregated intervals@@ -249,18 +248,18 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):returnasync def update_weather_alerts( self,- weather_data_source : WeatherDataSource,- weather_alerts : List[WeatherAlert] ):+ data_point_source : DataPointSource,+ weather_alerts : List[WeatherAlert] ):"""Update weather alerts from data sources and create system alarms for qualifying alerts."""# Check if weather alerts processing is enabledweather_settings_helper = WeatherSettingsHelper()if not weather_settings_helper.is_weather_alerts_enabled():logger.debug(f'Weather alerts processing disabled, ignoring'- f' {len(weather_alerts)} alerts from {weather_data_source.id}')+ f' {len(weather_alerts)} alerts from {data_point_source.id}')returnasync with self._data_async_lock:- logger.debug( f'Received weather alerts from {weather_data_source.id}:'+ logger.debug( f'Received weather alerts from {data_point_source.id}:'f' {len(weather_alerts)} alerts' )# For now, simply replace all alerts with the new ones from this source@@ -441,23 +440,15 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):DIVID['WEATHER_ALERTS']: weather_alerts_html_str,}- def _get_location_key(self, weather_data_source=None):+ def _get_location_key(self):"""Generate a location key for the daily weather tracker.-- Args:- weather_data_source: Optional weather source to get location fromReturns:String key representing the geographic location"""- if weather_data_source and hasattr(weather_data_source, 'geographic_location'):- geo_location = weather_data_source.geographic_location- else:- # Fallback: try to get location from any available weather source- # This is needed when called from get_current_conditions_data()- console_helper = ConsoleSettingsHelper()- geo_location = console_helper.get_geographic_location()+ console_helper = ConsoleSettingsHelper()+ geo_location = console_helper.get_geographic_location()if geo_location:# Create location key from lat/lon rounded to 3 decimal placesdiff --git a/src/hi/apps/weather/weather_mixins.py b/src/hi/apps/weather/weather_mixins.pyindex 2b117b4d..80095c76 100644--- a/src/hi/apps/weather/weather_mixins.py+++ b/src/hi/apps/weather/weather_mixins.py@@ -2,20 +2,20 @@ from asgiref.sync import sync_to_asyncimport asyncioimport logging-from .weather_manager import WeatherManager-logger = logging.getLogger(__name__)class WeatherMixin:def weather_manager(self):+ from .weather_manager import WeatherManagerif not hasattr( self, '_weather_manager' ):self._weather_manager = WeatherManager()self._weather_manager.ensure_initialized()return self._weather_managerasync def weather_manager_async(self):+ from .weather_manager import WeatherManagerif not hasattr( self, '_weather_manager' ):self._weather_manager = WeatherManager()try:diff --git a/src/hi/apps/weather/weather_source_discovery.py b/src/hi/apps/weather/weather_source_discovery.pyindex 5620ca56..eed99462 100644--- a/src/hi/apps/weather/weather_source_discovery.py+++ b/src/hi/apps/weather/weather_source_discovery.py@@ -21,6 +21,7 @@ class WeatherSourceDiscovery:This is the single source of truth for weather source discovery,used by both the settings system and the monitoring system."""+ from .weather_data_source import WeatherDataSourcesources_dir = os.path.join(Path(__file__).parent, 'weather_sources')logger.debug(f'Discovering weather sources in: {sources_dir}')diff --git a/src/hi/apps/weather/weather_sources/nws.py b/src/hi/apps/weather/weather_sources/nws.pyindex 719bc75e..c125574c 100644--- a/src/hi/apps/weather/weather_sources/nws.py+++ b/src/hi/apps/weather/weather_sources/nws.py@@ -98,7 +98,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):)if current_conditions_data:await weather_manager.update_current_conditions(- weather_data_source = self,+ data_point_source = self.data_point_source,weather_conditions_data = current_conditions_data,)except Exception as e:@@ -111,7 +111,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):)if interval_hourly_forecast_list:await weather_manager.update_hourly_forecast(- weather_data_source = self,+ data_point_source = self.data_point_source,forecast_data_list = interval_hourly_forecast_list,)except Exception as e:@@ -124,7 +124,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):)if interval_daily_forecast_list:await weather_manager.update_daily_forecast(- weather_data_source = self,+ data_point_source = self.data_point_source,forecast_data_list = interval_daily_forecast_list,)except Exception as e:@@ -137,7 +137,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):)if weather_alerts:await weather_manager.update_weather_alerts(- weather_data_source = self,+ data_point_source = self.data_point_source,weather_alerts = weather_alerts,)except Exception as e:diff --git a/src/hi/apps/weather/weather_sources/openmeteo.py b/src/hi/apps/weather/weather_sources/openmeteo.pyindex ad4a4c67..0a75be18 100644--- a/src/hi/apps/weather/weather_sources/openmeteo.py+++ b/src/hi/apps/weather/weather_sources/openmeteo.py@@ -83,7 +83,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):)if current_conditions_data:await weather_manager.update_current_conditions(- weather_data_source = self,+ data_point_source = self.data_point_source,weather_conditions_data = current_conditions_data,)except Exception as e:@@ -96,7 +96,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):)if interval_hourly_forecast_list:await weather_manager.update_hourly_forecast(- weather_data_source = self,+ data_point_source = self.data_point_source,forecast_data_list = interval_hourly_forecast_list,)except Exception as e:@@ -109,7 +109,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):)if interval_daily_forecast_list:await weather_manager.update_daily_forecast(- weather_data_source = self,+ data_point_source = self.data_point_source,forecast_data_list = interval_daily_forecast_list,)except Exception as e:@@ -124,7 +124,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):)if interval_daily_history_list:await weather_manager.update_daily_history(- weather_data_source = self,+ data_point_source = self.data_point_source,history_data_list = interval_daily_history_list,)else:diff --git a/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py b/src/hi/apps/weather/weather_sources/sunrise_sunset_org.pyindex ba8a2bd0..160072e7 100644--- a/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py+++ b/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py@@ -86,7 +86,7 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):)if astronomical_data_list:await weather_manager.update_astronomical_data(- weather_data_source = self,+ data_point_source = self.data_point_source,astronomical_data_list = astronomical_data_list,)except Exception as e:@@ -99,7 +99,7 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):)if todays_astronomical_data:await weather_manager.update_todays_astronomical_data(- weather_data_source = self,+ data_point_source = self.data_point_source,astronomical_data = todays_astronomical_data,)except Exception as e:diff --git a/src/hi/apps/weather/weather_sources/usno.py b/src/hi/apps/weather/weather_sources/usno.pyindex 3f7eb293..7c553a1c 100644--- a/src/hi/apps/weather/weather_sources/usno.py+++ b/src/hi/apps/weather/weather_sources/usno.py@@ -95,7 +95,7 @@ class USNO(WeatherDataSource, WeatherMixin):)if astronomical_data_list:await weather_manager.update_astronomical_data(- weather_data_source = self,+ data_point_source = self.data_point_source,astronomical_data_list = astronomical_data_list,)except Exception as e:@@ -108,7 +108,7 @@ class USNO(WeatherDataSource, WeatherMixin):)if todays_astronomical_data:await weather_manager.update_todays_astronomical_data(- weather_data_source = self,+ data_point_source = self.data_point_source,astronomical_data = todays_astronomical_data,)except Exception as e:diff --git a/src/hi/hi_async_view.py b/src/hi/hi_async_view.pyindex 2262acb4..1166b21c 100644--- a/src/hi/hi_async_view.py+++ b/src/hi/hi_async_view.py@@ -108,6 +108,9 @@ class HiModalView( View ):def get_template_name( self ) -> str:raise NotImplementedError('Subclasses must override this method.')+ def get( self, request, *args, **kwargs ):+ return self.modal_response( request )+def modal_response( self, request, context = None, status = 200 ):if context is None:context = dict()diff --git a/src/hi/settings/base.py b/src/hi/settings/base.pyindex 397394e7..26164f93 100644--- a/src/hi/settings/base.py+++ b/src/hi/settings/base.py@@ -112,6 +112,7 @@ INSTALLED_APPS = ['hi.apps.event','hi.apps.notify','hi.apps.alert',+ 'hi.apps.audio','hi.apps.security','hi.apps.edit','hi.apps.api',@@ -153,6 +154,7 @@ TEMPLATES = ['django.contrib.messages.context_processors.messages','hi.context_processors.constants_context','hi.apps.console.context_processors.settings_context',+ 'hi.apps.audio.context_processors.audio_context',],},},@@ -244,6 +246,7 @@ PIPELINE = {'js/autosize.min.js','js/main.js','js/settings.js',+ 'js/audio.js',),'output_filename': 'js/js_before_content.js',},diff --git a/src/hi/settings/development.py b/src/hi/settings/development.pyindex 0a948a16..51e191a2 100644--- a/src/hi/settings/development.py+++ b/src/hi/settings/development.py@@ -67,7 +67,7 @@ LOGGING = {},'hi.apps.alert': {'handlers': ['console' ],- 'level': 'INFO',+ 'level': 'DEBUG','propagate': False,},'hi.apps.control': {@@ -97,7 +97,7 @@ LOGGING = {},'hi.apps.weather': {'handlers': ['console' ],- 'level': 'DEBUG',+ 'level': 'INFO','propagate': False,},'hi.integrations': {diff --git a/src/hi/static/js/audio.js b/src/hi/static/js/audio.jsindex 812c2856..cc2467cd 100644--- a/src/hi/static/js/audio.js+++ b/src/hi/static/js/audio.js@@ -2,25 +2,37 @@window.Hi = window.Hi || {};const HiAudio = {-- WARNING_SIGNAL_NAME: 'warning',- INFO_SIGNAL_NAME: 'info',-- init: function() {- startAudioPolling();- },+ // Constants used by status.js+ WARNING_SIGNAL_NAME: 'ConsoleWarning',+ INFO_SIGNAL_NAME: 'ConsoleInfo',++ // Audio playback methods used by status.jsstartAudibleSignal: function( signalName ) {- _startAudibleSignal( signalName );+ _startAudibleSignal( signalName );+ },+ setMaxSignalName: function( signalName ) {+ return _setMaxSignalName( signalName );},- setMaxSignalName: function( signalName ) {- return _setMaxSignalName( signalName );- }++ // Audio control UI methods used by audio_control.html+ updateAudioButtonState: function() {+ return _updateAudioButtonState();+ },+ handleAudioButtonClick: function() {+ return _handleAudioButtonClick();+ },++ // Initialization+ init: function() {+ startAudioPolling();+ }};window.Hi.audio = HiAudio;window.addEventListener('load', function() {- HiAudio.init();+ HiAudio.init();+ _setupAudioErrorHandlers();});const AudioPollingWatchdogType = 'audioPolling';@@ -31,38 +43,53 @@let gCurrentMaxSignalName = null;function startAudioPolling() {- Hi.watchdog.add( AudioPollingWatchdogType,- checkAudioStatus,- AudioPollingIntervalMs );- gAudioPollingTimer = setTimeout( checkAudioStatus, AudioPollingStartDelayMs );+ if (Hi.DEBUG) { console.log('π΅ Starting audio polling system'); }++ if (typeof Hi.watchdog === 'undefined') {+ if (Hi.DEBUG) { console.error('β Hi.watchdog not available - audio polling disabled'); }+ return;+ }++ if (Hi.DEBUG) { console.log(`π Adding audio watchdog (interval: ${AudioPollingIntervalMs}ms, start delay: ${AudioPollingStartDelayMs}ms)`); }++ Hi.watchdog.add( AudioPollingWatchdogType,+ checkAudioStatus,+ AudioPollingIntervalMs );+ gAudioPollingTimer = setTimeout( checkAudioStatus, AudioPollingStartDelayMs );++ if (Hi.DEBUG) { console.log('β Audio polling system initialized'); }}function setAudioPollingTimer() {- clearAudioPollingTimer();- gAudioPollingTimer = setTimeout( checkAudioStatus, AudioPollingIntervalMs );+ clearAudioPollingTimer();+ gAudioPollingTimer = setTimeout( checkAudioStatus, AudioPollingIntervalMs );}function clearAudioPollingTimer() {- if ( gAudioPollingTimer ) {- clearTimeout( gAudioPollingTimer );- gAudioPollingTimer = null;- }+ if ( gAudioPollingTimer ) {+ clearTimeout( gAudioPollingTimer );+ gAudioPollingTimer = null;+ }}function checkAudioStatus() {- clearAudioPollingTimer();- try {- Hi.watchdog.ok( AudioPollingWatchdogType );+ clearAudioPollingTimer();+ try {+ if (Hi.DEBUG) { console.log(`π Audio polling check - current max signal: ${gCurrentMaxSignalName}`); }++ Hi.watchdog.ok( AudioPollingWatchdogType );- if ( gCurrentMaxSignalName ) {- if ( Hi.DEBUG ) { console.log( "Audio max signal found." ); }- _startAudibleSignal( gCurrentMaxSignalName );- }- } catch (e) {- console.error( `Exception in audio polling: ${e} (line=${e.lineNumber})` );- } finally {- setAudioPollingTimer();- }+ if ( gCurrentMaxSignalName ) {+ if ( Hi.DEBUG ) { console.log( `π Audio max signal found: ${gCurrentMaxSignalName}` ); }+ _startAudibleSignal( gCurrentMaxSignalName );+ } else {+ if ( Hi.DEBUG ) { console.log( "π No audio signal to play" ); }+ }+ } catch (e) {+ console.error( `Exception in audio polling: ${e} (line=${e.lineNumber})` );+ } finally {+ setAudioPollingTimer();+ }}const SignalAudioIdPrefix = 'hi-audio-signal';@@ -72,70 +99,551 @@let gActiveAudibleSignalName = null;function _setMaxSignalName( signalName ) {- gCurrentMaxSignalName = signalName;- return true;+ if (Hi.DEBUG) { console.log(`π’ Setting max audio signal: ${signalName}`); }+ gCurrentMaxSignalName = signalName;+ if (Hi.DEBUG) { console.log(`π’ gCurrentMaxSignalName is now: ${gCurrentMaxSignalName}`); }+ return true;}function setAudibleSignalTimer( ) {- clearAudibleSignalTimer();- gAudibleSignalTimer = setTimeout( endAudibleSignal, AudibleSignalDurationMs );+ clearAudibleSignalTimer();+ gAudibleSignalTimer = setTimeout( endAudibleSignal, AudibleSignalDurationMs );}function clearAudibleSignalTimer( ) {- if ( gAudibleSignalTimer ) {- clearTimeout( gAudibleSignalTimer );- gAudibleSignalTimer = null;- }+ if ( gAudibleSignalTimer ) {+ clearTimeout( gAudibleSignalTimer );+ gAudibleSignalTimer = null;+ }}function getAudioElementId( signalName ) {- return `${SignalAudioIdPrefix}-${signalName}`;+ return `${SignalAudioIdPrefix}-${signalName}`;}function _startAudibleSignal( signalName ) {- if ( Hi.DEBUG ) { console.log( `Starting audio signal = ${signalName}` ); }- try {- stopAudio( );- clearAudibleSignalTimer();- if ( ! Hi.settings.isAudioEnabled() ) {- return;- }- let id = getAudioElementId( signalName );- let elem = document.getElementById(id);- if ( ! elem ) {- if ( Hi.DEBUG ) { console.log( `Missing audio tag for ${signalName}` ); }- return;- }- else {- elem.currentTime = 0;- elem.play();- gActiveAudibleSignalName = signalName;- setAudibleSignalTimer();- }- }- catch (e) {- console.error( `Exception starting audible signal: ${e} (line=${e.lineNumber})` );- }+ if ( Hi.DEBUG ) { console.log( `π΅ Starting audio signal = ${signalName}` ); }+ if ( Hi.DEBUG ) { console.log( `π§ Audio enabled check: ${Hi.settings.isAudioEnabled()}` ); }+ try {+ stopAudio( );+ clearAudibleSignalTimer();+ if ( ! Hi.settings.isAudioEnabled() ) {+ if ( Hi.DEBUG ) { console.log( `π Audio disabled, not playing signal: ${signalName}` ); }+ return;+ }+ let id = getAudioElementId( signalName );+ if ( Hi.DEBUG ) { console.log( `π Looking for audio element with ID: ${id}` ); }+ let elem = document.getElementById(id);+ if ( ! elem ) {+ if ( Hi.DEBUG ) { console.log( `β Missing audio tag for ${signalName}` ); }+ return;+ }+ if ( Hi.DEBUG ) { console.log( `β Found audio element for ${signalName}` ); }++ // Check if audio file loaded successfully+ if (elem.readyState === 0) {+ console.error( `Audio file not loaded for ${signalName}` );+ return;+ }++ // Check for audio loading errors+ if (elem.error) {+ console.error( `Audio file error for ${signalName}: ${elem.error.message}` );+ return;+ }+ else {+ elem.currentTime = 0;+ // Handle autoplay policy restrictions+ const playPromise = elem.play();+ if ( Hi.DEBUG ) { console.log( `π΅ Attempting to play audio element: ${id}` ); }+ if (playPromise !== undefined) {+ playPromise.then(() => {+ // Audio playback started successfully+ if ( Hi.DEBUG ) { console.log( `β Audio playback started successfully: ${signalName}` ); }+ gActiveAudibleSignalName = signalName;+ setAudibleSignalTimer();+ }).catch(error => {+ // Autoplay was prevented+ if (error.name === 'NotAllowedError') {+ if ( Hi.DEBUG ) { console.log( `β Audio autoplay blocked for ${signalName}` ); }+ _showPermissionGuidanceIfNeeded();+ } else {+ console.error( `Audio playback error for ${signalName}: ${error}` );+ }+ });+ } else {+ // Fallback for older browsers that don't return a Promise+ gActiveAudibleSignalName = signalName;+ setAudibleSignalTimer();+ }+ }+ }+ catch (e) {+ console.error( `Exception starting audible signal: ${e} (line=${e.lineNumber})` );+ }}function endAudibleSignal( ) {- stopAudio();- clearAudibleSignalTimer();-- // Always "reset" this so we do not signal too frequently- setAudioPollingTimer();+ stopAudio();+ clearAudibleSignalTimer();++ // Always "reset" this so we do not signal too frequently+ setAudioPollingTimer();}function stopAudio( ) {- if ( ! gActiveAudibleSignalName ) {- return;- }- let id = getAudioElementId( gActiveAudibleSignalName );- let elem = document.getElementById(id);- if ( elem ) {- elem.pause();- }- gActiveAudibleSignalName = null;+ if ( ! gActiveAudibleSignalName ) {+ return;+ }+ let id = getAudioElementId( gActiveAudibleSignalName );+ let elem = document.getElementById(id);+ if ( elem ) {+ elem.pause();+ }+ gActiveAudibleSignalName = null;}+ function _setupAudioErrorHandlers( ) {+ // Add error handlers to all audio elements+ const audioElements = document.querySelectorAll('audio[id^="hi-audio-signal-"]');+ audioElements.forEach(function(elem) {+ elem.addEventListener('error', function(e) {+ const signalName = elem.id.replace('hi-audio-signal-', '');+ console.error( `Audio loading error for ${signalName}: ${e.target.error ? e.target.error.message : 'Unknown error'}` );+ });++ elem.addEventListener('loadstart', function(e) {+ if ( Hi.DEBUG ) {+ const signalName = elem.id.replace('hi-audio-signal-', '');+ console.log( `Loading audio for ${signalName}` );+ }+ });++ elem.addEventListener('canplaythrough', function(e) {+ if ( Hi.DEBUG ) {+ const signalName = elem.id.replace('hi-audio-signal-', '');+ console.log( `Audio ready for ${signalName}` );+ }+ });+ });+ }++ function _showPermissionGuidanceIfNeeded() {+ // Only show guidance once per browser/user+ if (Hi.settings.hasShownPermissionGuidance()) {+ return;+ }++ // Mark as shown to prevent future displays+ Hi.settings.markPermissionGuidanceShown();++ // Show the server-rendered notification element+ _showPermissionGuidanceNotification();+ }++ function _showPermissionGuidanceNotification() {+ // Show the pre-rendered notification element+ $(Hi.AUDIO_PERMISSION_GUIDANCE_SELECTOR).show();++ // Auto-dismiss after 8 seconds+ setTimeout(function() {+ $(Hi.AUDIO_PERMISSION_GUIDANCE_SELECTOR).fadeOut(500);+ }, 8000);+ }++ /*+ AUDIO PERMISSION HANDLING++ - Modern browser autoplay policy detection and management+ - Dual-state system: baseline (no user interaction) vs current state+ */++ const AudioPermissionState = {+ GRANTED: 'granted',+ BLOCKED: 'blocked',+ UNKNOWN: 'unknown'+ };++ const FirefoxAutoplayPolicy = {+ ALLOWED: 'allowed',+ ALLOWED_MUTED: 'allowed-muted',+ DISALLOWED: 'disallowed'+ };++ const AudioButtonState = {+ ENABLED: 'enabled',+ DISABLED: 'disabled',+ BLOCKED: 'blocked'+ };++ function _getAudioPermissionState() {+ if (Hi.DEBUG) { console.log('_getAudioPermissionState() called'); }++ // Method 1: Firefox getAutoplayPolicy API+ if (typeof navigator.getAutoplayPolicy === 'function') {+ const policy = navigator.getAutoplayPolicy('mediaelement');+ if (Hi.DEBUG) { console.log('Using navigator.getAutoplayPolicy, result:', policy); }++ // Firefox autoplay policy values for BACKGROUND ALERTS:+ // "allowed" = Background alerts can play audio automatically+ // "allowed-muted" = Background alerts blocked (can only play muted audio)+ // "disallowed" = Background alerts completely blocked+ if (policy === FirefoxAutoplayPolicy.ALLOWED) {+ if (Hi.DEBUG) { console.log('Firefox: Background alert audio allowed'); }+ return AudioPermissionState.GRANTED;+ } else {+ if (Hi.DEBUG) { console.log('Firefox: Background alert audio blocked'); }+ return AudioPermissionState.BLOCKED;+ }+ }++ // Method 2: Fallback for Chrome/Safari/others+ // Test background alert audio capability (autoplay without user activation)+ if (Hi.DEBUG) { console.log('Testing background alert audio capability...'); }+ const testAudio = document.createElement('audio');+ testAudio.muted = false;+ testAudio.volume = 0.001; // Nearly silent but not muted - tests real autoplay+ testAudio.src = 'data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+D2w3UlBSuBzvLZiTYIF2ez7eeZVQwKT6zj9r5uHwU8k9n2vpg8Cwi';++ // Test autoplay without user activation (same context as background alerts)+ const playPromise = testAudio.play();+ if (playPromise !== undefined) {+ return playPromise.then(() => {+ testAudio.pause();+ if (Hi.DEBUG) { console.log('Background alert audio test succeeded - GRANTED'); }+ return AudioPermissionState.GRANTED;+ }).catch((error) => {+ if (Hi.DEBUG) { console.log('Background alert audio test failed:', error.name); }+ // Handle different browser error types+ if (error.name === 'NotAllowedError' || error.name === 'AbortError') {+ if (Hi.DEBUG) { console.log('Background alert audio blocked - BLOCKED'); }+ return AudioPermissionState.BLOCKED;+ }+ if (Hi.DEBUG) { console.log('Unknown autoplay error - UNKNOWN'); }+ return AudioPermissionState.UNKNOWN;+ });+ }++ // Very old browsers without Promise support+ if (Hi.DEBUG) { console.log('No Promise support - assuming UNKNOWN'); }+ return AudioPermissionState.UNKNOWN;+ }++ async function _requestAudioPermission() {+ try {+ if (Hi.DEBUG) { console.log('Attempting audio permission request via user activation...'); }++ // Check current autoplay state before user activation+ const policyBefore = typeof navigator.getAutoplayPolicy === 'function' ?+ navigator.getAutoplayPolicy('mediaelement') : 'API not available';+ if (Hi.DEBUG) { console.log('Policy before user activation:', policyBefore); }++ // Try to play audible test audio with user activation+ const testAudio = document.createElement('audio');+ testAudio.src = 'data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+D2w3UlBSuBzvLZiTYIF2ez7eeZVQwKT6zj9r5uHwU8k9n2vpg8Cwi';+ testAudio.volume = 0.01;+ testAudio.muted = false;++ const playPromise = testAudio.play();+ if (playPromise !== undefined) {+ try {+ await playPromise;+ testAudio.pause();+ if (Hi.DEBUG) { console.log('User activation audio succeeded'); }++ // Check if Firefox policy changed after user interaction+ if (typeof navigator.getAutoplayPolicy === 'function') {+ const policyAfter = navigator.getAutoplayPolicy('mediaelement');+ if (Hi.DEBUG) { console.log('Policy after user activation:', policyAfter); }++ if (policyAfter === FirefoxAutoplayPolicy.ALLOWED) {+ if (Hi.DEBUG) { console.log('Firefox: User activation granted full autoplay permission'); }+ return AudioPermissionState.GRANTED;+ } else {+ if (Hi.DEBUG) { console.log('Firefox: User activation succeeded but autoplay still restricted'); }+ if (Hi.DEBUG) { console.log('This means audio works with user interaction but not automatically'); }+ // In this case, we consider permission "granted" for user-activated audio+ // even though autoplay remains blocked+ return AudioPermissionState.GRANTED;+ }+ } else {+ // Chrome/Safari: If user activation succeeded, permission is granted+ if (Hi.DEBUG) { console.log('Chrome/Safari: User activation succeeded - permission granted'); }+ return AudioPermissionState.GRANTED;+ }+ } catch (playError) {+ if (Hi.DEBUG) { console.log('User activation audio failed:', playError.name); }+ if (playError.name === 'NotAllowedError' || playError.name === 'AbortError') {+ return AudioPermissionState.BLOCKED;+ }+ throw playError;+ }+ }+ return AudioPermissionState.UNKNOWN;+ } catch (error) {+ if (Hi.DEBUG) { console.log('Permission request error:', error.name); }+ if (error.name === 'NotAllowedError' || error.name === 'AbortError') {+ return AudioPermissionState.BLOCKED;+ }+ throw error;+ }+ }++ /*+ AUDIO CONTROL UI MANAGEMENT++ - Dual-state audio permission system for button display+ - Baseline monitoring and user interaction handling+ */++ // Dual-state audio permission system variables+ const BASELINE_STATE_MONITOR_INTERVAL_MS = 15 * 1000;++ let baselineAudioState = null; // State immediately after page load (no user interaction)+ let currentAudioState = null; // State right now (may include user interaction effects)+ let baselineRecheckTimer = null;++ function hasBaselineStateChanged() {+ return currentAudioState !== null && currentAudioState !== baselineAudioState;+ }++ async function _setInitialBaselineState() {+ if (Hi.DEBUG) { console.log('π― Setting initial baseline audio state (clean page load)'); }++ try {+ const state = await _getAudioPermissionState();+ baselineAudioState = state;+ currentAudioState = state; // At page load, current state equals baseline state++ if (Hi.DEBUG) { console.log(`Initial baseline and current audio state: ${baselineAudioState}`); }++ // Update button display based on current state+ await _updateAudioButtonState();++ return baselineAudioState;+ } catch (error) {+ if (Hi.DEBUG) { console.error('Error setting initial baseline audio state:', error); }+ return null;+ }+ }++ async function _checkForBaselineStateChange() {+ if (hasBaselineStateChanged()) {+ // Already detected a change, no need to keep checking+ return;+ }++ if (Hi.DEBUG) { console.log('π Checking for baseline audio state changes'); }++ try {+ const state = await _getAudioPermissionState();+ currentAudioState = state;++ if (hasBaselineStateChanged()) {+ if (Hi.DEBUG) { console.log(`π Baseline state changed: ${baselineAudioState} β ${currentAudioState}`); }++ // Update button display+ await _updateAudioButtonState();++ // Stop monitoring since we detected a change+ if (baselineRecheckTimer) {+ if (Hi.DEBUG) { console.log('π Stopping baseline monitoring - change detected'); }+ clearInterval(baselineRecheckTimer);+ baselineRecheckTimer = null;+ }+ } else {+ if (Hi.DEBUG) { console.log(`Baseline state unchanged: ${baselineAudioState}`); }+ }+ } catch (error) {+ if (Hi.DEBUG) { console.error('Error checking for baseline state change:', error); }+ }+ }++ async function _checkCurrentAudioState() {+ if (Hi.DEBUG) { console.log('π Checking current audio state'); }++ try {+ const state = await _getAudioPermissionState();+ currentAudioState = state;++ if (Hi.DEBUG) { console.log(`Current audio state: ${currentAudioState}`); }++ return currentAudioState;+ } catch (error) {+ if (Hi.DEBUG) { console.error('Error checking current audio state:', error); }+ return null;+ }+ }+++ async function _startBaselineMonitoring() {+ if (Hi.DEBUG) { console.log('π― Starting baseline audio monitoring system'); }++ // Set initial baseline immediately on page load (cleanest state)+ await _setInitialBaselineState();++ // Only start baseline monitoring if baseline state is blocked+ if (baselineAudioState === AudioPermissionState.BLOCKED) {+ if (Hi.DEBUG) { console.log('π Starting baseline state monitoring (baseline is blocked)'); }+ baselineRecheckTimer = setInterval(async () => {+ await _checkForBaselineStateChange();+ }, BASELINE_STATE_MONITOR_INTERVAL_MS );+ } else {+ if (Hi.DEBUG) { console.log('β Baseline state is allowed - no monitoring needed'); }+ }+ }++ async function _updateAudioButtonState() {+ // Hide all buttons first+ $('#hi-audio-state-enabled').hide();+ $('#hi-audio-state-disabled').hide();+ $('#hi-audio-state-blocked').hide();++ try {+ // Use current state for button display (fallback to fresh check if needed)+ const permissionState = currentAudioState || await _getAudioPermissionState();++ // Priority order: Disabled > Blocked > Enabled+ if (!Hi.settings.isAudioEnabled()) {+ // User has explicitly disabled audio - show disabled (takes precedence)+ $('#hi-audio-state-disabled').show();+ } else if (permissionState === AudioPermissionState.BLOCKED) {+ // User wants audio but permissions are blocked - show blocked+ $('#hi-audio-state-blocked').show();+ } else {+ // User wants audio and permissions are OK - show enabled+ $('#hi-audio-state-enabled').show();+ }++ if (Hi.DEBUG) {+ const changeStatus = hasBaselineStateChanged() ? 'changed' : 'unchanged';+ const userSetting = Hi.settings.isAudioEnabled() ? AudioButtonState.ENABLED : AudioButtonState.DISABLED;+ let buttonState;+ if (!Hi.settings.isAudioEnabled()) {+ buttonState = AudioButtonState.DISABLED;+ } else if (permissionState === AudioPermissionState.BLOCKED) {+ buttonState = AudioButtonState.BLOCKED;+ } else {+ buttonState = AudioButtonState.ENABLED;+ }+ console.log(`Button showing: ${buttonState} (permission: ${permissionState}, user: ${userSetting}, baseline: ${baselineAudioState}, current: ${currentAudioState}, status: ${changeStatus})`);+ }++ } catch (error) {+ if (Hi.DEBUG) { console.error('Error updating audio button state:', error); }+ // Fallback - show based on settings only (assume permissions are OK)+ if (Hi.settings.isAudioEnabled()) {+ $('#hi-audio-state-enabled').show();+ } else {+ $('#hi-audio-state-disabled').show();+ }+ }+ }++ async function _handleAudioButtonClick() {+ try {+ if (Hi.DEBUG) { console.log('π Audio button clicked'); }+ if (Hi.DEBUG) { console.log(`Current states - baseline: ${baselineAudioState}, current: ${currentAudioState}, settings enabled: ${Hi.settings.isAudioEnabled()}`); }++ // Check if we should show guidance dialog+ if (baselineAudioState === AudioPermissionState.BLOCKED && Hi.settings.isAudioEnabled()) {+ if (Hi.DEBUG) { console.log('π Showing guidance dialog (baseline blocked + audio enabled)'); }+ await _showAudioPermissionGuidanceDialog();+ } else {+ if (Hi.DEBUG) { console.log('π No guidance needed - normal button toggle'); }+ // Normal case: just toggle audio setting and update button+ if (Hi.settings.isAudioEnabled()) {+ if (Hi.DEBUG) { console.log('π Disabling audio'); }+ Hi.settings.disableAudio();+ } else {+ if (Hi.DEBUG) { console.log('π Enabling audio'); }+ Hi.settings.enableAudio();+ }+ await _updateAudioButtonState();+ }+ } catch (error) {+ if (Hi.DEBUG) { console.error('β Error handling audio button click:', error); }+ }+ }++ async function _showAudioPermissionGuidanceDialog() {+ try {+ if (Hi.DEBUG) { console.log('π Fetching and showing audio permission guidance dialog...'); }++ // Use antinode's direct API instead of triggering events+ if (typeof window.AN !== 'undefined') {+ if (Hi.DEBUG) { console.log('π‘ Using antinode AN.get() to fetch modal content'); }+ window.AN.get('/audio/permission-guidance');+ } else {+ if (Hi.DEBUG) { console.log('β οΈ Antinode not available, using fallback approach'); }+ // Fallback: manual AJAX call+ $.get('/audio/permission-guidance')+ .done(function(html) {+ if (Hi.DEBUG) { console.log('β Got guidance HTML, creating modal'); }+ // Create modal manually+ let modalId = 'audio-guidance-modal-' + Date.now();+ let modalHtml = `<div id="${modalId}" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">${html}</div>`;+ $('body').append(modalHtml);+ $(`#${modalId}`).modal('show');+ })+ .fail(function(xhr, status, error) {+ if (Hi.DEBUG) { console.error('β Failed to fetch guidance dialog:', error); }+ alert('Audio is blocked by your browser. Please check your browser\'s autoplay settings.');+ });+ }++ if (Hi.DEBUG) { console.log('π Audio guidance dialog request initiated'); }+ } catch (error) {+ if (Hi.DEBUG) { console.error('β Error showing audio guidance dialog:', error); }+ // Fallback: show simple alert+ alert('Audio is blocked by your browser. Please check your browser\'s autoplay settings.');+ }+ }++ /*+ DIAGNOSTIC BACKGROUND AUDIO TESTING++ - Controlled by Hi.DEBUG_AUDIO flag+ - Plays sound every 10 seconds to test autoplay capability+ - Useful for verifying baseline state detection+ */++ let diagnosticAudioTimer = null;+ let diagnosticCounter = 0;++ function _startDiagnosticAudio() {+ if (!Hi.DEBUG_AUDIO) return;++ if (Hi.DEBUG) { console.log('π Starting diagnostic background audio (every 10 seconds)'); }++ diagnosticAudioTimer = setInterval(() => {+ diagnosticCounter++;++ if (Hi.DEBUG) { console.log(`π Diagnostic background audio #${diagnosticCounter}`); }++ try {+ // Use the same method as real weather alerts (no user activation)+ _startAudibleSignal('ConsoleInfo');+ if (Hi.DEBUG) { console.log(`β Diagnostic audio #${diagnosticCounter} triggered`); }+ } catch (error) {+ if (Hi.DEBUG) { console.log(`β Diagnostic audio #${diagnosticCounter} failed:`, error); }+ }+ }, 10000);+ }++ function _stopDiagnosticAudio() {+ if (diagnosticAudioTimer) {+ clearInterval(diagnosticAudioTimer);+ diagnosticAudioTimer = null;+ diagnosticCounter = 0;+ if (Hi.DEBUG) { console.log('π Diagnostic background audio stopped'); }+ }+ }++ // Initialize systems when audio module loads+ window.addEventListener('load', function() {+ _startBaselineMonitoring();+ _startDiagnosticAudio();+ });+})();diff --git a/src/hi/static/js/main.js b/src/hi/static/js/main.jsindex 9c08e573..e1906c57 100644--- a/src/hi/static/js/main.js+++ b/src/hi/static/js/main.js@@ -3,6 +3,7 @@const Hi = {DEBUG: true,+ DEBUG_AUDIO: false, // Enable diagnostic background audio testingisEditMode: ( gHiViewMode == 'edit' ), // Set by server to keep front-end in sync with back-endLOCATION_VIEW_AREA_SELECTOR: '#hi-location-view-main',LOCATION_VIEW_SVG_CLASS: 'hi-location-view-svg',@@ -14,6 +15,7 @@HIGHLIGHTED_CLASS: 'highlighted',ATTRIBUTE_CONTAINER_SELECTOR: '.hi-attribute',FORM_FIELD_CONTAINER_SELECTOR: '.input-group',+ AUDIO_PERMISSION_GUIDANCE_SELECTOR: '#hi-audio-permission-guidance',SVG_ACTION_STATE_ATTR_NAME: 'action-state',DATA_TYPE_ATTR: 'data-type',diff --git a/src/hi/static/js/settings.js b/src/hi/static/js/settings.jsindex 61b22652..ad00ff44 100644--- a/src/hi/static/js/settings.js+++ b/src/hi/static/js/settings.js@@ -13,6 +13,12 @@isAudioEnabled: function() {return _isAudioEnabled( );},+ hasShownPermissionGuidance: function() {+ return _hasShownPermissionGuidance( );+ },+ markPermissionGuidanceShown: function() {+ return _markPermissionGuidanceShown( );+ },enableSleepMode: function() {return _enableSleepMode( );},@@ -33,6 +39,8 @@const AudioStateSettingName = 'audioState';const AudioStateEnabled = 'enabled';const AudioStateDisabled = 'disabled';+ const PermissionGuidanceShownSettingName = 'audioPermissionGuidanceShown';+ const PermissionGuidanceShownValue = 'true';function setConsoleSetting( name, value ) {Hi.setCookie( name, value );@@ -67,5 +75,15 @@function _disableSleepMode() {$(SleepOverlaySelector).hide();}++ function _hasShownPermissionGuidance() {+ var guidanceShown = getConsoleSetting( PermissionGuidanceShownSettingName );+ return guidanceShown === PermissionGuidanceShownValue;+ }++ function _markPermissionGuidanceShown() {+ setConsoleSetting( PermissionGuidanceShownSettingName, PermissionGuidanceShownValue );+ return true;+ }-})();+})();\ No newline at end of filediff --git a/src/hi/static/js/status.js b/src/hi/static/js/status.jsindex 00c1ffd2..3f20c086 100644--- a/src/hi/static/js/status.js+++ b/src/hi/static/js/status.js@@ -37,7 +37,7 @@const AlertStatusDataAttr = 'alertData';const AlertBannerContainerSelector = '#hi-alert-banner-container';const AlertBannerContentSelector = '#hi-alert-banner-content';- const MaxAudioSignalNameAttr = 'maxAudioSignaName';+ const MaxAudioSignalNameAttr = 'maxAudioSignalName';const NewAudioSignalNameAttr = 'newAudioSignalName';const AlarmMessageHtmlAttr = 'alarmMessageHtml';@@ -161,17 +161,27 @@function handleAlertStatusData( alertStatusData ) {if ( ! alertStatusData ) {+ if ( Hi.DEBUG ) { console.log('π No alert status data received'); }return;}+ if ( Hi.DEBUG ) { console.log('π Alert status data:', alertStatusData); }+if (( MaxAudioSignalNameAttr in alertStatusData )&& ( alertStatusData[MaxAudioSignalNameAttr] )) {+ if ( Hi.DEBUG ) { console.log(`π Found max audio signal: ${alertStatusData[MaxAudioSignalNameAttr]}`); }Hi.audio.setMaxSignalName( alertStatusData[MaxAudioSignalNameAttr] );+ if ( Hi.DEBUG ) { console.log(`π setMaxSignalName completed for: ${alertStatusData[MaxAudioSignalNameAttr]}`); }+ } else {+ if ( Hi.DEBUG ) { console.log('π No max audio signal in alert data'); }}if (( NewAudioSignalNameAttr in alertStatusData )&& ( alertStatusData[NewAudioSignalNameAttr] )) {+ if ( Hi.DEBUG ) { console.log(`π΅ Found new audio signal: ${alertStatusData[NewAudioSignalNameAttr]}`); }Hi.audio.startAudibleSignal( alertStatusData[NewAudioSignalNameAttr] );+ } else {+ if ( Hi.DEBUG ) { console.log('π΅ No new audio signal in alert data'); }}if (( AlarmMessageHtmlAttr in alertStatusData )@@ -260,7 +270,7 @@}$(ServerErrorMessageSelector).show();gIsServerErrorShowing = true;- Hi.sound.startAudibleSignal( Hi.sound.WARNING_SIGNAL_NAME );+ Hi.audio.startAudibleSignal( Hi.audio.WARNING_SIGNAL_NAME );}function clearServerErrorIfNeeded() {@@ -269,7 +279,7 @@}$(ServerErrorMessageSelector).hide();gIsServerErrorShowing = false;- Hi.sound.startAudibleSignal( Hi.sound.INFO_SIGNAL_NAME );+ Hi.audio.startAudibleSignal( Hi.audio.INFO_SIGNAL_NAME );}})();diff --git a/src/hi/templates/modals/base.html b/src/hi/templates/modals/base.htmlindex c0864988..ac24a12b 100644--- a/src/hi/templates/modals/base.html+++ b/src/hi/templates/modals/base.html@@ -1,26 +1,28 @@{% load static %}-<div class="modal-dialog hi-modal {% block modal_dialog_class %}{% endblock %}">+<div id="{% block modal_dialog_id %}{% endblock %}"+ class="modal-dialog hi-modal {% block modal_dialog_class %}{% endblock %}"+ style="{% block modal_dialog_style %}{% endblock %}"><div class="modal-content"><div class="modal-title"><div class="row {% block header_class %}bg-secondary{% endblock %} m-0 py-2">- <div class="col-md-2 col-3 align-self-center text-center">- {% block title_image %}- <img class="img-fluid"- src="{% static 'img/hi-icon-196x196.png' %}"- alt="HI Logo" \>- {% endblock %}- </div>- <div class="col-md-9 col-8 align-self-center h4 m-0 px-1">- {% block title_text %}- {% endblock %}- </div>- <div class="col-md-1 col-1 align-self-center m-0 pl-1 text-right">- {% block dismiss_button %}- <button id="modal_dismiss_x"- type="button" class=" w-100 text-center text-white close"- data-dismiss="modal" aria-hidden="true">X</button>- {% endblock %}- </div>+ <div class="col-md-2 col-3 align-self-center text-center">+ {% block title_image %}+ <img class="img-fluid"+ src="{% static 'img/hi-icon-196x196.png' %}"+ alt="HI Logo" \>+ {% endblock %}+ </div>+ <div class="col-md-9 col-8 align-self-center h4 m-0 px-1">+ {% block title_text %}+ {% endblock %}+ </div>+ <div class="col-md-1 col-1 align-self-center m-0 pl-1 text-right">+ {% block dismiss_button %}+ <button id="modal_dismiss_x"+ type="button" class=" w-100 text-center text-white close"+ data-dismiss="modal" aria-hidden="true">X</button>+ {% endblock %}+ </div></div></div>{% block preamble %}diff --git a/src/hi/templates/pages/base.html b/src/hi/templates/pages/base.htmlindex ea4072ec..94cda6a4 100644--- a/src/hi/templates/pages/base.html+++ b/src/hi/templates/pages/base.html@@ -44,6 +44,6 @@{% include initial_modal_template_name %}</div>{% endif %}-+</body></html>diff --git a/src/hi/urls.py b/src/hi/urls.pyindex d5a4a6dc..dbe804eb 100644--- a/src/hi/urls.py+++ b/src/hi/urls.py@@ -44,6 +44,7 @@ urlpatterns = [re_path( r'^notify/', include('hi.apps.notify.urls' )),re_path( r'^console/', include('hi.apps.console.urls' )),re_path( r'^weather/', include('hi.apps.weather.urls' )),+ re_path( r'^audio/', include('hi.apps.audio.urls' )),# Custom error pagesre_path( r'^400.html$', views.bad_request_response, name='bad_request' ),