Skip to content

Home Information - Your home, your data, organized.

Python

Simulator restructure, weather pane status, HA camera motion_detection (#344)

Tony C3864a8dd86b6
diff --git a/src/hi/apps/alert/alarm.py b/src/hi/apps/alert/alarm.py
index b75d3bf8..55f62561 100644
--- a/src/hi/apps/alert/alarm.py
+++ b/src/hi/apps/alert/alarm.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass
from datetime import datetime
-from typing import List
+from typing import List, Optional
from hi.apps.audio.audio_signal import AudioSignal
from hi.apps.security.enums import SecurityLevel
@@ -29,6 +29,15 @@ class Alarm:
alarm_lifetime_secs : int
timestamp : datetime
+ # Optional caller-supplied identifier for the *specific incident*
+ # this alarm represents. When set, Alert.upsert_alarm uses it to
+ # recognize repeated submissions of the same incident (NWS poll
+ # returning the same alert each cycle, motion sensor re-firing on
+ # the same trigger, etc.) and refresh expiry without incrementing
+ # the alarm count. None preserves legacy "every submission
+ # counts" behavior.
+ source_alarm_id : Optional[str] = None
+
def __post_init__(self):
# The lifetime field drives ``Alert.end_datetime``; zero or
# negative values produce an already-expired alert (a
diff --git a/src/hi/apps/alert/alert.py b/src/hi/apps/alert/alert.py
index fa47d0a5..b0952edd 100644
--- a/src/hi/apps/alert/alert.py
+++ b/src/hi/apps/alert/alert.py
@@ -116,9 +116,20 @@ class Alert:
def is_matching_alarm( self, alarm : Alarm ) -> bool:
return bool( self._first_alarm.signature == alarm.signature )
- def add_alarm( self, alarm : Alarm ):
+ def upsert_alarm( self, alarm : Alarm ):
assert alarm.signature == self.first_alarm.signature
+ # Always refresh expiry from the incoming alarm. A follow-up
+ # submission with a shorter lifetime correctly shortens the
+ # Alert's end_datetime (e.g. NWS reducing its ``expires``).
self._end_datetime = datetimeproxy.now() + timedelta( seconds = alarm.alarm_lifetime_secs )
+ # If the caller identified this as a specific incident and we
+ # already have that incident in the deque, do not count it
+ # again — the alarm_count should reflect distinct occurrences,
+ # not how often the source re-reported the same one.
+ if alarm.source_alarm_id is not None:
+ for existing in self._latest_alarms:
+ if existing.source_alarm_id == alarm.source_alarm_id:
+ return
self._latest_alarms.appendleft( alarm )
return
diff --git a/src/hi/apps/alert/alert_manager.py b/src/hi/apps/alert/alert_manager.py
index eb9d7f96..2fa708e4 100644
--- a/src/hi/apps/alert/alert_manager.py
+++ b/src/hi/apps/alert/alert_manager.py
@@ -82,19 +82,19 @@ class AlertManager( Singleton, NotificationMixin, SecurityMixin ):
self._alert_queue.acknowledge_alert( alert_id = alert_id )
return
- async def add_alarm_async( self, alarm : Alarm ):
+ async def upsert_alarm_async( self, alarm : Alarm ):
notification_manager = await self.notification_manager_async()
if not notification_manager:
return
- self._add_alarm_impl(
+ self._upsert_alarm_impl(
alarm = alarm,
notification_manager = notification_manager,
)
return
- def add_alarm( self, alarm : Alarm ):
+ def upsert_alarm( self, alarm : Alarm ):
"""
- Synchronous peer of add_alarm_async. Both AlertQueue.add_alarm
+ Synchronous peer of upsert_alarm_async. Both AlertQueue.add_alarm
and NotificationManager.add_notification_item are sync
thread-safe; the async wrapper exists only for compatibility
with async callers. Use this from sync code (e.g.,
@@ -103,13 +103,13 @@ class AlertManager( Singleton, NotificationMixin, SecurityMixin ):
notification_manager = self.notification_manager()
if not notification_manager:
return
- self._add_alarm_impl(
+ self._upsert_alarm_impl(
alarm = alarm,
notification_manager = notification_manager,
)
return
- def _add_alarm_impl( self, alarm : Alarm, notification_manager ):
+ def _upsert_alarm_impl( self, alarm : Alarm, notification_manager ):
logging.debug( f'Adding Alarm: {alarm}' )
security_state = self.security_manager().security_state
try:
diff --git a/src/hi/apps/alert/alert_queue.py b/src/hi/apps/alert/alert_queue.py
index bd956704..63a3b292 100644
--- a/src/hi/apps/alert/alert_queue.py
+++ b/src/hi/apps/alert/alert_queue.py
@@ -109,7 +109,7 @@ class AlertQueue:
for alert in self._alert_list:
if not alert.is_matching_alarm( alarm = alarm ):
continue
- alert.add_alarm( alarm = alarm )
+ alert.upsert_alarm( alarm = alarm )
self._last_changed_datetime = datetimeproxy.now()
logger.debug( f'Added to existing alert: alarm={alarm}, alert={alert}' )
return alert
diff --git a/src/hi/apps/alert/tests/synthetic_data.py b/src/hi/apps/alert/tests/synthetic_data.py
index e1853962..6065ed66 100644
--- a/src/hi/apps/alert/tests/synthetic_data.py
+++ b/src/hi/apps/alert/tests/synthetic_data.py
@@ -132,7 +132,7 @@ class AlertSyntheticData:
alarm_lifetime_secs = alarm_lifetime_secs,
timestamp = reference_datetime - timedelta(minutes=time_interval_mins * (alarm_count - i)),
)
- alert.add_alarm( additional_alarm )
+ alert.upsert_alarm( additional_alarm )
return alert
@@ -315,7 +315,7 @@ class AlertSyntheticData:
alarm_lifetime_secs = alarm_lifetime_secs,
timestamp = alarm_timestamp,
)
- alert.add_alarm( alarm )
+ alert.upsert_alarm( alarm )
continue
alert_list.append( alert )
continue
diff --git a/src/hi/apps/alert/tests/test_alert.py b/src/hi/apps/alert/tests/test_alert.py
index c518afa9..77a53c89 100644
--- a/src/hi/apps/alert/tests/test_alert.py
+++ b/src/hi/apps/alert/tests/test_alert.py
@@ -77,7 +77,7 @@ class TestAlert(BaseTestCase):
self.assertFalse(alert.is_matching_alarm(non_matching_alarm))
return
- def test_alert_add_alarm_aggregation(self):
+ def test_alert_upsert_alarm_aggregation(self):
"""Test adding alarms to alert - complex aggregation logic with deque management."""
alert = Alert(self.test_alarm)
initial_end_time = alert.end_datetime
@@ -94,7 +94,7 @@ class TestAlert(BaseTestCase):
timestamp=datetimeproxy.now(),
)
- alert.add_alarm(second_alarm)
+ alert.upsert_alarm(second_alarm)
# Should update alarm count and end time
self.assertEqual(alert.alarm_count, 2)
@@ -108,8 +108,85 @@ class TestAlert(BaseTestCase):
self.assertEqual(alert.get_latest_alarm(), second_alarm)
return
- def test_alert_add_alarm_signature_assertion(self):
- """Test add_alarm signature validation - critical error handling."""
+ def test_alert_upsert_alarm_skips_duplicate_source_alarm_id(self):
+ """Resubmitting an alarm with a known source_alarm_id refreshes
+ expiry but does not increment alarm_count — the count reflects
+ distinct incidents, not how often a source re-reported the
+ same one."""
+ first_alarm = Alarm(
+ alarm_source = AlarmSource.EVENT,
+ alarm_type = 'test_alarm',
+ alarm_level = AlarmLevel.WARNING,
+ title = 'Test Alarm',
+ sensor_response_list = [],
+ security_level = SecurityLevel.LOW,
+ alarm_lifetime_secs = 300,
+ timestamp = datetimeproxy.now(),
+ source_alarm_id = 'INCIDENT-A',
+ )
+ alert = Alert( first_alarm )
+
+ # Re-poll of the same incident: different timestamp / lifetime,
+ # same source_alarm_id. Expiry should refresh; count must not.
+ repoll_alarm = Alarm(
+ alarm_source = AlarmSource.EVENT,
+ alarm_type = 'test_alarm',
+ alarm_level = AlarmLevel.WARNING,
+ title = 'Test Alarm (re-polled)',
+ sensor_response_list = [],
+ security_level = SecurityLevel.LOW,
+ alarm_lifetime_secs = 600,
+ timestamp = datetimeproxy.now(),
+ source_alarm_id = 'INCIDENT-A',
+ )
+ before_end = alert.end_datetime
+ alert.upsert_alarm( repoll_alarm )
+
+ self.assertEqual( alert.alarm_count, 1 )
+ self.assertGreater( alert.end_datetime, before_end )
+
+ # A distinct incident (different source_alarm_id) of the same
+ # kind is still counted as a new occurrence.
+ distinct_alarm = Alarm(
+ alarm_source = AlarmSource.EVENT,
+ alarm_type = 'test_alarm',
+ alarm_level = AlarmLevel.WARNING,
+ title = 'Test Alarm (different incident)',
+ sensor_response_list = [],
+ security_level = SecurityLevel.LOW,
+ alarm_lifetime_secs = 300,
+ timestamp = datetimeproxy.now(),
+ source_alarm_id = 'INCIDENT-B',
+ )
+ alert.upsert_alarm( distinct_alarm )
+ self.assertEqual( alert.alarm_count, 2 )
+ return
+
+ def test_alert_upsert_alarm_no_source_id_always_counts(self):
+ """Legacy behavior: when source_alarm_id is None on both the
+ existing and incoming alarm, every submission counts. Existing
+ callers that have not adopted the new field see unchanged
+ behavior."""
+ alert = Alert( self.test_alarm )
+
+ followup_alarm = Alarm(
+ alarm_source = AlarmSource.EVENT,
+ alarm_type = 'test_alarm',
+ alarm_level = AlarmLevel.WARNING,
+ title = 'Test Alarm',
+ sensor_response_list = [],
+ security_level = SecurityLevel.LOW,
+ alarm_lifetime_secs = 300,
+ timestamp = datetimeproxy.now(),
+ )
+ alert.upsert_alarm( followup_alarm )
+ alert.upsert_alarm( followup_alarm )
+
+ self.assertEqual( alert.alarm_count, 3 )
+ return
+
+ def test_alert_upsert_alarm_signature_assertion(self):
+ """Test upsert_alarm signature validation - critical error handling."""
alert = Alert(self.test_alarm)
# Create alarm with different signature
@@ -126,7 +203,7 @@ class TestAlert(BaseTestCase):
# Should raise assertion error for signature mismatch
with self.assertRaises(AssertionError):
- alert.add_alarm(different_alarm)
+ alert.upsert_alarm(different_alarm)
return
def test_alert_title_generation_with_count(self):
@@ -149,7 +226,7 @@ class TestAlert(BaseTestCase):
timestamp=datetimeproxy.now(),
)
- alert.add_alarm(second_alarm)
+ alert.upsert_alarm(second_alarm)
expected_title_with_count = f'{AlarmLevel.WARNING.label}: Test Alarm (2)'
self.assertEqual(alert.title, expected_title_with_count)
return
@@ -170,7 +247,7 @@ class TestAlert(BaseTestCase):
alarm_lifetime_secs=300,
timestamp=datetimeproxy.now(),
)
- alert.add_alarm(new_alarm)
+ alert.upsert_alarm(new_alarm)
# Should not exceed max size
self.assertEqual(alert.alarm_count, Alert.MAX_ALARM_LIST_SIZE)
@@ -246,7 +323,7 @@ class TestAlert(BaseTestCase):
timestamp=datetimeproxy.now(),
)
- alert.add_alarm(second_alarm)
+ alert.upsert_alarm(second_alarm)
self.assertFalse(alert.has_single_alarm)
return
@@ -356,7 +433,7 @@ class TestAlert(BaseTestCase):
)
alert = Alert(first_alarm_with_image)
- alert.add_alarm(second_alarm_no_image)
+ alert.upsert_alarm(second_alarm_no_image)
visual_content = alert.get_first_visual_content()
self.assertIsNotNone(visual_content)
@@ -410,7 +487,7 @@ class TestAlert(BaseTestCase):
)
alert = Alert(first_alarm_no_image)
- alert.add_alarm(second_alarm_with_image)
+ alert.upsert_alarm(second_alarm_with_image)
visual_content = alert.get_first_visual_content()
self.assertIsNotNone(visual_content)
diff --git a/src/hi/apps/alert/tests/test_alert_manager_delegation.py b/src/hi/apps/alert/tests/test_alert_manager_delegation.py
index 496c3c2d..129a27da 100644
--- a/src/hi/apps/alert/tests/test_alert_manager_delegation.py
+++ b/src/hi/apps/alert/tests/test_alert_manager_delegation.py
@@ -111,7 +111,7 @@ class TestAlertManagerDelegation(BaseTestCase):
mock_helper_class.return_value = mock_helper
# Add alarm to create an alert
- self.run_async_test(self.alert_manager.add_alarm_async(motion_alarm))
+ self.run_async_test(self.alert_manager.upsert_alarm_async(motion_alarm))
# Get alert status data (this should trigger delegation to TransientViewManager)
self.alert_manager.get_alert_status_data(
@@ -254,13 +254,13 @@ class TestAlertManagerDelegation(BaseTestCase):
)
# Add old alarm first
- self.run_async_test(self.alert_manager.add_alarm_async(old_alarm))
+ self.run_async_test(self.alert_manager.upsert_alarm_async(old_alarm))
# Verify no suggestion exists yet
self.assertFalse(self.transient_manager.has_suggestion())
# Add new alarm
- self.run_async_test(self.alert_manager.add_alarm_async(new_alarm))
+ self.run_async_test(self.alert_manager.upsert_alarm_async(new_alarm))
# Mock settings to enable auto-view for this test
with patch('hi.apps.console.transient_view_manager.ConsoleSettingsHelper') as mock_helper_class:
diff --git a/src/hi/apps/common/templatetags/icons.py b/src/hi/apps/common/templatetags/icons.py
index 60a2a60e..a9ac3342 100644
--- a/src/hi/apps/common/templatetags/icons.py
+++ b/src/hi/apps/common/templatetags/icons.py
@@ -34,6 +34,7 @@ AVAILABLE_ICONS = {
'close',
'cloud',
'collection',
+ 'copy',
'delete',
'disabled',
'download',
diff --git a/src/hi/apps/config/enums.py b/src/hi/apps/config/enums.py
index f1663cbb..068f3b36 100644
--- a/src/hi/apps/config/enums.py
+++ b/src/hi/apps/config/enums.py
@@ -17,8 +17,8 @@ class ConfigPageType(LabeledEnum):
return
SETTINGS = ('Settings' , '' , 'config_settings' )
- EVENTS = ('Triggers' , '' , 'event_definitions' )
INTEGRATIONS = ('Integrations' , '' , 'integrations_home' )
+ EVENTS = ('Triggers' , '' , 'event_definitions' )
SYSTEM_INFO = ('System Info' , '' , 'system_info' )
@classmethod
diff --git a/src/hi/apps/config/signals.py b/src/hi/apps/config/signals.py
index dda10c5c..7875d97d 100644
--- a/src/hi/apps/config/signals.py
+++ b/src/hi/apps/config/signals.py
@@ -71,12 +71,14 @@ class SettingsInitializer:
return subsystem
def _create_attributes_if_needed( self, subsystem, app_settings ):
- all_defined_setting_definitions_map = app_settings.all_setting_definitions()
- for setting_key, setting_definition in all_defined_setting_definitions_map.items():
+ all_defined_setting_definitions_map = app_settings.all_setting_definitions()
+ for order_id, ( setting_key, setting_definition ) in enumerate(
+ all_defined_setting_definitions_map.items() ):
_ = self._create_setting_attribute_if_needed(
subsystem = subsystem,
setting_key = setting_key,
setting_definition = setting_definition,
+ order_id = order_id,
)
continue
return
@@ -84,7 +86,8 @@ class SettingsInitializer:
def _create_setting_attribute_if_needed( self,
subsystem,
setting_key,
- setting_definition ):
+ setting_definition,
+ order_id ):
from hi.apps.attribute.enums import AttributeType
from hi.apps.config.models import SubsystemAttribute
@@ -104,12 +107,19 @@ class SettingsInitializer:
attribute_type_str = AttributeType.PREDEFINED,
is_editable = setting_definition.is_editable,
is_required = setting_definition.is_required,
+ order_id = order_id,
)
else:
+ update_fields = []
if attribute.name != setting_definition.label:
attribute.name = setting_definition.label
+ update_fields.append( 'name' )
+ if attribute.order_id != order_id:
+ attribute.order_id = order_id
+ update_fields.append( 'order_id' )
+ if update_fields:
attribute.save(
- update_fields = ['name'],
+ update_fields = update_fields,
track_history = False,
)
return attribute
diff --git a/src/hi/apps/console/console_helper.py b/src/hi/apps/console/console_helper.py
index b961d026..09f81f35 100644
--- a/src/hi/apps/console/console_helper.py
+++ b/src/hi/apps/console/console_helper.py
@@ -1,10 +1,13 @@
import logging
+import re
+from typing import Dict, Iterable
from django.http import HttpRequest
from hi.apps.common.singleton import Singleton
from hi.apps.common.geo_utils import parse_long_lat_from_text, GeoPointParseError
from hi.apps.config.settings_mixins import SettingsMixin
+from hi.apps.entity.models import Entity
from hi.transient_models import GeographicLocation
from .enums import DisplayUnits
@@ -66,4 +69,49 @@ class ConsoleSettingsHelper( Singleton, SettingsMixin ):
def get_auto_view_duration( self ) -> int:
return int( self.settings_manager().get_setting_value( ConsoleSetting.AUTO_VIEW_DURATION ) )
-
+
+ @staticmethod
+ def compute_camera_short_names( entity_list : Iterable[ Entity ] ) -> Dict[ int, str ]:
+ """Return a ``{entity.id: short_name}`` mapping for camera-button
+ labels. Heuristic, operating on the full displayed set so the
+ label can honor cross-entity context:
+
+ 1. Strip whole-word "camera" tokens (case-insensitive) and
+ collapse intermediate whitespace.
+ 2. If two or more entities share a leading whole-word token,
+ strip that common token-prefix from each. Only applied when
+ every per-entity result remains non-empty after stripping;
+ otherwise the prefix-strip is skipped for the whole set.
+
+ Single-entity inputs (or no shared leading token) get only the
+ per-entity "camera"-token strip — no global awareness needed.
+ Empty short names are never produced; if both passes would
+ yield empty, the falls-back result is the entity's stripped
+ name (or the original if even that is empty after stripping).
+ """
+ def strip_camera_tokens( name : str ) -> str:
+ cleaned = re.sub( r'\bcamera\b', '', name, flags = re.IGNORECASE )
+ return re.sub( r'\s+', ' ', cleaned ).strip()
+
+ stripped : Dict[ int, str ] = {
+ e.id: strip_camera_tokens( e.name ) or e.name for e in entity_list
+ }
+
+ token_lists = [ s.split() for s in stripped.values() ]
+ common_prefix : list = []
+ if len( token_lists ) >= 2 and all( token_lists ):
+ for tokens in zip( *token_lists ):
+ if len( set( tokens ) ) == 1:
+ common_prefix.append( tokens[ 0 ] )
+ else:
+ break
+
+ if common_prefix:
+ prefix_len = len( common_prefix )
+ candidates = {
+ eid: ' '.join( s.split()[ prefix_len: ] ) for eid, s in stripped.items()
+ }
+ if all( candidates.values() ):
+ return candidates
+
+ return stripped
diff --git a/src/hi/apps/console/console_manager.py b/src/hi/apps/console/console_manager.py
index 11ece11c..f4595ae2 100644
--- a/src/hi/apps/console/console_manager.py
+++ b/src/hi/apps/console/console_manager.py
@@ -13,14 +13,15 @@ from hi.apps.entity.entity_manager import EntityManager
from hi.apps.entity.models import Entity, EntityState
from hi.apps.entity.enums import EntityStateType
from hi.apps.sense.sensor_response_manager import SensorResponseMixin
+from hi.apps.weather.weather_mixins import WeatherMixin
-from .constants import ConsoleConstants
+from .console_helper import ConsoleSettingsHelper
from .transient_models import CameraControlDisplayData
logger = logging.getLogger(__name__)
-class ConsoleManager( Singleton, SettingsMixin, SensorResponseMixin ):
+class ConsoleManager( Singleton, SettingsMixin, SensorResponseMixin, WeatherMixin ):
# TTL cache settings
CAMERA_CONTROL_CACHE_SIZE = 5
@@ -55,11 +56,19 @@ class ConsoleManager( Singleton, SettingsMixin, SensorResponseMixin ):
def get_status_id_replace_map( self, request : HttpRequest ) -> Dict[ str, str ]:
- context = dict()
- template = get_template( ConsoleConstants.DATETIME_HEADER_TEMPLATE_NAME )
- datetime_header_html_str = template.render( context, request = request )
+ weather_alert_list = []
+ try:
+ weather_alert_list = self.weather_manager().get_active_weather_alerts()
+ except Exception as e:
+ logger.error( f'Weather data unavailable for sidebar notice: {e}' )
+
+ context = {
+ 'weather_alert_list': weather_alert_list,
+ }
+ template = get_template( 'console/panes/sidebar_notice.html' )
+ sidebar_notice_html_str = template.render( context, request = request )
return {
- DIVID['DATETIME_HEADER']: datetime_header_html_str,
+ DIVID['SIDEBAR_NOTICE']: sidebar_notice_html_str,
}
def get_camera_control_display_list(self) -> List[CameraControlDisplayData]:
@@ -94,16 +103,19 @@ class ConsoleManager( Singleton, SettingsMixin, SensorResponseMixin ):
.prefetch_related('states')
.order_by('name')
)
-
+
+ short_name_map = ConsoleSettingsHelper.compute_camera_short_names( entity_list )
+
display_data_list = []
for entity in entity_list:
status_entity_state = self._find_priority_entity_state(entity)
display_data = CameraControlDisplayData(
entity=entity,
- status_entity_state=status_entity_state
+ status_entity_state=status_entity_state,
+ short_name=short_name_map.get( entity.id, entity.name ),
)
display_data_list.append(display_data)
-
+
return display_data_list
def _find_priority_entity_state(self, entity: Entity) -> Optional[EntityState]:
diff --git a/src/hi/apps/console/console_side.py b/src/hi/apps/console/console_side.py
index 304dd0dd..466a6c93 100644
--- a/src/hi/apps/console/console_side.py
+++ b/src/hi/apps/console/console_side.py
@@ -13,16 +13,19 @@ class ConsoleSideHelper( ConsoleMixin, SecurityMixin, WeatherMixin ):
def get_side_template_name_and_context( self, request, *args, **kwargs ):
weather_overview_data = None
weather_alert_list = []
+ weather_pane_status = None
try:
weather_manager = self.weather_manager()
weather_overview_data = weather_manager.get_weather_overview_data()
- weather_alert_list = weather_manager.get_weather_alerts()
+ weather_alert_list = weather_manager.get_active_weather_alerts()
+ weather_pane_status = weather_manager.get_weather_pane_status()
except Exception as e:
logger.error( f'Weather data unavailable: {e}' )
context = {
'weather_overview_data': weather_overview_data,
'weather_alert_list': weather_alert_list,
+ 'weather_pane_status': weather_pane_status,
'security_status_data': self.security_manager().get_security_status_data(),
'camera_control_display_list': self.console_manager().get_camera_control_display_list(),
}
diff --git a/src/hi/apps/console/constants.py b/src/hi/apps/console/constants.py
index bb3e2c31..e674798e 100644
--- a/src/hi/apps/console/constants.py
+++ b/src/hi/apps/console/constants.py
@@ -2,4 +2,3 @@ class ConsoleConstants:
CONSOLE_LOCKED_SESSION_VAR = 'console_locked'
CONSOLE_AWAY_LOCK_TIMESTAMP_SESSION_VAR = 'console_away_lock_timestamp'
- DATETIME_HEADER_TEMPLATE_NAME = 'console/panes/datetime_header.html'
diff --git a/src/hi/apps/console/templates/console/panes/camera_controls.html b/src/hi/apps/console/templates/console/panes/camera_controls.html
index 00f04e22..7fa64a1c 100644
--- a/src/hi/apps/console/templates/console/panes/camera_controls.html
+++ b/src/hi/apps/console/templates/console/panes/camera_controls.html
@@ -7,6 +7,7 @@
data-entity-id="{{ camera_data.entity.id }}"
data-async="#main-content"
class="btn btn-primary btn-control btn-camera"
+ title="{{ camera_data.entity.name }}"
{% if camera_data.status_entity_state %}data-state-id="{{ camera_data.status_entity_state.id }}" data-status status=""{% endif %}
role="button">
{{ camera_data.short_name }}
diff --git a/src/hi/apps/console/templates/console/panes/datetime_header.html b/src/hi/apps/console/templates/console/panes/datetime_header.html
index 43005d2b..c5079488 100644
--- a/src/hi/apps/console/templates/console/panes/datetime_header.html
+++ b/src/hi/apps/console/templates/console/panes/datetime_header.html
@@ -1,6 +1,6 @@
{% load tz %}
{% timezone USER_TIMEZONE %}
-<div id="{{ DIVID.DATETIME_HEADER }}" class="datetime-header text-center my-2 border-bottom">
+<div class="datetime-header text-center my-2 border-bottom">
<a class="plain text-black" href="{% url 'config_settings' %}">
<div class="">
{% now "l, F jS" %}
diff --git a/src/hi/apps/console/templates/console/panes/hi_grid_side.html b/src/hi/apps/console/templates/console/panes/hi_grid_side.html
index f98d1db4..5eae6c07 100644
--- a/src/hi/apps/console/templates/console/panes/hi_grid_side.html
+++ b/src/hi/apps/console/templates/console/panes/hi_grid_side.html
@@ -2,12 +2,8 @@
{% if show_view_intro_help %}
{% include "profiles/panes/view_intro_help_sidebar.html" %}
{% else %}
-
- {% if weather_alert_list %}
- {% include "weather/panes/weather_alerts.html" %}
- {% else %}
- {% include "console/panes/datetime_header.html" %}
- {% endif %}
+
+ {% include "console/panes/sidebar_notice.html" %}
{% include "weather/panes/weather_overview.html" %}
<div class="d-flex justify-content-center border-top my-2 pt-2">
diff --git a/src/hi/apps/console/templates/console/panes/sidebar_notice.html b/src/hi/apps/console/templates/console/panes/sidebar_notice.html
new file mode 100644
index 00000000..95aa3f89
--- /dev/null
+++ b/src/hi/apps/console/templates/console/panes/sidebar_notice.html
@@ -0,0 +1,7 @@
+<div id="{{ DIVID.SIDEBAR_NOTICE }}">
+ {% if weather_alert_list %}
+ {% include "weather/panes/weather_alerts.html" %}
+ {% else %}
+ {% include "console/panes/datetime_header.html" %}
+ {% endif %}
+</div>
diff --git a/src/hi/apps/console/transient_models.py b/src/hi/apps/console/transient_models.py
index 65b0c481..918ccf6e 100644
--- a/src/hi/apps/console/transient_models.py
+++ b/src/hi/apps/console/transient_models.py
@@ -1,6 +1,5 @@
from dataclasses import dataclass
from datetime import datetime
-import re
from typing import Dict, List, Optional
from hi.apps.entity.models import Entity, EntityState
@@ -31,15 +30,15 @@ class CameraControlDisplayData:
"""
Data container for camera control display information.
Encapsulates entity and its primary status entity state for template rendering.
+
+ ``short_name`` is computed by the manager when the full camera list
+ is assembled — see ``ConsoleSettingsHelper.compute_camera_short_names`` —
+ so the label can honor cross-entity context (e.g., stripping a
+ leading token that is common across all displayed cameras).
"""
entity: Entity
status_entity_state: Optional[EntityState] = None
-
- @property
- def short_name(self):
- """ Heuristic rules to reduce name length to fit in side panel narrow buttons """
- short_name = re.sub( r'camera$', '', self.entity.name, flags = re.IGNORECASE )
- return short_name.strip()
+ short_name: str = ''
@dataclass
diff --git a/src/hi/apps/entity/entity_placement.py b/src/hi/apps/entity/entity_placement.py
index ba3d7cef..1ab16802 100644
--- a/src/hi/apps/entity/entity_placement.py
+++ b/src/hi/apps/entity/entity_placement.py
@@ -36,10 +36,11 @@ from typing import List, Optional, Tuple, Union
from django.db import transaction
from hi.apps.entity.edit.forms import EntityPositionForm
-from hi.apps.entity.enums import EntityTransitionType
+from hi.apps.entity.enums import EntityType, EntityTransitionType
from hi.apps.location.models import Location, LocationView
from hi.apps.location.path_geometry import PathGeometry
from hi.apps.location.position_geometry import PositionGeometry
+from hi.hi_styles import EntityIconDirection, EntityStyle
from .entity_pairing_manager import EntityPairingManager
from .models import (
@@ -469,8 +470,10 @@ class EntityPlacer:
placement_shape = placement_shape,
)
for delegate_entity in delegate_entity_list:
- delegate_shape = self._calculator.shape_for_entity(
- entity = delegate_entity,
+ delegate_shape = self._build_delegate_shape(
+ principal_entity = entity,
+ principal_shape = placement_shape,
+ delegate_entity = delegate_entity,
location_view = location_view,
)
self._create_entity_view(
@@ -481,6 +484,62 @@ class EntityPlacer:
continue
return
+ # Apex offset along the principal's icon-facing direction, expressed
+ # as a fraction of the icon's half-extent in that direction. 0.0 =
+ # apex at icon center; 1.0 = apex at icon edge. Falls between for a
+ # less-than-edge but past-center anchor.
+ _COVERAGE_APEX_OFFSET_FRACTION = 0.75
+
+ def _build_delegate_shape(
+ self,
+ principal_entity : Entity,
+ principal_shape : PlacementShape,
+ delegate_entity : Entity,
+ location_view : LocationView,
+ ) -> PlacementShape:
+ """Compute the delegate's placement shape. Default is the
+ calculator's centered default. When the principal is an icon
+ entity whose source-icon facing direction is known and the
+ delegate is an AREA, build a triangular coverage path with its
+ apex anchored near the principal's position so the delegate
+ visually reads as the principal's coverage cone."""
+ default_shape = self._calculator.shape_for_entity(
+ entity = delegate_entity,
+ location_view = location_view,
+ )
+ if delegate_entity.entity_type != EntityType.AREA:
+ return default_shape
+ if not isinstance( principal_shape, PlacementPoint ):
+ return default_shape
+
+ icon_direction = EntityStyle.get_icon_direction( principal_entity.entity_type )
+ if icon_direction is EntityIconDirection.UNKNOWN:
+ return default_shape
+
+ dx, dy = icon_direction.value
+ icon_viewbox = EntityStyle.get_svg_icon_viewbox( principal_entity.entity_type )
+
+ # Icon's dimension along the facing direction. ``dx`` and ``dy``
+ # are 0/±1 for cardinal directions so this picks the relevant
+ # axis cleanly.
+ facing_extent = ( abs( dx ) * icon_viewbox.width
+ + abs( dy ) * icon_viewbox.height )
+ principal_scale = float( principal_shape.svg_scale )
+ apex_offset = ( facing_extent / 2.0
+ * self._COVERAGE_APEX_OFFSET_FRACTION
+ * principal_scale )
+
+ apex_x = float( principal_shape.svg_x ) + ( dx * apex_offset )
+ apex_y = float( principal_shape.svg_y ) + ( dy * apex_offset )
+
+ svg_path = PathGeometry.create_coverage_triangle_path_string(
+ location_view = location_view,
+ apex_x = apex_x,
+ apex_y = apex_y,
+ direction = icon_direction.value,
+ )
+ return PlacementPath( svg_path = svg_path )
+
def place_entities_in_view( self,
entities : List[Entity],
location_view : LocationView ):
diff --git a/src/hi/apps/entity/templates/entity/modals/entity_edit.html b/src/hi/apps/entity/templates/entity/modals/entity_edit.html
index 0dbfcc53..cd28c87f 100644
--- a/src/hi/apps/entity/templates/entity/modals/entity_edit.html
+++ b/src/hi/apps/entity/templates/entity/modals/entity_edit.html
@@ -1,28 +1,14 @@
-{% extends "modals/base.html" %}
-{% load icons static %}
-{% load integration_tags %}
+{% extends "modals/action_3.html" %}
+{% load icons %}
{% block modal_dialog_class %}hi-modal-dialog-700{% endblock %}
{% block title_text %}{{ entity.name }}{% endblock %}
+{% block subheader %}
+ {% include "entity/panes/entity_modal_subheader.html" with entity=entity modal_name="Edit" %}
+{% endblock %}
+
{% block body %}
-{% if entity.integration_id %}
-<div class="text-muted text-center">
- <small>
- {% integration_logo_path entity as logo_path %}
- {% if logo_path %}<img src="{% static logo_path %}" alt="" class="hi-integration-logo--inline mr-1">{% endif %}
- From: {% integration_display_name entity %}
- </small>
-</div>
-{% elif entity.previous_integration_id %}
-<div class="text-muted text-center font-italic">
- <small>
- {% previous_integration_logo_path entity as prev_logo_path %}
- {% if prev_logo_path %}<img src="{% static prev_logo_path %}" alt="" class="hi-integration-logo--detached mr-1">{% endif %}
- Detached from: {% previous_integration_display_name entity %}
- </small>
-</div>
-{% endif %}
<!-- Root container for this attribute editing context -->
<div id="{{ attr_page_context.container_html_id }}"
class="{{ DIVID.ATTR_V2_CONTAINER_CLASS }}">
@@ -65,6 +51,23 @@
</div>
{% endblock %}
-{% block footer %}
-<!-- No footer - sticky panel contains all actions -->
+{% block action_left %}
+<a class="btn btn-primary"
+ href="{% url 'entity_status' entity_id=entity.id %}"
+ data-async="modal">
+ {% icon "info-circle" size="sm" css_class="hi-icon-left" %}STATUS
+</a>
+{% endblock %}
+
+{% block action_center %}
+<a class="btn btn-primary"
+ href="{% url 'entity_history' entity_id=entity.id %}"
+ data-async="modal">
+ {% icon "history" size="sm" css_class="hi-icon-left" %}HISTORY
+</a>
+{% endblock %}
+
+{% block action_right %}
+<a id="hi-modal-done" role="button" {% if autofocus %}autofocus="autofocus"{% endif %}
+ class="btn btn-primary" href="#" data-dismiss="modal">DONE</a>
{% endblock %}
diff --git a/src/hi/apps/entity/templates/entity/modals/entity_history.html b/src/hi/apps/entity/templates/entity/modals/entity_history.html
index 8a58f12a..d14d85e9 100644
--- a/src/hi/apps/entity/templates/entity/modals/entity_history.html
+++ b/src/hi/apps/entity/templates/entity/modals/entity_history.html
@@ -6,6 +6,10 @@
{{ entity.name }}
{% endblock %}
+{% block subheader %}
+ {% include "entity/panes/entity_modal_subheader.html" with entity=entity modal_name="History" %}
+{% endblock %}
+
{% block body %}
{% if state_to_rows %}
{% for state, rows in state_to_rows.items %}
diff --git a/src/hi/apps/entity/templates/entity/modals/entity_status.html b/src/hi/apps/entity/templates/entity/modals/entity_status.html
index 5c2180f0..543b2bfb 100644
--- a/src/hi/apps/entity/templates/entity/modals/entity_status.html
+++ b/src/hi/apps/entity/templates/entity/modals/entity_status.html
@@ -1,7 +1,6 @@
{% extends "modals/action_3.html" %}
{% load icons %}
{% load common_tags %}
-{% load static %}
{% load state_panel_tags %}
{% load integration_tags %}
@@ -11,35 +10,8 @@
{{ state_panel_data.entity.name }}
{% endblock %}
-{# Framework-level subheader: entity type icon + label on the left, #}
-{# integration logo centered (when present), "Status" label on the #}
-{# right. Panels render their body below without repeating any of #}
-{# this identifying chrome. #}
{% block subheader %}
-{% with entity=state_panel_data.entity icon_item=state_panel_data.display_only_svg_icon_item %}
-<div class="hi-entity-status-subheader d-flex align-items-center px-3 py-1 border-bottom">
- <div class="hi-entity-status-subheader__left d-flex align-items-center">
- {% if icon_item %}
- <span class="hi-entity-status-subheader__type-icon mr-2">
- {% include "entity/panes/entity_display_only_svg_icon.html" with svg_icon_item=icon_item %}
- </span>
- {% endif %}
- <small class="text-muted text-uppercase">{{ entity.entity_type.label }}</small>
- </div>
- <div class="hi-entity-status-subheader__center flex-grow-1 text-center">
- {% if entity.integration_id %}
- {% integration_logo_path entity as logo_path %}
- {% if logo_path %}<img src="{% static logo_path %}" alt="" class="hi-integration-logo--inline">{% endif %}
- {% elif entity.previous_integration_id %}
- {% previous_integration_logo_path entity as prev_logo_path %}
- {% if prev_logo_path %}<img src="{% static prev_logo_path %}" alt="" class="hi-integration-logo--detached">{% endif %}
- {% endif %}
- </div>
- <div class="hi-entity-status-subheader__right">
- <small class="text-muted text-uppercase">Status</small>
- </div>
-</div>
-{% endwith %}
+ {% include "entity/panes/entity_modal_subheader.html" with entity=state_panel_data.entity modal_name="Status" %}
{% endblock %}
{% block body %}
diff --git a/src/hi/apps/entity/templates/entity/panes/entity_modal_subheader.html b/src/hi/apps/entity/templates/entity/panes/entity_modal_subheader.html
new file mode 100644
index 00000000..06e9ebe8
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/panes/entity_modal_subheader.html
@@ -0,0 +1,33 @@
+{% load static %}
+{% load entity_tags %}
+{% load integration_tags %}
+{# Shared subheader for the per-entity modals (status / edit / history).#}
+{# Renders: entity type icon + type label on the left, integration logo #}
+{# centered (when present), the modal-view name on the right. Callers #}
+{# pass ``entity`` and ``modal_name`` (e.g. "Status", "Edit", #}
+{# "History"). #}
+{% entity_display_svg_icon_item entity as icon_item %}
+<div class="hi-entity-status-subheader d-flex align-items-center px-3 py-1 mb-3">
+ <div class="hi-entity-status-subheader__left d-flex align-items-center">
+ {% if icon_item %}
+ <span class="hi-entity-status-subheader__type-icon mr-2">
+ {% include "entity/panes/entity_display_only_svg_icon.html" with svg_icon_item=icon_item %}
+ </span>
+ {% endif %}
+ <small class="text-muted text-uppercase">{{ entity.entity_type.label }}</small>
+ </div>
+ <div class="hi-entity-status-subheader__center flex-grow-1 text-center">
+ {% if entity.integration_id %}
+ {% integration_logo_path entity as logo_path %}
+ {% if logo_path %}<img src="{% static logo_path %}" alt="" class="hi-integration-logo--inline mr-1">{% endif %}
+ <small>{% integration_display_name entity %}</small>
+ {% elif entity.previous_integration_id %}
+ {% previous_integration_logo_path entity as prev_logo_path %}
+ {% if prev_logo_path %}<img src="{% static prev_logo_path %}" alt="" class="hi-integration-logo--detached mr-1">{% endif %}
+ <small class="font-italic">Detached from {% previous_integration_display_name entity %}</small>
+ {% endif %}
+ </div>
+ <div class="hi-entity-status-subheader__right">
+ <small class="text-muted text-uppercase">{{ modal_name }}</small>
+ </div>
+</div>
diff --git a/src/hi/apps/entity/templatetags/entity_tags.py b/src/hi/apps/entity/templatetags/entity_tags.py
index aa862cd5..ca8b9618 100644
--- a/src/hi/apps/entity/templatetags/entity_tags.py
+++ b/src/hi/apps/entity/templatetags/entity_tags.py
@@ -12,3 +12,15 @@ def value_label( value ):
their authoritative label, free-form names get humanized,
numeric values pass through."""
return EntityStateValue.to_display_label( value )
+
+
+def entity_display_svg_icon_item( entity ):
+ """Build the display-only SvgIconItem for ``entity`` from the
+ factory. Useful for templates that need the icon (e.g. the shared
+ entity-modal subheader) but whose views don't otherwise carry the
+ icon item in their context."""
+ from hi.apps.location.svg_item_factory import SvgItemFactory
+ if not entity:
+ return None
+ return SvgItemFactory().get_display_only_svg_icon_item( entity = entity )
diff --git a/src/hi/apps/entity/tests/test_entity_placement.py b/src/hi/apps/entity/tests/test_entity_placement.py
index 508e8ffc..0790aae4 100644
--- a/src/hi/apps/entity/tests/test_entity_placement.py
+++ b/src/hi/apps/entity/tests/test_entity_placement.py
@@ -73,14 +73,20 @@ class TestEntityPlacerPersistence(BaseTestCase):
# Centered on the viewbox: 100 + 400/2 = 300, 200 + 300/2 = 350.
self.assertEqual(entity_position.svg_x, Decimal('300'))
self.assertEqual(entity_position.svg_y, Decimal('350'))
- # Default icon size is a percentage of the viewbox's smaller dimension.
+ # Default icon size is a percentage of the viewbox's smaller
+ # dimension. Tolerance-based comparison to avoid coupling to
+ # the field's storage rounding mode (the field rounds to 6
+ # decimal places; the exact rounding mode is an implementation
+ # detail).
expected_scale = (
Decimal('300')
* Decimal(str(PositionGeometry.DEFAULT_ICON_SIZE_PERCENT_OF_VIEWBOX))
/ Decimal('100')
/ Decimal('64')
)
- self.assertEqual(entity_position.svg_scale, expected_scale)
+ self.assertAlmostEqual(
+ float(entity_position.svg_scale), float(expected_scale), places=5,
+ )
self.assertEqual(entity_position.svg_rotate, Decimal('0.0'))
# Re-call must not create a duplicate row.
@@ -156,9 +162,10 @@ class TestEntityPlacementCalculatorBulkShapes(BaseTestCase):
self.assertEqual(len(shapes), len(entities))
for shape in shapes:
self.assertIsInstance(shape, PlacementPoint)
- # Distinct x positions in a single row.
- xs = [s.svg_x for s in shapes]
- self.assertEqual(len(set(xs)), 4)
+ # All placement positions are distinct — adaptive grid shape
+ # (rows × cols) is an implementation detail and not asserted.
+ positions = [(s.svg_x, s.svg_y) for s in shapes]
+ self.assertEqual(len(set(positions)), 4)
class TestEntityPlacerSetEntityPath(BaseTestCase):
diff --git a/src/hi/apps/event/edit/forms.py b/src/hi/apps/event/edit/forms.py
index 755fbb2c..71abf8d4 100644
--- a/src/hi/apps/event/edit/forms.py
+++ b/src/hi/apps/event/edit/forms.py
@@ -25,7 +25,7 @@ class EventDefinitionForm( forms.ModelForm ):
'dedupe_window_secs',
'enabled',
)
-
+
event_type_str = forms.ChoiceField(
label = 'Trigger Type',
choices = EventType.choices,
@@ -34,6 +34,12 @@ class EventDefinitionForm( forms.ModelForm ):
widget = forms.Select( attrs = { 'class' : 'custom-select' } ),
)
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ for field_name in ( 'name', 'event_window_secs', 'dedupe_window_secs' ):
+ self.fields[field_name].widget.attrs.setdefault( 'class', 'form-control' )
+ return
+
class EventClauseForm( forms.ModelForm, EntityStateSelectModelFormMixin ):
@@ -73,6 +79,8 @@ class EventClauseForm( forms.ModelForm, EntityStateSelectModelFormMixin ):
f'Hi.setEventClauseValueOperatorWidget('
f'"{operator_field_id}", "{value_field_id}");'
)
+ if 'class' not in self.fields['value'].widget.attrs:
+ self.fields['value'].widget.attrs['class'] = 'form-control'
return
def clean(self):
@@ -119,7 +127,14 @@ class AlarmActionForm( forms.ModelForm ):
widget = forms.Select( attrs = { 'class' : 'custom-select' } ),
)
-
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.fields['alarm_lifetime_secs'].widget.attrs.setdefault(
+ 'class', 'form-control',
+ )
+ return
+
+
class ControlActionForm( forms.ModelForm, EntityStateSelectModelFormMixin ):
class Meta:
@@ -142,6 +157,8 @@ class ControlActionForm( forms.ModelForm, EntityStateSelectModelFormMixin ):
entity_state = entity_state,
)
self.fields['controller'].widget.attrs.update({ 'class': 'custom-select' })
+ if 'class' not in self.fields['value'].widget.attrs:
+ self.fields['value'].widget.attrs['class'] = 'form-control'
return
diff --git a/src/hi/apps/event/event_manager.py b/src/hi/apps/event/event_manager.py
index e94a0365..6ab8457b 100644
--- a/src/hi/apps/event/event_manager.py
+++ b/src/hi/apps/event/event_manager.py
@@ -209,7 +209,7 @@ class EventManager( Singleton, AlertMixin, ControllerMixin, SecurityMixin ):
if alarm_action.security_level != current_security_level:
continue
alarm = event.to_alarm( alarm_action = alarm_action )
- await alert_manager.add_alarm_async( alarm )
+ await alert_manager.upsert_alarm_async( alarm )
continue
control_actions = await sync_to_async(list)(event.event_definition.control_actions.all())
diff --git a/src/hi/apps/event/templates/event/edit/panes/alarm_action_form.html b/src/hi/apps/event/templates/event/edit/panes/alarm_action_form.html
index 39fc197d..ec434e4b 100644
--- a/src/hi/apps/event/templates/event/edit/panes/alarm_action_form.html
+++ b/src/hi/apps/event/templates/event/edit/panes/alarm_action_form.html
@@ -2,27 +2,29 @@
{% load icons %}
{% generate_uuid as unique_id %}
{% if not alarm_action_form.instance.pk %}
-<div class="my-3">
- <a class="" data-toggle="collapse" href="#hi-alarm-action-new-{{ unique_id }}"
+<div class="event-edit-add">
+ <a class="btn btn-sm btn-outline-primary" data-toggle="collapse"
+ href="#hi-alarm-action-new-{{ unique_id }}"
role="button" aria-expanded="false" aria-controls="hi-alarm-action-new-{{ unique_id }}">
- {% icon "plus" size="sm" css_class="hi-icon-left" %} Add Alarm Action
+ {% icon "plus" size="sm" css_class="hi-icon-left" %}Add Alarm Action
</a>
</div>
-<div class="collapse my-2" id="hi-alarm-action-new-{{ unique_id }}">
+<div class="collapse event-edit-action-card event-edit-action-card-new"
+ id="hi-alarm-action-new-{{ unique_id }}">
{% else %}
-<div class="my-3">
+<div class="event-edit-action-card">
{% endif %}
- <div class="d-flex justify-content-between" >
- <div class="h6"><em>Alarm Action {{ forloop.counter }}</em></div>
+ <div class="event-edit-action-card-head">
+ <span class="event-edit-action-card-label">Alarm Action {{ forloop.counter }}</span>
{% if alarm_action_form.instance.pk %}
- <div class="">
- {{ alarm_action_form.DELETE }}<span class="pl-2">Delete</span>
- </div>
+ <label class="event-edit-remove">
+ {{ alarm_action_form.DELETE }}<span>Remove</span>
+ </label>
{% endif %}
</div>
- <div class="pl-2">
+ <div class="event-edit-action-card-body">
{% for hidden in alarm_action_form.hidden_fields %}
{{ hidden }}
{% endfor %}
@@ -35,37 +37,37 @@
</div>
{% endif %}
- <div class="input-group mb-2 mr-sm-2 w-100">
- <div class="input-group-prepend" >
- <label for="{{ alarm_action_form.security.id_for_label }}"
- class="input-group-text" >{{ alarm_action_form.security_level_str.label }}</label>
+ <div class="event-edit-field">
+ <div class="input-group">
+ <div class="input-group-prepend">
+ <label for="{{ alarm_action_form.security_level_str.id_for_label }}"
+ class="input-group-text">{{ alarm_action_form.security_level_str.label }}</label>
+ </div>
{{ alarm_action_form.security_level_str }}
- <small class="form-error text-danger" >{{ alarm_action_form.security_level_str.errors }}</small>
</div>
+ <small class="form-error text-danger">{{ alarm_action_form.security_level_str.errors }}</small>
</div>
- <div class="input-group mb-2 mr-sm-2 w-100">
- <div class="input-group-prepend" >
- <label for="{{ alarm_action_form.alarm.id_for_label }}"
- class="input-group-text" >{{ alarm_action_form.alarm_level_str.label }}</label>
+ <div class="event-edit-field">
+ <div class="input-group">
+ <div class="input-group-prepend">
+ <label for="{{ alarm_action_form.alarm_level_str.id_for_label }}"
+ class="input-group-text">{{ alarm_action_form.alarm_level_str.label }}</label>
+ </div>
{{ alarm_action_form.alarm_level_str }}
- <small class="form-error text-danger" >{{ alarm_action_form.alarm_level_str.errors }}</small>
</div>
+ <small class="form-error text-danger">{{ alarm_action_form.alarm_level_str.errors }}</small>
</div>
- <div class="input-group mb-2 mr-sm-2">
- <div class="input-group-prepend" >
- <label for="{{ alarm_action_form.alarm.id_for_label }}"
- class="input-group-text" >{{ alarm_action_form.alarm_lifetime_secs.label }}</label>
+ <div class="event-edit-field">
+ <div class="input-group">
+ <div class="input-group-prepend">
+ <label for="{{ alarm_action_form.alarm_lifetime_secs.id_for_label }}"
+ class="input-group-text">{{ alarm_action_form.alarm_lifetime_secs.label }}</label>
+ </div>
{{ alarm_action_form.alarm_lifetime_secs }}
- <small class="form-error text-danger" >{{ alarm_action_form.alarm_lifetime_secs.errors }}</small>
</div>
+ <small class="form-error text-danger">{{ alarm_action_form.alarm_lifetime_secs.errors }}</small>
</div>
-
- {% if alarm_action_form.instance.pk %}
- <div>
- {{ alarm_action_form.DELETE }} Delete
- </div>
- {% endif %}
</div>
</div>
diff --git a/src/hi/apps/event/templates/event/edit/panes/control_action_form.html b/src/hi/apps/event/templates/event/edit/panes/control_action_form.html
index bc82cf64..ef5ff1e5 100644
--- a/src/hi/apps/event/templates/event/edit/panes/control_action_form.html
+++ b/src/hi/apps/event/templates/event/edit/panes/control_action_form.html
@@ -2,27 +2,29 @@
{% load icons %}
{% generate_uuid as unique_id %}
{% if not control_action_form.instance.pk %}
-<div class="my-3">
- <a class="" data-toggle="collapse" href="#hi-control-action-new-{{ unique_id }}"
+<div class="event-edit-add">
+ <a class="btn btn-sm btn-outline-primary" data-toggle="collapse"
+ href="#hi-control-action-new-{{ unique_id }}"
role="button" aria-expanded="false" aria-controls="hi-control-action-new-{{ unique_id }}">
- {% icon "plus" size="sm" css_class="hi-icon-left" %} Add Control Action
+ {% icon "plus" size="sm" css_class="hi-icon-left" %}Add Control Action
</a>
</div>
-<div class="collapse my-2" id="hi-control-action-new-{{ unique_id }}">
+<div class="collapse event-edit-action-card event-edit-action-card-new"
+ id="hi-control-action-new-{{ unique_id }}">
{% else %}
-<div class="my-3">
+<div class="event-edit-action-card">
{% endif %}
- <div class="d-flex justify-content-between" >
- <div class="h6"><em>Control Action {{ forloop.counter }}</em></div>
+ <div class="event-edit-action-card-head">
+ <span class="event-edit-action-card-label">Control Action {{ forloop.counter }}</span>
{% if control_action_form.instance.pk %}
- <div class="">
- {{ control_action_form.DELETE }}<span class="pl-2">Delete</span>
- </div>
+ <label class="event-edit-remove">
+ {{ control_action_form.DELETE }}<span>Remove</span>
+ </label>
{% endif %}
</div>
- <div class="pl-2">
+ <div class="event-edit-action-card-body">
{% for hidden in control_action_form.hidden_fields %}
{{ hidden }}
{% endfor %}
@@ -35,28 +37,26 @@
</div>
{% endif %}
- <div class="input-group mb-2 mr-sm-2 w-100">
- <div class="input-group-prepend" >
- <label for="{{ control_action_form.controller.id_for_label }}"
- class="input-group-text" >{{ control_action_form.controller.label }}</label>
+ <div class="event-edit-field">
+ <div class="input-group">
+ <div class="input-group-prepend">
+ <label for="{{ control_action_form.controller.id_for_label }}"
+ class="input-group-text">{{ control_action_form.controller.label }}</label>
+ </div>
{{ control_action_form.controller }}
- <small class="form-error text-danger" >{{ control_action_form.controller.errors }}</small>
</div>
+ <small class="form-error text-danger">{{ control_action_form.controller.errors }}</small>
</div>
- <div class="input-group mb-2 mr-sm-2 w-100">
- <div class="input-group-prepend" >
- <label for="{{ control_action_form.value.id_for_label }}"
- class="input-group-text" >{{ control_action_form.value.label }}</label>
+ <div class="event-edit-field">
+ <div class="input-group">
+ <div class="input-group-prepend">
+ <label for="{{ control_action_form.value.id_for_label }}"
+ class="input-group-text">{{ control_action_form.value.label }}</label>
+ </div>
{{ control_action_form.value }}
- <small class="form-error text-danger" >{{ control_action_form.value.errors }}</small>
</div>
+ <small class="form-error text-danger">{{ control_action_form.value.errors }}</small>
</div>
-
- {% if control_action_form.instance.pk %}
- <div>
- {{ control_action_form.DELETE }} Delete
- </div>
- {% endif %}
</div>
</div>
diff --git a/src/hi/apps/event/templates/event/edit/panes/event_clause_form.html b/src/hi/apps/event/templates/event/edit/panes/event_clause_form.html
index dfea3024..f19e3113 100644
--- a/src/hi/apps/event/templates/event/edit/panes/event_clause_form.html
+++ b/src/hi/apps/event/templates/event/edit/panes/event_clause_form.html
@@ -2,31 +2,33 @@
{% load icons %}
{% generate_uuid as unique_id %}
{% if not event_clause_form.instance.pk %}
-<div class="my-3">
- <a class="" data-toggle="collapse" href="#hi-event-clause-new-{{ unique_id }}"
+<div class="event-edit-add">
+ <a class="btn btn-sm btn-outline-primary" data-toggle="collapse"
+ href="#hi-event-clause-new-{{ unique_id }}"
role="button" aria-expanded="false" aria-controls="hi-event-clause-new-{{ unique_id }}">
- {% icon "plus" size="sm" css_class="hi-icon-left" %} Add New Clause
+ {% icon "plus" size="sm" css_class="hi-icon-left" %}Add New Clause
</a>
</div>
-<div class="collapse my-2" id="hi-event-clause-new-{{ unique_id }}">
+<div class="collapse event-edit-action-card event-edit-action-card-new"
+ id="hi-event-clause-new-{{ unique_id }}">
{% else %}
-<div class="my-3">
+<div class="event-edit-action-card">
{% endif %}
- <div class="d-flex justify-content-between" >
- <div class="h6"><em>Clause {{ forloop.counter }}</em></div>
+ <div class="event-edit-action-card-head">
+ <span class="event-edit-action-card-label">Clause {{ forloop.counter }}</span>
{% if event_clause_form.instance.pk %}
- <div class="">
- {{ event_clause_form.DELETE }}<span class="pl-2">Delete</span>
- </div>
+ <label class="event-edit-remove">
+ {{ event_clause_form.DELETE }}<span>Remove</span>
+ </label>
{% endif %}
</div>
- <div class="pl-2">
+ <div class="event-edit-action-card-body">
{% for hidden in event_clause_form.hidden_fields %}
{{ hidden }}
{% endfor %}
-
+
{% if event_clause_form.non_field_errors %}
<div class="non-field-errors">
{% for err in event_clause_form.non_field_errors %}
@@ -35,31 +37,37 @@
</div>
{% endif %}
- <div class="input-group mb-2 mr-sm-2 w-100">
- <div class="input-group-prepend" >
- <label for="{{ event_clause_form.entity_state.id_for_label }}"
- class="input-group-text" >{{ event_clause_form.entity_state.label }}</label>
+ <div class="event-edit-field">
+ <div class="input-group">
+ <div class="input-group-prepend">
+ <label for="{{ event_clause_form.entity_state.id_for_label }}"
+ class="input-group-text">{{ event_clause_form.entity_state.label }}</label>
+ </div>
{{ event_clause_form.entity_state }}
- <small class="form-error text-danger" >{{ event_clause_form.entity_state.errors }}</small>
</div>
+ <small class="form-error text-danger">{{ event_clause_form.entity_state.errors }}</small>
</div>
- <div class="input-group mb-2 mr-sm-2 w-100">
- <div class="input-group-prepend" >
- <label for="{{ event_clause_form.value_operator_str.id_for_label }}"
- class="input-group-text" >{{ event_clause_form.value_operator_str.label }}</label>
+ <div class="event-edit-field">
+ <div class="input-group">
+ <div class="input-group-prepend">
+ <label for="{{ event_clause_form.value_operator_str.id_for_label }}"
+ class="input-group-text">{{ event_clause_form.value_operator_str.label }}</label>
+ </div>
{{ event_clause_form.value_operator_str }}
- <small class="form-error text-danger" >{{ event_clause_form.value_operator_str.errors }}</small>
</div>
+ <small class="form-error text-danger">{{ event_clause_form.value_operator_str.errors }}</small>
</div>
- <div class="input-group mb-2 mr-sm-2 w-100">
- <div class="input-group-prepend" >
- <label for="{{ event_clause_form.value.id_for_label }}"
- class="input-group-text" >{{ event_clause_form.value.label }}</label>
+ <div class="event-edit-field">
+ <div class="input-group">
+ <div class="input-group-prepend">
+ <label for="{{ event_clause_form.value.id_for_label }}"
+ class="input-group-text">{{ event_clause_form.value.label }}</label>
+ </div>
{{ event_clause_form.value }}
- <small class="form-error text-danger" >{{ event_clause_form.value.errors }}</small>
</div>
+ <small class="form-error text-danger">{{ event_clause_form.value.errors }}</small>
</div>
- </div>
+ </div>
</div>
diff --git a/src/hi/apps/event/templates/event/edit/panes/event_definition_form.html b/src/hi/apps/event/templates/event/edit/panes/event_definition_form.html
index b9447193..a91f49b2 100644
--- a/src/hi/apps/event/templates/event/edit/panes/event_definition_form.html
+++ b/src/hi/apps/event/templates/event/edit/panes/event_definition_form.html
@@ -1,3 +1,4 @@
+{% load icons %}
{% for hidden in event_definition_form.hidden_fields %}
{{ hidden }}
{% endfor %}
@@ -10,69 +11,75 @@
</div>
{% endif %}
-<div class="input-group mb-2 mr-sm-2">
- <div class="input-group-prepend" >
- <label for="{{ event_definition_form.name.id_for_label }}"
- class="input-group-text" >{{ event_definition_form.name.label }}</label>
- {{ event_definition_form.name }}
- <small class="form-error text-danger" >{{ event_definition_form.name.errors }}</small>
+<div class="event-edit-field">
+ <div class="input-group">
+ <div class="input-group-prepend">
+ <label for="{{ event_definition_form.name.id_for_label }}"
+ class="input-group-text">{{ event_definition_form.name.label }}</label>
+ </div>
+ {{ event_definition_form.name }}
</div>
+ <small class="form-error text-danger">{{ event_definition_form.name.errors }}</small>
</div>
-<div class="input-group mb-2 mr-sm-2">
- <div class="input-group-prepend" >
- <label for="{{ event_definition_form.event.id_for_label }}"
- class="input-group-text" >{{ event_definition_form.event_type_str.label }}</label>
- {{ event_definition_form.event_type_str }}
- <small class="form-error text-danger" >{{ event_definition_form.event_type_str.errors }}</small>
+<div class="event-edit-field">
+ <div class="input-group">
+ <div class="input-group-prepend">
+ <label for="{{ event_definition_form.event_type_str.id_for_label }}"
+ class="input-group-text">{{ event_definition_form.event_type_str.label }}</label>
+ </div>
+ {{ event_definition_form.event_type_str }}
</div>
+ <small class="form-error text-danger">{{ event_definition_form.event_type_str.errors }}</small>
</div>
-<div class="input-group mb-2 mr-sm-2">
- <div class="input-group-prepend" >
- <label for="{{ event_definition_form.event.id_for_label }}"
- class="input-group-text" >{{ event_definition_form.event_window_secs.label }}</label>
- {{ event_definition_form.event_window_secs }}
- <small class="form-error text-danger" >{{ event_definition_form.event_window_secs.errors }}</small>
+<div class="event-edit-field">
+ <div class="input-group">
+ <div class="input-group-prepend">
+ <label for="{{ event_definition_form.event_window_secs.id_for_label }}"
+ class="input-group-text">{{ event_definition_form.event_window_secs.label }}</label>
+ </div>
+ {{ event_definition_form.event_window_secs }}
</div>
+ <small class="form-error text-danger">{{ event_definition_form.event_window_secs.errors }}</small>
</div>
-<div class="input-group mb-2 mr-sm-2">
- <div class="input-group-prepend" >
- <label for="{{ event_definition_form.dedupe.id_for_label }}"
- class="input-group-text" >{{ event_definition_form.dedupe_window_secs.label }}</label>
- {{ event_definition_form.dedupe_window_secs }}
- <small class="form-error text-danger" >{{ event_definition_form.dedupe_window_secs.errors }}</small>
+<div class="event-edit-field">
+ <div class="input-group">
+ <div class="input-group-prepend">
+ <label for="{{ event_definition_form.dedupe_window_secs.id_for_label }}"
+ class="input-group-text">{{ event_definition_form.dedupe_window_secs.label }}</label>
+ </div>
+ {{ event_definition_form.dedupe_window_secs }}
</div>
+ <small class="form-error text-danger">{{ event_definition_form.dedupe_window_secs.errors }}</small>
</div>
-<div class="mb-2 mr-sm-2">
- {{ event_definition_form.enabled }}<span class="pl-2">Enabled</span>
+<div class="event-edit-toggle">
+ {{ event_definition_form.enabled }}
+ <label for="{{ event_definition_form.enabled.id_for_label }}">Enabled</label>
</div>
-<hr />
-<div>
- <div class="h5">Clauses</div>
+<section class="event-edit-section">
+ <h2 class="event-edit-section-heading">Clauses</h2>
{{ event_clause_formset.management_form }}
{% for event_clause_form in event_clause_formset %}
{% include "event/edit/panes/event_clause_form.html" %}
{% endfor %}
-</div>
+</section>
-<hr />
-<div>
- <div class="h5">Alarm Actions</div>
+<section class="event-edit-section">
+ <h2 class="event-edit-section-heading">Alarm Actions</h2>
{{ alarm_action_formset.management_form }}
{% for alarm_action_form in alarm_action_formset %}
{% include "event/edit/panes/alarm_action_form.html" %}
{% endfor %}
-</div>
+</section>
-<hr />
-<div>
- <div class="h5">Control Actions</div>
+<section class="event-edit-section">
+ <h2 class="event-edit-section-heading">Control Actions</h2>
{{ control_action_formset.management_form }}
{% for control_action_form in control_action_formset %}
{% include "event/edit/panes/control_action_form.html" %}
{% endfor %}
-</div>
+</section>
diff --git a/src/hi/apps/event/tests/test_event_manager.py b/src/hi/apps/event/tests/test_event_manager.py
index 6f56de5e..f2d351e9 100644
--- a/src/hi/apps/event/tests/test_event_manager.py
+++ b/src/hi/apps/event/tests/test_event_manager.py
@@ -535,8 +535,8 @@ class TestEventManagerEventActions(AsyncEventManagerTestCase):
await self.manager._do_new_event_action([event])
# Examine the results - should have called alert manager with correct alarm
- mock_alert_manager.add_alarm_async.assert_called_once()
- alarm_call_args = mock_alert_manager.add_alarm_async.call_args[0][0]
+ mock_alert_manager.upsert_alarm_async.assert_called_once()
+ alarm_call_args = mock_alert_manager.upsert_alarm_async.call_args[0][0]
self.assertEqual(alarm_call_args.title, 'Test Event')
self.assertEqual(alarm_call_args.alarm_level, AlarmLevel.CRITICAL)
@@ -578,7 +578,7 @@ class TestEventManagerEventActions(AsyncEventManagerTestCase):
await self.manager._do_new_event_action([event])
# Examine the results - should NOT have called alert manager
- mock_alert_manager.add_alarm_async.assert_not_called()
+ mock_alert_manager.upsert_alarm_async.assert_not_called()
self.run_async(async_test_logic())
return
diff --git a/src/hi/apps/location/path_geometry.py b/src/hi/apps/location/path_geometry.py
index 0f1001f1..7f2a613f 100644
--- a/src/hi/apps/location/path_geometry.py
+++ b/src/hi/apps/location/path_geometry.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Optional, Tuple
from hi.apps.common.svg_models import SvgRadius
from hi.apps.entity.enums import EntityType
@@ -116,3 +116,41 @@ class PathGeometry:
end_x = center_x + radius_x
end_y = center_y
return f'M {start_x},{start_y} L {end_x},{end_y}'
+
+ @classmethod
+ def create_coverage_triangle_path_string(
+ cls,
+ location_view : LocationView,
+ apex_x : float,
+ apex_y : float,
+ direction : Tuple[float, float],
+ ) -> str:
+ """Closed-path SVG triangle representing a directional coverage
+ area. Apex at ``(apex_x, apex_y)``; base extends along the
+ ``direction`` unit vector. Sized to roughly match the default
+ rectangle path so the visual scale is consistent with other
+ auto-placed Area delegates.
+ """
+ dx, dy = direction
+ # Both dimensions scaled from viewbox so the triangle reads at
+ # the same magnitude as the default rectangle path
+ # (DEFAULT_RADIUS_PERCENT controls both).
+ size_fraction = cls.DEFAULT_RADIUS_PERCENT / 50.0
+ height = location_view.svg_view_box.width * size_fraction * 2.0
+ base_half_width = location_view.svg_view_box.height * size_fraction
+
+ # Perpendicular to direction (rotate 90° counter-clockwise in
+ # SVG coordinates).
+ perp_dx, perp_dy = -dy, dx
+
+ # Base center
+ base_cx = apex_x + ( dx * height )
+ base_cy = apex_y + ( dy * height )
+
+ # Base corners
+ c1x = base_cx + ( perp_dx * base_half_width )
+ c1y = base_cy + ( perp_dy * base_half_width )
+ c2x = base_cx - ( perp_dx * base_half_width )
+ c2y = base_cy - ( perp_dy * base_half_width )
+
+ return f'M {apex_x},{apex_y} L {c1x},{c1y} L {c2x},{c2y} Z'
diff --git a/src/hi/apps/location/position_geometry.py b/src/hi/apps/location/position_geometry.py
index d370d719..2282288a 100644
--- a/src/hi/apps/location/position_geometry.py
+++ b/src/hi/apps/location/position_geometry.py
@@ -24,6 +24,7 @@ heuristic live here as the canonical home.
"""
from decimal import Decimal
+import math
import re
from typing import Optional, Tuple
@@ -33,9 +34,12 @@ from hi.hi_styles import EntityStyle
class PositionGeometry:
- DEFAULT_ICON_SIZE_PERCENT_OF_VIEWBOX = 10.0
- DEFAULT_GRID_COLUMNS = 4
- DEFAULT_GRID_SPACING_FRACTION = 0.18
+ DEFAULT_ICON_SIZE_PERCENT_OF_VIEWBOX = 7.5
+ # Default center-to-center distance between bulk-placement grid
+ # slots, as a fraction of viewbox dimension. Used as a target for
+ # modest counts; large grids tighten below this to fit the
+ # viewbox without clamping.
+ DEFAULT_GRID_SPACING_FRACTION = 0.12
DEFAULT_VIEWBOX_MARGIN_FRACTION = 0.05
@classmethod
@@ -57,7 +61,17 @@ class PositionGeometry:
if grid_total <= 1:
return center_x, center_y
- columns = min( max( 2, cls.DEFAULT_GRID_COLUMNS ), grid_total )
+ # Column count adapts to ``grid_total`` and viewbox aspect:
+ # wider views get more columns, taller views get more rows.
+ # Cap at ``grid_total`` so a small batch in a wide view does
+ # not produce trailing empty cells that skew item centering.
+ aspect_ratio = (
+ view_box.width / view_box.height if view_box.height > 0 else 1.0
+ )
+ columns = min(
+ grid_total,
+ max( 2, math.ceil( math.sqrt( grid_total * aspect_ratio ) ) ),
+ )
rows = ( grid_total + columns - 1 ) // columns
column_index = grid_index % columns
@@ -66,8 +80,26 @@ class PositionGeometry:
column_offset = column_index - ( ( columns - 1 ) / 2.0 )
row_offset = row_index - ( ( rows - 1 ) / 2.0 )
- spacing_x = view_box.width * cls.DEFAULT_GRID_SPACING_FRACTION
- spacing_y = view_box.height * cls.DEFAULT_GRID_SPACING_FRACTION
+ # Default spacing for modest counts; for grids large enough
+ # that the default would overflow the viewbox (minus margin),
+ # tighten so the full grid fits without clamping. Items may
+ # still overlap each other at very large counts — that is
+ # the natural consequence of "user added many items at once,"
+ # not a layout failure.
+ default_spacing_x = view_box.width * cls.DEFAULT_GRID_SPACING_FRACTION
+ default_spacing_y = view_box.height * cls.DEFAULT_GRID_SPACING_FRACTION
+ margin = cls.DEFAULT_VIEWBOX_MARGIN_FRACTION
+ usable_width = view_box.width * ( 1.0 - ( 2.0 * margin ) )
+ usable_height = view_box.height * ( 1.0 - ( 2.0 * margin ) )
+
+ spacing_x = (
+ min( default_spacing_x, usable_width / ( columns - 1 ) )
+ if columns > 1 else 0.0
+ )
+ spacing_y = (
+ min( default_spacing_y, usable_height / ( rows - 1 ) )
+ if rows > 1 else 0.0
+ )
svg_x = center_x + ( column_offset * spacing_x )
svg_y = center_y + ( row_offset * spacing_y )
@@ -105,7 +137,10 @@ class PositionGeometry:
entity,
location_view : LocationView ) -> Decimal:
"""Default scale for an icon entity: ~10% of the viewbox's
- smaller dimension, clamped to the location's
+ smaller dimension, multiplied by the entity type's opt-in
+ size factor (defaults to 1.0; only entity types with
+ meaningfully different intended layout sizes — e.g.
+ Automobile — override it), clamped to the location's
svg_position_bounds.min_scale / max_scale."""
view_box = location_view.svg_view_box
icon_view_box = EntityStyle.get_svg_icon_viewbox( entity.entity_type )
@@ -116,7 +151,8 @@ class PositionGeometry:
viewbox_min_dimension = min( view_box.width, view_box.height )
size_fraction = cls.DEFAULT_ICON_SIZE_PERCENT_OF_VIEWBOX / 100.0
- target_icon_size = viewbox_min_dimension * size_fraction
+ size_factor = EntityStyle.get_icon_size_factor( entity.entity_type )
+ target_icon_size = viewbox_min_dimension * size_fraction * size_factor
scale = target_icon_size / icon_max_dimension
position_bounds = location_view.location.svg_position_bounds
diff --git a/src/hi/apps/location/templates/location/panes/location_dropdown.html b/src/hi/apps/location/templates/location/panes/location_dropdown.html
index a9b23a48..2591d853 100644
--- a/src/hi/apps/location/templates/location/panes/location_dropdown.html
+++ b/src/hi/apps/location/templates/location/panes/location_dropdown.html
@@ -4,7 +4,7 @@
<div class="dropdown">
<button class="btn btn-outline-primary btn-control dropdown-toggle" type="button"
id="hi-location-menu" data-toggle="dropdown">
- SPACES
+ {% icon "layers" size="sm" css_class="hi-icon-left" %}SWITCH SPACE
<span class="caret"></span>
</button>
<div class="dropdown-menu"
diff --git a/src/hi/apps/location/tests/test_position_geometry.py b/src/hi/apps/location/tests/test_position_geometry.py
index 22cfd774..7091be66 100644
--- a/src/hi/apps/location/tests/test_position_geometry.py
+++ b/src/hi/apps/location/tests/test_position_geometry.py
@@ -51,19 +51,36 @@ class TestPositionGeometryGridSlot(BaseTestCase):
PositionGeometry.grid_slot(location_view=view, grid_index=i, grid_total=4)
for i in range(4)
]
- xs = [p[0] for p in positions]
- ys = [p[1] for p in positions]
- self.assertAlmostEqual(xs[0] + xs[3], 1000.0)
- self.assertAlmostEqual(xs[1] + xs[2], 1000.0)
- self.assertEqual(len(set(round(y, 6) for y in ys)), 1)
- self.assertAlmostEqual(ys[0], 500.0)
+ # All four positions are distinct, all sit inside the viewbox
+ # margin, and the distribution is symmetric around the view
+ # center (mean position equals center). Specific grid shape
+ # (2x2 vs 1x4) is an implementation detail of the column-count
+ # adaptation and is not asserted.
+ self.assertEqual(len(set(positions)), 4)
+ margin = 1000 * PositionGeometry.DEFAULT_VIEWBOX_MARGIN_FRACTION
+ for x, y in positions:
+ self.assertGreaterEqual(x, margin)
+ self.assertLessEqual(x, 1000 - margin)
+ self.assertGreaterEqual(y, margin)
+ self.assertLessEqual(y, 1000 - margin)
+ mean_x = sum(p[0] for p in positions) / len(positions)
+ mean_y = sum(p[1] for p in positions) / len(positions)
+ self.assertAlmostEqual(mean_x, 500.0)
+ self.assertAlmostEqual(mean_y, 500.0)
def test_grid_wraps_to_multiple_rows(self):
view = self._make_view(0, 0, 1000, 1000)
- x_0, y_0 = PositionGeometry.grid_slot(location_view=view, grid_index=0, grid_total=8)
- x_4, y_4 = PositionGeometry.grid_slot(location_view=view, grid_index=4, grid_total=8)
- self.assertAlmostEqual(x_0, x_4)
- self.assertLess(y_0, y_4)
+ positions = [
+ PositionGeometry.grid_slot(location_view=view, grid_index=i, grid_total=8)
+ for i in range(8)
+ ]
+ # Grid spans multiple rows AND multiple columns (eight items
+ # cannot fit in a single row or single column at the default
+ # adaptive shape).
+ distinct_xs = {round(p[0], 6) for p in positions}
+ distinct_ys = {round(p[1], 6) for p in positions}
+ self.assertGreater(len(distinct_xs), 1)
+ self.assertGreater(len(distinct_ys), 1)
def test_clamps_to_viewbox_margin(self):
view = self._make_view(0, 0, 100, 100)
diff --git a/src/hi/apps/system/health_status_provider.py b/src/hi/apps/system/health_status_provider.py
index 7eede19a..519f0aff 100644
--- a/src/hi/apps/system/health_status_provider.py
+++ b/src/hi/apps/system/health_status_provider.py
@@ -184,7 +184,7 @@ class HealthStatusProvider(ABC):
)
if alarm is None:
return
- AlertManager().add_alarm( alarm = alarm )
+ AlertManager().upsert_alarm( alarm = alarm )
return
diff --git a/src/hi/apps/weather/constants.py b/src/hi/apps/weather/constants.py
index 4b9c243a..c987d3ad 100644
--- a/src/hi/apps/weather/constants.py
+++ b/src/hi/apps/weather/constants.py
@@ -1,3 +1,8 @@
class WeatherConstants:
WEATHER_OVERVIEW_TEMPLATE_NAME = 'weather/panes/weather_overview.html'
+
+ # Threshold beyond which the displayed current-conditions reading is
+ # considered "stale" — drives a timestamp tint in the pane plus the
+ # promotion of monitor-health messages from advisory to displayed.
+ CONDITIONS_STALE_THRESHOLD_SECS = 60 * 60
diff --git a/src/hi/apps/weather/enums.py b/src/hi/apps/weather/enums.py
index ee01e748..020d8800 100644
--- a/src/hi/apps/weather/enums.py
+++ b/src/hi/apps/weather/enums.py
@@ -103,16 +103,18 @@ class AlertSeverity( LabeledEnum ):
SEVERE = ( 'Severe' , '' )
MODERATE = ( 'Moderate' , '' )
MINOR = ( 'Minor' , '' )
+ UNKNOWN = ( 'Unknown' , '' )
def css_class(self):
"""Return Bootstrap alert CSS class for this severity level."""
severity_css_map = {
'EXTREME': 'danger',
- 'SEVERE': 'warning',
+ 'SEVERE': 'warning',
'MODERATE': 'primary',
- 'MINOR': 'info'
+ 'MINOR': 'info',
+ 'UNKNOWN': 'tertiary',
}
- return severity_css_map.get(self.name, 'secondary')
+ return severity_css_map.get(self.name, 'tertiary')
class AlertUrgency( LabeledEnum ):
@@ -127,6 +129,7 @@ class AlertCertainty( LabeledEnum ):
LIKELY = ( 'Likely' , '' )
POSSIBLE = ( 'Possible' , '' )
UNLIKELY = ( 'Unlikely' , '' )
+ UNKNOWN = ( 'Unknown' , '' )
class AlertStatus( LabeledEnum ):
diff --git a/src/hi/apps/weather/monitors.py b/src/hi/apps/weather/monitors.py
index e32e9620..648e7f4e 100644
--- a/src/hi/apps/weather/monitors.py
+++ b/src/hi/apps/weather/monitors.py
@@ -19,20 +19,25 @@ logger = logging.getLogger(__name__)
class WeatherMonitor( PeriodicMonitor, AlertMixin, SettingsMixin ):
MONITOR_ID = 'hi.apps.weather.monitor'
- WEATHER_POLLING_INTERVAL_SECS = 150
- STARTUP_SAFETY_SECS = 30
-
+
def __init__( self ):
+ self._settings_helper = WeatherSettingsHelper()
super().__init__(
id = self.MONITOR_ID,
- interval_secs = self.WEATHER_POLLING_INTERVAL_SECS,
+ # Provisional interval; ``initialize()`` reads the configured
+ # value via the async settings path and overwrites it. The
+ # async loop reads self._query_interval_secs each tick so a
+ # post-init change takes effect before the next sleep.
+ interval_secs = WeatherSettingsHelper.DEFAULT_POLLING_INTERVAL_SECONDS,
)
self._weather_data_source_instance_list = list()
self._started_datetime = datetimeproxy.now()
- self._settings_helper = WeatherSettingsHelper()
return
-
+
async def initialize(self) -> None:
+ self._query_interval_secs = (
+ await self._settings_helper.get_default_polling_interval_secs_async()
+ )
discovered_sources = WeatherSourceDiscovery.discover_weather_data_source_instances()
self._weather_data_source_instance_list = discovered_sources
@@ -59,16 +64,18 @@ class WeatherMonitor( PeriodicMonitor, AlertMixin, SettingsMixin ):
provider_id = cls.MONITOR_ID,
provider_name = 'Weather Monitor',
description = 'Weather data collection and monitoring',
- expected_heartbeat_interval_secs = cls.WEATHER_POLLING_INTERVAL_SECS,
+ expected_heartbeat_interval_secs = (
+ WeatherSettingsHelper.DEFAULT_POLLING_INTERVAL_SECONDS
+ ),
)
def alarm_ceiling(self):
# Cap at INFO for two reasons:
# 1. Weather staleness is informational — the user is not
- # typically depending on a 150-second freshness window.
- # 2. The monitor records WARNING during its 30-second startup-
- # safety window. Capping at INFO prevents that startup
- # transition from firing alarms on every server restart.
+ # typically depending on the configured freshness window.
+ # 2. The monitor records WARNING during its startup-safety
+ # window. Capping at INFO prevents that startup transition
+ # from firing alarms on every server restart.
return AlarmLevel.INFO
async def do_work(self):
@@ -80,7 +87,8 @@ class WeatherMonitor( PeriodicMonitor, AlertMixin, SettingsMixin ):
weather_source_manager = WeatherSourceManager()
uptime = datetimeproxy.now() - self._started_datetime
- if uptime.total_seconds() < self.STARTUP_SAFETY_SECS:
+ warmup_secs = await self._settings_helper.get_startup_warmup_secs_async()
+ if uptime.total_seconds() < warmup_secs:
message = 'Startup safety period. Waiting to fetch.'
logger.debug( message )
self.record_warning( message )
diff --git a/src/hi/apps/weather/settings.py b/src/hi/apps/weather/settings.py
index b9ebc6d6..c66afe9f 100644
--- a/src/hi/apps/weather/settings.py
+++ b/src/hi/apps/weather/settings.py
@@ -14,8 +14,10 @@ def _create_dynamic_weather_settings() -> Dict[str, SettingDefinition]:
discovered_sources = WeatherSourceDiscovery.discover_weather_data_source_instances()
for source in discovered_sources:
+ source_key_prefix = source.id.upper().replace( '-', '_' )
+
# Create enabled/disabled setting for each source
- enabled_key = f"{source.id.upper()}_ENABLED"
+ enabled_key = f"{source_key_prefix}_ENABLED"
settings_dict[enabled_key] = SettingDefinition(
label=f'Enable {source.label}',
description=f'Enable the {source.label} weather data source.',
@@ -25,10 +27,28 @@ def _create_dynamic_weather_settings() -> Dict[str, SettingDefinition]:
is_required=True,
initial_value=source.get_default_enabled_state(),
)
-
+
+ # Create base URL setting for each source so the upstream API
+ # endpoint is configurable (point at a simulator, a mirror,
+ # etc.). Default is the source's canonical URL.
+ base_url_key = f"{source_key_prefix}_BASE_URL"
+ canonical_base_url = getattr( source, 'BASE_URL', '' )
+ settings_dict[base_url_key] = SettingDefinition(
+ label=f'{source.label} Base URL',
+ description=(
+ f'Base URL for {source.label} HTTP requests. '
+ f'Usually: {canonical_base_url}'
+ ),
+ value_type=AttributeValueType.TEXT,
+ value_range_str='',
+ is_editable=True,
+ is_required=False,
+ initial_value=canonical_base_url,
+ )
+
# Create API key setting if source requires it
if source.requires_api_key():
- api_key_key = f"{source.id.upper()}_API_KEY"
+ api_key_key = f"{source_key_prefix}_API_KEY"
settings_dict[api_key_key] = SettingDefinition(
label=f'{source.label} API Key',
description=f'API key for {source.label} weather service (required if is enabled).',
@@ -38,16 +58,30 @@ def _create_dynamic_weather_settings() -> Dict[str, SettingDefinition]:
is_required=False,
initial_value='',
)
-
+
# Add general weather settings
- settings_dict['DEFAULT_POLLING_INTERVAL_MINUTES'] = SettingDefinition(
- label='Default Polling Interval (Minutes)',
- description='Default interval in minutes for polling weather data from enabled sources.',
+ settings_dict['DEFAULT_POLLING_INTERVAL_SECONDS'] = SettingDefinition(
+ label='Default Polling Interval (Seconds)',
+ description='Default interval in seconds for polling weather data from enabled sources.',
+ value_type=AttributeValueType.INTEGER,
+ value_range_str='5-86400', # 5 seconds to 24 hours
+ is_editable=True,
+ is_required=True,
+ initial_value=600,
+ )
+
+ settings_dict['STARTUP_WARMUP_SECONDS'] = SettingDefinition(
+ label='Startup Warmup (Seconds)',
+ description=(
+ 'Delay before the weather monitor issues its first API '
+ 'calls after server startup. Guards against accidental '
+ 'rate-limit hits during restart loops. 0 disables warmup.'
+ ),
value_type=AttributeValueType.INTEGER,
- value_range_str='5-1440', # 5 minutes to 24 hours
+ value_range_str='0-300',
is_editable=True,
is_required=True,
- initial_value=10,
+ initial_value=30,
)
settings_dict['WEATHER_CACHE_ENABLED'] = SettingDefinition(
diff --git a/src/hi/apps/weather/templates/weather/panes/conditions.html b/src/hi/apps/weather/templates/weather/panes/conditions.html
index a42d3198..d17ca35b 100644
--- a/src/hi/apps/weather/templates/weather/panes/conditions.html
+++ b/src/hi/apps/weather/templates/weather/panes/conditions.html
@@ -1,4 +1,5 @@
{% load static %}
+{% load icons %}
{% load units %}
{% load tz %}
{% timezone USER_TIMEZONE %}
@@ -72,9 +73,16 @@
</div>
-{% if conditions.temperature.source %}
-<div class="text-muted">
- <small><em>At {{ conditions.temperature.source_datetime |localtime|date:"g:i A" }} from {{ conditions.temperature.source.abbreviation }} </em></small>
+<div class="weather-pane-status mt-2">
+ {% if weather_pane_status.caption_text %}
+ <div class="alert {{ weather_pane_status.caption_alert_class }} py-1 px-2 mb-0 d-flex align-items-center small" role="status">
+ {% icon weather_pane_status.caption_icon size="sm" css_class="hi-icon-left" %}<span>{{ weather_pane_status.caption_text }}</span>
+ </div>
+ {% if conditions.temperature.source %}
+ <small class="text-muted d-block mt-1"><em>Last reading: {{ conditions.temperature.source_datetime |localtime|date:"g:i A" }} from {{ conditions.temperature.source.abbreviation }}</em></small>
+ {% endif %}
+ {% elif conditions.temperature.source %}
+ <small class="{% if weather_pane_status.is_timestamp_stale %}text-warning{% else %}text-muted{% endif %}"><em>At {{ conditions.temperature.source_datetime |localtime|date:"g:i A" }} from {{ conditions.temperature.source.abbreviation }}</em></small>
+ {% endif %}
</div>
-{% endif %}
{% endtimezone%}
diff --git a/src/hi/apps/weather/templates/weather/panes/weather_alerts.html b/src/hi/apps/weather/templates/weather/panes/weather_alerts.html
index 2024a1ab..be353254 100644
--- a/src/hi/apps/weather/templates/weather/panes/weather_alerts.html
+++ b/src/hi/apps/weather/templates/weather/panes/weather_alerts.html
@@ -1,30 +1,25 @@
{% load tz %}
{% timezone USER_TIMEZONE %}
-<div id="{{ DIVID.WEATHER_ALERTS }}">
- {% for weather_alert in weather_alert_list %}
- <div class="details-popup-wrapper alert alert-{{ weather_alert.css_class }} mb-2">
- <div class="details-popup-summary"
- onclick="Hi.toggleDetails('weather-alert-{{ forloop.counter }}');">
- <strong>{{ weather_alert.event }}</strong> • {{ weather_alert.severity.label }} •
- </div>
- <div id="weather-alert-{{ forloop.counter }}" class="details-popup-content"
- onclick="Hi.toggleDetails('weather-alert-{{ forloop.counter }}');">
- <p>
- <strong>{{ weather_alert.headline }}</strong>
- </p>
- <hr>
- <p class="mb-1">{{ weather_alert.description }}</p>
- <hr>
- <small>
- <strong>{{ weather_alert.event_type.label }}</strong> • {{ weather_alert.severity.label }} •
- Effective: {{ weather_alert.effective|localtime|date:"M j, Y g:i A" }}
- {% if weather_alert.expires %} • Expires: {{ weather_alert.expires|localtime|date:"M j, Y g:i A" }}{% endif %}
- </small>
- </div>
-
+{% for weather_alert in weather_alert_list %}
+<div class="details-popup-wrapper alert alert-{{ weather_alert.css_class }} mb-2">
+ <div class="details-popup-summary"
+ onclick="Hi.toggleDetails('weather-alert-{{ forloop.counter }}');">
+ <strong>{{ weather_alert.event }}</strong> • {{ weather_alert.severity.label }} •
+ </div>
+ <div id="weather-alert-{{ forloop.counter }}" class="details-popup-content"
+ onclick="Hi.toggleDetails('weather-alert-{{ forloop.counter }}');">
+ <p>
+ <strong>{{ weather_alert.headline }}</strong>
+ </p>
+ <hr>
+ <p class="mb-1">{{ weather_alert.description }}</p>
+ <hr>
+ <small>
+ <strong>{{ weather_alert.event_type.label }}</strong> • {{ weather_alert.severity.label }} •
+ Effective: {{ weather_alert.effective|localtime|date:"M j, Y g:i A" }}
+ {% if weather_alert.expires %} • Expires: {{ weather_alert.expires|localtime|date:"M j, Y g:i A" }}{% endif %}
+ </small>
</div>
- {% empty %}
- <div class="alert alert-info"> No weather alerts.</div>
- {% endfor %}
</div>
+{% endfor %}
{% endtimezone %}
diff --git a/src/hi/apps/weather/tests/test_enums.py b/src/hi/apps/weather/tests/test_enums.py
index 451d793c..57c98180 100644
--- a/src/hi/apps/weather/tests/test_enums.py
+++ b/src/hi/apps/weather/tests/test_enums.py
@@ -214,7 +214,7 @@ class TestWeatherEnums(BaseTestCase):
def test_AlertSeverity_basic_functionality(self):
"""Test AlertSeverity enum has expected values"""
- expected_severities = ['MINOR', 'MODERATE', 'SEVERE', 'EXTREME']
+ expected_severities = ['MINOR', 'MODERATE', 'SEVERE', 'EXTREME', 'UNKNOWN']
for severity_name in expected_severities:
with self.subTest(severity=severity_name):
@@ -239,7 +239,7 @@ class TestWeatherEnums(BaseTestCase):
def test_AlertCertainty_basic_functionality(self):
"""Test AlertCertainty enum has expected values"""
- expected_certainties = ['OBSERVED', 'LIKELY', 'POSSIBLE', 'UNLIKELY']
+ expected_certainties = ['OBSERVED', 'LIKELY', 'POSSIBLE', 'UNLIKELY', 'UNKNOWN']
for certainty_name in expected_certainties:
with self.subTest(certainty=certainty_name):
diff --git a/src/hi/apps/weather/tests/test_nws.py b/src/hi/apps/weather/tests/test_nws.py
index 4be0fe51..e48a16a2 100644
--- a/src/hi/apps/weather/tests/test_nws.py
+++ b/src/hi/apps/weather/tests/test_nws.py
@@ -1417,7 +1417,7 @@ class TestNationalWeatherService( BaseTestCase ):
continue
return
- @patch('hi.apps.weather.weather_sources.nws.requests.get')
+ @patch('hi.apps.weather.weather_data_source.requests.get')
def test_get_points_data_from_api(self, mock_get):
"""Test API call for points data."""
nws = NationalWeatherService()
@@ -1445,7 +1445,7 @@ class TestNationalWeatherService( BaseTestCase ):
self.assertEqual(actual_url, expected_url)
return
- @patch('hi.apps.weather.weather_sources.nws.requests.get')
+ @patch('hi.apps.weather.weather_data_source.requests.get')
def test_get_points_data_from_api_error(self, mock_get):
"""Test API call error handling."""
nws = NationalWeatherService()
@@ -2333,7 +2333,7 @@ class TestNationalWeatherService( BaseTestCase ):
return
- @patch('hi.apps.weather.weather_sources.nws.requests.get')
+ @patch('hi.apps.weather.weather_data_source.requests.get')
def test_get_alerts_data_from_api_success(self, mock_get):
"""Test successful API call for weather alerts - HIGH VALUE for alerts integration."""
# Mock successful API response based on NWS alerts API format
@@ -2403,7 +2403,7 @@ class TestNationalWeatherService( BaseTestCase ):
self.assertIn('alerts/active', actual_url)
return
- @patch('hi.apps.weather.weather_sources.nws.requests.get')
+ @patch('hi.apps.weather.weather_data_source.requests.get')
def test_get_alerts_data_from_api_no_alerts(self, mock_get):
"""Test API response with no active alerts - HIGH VALUE for empty response handling."""
# Mock API response with no alerts
diff --git a/src/hi/apps/weather/tests/test_openmeteo.py b/src/hi/apps/weather/tests/test_openmeteo.py
index eb07cc63..631d6e72 100644
--- a/src/hi/apps/weather/tests/test_openmeteo.py
+++ b/src/hi/apps/weather/tests/test_openmeteo.py
@@ -39,7 +39,7 @@ class TestOpenMeteo(BaseTestCase):
self.assertEqual(self.openmeteo.priority, 2)
return
- @patch('hi.apps.weather.weather_sources.openmeteo.requests.get')
+ @patch('hi.apps.weather.weather_data_source.requests.get')
def test_current_weather_api_integration(self, mock_get):
"""Test that OpenMeteo API integration works correctly end-to-end."""
# Mock realistic OpenMeteo API response
diff --git a/src/hi/apps/weather/tests/test_sunrise_sunset_org.py b/src/hi/apps/weather/tests/test_sunrise_sunset_org.py
index 09cd8c0b..aa886fea 100644
--- a/src/hi/apps/weather/tests/test_sunrise_sunset_org.py
+++ b/src/hi/apps/weather/tests/test_sunrise_sunset_org.py
@@ -53,7 +53,7 @@ class TestSunriseSunsetOrg(BaseTestCase):
self.assertEqual(self.sunrise_sunset.id, SunriseSunsetOrg.SOURCE_ID)
return
- @patch('hi.apps.weather.weather_sources.sunrise_sunset_org.requests.get')
+ @patch('hi.apps.weather.weather_data_source.requests.get')
def test_get_astronomical_api_data_from_api_success(self, mock_get):
"""Test successful API call for astronomical data."""
# Mock successful API response based on sunrise-sunset.org documentation
@@ -97,7 +97,7 @@ class TestSunriseSunsetOrg(BaseTestCase):
self.assertIn('formatted=0', actual_url)
return
- @patch('hi.apps.weather.weather_sources.sunrise_sunset_org.requests.get')
+ @patch('hi.apps.weather.weather_data_source.requests.get')
def test_get_astronomical_api_data_from_api_error(self, mock_get):
"""Test API error handling."""
# Mock HTTP error response
diff --git a/src/hi/apps/weather/tests/test_usno.py b/src/hi/apps/weather/tests/test_usno.py
index 00f1778f..f50186f1 100644
--- a/src/hi/apps/weather/tests/test_usno.py
+++ b/src/hi/apps/weather/tests/test_usno.py
@@ -58,7 +58,7 @@ class TestUSNO(BaseTestCase):
# These tests focus on testing the public interface of USNO
# rather than testing private implementation details
- @patch('hi.apps.weather.weather_sources.usno.requests.get')
+ @patch('hi.apps.weather.weather_data_source.requests.get')
def test_get_astronomical_data_returns_complete_data(self, mock_get):
"""Test that get_astronomical_data returns properly structured astronomical data."""
# Mock successful API response with comprehensive data
@@ -132,7 +132,7 @@ class TestUSNO(BaseTestCase):
self.assertEqual(result.sunrise.station.source.id, 'usno')
return
- @patch('hi.apps.weather.weather_sources.usno.requests.get')
+ @patch('hi.apps.weather.weather_data_source.requests.get')
def test_get_astronomical_data_handles_api_errors_gracefully(self, mock_get):
"""Test that API errors are handled gracefully in public interface."""
# Mock API error - need to mock the redis client to skip cache
@@ -152,7 +152,7 @@ class TestUSNO(BaseTestCase):
)
return
- @patch('hi.apps.weather.weather_sources.usno.requests.get')
+ @patch('hi.apps.weather.weather_data_source.requests.get')
def test_get_astronomical_data_uses_caching(self, mock_get):
"""Test that the public interface properly uses Redis caching."""
# Mock cached data
@@ -262,7 +262,7 @@ class TestUSNO(BaseTestCase):
# ============= ORIGINAL TESTS (TO BE DEPRECATED) =============
- @patch('hi.apps.weather.weather_sources.usno.requests.get')
+ @patch('hi.apps.weather.weather_data_source.requests.get')
def test_get_astronomical_api_data_from_api_success(self, mock_get):
"""Test successful API call for astronomical data."""
# Mock successful API response based on real USNO API response
@@ -328,7 +328,7 @@ class TestUSNO(BaseTestCase):
self.assertIn('tz=', actual_url)
return
- @patch('hi.apps.weather.weather_sources.usno.requests.get')
+ @patch('hi.apps.weather.weather_data_source.requests.get')
def test_get_astronomical_api_data_from_api_error(self, mock_get):
"""Test API error handling."""
# Mock HTTP error response
diff --git a/src/hi/apps/weather/tests/test_weather_alert_integration.py b/src/hi/apps/weather/tests/test_weather_alert_integration.py
index 5e7ff792..59854401 100644
--- a/src/hi/apps/weather/tests/test_weather_alert_integration.py
+++ b/src/hi/apps/weather/tests/test_weather_alert_integration.py
@@ -197,10 +197,10 @@ class TestWeatherAlertIntegration(AsyncTaskFastTestCase):
self.run_async(test_update())
# Verify alert manager was called to add alarms
- self.assertEqual(mock_alert_manager.add_alarm_async.call_count, 2) # Only 2 should create alarms
+ self.assertEqual(mock_alert_manager.upsert_alarm_async.call_count, 2) # Only 2 should create alarms
# Verify the alarms that were created
- call_args_list = mock_alert_manager.add_alarm_async.call_args_list
+ call_args_list = mock_alert_manager.upsert_alarm_async.call_args_list
alarm1 = call_args_list[0][0][0] # First alarm
alarm2 = call_args_list[1][0][0] # Second alarm
@@ -209,8 +209,11 @@ class TestWeatherAlertIntegration(AsyncTaskFastTestCase):
expected_types = {WeatherEventType.TORNADO.name, WeatherEventType.SEVERE_THUNDERSTORM.name}
self.assertEqual(alarm_types, expected_types)
- # Verify weather alerts were stored
- stored_alerts = mock_weather_manager.get_weather_alerts()
+ # Verify weather alerts were stored. Read from internal storage
+ # directly because the public getter filters out alerts whose
+ # ``expires`` is in the past — the fixture intentionally uses
+ # 2024 dates, which would always be expired.
+ stored_alerts = mock_weather_manager._weather_alerts
self.assertEqual(len(stored_alerts), 3) # All alerts stored, regardless of alarm creation
def _create_test_alert(self, event_type, severity, headline):
diff --git a/src/hi/apps/weather/tests/test_weather_manager.py b/src/hi/apps/weather/tests/test_weather_manager.py
index 67401b44..c0452137 100644
--- a/src/hi/apps/weather/tests/test_weather_manager.py
+++ b/src/hi/apps/weather/tests/test_weather_manager.py
@@ -308,7 +308,7 @@ class TestWeatherManager( AsyncTaskFastTestCase ):
)
# Verify alerts are stored
- stored_alerts = weather_manager.get_weather_alerts()
+ stored_alerts = weather_manager.get_active_weather_alerts()
self.assertEqual(len(stored_alerts), 1)
self.assertEqual(stored_alerts[0].event, "Severe Thunderstorm Warning")
@@ -684,7 +684,7 @@ class TestWeatherManager( AsyncTaskFastTestCase ):
)
# Verify actual behavior: alerts are stored
- stored_alerts = weather_manager.get_weather_alerts()
+ stored_alerts = weather_manager.get_active_weather_alerts()
self.assertEqual(len(stored_alerts), 1)
self.assertEqual(stored_alerts[0].event, "Severe Thunderstorm Warning")
self.assertEqual(stored_alerts[0].severity, AlertSeverity.SEVERE)
@@ -713,7 +713,7 @@ class TestWeatherManager( AsyncTaskFastTestCase ):
)
# Verify actual behavior: no alerts stored when disabled
- stored_alerts = weather_manager.get_weather_alerts()
+ stored_alerts = weather_manager.get_active_weather_alerts()
self.assertEqual(len(stored_alerts), 0,
"No alerts should be stored when alerts are disabled")
@@ -726,7 +726,7 @@ class TestWeatherManager( AsyncTaskFastTestCase ):
weather_manager._weather_alerts = []
# Initially should be empty
- alerts = weather_manager.get_weather_alerts()
+ alerts = weather_manager.get_active_weather_alerts()
self.assertEqual(len(alerts), 0)
# Add test alert directly to verify getter works
@@ -734,7 +734,38 @@ class TestWeatherManager( AsyncTaskFastTestCase ):
weather_manager._weather_alerts = [test_alert]
# Verify getter returns the alert
- alerts = weather_manager.get_weather_alerts()
+ alerts = weather_manager.get_active_weather_alerts()
self.assertEqual(len(alerts), 1)
self.assertEqual(alerts[0].event, "Severe Thunderstorm Warning")
-
+
+ def test_get_active_weather_alerts_filters_expired(self):
+ """Expired alerts are filtered out on read; non-expired and
+ ``expires=None`` alerts pass through. Storage is left untouched
+ (deliberate — wholesale-replace from the next source fetch is
+ the only path that mutates ``_weather_alerts``)."""
+ weather_manager = WeatherManager()
+ weather_manager.ensure_initialized()
+
+ now = datetimeproxy.now()
+ expired_alert = self._create_test_weather_alert()
+ expired_alert.expires = now - timedelta(seconds=10)
+ future_alert = self._create_test_weather_alert()
+ future_alert.event = 'Tornado Warning'
+ future_alert.expires = now + timedelta(minutes=30)
+ permanent_alert = self._create_test_weather_alert()
+ permanent_alert.event = 'Flood Watch'
+ permanent_alert.expires = None
+
+ weather_manager._weather_alerts = [
+ expired_alert, future_alert, permanent_alert,
+ ]
+
+ active = weather_manager.get_active_weather_alerts()
+
+ self.assertEqual(len(active), 2)
+ events = { a.event for a in active }
+ self.assertEqual(events, { 'Tornado Warning', 'Flood Watch' })
+ # Storage is intentionally not mutated by the read path.
+ self.assertEqual(len(weather_manager._weather_alerts), 3)
+
+
diff --git a/src/hi/apps/weather/transient_models.py b/src/hi/apps/weather/transient_models.py
index e916aae4..9245b0a7 100644
--- a/src/hi/apps/weather/transient_models.py
+++ b/src/hi/apps/weather/transient_models.py
@@ -4,6 +4,7 @@ from typing import Dict, Generic, List, Optional, Set, TypeVar
from pint.errors import OffsetUnitCalculusError
+from hi.apps.system.health_status import HealthStatus
from hi.transient_models import GeographicLocation
from hi.units import UnitQuantity
@@ -434,6 +435,55 @@ class WeatherOverviewData:
todays_weather_stats : WeatherStats = None
todays_astronomical_data : AstronomicalData = None
+
+@dataclass( kw_only = True )
+class WeatherPaneStatus:
+ """Caption + timestamp-shading hints for the current-conditions
+ pane, computed from (data freshness × weather monitor health).
+
+ ``caption_text``: text to render in a small status line above the
+ pane, or ``None`` to suppress. ``health_status``: the underlying
+ ``HealthStatus`` when the caption was sourced from the monitor —
+ the template uses its ``status_icon`` and ``status_alert_class``
+ helpers for severity styling. ``None`` for the defensive
+ ``Waiting for data`` fallback, which uses info styling.
+ ``is_timestamp_stale``: tint the existing "At HH:MM" line."""
+
+ caption_text : Optional[str] = None
+ health_status : Optional[HealthStatus] = None
+ is_timestamp_stale : bool = False
+
+ @property
+ def caption_text_class(self) -> str:
+ """Bootstrap text-* class for the status caption. Critical
+ (ERROR) goes red; everything else (WARNING / UNKNOWN /
+ DISABLED) goes yellow; the defensive ``health_status is None``
+ fallback goes blue."""
+ if self.health_status is None:
+ return 'text-info'
+ if self.health_status.is_critical:
+ return 'text-danger'
+ return 'text-warning'
+
+ @property
+ def caption_icon(self) -> str:
+ """Bootstrap icon name for the status caption, taken from the
+ underlying ``HealthStatus`` when present (it already maps each
+ status to an icon) or ``info-circle`` for the defensive
+ fallback."""
+ if self.health_status is None:
+ return 'info-circle'
+ return self.health_status.status_icon
+
+ @property
+ def caption_alert_class(self) -> str:
+ """Bootstrap alert-* class for the status caption banner."""
+ if self.health_status is None:
+ return 'alert-info'
+ if self.health_status.is_critical:
+ return 'alert-danger'
+ return 'alert-warning'
+
@dataclass( kw_only = True )
class HourlyForecast:
@@ -473,6 +523,11 @@ class WeatherAlert:
severity : AlertSeverity
certainty : AlertCertainty
urgency : AlertUrgency
+ # Source-stable identifier for this specific alert. NWS provides
+ # one at the GeoJSON feature level; other sources may not. Used
+ # downstream as ``Alarm.source_alarm_id`` so repeat polls of the
+ # same upstream alert don't tick the alarm counter.
+ alert_id : str | None = None
def css_class(self):
"""Return Bootstrap alert CSS class for this alert's severity."""
diff --git a/src/hi/apps/weather/views.py b/src/hi/apps/weather/views.py
index e5c42724..d0734d28 100644
--- a/src/hi/apps/weather/views.py
+++ b/src/hi/apps/weather/views.py
@@ -14,14 +14,16 @@ class CurrentConditionsDetailsView( HiModalView, WeatherMixin ):
return 'weather/modals/conditions_details.html'
def get(self, request, *args, **kwargs):
- weather_overview_data = self.weather_manager().get_weather_overview_data()
+ weather_manager = self.weather_manager()
+ weather_overview_data = weather_manager.get_weather_overview_data()
context = {
'weather_conditions_data': weather_overview_data.current_conditions_data,
'weather_stats': weather_overview_data.todays_weather_stats,
+ 'weather_pane_status': weather_manager.get_weather_pane_status(),
}
return self.modal_response( request, context )
-
+
class TodaysAstronomicalDetailsView( HiModalView, WeatherMixin ):
def get_template_name( self ) -> str:
diff --git a/src/hi/apps/weather/weather_alert_alarm_mapper.py b/src/hi/apps/weather/weather_alert_alarm_mapper.py
index d05fd3f4..b06da913 100644
--- a/src/hi/apps/weather/weather_alert_alarm_mapper.py
+++ b/src/hi/apps/weather/weather_alert_alarm_mapper.py
@@ -385,7 +385,10 @@ class WeatherAlertAlarmMapper:
if not title or len(title.strip()) == 0:
title = f"{weather_alert.event_type.label} - {weather_alert.severity.label}"
- # Create the alarm
+ # Create the alarm. source_alarm_id ties this Alarm record
+ # back to the specific upstream alert, so repeated polls of
+ # the same active alert refresh expiry without incrementing
+ # alarm_count.
alarm = Alarm(
alarm_source=AlarmSource.WEATHER,
alarm_type=self.get_alarm_type(weather_alert),
@@ -395,6 +398,7 @@ class WeatherAlertAlarmMapper:
security_level=SecurityLevel.OFF, # Weather alarms apply to all security levels
alarm_lifetime_secs=self.get_alarm_lifetime(weather_alert),
timestamp=datetimeproxy.now(),
+ source_alarm_id=weather_alert.alert_id,
)
logger.info(f'Created weather alarm: {alarm.signature} - {alarm.title}')
diff --git a/src/hi/apps/weather/weather_data_source.py b/src/hi/apps/weather/weather_data_source.py
index e1531e22..57293769 100644
--- a/src/hi/apps/weather/weather_data_source.py
+++ b/src/hi/apps/weather/weather_data_source.py
@@ -2,6 +2,8 @@ from abc import abstractmethod
from datetime import datetime
import logging
import redis
+import requests
+from urllib.parse import urlparse
from django.conf import settings
@@ -18,7 +20,54 @@ logger = logging.getLogger(__name__)
class WeatherDataSource( ApiHealthStatusProvider ):
TRACE = False
- FORCE_CAN_POLL = False # For debugging
+ BASE_URL = '' # Override in each subclass with the canonical upstream URL.
+
+ LOCALHOST_HOSTNAMES = ( '127.0.0.1', 'localhost', '::1' )
+
+ def _log_fetch_error( self, label : str, exc : Exception ) -> None:
+ """Log an upstream-fetch failure at the right level / verbosity.
+
+ HTTP errors and other ``requests`` failures emit a single-line
+ ERROR — the status/url/message is the whole story and a
+ traceback is just noise. Anything else still gets the full
+ ``logger.exception`` traceback because it's likely a real bug
+ in the parsing or wiring path.
+ """
+ if isinstance( exc, requests.exceptions.HTTPError ):
+ response = exc.response
+ if response is not None:
+ logger.error(
+ f'Problem fetching {self._abbreviation} {label}: '
+ f'HTTP {response.status_code} for {response.url}'
+ )
+ return
+ if isinstance( exc, requests.exceptions.RequestException ):
+ logger.error(
+ f'Problem fetching {self._abbreviation} {label}: '
+ f'{type(exc).__name__}: {exc}'
+ )
+ return
+ logger.exception( f'Problem fetching {self._abbreviation} {label}: {exc}' )
+ return
+
+ def _is_localhost_target( self ) -> bool:
+ host = urlparse( self._get_base_url() ).hostname or ''
+ return host.lower() in self.LOCALHOST_HOSTNAMES
+
+ def _get_base_url( self ) -> str:
+ """Effective base URL for this source's HTTP calls.
+
+ Consults the configured ``<SOURCE>_BASE_URL`` setting (lets
+ operators point a source at a simulator, mirror, etc.) and
+ falls back to the subclass's canonical ``BASE_URL`` constant
+ when the setting is unset.
+ """
+ helper = self._get_weather_settings_helper()
+ if helper:
+ override = helper.get_weather_source_base_url( self.weather_source_id() )
+ if override:
+ return override
+ return self.BASE_URL
@classmethod
@abstractmethod
@@ -115,6 +164,37 @@ class WeatherDataSource( ApiHealthStatusProvider ):
def get_api_timeout(self) -> float:
return 30.0
+
+ def _api_get_json( self,
+ operation_name : str,
+ url : str,
+ *,
+ headers : dict = None,
+ timeout : float = None ) -> dict:
+ """Issue a GET, track it for API health, and return parsed JSON.
+
+ Wraps the entire request lifecycle (HTTP status check + JSON
+ parse) inside ``api_call_context`` so that:
+
+ - 4xx/5xx responses (HTTPError from ``raise_for_status``)
+ - JSON parse failures
+ - network errors / timeouts (RequestException)
+
+ all count against the API success rate. Tracking only the
+ ``requests.get`` call would let HTTP errors slip through as
+ ``SUCCESS`` because ``requests`` returns a Response object
+ even for non-2xx status — that was the original bug.
+ """
+ if timeout is None:
+ timeout = self.get_api_timeout()
+ with self.api_call_context( operation_name ):
+ response = requests.get(
+ url,
+ headers = headers,
+ timeout = timeout,
+ )
+ response.raise_for_status()
+ return response.json()
def _get_weather_settings_helper(self):
"""Lazy initialization of weather settings helper to avoid circular imports."""
@@ -175,10 +255,14 @@ class WeatherDataSource( ApiHealthStatusProvider ):
def can_fetch(self):
- if settings.DEBUG and self.FORCE_CAN_POLL:
- logger.warning( 'Force polling in effect.' )
+ # Targeting a localhost simulator in DEBUG means the operator
+ # is iterating against a fake API — rate limits don't apply.
+ if settings.DEBUG and self._is_localhost_target():
+ logger.debug(
+ f'[{self.id}] Bypassing rate limit (DEBUG + localhost target)'
+ )
return True
-
+
last_poll_datetime = self.fetch_last_poll_datetime()
if not last_poll_datetime:
logger.info( f'No last polling data for: {self.label}' )
diff --git a/src/hi/apps/weather/weather_manager.py b/src/hi/apps/weather/weather_manager.py
index 9f1addcf..cab93b1f 100644
--- a/src/hi/apps/weather/weather_manager.py
+++ b/src/hi/apps/weather/weather_manager.py
@@ -8,6 +8,7 @@ from django.http import HttpRequest
from django.template.loader import get_template
from hi.apps.alert.alert_mixins import AlertMixin
+from hi.apps.common import datetimeproxy
from hi.apps.common.singleton import Singleton
from hi.apps.config.settings_mixins import SettingsMixin
from hi.apps.console.console_helper import ConsoleSettingsHelper
@@ -32,6 +33,7 @@ from .transient_models import (
IntervalWeatherHistory,
IntervalAstronomical,
WeatherAlert,
+ WeatherPaneStatus,
WeatherStats,
)
from .interval_data_manager import IntervalDataManager
@@ -127,6 +129,74 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
todays_astronomical_data = self.get_todays_astronomical_data(),
)
+ def get_weather_pane_status(self) -> WeatherPaneStatus:
+ """Status line content for the current-conditions pane,
+ computed from (data freshness × weather monitor health). See
+ the design discussion in the commit that introduced this for
+ the cross-product rules. The pane always renders something at
+ the bottom: in the healthy path, the existing
+ ``At HH:MM from <SOURCE>`` timestamp; otherwise this method's
+ result drives the swap to a captioned/iconified line."""
+ # Lazy imports keep the transient-models import graph quiet
+ # (these modules also import from weather indirectly).
+ from hi.apps.monitor.monitor_manager import AppMonitorManager
+ from .monitors import WeatherMonitor
+
+ conditions = self.get_current_conditions_data()
+ if conditions.temperature is None:
+ data_state = 'none'
+ else:
+ age_secs = (
+ datetimeproxy.now() - conditions.temperature.source_datetime
+ ).total_seconds()
+ if age_secs > WeatherConstants.CONDITIONS_STALE_THRESHOLD_SECS:
+ data_state = 'stale'
+ else:
+ data_state = 'fresh'
+
+ health_status = None
+ try:
+ provider = AppMonitorManager().get_health_status_by_monitor_id(
+ WeatherMonitor.MONITOR_ID,
+ )
+ health_status = provider.health_status
+ except KeyError:
+ # Monitor isn't registered. Treat the same as the defensive
+ # "none × healthy" cell below — caller will surface the
+ # fallback caption.
+ pass
+
+ is_healthy = ( health_status is not None and health_status.is_healthy )
+
+ if data_state == 'fresh':
+ # The pane's existing timestamp line is sufficient.
+ return WeatherPaneStatus()
+
+ if data_state == 'stale' and is_healthy:
+ # Keep the timestamp line; just tint it.
+ return WeatherPaneStatus( is_timestamp_stale = True )
+
+ if data_state == 'none' and is_healthy:
+ # Reachable in practice — the weather monitor reports
+ # aggregate health across multiple endpoints, so it can
+ # land HEALTHY when only some of the underlying endpoints
+ # succeed. Operators can drill into System Info for the
+ # per-endpoint detail; the pane just shows a neutral
+ # fallback instead of going blank.
+ return WeatherPaneStatus( caption_text = 'Waiting for data' )
+
+ # Non-healthy: surface the monitor's own message.
+ caption_text = None
+ if health_status is not None:
+ caption_text = health_status.last_message or health_status.status_display
+ if not caption_text:
+ caption_text = 'Weather data unavailable'
+ return WeatherPaneStatus(
+ caption_text = caption_text,
+ health_status = health_status,
+ is_timestamp_stale = ( data_state == 'stale' ),
+ )
+
def get_weather_stats_today(self) -> WeatherStats:
location_key = self._get_location_key()
return self._daily_weather_tracker.get_weather_stats_today(location_key)
@@ -147,9 +217,21 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
with self._data_sync_lock:
return self._daily_astronomical_data
- def get_weather_alerts(self) -> List[WeatherAlert]:
+ def get_active_weather_alerts(self) -> List[WeatherAlert]:
+ """Stored alerts whose ``expires`` is still in the future (or
+ unset). Filtering on read means a self-expiring alert drops
+ from the UI on the next read, without waiting for the slower
+ weather-source poll to overwrite the stored list.
+
+ If a caller ever needs the unfiltered set, add an explicit
+ ``get_all_weather_alerts`` rather than relaxing this method.
+ """
+ now = datetimeproxy.now()
with self._data_sync_lock:
- return self._weather_alerts
+ return [
+ alert for alert in self._weather_alerts
+ if alert.expires is None or alert.expires > now
+ ]
async def update_current_conditions( self,
data_point_source : DataPointSource,
@@ -275,7 +357,7 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
alert_manager = await self.alert_manager_async()
if alert_manager:
for alarm in alarms:
- await alert_manager.add_alarm_async(alarm)
+ await alert_manager.upsert_alarm_async(alarm)
logger.info(f'Added weather alarm to system: {alarm.signature}')
else:
logger.warning('Alert manager not available, weather alarms not created')
@@ -422,20 +504,13 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
weather_overview_data = self.get_weather_overview_data()
context = {
'weather_overview_data': weather_overview_data,
+ 'weather_pane_status': self.get_weather_pane_status(),
}
template = get_template( WeatherConstants.WEATHER_OVERVIEW_TEMPLATE_NAME )
weather_overview_html_str = template.render( context, request = request )
-
- weather_alert_list = self.get_weather_alerts()
- alerts_context = {
- 'weather_alert_list': weather_alert_list
- }
- alerts_template = get_template( 'weather/panes/weather_alerts.html' )
- weather_alerts_html_str = alerts_template.render( alerts_context, request = request )
-
+
return {
DIVID['WEATHER_OVERVIEW']: weather_overview_html_str,
- DIVID['WEATHER_ALERTS']: weather_alerts_html_str,
}
def _get_location_key(self):
diff --git a/src/hi/apps/weather/weather_settings_helper.py b/src/hi/apps/weather/weather_settings_helper.py
index f4e3b413..173a211b 100644
--- a/src/hi/apps/weather/weather_settings_helper.py
+++ b/src/hi/apps/weather/weather_settings_helper.py
@@ -1,5 +1,5 @@
import logging
-from typing import Dict, List
+from typing import Dict, List, Optional
from hi.apps.config.settings_mixins import SettingsMixin
from .settings import WeatherSetting
@@ -9,11 +9,15 @@ logger = logging.getLogger(__name__)
class WeatherSettingsHelper( SettingsMixin ):
"""Helper class to access weather-related settings."""
-
+
+ @staticmethod
+ def _source_setting_prefix( source_id: str ) -> str:
+ return source_id.upper().replace( '-', '_' )
+
def _get_weather_source_enabled_value(self, source_id: str, settings_manager):
"""Private helper to get weather source enabled value with any settings manager."""
# Dynamically find the setting enum for this source
- enabled_setting_name = f"{source_id.upper()}_ENABLED"
+ enabled_setting_name = f"{self._source_setting_prefix(source_id)}_ENABLED"
try:
setting_enum = getattr(WeatherSetting, enabled_setting_name)
@@ -39,14 +43,29 @@ class WeatherSettingsHelper( SettingsMixin ):
return False
return self._get_weather_source_enabled_value(source_id, settings_manager)
+ def get_weather_source_base_url(self, source_id: str) -> Optional[str]:
+ """Configured base URL for this source. Returns ``None`` if the
+ setting is unset / empty so the caller can fall back to the
+ source's canonical default."""
+ setting_name = f"{self._source_setting_prefix(source_id)}_BASE_URL"
+ try:
+ setting_enum = getattr(WeatherSetting, setting_name)
+ except AttributeError:
+ return None
+ value = self.settings_manager().get_setting_value(setting_enum)
+ if value is None:
+ return None
+ value_str = str(value).strip()
+ return value_str if value_str else None
+
def get_weather_source_api_key(self, source_id: str) -> str:
- api_key_setting_name = f"{source_id.upper()}_API_KEY"
+ api_key_setting_name = f"{self._source_setting_prefix(source_id)}_API_KEY"
try:
setting_enum = getattr(WeatherSetting, api_key_setting_name)
except AttributeError:
logger.debug(f'No API key setting for weather source: {source_id}')
return ''
-
+
value = self.settings_manager().get_setting_value(setting_enum)
return str(value) if value is not None else ''
@@ -64,25 +83,68 @@ class WeatherSettingsHelper( SettingsMixin ):
return enabled_sources
- def get_default_polling_interval_minutes(self) -> int:
- """Get the default polling interval in minutes."""
- value = self.settings_manager().get_setting_value(WeatherSetting.DEFAULT_POLLING_INTERVAL_MINUTES)
+ DEFAULT_POLLING_INTERVAL_SECONDS = 600
+ DEFAULT_STARTUP_WARMUP_SECONDS = 30
+
+ def _coerce_int_setting( self, value, default : int, label : str ) -> int:
try:
- return int(value) if value is not None else 10
+ return int(value) if value is not None else default
except (ValueError, TypeError):
- logger.warning(f'Invalid polling interval value: {value}, using default 10 minutes')
- return 10
+ logger.warning(
+ f'Invalid {label} value: {value}, using default {default} seconds'
+ )
+ return default
+
+ def get_default_polling_interval_secs(self) -> int:
+ """Get the default polling interval in seconds."""
+ value = self.settings_manager().get_setting_value(
+ WeatherSetting.DEFAULT_POLLING_INTERVAL_SECONDS )
+ return self._coerce_int_setting(
+ value, self.DEFAULT_POLLING_INTERVAL_SECONDS, 'polling interval' )
+
+ async def get_default_polling_interval_secs_async(self) -> int:
+ settings_manager = await self.settings_manager_async()
+ if not settings_manager:
+ return self.DEFAULT_POLLING_INTERVAL_SECONDS
+ value = settings_manager.get_setting_value(
+ WeatherSetting.DEFAULT_POLLING_INTERVAL_SECONDS )
+ return self._coerce_int_setting(
+ value, self.DEFAULT_POLLING_INTERVAL_SECONDS, 'polling interval' )
+
+ def get_startup_warmup_secs(self) -> int:
+ """Get the startup warmup delay in seconds."""
+ value = self.settings_manager().get_setting_value(
+ WeatherSetting.STARTUP_WARMUP_SECONDS )
+ return self._coerce_int_setting(
+ value, self.DEFAULT_STARTUP_WARMUP_SECONDS, 'startup warmup' )
+
+ async def get_startup_warmup_secs_async(self) -> int:
+ settings_manager = await self.settings_manager_async()
+ if not settings_manager:
+ return self.DEFAULT_STARTUP_WARMUP_SECONDS
+ value = settings_manager.get_setting_value(
+ WeatherSetting.STARTUP_WARMUP_SECONDS )
+ return self._coerce_int_setting(
+ value, self.DEFAULT_STARTUP_WARMUP_SECONDS, 'startup warmup' )
def is_weather_cache_enabled(self) -> bool:
"""Check if weather data caching is enabled."""
- value = self.settings_manager().get_setting_value(WeatherSetting.WEATHER_CACHE_ENABLED)
+ return self._get_weather_cache_enabled_value(self.settings_manager())
+
+ def _get_weather_cache_enabled_value(self, settings_manager):
+ value = settings_manager.get_setting_value(WeatherSetting.WEATHER_CACHE_ENABLED)
if value is None:
return True
- # Handle string boolean values from database
if isinstance(value, str):
return value.lower() in ('true', '1', 'yes', 'on')
return bool(value)
-
+
+ async def is_weather_cache_enabled_async(self) -> bool:
+ settings_manager = await self.settings_manager_async()
+ if not settings_manager:
+ return True
+ return self._get_weather_cache_enabled_value(settings_manager)
+
def _get_weather_alerts_enabled_value(self, settings_manager):
"""Private helper to get weather alerts enabled value with any settings manager."""
value = settings_manager.get_setting_value(WeatherSetting.WEATHER_ALERTS_ENABLED)
@@ -109,7 +171,7 @@ class WeatherSettingsHelper( SettingsMixin ):
return {
'enabled': self.is_weather_source_enabled(source_id),
'api_key': self.get_weather_source_api_key(source_id),
- 'polling_interval_minutes': self.get_default_polling_interval_minutes(),
+ 'polling_interval_secs': self.get_default_polling_interval_secs(),
'cache_enabled': self.is_weather_cache_enabled(),
}
diff --git a/src/hi/apps/weather/weather_sources/nws.py b/src/hi/apps/weather/weather_sources/nws.py
index 67b00bcc..4896da48 100644
--- a/src/hi/apps/weather/weather_sources/nws.py
+++ b/src/hi/apps/weather/weather_sources/nws.py
@@ -1,11 +1,8 @@
from datetime import datetime
import json
import logging
-import requests
from typing import Any, Dict, List
-from django.conf import settings
-
import hi.apps.common.datetimeproxy as datetimeproxy
import hi.apps.common.geo_utils as geo_utils
from hi.apps.common.utils import str_to_bool
@@ -52,8 +49,6 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
OBSERVATIONS_DATA_CACHE_EXPIRY_SECS = 5 * 60 # Cache for rate-limit risk reduction
FORECAST_DATA_CACHE_EXPIRY_SECS = 60 * 60
ALERTS_DATA_CACHE_EXPIRY_SECS = 10 * 60 # Alerts can change frequently, short cache
-
- SKIP_CACHE = False # For debugging
@classmethod
def weather_source_id(cls):
@@ -112,7 +107,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
weather_conditions_data = current_conditions_data,
)
except Exception as e:
- logger.exception( f'Problem fetching NWS current conditions: {e}' )
+ self._log_fetch_error( 'current conditions', e )
# Fetch hourly forecast data
try:
@@ -125,7 +120,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
forecast_data_list = interval_hourly_forecast_list,
)
except Exception as e:
- logger.exception( f'Problem fetching NWS hourly forecast: {e}' )
+ self._log_fetch_error( 'hourly forecast', e )
# Fetch 12-hour forecast data (used for daily forecast)
try:
@@ -138,20 +133,22 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
forecast_data_list = interval_daily_forecast_list,
)
except Exception as e:
- logger.exception( f'Problem fetching NWS daily forecast: {e}' )
+ self._log_fetch_error( 'daily forecast', e )
- # Fetch weather alerts
+ # Fetch weather alerts. Always push the result — even an empty
+ # list — so removed-upstream alerts clear from our stored list.
+ # NWS /alerts/active is contractually the full set of active
+ # alerts, so wholesale replacement is correct.
try:
weather_alerts = self.get_weather_alerts(
geographic_location = geographic_location,
)
- if weather_alerts:
- await weather_manager.update_weather_alerts(
- data_point_source = self.data_point_source,
- weather_alerts = weather_alerts,
- )
+ await weather_manager.update_weather_alerts(
+ data_point_source = self.data_point_source,
+ weather_alerts = weather_alerts,
+ )
except Exception as e:
- logger.exception( f'Problem fetching NWS weather alerts: {e}' )
+ self._log_fetch_error( 'weather alerts', e )
# Note: NWS does not provide historical weather data or astronomical data
# These would need to be fetched from other sources if needed
@@ -492,8 +489,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
cache_key = f'ws:{self.id}:observations:{station.key}'
observations_data_str = self.redis_client.get( cache_key )
- if settings.DEBUG and self.SKIP_CACHE:
- logger.warning( 'Skip caching in effect.' )
+ if not self.is_cache_enabled:
observations_data_str = None
if observations_data_str:
@@ -511,23 +507,17 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
return observations_data
def _get_observations_data_from_api( self, station : Station ) -> Dict[ str, Any ]:
- with self.api_call_context( 'nws_observations' ):
- observations_response = requests.get(
- station.observations_url,
- headers = self._headers,
- timeout = self.get_api_timeout(),
- )
-
- observations_response.raise_for_status()
- observations_data = observations_response.json()
- return observations_data
+ return self._api_get_json(
+ operation_name = 'nws_observations',
+ url = station.observations_url,
+ headers = self._headers,
+ )
def _get_forecast_hourly_data( self, station : Station ) -> Dict[ str, Any ]:
cache_key = f'ws:{self.id}:forecast-hourly:{station.key}'
forecast_hourly_data_str = self.redis_client.get( cache_key )
- if settings.DEBUG and self.SKIP_CACHE:
- logger.warning( 'Skip caching in effect.' )
+ if not self.is_cache_enabled:
forecast_hourly_data_str = None
if forecast_hourly_data_str:
@@ -545,22 +535,17 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
return forecast_hourly_data
def _get_forecast_hourly_data_from_api( self, station : Station ) -> Dict[ str, Any ]:
- with self.api_call_context( 'nws_forecast_hourly' ):
- forecast_hourly_response = requests.get(
- station.forecast_url,
- headers = self._headers,
- timeout = self.get_api_timeout(),
- )
- forecast_hourly_response.raise_for_status()
- forecast_hourly_data = forecast_hourly_response.json()
- return forecast_hourly_data
+ return self._api_get_json(
+ operation_name = 'nws_forecast_hourly',
+ url = station.forecast_url,
+ headers = self._headers,
+ )
def _get_forecast_12h_data( self, station : Station ) -> Dict[ str, Any ]:
cache_key = f'ws:{self.id}:forecast-12h:{station.key}'
forecast_12h_data_str = self.redis_client.get( cache_key )
- if settings.DEBUG and self.SKIP_CACHE:
- logger.warning( 'Skip caching in effect.' )
+ if not self.is_cache_enabled:
forecast_12h_data_str = None
if forecast_12h_data_str:
@@ -578,15 +563,11 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
return forecast_12h_data
def _get_forecast_12h_data_from_api( self, station : Station ) -> Dict[ str, Any ]:
- with self.api_call_context( 'nws_forecast' ):
- forecast_12h_response = requests.get(
- station.forecast_url,
- headers = self._headers,
- timeout = self.get_api_timeout(),
- )
- forecast_12h_response.raise_for_status()
- forecast_12h_data = forecast_12h_response.json()
- return forecast_12h_data
+ return self._api_get_json(
+ operation_name = 'nws_forecast',
+ url = station.forecast_url,
+ headers = self._headers,
+ )
def _get_station( self, geographic_location : GeographicLocation ) -> Station:
stations_data = self._get_stations_data( geographic_location = geographic_location )
@@ -599,8 +580,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
cache_key = f'ws:{self.id}:stations:{geographic_location}'
stations_data_str = self.redis_client.get( cache_key )
- if settings.DEBUG and self.SKIP_CACHE:
- logger.warning( 'Skip caching in effect.' )
+ if not self.is_cache_enabled:
stations_data_str = None
if stations_data_str:
@@ -622,22 +602,17 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
points_data = self._get_points_data( geographic_location = geographic_location )
stations_url = points_data['properties']['observationStations']
- with self.api_call_context( 'nws_stations' ):
- stations_response = requests.get(
- stations_url,
- headers = self._headers,
- timeout = self.get_api_timeout(),
- )
- stations_response.raise_for_status()
- stations_data = stations_response.json()
- return stations_data
+ return self._api_get_json(
+ operation_name = 'nws_stations',
+ url = stations_url,
+ headers = self._headers,
+ )
def _get_points_data( self, geographic_location : GeographicLocation ) -> Dict[ str, Any ]:
cache_key = f'ws:{self.id}:points:{geographic_location}'
points_data_str = self.redis_client.get( cache_key )
- if settings.DEBUG and self.SKIP_CACHE:
- logger.warning( 'Skip caching in effect.' )
+ if not self.is_cache_enabled:
points_data_str = None
if points_data_str:
@@ -656,17 +631,13 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
def _get_points_data_from_api( self, geographic_location : GeographicLocation ) -> Dict[ str, Any ]:
# Can cache this data, expires 12 hours-ish (they do not change often)
- points_url = f'{self.BASE_URL}points/{geographic_location.latitude},{geographic_location.longitude}'
+ points_url = f'{self._get_base_url()}points/{geographic_location.latitude},{geographic_location.longitude}'
- with self.api_call_context( 'nws_points' ):
- points_response = requests.get(
- points_url,
- headers = self._headers,
- timeout = self.get_api_timeout(),
- )
- points_response.raise_for_status()
- points_data = points_response.json()
- return points_data
+ return self._api_get_json(
+ operation_name = 'nws_points',
+ url = points_url,
+ headers = self._headers,
+ )
def _get_closest_station( self,
geographic_location : GeographicLocation,
@@ -1058,8 +1029,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
cache_key = f'ws:{self.id}:alerts:{geographic_location.latitude:.3f}:{geographic_location.longitude:.3f}'
alerts_data_str = self.redis_client.get(cache_key)
- if settings.DEBUG and self.SKIP_CACHE:
- logger.warning('Skip caching in effect.')
+ if not self.is_cache_enabled:
alerts_data_str = None
if alerts_data_str:
@@ -1080,18 +1050,14 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
def _get_alerts_data_from_api( self, geographic_location : GeographicLocation ) -> Dict[str, Any]:
"""Make API call to NWS for alerts data."""
- alerts_url = f'{self.BASE_URL}alerts/active?point={geographic_location.latitude},{geographic_location.longitude}'
+ alerts_url = f'{self._get_base_url()}alerts/active?point={geographic_location.latitude},{geographic_location.longitude}'
logger.debug(f'NWS alerts API request: {alerts_url}')
- with self.api_call_context( 'nws_alerts' ):
- response = requests.get(
- alerts_url,
- headers=self._headers,
- timeout = self.get_api_timeout(),
- )
- response.raise_for_status()
- alerts_data = response.json()
- return alerts_data
+ return self._api_get_json(
+ operation_name = 'nws_alerts',
+ url = alerts_url,
+ headers = self._headers,
+ )
def _parse_alerts_data( self,
alerts_data : Dict[str, Any],
@@ -1109,7 +1075,14 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
properties = feature.get('properties', {})
if not properties:
continue
-
+
+ # NWS publishes a stable per-alert id at the feature
+ # level (typically a URI). Threading it onto the
+ # parsed WeatherAlert lets the alarm mapper use it as
+ # source_alarm_id to dedup repeat polls of the same
+ # active alert.
+ alert_id = feature.get('id')
+
# Extract basic alert information
event = properties.get('event', 'Unknown Event')
headline = properties.get('headline', '')
@@ -1194,6 +1167,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
severity = severity,
certainty = certainty,
urgency = urgency,
+ alert_id = alert_id,
)
weather_alerts.append(weather_alert)
diff --git a/src/hi/apps/weather/weather_sources/nws_converters.py b/src/hi/apps/weather/weather_sources/nws_converters.py
index 0f3dce14..d9c54e47 100644
--- a/src/hi/apps/weather/weather_sources/nws_converters.py
+++ b/src/hi/apps/weather/weather_sources/nws_converters.py
@@ -32,6 +32,7 @@ class NwsConverters:
'severe' : AlertSeverity.SEVERE,
'moderate' : AlertSeverity.MODERATE,
'minor' : AlertSeverity.MINOR,
+ 'unknown' : AlertSeverity.UNKNOWN,
}
NwsAlertUrgencyMp = {
'immediate' : AlertUrgency.IMMEDIATE,
@@ -44,6 +45,7 @@ class NwsConverters:
'likely' : AlertCertainty.LIKELY,
'possible' : AlertCertainty.POSSIBLE,
'unlikely' : AlertCertainty.UNLIKELY,
+ 'unknown' : AlertCertainty.UNKNOWN,
}
NwsAlertStatusMap = {
'actual' : AlertStatus.ACTUAL,
diff --git a/src/hi/apps/weather/weather_sources/openmeteo.py b/src/hi/apps/weather/weather_sources/openmeteo.py
index 09deb4bb..e8f8af7a 100644
--- a/src/hi/apps/weather/weather_sources/openmeteo.py
+++ b/src/hi/apps/weather/weather_sources/openmeteo.py
@@ -1,10 +1,8 @@
from datetime import date, datetime, timedelta
import json
import logging
-import requests
from typing import Any, Dict, List
-from django.conf import settings
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.weather.weather_data_source import WeatherDataSource
@@ -39,7 +37,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
FORECAST_DATA_CACHE_EXPIRY_SECS = 60 * 60 # Cache for 1 hour
HISTORICAL_DATA_CACHE_EXPIRY_SECS = 30 * 24 * 60 * 60 # 30 days - historical data rarely changes
- SKIP_CACHE = False # For debugging
@classmethod
def weather_source_id(cls):
@@ -100,7 +97,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
)
except Exception as e:
self.record_error( 'Current conditions fetch error: {e}' )
- logger.exception(f'Problem fetching OpenMeteo current conditions: {e}')
+ self._log_fetch_error( 'current conditions', e )
# Fetch hourly forecast data
try:
@@ -114,7 +111,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
)
except Exception as e:
self.record_error( 'Hourly forecast fetch error: {e}' )
- logger.exception(f'Problem fetching OpenMeteo hourly forecast: {e}')
+ self._log_fetch_error( 'hourly forecast', e )
# Fetch daily forecast data
try:
@@ -128,7 +125,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
)
except Exception as e:
self.record_error( 'Daily forecast fetch error: {e}' )
- logger.exception(f'Problem fetching OpenMeteo daily forecast: {e}')
+ self._log_fetch_error( 'daily forecast', e )
# Fetch historical weather data (last 7 days)
try:
@@ -146,7 +143,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
logger.warning('OpenMeteo returned no historical weather data')
except Exception as e:
self.record_error( 'Historical data fetch error: {e}' )
- logger.exception(f'Problem fetching OpenMeteo historical data: {e}')
+ self._log_fetch_error( 'historical data', e )
# Note: OpenMeteo does not provide astronomical data
# This would need to be fetched from other sources if needed
@@ -726,8 +723,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
cache_key = f'ws:{self.id}:current:{geographic_location}'
current_data_str = self.redis_client.get(cache_key)
- if settings.DEBUG and self.SKIP_CACHE:
- logger.warning('Skip caching in effect.')
+ if not self.is_cache_enabled:
current_data_str = None
if current_data_str:
@@ -746,29 +742,24 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
def _get_current_weather_data_from_api(self, geographic_location: GeographicLocation) -> Dict[str, Any]:
# Request current weather plus additional hourly data for current hour
- url = (f"{self.BASE_URL}forecast?"
+ url = (f"{self._get_base_url()}forecast?"
f"latitude={geographic_location.latitude}&"
f"longitude={geographic_location.longitude}&"
f"current_weather=true&"
f"hourly=temperature_2m,relativehumidity_2m,dewpoint_2m,precipitation,pressure_msl&"
f"units=metric")
- with self.api_call_context( 'openmeteo_current' ):
- response = requests.get(
- url,
- headers = self._headers,
- timeout = self.get_api_timeout(),
- )
- response.raise_for_status()
- current_data = response.json()
- return current_data
+ return self._api_get_json(
+ operation_name = 'openmeteo_current',
+ url = url,
+ headers = self._headers,
+ )
def _get_hourly_forecast_data(self, geographic_location: GeographicLocation) -> Dict[str, Any]:
cache_key = f'ws:{self.id}:forecast-hourly:{geographic_location}'
forecast_data_str = self.redis_client.get(cache_key)
- if settings.DEBUG and self.SKIP_CACHE:
- logger.warning('Skip caching in effect.')
+ if not self.is_cache_enabled:
forecast_data_str = None
if forecast_data_str:
@@ -787,29 +778,24 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
def _get_hourly_forecast_data_from_api(self, geographic_location: GeographicLocation) -> Dict[str, Any]:
# Request 7 days of hourly forecast data
- url = (f"{self.BASE_URL}forecast?"
+ url = (f"{self._get_base_url()}forecast?"
f"latitude={geographic_location.latitude}&"
f"longitude={geographic_location.longitude}&"
f"hourly=temperature_2m,relativehumidity_2m,windspeed_10m,winddirection_10m,precipitation,weathercode&"
f"forecast_days=7&"
f"units=metric")
- with self.api_call_context( 'openmeteo_forecast_hourly' ):
- response = requests.get(
- url,
- headers = self._headers,
- timeout = self.get_api_timeout(),
- )
- response.raise_for_status()
- forecast_data = response.json()
- return forecast_data
+ return self._api_get_json(
+ operation_name = 'openmeteo_forecast_hourly',
+ url = url,
+ headers = self._headers,
+ )
def _get_daily_forecast_data(self, geographic_location: GeographicLocation) -> Dict[str, Any]:
cache_key = f'ws:{self.id}:forecast-daily:{geographic_location}'
forecast_data_str = self.redis_client.get(cache_key)
- if settings.DEBUG and self.SKIP_CACHE:
- logger.warning('Skip caching in effect.')
+ if not self.is_cache_enabled:
forecast_data_str = None
if forecast_data_str:
@@ -828,22 +814,18 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
def _get_daily_forecast_data_from_api(self, geographic_location: GeographicLocation) -> Dict[str, Any]:
# Request 14 days of daily forecast data
- url = (f"{self.BASE_URL}forecast?"
+ url = (f"{self._get_base_url()}forecast?"
f"latitude={geographic_location.latitude}&"
f"longitude={geographic_location.longitude}&"
f"daily=weathercode,temperature_2m_max,temperature_2m_min,precipitation_sum&"
f"forecast_days=14&"
f"units=metric")
- with self.api_call_context( 'openmeteo_forecast_daily' ):
- response = requests.get(
- url,
- headers = self._headers,
- timeout = self.get_api_timeout(),
- )
- response.raise_for_status()
- forecast_data = response.json()
- return forecast_data
+ return self._api_get_json(
+ operation_name = 'openmeteo_forecast_daily',
+ url = url,
+ headers = self._headers,
+ )
def _get_historical_weather_data( self,
geographic_location : GeographicLocation,
@@ -852,8 +834,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
cache_key = f'ws:{self.id}:historical:{geographic_location}:{start_date}:{end_date}'
historical_data_str = self.redis_client.get(cache_key)
- if settings.DEBUG and self.SKIP_CACHE:
- logger.warning('Skip caching in effect.')
+ if not self.is_cache_enabled:
historical_data_str = None
if historical_data_str:
@@ -887,12 +868,8 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
f"daily=weathercode,temperature_2m_max,temperature_2m_min,precipitation_sum&"
f"units=metric")
- with self.api_call_context( 'openmeteo_history' ):
- response = requests.get(
- url,
- headers = self._headers,
- timeout = self.get_api_timeout(),
- )
- response.raise_for_status()
- historical_data = response.json()
- return historical_data
+ return self._api_get_json(
+ operation_name = 'openmeteo_history',
+ url = url,
+ headers = self._headers,
+ )
diff --git a/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py b/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py
index 7aa4451e..3bed2800 100644
--- a/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py
+++ b/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py
@@ -3,10 +3,8 @@ from enum import Enum
import json
import logging
import pytz
-import requests
from typing import Any, Dict, List
-from django.conf import settings
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.weather.weather_data_source import WeatherDataSource
@@ -40,7 +38,6 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):
# Cache for 25 hours - astronomical data only changes once per day per location
ASTRONOMICAL_DATA_CACHE_EXPIRY_SECS = 25 * 60 * 60
- SKIP_CACHE = False # For debugging
@classmethod
def weather_source_id(cls):
@@ -102,7 +99,7 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):
)
except Exception as e:
self.record_error( 'Multi-data astronomical fetch error: {e}' )
- logger.exception(f'Problem fetching Sunrise-Sunset.org multi-day astronomical data: {e}')
+ self._log_fetch_error( 'multi-day astronomical data', e )
# Also update today's astronomical data for backwards compatibility
try:
@@ -116,7 +113,7 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):
)
except Exception as e:
self.record_error( 'Today\'s atronomical fetch error: {e}' )
- logger.exception(f'Problem fetching Sunrise-Sunset.org today\'s astronomical data: {e}')
+ self._log_fetch_error( "today's astronomical data", e )
return
@@ -253,8 +250,7 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):
cache_key = f'ws:{self.id}:astronomical:{geographic_location.latitude:.3f}:{geographic_location.longitude:.3f}:{target_date}'
api_data_str = self.redis_client.get(cache_key)
- if settings.DEBUG and self.SKIP_CACHE:
- logger.warning('Skip caching in effect.')
+ if not self.is_cache_enabled:
api_data_str = None
if api_data_str:
@@ -278,18 +274,14 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):
geographic_location : GeographicLocation,
target_date : date) -> Dict[str, Any]:
# Build API URL with parameters
- url = (f"{self.BASE_URL}?"
+ url = (f"{self._get_base_url()}?"
f"lat={geographic_location.latitude}&"
f"lng={geographic_location.longitude}&"
f"date={target_date.isoformat()}&"
f"formatted=0") # Get ISO format times
- with self.api_call_context( 'sunrise_sunset' ):
- response = requests.get(
- url,
- headers = self._headers,
- timeout = self.get_api_timeout(),
- )
- response.raise_for_status()
- api_data = response.json()
- return api_data
+ return self._api_get_json(
+ operation_name = 'sunrise_sunset',
+ url = url,
+ headers = self._headers,
+ )
diff --git a/src/hi/apps/weather/weather_sources/usno.py b/src/hi/apps/weather/weather_sources/usno.py
index 859313e9..42f80c9e 100644
--- a/src/hi/apps/weather/weather_sources/usno.py
+++ b/src/hi/apps/weather/weather_sources/usno.py
@@ -3,10 +3,8 @@ from enum import Enum
import json
import logging
import pytz
-import requests
from typing import Any, Dict, List
-from django.conf import settings
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.weather.weather_data_source import WeatherDataSource
@@ -49,7 +47,6 @@ class USNO( WeatherDataSource, WeatherMixin ):
# Cache for 25 hours - astronomical data only changes once per day per location
ASTRONOMICAL_DATA_CACHE_EXPIRY_SECS = 25 * 60 * 60
- SKIP_CACHE = False # For debugging
@classmethod
def weather_source_id(cls):
@@ -111,7 +108,7 @@ class USNO( WeatherDataSource, WeatherMixin ):
)
except Exception as e:
self.record_error( 'Multi-data astronomical fetch error: {e}' )
- logger.exception(f'Problem fetching USNO multi-day astronomical data: {e}')
+ self._log_fetch_error( 'multi-day astronomical data', e )
# Also update today's astronomical data for backwards compatibility
try:
@@ -125,7 +122,7 @@ class USNO( WeatherDataSource, WeatherMixin ):
)
except Exception as e:
self.record_error( 'Today\'s astronomical fetch error: {e}' )
- logger.exception(f'Problem fetching USNO today\'s astronomical data: {e}')
+ self._log_fetch_error( "today's astronomical data", e )
return
@@ -358,8 +355,7 @@ class USNO( WeatherDataSource, WeatherMixin ):
cache_key = f'ws:{self.id}:astronomical:{geographic_location.latitude:.3f}:{geographic_location.longitude:.3f}:{target_date}'
api_data_str = self.redis_client.get(cache_key)
- if settings.DEBUG and self.SKIP_CACHE:
- logger.warning('Skip caching in effect.')
+ if not self.is_cache_enabled:
api_data_str = None
if api_data_str:
@@ -391,19 +387,15 @@ class USNO( WeatherDataSource, WeatherMixin ):
tz_offset = offset_seconds / 3600 # Convert to hours
# Build API URL with parameters
- url = (f"{self.BASE_URL}?"
+ url = (f"{self._get_base_url()}?"
f"date={target_date.isoformat()}&"
f"coords={geographic_location.latitude},{geographic_location.longitude}&"
f"tz={tz_offset}")
logger.debug(f'USNO API request: {url}')
- with self.api_call_context( 'usno' ):
- response = requests.get(
- url,
- headers = self._headers,
- timeout = self.get_api_timeout(),
- )
- response.raise_for_status()
- api_data = response.json()
- return api_data
+ return self._api_get_json(
+ operation_name = 'usno',
+ url = url,
+ headers = self._headers,
+ )
diff --git a/src/hi/constants.py b/src/hi/constants.py
index 80a104b1..a97e9086 100644
--- a/src/hi/constants.py
+++ b/src/hi/constants.py
@@ -53,12 +53,11 @@ DIVID = {
'ATTRIBUTE_CONTAINER_CLASS': 'hi-attribute',
- 'DATETIME_HEADER': 'hi-datetime-header',
+ 'SIDEBAR_NOTICE': 'hi-sidebar-notice',
'ALERT_BANNER_CONTAINER': 'hi-alert-banner-container',
'ALERT_BANNER_CONTENT': 'hi-alert-banner-content',
'SECURITY_STATE_CONTROL': 'hi-security-state-control',
'WEATHER_OVERVIEW': 'hi-weather-overview',
- 'WEATHER_ALERTS': 'hi-weather-alerts',
'CONSOLE_LOCK_BUTTON': 'hi-console-lock-button',
diff --git a/src/hi/hi_styles.py b/src/hi/hi_styles.py
index 2a119456..bde8e49a 100644
--- a/src/hi/hi_styles.py
+++ b/src/hi/hi_styles.py
@@ -1,9 +1,26 @@
+from enum import Enum
+
from hi.apps.common.svg_models import SvgRadius, SvgStatusStyle, SvgViewBox
from hi.apps.collection.enums import CollectionType
from hi.apps.entity.enums import EntityType
+class EntityIconDirection(Enum):
+ """Direction an entity's source icon SVG was authored to point.
+ Independent of any runtime rotation the user applies to a placed
+ entity. Values for the cardinal directions are (dx, dy) unit
+ vectors in SVG coordinates (+x = right, +y = down). ``UNKNOWN``
+ is a sentinel returned by ``EntityStyle.get_icon_direction`` when
+ the entity type has no mapped direction; callers choose their own
+ default behavior."""
+ UNKNOWN = None
+ POINTS_RIGHT = (1.0, 0.0)
+ POINTS_DOWN = (0.0, 1.0)
+ POINTS_LEFT = (-1.0, 0.0)
+ POINTS_UP = (0.0, -1.0)
+
+
class ItemStyle:
@classmethod
@@ -421,12 +438,85 @@ class EntityStyle:
EntityType.WINDOW: Window,
}
+ # Per-EntityType initial-placement size factor. Opt-in: only entity
+ # types whose intended layout size deviates from the default (1.0)
+ # need entries here. The factor multiplies the base placement size
+ # in PositionGeometry.default_icon_scale.
+ #
+ # This is layout-driven, not realism-driven — the goal is fitting
+ # many items in a view with touch-friendly sizing and reducing
+ # post-placement resizing labor. Smaller-than-default types are
+ # ones a user is likely to place many of in a single view; larger-
+ # than-default types are ones that anchor a view's visual layout.
+ # Primary control surfaces (lights, switches) stay at the default
+ # since they are interactive targets the user will exercise.
+ EntityTypeToIconSizeFactor = {
+ # Smaller (high-count or modest-importance items)
+ EntityType.BAROMETER: 0.7,
+ EntityType.CARBON_MONOXIDE_DETECTOR: 0.7,
+ EntityType.CONSUMABLE: 0.7,
+ EntityType.DOORBELL: 0.7,
+ EntityType.DOOR_LOCK: 0.7,
+ EntityType.ELECTRICAL_OUTLET: 0.7,
+ EntityType.FIRE_EXTINGUISHER: 0.7,
+ EntityType.GARBAGE_DISPOSAL: 0.7,
+ EntityType.GAS_DETECTOR: 0.7,
+ EntityType.HYGROMETER: 0.7,
+ EntityType.LEAK_SENSOR: 0.7,
+ EntityType.LIGHT_SENSOR: 0.7,
+ EntityType.MOTION_SENSOR: 0.7,
+ EntityType.OPEN_CLOSE_SENSOR: 0.7,
+ EntityType.PRESENCE_SENSOR: 0.7,
+ EntityType.RADON_DETECTOR: 0.7,
+ EntityType.SMOKE_DETECTOR: 0.7,
+ EntityType.SPEAKER: 0.7,
+ EntityType.SPRINKLER_HEAD: 0.7,
+ EntityType.THERMOMETER: 0.7,
+ EntityType.WATER_SHUTOFF_VALVE: 0.7,
+
+ # Larger (room-anchoring single items)
+ EntityType.BATHTUB: 1.5,
+ EntityType.FIREPLACE: 1.5,
+ EntityType.HVAC_AIR_HANDLER: 1.5,
+ EntityType.HVAC_CONDENSER: 1.5,
+ EntityType.HVAC_FURNACE: 1.5,
+ EntityType.REFRIGERATOR: 1.5,
+ EntityType.TREE: 1.5,
+
+ # Very large
+ EntityType.AUTOMOBILE: 2.0,
+ }
+
@classmethod
def get_svg_icon_viewbox( cls, entity_type : EntityType ) -> SvgViewBox:
if entity_type in cls.EntityTypeToIconViewbox:
return cls.EntityTypeToIconViewbox.get( entity_type )
return ItemStyle.get_default_svg_icon_viewbox()
-
+
+ @classmethod
+ def get_icon_size_factor( cls, entity_type : EntityType ) -> float:
+ return cls.EntityTypeToIconSizeFactor.get( entity_type, 1.0 )
+
+ # Per-EntityType source-icon facing direction. Used at placement
+ # time to give the auto-created Area delegate a triangular path
+ # (apex near the principal, base extending along the icon's facing
+ # direction) instead of the generic rectangle, so the delegate
+ # visually reads as a coverage cone for the principal.
+ #
+ # Opt-in: entity types without an entry get no triangle treatment;
+ # the delegate stays as the default rectangle.
+ EntityTypeToIconDirection = {
+ EntityType.CAMERA: EntityIconDirection.POINTS_RIGHT,
+ EntityType.MOTION_SENSOR: EntityIconDirection.POINTS_DOWN,
+ EntityType.PRESENCE_SENSOR: EntityIconDirection.POINTS_RIGHT,
+ }
+
+ @classmethod
+ def get_icon_direction( cls, entity_type : EntityType ) -> 'EntityIconDirection':
+ return cls.EntityTypeToIconDirection.get(
+ entity_type, EntityIconDirection.UNKNOWN,
+ )
+
@classmethod
def get_svg_icon_template_name( cls, entity_type : EntityType ) -> str:
if entity_type in cls.EntityTypesWithIcons:
diff --git a/src/hi/integrations/sync_check.py b/src/hi/integrations/sync_check.py
index 47265b20..6ea90173 100644
--- a/src/hi/integrations/sync_check.py
+++ b/src/hi/integrations/sync_check.py
@@ -262,7 +262,7 @@ class IntegrationSyncCheck:
alarm_lifetime_secs = Alarm.MAX_LIFETIME_SECS,
timestamp = datetimeproxy.now(),
)
- AlertManager().add_alarm( alarm )
+ AlertManager().upsert_alarm( alarm )
@classmethod
def clear_state( cls, integration_id : str ) -> None:
diff --git a/src/hi/integrations/tests/test_sync_check.py b/src/hi/integrations/tests/test_sync_check.py
index ae7becd1..bfffdf02 100644
--- a/src/hi/integrations/tests/test_sync_check.py
+++ b/src/hi/integrations/tests/test_sync_check.py
@@ -415,7 +415,7 @@ class TransitionAlarmTests(TestCase):
with patch(
'hi.apps.alert.alert_manager.AlertManager',
) as mock_manager_class:
- mock_manager_class.return_value.add_alarm = capture
+ mock_manager_class.return_value.upsert_alarm = capture
IntegrationSyncCheck._fire_needs_sync_alarm(
integration_id=self.INTEGRATION_ID,
result=self._result(needs_sync=True),
diff --git a/src/hi/requirements/base.txt b/src/hi/requirements/base.txt
index 55b5e9b3..fa0f526a 100644
--- a/src/hi/requirements/base.txt
+++ b/src/hi/requirements/base.txt
@@ -10,7 +10,7 @@ django-csp==4.0
django-pipeline==4.1.0
frozenlist==1.4.1
gunicorn==23.0.0
-idna==3.10
+idna==3.15
multidict==6.0.5
numpy==2.1.0
pdf2image==1.17.0
diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.py
index 62521c6c..80a0c043 100644
--- a/src/hi/services/hass/hass_converter.py
+++ b/src/hi/services/hass/hass_converter.py
@@ -179,12 +179,14 @@ class HassConverter:
# All controllable domains
ALL_CONTROLLABLE_DOMAINS = ON_OFF_CONTROLLABLE_DOMAINS | COMPLEX_CONTROLLABLE_DOMAINS
- # Domains for sensor-only devices (read-only)
+ # Domains for sensor-only devices (read-only). The camera domain
+ # is intentionally NOT here despite its primary state being
+ # read-only: its ``motion_detection`` substate is controllable, so
+ # the domain as a whole is not purely sensor-only.
#
SENSOR_ONLY_DOMAINS = {
HassApi.BINARY_SENSOR_DOMAIN,
HassApi.SENSOR_DOMAIN,
- HassApi.CAMERA_DOMAIN,
HassApi.SUN_DOMAIN,
HassApi.WEATHER_DOMAIN,
}
@@ -363,8 +365,23 @@ class HassConverter:
HassApi.VOLUME_LEVEL_PARAM: 'percentage_decimal', # 0.0-1.0
},
},
+
+ # Camera Domain Services — the camera's own primary state is
+ # read-only (no entry in HASS_STATE_TO_ENTITY_STATE_TYPE_MAPPING
+ # for the CAMERA_DOMAIN); the only controllable surface is the
+ # ``motion_detection`` substate, dispatched via the ``substate``
+ # branch in ``_substate_service_call`` rather than the
+ # bare-key on/off path. The mapping below populates the
+ # substate controller's payload so the dispatch finds the
+ # right enable/disable services.
+ (HassApi.CAMERA_DOMAIN, EntityStateType.ON_OFF): {
+ 'on_service': HassApi.ENABLE_MOTION_DETECTION_SERVICE,
+ 'off_service': HassApi.DISABLE_MOTION_DETECTION_SERVICE,
+ 'parameters': {},
+ },
}
+
INSTEON_ADDRESS_ATTR_NAME = 'Insteon Address'
@classmethod
@@ -701,8 +718,15 @@ class HassConverter:
# multi-substate lights have no parent model.
model_with_entity_state = controller if controller else sensor
existing_entity_state_type = model_with_entity_state.entity_state.entity_state_type
- is_controllable = cls._is_controllable_domain_and_type(hass_state.domain, existing_entity_state_type)
- new_payload = cls._create_service_payload(hass_state, existing_entity_state_type, is_controllable)
+ is_controllable = cls._is_controllable_domain_and_type(
+ hass_state.domain,
+ existing_entity_state_type,
+ )
+ new_payload = cls._create_service_payload(
+ hass_state,
+ existing_entity_state_type,
+ is_controllable,
+ )
for model, model_type in [(sensor, 'sensor'), (controller, 'controller')]:
if model:
changed_fields = model.update_integration_payload(new_payload)
@@ -1158,6 +1182,8 @@ class HassConverter:
return cls._fan_state_specs( hass_state )
if hass_state.domain == HassApi.CLIMATE_DOMAIN:
return cls._climate_state_specs( hass_state )
+ if hass_state.domain == HassApi.CAMERA_DOMAIN:
+ return cls._camera_state_specs( hass_state )
return []
@classmethod
@@ -1427,6 +1453,41 @@ class HassConverter:
))
return specs
+ # HA's fixed set of camera state values. Listed here (rather than
+ # read from an attribute) because HA's camera spec declares the
+ # set itself, not the entity — same shape as ``_HVAC_ACTION_CHOICES``.
+ _CAMERA_STATE_VALUES = (
+ HassApi.CAMERA_STATE_IDLE,
+ HassApi.CAMERA_STATE_STREAMING,
+ HassApi.CAMERA_STATE_RECORDING,
+ )
+
+ @classmethod
+ def _camera_state_specs(
+ cls, hass_state : HassState ) -> List[ '_StateSpec' ]:
+ """Substates for a ``camera.x`` entity. A read-only ``state``
+ substate carries the primary mode (idle / streaming /
+ recording); when the entity reports ``motion_detection`` in
+ its attributes a controllable ON_OFF substate is exposed for
+ the HA enable/disable services."""
+ specs = [
+ cls._StateSpec(
+ suffix = HassApi.STATE_FIELD,
+ entity_state_type = EntityStateType.DISCRETE,
+ is_controllable = False,
+ value_range = { v: v for v in cls._CAMERA_STATE_VALUES },
+ label = 'Mode',
+ ),
+ ]
+ if HassApi.MOTION_DETECTION_ATTR in hass_state.attributes:
+ specs.append( cls._StateSpec(
+ suffix = HassApi.MOTION_DETECTION_ATTR,
+ entity_state_type = EntityStateType.ON_OFF,
+ is_controllable = True,
+ label = 'Motion Detection',
+ ))
+ return specs
+
@classmethod
def _setpoint_value_range( cls ) -> Dict[ str, float ]:
"""Slider bounds for thermostat setpoints, in HI's canonical
@@ -1457,6 +1518,8 @@ class HassConverter:
return cls._fan_substate_value( hass_state, spec.suffix )
if hass_state.domain == HassApi.CLIMATE_DOMAIN:
return cls._climate_substate_value( hass_state, spec )
+ if hass_state.domain == HassApi.CAMERA_DOMAIN:
+ return cls._camera_substate_value( hass_state, spec.suffix )
return None
@classmethod
@@ -1529,6 +1592,24 @@ class HassConverter:
return attrs.get( HassApi.PRESET_MODE_ATTR )
return None
+ @classmethod
+ def _camera_substate_value(
+ cls, hass_state : HassState, suffix : str ) -> Optional[ str ]:
+ """Camera-domain substate values. The ``state`` substate
+ passes HA's primary state field through (idle / streaming /
+ recording); ``motion_detection`` arrives as a JSON bool on the
+ camera entity's attributes (HA folds the enable-motion-detection
+ flag into its attributes rather than exposing it as a separate
+ entity)."""
+ if suffix == HassApi.STATE_FIELD:
+ return hass_state.state_value
+ if suffix == HassApi.MOTION_DETECTION_ATTR:
+ value = hass_state.attributes.get( HassApi.MOTION_DETECTION_ATTR )
+ if value is None:
+ return None
+ return str( EntityStateValue.ON ) if value else str( EntityStateValue.OFF )
+ return None
+
@classmethod
def _climate_substate_value(
cls, hass_state : HassState, spec : '_StateSpec' ) -> Optional[ str ]:
@@ -2277,6 +2358,8 @@ class HassConverter:
return cls._fan_to_sensor_value_map( hass_state )
if domain == HassApi.CLIMATE_DOMAIN:
return cls._climate_to_sensor_value_map( hass_state )
+ if domain == HassApi.CAMERA_DOMAIN:
+ return cls._camera_to_sensor_value_map( hass_state )
if domain == HassApi.SENSOR_DOMAIN:
return cls._sensor_domain_to_sensor_value_map( hass_state )
return cls._passthrough_to_sensor_value_map( hass_state )
@@ -2497,6 +2580,26 @@ class HassConverter:
return {}
return { cls.hass_state_to_integration_key( hass_state ) : str( percentage ) }
+ @classmethod
+ def _camera_to_sensor_value_map(
+ cls, hass_state : HassState ) -> Dict[ IntegrationKey, str ]:
+ """Camera domain: pure substate decomposition. The primary
+ ``state`` substate carries idle / streaming / recording; the
+ ``motion_detection`` substate carries the toggle when HA
+ reports the attribute."""
+ result : Dict[ IntegrationKey, str ] = {}
+ for spec in cls._state_specs_for_hass_state( hass_state ):
+ value = cls._extract_substate_value( hass_state, spec )
+ if value is None:
+ continue
+ substate_key = cls._substate_integration_key(
+ hass_state = hass_state,
+ suffix = spec.suffix,
+ )
+ result[ substate_key ] = value
+ continue
+ return result
+
@classmethod
def _climate_to_sensor_value_map(
cls, hass_state : HassState ) -> Dict[ IntegrationKey, str ]:
@@ -2835,6 +2938,14 @@ class HassConverter:
fan_mode = hi_control_value,
)
+ if substate == HassApi.MOTION_DETECTION_ATTR:
+ return HassServiceComposer.for_motion_detection(
+ domain = domain,
+ hass_substate_id = parent_entity_id,
+ enabled = ( cls.to_ha_on_off_intent( hi_control_value )
+ == ControlIntent.ON ),
+ )
+
raise ValueError( f'Unknown substate: {substate}' )
@classmethod
diff --git a/src/hi/services/hass/hass_models.py b/src/hi/services/hass/hass_models.py
index d3c727b2..b3c10e36 100644
--- a/src/hi/services/hass/hass_models.py
+++ b/src/hi/services/hass/hass_models.py
@@ -50,6 +50,8 @@ class HassApi:
SET_DIRECTION_SERVICE = 'set_direction'
SET_PRESET_MODE_SERVICE = 'set_preset_mode'
SET_FAN_MODE_SERVICE = 'set_fan_mode'
+ ENABLE_MOTION_DETECTION_SERVICE = 'enable_motion_detection'
+ DISABLE_MOTION_DETECTION_SERVICE = 'disable_motion_detection'
# Legacy aliases for backward compatibility (remove after migration)
AUTOMATION_ID_PREFIX = AUTOMATION_DOMAIN
@@ -175,6 +177,12 @@ class HassApi:
DIRECTION_ATTR = 'direction'
PRESET_MODE_ATTR = 'preset_mode'
PRESET_MODES_ATTR = 'preset_modes'
+
+ # Camera-domain attributes and state values.
+ MOTION_DETECTION_ATTR = 'motion_detection'
+ CAMERA_STATE_IDLE = 'idle'
+ CAMERA_STATE_STREAMING = 'streaming'
+ CAMERA_STATE_RECORDING = 'recording'
FAN_DIRECTION_FORWARD = 'forward'
FAN_DIRECTION_REVERSE = 'reverse'
diff --git a/src/hi/services/hass/hass_service_composer.py b/src/hi/services/hass/hass_service_composer.py
index 26f8bda5..3009a782 100644
--- a/src/hi/services/hass/hass_service_composer.py
+++ b/src/hi/services/hass/hass_service_composer.py
@@ -375,6 +375,27 @@ class HassServiceComposer:
service_data = { HassApi.OSCILLATING_ATTR: bool( oscillating ) },
)
+ @classmethod
+ def for_motion_detection(
+ cls,
+ domain : str,
+ hass_substate_id : str,
+ enabled : bool,
+ ) -> HassServiceCall:
+ """Camera ``motion_detection`` toggle. HA exposes two distinct
+ services (``enable_motion_detection`` / ``disable_motion_detection``)
+ rather than a single parametric one — same pattern as
+ ``lock`` / ``unlock`` and ``open_cover`` / ``close_cover``."""
+ service = (
+ HassApi.ENABLE_MOTION_DETECTION_SERVICE if enabled
+ else HassApi.DISABLE_MOTION_DETECTION_SERVICE
+ )
+ return HassServiceCall(
+ domain = domain,
+ service = service,
+ hass_entity_id = hass_substate_id,
+ )
+
@classmethod
def for_direction(
cls,
diff --git a/src/hi/services/hass/tests/test_hass_converter_mapping.py b/src/hi/services/hass/tests/test_hass_converter_mapping.py
index a8423a8c..98d898e7 100644
--- a/src/hi/services/hass/tests/test_hass_converter_mapping.py
+++ b/src/hi/services/hass/tests/test_hass_converter_mapping.py
@@ -283,7 +283,7 @@ class TestHassConverterMapping(TestCase):
# Test that sensor-only domains are never controllable
for domain in HassConverter.SENSOR_ONLY_DOMAINS:
# Test with various entity types
- for entity_type in [EntityStateType.ON_OFF, EntityStateType.TEMPERATURE,
+ for entity_type in [EntityStateType.ON_OFF, EntityStateType.TEMPERATURE,
EntityStateType.BLOB, EntityStateType.MOVEMENT]:
is_controllable = HassConverter._is_controllable_domain_and_type(domain, entity_type)
self.assertFalse(is_controllable,
diff --git a/src/hi/settings/simulator.py b/src/hi/settings/simulator.py
index fe4ec700..aff43d69 100644
--- a/src/hi/settings/simulator.py
+++ b/src/hi/settings/simulator.py
@@ -14,9 +14,14 @@ INSTALLED_APPS = [
'custom',
'hi.apps.common',
'hi.simulator',
+ 'hi.simulator.profile',
+ 'hi.simulator.services',
+ 'hi.simulator.weather_sources',
+ 'hi.simulator.settings',
'hi.simulator.services.hass',
'hi.simulator.services.homebox',
'hi.simulator.services.zoneminder',
+ 'hi.simulator.weather_sources.nws',
]
MIDDLEWARE = [
@@ -29,8 +34,7 @@ MIDDLEWARE = [
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
- 'hi.simulator.middleware.SimViewMiddleware',
- 'hi.simulator.middleware.SimulatorFaultInjectionMiddleware',
+ 'hi.simulator.services.middleware.ServiceFaultInjectionMiddleware',
]
ROOT_URLCONF = 'hi.simulator.urls'
diff --git a/src/hi/simulator/admin.py b/src/hi/simulator/admin.py
deleted file mode 100644
index 12c5153f..00000000
--- a/src/hi/simulator/admin.py
+++ /dev/null
@@ -1,38 +0,0 @@
-from django.contrib import admin
-
-from . import models
-
-
[email protected](models.DbSimEntity)
-class DbSimEntityAdmin(admin.ModelAdmin):
-
- show_full_result_count = False
-
- list_display = (
- 'sim_profile',
- 'simulator_id',
- 'entity_fields_class_id',
- 'sim_entity_type_str',
- 'sim_entity_fields_json',
- 'updated_datetime',
- 'created_datetime',
- )
-
- search_fields = ['entity_fields_class_id']
- readonly_fields = ( 'updated_datetime', 'created_datetime', )
-
-
[email protected](models.SimProfile)
-class SimProfileAdmin(admin.ModelAdmin):
-
- show_full_result_count = False
-
- list_display = (
- 'name',
- 'last_switched_to_datetime',
- 'created_datetime',
- )
-
- search_fields = ['name']
- readonly_fields = ( 'created_datetime', 'last_switched_to_datetime', )
-
diff --git a/src/hi/simulator/apps.py b/src/hi/simulator/apps.py
index 896505aa..cd667ec2 100644
--- a/src/hi/simulator/apps.py
+++ b/src/hi/simulator/apps.py
@@ -1,35 +1,6 @@
-import os
-import sys
from django.apps import AppConfig
-class SimulatorConfig(AppConfig):
- default_auto_field = "django.db.models.BigAutoField"
- name = "hi.simulator"
-
- def ready(self):
- import time
- from hi.apps.common.asyncio_utils import start_background_event_loop
- from hi.simulator.simulator_manager import SimulatorManager
-
- # Notes:
- # - This method does not run in a production-like environment using gunicorn.
- # - When it is called, it is often called multiple times during Django initialization.
- # - Django seem to be suing different processes on each invocation.
-
- if os.environ.get('RUN_MAIN') != 'true': # Prevents duplicate execution in `runserver`
- return
-
- # The responsibility for replicating the logic below falls to
- # gunicorn when it is being used (via its post_fork() config file).
- #
- # However, the simulator is not currently set up for anything but
- # runserver execution.
- #
- if (( "gunicorn" in os.environ.get("SERVER_SOFTWARE", ""))
- or ( "gunicorn" in sys.argv[0] )):
- return
-
- time.sleep(1) # Hack - Despite this method's name, Django is not actually "ready".
- start_background_event_loop( task_function = SimulatorManager().initialize )
- return
+class SimulatorConfig( AppConfig ):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'hi.simulator'
diff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.py
index 58925a25..dec41916 100644
--- a/src/hi/simulator/management/commands/seed_sim_profiles.py
+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py
@@ -1,78 +1,75 @@
"""
-Seed the simulator with a curated suite of SimProfiles for manual
-testing of the integration sync flows.
-
-Five profiles, each designed to exercise a specific scenario:
-
- * empty — zero items in every integration. Tests the
- initial-import-with-nothing path and the
- refresh-against-emptied-upstream path.
- * baseline — the realistic small-install set. Mixed HASS
- device types, a handful of HomeBox items, a
- few ZM monitors. Used as the *before* state
- for delta tests.
- * baseline-changed — same shape as baseline, with deltas in every
- integration. The pair (baseline ↔
- baseline-changed) is designed to exercise all
- five sync-result categories — created,
- updated, reconnected, detached, removed — in
- a single flip back-and-forth. See "Operator
- workflow for full-category coverage" below.
- * hass-zoo — one HASS entity of every supported type.
- Visual / grouping coverage for the HASS
- converter; HomeBox/ZM stay empty.
- * volume — large counts (30 HASS, 25 HomeBox, 10 ZM
- monitors). Stresses modal list overflow
- scrolling and dispatcher group sizing.
-
-Re-running the command is a no-op when the named profile exists.
+Seed the simulator with a curated suite of per-module SimProfiles for
+manual testing of the integration sync flows.
+
+Profiles are scoped to a single module (each service simulator owns its
+own profile namespace), so the seed catalog is partitioned by module:
+
+ HASS (hi.simulator.services.hass)
+ * empty
+ * baseline
+ * baseline-changed
+ * hass-zoo — one HASS entity of every supported type
+
+ HomeBox (hi.simulator.services.homebox)
+ * empty
+ * baseline
+ * baseline-changed
+ * volume — 25 items, varied metadata
+
+ ZoneMinder (hi.simulator.services.zoneminder)
+ * empty
+ * baseline
+ * baseline-changed
+ * volume — 1 server + 10 monitors
+
+ NWS (hi.simulator.weather_sources.nws)
+ * sample — curated 8-alert catalog spanning event
+ types; every alert starts inactive so
+ the operator toggles individually to
+ exercise the active-alerts feed.
+
+Re-running the command is a no-op for profiles that already exist.
Pass ``--reset`` to delete the matching profile (and its entities)
-before recreating.
+before recreating. Pass ``--module <short>`` (``hass``, ``homebox``,
+``zoneminder``) to restrict seeding to one service's catalog.
Operator workflow for full-category coverage (sync result modal
-manual validation):
-
- 1. Switch simulator to ``baseline``. Sync HI. Two entities
- whose names start with ``★ Custom Attr Needed ★`` will be
- imported (HASS and ZM only — HomeBox sets
+manual validation): each module's ``baseline`` / ``baseline-changed``
+pair is designed to exercise its own integration's sync results
+independently. Switch the relevant module's profile selector between
+the two and refresh sync to see created / updated / reconnected /
+detached / removed transitions for that integration.
+
+ 1. Switch HASS to ``baseline``. Sync HI. An entity whose name
+ starts with ``★ Custom Attr Needed ★`` will be imported.
+ Open it in entity-edit and add ANY custom attribute (e.g., a
+ ``Note`` attribute with any value). The custom attribute is
+ what flips it onto the preserve-with-user-data path when it
+ later disappears upstream.
+ 2. Repeat for ZM: switch ZoneMinder to ``baseline``, sync, add a
+ custom attribute to its ★-prefixed monitor. (HomeBox sets
``can_add_custom_attributes = False`` by design, so HB
- entities cannot participate in the detach/reconnect cycle
- and have no anchor item). Open each in entity-edit and add
- ANY custom attribute (e.g., a "Note" attribute with any
- value). The custom attribute is what flips them onto the
- preserve-with-user-data path when they later disappear
- upstream.
- 2. Switch simulator to ``baseline-changed``. Refresh sync.
- The result modal shows:
- - Created: three new items present only in baseline-changed
- - Updated: three items renamed / metadata-changed
- - Removed: three items absent here, no user attribute
- - Detached: two ★-prefixed items (HASS, ZM) absent here,
- with the user attribute the operator added in step 1
- retained
- - (Reconnected is empty on this direction)
- 3. Switch simulator back to ``baseline``. Refresh sync.
- The result modal shows:
- - Reconnected: the two ★-prefixed items (HASS, ZM) rejoin
- via the secondary-match path; their custom attributes
- are intact
- - Created: the three previously-Removed items return as
- fresh entities (no previous_integration_id, so no
- reconnect — they come back as duplicates would, but
- since the originals were hard-deleted there's no
- duplication, just re-creation)
- - Updated: the renames / changes swap back
- - Removed: the three baseline-changed-only items are
- dropped (no user attributes anchored, so hard-deleted)
- - (Detached is empty on this direction unless extra
- attributes were anchored on items unique to
- baseline-changed)
+ entities cannot participate in the detach/reconnect cycle and
+ have no anchor item.)
+ 3. Switch each module to its ``baseline-changed``. Refresh sync.
+ The result modal shows per-module:
+ - Created: new items present only in baseline-changed
+ - Updated: items renamed / metadata-changed
+ - Removed: items absent here, no user attribute
+ - Detached: ★-prefixed items (HASS, ZM) absent here, with
+ the user attribute the operator added retained
+ 4. Switch each module back to ``baseline``. Refresh sync.
+ Reconnected: the ★-prefixed items rejoin via the
+ secondary-match path; their custom attributes are intact.
"""
from django.core.management.base import BaseCommand
from django.db import transaction
-from hi.simulator.enums import SimEntityType
-from hi.simulator.models import DbSimEntity, SimProfile
+from hi.simulator.profile.models import SimProfile
+from hi.simulator.profile.profile_manager import ProfileManager
+from hi.simulator.services.enums import SimEntityType
+from hi.simulator.services.hass.apps import HassConfig
from hi.simulator.services.hass.sim_models import (
HassCameraNoMotionSimEntityFields,
HassCameraSimEntityFields,
@@ -111,30 +108,36 @@ from hi.simulator.services.hass.sim_models import (
HassWindowBlindCoverFields,
HassWindowContactSensorFields,
)
+from hi.simulator.services.homebox.apps import HomeBoxConfig
from hi.simulator.services.homebox.attachment_catalog import AttachmentTemplate
from hi.simulator.services.homebox.sim_models import (
HomeBoxInventoryItemFields,
)
+from hi.simulator.services.models import DbSimEntity
+from hi.simulator.services.zoneminder.apps import ZoneminderConfig
from hi.simulator.services.zoneminder.sim_models import (
ZmMonitorSimEntityFields,
ZmServerSimEntityFields,
)
+from hi.simulator.weather_sources.nws.apps import NwsWeatherSimConfig
+from hi.simulator.weather_sources.nws.models import NwsSimAlert
-PROFILE_NAMES = [
- 'empty',
- 'baseline',
- 'baseline-changed',
- 'hass-zoo',
- 'volume',
-]
+# Short module aliases for the --module CLI flag, mapped to the full
+# AppConfig.name used as ``SimProfile.module_key``.
+MODULE_SHORT_NAMES = {
+ 'hass': HassConfig.name,
+ 'homebox': HomeBoxConfig.name,
+ 'zoneminder': ZoneminderConfig.name,
+ 'nws': NwsWeatherSimConfig.name,
+}
class Command(BaseCommand):
help = (
- 'Seed the simulator with a curated set of SimProfiles for '
- 'integration sync testing (empty, baseline, baseline-changed, '
- 'hass-zoo, volume).'
+ 'Seed the simulator with a curated set of per-module SimProfiles '
+ 'for integration sync testing. By default seeds all service '
+ 'modules (HASS, HomeBox, ZoneMinder); restrict with --module.'
)
def add_arguments(self, parser):
@@ -148,65 +151,121 @@ class Command(BaseCommand):
),
)
parser.add_argument(
- '--only',
- nargs = '+',
- choices = PROFILE_NAMES,
- help = 'Restrict seeding to the named profile(s).',
+ '--module',
+ choices = sorted( MODULE_SHORT_NAMES.keys() ),
+ help = (
+ 'Restrict seeding to a single service module. Default '
+ 'is to seed all service modules.'
+ ),
)
def handle(self, *args, **options):
- targets = options.get('only') or PROFILE_NAMES
reset = options.get('reset', False)
-
- builders = {
- 'empty': self._build_empty,
- 'baseline': self._build_baseline,
- 'baseline-changed': self._build_baseline_changed,
- 'hass-zoo': self._build_hass_zoo,
- 'volume': self._build_volume,
- }
-
- for name in targets:
+ module_filter = options.get('module')
+
+ registry = self._build_registry()
+ if module_filter:
+ target_module_key = MODULE_SHORT_NAMES[ module_filter ]
+ registry = [
+ entry for entry in registry
+ if entry[0] == target_module_key
+ ]
+
+ last_module_key = None
+ for module_key, profile_name, builder in registry:
+ if module_key != last_module_key:
+ self.stdout.write( f'\n[{module_key}]' )
+ last_module_key = module_key
self._seed_profile(
- name = name,
- builder = builders[name],
+ module_key = module_key,
+ name = profile_name,
+ builder = builder,
reset = reset,
)
+ # ----- registry -----
+
+ def _build_registry(self):
+ """List of (module_key, profile_name, builder_callable).
+
+ Order matters for output legibility — keep grouped by module.
+ Each builder takes a freshly-created SimProfile and returns the
+ count of DbSimEntity rows it created.
+ """
+ hass = HassConfig.name
+ homebox = HomeBoxConfig.name
+ zoneminder = ZoneminderConfig.name
+ nws = NwsWeatherSimConfig.name
+ return [
+ ( hass , 'empty' , self._build_empty ),
+ ( hass , 'baseline' , self._build_hass_baseline ),
+ ( hass , 'baseline-changed' , self._build_hass_baseline_changed ),
+ ( hass , 'hass-zoo' , self._build_hass_zoo ),
+
+ ( homebox , 'empty' , self._build_empty ),
+ ( homebox , 'baseline' , self._build_homebox_baseline ),
+ ( homebox , 'baseline-changed' , self._build_homebox_baseline_changed ),
+ ( homebox , 'volume' , self._build_homebox_volume ),
+
+ ( zoneminder , 'empty' , self._build_empty ),
+ ( zoneminder , 'baseline' , self._build_zm_baseline ),
+ ( zoneminder , 'baseline-changed' , self._build_zm_baseline_changed ),
+ ( zoneminder , 'volume' , self._build_zm_volume ),
+
+ ( nws , 'sample' , self._build_nws_sample ),
+ ]
+
# ----- profile orchestration -----
- def _seed_profile(self, name, builder, reset):
- existing = SimProfile.objects.filter(name = name).first()
+ def _seed_profile(self, module_key, name, builder, reset):
+ existing = SimProfile.objects.filter(
+ module_key = module_key, name = name,
+ ).first()
if existing:
if not reset:
self.stdout.write(
- f' skip {name}: already exists '
+ f' skip {name}: already exists '
'(pass --reset to recreate)'
)
return
- self.stdout.write(f' reset {name}: deleting existing profile')
+ self.stdout.write( f' reset {name}: deleting existing profile' )
existing.delete() # cascades to db_sim_entities
with transaction.atomic():
- profile = SimProfile.objects.create(name = name)
+ profile = SimProfile.objects.create(
+ module_key = module_key, name = name,
+ )
count = builder(profile)
self.stdout.write(
self.style.SUCCESS(
- f' ok {name}: created with {count} entit'
+ f' ok {name}: created with {count} entit'
f'{"y" if count == 1 else "ies"}'
)
)
- # ----- builders -----
+ # Notify the relevant module if the freshly-(re)created profile
+ # is its currently-selected profile, so its in-memory caches
+ # reload against the new entity set. Safe no-op when the
+ # module hasn't registered a callback or the profile isn't
+ # current.
+ try:
+ current = ProfileManager().get_current( module_key )
+ if current.pk == profile.pk:
+ ProfileManager().set_current( module_key, profile )
+ except Exception: # pragma: no cover - defensive on first-run
+ pass
+
+ # ----- module-agnostic builders -----
def _build_empty(self, profile: SimProfile) -> int:
return 0
- def _build_baseline(self, profile: SimProfile) -> int:
- # HASS: one of each common device kind, plus a ★-prefixed
- # item that the operator anchors with a custom attribute
- # before flipping to baseline-changed (drives the
- # detach/reconnect cycle on the HASS side).
+ # ----- HASS builders -----
+
+ def _build_hass_baseline(self, profile: SimProfile) -> int:
+ # One of each common device kind, plus a ★-prefixed item that
+ # the operator anchors with a custom attribute before flipping
+ # to baseline-changed (drives the detach/reconnect cycle).
self._add_hass_light_switch( profile, 'Garage Light' , '01.AA.01' )
self._add_hass_dimmer( profile, 'Den Lamp' , '01.AA.02' )
self._add_hass_motion( profile, 'Hallway Motion' , '01.AA.03' )
@@ -215,16 +274,88 @@ class Command(BaseCommand):
self._add_hass_light_switch(
profile, '★ Custom Attr Needed ★ Office Light', '01.AA.10',
)
+ return profile.db_sim_entities.count()
+
+ def _build_hass_baseline_changed(self, profile: SimProfile) -> int:
+ # HASS deltas vs baseline:
+ # Garage Light — kept (no change)
+ # Den Lamp — RENAMED to "Den Reading Lamp" (update)
+ # Hallway Motion — kept
+ # Front Door — REMOVED (no user attribute → hard delete)
+ # Kitchen Outlet — kept
+ # ★ Office Light — ABSENT here; with a user attribute
+ # anchored on the HI side it takes
+ # the preserve path → Detached
+ # <new> Patio Switch — ADDED (create)
+ self._add_hass_light_switch( profile, 'Garage Light' , '01.AA.01' )
+ self._add_hass_dimmer( profile, 'Den Reading Lamp' , '01.AA.02' )
+ self._add_hass_motion( profile, 'Hallway Motion' , '01.AA.03' )
+ self._add_hass_outlet( profile, 'Kitchen Outlet' , '01.AA.05' )
+ self._add_hass_light_switch( profile, 'Patio Switch' , '01.AA.06' )
+ return profile.db_sim_entities.count()
- # HomeBox: 4 items with mixed metadata richness. No
- # ★-prefixed anchor here: HomeBox sets
- # ``can_add_custom_attributes = False`` (the converter is
- # the source of truth for HB item attributes), so the
- # operator cannot add a custom attribute on the HI side and
- # the detach/reconnect cycle does not apply to HB. ``item_id``
- # is the per-item stable id used by the integration's
- # change-detection — kept identical across baseline /
- # baseline-changed for items that should be 'the same item'.
+ def _build_hass_zoo(self, profile: SimProfile) -> int:
+ # One of every HASS sim entity definition type. Subsumes the
+ # historical cross-module "volume" stress case for HASS.
+ self._add_hass_camera( profile, 'Zoo Camera' , 'zoo_camera' )
+ self._add_hass_camera_no_motion( profile, 'Zoo Camera No Motion', 'zoo_camera_no_motion' )
+ self._add_hass_light_switch( profile, 'Zoo Insteon Light Switch' , '01.BB.01' )
+ self._add_hass_dimmer( profile, 'Zoo Insteon Dimmer' , '01.BB.02' )
+ self._add_hass_dual_band( profile, 'Zoo Insteon Dual Band Switch' , '01.BB.03' )
+ self._add_hass_motion( profile, 'Zoo Insteon Motion' , '01.BB.04' )
+ self._add_hass_open_close( profile, 'Zoo Insteon Open/Close' , '01.BB.05' )
+ self._add_hass_outlet( profile, 'Zoo Insteon Outlet' , '01.BB.06' )
+ self._add_hass_switch( profile, 'Zoo Switch' )
+ self._add_hass_motion_sensor( profile, 'Zoo Motion' )
+ self._add_hass_combo_motion_sensor( profile, 'Zoo Smart Motion' )
+ self._add_hass_basic_outlet( profile, 'Zoo Outlet' )
+ self._add_hass_presence_sensor( profile, 'Zoo Presence' )
+ self._add_hass_opening_sensor( profile, 'Zoo Opening' )
+ self._add_hass_power_meter( profile, 'Zoo Power Meter' )
+ self._add_hass_weather_station( profile, 'Zoo Weather Station' )
+ self._add_hass_occupancy_light_sensor( profile, 'Zoo Room Sensor' )
+ self._add_hass_water_leak_sensor( profile, 'Zoo Leak Sensor' )
+ self._add_hass_smart_bulb( profile, 'Zoo Smart Bulb' )
+ self._add_hass_color_smart_bulb( profile, 'Zoo Color Bulb' )
+ self._add_hass_door_contact( profile, 'Zoo Door Contact' )
+ self._add_hass_window_contact( profile, 'Zoo Window Contact' )
+ self._add_hass_smoke_detector( profile, 'Zoo Smoke Detector' )
+ self._add_hass_smoke_detector_with_battery( profile, 'Zoo Smoke Detector (Battery)' )
+ self._add_hass_carbon_monoxide_detector( profile, 'Zoo CO Detector' )
+ self._add_hass_gas_detector( profile, 'Zoo Gas Detector' )
+ self._add_hass_temperature_sensor( profile, 'Zoo Thermometer' )
+ self._add_hass_temperature_sensor(
+ profile, 'Zoo Thermometer Celsius', temperature_unit = '°C',
+ )
+ self._add_hass_humidity_sensor( profile, 'Zoo Hygrometer' )
+ self._add_hass_temp_humidity_sensor( profile, 'Zoo Climate Sensor' )
+ self._add_hass_lock( profile, 'Zoo Lock' )
+ self._add_hass_garage_cover( profile, 'Zoo Garage' )
+ self._add_hass_window_blind_cover( profile, 'Zoo Blind' )
+ self._add_hass_generic_cover( profile, 'Zoo Cover' )
+ self._add_hass_ceiling_fan( profile, 'Zoo Fan' )
+ self._add_hass_multi_feature_fan( profile, 'Zoo Smart Fan' )
+ self._add_hass_thermostat( profile, 'Zoo Thermostat' )
+ self._add_hass_thermostat(
+ profile, 'Zoo Heater',
+ hvac_modes = [ 'heat', 'off' ],
+ fan_modes = [],
+ temperature_unit = '°C',
+ )
+ return profile.db_sim_entities.count()
+
+ # ----- HomeBox builders -----
+
+ def _build_homebox_baseline(self, profile: SimProfile) -> int:
+ # 4 items with mixed metadata richness. No ★-prefixed anchor
+ # here: HomeBox sets ``can_add_custom_attributes = False`` (the
+ # converter is the source of truth for HB item attributes), so
+ # the operator cannot add a custom attribute on the HI side
+ # and the detach/reconnect cycle does not apply to HB.
+ # ``item_id`` is the per-item stable id used by the
+ # integration's change-detection — kept identical across
+ # baseline / baseline-changed for items that should be 'the
+ # same item'.
self._add_homebox_item(
profile, 'Cordless Drill',
item_id = 'cordless-drill',
@@ -256,60 +387,16 @@ class Command(BaseCommand):
item_id = 'spare-light-bulbs',
quantity = 12,
)
-
- # ZoneMinder: 1 server (singleton) + 2 monitors + a
- # ★-prefixed monitor anchor for the ZM detach/reconnect
- # cycle.
- self._add_zm_server( profile )
- self._add_zm_monitor( profile, 'Front Door Camera' , monitor_id = 1 )
- self._add_zm_monitor( profile, 'Driveway Camera' , monitor_id = 2 )
- self._add_zm_monitor(
- profile, '★ Custom Attr Needed ★ Backyard Camera',
- monitor_id = 5,
- )
-
return profile.db_sim_entities.count()
- def _build_baseline_changed(self, profile: SimProfile) -> int:
- # Designed as the partner of baseline so that flipping the
- # simulator between the two profiles and Refreshing
- # exercises every one of the five sync-result categories
- # (created / updated / reconnected / detached / removed)
- # in a single click. See the module docstring for the
- # operator workflow that drives the detach/reconnect path
- # via user-attribute anchoring.
-
- # HASS deltas vs baseline:
- # Garage Light — kept (no change)
- # Den Lamp — RENAMED to "Den Reading Lamp" (update)
- # Hallway Motion — kept
- # Front Door — REMOVED (no user attribute → hard delete)
- # Kitchen Outlet — kept
- # ★ Office Light — ABSENT here; with a user attribute
- # anchored on the HI side it takes
- # the preserve path → Detached
- # <new> Patio Switch — ADDED (create)
- self._add_hass_light_switch( profile, 'Garage Light' , '01.AA.01' )
- self._add_hass_dimmer( profile, 'Den Reading Lamp' , '01.AA.02' )
- self._add_hass_motion( profile, 'Hallway Motion' , '01.AA.03' )
- # Front Door (01.AA.04) intentionally absent.
- self._add_hass_outlet( profile, 'Kitchen Outlet' , '01.AA.05' )
- self._add_hass_light_switch( profile, 'Patio Switch' , '01.AA.06' )
- # Office Light (01.AA.10) intentionally absent — its HI-side
- # entity has the user-anchored custom attribute and takes
- # the detach path on the first sync after switching here.
-
- # HomeBox deltas:
- # Cordless Drill — kept (same item_id, same content)
+ def _build_homebox_baseline_changed(self, profile: SimProfile) -> int:
+ # HomeBox deltas vs baseline:
+ # Cordless Drill — kept (same item_id, attachment churn)
# Stud Finder — same item_id, manufacturer changed
# (attribute update path)
# Soldering Iron — REMOVED (item_id absent, no user attr)
# Spare Bulbs — kept (same item_id, same content)
# <new> Caulk Gun — ADDED (new item_id)
- # No HB detach/reconnect anchor — see baseline's HB section.
- # Identity carries via ``item_id`` (the simulator's stable
- # API id), not row order — so the order here doesn't matter
- # for change-detection.
self._add_homebox_item(
profile, 'Cordless Drill',
item_id = 'cordless-drill',
@@ -331,7 +418,7 @@ class Command(BaseCommand):
item_id = 'stud-finder',
manufacturer = 'Bosch', # changed from 'Franklin Sensors'
quantity = 1,
- attachment_keys = AttachmentTemplate.PHOTO.key, # unchanged across baseline pair
+ attachment_keys = AttachmentTemplate.PHOTO.key,
)
self._add_homebox_item(
profile, 'Spare Light Bulbs',
@@ -344,8 +431,41 @@ class Command(BaseCommand):
description = '10-oz cartridge gun, dripless',
quantity = 1,
)
+ return profile.db_sim_entities.count()
+
+ def _build_homebox_volume(self, profile: SimProfile) -> int:
+ # 25 items, varied metadata richness. Stresses HB list rendering
+ # and the inventory pagination/scroll behavior.
+ for index in range(25):
+ self._add_homebox_item(
+ profile,
+ f'Volume Item {index + 1:03}',
+ item_id = f'volume-item-{index + 1:03}',
+ description = (
+ f'Stress-test inventory item #{index + 1}'
+ if index % 3 == 0 else ''
+ ),
+ manufacturer = 'Acme' if index % 5 == 0 else '',
+ quantity = (index % 4) + 1,
+ )
+ return profile.db_sim_entities.count()
+
+ # ----- ZoneMinder builders -----
+
+ def _build_zm_baseline(self, profile: SimProfile) -> int:
+ # 1 server (singleton) + 2 monitors + a ★-prefixed monitor
+ # anchor for the ZM detach/reconnect cycle.
+ self._add_zm_server( profile )
+ self._add_zm_monitor( profile, 'Front Door Camera' , monitor_id = 1 )
+ self._add_zm_monitor( profile, 'Driveway Camera' , monitor_id = 2 )
+ self._add_zm_monitor(
+ profile, '★ Custom Attr Needed ★ Backyard Camera',
+ monitor_id = 5,
+ )
+ return profile.db_sim_entities.count()
- # ZoneMinder deltas:
+ def _build_zm_baseline_changed(self, profile: SimProfile) -> int:
+ # ZoneMinder deltas vs baseline:
# ZM Server — kept
# Front Door Camera — RENAMED to "Front Porch Camera"
# Driveway Camera — REMOVED
@@ -359,120 +479,171 @@ class Command(BaseCommand):
self._add_zm_server( profile )
self._add_zm_monitor( profile, 'Front Porch Camera' , monitor_id = 1 )
self._add_zm_monitor( profile, 'Garage Camera' , monitor_id = 3 )
- # monitor_id 5 (Backyard Camera) intentionally absent.
-
return profile.db_sim_entities.count()
- def _build_hass_zoo(self, profile: SimProfile) -> int:
- # One of every HASS sim entity definition type.
- self._add_hass_camera( profile, 'Zoo Camera' , 'zoo_camera' )
- self._add_hass_camera_no_motion( profile, 'Zoo Camera No Motion', 'zoo_camera_no_motion' )
- self._add_hass_light_switch( profile, 'Zoo Insteon Light Switch' , '01.BB.01' )
- self._add_hass_dimmer( profile, 'Zoo Insteon Dimmer' , '01.BB.02' )
- self._add_hass_dual_band( profile, 'Zoo Insteon Dual Band Switch' , '01.BB.03' )
- self._add_hass_motion( profile, 'Zoo Insteon Motion' , '01.BB.04' )
- self._add_hass_open_close( profile, 'Zoo Insteon Open/Close' , '01.BB.05' )
- self._add_hass_outlet( profile, 'Zoo Insteon Outlet' , '01.BB.06' )
- self._add_hass_switch( profile, 'Zoo Switch' )
- self._add_hass_motion_sensor( profile, 'Zoo Motion' )
- self._add_hass_combo_motion_sensor( profile, 'Zoo Smart Motion' )
- self._add_hass_basic_outlet( profile, 'Zoo Outlet' )
- self._add_hass_presence_sensor( profile, 'Zoo Presence' )
- self._add_hass_opening_sensor( profile, 'Zoo Opening' )
- self._add_hass_power_meter( profile, 'Zoo Power Meter' )
- self._add_hass_weather_station( profile, 'Zoo Weather Station' )
- self._add_hass_occupancy_light_sensor( profile, 'Zoo Room Sensor' )
- self._add_hass_water_leak_sensor( profile, 'Zoo Leak Sensor' )
- self._add_hass_smart_bulb( profile, 'Zoo Smart Bulb' )
- self._add_hass_color_smart_bulb( profile, 'Zoo Color Bulb' )
- self._add_hass_door_contact( profile, 'Zoo Door Contact' )
- self._add_hass_window_contact( profile, 'Zoo Window Contact' )
- self._add_hass_smoke_detector( profile, 'Zoo Smoke Detector' )
- self._add_hass_smoke_detector_with_battery( profile, 'Zoo Smoke Detector (Battery)' )
- self._add_hass_carbon_monoxide_detector( profile, 'Zoo CO Detector' )
- self._add_hass_gas_detector( profile, 'Zoo Gas Detector' )
- self._add_hass_temperature_sensor( profile, 'Zoo Thermometer' )
- self._add_hass_temperature_sensor(
- profile, 'Zoo Thermometer Celsius', temperature_unit = '°C',
- )
- self._add_hass_humidity_sensor( profile, 'Zoo Hygrometer' )
- self._add_hass_temp_humidity_sensor( profile, 'Zoo Climate Sensor' )
- self._add_hass_lock( profile, 'Zoo Lock' )
- self._add_hass_garage_cover( profile, 'Zoo Garage' )
- self._add_hass_window_blind_cover( profile, 'Zoo Blind' )
- self._add_hass_generic_cover( profile, 'Zoo Cover' )
- self._add_hass_ceiling_fan( profile, 'Zoo Fan' )
- self._add_hass_multi_feature_fan( profile, 'Zoo Smart Fan' )
- self._add_hass_thermostat( profile, 'Zoo Thermostat' )
- self._add_hass_thermostat(
- profile, 'Zoo Heater',
- hvac_modes = [ 'heat', 'off' ],
- fan_modes = [],
- temperature_unit = '°C',
- )
- return profile.db_sim_entities.count()
-
- def _build_volume(self, profile: SimProfile) -> int:
- # 30 HASS items spread across types with a heavy bias toward
- # the most common (lights). Insteon addresses are sequential
- # under the 01.CC.* prefix to avoid colliding with other
- # profiles if they happen to share a database load.
- light_types = [
- self._add_hass_light_switch,
- self._add_hass_dimmer,
- self._add_hass_dual_band,
- ]
- for index in range(20):
- adder = light_types[index % len(light_types)]
- adder(profile, f'Volume Light {index + 1:02}',
- f'01.CC.{index + 1:02X}')
- for index in range(5):
- self._add_hass_motion(
- profile, f'Volume Motion {index + 1:02}',
- f'01.CD.{index + 1:02X}',
- )
- for index in range(3):
- self._add_hass_open_close(
- profile, f'Volume Door {index + 1:02}',
- f'01.CE.{index + 1:02X}',
- )
- for index in range(2):
- self._add_hass_outlet(
- profile, f'Volume Outlet {index + 1:02}',
- f'01.CF.{index + 1:02X}',
- )
-
- # 25 HomeBox items, varied metadata.
- for index in range(25):
- self._add_homebox_item(
- profile,
- f'Volume Item {index + 1:03}',
- item_id = f'volume-item-{index + 1:03}',
- description = (
- f'Stress-test inventory item #{index + 1}'
- if index % 3 == 0 else ''
- ),
- manufacturer = 'Acme' if index % 5 == 0 else '',
- quantity = (index % 4) + 1,
- )
-
- # ZM: 1 server + 10 monitors.
- self._add_zm_server(profile)
+ def _build_zm_volume(self, profile: SimProfile) -> int:
+ # 1 server + 10 monitors. Stresses dispatcher group sizing.
+ self._add_zm_server( profile )
for index in range(10):
self._add_zm_monitor(
profile,
f'Volume Camera {index + 1:02}',
monitor_id = 100 + index,
)
-
return profile.db_sim_entities.count()
+ # ----- NWS builders -----
+
+ def _build_nws_sample(self, profile: SimProfile) -> int:
+ # 8-alert catalog spanning event types and severities. Every
+ # alert is inactive by default so the operator toggles each on
+ # individually to drive the active-alerts feed through one
+ # event type at a time. Severity / certainty / urgency follow
+ # the canonical CAP pairings the NWS issues for each product.
+ area = 'Demo County, ZZ'
+ self._add_nws_alert(
+ profile,
+ event_code = 'TOR',
+ event_name = 'Tornado Warning',
+ severity = 'Extreme', certainty = 'Observed', urgency = 'Immediate',
+ category = 'met', area_desc = area,
+ headline = 'Tornado Warning issued for Demo County',
+ description = (
+ 'At 4:15 PM, a confirmed tornado was located near Demo '
+ 'Town, moving northeast at 35 mph. This is a particularly '
+ 'dangerous situation.'
+ ),
+ instruction = (
+ 'TAKE COVER NOW! Move to a basement or interior room on '
+ 'the lowest floor of a sturdy building. Avoid windows.'
+ ),
+ )
+ self._add_nws_alert(
+ profile,
+ event_code = 'HUW',
+ event_name = 'Hurricane Warning',
+ severity = 'Extreme', certainty = 'Likely', urgency = 'Expected',
+ category = 'met', area_desc = area,
+ headline = 'Hurricane Warning in effect for Demo County',
+ description = (
+ 'Hurricane conditions are expected somewhere within the '
+ 'warning area within 36 hours. Devastating wind damage '
+ 'and life-threatening storm surge are anticipated.'
+ ),
+ instruction = (
+ 'Complete preparations for hurricane-force winds and '
+ 'storm surge. Follow evacuation orders from local '
+ 'officials.'
+ ),
+ )
+ self._add_nws_alert(
+ profile,
+ event_code = 'SVR',
+ event_name = 'Severe Thunderstorm Warning',
+ severity = 'Severe', certainty = 'Observed', urgency = 'Immediate',
+ category = 'met', area_desc = area,
+ headline = 'Severe Thunderstorm Warning for Demo County',
+ description = (
+ 'At 3:50 PM, severe thunderstorms were located along a '
+ 'line moving east at 40 mph. Hazards include 60 mph wind '
+ 'gusts and quarter-size hail.'
+ ),
+ instruction = (
+ 'For your protection move to an interior room on the '
+ 'lowest floor of a building.'
+ ),
+ )
+ self._add_nws_alert(
+ profile,
+ event_code = 'FFW',
+ event_name = 'Flash Flood Warning',
+ severity = 'Severe', certainty = 'Likely', urgency = 'Immediate',
+ category = 'met', area_desc = area,
+ headline = 'Flash Flood Warning for Demo County',
+ description = (
+ 'Flash flooding is ongoing or expected to begin shortly. '
+ 'Between 1 and 3 inches of rain have fallen. Additional '
+ 'rainfall amounts of 1 to 2 inches are possible.'
+ ),
+ instruction = (
+ 'Turn around, don\'t drown when encountering flooded '
+ 'roads. Most flood deaths occur in vehicles.'
+ ),
+ )
+ self._add_nws_alert(
+ profile,
+ event_code = 'WSW',
+ event_name = 'Winter Storm Warning',
+ severity = 'Moderate', certainty = 'Likely', urgency = 'Expected',
+ category = 'met', area_desc = area,
+ headline = 'Winter Storm Warning issued for Demo County',
+ description = (
+ 'Heavy snow expected. Total snow accumulations of 8 to '
+ '12 inches. Winds gusting as high as 35 mph.'
+ ),
+ instruction = (
+ 'Travel could be very difficult to impossible. The '
+ 'hazardous conditions could impact the morning commute.'
+ ),
+ )
+ self._add_nws_alert(
+ profile,
+ event_code = 'TOA',
+ event_name = 'Tornado Watch',
+ severity = 'Severe', certainty = 'Possible', urgency = 'Future',
+ category = 'met', area_desc = area,
+ headline = 'Tornado Watch in effect for Demo County',
+ description = (
+ 'Conditions are favorable for the development of '
+ 'tornadoes within the watch area. Damaging winds and '
+ 'large hail are also possible.'
+ ),
+ instruction = (
+ 'Review tornado safety rules and be prepared to take '
+ 'shelter quickly if a warning is issued.'
+ ),
+ )
+ self._add_nws_alert(
+ profile,
+ event_code = '',
+ event_name = 'Heat Advisory',
+ severity = 'Moderate', certainty = 'Likely', urgency = 'Expected',
+ category = 'met', area_desc = area,
+ headline = 'Heat Advisory in effect for Demo County',
+ description = (
+ 'Heat index values up to 105 expected. Hot temperatures '
+ 'and high humidity may cause heat illnesses to occur.'
+ ),
+ instruction = (
+ 'Drink plenty of fluids, stay in an air-conditioned '
+ 'room, and check up on relatives and neighbors.'
+ ),
+ )
+ self._add_nws_alert(
+ profile,
+ event_code = 'AQA',
+ event_name = 'Air Quality Alert',
+ severity = 'Moderate', certainty = 'Observed', urgency = 'Expected',
+ category = 'health', area_desc = area,
+ headline = 'Air Quality Alert for Demo County',
+ description = (
+ 'The Department of Environmental Quality has issued an '
+ 'Air Quality Alert. Fine particulate concentrations are '
+ 'expected to reach unhealthy levels.'
+ ),
+ instruction = (
+ 'Sensitive groups including children, the elderly, and '
+ 'those with heart or lung conditions should limit '
+ 'prolonged outdoor exertion.'
+ ),
+ )
+ return profile.nws_sim_alerts.count()
+
# ----- per-integration row builders -----
def _add_hass_light_switch(self, profile, name, addr):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassInsteonLightSwitchFields,
sim_entity_type = SimEntityType.LIGHT,
fields_kwargs = {'name': name, 'insteon_address': addr},
@@ -481,7 +652,6 @@ class Command(BaseCommand):
def _add_hass_dimmer(self, profile, name, addr):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassInsteonDimmerLightSwitchFields,
sim_entity_type = SimEntityType.LIGHT,
fields_kwargs = {'name': name, 'insteon_address': addr},
@@ -490,7 +660,6 @@ class Command(BaseCommand):
def _add_hass_dual_band(self, profile, name, addr):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassInsteonDualBandLightSwitchFields,
sim_entity_type = SimEntityType.LIGHT,
fields_kwargs = {'name': name, 'insteon_address': addr},
@@ -499,7 +668,6 @@ class Command(BaseCommand):
def _add_hass_motion(self, profile, name, addr):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassInsteonMotionDetectorFields,
sim_entity_type = SimEntityType.MOTION_SENSOR,
fields_kwargs = {'name': name, 'insteon_address': addr},
@@ -508,7 +676,6 @@ class Command(BaseCommand):
def _add_hass_open_close(self, profile, name, addr):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassInsteonOpenCloseSensorFields,
sim_entity_type = SimEntityType.OPEN_CLOSE_SENSOR,
fields_kwargs = {'name': name, 'insteon_address': addr},
@@ -517,7 +684,6 @@ class Command(BaseCommand):
def _add_hass_outlet(self, profile, name, addr):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassInsteonOutletFields,
sim_entity_type = SimEntityType.ELECTRICAL_OUTLET,
fields_kwargs = {'name': name, 'insteon_address': addr},
@@ -526,7 +692,6 @@ class Command(BaseCommand):
def _add_hass_smart_bulb(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassSmartBulbFields,
sim_entity_type = SimEntityType.LIGHT,
fields_kwargs = {'name': name},
@@ -535,7 +700,6 @@ class Command(BaseCommand):
def _add_hass_color_smart_bulb(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassColorSmartBulbFields,
sim_entity_type = SimEntityType.LIGHT,
fields_kwargs = {'name': name},
@@ -544,7 +708,6 @@ class Command(BaseCommand):
def _add_hass_door_contact(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassDoorContactSensorFields,
sim_entity_type = SimEntityType.OPEN_CLOSE_SENSOR,
fields_kwargs = {'name': name},
@@ -553,7 +716,6 @@ class Command(BaseCommand):
def _add_hass_window_contact(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassWindowContactSensorFields,
sim_entity_type = SimEntityType.OPEN_CLOSE_SENSOR,
fields_kwargs = {'name': name},
@@ -562,7 +724,6 @@ class Command(BaseCommand):
def _add_hass_smoke_detector(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassSmokeDetectorFields,
sim_entity_type = SimEntityType.SMOKE_DETECTOR,
fields_kwargs = {'name': name},
@@ -571,7 +732,6 @@ class Command(BaseCommand):
def _add_hass_smoke_detector_with_battery(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassSmokeDetectorWithBatteryFields,
sim_entity_type = SimEntityType.SMOKE_DETECTOR,
fields_kwargs = {'name': name},
@@ -580,7 +740,6 @@ class Command(BaseCommand):
def _add_hass_carbon_monoxide_detector(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassCarbonMonoxideDetectorFields,
sim_entity_type = SimEntityType.CARBON_MONOXIDE_DETECTOR,
fields_kwargs = {'name': name},
@@ -589,7 +748,6 @@ class Command(BaseCommand):
def _add_hass_gas_detector(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassGasDetectorFields,
sim_entity_type = SimEntityType.GAS_DETECTOR,
fields_kwargs = {'name': name},
@@ -598,7 +756,6 @@ class Command(BaseCommand):
def _add_hass_motion_sensor(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassMotionSensorFields,
sim_entity_type = SimEntityType.MOTION_SENSOR,
fields_kwargs = {'name': name},
@@ -607,7 +764,6 @@ class Command(BaseCommand):
def _add_hass_combo_motion_sensor(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassComboMotionSensorFields,
sim_entity_type = SimEntityType.MOTION_SENSOR,
fields_kwargs = {'name': name},
@@ -616,7 +772,6 @@ class Command(BaseCommand):
def _add_hass_presence_sensor(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassPresenceSensorFields,
sim_entity_type = SimEntityType.PRESENCE_SENSOR,
fields_kwargs = {'name': name},
@@ -625,7 +780,6 @@ class Command(BaseCommand):
def _add_hass_opening_sensor(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassOpeningSensorFields,
sim_entity_type = SimEntityType.OPEN_CLOSE_SENSOR,
fields_kwargs = {'name': name},
@@ -634,7 +788,6 @@ class Command(BaseCommand):
def _add_hass_power_meter(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassPowerMeterFields,
sim_entity_type = SimEntityType.ELECTRICY_METER,
fields_kwargs = {'name': name},
@@ -643,7 +796,6 @@ class Command(BaseCommand):
def _add_hass_weather_station(self, profile, name, temperature_unit = '°F'):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassWeatherStationFields,
sim_entity_type = SimEntityType.BAROMETER,
fields_kwargs = {
@@ -655,7 +807,6 @@ class Command(BaseCommand):
def _add_hass_occupancy_light_sensor(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassOccupancyLightSensorFields,
sim_entity_type = SimEntityType.PRESENCE_SENSOR,
fields_kwargs = {'name': name},
@@ -664,7 +815,6 @@ class Command(BaseCommand):
def _add_hass_water_leak_sensor(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassWaterLeakSensorFields,
sim_entity_type = SimEntityType.LEAK_SENSOR,
fields_kwargs = {'name': name},
@@ -673,7 +823,6 @@ class Command(BaseCommand):
def _add_hass_switch(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassSwitchFields,
sim_entity_type = SimEntityType.WALL_SWITCH,
fields_kwargs = {'name': name},
@@ -682,7 +831,6 @@ class Command(BaseCommand):
def _add_hass_camera(self, profile, name, entity_id_suffix):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassCameraSimEntityFields,
sim_entity_type = SimEntityType.CAMERA,
fields_kwargs = {
@@ -694,7 +842,6 @@ class Command(BaseCommand):
def _add_hass_camera_no_motion(self, profile, name, entity_id_suffix):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassCameraNoMotionSimEntityFields,
sim_entity_type = SimEntityType.CAMERA,
fields_kwargs = {
@@ -706,7 +853,6 @@ class Command(BaseCommand):
def _add_hass_basic_outlet(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassOutletFields,
sim_entity_type = SimEntityType.ELECTRICAL_OUTLET,
fields_kwargs = {'name': name},
@@ -715,7 +861,6 @@ class Command(BaseCommand):
def _add_hass_temperature_sensor(self, profile, name, temperature_unit = '°F'):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassTemperatureSensorFields,
sim_entity_type = SimEntityType.THERMOMETER,
fields_kwargs = {
@@ -727,7 +872,6 @@ class Command(BaseCommand):
def _add_hass_humidity_sensor(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassHumiditySensorFields,
sim_entity_type = SimEntityType.HYGROMETER,
fields_kwargs = {'name': name},
@@ -736,7 +880,6 @@ class Command(BaseCommand):
def _add_hass_temp_humidity_sensor(self, profile, name, temperature_unit = '°F'):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassTempHumiditySensorFields,
sim_entity_type = SimEntityType.THERMOMETER,
fields_kwargs = {
@@ -748,7 +891,6 @@ class Command(BaseCommand):
def _add_hass_lock(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassLockFields,
sim_entity_type = SimEntityType.DOOR_LOCK,
fields_kwargs = {'name': name},
@@ -757,7 +899,6 @@ class Command(BaseCommand):
def _add_hass_garage_cover(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassGarageCoverFields,
sim_entity_type = SimEntityType.OPEN_CLOSE_ACTUATOR,
fields_kwargs = {'name': name},
@@ -766,7 +907,6 @@ class Command(BaseCommand):
def _add_hass_window_blind_cover(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassWindowBlindCoverFields,
sim_entity_type = SimEntityType.OPEN_CLOSE_ACTUATOR,
fields_kwargs = {'name': name},
@@ -775,7 +915,6 @@ class Command(BaseCommand):
def _add_hass_generic_cover(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassGenericCoverFields,
sim_entity_type = SimEntityType.OPEN_CLOSE_ACTUATOR,
fields_kwargs = {'name': name},
@@ -784,7 +923,6 @@ class Command(BaseCommand):
def _add_hass_ceiling_fan(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassFanFields,
sim_entity_type = SimEntityType.CEILING_FAN,
fields_kwargs = {'name': name},
@@ -793,7 +931,6 @@ class Command(BaseCommand):
def _add_hass_multi_feature_fan(self, profile, name):
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassMultiFeatureFanFields,
sim_entity_type = SimEntityType.CEILING_FAN,
fields_kwargs = {'name': name},
@@ -812,7 +949,6 @@ class Command(BaseCommand):
fields_kwargs[ 'fan_modes' ] = fan_modes
self._create_db_entity(
profile = profile,
- simulator_id = 'hass',
fields_class = HassThermostatFields,
sim_entity_type = SimEntityType.THERMOSTAT,
fields_kwargs = fields_kwargs,
@@ -823,7 +959,6 @@ class Command(BaseCommand):
kwargs.update(fields_kwargs)
self._create_db_entity(
profile = profile,
- simulator_id = 'hb',
fields_class = HomeBoxInventoryItemFields,
sim_entity_type = SimEntityType.OTHER,
fields_kwargs = kwargs,
@@ -832,7 +967,6 @@ class Command(BaseCommand):
def _add_zm_server(self, profile):
self._create_db_entity(
profile = profile,
- simulator_id = 'zm',
fields_class = ZmServerSimEntityFields,
sim_entity_type = SimEntityType.SERVICE,
fields_kwargs = {'name': 'ZM Server'},
@@ -841,17 +975,40 @@ class Command(BaseCommand):
def _add_zm_monitor(self, profile, name, monitor_id):
self._create_db_entity(
profile = profile,
- simulator_id = 'zm',
fields_class = ZmMonitorSimEntityFields,
sim_entity_type = SimEntityType.MOTION_SENSOR,
fields_kwargs = {'name': name, 'monitor_id': monitor_id},
)
+ def _add_nws_alert(self, profile, *,
+ event_code, event_name,
+ severity, certainty, urgency, category,
+ area_desc, headline, description, instruction,
+ status = 'Actual',
+ effective_offset_secs = -3600,
+ expires_offset_secs = 43200):
+ NwsSimAlert.objects.create(
+ sim_profile = profile,
+ is_active = False,
+ event_code = event_code,
+ event_name = event_name,
+ severity_str = severity,
+ certainty_str = certainty,
+ urgency_str = urgency,
+ status_str = status,
+ category_str = category,
+ headline = headline,
+ description = description,
+ instruction = instruction,
+ area_desc = area_desc,
+ effective_offset_secs = effective_offset_secs,
+ expires_offset_secs = expires_offset_secs,
+ )
+
# ----- low-level row creator -----
def _create_db_entity(self,
profile: SimProfile,
- simulator_id: str,
fields_class,
sim_entity_type: SimEntityType,
fields_kwargs: dict):
@@ -862,7 +1019,6 @@ class Command(BaseCommand):
fields_instance = fields_class(**fields_kwargs)
DbSimEntity.objects.create(
sim_profile = profile,
- simulator_id = simulator_id,
entity_fields_class_id = fields_class.class_id(),
sim_entity_type_str = str(sim_entity_type),
sim_entity_fields_json = fields_instance.to_json_dict(),
diff --git a/src/hi/simulator/profile/__init__.py b/src/hi/simulator/profile/__init__.py
new file mode 100644
index 00000000..5bf80200
--- /dev/null
+++ b/src/hi/simulator/profile/__init__.py
@@ -0,0 +1 @@
+default_app_config = 'hi.simulator.profile.apps.ProfileConfig'
diff --git a/src/hi/simulator/profile/admin.py b/src/hi/simulator/profile/admin.py
new file mode 100644
index 00000000..24215130
--- /dev/null
+++ b/src/hi/simulator/profile/admin.py
@@ -0,0 +1,20 @@
+from django.contrib import admin
+
+from .models import SimProfile
+
+
[email protected]( SimProfile )
+class SimProfileAdmin( admin.ModelAdmin ):
+
+ show_full_result_count = False
+
+ list_display = (
+ 'module_key',
+ 'name',
+ 'last_switched_to_datetime',
+ 'created_datetime',
+ )
+
+ search_fields = [ 'module_key', 'name' ]
+ readonly_fields = ( 'created_datetime', 'last_switched_to_datetime' )
+ list_filter = ( 'module_key', )
diff --git a/src/hi/simulator/profile/apps.py b/src/hi/simulator/profile/apps.py
new file mode 100644
index 00000000..f3ca7384
--- /dev/null
+++ b/src/hi/simulator/profile/apps.py
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class ProfileConfig( AppConfig ):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'hi.simulator.profile'
+ label = 'simulator_profile'
diff --git a/src/hi/simulator/profile/forms.py b/src/hi/simulator/profile/forms.py
new file mode 100644
index 00000000..e175266a
--- /dev/null
+++ b/src/hi/simulator/profile/forms.py
@@ -0,0 +1,10 @@
+from django import forms
+
+from .models import SimProfile
+
+
+class SimProfileForm( forms.ModelForm ):
+
+ class Meta:
+ model = SimProfile
+ fields = ( 'name', )
diff --git a/src/hi/simulator/profile/migrations/0001_initial.py b/src/hi/simulator/profile/migrations/0001_initial.py
new file mode 100644
index 00000000..87232a83
--- /dev/null
+++ b/src/hi/simulator/profile/migrations/0001_initial.py
@@ -0,0 +1,46 @@
+# Generated by Django 5.2.14 on 2026-05-19 20:11
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = []
+
+ operations = [
+ migrations.CreateModel(
+ name="SimProfile",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "module_key",
+ models.CharField(max_length=96, verbose_name="Module Key"),
+ ),
+ ("name", models.CharField(max_length=64, verbose_name="Profile Name")),
+ (
+ "last_switched_to_datetime",
+ models.DateTimeField(
+ blank=True, null=True, verbose_name="Last Switched To"
+ ),
+ ),
+ (
+ "created_datetime",
+ models.DateTimeField(auto_now_add=True, verbose_name="Created"),
+ ),
+ ],
+ options={
+ "ordering": ["module_key", "name"],
+ "unique_together": {("module_key", "name")},
+ },
+ ),
+ ]
diff --git a/src/hi/simulator/migrations/__init__.py b/src/hi/simulator/profile/migrations/__init__.py
similarity index 100%
rename from src/hi/simulator/migrations/__init__.py
rename to src/hi/simulator/profile/migrations/__init__.py
diff --git a/src/hi/simulator/profile/models.py b/src/hi/simulator/profile/models.py
new file mode 100644
index 00000000..443eff65
--- /dev/null
+++ b/src/hi/simulator/profile/models.py
@@ -0,0 +1,36 @@
+from django.db import models
+
+
+class SimProfile( models.Model ):
+ """Per-module profile of simulator data. Each module (service
+ simulator or weather source) maintains its own profile space —
+ e.g., ``module_key = 'hi.simulator.services.hass'`` profiles are
+ independent of ``module_key = 'hi.simulator.services.zoneminder'``
+ profiles, so an operator can iterate one module's scenario
+ without disturbing another's.
+ """
+
+ module_key = models.CharField(
+ 'Module Key',
+ max_length = 96,
+ )
+ name = models.CharField(
+ 'Profile Name',
+ max_length = 64,
+ )
+ last_switched_to_datetime = models.DateTimeField(
+ 'Last Switched To',
+ null = True,
+ blank = True,
+ )
+ created_datetime = models.DateTimeField(
+ 'Created',
+ auto_now_add = True,
+ )
+
+ class Meta:
+ unique_together = ( 'module_key', 'name' )
+ ordering = [ 'module_key', 'name' ]
+
+ def __str__(self):
+ return f'[{self.module_key}] {self.name}'
diff --git a/src/hi/simulator/profile/module_registry.py b/src/hi/simulator/profile/module_registry.py
new file mode 100644
index 00000000..d1689e1c
--- /dev/null
+++ b/src/hi/simulator/profile/module_registry.py
@@ -0,0 +1,65 @@
+"""Discovery of pluggable simulator modules.
+
+A "module" here is any sub-app of ``hi.simulator.services.*`` or
+``hi.simulator.weather_sources.*``. Each pluggable module declares
+its operator-facing label via a ``simulator_module_label`` class
+attribute on its AppConfig (single convention across services and
+weather sources).
+"""
+import logging
+from dataclasses import dataclass
+from typing import List, Optional
+
+from django.apps import apps as django_apps
+
+
+logger = logging.getLogger(__name__)
+
+
+_MODULE_NAME_PREFIXES = (
+ 'hi.simulator.services.',
+ 'hi.simulator.weather_sources.',
+)
+
+
+@dataclass(frozen=True)
+class SimulatorModule:
+ """Operator-visible identity of a single simulator module."""
+ module_key : str # AppConfig.name (full dotted path)
+ label : str # AppConfig.simulator_module_label
+
+
+def discover_modules() -> List[ SimulatorModule ]:
+ modules : List[ SimulatorModule ] = []
+ for app_config in django_apps.get_app_configs():
+ if not any( app_config.name.startswith( prefix )
+ for prefix in _MODULE_NAME_PREFIXES ):
+ continue
+ # Skip the parent sub-apps themselves (services, weather_sources);
+ # only their sub-sub-apps are pluggable modules.
+ if app_config.name.rstrip('.') in (
+ 'hi.simulator.services',
+ 'hi.simulator.weather_sources' ):
+ continue
+ label = getattr( app_config, 'simulator_module_label', None )
+ if label is None:
+ logger.warning(
+ f'AppConfig {app_config.name} is missing '
+ 'simulator_module_label; module not registered.'
+ )
+ continue
+ modules.append( SimulatorModule(
+ module_key = app_config.name,
+ label = label,
+ ))
+ continue
+ modules.sort( key = lambda m : m.label )
+ return modules
+
+
+def find_module( module_key : str ) -> Optional[ SimulatorModule ]:
+ for module in discover_modules():
+ if module.module_key == module_key:
+ return module
+ continue
+ return None
diff --git a/src/hi/simulator/profile/profile_manager.py b/src/hi/simulator/profile/profile_manager.py
new file mode 100644
index 00000000..c122d60d
--- /dev/null
+++ b/src/hi/simulator/profile/profile_manager.py
@@ -0,0 +1,185 @@
+"""Per-module current-profile state for the simulator.
+
+Singleton. Each module (`module_key`) has its own ``current`` profile.
+Switching one module's profile does not affect any other module.
+Hydrates lazily — first access for a module reads the DB; if the
+module has no profiles, an ``empty`` profile is created.
+"""
+import logging
+import threading
+from typing import Dict, List, Optional
+
+from django.db import transaction
+
+import hi.apps.common.datetimeproxy as datetimeproxy
+from hi.apps.common.singleton import Singleton
+
+from .models import SimProfile
+
+logger = logging.getLogger(__name__)
+
+
+EMPTY_PROFILE_NAME = 'empty'
+
+
+class ProfileManager( Singleton ):
+
+ def __init_singleton__(self):
+ self._current_by_module : Dict[ str, SimProfile ] = {}
+ self._lock = threading.Lock()
+ self._on_switched_callbacks : Dict[ str, list ] = {}
+ return
+
+ def list_profiles( self, module_key : str ) -> List[ SimProfile ]:
+ return list( SimProfile.objects
+ .filter( module_key = module_key )
+ .order_by( 'name' ))
+
+ def get_current( self, module_key : str ) -> SimProfile:
+ with self._lock:
+ cached = self._current_by_module.get( module_key )
+ if cached is not None:
+ # Re-fetch to pick up edits to the row (e.g. rename).
+ try:
+ return SimProfile.objects.get( pk = cached.pk )
+ except SimProfile.DoesNotExist:
+ # Cached entry was deleted out from under us; fall
+ # through to re-pick from DB.
+ self._current_by_module.pop( module_key, None )
+
+ profile = self._pick_current_from_db( module_key )
+ if profile is None:
+ profile = self._auto_create_empty( module_key )
+ self._current_by_module[ module_key ] = profile
+ return profile
+
+ def set_current( self, module_key : str, profile : SimProfile ) -> SimProfile:
+ if profile.module_key != module_key:
+ raise ValueError(
+ f'Profile {profile.pk} belongs to module {profile.module_key!r},'
+ f' not {module_key!r}.'
+ )
+ with transaction.atomic():
+ profile.last_switched_to_datetime = datetimeproxy.now()
+ profile.save( update_fields = [ 'last_switched_to_datetime' ] )
+ with self._lock:
+ self._current_by_module[ module_key ] = profile
+ self._dispatch_switched( module_key, profile )
+ return profile
+
+ def create( self, module_key : str, name : str ) -> SimProfile:
+ profile = SimProfile.objects.create(
+ module_key = module_key,
+ name = name,
+ )
+ return profile
+
+ def clone( self,
+ module_key : str,
+ source_profile : SimProfile,
+ new_name : str ) -> SimProfile:
+ if source_profile.module_key != module_key:
+ raise ValueError(
+ f'Source profile module mismatch: {source_profile.module_key!r}'
+ f' vs {module_key!r}.'
+ )
+ with transaction.atomic():
+ new_profile = SimProfile.objects.create(
+ module_key = module_key,
+ name = new_name,
+ )
+ self._copy_owned_rows(
+ source_profile = source_profile,
+ target_profile = new_profile,
+ )
+ return new_profile
+
+ def delete( self, module_key : str, profile : SimProfile ) -> None:
+ if profile.module_key != module_key:
+ raise ValueError( 'Profile module mismatch on delete.' )
+ with self._lock:
+ cached = self._current_by_module.get( module_key )
+ if cached is not None and cached.pk == profile.pk:
+ self._current_by_module.pop( module_key, None )
+ profile.delete()
+ # Force re-pick of current on next get_current(); also fires the
+ # switched callback so the module reloads against the new current.
+ new_current = self.get_current( module_key )
+ self._dispatch_switched( module_key, new_current )
+ return
+
+ def register_on_switched( self, module_key : str, callback ):
+ """Module registers a callback invoked after every
+ set_current / delete-driven switch for that module_key.
+ Callback signature: ``callback(profile: SimProfile)``."""
+ self._on_switched_callbacks.setdefault( module_key, [] ).append( callback )
+ return
+
+ def _pick_current_from_db( self, module_key : str ) -> Optional[ SimProfile ]:
+ return ( SimProfile.objects
+ .filter( module_key = module_key )
+ .order_by( '-last_switched_to_datetime', 'name' )
+ .first() )
+
+ def _auto_create_empty( self, module_key : str ) -> SimProfile:
+ profile, _created = SimProfile.objects.get_or_create(
+ module_key = module_key,
+ name = EMPTY_PROFILE_NAME,
+ )
+ return profile
+
+ def _dispatch_switched( self, module_key : str, profile : SimProfile ):
+ for callback in self._on_switched_callbacks.get( module_key, () ):
+ try:
+ callback( profile )
+ except Exception:
+ logger.exception(
+ f'Profile-switched callback failed for {module_key!r}'
+ )
+ continue
+ return
+
+ def _copy_owned_rows( self,
+ source_profile : SimProfile,
+ target_profile : SimProfile ) -> None:
+ """Profile rows referencing source via FK get duplicates pointing
+ at target. Each owning sub-app is responsible for handling its
+ own clone via on_profile_cloned callback (future). For now,
+ copy DbSimEntity (services) and NwsSimAlert (nws) by import."""
+ # Imports kept local — these are cross-sub-app references and
+ # we want lazy resolution so the profile sub-app remains
+ # importable in isolation (e.g. management commands that touch
+ # only profiles).
+ from hi.simulator.services.models import DbSimEntity
+ from hi.simulator.weather_sources.nws.models import NwsSimAlert
+
+ DbSimEntity.objects.bulk_create([
+ DbSimEntity(
+ sim_profile = target_profile,
+ entity_fields_class_id = row.entity_fields_class_id,
+ sim_entity_type_str = row.sim_entity_type_str,
+ sim_entity_fields_json = row.sim_entity_fields_json,
+ )
+ for row in source_profile.dbsimentity_set.all()
+ ])
+ NwsSimAlert.objects.bulk_create([
+ NwsSimAlert(
+ sim_profile = target_profile,
+ is_active = row.is_active,
+ event_code = row.event_code,
+ event_name = row.event_name,
+ severity_str = row.severity_str,
+ certainty_str = row.certainty_str,
+ urgency_str = row.urgency_str,
+ status_str = row.status_str,
+ category_str = row.category_str,
+ headline = row.headline,
+ description = row.description,
+ instruction = row.instruction,
+ area_desc = row.area_desc,
+ effective_offset_secs = row.effective_offset_secs,
+ expires_offset_secs = row.expires_offset_secs,
+ )
+ for row in source_profile.nwssimalert_set.all()
+ ])
+ return
diff --git a/src/hi/simulator/profile/templates/profile/modals/profile_clone.html b/src/hi/simulator/profile/templates/profile/modals/profile_clone.html
new file mode 100644
index 00000000..e5cf5900
--- /dev/null
+++ b/src/hi/simulator/profile/templates/profile/modals/profile_clone.html
@@ -0,0 +1,32 @@
+{% extends "modals/action_with_cancel.html" %}
+{% load icons %}
+
+{% block preamble %}
+<form action="{% url 'simulator_profile_clone' module_key=module.module_key profile_id=source_profile.id %}"
+ method="post" class="form" data-async="modal">
+ {% csrf_token %}
+{% endblock %}
+
+{% block title_text %}
+Clone {{ module.label }} Profile
+{% endblock %}
+
+{% block body %}
+<p>
+ Cloning <strong>{{ source_profile.name }}</strong>. The new profile
+ will contain a copy of every simulated entry from the source.
+ Choose a name for the new profile:
+</p>
+{% include "profile/panes/profile_form.html" %}
+{% endblock %}
+
+{% block action_right %}
+<button id="hi-simulator-profile-clone-submit" type="submit" class="btn btn-primary"
+ name="action" value="clone">
+ {% icon "plus" size="sm" css_class="hi-icon-left" %}CLONE
+</button>
+{% endblock %}
+
+{% block postamble %}
+</form>
+{% endblock %}
diff --git a/src/hi/simulator/templates/simulator/modals/sim_profile_create.html b/src/hi/simulator/profile/templates/profile/modals/profile_create.html
similarity index 68%
rename from src/hi/simulator/templates/simulator/modals/sim_profile_create.html
rename to src/hi/simulator/profile/templates/profile/modals/profile_create.html
index ec2d41d9..75a9d049 100644
--- a/src/hi/simulator/templates/simulator/modals/sim_profile_create.html
+++ b/src/hi/simulator/profile/templates/profile/modals/profile_create.html
@@ -2,17 +2,17 @@
{% load icons %}
{% block preamble %}
-<form action="{% url 'simulator_profile_create' %}" method="post"
- class="form" data-async="modal">
+<form action="{% url 'simulator_profile_create' module_key=module.module_key %}"
+ method="post" class="form" data-async="modal">
{% csrf_token %}
{% endblock %}
{% block title_text %}
-Create Simulator Profile
+Create {{ module.label }} Profile
{% endblock %}
{% block body %}
-{% include "simulator/panes/sim_profile_form.html" %}
+{% include "profile/panes/profile_form.html" %}
{% endblock %}
{% block action_right %}
@@ -25,4 +25,3 @@ Create Simulator Profile
{% block postamble %}
</form>
{% endblock %}
-
diff --git a/src/hi/simulator/profile/templates/profile/modals/profile_delete.html b/src/hi/simulator/profile/templates/profile/modals/profile_delete.html
new file mode 100644
index 00000000..8465178c
--- /dev/null
+++ b/src/hi/simulator/profile/templates/profile/modals/profile_delete.html
@@ -0,0 +1,33 @@
+{% extends "modals/action_with_cancel.html" %}
+
+{% block preamble %}
+<form action="{% url 'simulator_profile_delete' module_key=module.module_key profile_id=sim_profile.id %}"
+ method="post" class="form" data-async="modal">
+ {% csrf_token %}
+{% endblock %}
+
+{% block title_text %}
+Delete {{ module.label }} Profile?
+{% endblock %}
+
+{% block body %}
+<p>
+ Delete the <strong>{{ sim_profile.name }}</strong> {{ module.label }}
+ profile? All simulated entries belonging to this profile will be
+ removed.
+</p>
+<p class="text-danger">
+ This action cannot be undone.
+</p>
+{% endblock %}
+
+{% block action_right %}
+<button id="hi-simulator-profile-delete-submit" type="submit" class="btn btn-danger"
+ name="action" value="delete">
+ DELETE
+</button>
+{% endblock %}
+
+{% block postamble %}
+</form>
+{% endblock %}
diff --git a/src/hi/simulator/templates/simulator/modals/sim_profile_edit.html b/src/hi/simulator/profile/templates/profile/modals/profile_edit.html
similarity index 66%
rename from src/hi/simulator/templates/simulator/modals/sim_profile_edit.html
rename to src/hi/simulator/profile/templates/profile/modals/profile_edit.html
index 4b7609f9..6e34b571 100644
--- a/src/hi/simulator/templates/simulator/modals/sim_profile_edit.html
+++ b/src/hi/simulator/profile/templates/profile/modals/profile_edit.html
@@ -2,17 +2,17 @@
{% load icons %}
{% block preamble %}
-<form action="{% url 'simulator_profile_edit' profile_id=sim_profile_form.instance.id %}" method="post"
- class="form" data-async="modal">
+<form action="{% url 'simulator_profile_edit' module_key=module.module_key profile_id=sim_profile.id %}"
+ method="post" class="form" data-async="modal">
{% csrf_token %}
{% endblock %}
{% block title_text %}
-Edit Simulator Profile
+Edit {{ module.label }} Profile
{% endblock %}
{% block body %}
-{% include "simulator/panes/sim_profile_form.html" %}
+{% include "profile/panes/profile_form.html" %}
{% endblock %}
{% block action_right %}
@@ -25,4 +25,3 @@ Edit Simulator Profile
{% block postamble %}
</form>
{% endblock %}
-
diff --git a/src/hi/simulator/templates/simulator/panes/sim_profile_form.html b/src/hi/simulator/profile/templates/profile/panes/profile_form.html
similarity index 100%
rename from src/hi/simulator/templates/simulator/panes/sim_profile_form.html
rename to src/hi/simulator/profile/templates/profile/panes/profile_form.html
diff --git a/src/hi/simulator/profile/templates/profile/panes/profile_selector.html b/src/hi/simulator/profile/templates/profile/panes/profile_selector.html
new file mode 100644
index 00000000..a2e32960
--- /dev/null
+++ b/src/hi/simulator/profile/templates/profile/panes/profile_selector.html
@@ -0,0 +1,54 @@
+{% load icons %}
+{% comment %}
+Per-module profile selector — dropdown + kebab actions menu.
+Each module's tab includes this with:
+ - module : SimulatorModule (module_key + label)
+ - profile_list : List[SimProfile]
+ - current_profile : SimProfile
+{% endcomment %}
+<div class="sim-profile-selector d-inline-flex align-items-center">
+ <div class="dropdown mr-1">
+ <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button"
+ id="hi-profile-switch-{{ module.module_key }}"
+ data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
+ Profile: <strong>{{ current_profile.name }}</strong>
+ </button>
+ <div class="dropdown-menu"
+ aria-labelledby="hi-profile-switch-{{ module.module_key }}">
+ {% for profile in profile_list %}
+ <a class="dropdown-item plain {% if profile.id == current_profile.id %}active{% endif %}"
+ href="{% url 'simulator_profile_switch' module_key=module.module_key profile_id=profile.id %}">
+ {{ profile.name }}
+ </a>
+ {% endfor %}
+ </div>
+ </div>
+ <div class="dropdown">
+ <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button"
+ id="hi-profile-actions-{{ module.module_key }}"
+ data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"
+ title="Profile actions">
+ {% icon "settings" size="sm" %}
+ </button>
+ <div class="dropdown-menu"
+ aria-labelledby="hi-profile-actions-{{ module.module_key }}">
+ <a class="dropdown-item plain" data-async="modal"
+ href="{% url 'simulator_profile_create' module_key=module.module_key %}">
+ {% icon "plus" size="sm" css_class="hi-icon-left" %}New Profile…
+ </a>
+ <a class="dropdown-item plain" data-async="modal"
+ href="{% url 'simulator_profile_edit' module_key=module.module_key profile_id=current_profile.id %}">
+ {% icon "edit" size="sm" css_class="hi-icon-left" %}Rename…
+ </a>
+ <a class="dropdown-item plain" data-async="modal"
+ href="{% url 'simulator_profile_clone' module_key=module.module_key profile_id=current_profile.id %}">
+ {% icon "copy" size="sm" css_class="hi-icon-left" %}Clone…
+ </a>
+ <div class="dropdown-divider"></div>
+ <a class="dropdown-item plain text-danger" data-async="modal"
+ href="{% url 'simulator_profile_delete' module_key=module.module_key profile_id=current_profile.id %}">
+ {% icon "delete" size="sm" css_class="hi-icon-left" %}Delete…
+ </a>
+ </div>
+ </div>
+</div>
diff --git a/src/hi/simulator/profile/urls.py b/src/hi/simulator/profile/urls.py
new file mode 100644
index 00000000..f2129b16
--- /dev/null
+++ b/src/hi/simulator/profile/urls.py
@@ -0,0 +1,26 @@
+from django.urls import path
+
+from . import views
+
+
+urlpatterns = [
+ path( '<str:module_key>/create',
+ views.CreateProfileView.as_view(),
+ name = 'simulator_profile_create' ),
+
+ path( '<str:module_key>/edit/<int:profile_id>',
+ views.EditProfileView.as_view(),
+ name = 'simulator_profile_edit' ),
+
+ path( '<str:module_key>/clone/<int:profile_id>',
+ views.CloneProfileView.as_view(),
+ name = 'simulator_profile_clone' ),
+
+ path( '<str:module_key>/delete/<int:profile_id>',
+ views.DeleteProfileView.as_view(),
+ name = 'simulator_profile_delete' ),
+
+ path( '<str:module_key>/switch/<int:profile_id>',
+ views.SwitchProfileView.as_view(),
+ name = 'simulator_profile_switch' ),
+]
diff --git a/src/hi/simulator/profile/views.py b/src/hi/simulator/profile/views.py
new file mode 100644
index 00000000..2bd8b76c
--- /dev/null
+++ b/src/hi/simulator/profile/views.py
@@ -0,0 +1,170 @@
+from django.core.exceptions import BadRequest
+from django.db import transaction
+from django.http import HttpResponseRedirect
+from django.shortcuts import get_object_or_404, render
+from django.urls import reverse
+from django.views.generic import View
+
+import hi.apps.common.antinode as antinode
+
+from . import forms
+from .models import SimProfile
+from .module_registry import find_module
+from .profile_manager import ProfileManager
+
+
+def _resolve_module( module_key : str ):
+ module = find_module( module_key )
+ if module is None:
+ raise BadRequest( f'Unknown simulator module: {module_key!r}' )
+ return module
+
+
+class CreateProfileView( View ):
+
+ MODAL_TEMPLATE_NAME = 'profile/modals/profile_create.html'
+
+ def get(self, request, module_key, *args, **kwargs):
+ module = _resolve_module( module_key )
+ context = {
+ 'module': module,
+ 'sim_profile_form': forms.SimProfileForm(),
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+ def post(self, request, module_key, *args, **kwargs):
+ module = _resolve_module( module_key )
+ form = forms.SimProfileForm( request.POST )
+ if not form.is_valid():
+ context = {
+ 'module': module,
+ 'sim_profile_form': form,
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+ new_profile = ProfileManager().create(
+ module_key = module_key,
+ name = form.cleaned_data[ 'name' ],
+ )
+ ProfileManager().set_current( module_key, new_profile )
+ return antinode.refresh_response()
+
+
+class EditProfileView( View ):
+
+ MODAL_TEMPLATE_NAME = 'profile/modals/profile_edit.html'
+
+ def get(self, request, module_key, profile_id, *args, **kwargs):
+ module = _resolve_module( module_key )
+ profile = get_object_or_404( SimProfile, pk = profile_id,
+ module_key = module_key )
+ context = {
+ 'module': module,
+ 'sim_profile': profile,
+ 'sim_profile_form': forms.SimProfileForm( instance = profile ),
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+ def post(self, request, module_key, profile_id, *args, **kwargs):
+ module = _resolve_module( module_key )
+ profile = get_object_or_404( SimProfile, pk = profile_id,
+ module_key = module_key )
+ form = forms.SimProfileForm( request.POST, instance = profile )
+ if not form.is_valid():
+ context = {
+ 'module': module,
+ 'sim_profile': profile,
+ 'sim_profile_form': form,
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+ form.save()
+ return antinode.refresh_response()
+
+
+class CloneProfileView( View ):
+
+ MODAL_TEMPLATE_NAME = 'profile/modals/profile_clone.html'
+
+ def get(self, request, module_key, profile_id, *args, **kwargs):
+ module = _resolve_module( module_key )
+ source_profile = get_object_or_404( SimProfile, pk = profile_id,
+ module_key = module_key )
+ context = {
+ 'module': module,
+ 'source_profile': source_profile,
+ 'sim_profile_form': forms.SimProfileForm(
+ initial = { 'name': self._suggest_name( source_profile ) },
+ ),
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+ def post(self, request, module_key, profile_id, *args, **kwargs):
+ module = _resolve_module( module_key )
+ source_profile = get_object_or_404( SimProfile, pk = profile_id,
+ module_key = module_key )
+ form = forms.SimProfileForm( request.POST )
+ if not form.is_valid():
+ context = {
+ 'module': module,
+ 'source_profile': source_profile,
+ 'sim_profile_form': form,
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+ with transaction.atomic():
+ new_profile = ProfileManager().clone(
+ module_key = module_key,
+ source_profile = source_profile,
+ new_name = form.cleaned_data[ 'name' ],
+ )
+ ProfileManager().set_current( module_key, new_profile )
+ return antinode.refresh_response()
+
+ @staticmethod
+ def _suggest_name( source_profile : SimProfile ) -> str:
+ candidate = f'{source_profile.name} (copy)'
+ if not SimProfile.objects.filter(
+ module_key = source_profile.module_key,
+ name = candidate ).exists():
+ return candidate
+ for index in range( 2, 100 ):
+ candidate = f'{source_profile.name} (copy {index})'
+ if not SimProfile.objects.filter(
+ module_key = source_profile.module_key,
+ name = candidate ).exists():
+ return candidate
+ return f'{source_profile.name} (copy)'
+
+
+class DeleteProfileView( View ):
+
+ MODAL_TEMPLATE_NAME = 'profile/modals/profile_delete.html'
+
+ def get(self, request, module_key, profile_id, *args, **kwargs):
+ module = _resolve_module( module_key )
+ profile = get_object_or_404( SimProfile, pk = profile_id,
+ module_key = module_key )
+ context = {
+ 'module': module,
+ 'sim_profile': profile,
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+ def post(self, request, module_key, profile_id, *args, **kwargs):
+ _resolve_module( module_key )
+ profile = get_object_or_404( SimProfile, pk = profile_id,
+ module_key = module_key )
+ ProfileManager().delete( module_key = module_key, profile = profile )
+ return antinode.refresh_response()
+
+
+class SwitchProfileView( View ):
+
+ def get(self, request, module_key, profile_id, *args, **kwargs):
+ _resolve_module( module_key )
+ profile = get_object_or_404( SimProfile, pk = profile_id,
+ module_key = module_key )
+ ProfileManager().set_current( module_key = module_key, profile = profile )
+ # Profile switching is always initiated from the tab being
+ # switched, so reloading the page that issued the request lands
+ # the user back on the same tab.
+ referer = request.META.get( 'HTTP_REFERER' )
+ return HttpResponseRedirect( referer or reverse( 'simulator_home' ))
diff --git a/src/hi/simulator/services/__init__.py b/src/hi/simulator/services/__init__.py
index e69de29b..ab4149df 100644
--- a/src/hi/simulator/services/__init__.py
+++ b/src/hi/simulator/services/__init__.py
@@ -0,0 +1 @@
+default_app_config = 'hi.simulator.services.apps.ServicesConfig'
diff --git a/src/hi/simulator/services/admin.py b/src/hi/simulator/services/admin.py
new file mode 100644
index 00000000..518c94ba
--- /dev/null
+++ b/src/hi/simulator/services/admin.py
@@ -0,0 +1,21 @@
+from django.contrib import admin
+
+from . import models
+
+
[email protected]( models.DbSimEntity )
+class DbSimEntityAdmin( admin.ModelAdmin ):
+
+ show_full_result_count = False
+
+ list_display = (
+ 'sim_profile',
+ 'entity_fields_class_id',
+ 'sim_entity_type_str',
+ 'sim_entity_fields_json',
+ 'updated_datetime',
+ 'created_datetime',
+ )
+
+ search_fields = [ 'entity_fields_class_id' ]
+ readonly_fields = ( 'updated_datetime', 'created_datetime' )
diff --git a/src/hi/simulator/services/apps.py b/src/hi/simulator/services/apps.py
new file mode 100644
index 00000000..3c5b9d3c
--- /dev/null
+++ b/src/hi/simulator/services/apps.py
@@ -0,0 +1,28 @@
+import os
+import sys
+
+from django.apps import AppConfig
+
+
+class ServicesConfig( AppConfig ):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'hi.simulator.services'
+
+ def ready(self):
+ import time
+ from hi.apps.common.asyncio_utils import start_background_event_loop
+ from .service_simulator_manager import ServiceSimulatorManager
+
+ if os.environ.get('RUN_MAIN') != 'true':
+ return
+
+ if (( 'gunicorn' in os.environ.get( 'SERVER_SOFTWARE', '' ))
+ or ( 'gunicorn' in sys.argv[0] )):
+ return
+
+ # Django's ready() fires before the system is fully usable.
+ time.sleep(1)
+ start_background_event_loop(
+ task_function = ServiceSimulatorManager().initialize,
+ )
+ return
diff --git a/src/hi/simulator/base_models.py b/src/hi/simulator/services/base_models.py
similarity index 94%
rename from src/hi/simulator/base_models.py
rename to src/hi/simulator/services/base_models.py
index d47a4789..fe3b590f 100644
--- a/src/hi/simulator/base_models.py
+++ b/src/hi/simulator/services/base_models.py
@@ -13,8 +13,8 @@ class SimEntityFields:
Base class that simulators should extend to add extra (editable) fields
needed to define for a specific simulator entity. Simulators should
define one or more subclasses of this and make those known to the
- SimulatorManager through the sim_entity_definition_list() method of the
- Simulator class (using the SimEntityDefinition class).
+ ServiceSimulatorManager through the sim_entity_definition_list() method of the
+ ServiceSimulator class (using the SimEntityDefinition class).
"""
name : str
@@ -81,13 +81,12 @@ class SimState:
states for a simulator entity. A simulator entity will provide one or
more SimState subclasses. SimState classes are provided via the
SimEntityDefinition and will be initialized with the containing
- entities fields and values by the SimulatorManager.
+ entities fields and values by the ServiceSimulatorManager.
SimState definitions and instances are not persisted in the database.
"""
- # These fields are provided by SimulatorManager when creating instances.
- simulator_id : str
+ # These fields are provided by ServiceSimulatorManager when creating instances.
sim_entity_id : int
sim_entity_fields : SimEntityFields
@@ -154,7 +153,7 @@ class SimState:
@dataclass
class SimEntityDefinition:
"""
- Used by Simulator instances to define a simulated entity that is
+ Used by ServiceSimulator instances to define a simulated entity that is
available to be defined and added to the simulator configuration. Each
type of simulated entity should also provide one or more SimState
subclasses that will be used to track the state/status of the simulation.
diff --git a/src/hi/simulator/enums.py b/src/hi/simulator/services/enums.py
similarity index 83%
rename from src/hi/simulator/enums.py
rename to src/hi/simulator/services/enums.py
index 7077630d..7a59643a 100644
--- a/src/hi/simulator/enums.py
+++ b/src/hi/simulator/services/enums.py
@@ -10,40 +10,40 @@ class SimStateType(LabeledEnum):
# Specific types
AIR_PRESSURE = ( 'Air Pressure' , '' )
BANDWIDTH_USAGE = ( 'Bandwidth Usage' , '' )
- CONNECTIVITY = ( 'Connectivity' , '' )
+ CONNECTIVITY = ( 'Connectivity' , '' )
DATETIME = ( 'Date/Time' , '' )
ELECTRIC_USAGE = ( 'Electric Usage' , '' )
- HIGH_LOW = ( 'High/Low' , '' )
+ HIGH_LOW = ( 'High/Low' , '' )
HUMIDITY = ( 'Humidity' , '' )
LIGHT_LEVEL = ( 'Light Level' , '' )
MOISTURE = ( 'Moisture' , '' )
- MOVEMENT = ( 'Movement' , '' )
- ON_OFF = ( 'On/Off' , '' )
- OPEN_CLOSE = ( 'Open/Close' , '' )
+ MOVEMENT = ( 'Movement' , '' )
+ ON_OFF = ( 'On/Off' , '' )
+ OPEN_CLOSE = ( 'Open/Close' , '' )
PRESENCE = ( 'Presence' , '' )
SOUND_LEVEL = ( 'Sound Level' , '' )
TEMPERATURE = ( 'Temperature' , '' )
WATER_FLOW = ( 'Water Flow' , '' )
WIND_SPEED = ( 'Wind Speed' , '' )
-
+
@classmethod
def default(cls):
return cls.DISCRETE
-
+
def template_name(self):
"""
Template used to render the simulator control for this state. Create the
template at the given location to define a state-specific rendering, else
it will fallback to the default template of
- "simulator/panes/sim_control_default.html"
+ "services/panes/sim_control_default.html"
"""
- return f'simulator/panes/sim_control_{self.name.lower()}.html'
+ return f'services/panes/sim_control_{self.name.lower()}.html'
+
-
-class SimulatorFaultMode(LabeledEnum):
+class ServiceFaultMode(LabeledEnum):
"""
Fault-injection state for a simulated service. Set per-simulator from
- the simulator UI; consumed by SimulatorFaultInjectionMiddleware to
+ the simulator UI; consumed by ServiceFaultInjectionMiddleware to
short-circuit API responses so the main app's integration
test_connection probe paths can be exercised without standing up real
misbehaving servers.
@@ -60,21 +60,6 @@ class SimulatorFaultMode(LabeledEnum):
return cls.HEALTHY
-class SimTemperatureUnit(LabeledEnum):
- """Integration-agnostic temperature unit choice for the
- simulator's runtime override. Each integration's composer maps
- these to its own wire format (e.g., HA uses ``°F`` / ``°C``;
- other integrations may use ``degF`` / ``degC`` or other
- conventions)."""
-
- FAHRENHEIT = ( 'Fahrenheit', '' )
- CELSIUS = ( 'Celsius', '' )
-
- @classmethod
- def default(cls):
- return cls.FAHRENHEIT
-
-
class SimEntityType(LabeledEnum):
AIR_CONDITIONER = ( 'Air Conditioner', '' )
@@ -130,7 +115,7 @@ class SimEntityType(LabeledEnum):
THERMOMETER = ( 'Thermometer', '' )
THERMOSTAT = ( 'Thermostat', '' )
TIME_SOURCE = ( 'Time Source', '' )
- TOILET = ( 'Toilet', '' )
+ TOILET = ( 'Toilet', '' )
TOOL = ( 'Tool', '' )
VIDEO_PLAYER = ( 'Video Player', '' )
WALL_SWITCH = ( 'Wall Switch', '' )
@@ -140,7 +125,7 @@ class SimEntityType(LabeledEnum):
WATER_SHUTOFF_VALVE = ( 'Water Shutoff Valve', '' )
WEATHER_STATION = ( 'Weather Station', '' )
WINDOW = ( 'Window', '' )
-
+
@classmethod
def default(cls):
return cls.OTHER
diff --git a/src/hi/simulator/exceptions.py b/src/hi/simulator/services/exceptions.py
similarity index 100%
rename from src/hi/simulator/exceptions.py
rename to src/hi/simulator/services/exceptions.py
diff --git a/src/hi/simulator/forms.py b/src/hi/simulator/services/forms.py
similarity index 96%
rename from src/hi/simulator/forms.py
rename to src/hi/simulator/services/forms.py
index 9d55928e..98dc91e4 100644
--- a/src/hi/simulator/forms.py
+++ b/src/hi/simulator/services/forms.py
@@ -5,16 +5,6 @@ from typing import Type
from django import forms
from .base_models import SimEntityFields
-from .models import SimProfile
-
-
-class SimProfileForm( forms.ModelForm ):
-
- class Meta:
- model = SimProfile
- fields = (
- 'name',
- )
class SimEntityFieldsForm( forms.Form ):
diff --git a/src/hi/simulator/services/hass/api_composers.py b/src/hi/simulator/services/hass/api_composers.py
index c01800ad..b0c6c0ec 100644
--- a/src/hi/simulator/services/hass/api_composers.py
+++ b/src/hi/simulator/services/hass/api_composers.py
@@ -22,7 +22,7 @@ it per SimEntity and concatenates the results.
"""
from typing import Dict, List
-from hi.simulator.base_models import SimState
+from hi.simulator.services.base_models import SimState
from .sim_models import (
HassCameraMotionDetectionState,
diff --git a/src/hi/simulator/services/hass/apps.py b/src/hi/simulator/services/hass/apps.py
index 60c6a9ae..c8a18d42 100644
--- a/src/hi/simulator/services/hass/apps.py
+++ b/src/hi/simulator/services/hass/apps.py
@@ -1,6 +1,7 @@
from django.apps import AppConfig
-class HassConfig(AppConfig):
- default_auto_field = "django.db.models.BigAutoField"
- name = "hi.simulator.services.hass"
+class HassConfig( AppConfig ):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'hi.simulator.services.hass'
+ simulator_module_label = 'Home Assistant'
diff --git a/src/hi/simulator/services/hass/service_dispatchers.py b/src/hi/simulator/services/hass/service_dispatchers.py
index f7bc125e..259c9db8 100644
--- a/src/hi/simulator/services/hass/service_dispatchers.py
+++ b/src/hi/simulator/services/hass/service_dispatchers.py
@@ -26,7 +26,7 @@ list. ``color_temp_kelvin`` is degrees Kelvin.
"""
from typing import Any, Dict, List, Optional, Tuple
-from hi.simulator.enums import SimStateType
+from hi.simulator.services.enums import SimStateType
from .unit_translation import UnitTranslationHelper
from .sim_models import (
diff --git a/src/hi/simulator/services/hass/sim_models.py b/src/hi/simulator/services/hass/sim_models.py
index 0acf5a89..1d9ad4ec 100644
--- a/src/hi/simulator/services/hass/sim_models.py
+++ b/src/hi/simulator/services/hass/sim_models.py
@@ -8,8 +8,8 @@ from typing import ClassVar, Dict, List, Tuple
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.common.utils import str_to_bool
-from hi.simulator.base_models import SimEntityFields, SimState, SimEntityDefinition
-from hi.simulator.enums import SimEntityType, SimStateType
+from hi.simulator.services.base_models import SimEntityFields, SimState, SimEntityDefinition
+from hi.simulator.services.enums import SimEntityType, SimStateType
@dataclass
diff --git a/src/hi/simulator/services/hass/simulator.py b/src/hi/simulator/services/hass/simulator.py
index 87073dd0..ab8fafd4 100644
--- a/src/hi/simulator/services/hass/simulator.py
+++ b/src/hi/simulator/services/hass/simulator.py
@@ -1,14 +1,14 @@
from typing import List, Set
-from hi.simulator.base_models import SimEntityDefinition, SimEntityFields, SimState
-from hi.simulator.exceptions import SimEntityValidationError
-from hi.simulator.simulator import Simulator
-from hi.simulator.sim_entity import SimEntity
+from hi.simulator.services.base_models import SimEntityDefinition, SimEntityFields, SimState
+from hi.simulator.services.exceptions import SimEntityValidationError
+from hi.simulator.services.service_simulator import ServiceSimulator
+from hi.simulator.services.sim_entity import SimEntity
from .sim_models import HASS_SIM_ENTITY_DEFINITION_LIST, HassInsteonSimEntityFields, HassState
-class HassSimulator( Simulator ):
+class HassSimulator( ServiceSimulator ):
@property
def id(self):
@@ -18,6 +18,10 @@ class HassSimulator( Simulator ):
def label(self):
return 'Home Assistant'
+ @property
+ def integration_urls(self):
+ return [ ( 'API URL', 'services/hass' ) ]
+
def get_hass_sim_state_list( self ) -> List[ HassState ]:
sim_state_list = list()
for sim_entity in self.sim_entities:
diff --git a/src/hi/simulator/services/hass/tests/test_unit_translation.py b/src/hi/simulator/services/hass/tests/test_unit_translation.py
index 7bf49976..80eeb847 100644
--- a/src/hi/simulator/services/hass/tests/test_unit_translation.py
+++ b/src/hi/simulator/services/hass/tests/test_unit_translation.py
@@ -3,7 +3,7 @@ from unittest.mock import patch
from django.test import TestCase
-from hi.simulator.enums import SimTemperatureUnit
+from hi.simulator.settings.enums import SimTemperatureUnit
from hi.simulator.services.hass.unit_translation import UnitTranslationHelper
logging.disable(logging.CRITICAL)
diff --git a/src/hi/simulator/services/hass/unit_translation.py b/src/hi/simulator/services/hass/unit_translation.py
index a38abe6d..3c5c878a 100644
--- a/src/hi/simulator/services/hass/unit_translation.py
+++ b/src/hi/simulator/services/hass/unit_translation.py
@@ -15,8 +15,8 @@ purely at this boundary.
"""
from typing import Optional
-from hi.simulator.enums import SimTemperatureUnit
-from hi.simulator.runtime_settings import SimulatorRuntimeSettings
+from hi.simulator.settings.enums import SimTemperatureUnit
+from hi.simulator.settings.runtime_settings import SimulatorRuntimeSettings
class UnitTranslationHelper:
diff --git a/src/hi/simulator/services/homebox/apps.py b/src/hi/simulator/services/homebox/apps.py
index 9c2327d4..db4b49f2 100644
--- a/src/hi/simulator/services/homebox/apps.py
+++ b/src/hi/simulator/services/homebox/apps.py
@@ -1,6 +1,7 @@
from django.apps import AppConfig
-class HomeBoxConfig(AppConfig):
- default_auto_field = "django.db.models.BigAutoField"
- name = "hi.simulator.services.homebox"
+class HomeBoxConfig( AppConfig ):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'hi.simulator.services.homebox'
+ simulator_module_label = 'HomeBox'
diff --git a/src/hi/simulator/services/homebox/sim_models.py b/src/hi/simulator/services/homebox/sim_models.py
index 6b6d7a55..09bb9684 100644
--- a/src/hi/simulator/services/homebox/sim_models.py
+++ b/src/hi/simulator/services/homebox/sim_models.py
@@ -15,8 +15,8 @@ from typing import Any, Dict, List
from hi.apps.common.utils import str_to_bool
-from hi.simulator.base_models import SimEntityFields, SimState, SimEntityDefinition
-from hi.simulator.enums import SimEntityType, SimStateType
+from hi.simulator.services.base_models import SimEntityFields, SimState, SimEntityDefinition
+from hi.simulator.services.enums import SimEntityType, SimStateType
from .attachment_catalog import (
attachment_choices,
diff --git a/src/hi/simulator/services/homebox/simulator.py b/src/hi/simulator/services/homebox/simulator.py
index b4e90ac6..8352e088 100644
--- a/src/hi/simulator/services/homebox/simulator.py
+++ b/src/hi/simulator/services/homebox/simulator.py
@@ -1,7 +1,7 @@
from typing import List
-from hi.simulator.base_models import SimEntityDefinition
-from hi.simulator.simulator import Simulator
+from hi.simulator.services.base_models import SimEntityDefinition
+from hi.simulator.services.service_simulator import ServiceSimulator
from .sim_models import (
HOMEBOX_SIM_ENTITY_DEFINITION_LIST,
@@ -10,7 +10,7 @@ from .sim_models import (
)
-class HomeBoxSimulator( Simulator ):
+class HomeBoxSimulator( ServiceSimulator ):
@property
def id(self):
@@ -20,6 +20,10 @@ class HomeBoxSimulator( Simulator ):
def label(self):
return 'HomeBox'
+ @property
+ def integration_urls(self):
+ return [ ( 'API URL', 'services/homebox/api' ) ]
+
@property
def sim_entity_definition_list(self) -> List[ SimEntityDefinition ]:
return HOMEBOX_SIM_ENTITY_DEFINITION_LIST
diff --git a/src/hi/simulator/middleware.py b/src/hi/simulator/services/middleware.py
similarity index 74%
rename from src/hi/simulator/middleware.py
rename to src/hi/simulator/services/middleware.py
index 58c3473e..44dcf232 100644
--- a/src/hi/simulator/middleware.py
+++ b/src/hi/simulator/services/middleware.py
@@ -5,29 +5,13 @@ import time
from django.http import HttpResponse, JsonResponse
-from .enums import SimulatorFaultMode
-from .sim_view_parameters import SimViewParameters
-from .simulator_manager import SimulatorManager
+from .enums import ServiceFaultMode
+from .service_simulator_manager import ServiceSimulatorManager
logger = logging.getLogger(__name__)
-class SimViewMiddleware:
-
- def __init__(self, get_response):
- self.get_response = get_response
- return
-
- def __call__(self, request):
- self._set_sim_view_parameters( request )
- return self.get_response( request )
-
- def _set_sim_view_parameters( self, request ):
- request.sim_view_parameters = SimViewParameters.from_session( request )
- return
-
-
-class SimulatorFaultInjectionMiddleware:
+class ServiceFaultInjectionMiddleware:
"""
Intercepts requests under /services/<short_name>/<...> and applies the
target simulator's current fault mode. Lets manual end-to-end testing
@@ -63,27 +47,27 @@ class SimulatorFaultInjectionMiddleware:
return self.get_response( request )
fault_mode = simulator.fault_mode
- if fault_mode == SimulatorFaultMode.HEALTHY:
+ if fault_mode == ServiceFaultMode.HEALTHY:
return self.get_response( request )
- if fault_mode == SimulatorFaultMode.AUTH_FAIL:
+ if fault_mode == ServiceFaultMode.AUTH_FAIL:
return JsonResponse(
{ 'message': 'Unauthorized' },
status = 401,
)
- if fault_mode == SimulatorFaultMode.SERVER_ERROR:
+ if fault_mode == ServiceFaultMode.SERVER_ERROR:
return JsonResponse(
{ 'message': 'Internal server error' },
status = 500,
)
- if fault_mode == SimulatorFaultMode.SLOW:
+ if fault_mode == ServiceFaultMode.SLOW:
logger.debug( f'Fault injection: sleeping {self.SLOW_FAULT_SECS}s for {request.path}' )
time.sleep( self.SLOW_FAULT_SECS )
return self.get_response( request )
- if fault_mode == SimulatorFaultMode.NON_JSON:
+ if fault_mode == ServiceFaultMode.NON_JSON:
return HttpResponse(
b'<html><body>simulated non-JSON response</body></html>',
content_type = 'text/html',
@@ -96,7 +80,7 @@ class SimulatorFaultInjectionMiddleware:
# No cache — the lookup is cheap (small list, dict comprehension)
# and avoids staleness if the simulator registry is ever changed
# at runtime (e.g., test isolation, future dynamic registration).
- for sim_data in SimulatorManager().get_simulator_data_list():
+ for sim_data in ServiceSimulatorManager().get_simulator_data_list():
if sim_data.simulator.url_path_segment == short_name:
return sim_data.simulator
return None
diff --git a/src/hi/simulator/migrations/0001_initial.py b/src/hi/simulator/services/migrations/0001_initial.py
similarity index 55%
rename from src/hi/simulator/migrations/0001_initial.py
rename to src/hi/simulator/services/migrations/0001_initial.py
index 40c26743..45e88bd4 100644
--- a/src/hi/simulator/migrations/0001_initial.py
+++ b/src/hi/simulator/services/migrations/0001_initial.py
@@ -1,51 +1,18 @@
-# Generated by Django 4.2.15 on 2025-02-02 16:19
+# Generated by Django 5.2.14 on 2026-05-19 20:11
-from django.db import migrations, models
import django.db.models.deletion
-import django.utils.timezone
+from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
- dependencies = []
+ dependencies = [
+ ("simulator_profile", "0001_initial"),
+ ]
operations = [
- migrations.CreateModel(
- name="SimProfile",
- fields=[
- (
- "id",
- models.BigAutoField(
- auto_created=True,
- primary_key=True,
- serialize=False,
- verbose_name="ID",
- ),
- ),
- (
- "name",
- models.CharField(max_length=128, unique=True, verbose_name="Name"),
- ),
- (
- "last_switched_to_datetime",
- models.DateTimeField(
- default=django.utils.timezone.now,
- verbose_name="Last Switched To",
- ),
- ),
- (
- "created_datetime",
- models.DateTimeField(auto_now_add=True, verbose_name="Created"),
- ),
- ],
- options={
- "verbose_name": "Simulator Profile",
- "verbose_name_plural": "Simulator Profiles",
- "ordering": ["-last_switched_to_datetime"],
- },
- ),
migrations.CreateModel(
name="DbSimEntity",
fields=[
@@ -58,10 +25,6 @@ class Migration(migrations.Migration):
verbose_name="ID",
),
),
- (
- "simulator_id",
- models.CharField(max_length=64, verbose_name="Simulator Id"),
- ),
(
"entity_fields_class_id",
models.CharField(
@@ -89,7 +52,7 @@ class Migration(migrations.Migration):
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="db_sim_entities",
- to="simulator.simprofile",
+ to="simulator_profile.simprofile",
verbose_name="Simulator Profile",
),
),
diff --git a/src/hi/simulator/services/migrations/__init__.py b/src/hi/simulator/services/migrations/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/simulator/models.py b/src/hi/simulator/services/models.py
similarity index 60%
rename from src/hi/simulator/models.py
rename to src/hi/simulator/services/models.py
index 7fbb6b16..42bfdc34 100644
--- a/src/hi/simulator/models.py
+++ b/src/hi/simulator/services/models.py
@@ -1,37 +1,11 @@
from django.db import models
-from django.utils.timezone import now
-from .enums import SimEntityType
-
-
-class SimProfile(models.Model):
+from hi.simulator.profile.models import SimProfile
- name = models.CharField(
- 'Name',
- max_length = 128,
- null = False, blank = False,
- unique = True,
- )
- last_switched_to_datetime = models.DateTimeField(
- 'Last Switched To',
- default = now,
- )
- created_datetime = models.DateTimeField(
- 'Created',
- auto_now_add = True,
- blank = True,
- )
-
- class Meta:
- verbose_name = 'Simulator Profile'
- verbose_name_plural = 'Simulator Profiles'
- ordering = [ '-last_switched_to_datetime' ]
+from .enums import SimEntityType
- def __str__(self):
- return f'{self.name} [{self.id}]'
-
-class DbSimEntity(models.Model):
+class DbSimEntity( models.Model ):
sim_profile = models.ForeignKey(
SimProfile,
@@ -39,11 +13,6 @@ class DbSimEntity(models.Model):
verbose_name = 'Simulator Profile',
on_delete = models.CASCADE,
)
- simulator_id = models.CharField(
- 'Simulator Id',
- max_length = 64,
- null = False, blank = False,
- )
entity_fields_class_id = models.CharField(
'Entity Fields Class Id',
max_length = 255,
@@ -53,7 +22,7 @@ class DbSimEntity(models.Model):
'Entity Type',
max_length = 32,
null = False, blank = False,
- )
+ )
sim_entity_fields_json = models.JSONField(
'Entity Fields',
default = dict,
@@ -68,7 +37,7 @@ class DbSimEntity(models.Model):
auto_now=True,
blank = True,
)
-
+
class Meta:
verbose_name = 'Simulator Entity'
verbose_name_plural = 'Simulator Entities'
diff --git a/src/hi/simulator/simulator.py b/src/hi/simulator/services/service_simulator.py
similarity index 75%
rename from src/hi/simulator/simulator.py
rename to src/hi/simulator/services/service_simulator.py
index 02c5eb57..e2e7ffaa 100644
--- a/src/hi/simulator/simulator.py
+++ b/src/hi/simulator/services/service_simulator.py
@@ -3,13 +3,13 @@ from typing import Dict, List
from hi.apps.common.singleton import Singleton
from .base_models import SimEntityDefinition, SimEntityFields, SimState
-from .enums import SimulatorFaultMode
+from .enums import ServiceFaultMode
from .sim_entity import SimEntity
-class Simulator( Singleton ):
+class ServiceSimulator( Singleton ):
"""
- Defining a Simulator
+ Defining a ServiceSimulator
- Each simulator should subclass this in a file named "simulator.py" in
its app directory.
@@ -17,7 +17,7 @@ class Simulator( Singleton ):
- The simulator's app directory should be located in the "simulator/services"
subdirectory.
- - The SimulatorManager will auto-discovery all simulators with a
+ - The ServiceSimulatorManager will auto-discovery all simulators with a
simulator.py file in that services directopry.
- The simulator should also define a urls.py and views.py file with the
@@ -38,17 +38,17 @@ class Simulator( Singleton ):
adjustable. The API views of the simulator should convert those
entities and current state values into the proper API responses.
- - The SimulatorManager is responsible for creating SimEntity instances
+ - The ServiceSimulatorManager is responsible for creating SimEntity instances
and for updating the values of then SimState instances.
- SimEntity definitions are persisted in the database with DbSimEntity,
but ther SimState definitions and values are not persisted. e.g., A
simulator server restart will lose any current SimState values.
- - The SimulatorManager also supports defining and switching between
+ - The ServiceSimulatorManager also supports defining and switching between
different simulation profiles, each with its own set of SimEntity
definitions. The individual simulator subclasses do not need to be
- aware of this as the SimulatorManager creates a new simulator
+ aware of this as the ServiceSimulatorManager creates a new simulator
subclass instance for each profile.
"""
@@ -57,7 +57,7 @@ class Simulator( Singleton ):
# Set BEFORE initialize() so that a SimProfile switch — which
# re-invokes initialize() to reload entity instances — does NOT
# reset the operator-selected fault mode.
- self._fault_mode = SimulatorFaultMode.default()
+ self._fault_mode = ServiceFaultMode.default()
self.initialize()
return
@@ -70,18 +70,36 @@ class Simulator( Singleton ):
def url_path_segment(self) -> str:
"""
The URL segment under which this simulator's routes are mounted by
- src/hi/simulator/urls.py:discover_urls() — derived from the
- services-app directory name (e.g., 'homebox' for the simulator at
- hi.simulator.services.homebox.simulator). Note this can differ
- from `id` (e.g., id='hb' but url_path_segment='homebox').
+ src/hi/simulator/services/urls.py:discover_service_urls() — derived
+ from the services-app directory name (e.g., 'homebox' for the
+ simulator at hi.simulator.services.homebox.simulator). Note this
+ can differ from `id` (e.g., id='hb' but url_path_segment='homebox').
"""
return self.__class__.__module__.split('.')[-2]
@property
- def fault_mode(self) -> SimulatorFaultMode:
+ def module_key(self) -> str:
+ """The simulator's pluggable module key — its Django AppConfig
+ name (e.g. ``hi.simulator.services.hass``). Used as the
+ ``SimProfile.module_key`` foreign reference so each service
+ simulator has its own independent profile space."""
+ return '.'.join( self.__class__.__module__.split('.')[:-1] )
+
+ @property
+ def integration_urls(self) -> List[ tuple ]:
+ """
+ URL path(s) operators paste into the main app's integration
+ settings to point at this simulator. Each entry is a tuple of
+ (label, path) where ``path`` is appended to ``<scheme>://<host>/``.
+ Default empty; subclasses opt in by overriding.
+ """
+ return []
+
+ @property
+ def fault_mode(self) -> ServiceFaultMode:
return self._fault_mode
- def set_fault_mode( self, fault_mode : SimulatorFaultMode ):
+ def set_fault_mode( self, fault_mode : ServiceFaultMode ):
self._fault_mode = fault_mode
return
@@ -110,7 +128,7 @@ class Simulator( Singleton ):
def initialize( self ):
"""
- The SimulatorManager stores, hydrates and defines the set of existing
+ The ServiceSimulatorManager stores, hydrates and defines the set of existing
SimEntity instances a simulator will use. This initialization will
occur at start up and if/when the simulation profile changes
(requiring a new list of SimEntity instances).
diff --git a/src/hi/simulator/simulator_data.py b/src/hi/simulator/services/service_simulator_data.py
similarity index 65%
rename from src/hi/simulator/simulator_data.py
rename to src/hi/simulator/services/service_simulator_data.py
index 84dbf8f6..1b792f3a 100644
--- a/src/hi/simulator/simulator_data.py
+++ b/src/hi/simulator/services/service_simulator_data.py
@@ -2,11 +2,11 @@ from dataclasses import dataclass, field
from typing import Dict
from .base_models import SimEntityDefinition
-from .simulator import Simulator
+from .service_simulator import ServiceSimulator
@dataclass
-class SimulatorData:
+class ServiceSimulatorData:
- simulator : Simulator
+ simulator : ServiceSimulator
sim_entity_definition_map : Dict[ str , SimEntityDefinition ] = field( default_factory = dict )
diff --git a/src/hi/simulator/services/service_simulator_manager.py b/src/hi/simulator/services/service_simulator_manager.py
new file mode 100644
index 00000000..4fb52633
--- /dev/null
+++ b/src/hi/simulator/services/service_simulator_manager.py
@@ -0,0 +1,229 @@
+from asgiref.sync import sync_to_async
+import logging
+import threading
+from typing import Dict, List
+
+from django.apps import apps as django_apps
+
+from hi.apps.common.module_utils import import_module_safe
+from hi.apps.common.singleton import Singleton
+
+from hi.simulator.profile.profile_manager import ProfileManager
+
+from .base_models import SimEntityDefinition, SimEntityFields
+from .exceptions import SimEntityValidationError
+from .models import DbSimEntity
+from .sim_entity import SimEntity
+from .service_simulator import ServiceSimulator
+from .service_simulator_data import ServiceSimulatorData
+
+logger = logging.getLogger(__name__)
+
+
+class ServiceSimulatorManager( Singleton ):
+ """Discovers service-simulator sub-apps, hydrates each one's
+ entities from its module-specific current profile, and registers
+ a reload callback so a profile switch in any module triggers a
+ fresh load of that module's entities.
+
+ The cross-cutting "current profile" concept lives in
+ ``ProfileManager`` (per-module). This manager only owns the
+ per-simulator runtime state (entity instances, definitions).
+ """
+
+ def __init_singleton__( self ):
+ self._simulator_data_map : Dict[ str, ServiceSimulatorData ] = dict() # Key = simulator.id
+ self._initialized = False
+ self._data_lock = threading.Lock()
+ return
+
+ def get_simulator( self, simulator_id : str ) -> ServiceSimulator:
+ simulator_data = self._simulator_data_map.get( simulator_id )
+ if not simulator_data:
+ raise KeyError( f'ServiceSimulator id "{simulator_id}" not found.' )
+ return simulator_data.simulator
+
+ def get_simulator_data_list( self ) -> List[ ServiceSimulatorData ]:
+ simulator_data_list = [ x for x in self._simulator_data_map.values() ]
+ simulator_data_list.sort( key = lambda item : item.simulator.label )
+ return simulator_data_list
+
+ def add_sim_entity( self,
+ simulator : ServiceSimulator,
+ sim_entity_definition : SimEntityDefinition,
+ sim_entity_fields : SimEntityFields ):
+
+ with self._data_lock:
+ simulator_data = self._simulator_data_map.get( simulator.id )
+ if not simulator_data:
+ raise KeyError( f'No data found for simulator id = {simulator.id}' )
+
+ current_profile = ProfileManager().get_current( simulator.module_key )
+ db_sim_entity = DbSimEntity(
+ sim_profile = current_profile,
+ entity_fields_class_id = sim_entity_definition.class_id,
+ sim_entity_type = sim_entity_definition.sim_entity_type,
+ sim_entity_fields_json = sim_entity_fields.to_json_dict(),
+ )
+ simulator.validate_new_sim_entity_fields(
+ new_sim_entity_fields = sim_entity_fields,
+ )
+ db_sim_entity.save()
+ sim_entity = SimEntity(
+ db_sim_entity = db_sim_entity,
+ sim_entity_definition = sim_entity_definition,
+ )
+ simulator.add_sim_entity( sim_entity = sim_entity )
+ return
+
+ def update_sim_entity_fields( self,
+ simulator : ServiceSimulator,
+ sim_entity_definition : SimEntityDefinition,
+ db_sim_entity : DbSimEntity,
+ sim_entity_fields : SimEntityFields ):
+
+ with self._data_lock:
+ simulator_data = self._simulator_data_map.get( simulator.id )
+ if not simulator_data:
+ raise KeyError( f'No data found for simulator id = {simulator.id}' )
+
+ db_sim_entity.sim_entity_fields_json = sim_entity_fields.to_json_dict()
+
+ sim_entity = SimEntity(
+ db_sim_entity = db_sim_entity,
+ sim_entity_definition = sim_entity_definition,
+ )
+ simulator.validate_updated_sim_entity( updated_sim_entity = sim_entity )
+ db_sim_entity.save()
+ simulator.add_sim_entity( sim_entity = sim_entity )
+ return
+
+ def delete_sim_entity( self,
+ simulator : ServiceSimulator,
+ db_sim_entity : DbSimEntity ):
+ simulator.remove_sim_entity_by_id( sim_entity_id = db_sim_entity.id )
+ db_sim_entity.delete()
+ return
+
+ async def initialize( self ) -> None:
+ with self._data_lock:
+ if self._initialized:
+ logger.info( 'ServiceSimulatorManager already initialized. Skipping.' )
+ return
+ self._initialized = True
+ logger.info( 'Initializing ServiceSimulatorManager ...' )
+ self._discover_defined_simulators()
+ self._fetch_sim_entity_definitions()
+ self._register_profile_callbacks()
+ await sync_to_async( self._load_entities_for_all_simulators,
+ thread_sensitive = True )()
+ return
+
+ async def shutdown( self ) -> None:
+ logger.info( 'Stopping ServiceSimulatorManager...' )
+ return
+
+ def _discover_defined_simulators( self ):
+ logger.debug( 'Discovering defined simulators ...' )
+
+ self._simulator_data_map = dict()
+ for app_config in django_apps.get_app_configs():
+ if not app_config.name.startswith( 'hi.simulator.services.' ):
+ continue
+ module_name = f'{app_config.name}.simulator'
+ try:
+ app_module = import_module_safe( module_name = module_name )
+ if not app_module:
+ logger.debug( f'No simulator module for {app_config.name}' )
+ continue
+
+ logger.debug( f'Found simulator module for {app_config.name}' )
+
+ for attr_name in dir( app_module ):
+ attr = getattr( app_module, attr_name )
+ if ( isinstance( attr, type )
+ and issubclass( attr, ServiceSimulator )
+ and attr is not ServiceSimulator ):
+ logger.debug( f'Found simulator: {attr_name}' )
+ simulator = attr()
+ self._simulator_data_map[simulator.id] = ServiceSimulatorData(
+ simulator = simulator,
+ )
+ continue
+
+ except Exception:
+ logger.exception( f'Problem getting simulator for {module_name}.' )
+ continue
+ return
+
+ def _fetch_sim_entity_definitions( self ):
+ logger.debug( 'Fetching simulator entity definitions ...' )
+
+ for simulator_id, simulator_data in self._simulator_data_map.items():
+ simulator = simulator_data.simulator
+ sim_entity_definition_list = simulator.sim_entity_definition_list
+ logger.debug(
+ f'Adding {len(sim_entity_definition_list)} entity'
+ f' definitions to {simulator_id}.'
+ )
+ for sim_entity_definition in sim_entity_definition_list:
+ class_id = sim_entity_definition.class_id
+ simulator_data.sim_entity_definition_map[class_id] = sim_entity_definition
+ continue
+ continue
+ return
+
+ def _register_profile_callbacks( self ):
+ for simulator_data in self._simulator_data_map.values():
+ simulator = simulator_data.simulator
+
+ def _on_switched( profile, simulator = simulator ):
+ self._load_entities_for_simulator(
+ simulator = simulator,
+ profile = profile,
+ )
+ return
+
+ ProfileManager().register_on_switched(
+ module_key = simulator.module_key,
+ callback = _on_switched,
+ )
+ continue
+ return
+
+ def _load_entities_for_all_simulators( self ):
+ for simulator_data in self._simulator_data_map.values():
+ simulator = simulator_data.simulator
+ profile = ProfileManager().get_current( simulator.module_key )
+ self._load_entities_for_simulator(
+ simulator = simulator,
+ profile = profile,
+ )
+ continue
+ return
+
+ def _load_entities_for_simulator( self, simulator, profile ):
+ logger.debug(
+ f'Loading entities for {simulator.id} from profile {profile}.'
+ )
+ simulator.initialize()
+ simulator_data = self._simulator_data_map.get( simulator.id )
+ if simulator_data is None:
+ return
+ sim_entity_definition_map = simulator_data.sim_entity_definition_map
+
+ for db_sim_entity in DbSimEntity.objects.filter( sim_profile = profile ):
+ class_id = db_sim_entity.entity_fields_class_id
+ sim_entity_definition = sim_entity_definition_map.get( class_id )
+ if not sim_entity_definition:
+ continue
+ sim_entity = SimEntity(
+ db_sim_entity = db_sim_entity,
+ sim_entity_definition = sim_entity_definition,
+ )
+ try:
+ simulator.add_sim_entity( sim_entity = sim_entity )
+ except SimEntityValidationError:
+ logger.exception( 'Could not add DB simulator entity.' )
+ continue
+ return
diff --git a/src/hi/simulator/sim_entity.py b/src/hi/simulator/services/sim_entity.py
similarity index 94%
rename from src/hi/simulator/sim_entity.py
rename to src/hi/simulator/services/sim_entity.py
index e3cc7232..d475fac5 100644
--- a/src/hi/simulator/sim_entity.py
+++ b/src/hi/simulator/services/sim_entity.py
@@ -9,7 +9,7 @@ from .base_models import SimEntityDefinition, SimEntityFields, SimState
class SimEntity:
"""
These are the run-time instances created and managed by the
- SimulatorManager and Simulator classes. These are the simulator
+ ServiceSimulatorManager and ServiceSimulator classes. These are the simulator
entities chosen by the user from the provided SimEntityDefinition
instances to define the run-time configuration of the simulator.
"""
@@ -25,7 +25,6 @@ class SimEntity:
self._sim_state_map = dict()
for SimStateSubclass in self.sim_entity_definition.sim_state_class_list:
sim_state = SimStateSubclass(
- simulator_id = self.db_sim_entity.simulator_id,
sim_entity_id = self.db_sim_entity.id,
sim_entity_fields = self._sim_entity_fields,
)
diff --git a/src/hi/simulator/templates/simulator/modals/sim_entity_add.html b/src/hi/simulator/services/templates/services/modals/sim_entity_add.html
similarity index 85%
rename from src/hi/simulator/templates/simulator/modals/sim_entity_add.html
rename to src/hi/simulator/services/templates/services/modals/sim_entity_add.html
index ac474e55..27b879ba 100644
--- a/src/hi/simulator/templates/simulator/modals/sim_entity_add.html
+++ b/src/hi/simulator/services/templates/services/modals/sim_entity_add.html
@@ -13,7 +13,7 @@ Add {{ simulator.label }} Entity
{% block body %}
<div>
<div class="h3">{{ sim_entity_definition.class_label }}</div>
- {% include "simulator/panes/sim_entity_fields_form.html" with sim_entity_fields_form=sim_entity_fields_form %}
+ {% include "services/panes/sim_entity_fields_form.html" with sim_entity_fields_form=sim_entity_fields_form %}
</div>
{% endblock %}
diff --git a/src/hi/simulator/templates/simulator/modals/sim_entity_delete.html b/src/hi/simulator/services/templates/services/modals/sim_entity_delete.html
similarity index 100%
rename from src/hi/simulator/templates/simulator/modals/sim_entity_delete.html
rename to src/hi/simulator/services/templates/services/modals/sim_entity_delete.html
diff --git a/src/hi/simulator/templates/simulator/modals/sim_entity_edit.html b/src/hi/simulator/services/templates/services/modals/sim_entity_edit.html
similarity index 84%
rename from src/hi/simulator/templates/simulator/modals/sim_entity_edit.html
rename to src/hi/simulator/services/templates/services/modals/sim_entity_edit.html
index e0d53dc0..ad7b2d45 100644
--- a/src/hi/simulator/templates/simulator/modals/sim_entity_edit.html
+++ b/src/hi/simulator/services/templates/services/modals/sim_entity_edit.html
@@ -13,7 +13,7 @@ Edit Entity
{% block body %}
<div>
- {% include "simulator/panes/sim_entity_fields_form.html" with sim_entity_fields_form=sim_entity_fields_form %}
+ {% include "services/panes/sim_entity_fields_form.html" with sim_entity_fields_form=sim_entity_fields_form %}
</div>
{% endblock %}
diff --git a/src/hi/simulator/services/templates/services/pages/empty.html b/src/hi/simulator/services/templates/services/pages/empty.html
new file mode 100644
index 00000000..ff957271
--- /dev/null
+++ b/src/hi/simulator/services/templates/services/pages/empty.html
@@ -0,0 +1,14 @@
+{% extends "pages/tabbed.html" %}
+
+{% block tab_body %}
+<div class="container-fluid sim-placeholder">
+ <div class="sim-placeholder-card">
+ <h2>Service Simulators</h2>
+ <p class="text-muted mb-0">
+ No service simulators are registered. Add a
+ <code>hi.simulator.services.&lt;service&gt;</code> app to
+ INSTALLED_APPS to start simulating an integration.
+ </p>
+ </div>
+</div>
+{% endblock %}
diff --git a/src/hi/simulator/services/templates/services/pages/service.html b/src/hi/simulator/services/templates/services/pages/service.html
new file mode 100644
index 00000000..8547b784
--- /dev/null
+++ b/src/hi/simulator/services/templates/services/pages/service.html
@@ -0,0 +1,49 @@
+{% extends "pages/tabbed.html" %}
+
+{% block main_attrs %} data-states-url="{% url 'simulator_api_states' %}"{% endblock %}
+
+{% block tab_body %}
+<div class="d-flex align-items-center justify-content-between mb-2">
+ {% include "profile/panes/profile_selector.html" with module=module profile_list=profile_list current_profile=current_profile %}
+
+ <div class="dropdown">
+ <button class="btn btn-secondary btn-control dropdown-toggle" type="button"
+ id="hi-sim-entity-{{ simulator.id }}-menu" data-toggle="dropdown">
+ ADD {{ simulator.label }} ENTITY
+ <span class="caret"></span>
+ </button>
+ <div class="dropdown-menu dropdown-menu-right"
+ role="menu" aria-labelledby="hi-sim-entity-{{ simulator.id }}-menu">
+ {% for sim_entity_definition in simulator.sim_entity_definition_list %}
+ {% if forloop.counter > 1 %}
+ <div class="dropdown-divider"></div>
+ {% endif %}
+ <a role="menuitem" class="dropdown-item plain"
+ href="{% url 'simulator_entity_add' simulator_id=simulator.id class_id=sim_entity_definition.class_id %}"
+ data-async="modal">
+ {{ sim_entity_definition.class_label }}
+ </a>
+ {% endfor %}
+ </div>
+ </div>
+
+ {% if simulator.integration_urls %}
+ <div class="text-muted small mx-3 flex-grow-1 text-center">
+ {% for url_label, url_path in simulator.integration_urls %}
+ <span class="mr-2">
+ <strong>{{ url_label }}:</strong>
+ <code>{{ request.scheme }}://{{ request.get_host }}/{{ url_path }}</code>
+ </span>
+ {% endfor %}
+ </div>
+ {% endif %}
+
+ {% include "services/panes/fault_mode_form.html" with simulator=simulator fault_mode_choices=fault_mode_choices %}
+</div>
+
+{% for sim_entity in simulator.sim_entities %}
+{% include "services/panes/sim_entity.html" with simulator=simulator sim_entity=sim_entity %}
+{% empty %}
+<div class="alert alert-info">No {{ simulator.label }} simulator entities defined.</div>
+{% endfor %}
+{% endblock %}
diff --git a/src/hi/simulator/templates/simulator/panes/fault_mode_form.html b/src/hi/simulator/services/templates/services/panes/fault_mode_form.html
similarity index 100%
rename from src/hi/simulator/templates/simulator/panes/fault_mode_form.html
rename to src/hi/simulator/services/templates/services/panes/fault_mode_form.html
diff --git a/src/hi/simulator/templates/simulator/panes/sim_control_continuous.html b/src/hi/simulator/services/templates/services/panes/sim_control_continuous.html
similarity index 100%
rename from src/hi/simulator/templates/simulator/panes/sim_control_continuous.html
rename to src/hi/simulator/services/templates/services/panes/sim_control_continuous.html
diff --git a/src/hi/simulator/templates/simulator/panes/sim_control_default.html b/src/hi/simulator/services/templates/services/panes/sim_control_default.html
similarity index 100%
rename from src/hi/simulator/templates/simulator/panes/sim_control_default.html
rename to src/hi/simulator/services/templates/services/panes/sim_control_default.html
diff --git a/src/hi/simulator/templates/simulator/panes/sim_control_discrete.html b/src/hi/simulator/services/templates/services/panes/sim_control_discrete.html
similarity index 100%
rename from src/hi/simulator/templates/simulator/panes/sim_control_discrete.html
rename to src/hi/simulator/services/templates/services/panes/sim_control_discrete.html
diff --git a/src/hi/simulator/templates/simulator/panes/sim_control_movement.html b/src/hi/simulator/services/templates/services/panes/sim_control_movement.html
similarity index 100%
rename from src/hi/simulator/templates/simulator/panes/sim_control_movement.html
rename to src/hi/simulator/services/templates/services/panes/sim_control_movement.html
diff --git a/src/hi/simulator/templates/simulator/panes/sim_control_on_off.html b/src/hi/simulator/services/templates/services/panes/sim_control_on_off.html
similarity index 100%
rename from src/hi/simulator/templates/simulator/panes/sim_control_on_off.html
rename to src/hi/simulator/services/templates/services/panes/sim_control_on_off.html
diff --git a/src/hi/simulator/templates/simulator/panes/sim_control_open_close.html b/src/hi/simulator/services/templates/services/panes/sim_control_open_close.html
similarity index 100%
rename from src/hi/simulator/templates/simulator/panes/sim_control_open_close.html
rename to src/hi/simulator/services/templates/services/panes/sim_control_open_close.html
diff --git a/src/hi/simulator/services/templates/services/panes/sim_entity.html b/src/hi/simulator/services/templates/services/panes/sim_entity.html
new file mode 100644
index 00000000..cd32ef4b
--- /dev/null
+++ b/src/hi/simulator/services/templates/services/panes/sim_entity.html
@@ -0,0 +1,25 @@
+{% load icons %}
+<div class="row sim-entity-row">
+ <div class="col-3 sim-entity-name">
+ {{ sim_entity.name }}
+ </div>
+ <div class="col-7">
+ {% for sim_state in sim_entity.sim_state_list %}
+ {% include "services/panes/sim_state.html" with sim_state=sim_state %}
+ {% empty %}
+ <div class="alert alert-warning">No simulation states defined.</div>
+ {% endfor %}
+ </div>
+ <div class="col-2 sim-entity-actions">
+ <a href="{% url 'simulator_entity_edit' sim_entity_id=sim_entity.id %}"
+ class="btn btn-primary sim-icon-btn" data-async="modal"
+ title="Edit {{ sim_entity.name }}" aria-label="Edit">
+ {% icon "edit" size="md" %}
+ </a>
+ <a href="{% url 'simulator_entity_delete' sim_entity_id=sim_entity.id %}"
+ class="btn btn-danger sim-icon-btn" data-async="modal"
+ title="Delete {{ sim_entity.name }}" aria-label="Delete">
+ {% icon "delete" size="md" %}
+ </a>
+ </div>
+</div>
diff --git a/src/hi/simulator/templates/simulator/panes/sim_entity_fields_form.html b/src/hi/simulator/services/templates/services/panes/sim_entity_fields_form.html
similarity index 100%
rename from src/hi/simulator/templates/simulator/panes/sim_entity_fields_form.html
rename to src/hi/simulator/services/templates/services/panes/sim_entity_fields_form.html
diff --git a/src/hi/simulator/services/templates/services/panes/sim_state.html b/src/hi/simulator/services/templates/services/panes/sim_state.html
new file mode 100644
index 00000000..28d4ed73
--- /dev/null
+++ b/src/hi/simulator/services/templates/services/panes/sim_state.html
@@ -0,0 +1,15 @@
+{% load common_tags %}
+<div id="hi-sim-state-{{ simulator.id }}-{{ sim_state.sim_entity_id }}-{{ sim_state.sim_state_id }}" class="row">
+ <div class="col-4">
+ {{ sim_state.name }}
+ </div>
+ <div class="col-8">
+ <form action="{% url 'simulator_entity_state_set' simulator_id=simulator.id sim_entity_id=sim_state.sim_entity_id sim_state_id=sim_state.sim_state_id %}"
+ method="POST" class="form"
+ data-async="#hi-sim-state-{{ simulator.id }}-{{ sim_state.sim_entity_id }}-{{ sim_state.sim_state_id }}"
+ data-mode="replace">
+ {% csrf_token %}
+ {% include_with_fallback sim_state.sim_state_type.template_name "services/panes/sim_control_default.html" %}
+ </form>
+ </div>
+</div>
diff --git a/src/hi/simulator/services/urls.py b/src/hi/simulator/services/urls.py
new file mode 100644
index 00000000..fe3ed864
--- /dev/null
+++ b/src/hi/simulator/services/urls.py
@@ -0,0 +1,73 @@
+import logging
+
+from django.apps import apps
+from django.urls import include, path, re_path
+
+from hi.apps.common.module_utils import import_module_safe
+
+from . import views
+
+logger = logging.getLogger(__name__)
+
+
+urlpatterns = [
+ path( '',
+ views.ServicesIndexView.as_view(),
+ name = 'simulator_services' ),
+
+ path( 'tab/<slug:simulator_id>/',
+ views.ServiceView.as_view(),
+ name = 'simulator_service' ),
+
+ path( 'api/states/',
+ views.SimStatesView.as_view(),
+ name = 'simulator_api_states' ),
+
+ re_path( r'^entity/add/(?P<simulator_id>[\w_\-\.\:]+)/(?P<class_id>[\w\.\_]+)$',
+ views.SimEntityAddView.as_view(),
+ name = 'simulator_entity_add' ),
+
+ path( 'entity/edit/<int:sim_entity_id>',
+ views.SimEntityEditView.as_view(),
+ name = 'simulator_entity_edit' ),
+
+ path( 'entity/delete/<int:sim_entity_id>',
+ views.SimEntityDeleteView.as_view(),
+ name = 'simulator_entity_delete' ),
+
+ re_path( r'^entity/state/set/(?P<simulator_id>[\w_\-\.\:]+)'
+ r'/(?P<sim_entity_id>\d+)/(?P<sim_state_id>[\w\-]+)$',
+ views.SimStateSetView.as_view(),
+ name = 'simulator_entity_state_set' ),
+
+ re_path( r'^fault-mode/set/(?P<simulator_id>[\w_\-\.\:]+)$',
+ views.SetServiceFaultModeView.as_view(),
+ name = 'simulator_fault_mode_set' ),
+]
+
+
+def discover_service_urls():
+ """ Add urls (if any) from all simulated integration services """
+ discovered_url_modules = dict()
+ for app_config in apps.get_app_configs():
+ if not app_config.name.startswith( 'hi.simulator.services.' ):
+ continue
+ module_name = f'{app_config.name}.urls'
+ short_name = app_config.name.split('.')[-1]
+ try:
+ urls_module = import_module_safe( module_name = module_name )
+ if not urls_module:
+ continue
+ discovered_url_modules[short_name] = urls_module
+ except Exception:
+ logger.exception( f'Problem importing URL module: {module_name}' )
+ pass
+ continue
+ return discovered_url_modules
+
+
+for short_name, urls_module in discover_service_urls().items():
+ urlpatterns.append(
+ re_path( f"{short_name}/", include( urls_module ))
+ )
+ continue
diff --git a/src/hi/simulator/services/view_mixins.py b/src/hi/simulator/services/view_mixins.py
new file mode 100644
index 00000000..60886402
--- /dev/null
+++ b/src/hi/simulator/services/view_mixins.py
@@ -0,0 +1,47 @@
+from django.core.exceptions import BadRequest
+from django.http import Http404
+
+from .models import DbSimEntity
+from .service_simulator import ServiceSimulator
+from .service_simulator_manager import ServiceSimulatorManager
+from .base_models import SimEntityDefinition
+
+
+class ServiceSimulatorViewMixin:
+
+ def get_simulator( self, request, *args, **kwargs ) -> ServiceSimulator:
+ simulator_id = kwargs.get( 'simulator_id' )
+ return self.get_simulator_by_id( simulator_id = simulator_id )
+
+ def get_simulator_by_id( self, simulator_id : str ) -> ServiceSimulator:
+ if not simulator_id:
+ raise BadRequest( 'Missing simulator id.' )
+ simulator = ServiceSimulatorManager().get_simulator( simulator_id = simulator_id )
+ if not simulator:
+ raise Http404( f'Unknown simulator id "{simulator_id}".' )
+ return simulator
+
+ def get_entity_definition( self,
+ simulator : ServiceSimulator,
+ request, *args, **kwargs ) -> SimEntityDefinition:
+ class_id = kwargs.get( 'class_id' )
+ return self.get_entity_definition_by_id(
+ simulator = simulator,
+ class_id = class_id,
+ )
+
+ def get_entity_definition_by_id( self,
+ simulator : ServiceSimulator,
+ class_id : str ) -> SimEntityDefinition:
+ for sim_entity_definition in simulator.sim_entity_definition_list:
+ if class_id == sim_entity_definition.class_id:
+ return sim_entity_definition
+ continue
+ raise Http404( 'Unknown entity class id.' )
+
+ def get_db_sim_entity( self, request, *args, **kwargs ) -> DbSimEntity:
+ db_sim_entity_id = kwargs.get( 'sim_entity_id' )
+ try:
+ return DbSimEntity.objects.get( id = db_sim_entity_id )
+ except DbSimEntity.DoesNotExist:
+ raise Http404( 'Simulator entity does not exist.' )
diff --git a/src/hi/simulator/services/views.py b/src/hi/simulator/services/views.py
new file mode 100644
index 00000000..6dcb9594
--- /dev/null
+++ b/src/hi/simulator/services/views.py
@@ -0,0 +1,331 @@
+from django.core.exceptions import BadRequest
+from django.http import Http404, HttpResponseRedirect, JsonResponse
+from django.shortcuts import render
+from django.urls import reverse
+from django.views.generic import View
+
+import hi.apps.common.antinode as antinode
+
+from hi.simulator.profile.profile_manager import ProfileManager
+from hi.simulator.settings.enums import SimTemperatureUnit
+from hi.simulator.settings.runtime_settings import SimulatorRuntimeSettings
+
+from .enums import ServiceFaultMode
+from .exceptions import SimEntityValidationError
+from . import forms
+from .service_simulator_manager import ServiceSimulatorManager
+from .sim_entity import SimEntity
+from .view_mixins import ServiceSimulatorViewMixin
+
+
+def _build_service_tab_specs( active_simulator_id : str ):
+ """Tab strip data for the Services section. Each entry routes to
+ its own URL (``simulator_service``); the active one is matched by
+ ``simulator.id``."""
+ specs = []
+ for sim_data in ServiceSimulatorManager().get_simulator_data_list():
+ simulator = sim_data.simulator
+ specs.append({
+ 'label': simulator.label,
+ 'url': reverse( 'simulator_service',
+ kwargs = { 'simulator_id': simulator.id } ),
+ 'is_active': ( simulator.id == active_simulator_id ),
+ })
+ continue
+ return specs
+
+
+class ServicesIndexView( View ):
+ """Default ``/services/`` route — redirects to the first registered
+ service's per-tab URL so the URL bar always reflects which tab is
+ showing."""
+
+ def get(self, request, *args, **kwargs):
+ sim_data_list = ServiceSimulatorManager().get_simulator_data_list()
+ if not sim_data_list:
+ return render( request, 'services/pages/empty.html',
+ { 'active_section': 'services',
+ 'tab_specs': [] } )
+ first_simulator = sim_data_list[0].simulator
+ return HttpResponseRedirect(
+ reverse( 'simulator_service',
+ kwargs = { 'simulator_id': first_simulator.id } )
+ )
+
+
+class ServiceView( View ):
+ """Renders a single service simulator's tab body. Tab switching is
+ a full page navigation between sibling ``simulator_service``
+ routes."""
+
+ def get(self, request, simulator_id, *args, **kwargs):
+ try:
+ simulator = ServiceSimulatorManager().get_simulator(
+ simulator_id = simulator_id,
+ )
+ except KeyError:
+ raise Http404( f'Unknown simulator: {simulator_id!r}' )
+
+ profile_manager = ProfileManager()
+ module_key = simulator.module_key
+ runtime_settings = SimulatorRuntimeSettings()
+ context = {
+ 'active_section': 'services',
+ 'tab_specs': _build_service_tab_specs( active_simulator_id = simulator.id ),
+ 'simulator': simulator,
+ 'module': {
+ 'module_key': module_key,
+ 'label': simulator.label,
+ },
+ 'profile_list': profile_manager.list_profiles( module_key ),
+ 'current_profile': profile_manager.get_current( module_key ),
+ 'fault_mode_choices': list( ServiceFaultMode ),
+ 'temperature_unit_choices': list( SimTemperatureUnit ),
+ 'temperature_unit_override': runtime_settings.temperature_unit_override,
+ }
+ return render( request, 'services/pages/service.html', context )
+
+
+class SimStatesView( View ):
+ """Periodic-poll endpoint returning a flat map of every service
+ simulator state's current value, keyed by the same DOM id used in
+ sim_state.html so the client can update in place."""
+
+ def get(self, request, *args, **kwargs):
+ states = {}
+ simulator_data_list = ServiceSimulatorManager().get_simulator_data_list()
+ for simulator_data in simulator_data_list:
+ simulator = simulator_data.simulator
+ for sim_entity in simulator.sim_entities:
+ for sim_state in sim_entity.sim_state_list:
+ key = (
+ f'hi-sim-state-{simulator.id}'
+ f'-{sim_state.sim_entity_id}'
+ f'-{sim_state.sim_state_id}'
+ )
+ states[key] = str( sim_state.value )
+ return JsonResponse( { 'states': states } )
+
+
+class SimEntityAddView( View, ServiceSimulatorViewMixin ):
+
+ MODAL_TEMPLATE_NAME = 'services/modals/sim_entity_add.html'
+
+ def get( self, request, *args, **kwargs ):
+ simulator = self.get_simulator( request, *args, **kwargs)
+ sim_entity_definition = self.get_entity_definition( simulator, request, *args, **kwargs )
+ sim_entity_fields_form = forms.SimEntityFieldsForm( sim_entity_definition.sim_entity_fields_class )
+ context = {
+ 'simulator': simulator,
+ 'sim_entity_definition': sim_entity_definition,
+ 'sim_entity_fields_form': sim_entity_fields_form,
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+ def post( self, request, *args, **kwargs ):
+ simulator = self.get_simulator( request, *args, **kwargs)
+ sim_entity_definition = self.get_entity_definition( simulator, request, *args, **kwargs )
+ sim_entity_fields_form = forms.SimEntityFieldsForm(
+ sim_entity_definition.sim_entity_fields_class,
+ request.POST,
+ )
+
+ def error_response():
+ context = {
+ 'simulator': simulator,
+ 'sim_entity_definition': sim_entity_definition,
+ 'sim_entity_fields_form': sim_entity_fields_form,
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+ if not sim_entity_fields_form.is_valid():
+ return error_response()
+
+ cleaned_data = sim_entity_fields_form.clean()
+ SimEntityFieldsSubclass = sim_entity_definition.sim_entity_fields_class
+ sim_entity_fields = SimEntityFieldsSubclass.from_form_data( form_data = cleaned_data )
+ try:
+ ServiceSimulatorManager().add_sim_entity(
+ simulator = simulator,
+ sim_entity_definition = sim_entity_definition,
+ sim_entity_fields = sim_entity_fields,
+ )
+ return antinode.refresh_response()
+
+ except SimEntityValidationError as ve:
+ sim_entity_fields_form.add_error( None, str(ve) )
+ return error_response()
+
+
+class SimEntityEditView( View, ServiceSimulatorViewMixin ):
+
+ MODAL_TEMPLATE_NAME = 'services/modals/sim_entity_edit.html'
+
+ def get( self, request, *args, **kwargs ):
+ db_sim_entity = self.get_db_sim_entity( request, *args, **kwargs )
+ simulator = self._get_simulator_for_entity( db_sim_entity )
+ sim_entity_definition = self.get_entity_definition_by_id(
+ simulator = simulator,
+ class_id = db_sim_entity.entity_fields_class_id,
+ )
+ sim_entity = SimEntity(
+ db_sim_entity = db_sim_entity,
+ sim_entity_definition = sim_entity_definition,
+ )
+ sim_entity_fields_form = forms.SimEntityFieldsForm(
+ sim_entity_fields_class = sim_entity_definition.sim_entity_fields_class,
+ initial = sim_entity.sim_entity_fields.to_initial_form_values(),
+ )
+ context = {
+ 'simulator': simulator,
+ 'db_sim_entity': db_sim_entity,
+ 'sim_entity_fields_form': sim_entity_fields_form,
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+ def post( self, request, *args, **kwargs ):
+ db_sim_entity = self.get_db_sim_entity( request, *args, **kwargs )
+ simulator = self._get_simulator_for_entity( db_sim_entity )
+ sim_entity_definition = self.get_entity_definition_by_id(
+ simulator = simulator,
+ class_id = db_sim_entity.entity_fields_class_id,
+ )
+ sim_entity_fields_form = forms.SimEntityFieldsForm(
+ sim_entity_definition.sim_entity_fields_class,
+ request.POST,
+ )
+
+ def error_response():
+ context = {
+ 'simulator': simulator,
+ 'db_sim_entity': db_sim_entity,
+ 'sim_entity_fields_form': sim_entity_fields_form,
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+ if not sim_entity_fields_form.is_valid():
+ return error_response()
+
+ cleaned_data = sim_entity_fields_form.clean()
+ SimEntityFieldsSubclass = sim_entity_definition.sim_entity_fields_class
+ sim_entity_fields = SimEntityFieldsSubclass.from_form_data( form_data = cleaned_data )
+
+ try:
+ ServiceSimulatorManager().update_sim_entity_fields(
+ simulator = simulator,
+ sim_entity_definition= sim_entity_definition,
+ db_sim_entity = db_sim_entity,
+ sim_entity_fields = sim_entity_fields,
+ )
+ return antinode.refresh_response()
+
+ except SimEntityValidationError as ve:
+ sim_entity_fields_form.add_error( None, str(ve) )
+ return error_response()
+
+ def _get_simulator_for_entity( self, db_sim_entity ):
+ """The DbSimEntity row is tied to a SimProfile (with
+ module_key) — derive the owning simulator by matching
+ module_key against the discovered service simulators."""
+ module_key = db_sim_entity.sim_profile.module_key
+ for sim_data in ServiceSimulatorManager().get_simulator_data_list():
+ if sim_data.simulator.module_key == module_key:
+ return sim_data.simulator
+ continue
+ raise BadRequest(
+ f'No service simulator registered for module {module_key!r}'
+ )
+
+
+class SimEntityDeleteView( View, ServiceSimulatorViewMixin ):
+
+ MODAL_TEMPLATE_NAME = 'services/modals/sim_entity_delete.html'
+
+ def get( self, request, *args, **kwargs ):
+ db_sim_entity = self.get_db_sim_entity( request, *args, **kwargs )
+ simulator = self._get_simulator_for_entity( db_sim_entity )
+ sim_entity_definition = self.get_entity_definition_by_id(
+ simulator = simulator,
+ class_id = db_sim_entity.entity_fields_class_id,
+ )
+ sim_entity = SimEntity(
+ db_sim_entity = db_sim_entity,
+ sim_entity_definition = sim_entity_definition,
+ )
+ context = {
+ 'sim_entity': sim_entity,
+ 'sim_entity_field': sim_entity.sim_entity_fields,
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+ def post( self, request, *args, **kwargs ):
+ db_sim_entity = self.get_db_sim_entity( request, *args, **kwargs )
+ simulator = self._get_simulator_for_entity( db_sim_entity )
+ ServiceSimulatorManager().delete_sim_entity(
+ simulator = simulator,
+ db_sim_entity = db_sim_entity,
+ )
+ return antinode.refresh_response()
+
+ def _get_simulator_for_entity( self, db_sim_entity ):
+ module_key = db_sim_entity.sim_profile.module_key
+ for sim_data in ServiceSimulatorManager().get_simulator_data_list():
+ if sim_data.simulator.module_key == module_key:
+ return sim_data.simulator
+ continue
+ raise BadRequest(
+ f'No service simulator registered for module {module_key!r}'
+ )
+
+
+class SetServiceFaultModeView( View, ServiceSimulatorViewMixin ):
+ """Operator-driven control to flip a simulator into a fault-
+ injection mode (or back to HEALTHY). Lives at a top-level URL —
+ outside the /services/<short_name>/ subtree — so the fault-
+ injection middleware never intercepts requests to it. This is the
+ operator's escape hatch when a simulator is in any non-HEALTHY
+ mode.
+
+ Returns the fault-mode form HTML fragment so antinode.js can swap
+ it in place (data-async + data-mode=replace), avoiding a full
+ page reload on each toggle.
+ """
+
+ TEMPLATE_NAME = 'services/panes/fault_mode_form.html'
+
+ def post( self, request, *args, **kwargs ):
+ simulator = self.get_simulator_by_id(
+ simulator_id = kwargs.get('simulator_id'),
+ )
+ fault_mode_name = request.POST.get('fault_mode')
+ try:
+ fault_mode = ServiceFaultMode[ fault_mode_name ]
+ except (KeyError, TypeError):
+ raise BadRequest( f'Invalid fault mode: {fault_mode_name}' )
+ simulator.set_fault_mode( fault_mode )
+ context = {
+ 'simulator': simulator,
+ 'fault_mode_choices': list( ServiceFaultMode ),
+ }
+ return render( request, self.TEMPLATE_NAME, context )
+
+
+class SimStateSetView( View, ServiceSimulatorViewMixin ):
+
+ TEMPLATE_NAME = 'services/panes/sim_state.html'
+
+ def post( self, request, *args, **kwargs ):
+ simulator = self.get_simulator( request, *args, **kwargs)
+ sim_entity_id = int( kwargs.get( 'sim_entity_id' ))
+ sim_state_id = kwargs.get( 'sim_state_id' )
+ value_str = request.POST.get('value')
+ sim_state = simulator.set_sim_state(
+ sim_entity_id = sim_entity_id,
+ sim_state_id = sim_state_id,
+ value_str = value_str,
+ )
+ context = {
+ 'simulator': simulator,
+ 'sim_state': sim_state,
+ }
+ return render( request, self.TEMPLATE_NAME, context )
diff --git a/src/hi/simulator/services/zoneminder/apps.py b/src/hi/simulator/services/zoneminder/apps.py
index 028703c0..31c81150 100644
--- a/src/hi/simulator/services/zoneminder/apps.py
+++ b/src/hi/simulator/services/zoneminder/apps.py
@@ -1,6 +1,7 @@
from django.apps import AppConfig
-class ZoneminderConfig(AppConfig):
- default_auto_field = "django.db.models.BigAutoField"
- name = "hi.simulator.services.zoneminder"
+class ZoneminderConfig( AppConfig ):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'hi.simulator.services.zoneminder'
+ simulator_module_label = 'ZoneMinder'
diff --git a/src/hi/simulator/services/zoneminder/sim_models.py b/src/hi/simulator/services/zoneminder/sim_models.py
index 53a08aa2..775ac772 100644
--- a/src/hi/simulator/services/zoneminder/sim_models.py
+++ b/src/hi/simulator/services/zoneminder/sim_models.py
@@ -5,9 +5,9 @@ from typing import ClassVar, List, Tuple
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.common.utils import str_to_bool
-from hi.simulator.base_models import SimEntityFields, SimState, SimEntityDefinition
-from hi.simulator.enums import SimEntityType, SimStateType
-from hi.simulator.sim_entity import SimEntity
+from hi.simulator.services.base_models import SimEntityFields, SimState, SimEntityDefinition
+from hi.simulator.services.enums import SimEntityType, SimStateType
+from hi.simulator.services.sim_entity import SimEntity
from .constants import ZmSimConstants
from .enums import ZmMonitorFunction, ZmRunStateType
@@ -297,7 +297,7 @@ class ZmSimEvent:
start_datetime : datetime
end_datetime : datetime
name : str
- cause : str = 'Simulator',
+ cause : str = 'ServiceSimulator',
length_secs : float = 0.0
total_frames : int = 0
alarm_frames : int = 0
diff --git a/src/hi/simulator/services/zoneminder/simulator.py b/src/hi/simulator/services/zoneminder/simulator.py
index fc0e49f8..1ca144ab 100644
--- a/src/hi/simulator/services/zoneminder/simulator.py
+++ b/src/hi/simulator/services/zoneminder/simulator.py
@@ -1,9 +1,9 @@
from typing import List, Set
-from hi.simulator.base_models import SimEntityDefinition, SimEntityFields, SimState
-from hi.simulator.exceptions import SimEntityValidationError
-from hi.simulator.simulator import Simulator
-from hi.simulator.sim_entity import SimEntity
+from hi.simulator.services.base_models import SimEntityDefinition, SimEntityFields, SimState
+from hi.simulator.services.exceptions import SimEntityValidationError
+from hi.simulator.services.service_simulator import ServiceSimulator
+from hi.simulator.services.sim_entity import SimEntity
from .enums import ZmMonitorFunction, ZmRunStateType
from .sim_models import (
@@ -21,7 +21,7 @@ from .sim_models import (
from .zm_event_manager import ZmSimEventManager
-class ZoneMinderSimulator( Simulator ):
+class ZoneMinderSimulator( ServiceSimulator ):
@property
def id(self):
@@ -31,6 +31,13 @@ class ZoneMinderSimulator( Simulator ):
def label(self) -> str:
return 'ZoneMinder'
+ @property
+ def integration_urls(self):
+ return [
+ ( 'API URL', 'services/zoneminder/api' ),
+ ( 'Portal URL', 'services/zoneminder' ),
+ ]
+
def get_zm_monitor_sim_entity_list( self ) -> List[ ZmSimMonitor ]:
return [ ZmSimMonitor( sim_entity = x ) for x in self.sim_entities
if x.sim_entity_definition.sim_entity_fields_class == ZmMonitorSimEntityFields ]
@@ -70,8 +77,8 @@ class ZoneMinderSimulator( Simulator ):
def _auto_create_default_server_entity( self ):
# Imported locally to avoid a module-load-time cycle: the
- # SimulatorManager imports the simulator subclasses at startup.
- from hi.simulator.simulator_manager import SimulatorManager
+ # ServiceSimulatorManager imports the simulator subclasses at startup.
+ from hi.simulator.services.service_simulator_manager import ServiceSimulatorManager
server_definition = None
for definition in self.sim_entity_definition_list:
@@ -83,7 +90,7 @@ class ZoneMinderSimulator( Simulator ):
raise ValueError( 'No ZmServerSimEntityFields definition registered.' )
try:
- SimulatorManager().add_sim_entity(
+ ServiceSimulatorManager().add_sim_entity(
simulator = self,
sim_entity_definition = server_definition,
sim_entity_fields = ZmServerSimEntityFields(),
diff --git a/src/hi/simulator/settings/__init__.py b/src/hi/simulator/settings/__init__.py
new file mode 100644
index 00000000..d49ca4ff
--- /dev/null
+++ b/src/hi/simulator/settings/__init__.py
@@ -0,0 +1 @@
+default_app_config = 'hi.simulator.settings.apps.SettingsConfig'
diff --git a/src/hi/simulator/settings/apps.py b/src/hi/simulator/settings/apps.py
new file mode 100644
index 00000000..03ef5e62
--- /dev/null
+++ b/src/hi/simulator/settings/apps.py
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class SettingsConfig( AppConfig ):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'hi.simulator.settings'
+ label = 'simulator_settings'
diff --git a/src/hi/simulator/settings/enums.py b/src/hi/simulator/settings/enums.py
new file mode 100644
index 00000000..90daac9d
--- /dev/null
+++ b/src/hi/simulator/settings/enums.py
@@ -0,0 +1,16 @@
+from hi.apps.common.enums import LabeledEnum
+
+
+class SimTemperatureUnit(LabeledEnum):
+ """Integration-agnostic temperature unit choice for the
+ simulator's runtime override. Each integration's composer maps
+ these to its own wire format (e.g., HA uses ``°F`` / ``°C``;
+ other integrations may use ``degF`` / ``degC`` or other
+ conventions)."""
+
+ FAHRENHEIT = ( 'Fahrenheit', '' )
+ CELSIUS = ( 'Celsius', '' )
+
+ @classmethod
+ def default(cls):
+ return cls.FAHRENHEIT
diff --git a/src/hi/simulator/runtime_settings.py b/src/hi/simulator/settings/runtime_settings.py
similarity index 100%
rename from src/hi/simulator/runtime_settings.py
rename to src/hi/simulator/settings/runtime_settings.py
diff --git a/src/hi/simulator/settings/templates/settings/pages/settings.html b/src/hi/simulator/settings/templates/settings/pages/settings.html
new file mode 100644
index 00000000..9ed9569d
--- /dev/null
+++ b/src/hi/simulator/settings/templates/settings/pages/settings.html
@@ -0,0 +1,12 @@
+{% extends "simulator/pages/base.html" %}
+
+{% block content %}
+<div class="container-fluid sim-placeholder">
+ <div class="sim-placeholder-card">
+ <h2>Settings</h2>
+ <p class="text-muted mb-0">
+ Global simulator settings (including temperature unit overrides) will live here.
+ </p>
+ </div>
+</div>
+{% endblock %}
diff --git a/src/hi/simulator/templates/simulator/panes/temperature_unit_override_form.html b/src/hi/simulator/settings/templates/settings/panes/temperature_unit_override_form.html
similarity index 100%
rename from src/hi/simulator/templates/simulator/panes/temperature_unit_override_form.html
rename to src/hi/simulator/settings/templates/settings/panes/temperature_unit_override_form.html
diff --git a/src/hi/simulator/settings/urls.py b/src/hi/simulator/settings/urls.py
new file mode 100644
index 00000000..fe463ebf
--- /dev/null
+++ b/src/hi/simulator/settings/urls.py
@@ -0,0 +1,14 @@
+from django.urls import path
+
+from . import views
+
+
+urlpatterns = [
+ path( '',
+ views.SettingsView.as_view(),
+ name = 'simulator_settings' ),
+
+ path( 'runtime/temperature-unit-override',
+ views.TemperatureUnitOverrideSetView.as_view(),
+ name = 'simulator_temperature_unit_override_set' ),
+]
diff --git a/src/hi/simulator/settings/views.py b/src/hi/simulator/settings/views.py
new file mode 100644
index 00000000..c799f4df
--- /dev/null
+++ b/src/hi/simulator/settings/views.py
@@ -0,0 +1,38 @@
+from django.core.exceptions import BadRequest
+from django.shortcuts import render
+from django.views.generic import View
+
+from .enums import SimTemperatureUnit
+from .runtime_settings import SimulatorRuntimeSettings
+
+
+class SettingsView( View ):
+
+ def get(self, request, *args, **kwargs):
+ context = { 'active_section': 'settings' }
+ return render( request, 'settings/pages/settings.html', context )
+
+
+class TemperatureUnitOverrideSetView( View ):
+ """Operator control to flip the simulator's process-wide
+ temperature unit override (or clear it back to per-profile
+ defaults). Returns the dropdown's form fragment so antinode.js
+ can swap it in place — preserves the current integration tab
+ and avoids a full reload."""
+
+ TEMPLATE_NAME = 'settings/panes/temperature_unit_override_form.html'
+
+ def post( self, request, *args, **kwargs ):
+ raw = ( request.POST.get( 'temperature_unit' ) or '' ).strip()
+ if raw:
+ override = SimTemperatureUnit.from_name_safe( raw )
+ if override is None:
+ raise BadRequest( f'Unknown temperature unit: {raw!r}' )
+ else:
+ override = None
+ SimulatorRuntimeSettings().set_temperature_unit_override( override )
+ context = {
+ 'temperature_unit_choices': list( SimTemperatureUnit ),
+ 'temperature_unit_override': override,
+ }
+ return render( request, self.TEMPLATE_NAME, context )
diff --git a/src/hi/simulator/sim_view_parameters.py b/src/hi/simulator/sim_view_parameters.py
deleted file mode 100644
index 5902099e..00000000
--- a/src/hi/simulator/sim_view_parameters.py
+++ /dev/null
@@ -1,30 +0,0 @@
-from dataclasses import dataclass
-
-from django.http import HttpRequest
-
-
-@dataclass
-class SimViewParameters:
-
- simulator_id : str = None # Last active simulator
-
- def __post_init__(self):
- return
-
- def to_session( self, request : HttpRequest ):
- if not hasattr( request, 'session' ):
- return
- request.session['simulator_id'] = self.simulator_id
- return
-
- @staticmethod
- def from_session( request : HttpRequest ):
- if not request:
- return SimViewParameters()
- if not hasattr( request, 'session' ):
- return SimViewParameters()
- simulator_id = request.session.get( 'simulator_id' )
- return SimViewParameters(
- simulator_id = simulator_id,
- )
-
diff --git a/src/hi/simulator/simulator_manager.py b/src/hi/simulator/simulator_manager.py
deleted file mode 100644
index bd689527..00000000
--- a/src/hi/simulator/simulator_manager.py
+++ /dev/null
@@ -1,276 +0,0 @@
-from asgiref.sync import sync_to_async
-import logging
-import threading
-from typing import Dict, List
-
-from django.apps import apps as django_apps
-
-import hi.apps.common.datetimeproxy as datetimeproxy
-from hi.apps.common.module_utils import import_module_safe
-from hi.apps.common.singleton import Singleton
-
-from .base_models import SimEntityDefinition, SimEntityFields
-from .exceptions import SimEntityValidationError
-from .models import DbSimEntity, SimProfile
-from .sim_entity import SimEntity
-from .simulator import Simulator
-from .simulator_data import SimulatorData
-
-logger = logging.getLogger(__name__)
-
-
-class SimulatorManager( Singleton ):
-
- DEFAULT_PROFILE_NAME = 'Default'
-
- def __init_singleton__( self ):
- self._current_sim_profile = None
- self._simulator_data_map : Dict[ str, SimulatorData ] = dict() # Key = simulator.id
- self._initialized = False
- self._data_lock = threading.Lock()
- return
-
- @property
- def sim_profile_list(self) -> List[ SimProfile ]:
- return list( SimProfile.objects.all().order_by('name') )
-
- @property
- def current_sim_profile(self) -> SimProfile:
- return self._current_sim_profile
-
- @classmethod
- def clone_sim_profile( cls,
- source_profile : SimProfile,
- new_name : str ) -> SimProfile:
- """Create a new ``SimProfile`` with ``new_name`` populated
- with copies of every ``DbSimEntity`` row under
- ``source_profile``. Returns the new profile (caller is
- responsible for switching to it if desired).
-
- Pure DB-side clone — does not touch the in-memory simulator
- state. The caller's subsequent ``set_sim_profile()`` (when
- they switch to the clone) is what triggers the simulator
- instances to load the cloned rows.
-
- Wrap this call in ``transaction.atomic()`` at the call site
- so a failure mid-clone leaves no partial profile behind.
- ``DbSimEntity`` JSON blobs are immutable strings — no
- deep-copy needed; passing ``json`` references between rows
- is safe because Django's JSONField round-trips through
- json.dumps on save.
- """
- new_profile = SimProfile.objects.create( name = new_name )
- DbSimEntity.objects.bulk_create([
- DbSimEntity(
- sim_profile = new_profile,
- simulator_id = row.simulator_id,
- entity_fields_class_id = row.entity_fields_class_id,
- sim_entity_type_str = row.sim_entity_type_str,
- sim_entity_fields_json = row.sim_entity_fields_json,
- )
- for row in source_profile.db_sim_entities.all()
- ])
- return new_profile
-
- def set_sim_profile( self, sim_profile : SimProfile ):
- should_reload_instances = bool( not sim_profile
- or ( sim_profile != self._current_sim_profile ))
- if not sim_profile:
- self._initialize_sim_profile()
- else:
- sim_profile.last_switched_to_datetime = datetimeproxy.now()
- sim_profile.save()
- self._current_sim_profile = sim_profile
-
- if should_reload_instances:
- self._load_sim_entity_instances()
- return
-
- def get_simulator( self, simulator_id : str ) -> Simulator:
- simulator_data = self._simulator_data_map.get( simulator_id )
- if not simulator_data:
- raise KeyError( f'Simulator id "{simulator_id}" not found.' )
- return simulator_data.simulator
-
- def get_simulator_data_list(self) -> List[ SimulatorData ]:
- simulator_data_list = [ x for x in self._simulator_data_map.values() ]
- simulator_data_list.sort( key = lambda item : item.simulator.label )
- return simulator_data_list
-
- def add_sim_entity( self,
- simulator : Simulator,
- sim_entity_definition : SimEntityDefinition,
- sim_entity_fields : SimEntityFields ):
-
- with self._data_lock:
- simulator_data = self._simulator_data_map.get( simulator.id )
- if not simulator_data:
- raise KeyError( f'No data found for simulator id = {simulator.id}' )
-
- db_sim_entity = DbSimEntity(
- sim_profile = self.current_sim_profile,
- simulator_id = simulator.id,
- entity_fields_class_id = sim_entity_definition.class_id,
- sim_entity_type = sim_entity_definition.sim_entity_type,
- sim_entity_fields_json = sim_entity_fields.to_json_dict(),
- )
-
- simulator.validate_new_sim_entity_fields( new_sim_entity_fields = sim_entity_fields )
- db_sim_entity.save()
- sim_entity = SimEntity(
- db_sim_entity = db_sim_entity,
- sim_entity_definition = sim_entity_definition,
- )
- simulator.add_sim_entity( sim_entity = sim_entity )
-
- def update_sim_entity_fields( self,
- simulator : Simulator,
- sim_entity_definition : SimEntityDefinition,
- db_sim_entity : DbSimEntity,
- sim_entity_fields : SimEntityFields ):
-
- with self._data_lock:
- simulator_data = self._simulator_data_map.get( simulator.id )
- if not simulator_data:
- raise KeyError( f'No data found for simulator id = {simulator.id}' )
-
- db_sim_entity.sim_entity_fields_json = sim_entity_fields.to_json_dict()
-
- sim_entity = SimEntity(
- db_sim_entity = db_sim_entity,
- sim_entity_definition = sim_entity_definition,
- )
- simulator.validate_updated_sim_entity( updated_sim_entity = sim_entity )
- db_sim_entity.save()
- simulator.add_sim_entity( sim_entity = sim_entity )
-
- return
-
- def delete_sim_entity( self,
- simulator : Simulator,
- db_sim_entity : DbSimEntity ):
- simulator.remove_sim_entity_by_id( sim_entity_id = db_sim_entity.id )
- db_sim_entity.delete()
- return
-
- async def initialize( self ) -> None:
- with self._data_lock:
- if self._initialized:
- logger.info('SimulationManager already initialize. Skipping.')
- return
- self._initialized = True
- logger.info('Initializing SimulationManager ...')
- await sync_to_async( self._initialize_sim_profile,
- thread_sensitive = True )()
- self._discover_defined_simulators()
- self._fetch_sim_entity_definitions()
- await sync_to_async( self._load_sim_entity_instances,
- thread_sensitive = True )()
-
- return
-
- async def shutdown(self) -> None:
- # Nothing yet
- logger.info('Stopping SimulationManager...')
- return
-
- def _initialize_sim_profile(self):
- logger.debug('Initialize SimProfile ...')
- self._current_sim_profile = SimProfile.objects.all().first() # Default ordering is by recency use
- if not self._current_sim_profile:
- self._current_sim_profile = SimProfile.objects.create(
- name = self.DEFAULT_PROFILE_NAME,
- last_switched_to_datetime = datetimeproxy.now(),
- )
- return
-
- def _discover_defined_simulators(self):
- logger.debug('Discovering defined simulators ...')
-
- self._simulator_data_map = dict()
- for app_config in django_apps.get_app_configs():
- if not app_config.name.startswith( 'hi.simulator.services' ):
- continue
- module_name = f'{app_config.name}.simulator'
- try:
- app_module = import_module_safe( module_name = module_name )
- if not app_module:
- logger.debug( f'No simulator module for {app_config.name}' )
- continue
-
- logger.debug( f'Found simulator module for {app_config.name}' )
-
- for attr_name in dir(app_module):
- attr = getattr( app_module, attr_name )
- if ( isinstance( attr, type )
- and issubclass( attr, Simulator )
- and attr is not Simulator ):
- logger.debug(f'Found simulator: {attr_name}')
- simulator = attr()
- self._simulator_data_map[simulator.id] = SimulatorData(
- simulator = simulator,
- )
- continue
-
- except Exception:
- logger.exception( f'Problem getting simulator for {module_name}.' )
- continue
-
- return
-
- def _fetch_sim_entity_definitions(self):
- """
- Query simulators to get the defined subclasses of SimEntity and
- populates the SimulatorData for each simulator.
- """
- logger.debug('Fetching simulator entity definitions ...')
-
- for simulator_id, simulator_data in self._simulator_data_map.items():
- simulator = simulator_data.simulator
- sim_entity_definition_list = simulator.sim_entity_definition_list
- logger.debug( f'Adding {len(sim_entity_definition_list)} entity definitions to {simulator_id}.' )
- for sim_entity_definition in sim_entity_definition_list:
- class_id = sim_entity_definition.class_id
- simulator_data.sim_entity_definition_map[class_id] = sim_entity_definition
- continue
- continue
- return
-
- def _load_sim_entity_instances(self):
-
- logger.debug('Initializing simulators ...')
- for simulator_id, simulator_data in self._simulator_data_map.items():
- simulator_data.simulator.initialize()
- continue
-
- logger.debug('Loading saved simulator entities ...')
- db_sim_entity_queryset = DbSimEntity.objects.filter(
- sim_profile = self.current_sim_profile,
- )
- for db_sim_entity in db_sim_entity_queryset:
- simulator_id = db_sim_entity.simulator_id
- simulator_data = self._simulator_data_map.get( simulator_id )
- if not simulator_data:
- logger.warning( f'Instance found for non-existent simulator id = {simulator_id}' )
- continue
-
- sim_entity_definition_map = simulator_data.sim_entity_definition_map
- class_id = db_sim_entity.entity_fields_class_id
- sim_entity_definition = sim_entity_definition_map.get( class_id )
- if not sim_entity_definition:
- logger.warning( f'Entity class "{class_id}" not found for simulator "{simulator_id}"' )
- continue
-
- sim_entity = SimEntity(
- db_sim_entity = db_sim_entity,
- sim_entity_definition = sim_entity_definition,
- )
- try:
- simulator_data.simulator.add_sim_entity( sim_entity = sim_entity )
- except SimEntityValidationError:
- logger.exception( 'Could not add DB simulator entity.' )
- continue
-
- return
-
-
diff --git a/src/hi/simulator/templates/pages/tabbed.html b/src/hi/simulator/templates/pages/tabbed.html
new file mode 100644
index 00000000..b3f71fb0
--- /dev/null
+++ b/src/hi/simulator/templates/pages/tabbed.html
@@ -0,0 +1,19 @@
+{% extends "simulator/pages/base.html" %}
+
+{% comment %}
+Shared base for the Services and Weather sections. Each tab is its
+own URL — selecting a tab is a full page navigation, not a client-side
+bootstrap-tab swap. Per-tab pages extend this and fill ``tab_body``.
+
+Context required:
+ - tab_specs : list of dicts with keys ``label``, ``url``, ``is_active``
+{% endcomment %}
+
+{% block content %}
+<main class="sim-main"{% block main_attrs %}{% endblock %}>
+ {% include "simulator/panes/tab_nav.html" %}
+ <div class="sim-tab-body">
+ {% block tab_body %}{% endblock %}
+ </div>
+</main>
+{% endblock %}
diff --git a/src/hi/simulator/templates/simulator/modals/sim_profile_clone.html b/src/hi/simulator/templates/simulator/modals/sim_profile_clone.html
deleted file mode 100644
index 2007c015..00000000
--- a/src/hi/simulator/templates/simulator/modals/sim_profile_clone.html
+++ /dev/null
@@ -1,42 +0,0 @@
-{% extends "modals/action_with_cancel.html" %}
-{% load icons %}
-
-{% comment %}
- Clone the source profile into a new profile with operator-chosen
- name. The form is pre-filled with '<source> (copy)' (or the next
- free numeric variant), but the operator can edit before submit.
-
- Context:
- source_profile : SimProfile (required) — the profile being cloned
- sim_profile_form : SimProfileForm (required) — name input
-{% endcomment %}
-
-{% block preamble %}
-<form action="{% url 'simulator_profile_clone' profile_id=source_profile.id %}" method="post"
- class="form" data-async="modal">
- {% csrf_token %}
-{% endblock %}
-
-{% block title_text %}
-Clone Simulator Profile
-{% endblock %}
-
-{% block body %}
-<p>
- Cloning <strong>{{ source_profile.name }}</strong>. The new
- profile will contain a copy of every simulated entity from
- the source. Choose a name for the new profile:
-</p>
-{% include "simulator/panes/sim_profile_form.html" %}
-{% endblock %}
-
-{% block action_right %}
-<button id="hi-simulator-profile-clone-submit" type="submit" class="btn btn-primary"
- name="action" value="clone">
- {% icon "plus" size="sm" css_class="hi-icon-left" %}CLONE
-</button>
-{% endblock %}
-
-{% block postamble %}
-</form>
-{% endblock %}
diff --git a/src/hi/simulator/templates/simulator/modals/sim_profile_delete.html b/src/hi/simulator/templates/simulator/modals/sim_profile_delete.html
deleted file mode 100644
index 7d9b9d3f..00000000
--- a/src/hi/simulator/templates/simulator/modals/sim_profile_delete.html
+++ /dev/null
@@ -1,32 +0,0 @@
-{% extends "modals/action_with_cancel.html" %}
-
-{% block preamble %}
-<form action="{% url 'simulator_profile_delete' profile_id=sim_profile.id %}" method="post"
- class="form" data-async="modal">
- {% csrf_token %}
-{% endblock %}
-
-{% block title_text %}
-Delete Simulation Profile?
-{% endblock %}
-
-{% block body %}
- <p>
- Deleting the simulation profile "{{ sim_profile.name }}" will remove all {{ sim_entity_count }} the defined simulator entities.
- </p>
- <p class="text-danger">
- This action cannot be undone. Are you sure you want to delete the "{{ sim_profile.name }}" simulation profile?
- </p>
-{% endblock %}
-
-{% block action_right %}
-<button id="hi-simulator-profile-delete-submit" type="submit" class="btn btn-danger"
- name="action" value="delete">
- DELETE
-</button>
-{% endblock %}
-
-{% block postamble %}
-</form>
-{% endblock %}
-
diff --git a/src/hi/simulator/templates/simulator/pages/base.html b/src/hi/simulator/templates/simulator/pages/base.html
index 7368e9f9..1bd4cf45 100644
--- a/src/hi/simulator/templates/simulator/pages/base.html
+++ b/src/hi/simulator/templates/simulator/pages/base.html
@@ -5,7 +5,7 @@
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
- <title>{% block head_title %}Service Simulators{% endblock %}</title>
+ <title>{% block head_title %}Home Information Simulator{% endblock %}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" type="image/png" href="{% static 'favicon.png' %}"/>
<link rel="icon" type="image/png" href="{% static 'img/hi-icon-16x16.png' %}" sizes="16x16">
@@ -14,6 +14,7 @@
<link rel="icon" type="image/png" href="{% static 'img/hi-icon-128x128.png' %}" sizes="128x128">
<link rel="icon" type="image/png" href="{% static 'img/hi-icon-196x196.png' %}" sizes="196x196">
<link href="{% static 'bootstrap/css/bootstrap.css' %}" rel="stylesheet" type="text/css" media="all" />
+ <link href="{% static 'css/icons.css' %}" rel="stylesheet" type="text/css" media="all" />
<link href="{% static 'css/simulator.css' %}" rel="stylesheet" type="text/css" media="all" />
</head>
<body>
@@ -25,7 +26,9 @@
<script type="text/javascript" src="{% static 'js/autosize.min.js' %}" charset="utf-8"></script>
<script type="text/javascript" src="{% static 'js/simulator.js' %}" charset="utf-8"></script>
+ {% include "simulator/panes/top_nav.html" %}
+
{% block content %}{% endblock %}
-
+
</body>
</html>
diff --git a/src/hi/simulator/templates/simulator/pages/home.html b/src/hi/simulator/templates/simulator/pages/home.html
deleted file mode 100644
index 22446320..00000000
--- a/src/hi/simulator/templates/simulator/pages/home.html
+++ /dev/null
@@ -1,8 +0,0 @@
-{% extends "simulator/pages/base.html" %}
-
-{% block content %}
-<div class="container-fluid">
- {% include "simulator/panes/sim_profile_header.html" %}
- {% include "simulator/panes/simulator_control_tabs.html" %}
-</div>
-{% endblock %}
diff --git a/src/hi/simulator/templates/simulator/panes/sim_entity.html b/src/hi/simulator/templates/simulator/panes/sim_entity.html
deleted file mode 100644
index f9e4960e..00000000
--- a/src/hi/simulator/templates/simulator/panes/sim_entity.html
+++ /dev/null
@@ -1,21 +0,0 @@
-{% load icons %}
-<div class="row">
- <div class="col-3">
- {{ sim_entity.name }}
- </div>
- <div class="col-7">
- {% for sim_state in sim_entity.sim_state_list %}
- {% include "simulator/panes/sim_state.html" with sim_state=sim_state %}
- {% empty %}
- <div class="alert alert-warning">No simulation states defined.</div>
- {% endfor %}
- </div>
- <div class="col-2">
- <a href="{% url 'simulator_entity_edit' sim_entity_id=sim_entity.id %}"
- class="btn btn-primary" data-async="modal">
- {% icon "edit" size="sm" css_class="hi-icon-left" %}EDIT
- </a>
- <a href="{% url 'simulator_entity_delete' sim_entity_id=sim_entity.id %}"
- class="btn btn-danger" data-async="modal">X</a>
- </div>
-</div>
diff --git a/src/hi/simulator/templates/simulator/panes/sim_profile_dropdown.html b/src/hi/simulator/templates/simulator/panes/sim_profile_dropdown.html
deleted file mode 100644
index 728e29fa..00000000
--- a/src/hi/simulator/templates/simulator/panes/sim_profile_dropdown.html
+++ /dev/null
@@ -1,36 +0,0 @@
-<div>
- <div class="dropdown">
- <button class="btn btn-secondary btn-control dropdown-toggle" type="button"
- id="hi-sim_profile-menu" data-toggle="dropdown">
- {% if current_sim_profile %}
- Profile: {{ current_sim_profile.name }}
- {% else %}
- -- CHOOSE --
- {% endif %}
- <span class="caret"></span>
- </button>
- <div class="dropdown-menu dropdown-menu-right"
- role="menu" aria-labelledby="hi-sim_profile-menu">
- {% for sim_profile in sim_profile_list %}
- {% if sim_profile != current_sim_profile %}
-
- <a role="menuitem" class="dropdown-item plain"
- href="{% url 'simulator_profile_switch' profile_id=sim_profile.id %} ">
- {{ sim_profile.name }}
- </a>
- <div class="dropdown-divider"></div>
-
- {% endif %}
- {% empty %}
- <div class="dropdown-item alert alert-secondary text-center">
- <em>No simulator profiles.</em>
- </div>
- {% endfor %}
- <a role="menuitem" class="dropdown-item plain"
- href="{% url 'simulator_profile_create' %}"
- data-async="modal">
- NEW PROFILE
- </a>
- </div>
- </div>
-</div>
diff --git a/src/hi/simulator/templates/simulator/panes/sim_profile_header.html b/src/hi/simulator/templates/simulator/panes/sim_profile_header.html
deleted file mode 100644
index ace2c97e..00000000
--- a/src/hi/simulator/templates/simulator/panes/sim_profile_header.html
+++ /dev/null
@@ -1,35 +0,0 @@
-<div class="d-flex justify-content-between align-items-center">
- <div class="h3">Service Simulators</div>
- <div class="d-flex align-items-center">
- {% include "simulator/panes/temperature_unit_override_form.html" %}
- <div class="ml-3">
- {% include "simulator/panes/sim_profile_dropdown.html" %}
- </div>
- </div>
-</div>
-<div class="d-flex justify-content-start">
- <div class="h4">
- <small>Profile: </small> {{ current_sim_profile.name }}
- </div>
- <div class="">
- <a role="button" class="btn btn-primary"
- href="{% url 'simulator_profile_edit' profile_id=current_sim_profile.id %}"
- data-async="modal">
- RENAME: {{ current_sim_profile.name }}
- </a>
- </div>
- <div class="">
- <a role="button" class="btn btn-secondary"
- href="{% url 'simulator_profile_clone' profile_id=current_sim_profile.id %}"
- data-async="modal">
- CLONE: {{ current_sim_profile.name }}
- </a>
- </div>
- <div class="">
- <a role="button" class="btn btn-danger"
- href="{% url 'simulator_profile_delete' profile_id=current_sim_profile.id %}"
- data-async="modal">
- DELETE: {{ current_sim_profile.name }}
- </a>
- </div>
-</div>
diff --git a/src/hi/simulator/templates/simulator/panes/sim_state.html b/src/hi/simulator/templates/simulator/panes/sim_state.html
deleted file mode 100644
index 2ca66f75..00000000
--- a/src/hi/simulator/templates/simulator/panes/sim_state.html
+++ /dev/null
@@ -1,15 +0,0 @@
-{% load common_tags %}
-<div id="hi-sim-state-{{ sim_state.simulator_id }}-{{ sim_state.sim_entity_id }}-{{ sim_state.sim_state_id }}" class="row">
- <div class="col-4">
- {{ sim_state.name }}
- </div>
- <div class="col-8">
- <form action="{% url 'simulator_entity_state_set' simulator_id=sim_state.simulator_id sim_entity_id=sim_state.sim_entity_id sim_state_id=sim_state.sim_state_id %}"
- method="POST" class="form"
- data-async="#hi-sim-state-{{ sim_state.simulator_id }}-{{ sim_state.sim_entity_id }}-{{ sim_state.sim_state_id }}"
- data-mode="replace">
- {% csrf_token %}
- {% include_with_fallback sim_state.sim_state_type.template_name "simulator/panes/sim_control_default.html" %}
- </form>
- </div>
-</div>
diff --git a/src/hi/simulator/templates/simulator/panes/simulator_control_tabs.html b/src/hi/simulator/templates/simulator/panes/simulator_control_tabs.html
deleted file mode 100644
index 0a16bdc4..00000000
--- a/src/hi/simulator/templates/simulator/panes/simulator_control_tabs.html
+++ /dev/null
@@ -1,77 +0,0 @@
-<div>
- <ul id="hi-simulator-tabs" class="nav nav-tabs" role="tablist">
- {% for simulator_data in simulator_data_list %}
- {% with simulator_data.simulator as simulator %}
- <li class="nav-item">
- <a id="hi-simulator-tab-{{ simulator.id }}" role="tab"
- class="nav-link {% if simulator.id == current_simulator.id %}active{% endif %}"
- data-toggle="tab"
- href="#simulator-{{ simulator.id }}"
- aria-controls="simulator-{{ simulator.id }}"
- aria-selected="{% if simulator.id == current_simulator.id %}true{% else %}false{% endif %}">
- {{ simulator.label }}</a>
- </li>
- {% endwith %}
- {% endfor %}
- </ul>
-
- <div id="hi-simulator-content" class="tab-content">
- {% for simulator_data in simulator_data_list %}
- {% with simulator_data.simulator as simulator %}
- <div id="simulator-{{ simulator.id }}" role="tabpanel"
- class="tab-pane fade {% if simulator.id == current_simulator.id %}show active{% endif %}"
- aria-labelledby="hi-simulator-tab-{{ simulator.id }}">
- <div class="d-flex align-items-center justify-content-between mb-2">
- <div class="dropdown">
- <button class="btn btn-secondary btn-control dropdown-toggle" type="button"
- id="hi-sim-entity-{{ simulator.id }}-menu" data-toggle="dropdown">
- ADD {{ simulator.label }} ENTITY
- <span class="caret"></span>
- </button>
- <div class="dropdown-menu dropdown-menu-right"
- role="menu" aria-labelledby="hi-sim-entity-{{ simulator.id }}-menu">
- {% for sim_entity_definition in simulator.sim_entity_definition_list %}
- {% if forloop.counter > 1 %}
- <div class="dropdown-divider"></div>
- {% endif %}
- <a role="menuitem" class="dropdown-item plain"
- href="{% url 'simulator_entity_add' simulator_id=simulator.id class_id=sim_entity_definition.class_id %} "
- data-async="modal">
- {{ sim_entity_definition.class_label }}
- </a>
- {% endfor %}
- </div>
- </div>
-
- {% include "simulator/panes/fault_mode_form.html" with simulator=simulator fault_mode_choices=fault_mode_choices %}
- </div>
-
- {% for sim_entity in simulator.sim_entities %}
- {% include "simulator/panes/sim_entity.html" with simulator=simulator sim_entity=sim_entity %}
- {% empty %}
- <div class="alert alert-info" >No {{ simulator.label }} simulator entities defined.</div>
- {% endfor %}
-
- </div>
- {% endwith %}
- {% endfor %}
- </div>
-</div>
-
-<script>
- $(document).ready(function () {
- $('a[data-toggle="tab"]').on('shown.bs.tab', function (event) {
- const tabId = $(event.target).attr('href');
- history.replaceState(null, null, tabId);
- console.log('Tab activated:', tabId);
- });
-
- const hash = window.location.hash;
- if ( hash ) {
- const targetTab = document.querySelector(`.nav-link[href="${hash}"]`);
- if ( targetTab ) {
- new bootstrap.Tab( targetTab ).show();
- }
- }
- });
-</script>
diff --git a/src/hi/simulator/templates/simulator/panes/tab_nav.html b/src/hi/simulator/templates/simulator/panes/tab_nav.html
new file mode 100644
index 00000000..479e464f
--- /dev/null
+++ b/src/hi/simulator/templates/simulator/panes/tab_nav.html
@@ -0,0 +1,18 @@
+{% comment %}
+URL-routed tab strip used by the Services and Weather sections. Active
+tab is determined server-side by URL match (each tab is its own route).
+
+Context: ``tab_specs`` — list of dicts with keys ``label``, ``url``,
+``is_active``.
+{% endcomment %}
+<ul class="nav nav-tabs sim-tab-nav" role="tablist">
+ {% for spec in tab_specs %}
+ <li class="nav-item">
+ <a class="nav-link {% if spec.is_active %}active{% endif %}"
+ href="{{ spec.url }}"
+ aria-selected="{% if spec.is_active %}true{% else %}false{% endif %}">
+ {{ spec.label }}
+ </a>
+ </li>
+ {% endfor %}
+</ul>
diff --git a/src/hi/simulator/templates/simulator/panes/top_nav.html b/src/hi/simulator/templates/simulator/panes/top_nav.html
new file mode 100644
index 00000000..54fc9228
--- /dev/null
+++ b/src/hi/simulator/templates/simulator/panes/top_nav.html
@@ -0,0 +1,27 @@
+{% load static %}
+<nav class="sim-top-nav">
+ <div class="sim-top-nav-brand">
+ <img src="{% static 'img/hi-icon-32x32.png' %}" alt="" class="sim-top-nav-logo">
+ <span class="sim-top-nav-title">Home Information Simulator</span>
+ </div>
+ <ul class="sim-top-nav-links">
+ <li>
+ <a href="{% url 'simulator_services' %}"
+ class="sim-top-nav-link {% if active_section == 'services' %}active{% endif %}">
+ Services
+ </a>
+ </li>
+ <li>
+ <a href="{% url 'simulator_weather' %}"
+ class="sim-top-nav-link {% if active_section == 'weather' %}active{% endif %}">
+ Weather
+ </a>
+ </li>
+ <li>
+ <a href="{% url 'simulator_settings' %}"
+ class="sim-top-nav-link {% if active_section == 'settings' %}active{% endif %}">
+ Settings
+ </a>
+ </li>
+ </ul>
+</nav>
diff --git a/src/hi/simulator/urls.py b/src/hi/simulator/urls.py
index be95bba0..0f75334b 100644
--- a/src/hi/simulator/urls.py
+++ b/src/hi/simulator/urls.py
@@ -1,95 +1,17 @@
-import logging
-
-from django.apps import apps
from django.contrib import admin
-from django.urls import include, path, re_path
-
-from hi.apps.common.module_utils import import_module_safe
-
-from . import views
-
-logger = logging.getLogger(__name__)
+from django.urls import include, path
+from django.views.generic import RedirectView
urlpatterns = [
path( 'admin/', admin.site.urls ),
path( '',
- views.HomeView.as_view(),
+ RedirectView.as_view( pattern_name = 'simulator_services', permanent = False ),
name = 'simulator_home' ),
-
- path( 'profile/create',
- views.ProfileCreateView.as_view(),
- name = 'simulator_profile_create' ),
-
- path( 'profile/edit/<int:profile_id>',
- views.ProfileEditView.as_view(),
- name = 'simulator_profile_edit' ),
-
- path( 'profile/delete/<int:profile_id>',
- views.ProfileDeleteView.as_view(),
- name = 'simulator_profile_delete' ),
- path( 'profile/clone/<int:profile_id>',
- views.ProfileCloneView.as_view(),
- name = 'simulator_profile_clone' ),
-
- path( 'profile/switch/<int:profile_id>',
- views.ProfileSwitchView.as_view(),
- name = 'simulator_profile_switch' ),
-
- re_path( r'^entity/add/(?P<simulator_id>[\w_\-\.\:]+)/(?P<class_id>[\w\.\_]+)$',
- views.SimEntityAddView.as_view(),
- name = 'simulator_entity_add' ),
-
- path( 'entity/edit/<int:sim_entity_id>',
- views.SimEntityEditView.as_view(),
- name = 'simulator_entity_edit' ),
-
- path( 'entity/delete/<int:sim_entity_id>',
- views.SimEntityDeleteView.as_view(),
- name = 'simulator_entity_delete' ),
-
- re_path( r'^entity/state/set/(?P<simulator_id>[\w_\-\.\:]+)/(?P<sim_entity_id>\d+)/(?P<sim_state_id>[\w\-]+)$',
- views.SimStateSetView.as_view(),
- name = 'simulator_entity_state_set' ),
-
- re_path( r'^fault-mode/set/(?P<simulator_id>[\w_\-\.\:]+)$',
- views.SetSimulatorFaultModeView.as_view(),
- name = 'simulator_fault_mode_set' ),
-
- path( 'runtime/temperature-unit-override',
- views.TemperatureUnitOverrideSetView.as_view(),
- name = 'simulator_temperature_unit_override_set' ),
+ path( 'services/', include( 'hi.simulator.services.urls' )),
+ path( 'weather/', include( 'hi.simulator.weather_sources.urls' )),
+ path( 'settings/', include( 'hi.simulator.settings.urls' )),
+ path( 'profile/', include( 'hi.simulator.profile.urls' )),
]
-
-
-def discover_urls():
- """ Add urls (if any) from all simulated integration services """
-
- discovered_url_modules = dict()
- for app_config in apps.get_app_configs():
- if not app_config.name.startswith( 'hi.simulator.services' ):
- continue
- module_name = f'{app_config.name}.urls'
- short_name = app_config.name.split('.')[-1]
- try:
- urls_module = import_module_safe( module_name = module_name )
- if not urls_module:
- continue
-
- discovered_url_modules[short_name] = urls_module
-
- except Exception:
- logger.exception( f'Problem importing URL module: {module_name}' )
- pass
- continue
-
- return discovered_url_modules
-
-
-for short_name, urls_module in discover_urls().items():
- urlpatterns.append(
- re_path(f"services/{short_name}/", include( urls_module ))
- )
- continue
diff --git a/src/hi/simulator/view_mixins.py b/src/hi/simulator/view_mixins.py
deleted file mode 100644
index c2bfaf0e..00000000
--- a/src/hi/simulator/view_mixins.py
+++ /dev/null
@@ -1,79 +0,0 @@
-from typing import List
-
-from django.core.exceptions import BadRequest
-from django.http import Http404, HttpRequest
-
-from .models import DbSimEntity, SimProfile
-from .simulator import Simulator
-from .simulator_manager import SimulatorManager
-from .base_models import SimEntityDefinition
-
-
-class SimulatorViewMixin:
-
- def get_current_simulator( self,
- request : HttpRequest,
- simulator_list : List[ Simulator ] ) -> Simulator:
- if not simulator_list:
- return None
- current_simulator_id = request.sim_view_parameters.simulator_id
- for simulator in simulator_list:
- if simulator.id == current_simulator_id:
- return simulator
- continue
- return simulator_list[0]
-
- def set_current_simulator( self,
- request : HttpRequest,
- simulator : Simulator ):
- request.sim_view_parameters.simulator_id = simulator.id
- request.sim_view_parameters.to_session( request )
- return
-
- def get_sim_profile( self, request, *args, **kwargs) -> SimProfile:
- sim_profile_id = kwargs.get('profile_id')
- try:
- return SimProfile.objects.get( id = sim_profile_id )
- except SimProfile.DoesNotExist:
- raise Http404( 'Simulator profile does not exist.' )
-
- def get_simulator( self, request, *args, **kwargs ) -> Simulator:
- """ Side effect of setting current simulator in session. """
- simulator_id = kwargs.get('simulator_id')
- simulator = self.get_simulator_by_id( simulator_id = simulator_id )
- self.set_current_simulator(
- request = request,
- simulator = simulator,
- )
- return simulator
-
- def get_simulator_by_id( self, simulator_id : str ) -> Simulator:
- if not simulator_id:
- raise BadRequest( 'Missing simulator id.' )
- simulator = SimulatorManager().get_simulator( simulator_id = simulator_id )
- if not simulator:
- raise Http404( 'Unknown simulator id "{simulator_id}".' )
- return simulator
-
- def get_entity_definition( self,
- simulator : Simulator,
- request, *args, **kwargs ) -> SimEntityDefinition:
- class_id = kwargs.get('class_id')
- return self.get_entity_definition_by_id(
- simulator = simulator,
- class_id = class_id,
- )
-
- def get_entity_definition_by_id( self, simulator : Simulator, class_id : str ) -> SimEntityDefinition:
- for sim_entity_definition in simulator.sim_entity_definition_list:
- if class_id == sim_entity_definition.class_id:
- return sim_entity_definition
- continue
- raise Http404( 'Unknown entity class id.' )
-
- def get_db_sim_entity( self, request, *args, **kwargs ) -> SimProfile:
- db_sim_entity_id = kwargs.get('sim_entity_id')
- try:
- return DbSimEntity.objects.get( id = db_sim_entity_id )
- except DbSimEntity.DoesNotExist:
- raise Http404( 'Simulator entity does not exist.' )
diff --git a/src/hi/simulator/views.py b/src/hi/simulator/views.py
deleted file mode 100644
index ff5a6099..00000000
--- a/src/hi/simulator/views.py
+++ /dev/null
@@ -1,419 +0,0 @@
-from django.core.exceptions import BadRequest
-from django.db import transaction
-from django.http import HttpResponseRedirect
-from django.shortcuts import render
-from django.urls import reverse
-from django.views.generic import View
-
-import hi.apps.common.antinode as antinode
-
-from .enums import SimulatorFaultMode, SimTemperatureUnit
-from .exceptions import SimEntityValidationError
-from . import forms
-from .models import DbSimEntity, SimProfile
-from .runtime_settings import SimulatorRuntimeSettings
-from .simulator_manager import SimulatorManager
-from .sim_entity import SimEntity
-from .view_mixins import SimulatorViewMixin
-
-
-class HomeView( View, SimulatorViewMixin ):
-
- def get(self, request, *args, **kwargs):
- simulator_manager = SimulatorManager()
- sim_profile_list = simulator_manager.sim_profile_list
- current_sim_profile = simulator_manager.current_sim_profile
- simulator_data_list = simulator_manager.get_simulator_data_list()
- current_simulator = self.get_current_simulator(
- request = request,
- simulator_list = [ x.simulator for x in simulator_data_list ],
- )
- runtime_settings = SimulatorRuntimeSettings()
- context = {
- 'sim_profile_list': sim_profile_list,
- 'current_sim_profile': current_sim_profile,
- 'simulator_data_list': simulator_data_list,
- 'current_simulator': current_simulator,
- 'fault_mode_choices': list( SimulatorFaultMode ),
- 'temperature_unit_choices': list( SimTemperatureUnit ),
- 'temperature_unit_override': runtime_settings.temperature_unit_override,
- }
- return render( request, 'simulator/pages/home.html', context )
-
-
-class ProfileCreateView( View ):
-
- MODAL_TEMPLATE_NAME = 'simulator/modals/sim_profile_create.html'
-
- def get(self, request, *args, **kwargs):
- context = {
- 'sim_profile_form': forms.SimProfileForm()
- }
- return render( request, self.MODAL_TEMPLATE_NAME, context )
-
- def post(self, request, *args, **kwargs):
-
- sim_profile_form = forms.SimProfileForm( request.POST )
- if not sim_profile_form.is_valid():
- context = {
- 'sim_profile_form': sim_profile_form,
- }
- return render( request, self.MODAL_TEMPLATE_NAME, context )
-
- sim_profile = sim_profile_form.save()
- sim_profile = SimulatorManager().set_sim_profile(
- sim_profile = sim_profile,
- )
- return antinode.refresh_response()
-
-
-class ProfileEditView( View, SimulatorViewMixin ):
-
- MODAL_TEMPLATE_NAME = 'simulator/modals/sim_profile_edit.html'
-
- def get(self, request, *args, **kwargs):
- sim_profile = self.get_sim_profile( request, *args, **kwargs)
- sim_profile_form = forms.SimProfileForm( instance = sim_profile )
- context = {
- 'sim_profile_form': sim_profile_form,
- }
- return render( request, self.MODAL_TEMPLATE_NAME, context )
-
- def post(self, request, *args, **kwargs):
- sim_profile = self.get_sim_profile( request, *args, **kwargs)
- sim_profile_form = forms.SimProfileForm( request.POST, instance = sim_profile )
- if not sim_profile_form.is_valid():
- context = {
- 'sim_profile_form': sim_profile_form
- }
- return render( request, self.MODAL_TEMPLATE_NAME, context )
-
- sim_profile = sim_profile_form.save()
- SimulatorManager().set_sim_profile( sim_profile = sim_profile )
- return antinode.refresh_response()
-
-
-class ProfileCloneView( View, SimulatorViewMixin ):
- """
- Clone the current profile into a new profile with operator-
- chosen name. The clone copies the profile row and every
- DbSimEntity row beneath it; SimState values are not persisted
- (rebuilt from class defaults on every profile load), so the
- clone naturally gets fresh state semantics with no extra work.
-
- The new profile becomes the active profile after creation —
- matches the Create flow's behavior and gives the operator
- immediate visual confirmation in the simulator UI.
- """
-
- MODAL_TEMPLATE_NAME = 'simulator/modals/sim_profile_clone.html'
-
- def get(self, request, *args, **kwargs):
- source_profile = self.get_sim_profile( request, *args, **kwargs )
- suggested_name = self._suggest_name( source_profile.name )
- sim_profile_form = forms.SimProfileForm(
- initial = { 'name': suggested_name },
- )
- context = {
- 'source_profile': source_profile,
- 'sim_profile_form': sim_profile_form,
- }
- return render( request, self.MODAL_TEMPLATE_NAME, context )
-
- def post(self, request, *args, **kwargs):
- source_profile = self.get_sim_profile( request, *args, **kwargs )
- sim_profile_form = forms.SimProfileForm( request.POST )
- if not sim_profile_form.is_valid():
- context = {
- 'source_profile': source_profile,
- 'sim_profile_form': sim_profile_form,
- }
- return render( request, self.MODAL_TEMPLATE_NAME, context )
-
- new_name = sim_profile_form.cleaned_data['name']
- with transaction.atomic():
- new_profile = SimulatorManager.clone_sim_profile(
- source_profile = source_profile,
- new_name = new_name,
- )
- SimulatorManager().set_sim_profile( sim_profile = new_profile )
- return antinode.refresh_response()
-
- @staticmethod
- def _suggest_name( source_name : str ) -> str:
- """Default new-name suggestion: '<source> (copy)'.
-
- If that name is already taken, append a numeric suffix
- ('<source> (copy 2)', '(copy 3)', ...) until a free name
- is found. Bounded probe — no DB-side lock — because the
- unique-name constraint at submit time is the actual
- guard; this is just a friendly default, and a race here
- means the operator sees a 'name already exists' on submit
- and edits the field, which is acceptable."""
- candidate = f'{source_name} (copy)'
- if not SimProfile.objects.filter( name = candidate ).exists():
- return candidate
- for index in range( 2, 100 ):
- candidate = f'{source_name} (copy {index})'
- if not SimProfile.objects.filter( name = candidate ).exists():
- return candidate
- return f'{source_name} (copy)'
-
-
-class ProfileSwitchView( View, SimulatorViewMixin ):
-
- def get(self, request, *args, **kwargs):
- sim_profile = self.get_sim_profile( request, *args, **kwargs)
- SimulatorManager().set_sim_profile(
- sim_profile = sim_profile,
- )
- url = reverse( 'simulator_home' )
- return HttpResponseRedirect( url )
-
-
-class ProfileDeleteView( View, SimulatorViewMixin ):
-
- MODAL_TEMPLATE_NAME = 'simulator/modals/sim_profile_delete.html'
-
- def get(self, request, *args, **kwargs):
- sim_profile = self.get_sim_profile( request, *args, **kwargs)
- sim_entity_count = DbSimEntity.objects.filter( sim_profile = sim_profile ).count()
- context = {
- 'sim_profile': sim_profile,
- 'sim_entity_count': sim_entity_count,
- }
- return render( request, self.MODAL_TEMPLATE_NAME, context )
-
- def post(self, request, *args, **kwargs):
- sim_profile = self.get_sim_profile( request, *args, **kwargs)
- needs_switch = bool( sim_profile == SimulatorManager().current_sim_profile )
- sim_profile.delete()
- if needs_switch:
- sim_profile = SimulatorManager().set_sim_profile( sim_profile = None )
- return antinode.refresh_response()
-
-
-class SimEntityAddView( View, SimulatorViewMixin ):
-
- MODAL_TEMPLATE_NAME = 'simulator/modals/sim_entity_add.html'
-
- def get( self, request, *args, **kwargs ):
- simulator = self.get_simulator( request, *args, **kwargs)
- sim_entity_definition = self.get_entity_definition( simulator, request, *args, **kwargs )
- sim_entity_fields_form = forms.SimEntityFieldsForm( sim_entity_definition.sim_entity_fields_class )
- context = {
- 'simulator': simulator,
- 'sim_entity_definition': sim_entity_definition,
- 'sim_entity_fields_form': sim_entity_fields_form,
- }
- return render( request, self.MODAL_TEMPLATE_NAME, context )
-
- def post( self, request, *args, **kwargs ):
- simulator = self.get_simulator( request, *args, **kwargs)
- sim_entity_definition = self.get_entity_definition( simulator, request, *args, **kwargs )
- sim_entity_fields_form = forms.SimEntityFieldsForm(
- sim_entity_definition.sim_entity_fields_class,
- request.POST,
- )
-
- def error_response():
- context = {
- 'simulator': simulator,
- 'sim_entity_definition': sim_entity_definition,
- 'sim_entity_fields_form': sim_entity_fields_form,
- }
- return render( request, self.MODAL_TEMPLATE_NAME, context )
-
- if not sim_entity_fields_form.is_valid():
- return error_response()
-
- cleaned_data = sim_entity_fields_form.clean()
- SimEntityFieldsSubclass = sim_entity_definition.sim_entity_fields_class
- sim_entity_fields = SimEntityFieldsSubclass.from_form_data( form_data = cleaned_data )
- try:
- SimulatorManager().add_sim_entity(
- simulator = simulator,
- sim_entity_definition = sim_entity_definition,
- sim_entity_fields = sim_entity_fields,
- )
- return antinode.refresh_response()
-
- except SimEntityValidationError as ve:
- sim_entity_fields_form.add_error( None, str(ve) )
- return error_response()
-
-
-class SimEntityEditView( View, SimulatorViewMixin ):
-
- MODAL_TEMPLATE_NAME = 'simulator/modals/sim_entity_edit.html'
-
- def get( self, request, *args, **kwargs ):
- db_sim_entity = self.get_db_sim_entity( request, *args, **kwargs )
- simulator = self.get_simulator_by_id( simulator_id = db_sim_entity.simulator_id )
- sim_entity_definition = self.get_entity_definition_by_id(
- simulator = simulator,
- class_id = db_sim_entity.entity_fields_class_id,
- )
- sim_entity = SimEntity(
- db_sim_entity = db_sim_entity,
- sim_entity_definition = sim_entity_definition,
- )
- sim_entity_fields_form = forms.SimEntityFieldsForm(
- sim_entity_fields_class = sim_entity_definition.sim_entity_fields_class,
- initial = sim_entity.sim_entity_fields.to_initial_form_values(),
- )
- context = {
- 'simulator': simulator,
- 'db_sim_entity': db_sim_entity,
- 'sim_entity_fields_form': sim_entity_fields_form,
- }
- return render( request, self.MODAL_TEMPLATE_NAME, context )
-
- def post( self, request, *args, **kwargs ):
- db_sim_entity = self.get_db_sim_entity( request, *args, **kwargs )
- simulator = self.get_simulator_by_id( simulator_id = db_sim_entity.simulator_id )
- sim_entity_definition = self.get_entity_definition_by_id(
- simulator = simulator,
- class_id = db_sim_entity.entity_fields_class_id,
- )
- sim_entity_fields_form = forms.SimEntityFieldsForm(
- sim_entity_definition.sim_entity_fields_class,
- request.POST,
- )
-
- def error_response():
- context = {
- 'simulator': simulator,
- 'db_sim_entity': db_sim_entity,
- 'sim_entity_fields_form': sim_entity_fields_form,
- }
- return render( request, self.MODAL_TEMPLATE_NAME, context )
-
- if not sim_entity_fields_form.is_valid():
- return error_response()
-
- cleaned_data = sim_entity_fields_form.clean()
- SimEntityFieldsSubclass = sim_entity_definition.sim_entity_fields_class
- sim_entity_fields = SimEntityFieldsSubclass.from_form_data( form_data = cleaned_data )
-
- try:
- SimulatorManager().update_sim_entity_fields(
- simulator = simulator,
- sim_entity_definition= sim_entity_definition,
- db_sim_entity = db_sim_entity,
- sim_entity_fields = sim_entity_fields,
- )
- return antinode.refresh_response()
-
- except SimEntityValidationError as ve:
- sim_entity_fields_form.add_error( None, str(ve) )
- return error_response()
-
-
-class SimEntityDeleteView( View, SimulatorViewMixin ):
-
- MODAL_TEMPLATE_NAME = 'simulator/modals/sim_entity_delete.html'
-
- def get( self, request, *args, **kwargs ):
- db_sim_entity = self.get_db_sim_entity( request, *args, **kwargs )
- simulator = self.get_simulator_by_id( simulator_id = db_sim_entity.simulator_id )
- sim_entity_definition = self.get_entity_definition_by_id(
- simulator = simulator,
- class_id = db_sim_entity.entity_fields_class_id,
- )
- sim_entity = SimEntity(
- db_sim_entity = db_sim_entity,
- sim_entity_definition = sim_entity_definition,
- )
- context = {
- 'sim_entity': sim_entity,
- 'sim_entity_field': sim_entity.sim_entity_fields,
- }
- return render( request, self.MODAL_TEMPLATE_NAME, context )
-
- def post( self, request, *args, **kwargs ):
- db_sim_entity = self.get_db_sim_entity( request, *args, **kwargs )
- simulator = self.get_simulator_by_id( simulator_id = db_sim_entity.simulator_id )
- SimulatorManager().delete_sim_entity(
- simulator = simulator,
- db_sim_entity = db_sim_entity,
- )
- return antinode.refresh_response()
-
-
-class SetSimulatorFaultModeView( View, SimulatorViewMixin ):
- """
- Operator-driven control to flip a simulator into a fault-injection
- mode (or back to HEALTHY). Lives at a top-level URL — outside the
- /services/<short_name>/ subtree — so the fault-injection middleware
- never intercepts requests to it. This is the operator's escape hatch
- when a simulator is in any non-HEALTHY mode.
-
- Returns the fault-mode form HTML fragment so antinode.js can swap it
- in place (data-async + data-mode=replace), avoiding a full page
- reload on each toggle.
- """
-
- TEMPLATE_NAME = 'simulator/panes/fault_mode_form.html'
-
- def post( self, request, *args, **kwargs ):
- simulator = self.get_simulator_by_id(
- simulator_id = kwargs.get('simulator_id'),
- )
- fault_mode_name = request.POST.get('fault_mode')
- try:
- fault_mode = SimulatorFaultMode[ fault_mode_name ]
- except (KeyError, TypeError):
- raise BadRequest( f'Invalid fault mode: {fault_mode_name}' )
- simulator.set_fault_mode( fault_mode )
- context = {
- 'simulator': simulator,
- 'fault_mode_choices': list( SimulatorFaultMode ),
- }
- return render( request, self.TEMPLATE_NAME, context )
-
-
-class SimStateSetView( View, SimulatorViewMixin ):
-
- TEMPLATE_NAME = 'simulator/panes/sim_state.html'
-
- def post( self, request, *args, **kwargs ):
- simulator = self.get_simulator( request, *args, **kwargs)
- sim_entity_id = int( kwargs.get( 'sim_entity_id' ))
- sim_state_id = kwargs.get( 'sim_state_id' )
- value_str = request.POST.get('value')
- sim_state = simulator.set_sim_state(
- sim_entity_id = sim_entity_id,
- sim_state_id = sim_state_id,
- value_str = value_str,
- )
- context = {
- 'sim_state': sim_state,
- }
- return render( request, self.TEMPLATE_NAME, context )
-
-
-class TemperatureUnitOverrideSetView( View ):
- """Operator control to flip the simulator's process-wide
- temperature unit override (or clear it back to per-profile
- defaults). Returns the dropdown's form fragment so antinode.js
- can swap it in place — preserves the current integration tab
- and avoids a full reload."""
-
- TEMPLATE_NAME = 'simulator/panes/temperature_unit_override_form.html'
-
- def post( self, request, *args, **kwargs ):
- raw = ( request.POST.get( 'temperature_unit' ) or '' ).strip()
- if raw:
- override = SimTemperatureUnit.from_name_safe( raw )
- if override is None:
- raise BadRequest( f'Unknown temperature unit: {raw!r}' )
- else:
- override = None
- SimulatorRuntimeSettings().set_temperature_unit_override( override )
- context = {
- 'temperature_unit_choices': list( SimTemperatureUnit ),
- 'temperature_unit_override': override,
- }
- return render( request, self.TEMPLATE_NAME, context )
-
diff --git a/src/hi/simulator/weather_sources/__init__.py b/src/hi/simulator/weather_sources/__init__.py
new file mode 100644
index 00000000..29f759bf
--- /dev/null
+++ b/src/hi/simulator/weather_sources/__init__.py
@@ -0,0 +1 @@
+default_app_config = 'hi.simulator.weather_sources.apps.WeatherSourcesConfig'
diff --git a/src/hi/simulator/weather_sources/apps.py b/src/hi/simulator/weather_sources/apps.py
new file mode 100644
index 00000000..4a01570a
--- /dev/null
+++ b/src/hi/simulator/weather_sources/apps.py
@@ -0,0 +1,6 @@
+from django.apps import AppConfig
+
+
+class WeatherSourcesConfig( AppConfig ):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'hi.simulator.weather_sources'
diff --git a/src/hi/simulator/weather_sources/nws/__init__.py b/src/hi/simulator/weather_sources/nws/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/simulator/weather_sources/nws/apps.py b/src/hi/simulator/weather_sources/nws/apps.py
new file mode 100644
index 00000000..f42e36be
--- /dev/null
+++ b/src/hi/simulator/weather_sources/nws/apps.py
@@ -0,0 +1,12 @@
+from django.apps import AppConfig
+
+
+class NwsWeatherSimConfig( AppConfig ):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'hi.simulator.weather_sources.nws'
+
+ simulator_module_label = 'National Weather Service'
+
+ weather_source_short_name = 'nws'
+ weather_source_label = 'National Weather Service'
+ weather_source_tab_template = 'weather_sources/nws/tab.html'
diff --git a/src/hi/simulator/weather_sources/nws/constants.py b/src/hi/simulator/weather_sources/nws/constants.py
new file mode 100644
index 00000000..4b0bafbb
--- /dev/null
+++ b/src/hi/simulator/weather_sources/nws/constants.py
@@ -0,0 +1,89 @@
+"""Choice lists for the NWS simulator alert editor.
+
+Values match the NWS / CAP spec strings that ``NwsConverters`` parses
+in the main app (lowercased before lookup). Keeping these here as plain
+tuples instead of pulling from ``hi.apps.weather.enums`` avoids
+coupling the simulator app to main-app imports at module load time.
+"""
+
+SEVERITY_CHOICES = [
+ ( 'Extreme', 'Extreme' ),
+ ( 'Severe', 'Severe' ),
+ ( 'Moderate', 'Moderate' ),
+ ( 'Minor', 'Minor' ),
+ ( 'Unknown', 'Unknown' ),
+]
+
+CERTAINTY_CHOICES = [
+ ( 'Observed', 'Observed' ),
+ ( 'Likely', 'Likely' ),
+ ( 'Possible', 'Possible' ),
+ ( 'Unlikely', 'Unlikely' ),
+ ( 'Unknown', 'Unknown' ),
+]
+
+URGENCY_CHOICES = [
+ ( 'Immediate', 'Immediate' ),
+ ( 'Expected', 'Expected' ),
+ ( 'Future', 'Future' ),
+ ( 'Unknown', 'Unknown' ),
+]
+
+STATUS_CHOICES = [
+ ( 'Actual', 'Actual' ),
+ ( 'Exercise', 'Exercise' ),
+ ( 'System', 'System' ),
+ ( 'Test', 'Test' ),
+ ( 'Draft', 'Draft' ),
+]
+
+# NWS 'category' field — short codes that the main-app converter
+# lowercases for lookup.
+CATEGORY_CHOICES = [
+ ( 'met', 'Meteorological' ),
+ ( 'geo', 'Geological' ),
+ ( 'safety', 'Public Safety' ),
+ ( 'security', 'Security' ),
+ ( 'rescue', 'Rescue' ),
+ ( 'fire', 'Fire' ),
+ ( 'health', 'Health' ),
+ ( 'env', 'Environmental' ),
+ ( 'transport', 'Transportation' ),
+ ( 'infra', 'Infrastructure' ),
+ ( 'other', 'Other' ),
+]
+
+# Subset of NWS three-letter event codes useful for exercising the
+# main-app code-to-event-type mapping. Not exhaustive; operator can
+# type the freeform event name to cover anything not listed.
+EVENT_CODE_CHOICES = [
+ ( '', '— None —' ),
+ ( 'TOR', 'TOR — Tornado Warning' ),
+ ( 'TOA', 'TOA — Tornado Watch' ),
+ ( 'SVR', 'SVR — Severe Thunderstorm Warning' ),
+ ( 'SVA', 'SVA — Severe Thunderstorm Watch' ),
+ ( 'FFW', 'FFW — Flash Flood Warning' ),
+ ( 'FFA', 'FFA — Flash Flood Watch' ),
+ ( 'FLW', 'FLW — Flood Warning' ),
+ ( 'FLA', 'FLA — Flood Watch' ),
+ ( 'EWW', 'EWW — Extreme Wind Warning' ),
+ ( 'HWW', 'HWW — High Wind Warning' ),
+ ( 'BZW', 'BZW — Blizzard Warning' ),
+ ( 'WSW', 'WSW — Winter Storm Warning' ),
+ ( 'WSA', 'WSA — Winter Storm Watch' ),
+ ( 'HUW', 'HUW — Hurricane Warning' ),
+ ( 'HUA', 'HUA — Hurricane Watch' ),
+ ( 'TRW', 'TRW — Tropical Storm Warning' ),
+ ( 'TRA', 'TRA — Tropical Storm Watch' ),
+ ( 'TSW', 'TSW — Tsunami Warning' ),
+ ( 'TSA', 'TSA — Tsunami Watch' ),
+ ( 'FRW', 'FRW — Fire Warning' ),
+ ( 'RFW', 'RFW — Red Flag Warning' ),
+ ( 'AFW', 'AFW — Ashfall Warning' ),
+ ( 'EQW', 'EQW — Earthquake Warning' ),
+ ( 'AQA', 'AQA — Air Quality Alert' ),
+ ( 'CDW', 'CDW — Civil Danger Warning' ),
+ ( 'CEM', 'CEM — Civil Emergency Message' ),
+ ( 'LAE', 'LAE — Local Area Emergency' ),
+ ( 'TST', 'TST — Test Message' ),
+]
diff --git a/src/hi/simulator/weather_sources/nws/forms.py b/src/hi/simulator/weather_sources/nws/forms.py
new file mode 100644
index 00000000..af588815
--- /dev/null
+++ b/src/hi/simulator/weather_sources/nws/forms.py
@@ -0,0 +1,52 @@
+from django import forms
+
+from .models import NwsSimAlert
+
+
+class NwsSimAlertForm( forms.ModelForm ):
+
+ class Meta:
+ model = NwsSimAlert
+ fields = (
+ 'is_active',
+ 'event_code',
+ 'event_name',
+ 'severity_str',
+ 'certainty_str',
+ 'urgency_str',
+ 'status_str',
+ 'category_str',
+ 'headline',
+ 'description',
+ 'instruction',
+ 'area_desc',
+ 'effective_offset_secs',
+ 'expires_offset_secs',
+ )
+ widgets = {
+ 'event_code': forms.Select( attrs = { 'class': 'custom-select' } ),
+ 'severity_str': forms.Select( attrs = { 'class': 'custom-select' } ),
+ 'certainty_str': forms.Select( attrs = { 'class': 'custom-select' } ),
+ 'urgency_str': forms.Select( attrs = { 'class': 'custom-select' } ),
+ 'status_str': forms.Select( attrs = { 'class': 'custom-select' } ),
+ 'category_str': forms.Select( attrs = { 'class': 'custom-select' } ),
+ 'event_name': forms.TextInput( attrs = { 'class': 'form-control' } ),
+ 'headline': forms.TextInput( attrs = { 'class': 'form-control' } ),
+ 'area_desc': forms.TextInput( attrs = { 'class': 'form-control' } ),
+ 'description': forms.Textarea( attrs = { 'class': 'form-control', 'rows': 3 } ),
+ 'instruction': forms.Textarea( attrs = { 'class': 'form-control', 'rows': 2 } ),
+ 'effective_offset_secs': forms.NumberInput( attrs = { 'class': 'form-control' } ),
+ 'expires_offset_secs': forms.NumberInput( attrs = { 'class': 'form-control' } ),
+ }
+ labels = {
+ 'event_code': 'NWS Event Code',
+ 'event_name': 'Event',
+ 'severity_str': 'Severity',
+ 'certainty_str': 'Certainty',
+ 'urgency_str': 'Urgency',
+ 'status_str': 'Status',
+ 'category_str': 'Category',
+ 'area_desc': 'Affected Areas',
+ 'effective_offset_secs': 'Effective Offset (sec)',
+ 'expires_offset_secs': 'Expires Offset (sec)',
+ }
diff --git a/src/hi/simulator/weather_sources/nws/migrations/0001_initial.py b/src/hi/simulator/weather_sources/nws/migrations/0001_initial.py
new file mode 100644
index 00000000..c9f6cd59
--- /dev/null
+++ b/src/hi/simulator/weather_sources/nws/migrations/0001_initial.py
@@ -0,0 +1,196 @@
+# Generated by Django 5.2.14 on 2026-05-19 20:11
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ ("simulator_profile", "0001_initial"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="NwsSimAlert",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "is_active",
+ models.BooleanField(
+ default=True,
+ help_text="Include this alert in the simulated active-alerts feed.",
+ ),
+ ),
+ (
+ "event_code",
+ models.CharField(
+ blank=True,
+ choices=[
+ ("", "— None —"),
+ ("TOR", "TOR — Tornado Warning"),
+ ("TOA", "TOA — Tornado Watch"),
+ ("SVR", "SVR — Severe Thunderstorm Warning"),
+ ("SVA", "SVA — Severe Thunderstorm Watch"),
+ ("FFW", "FFW — Flash Flood Warning"),
+ ("FFA", "FFA — Flash Flood Watch"),
+ ("FLW", "FLW — Flood Warning"),
+ ("FLA", "FLA — Flood Watch"),
+ ("EWW", "EWW — Extreme Wind Warning"),
+ ("HWW", "HWW — High Wind Warning"),
+ ("BZW", "BZW — Blizzard Warning"),
+ ("WSW", "WSW — Winter Storm Warning"),
+ ("WSA", "WSA — Winter Storm Watch"),
+ ("HUW", "HUW — Hurricane Warning"),
+ ("HUA", "HUA — Hurricane Watch"),
+ ("TRW", "TRW — Tropical Storm Warning"),
+ ("TRA", "TRA — Tropical Storm Watch"),
+ ("TSW", "TSW — Tsunami Warning"),
+ ("TSA", "TSA — Tsunami Watch"),
+ ("FRW", "FRW — Fire Warning"),
+ ("RFW", "RFW — Red Flag Warning"),
+ ("AFW", "AFW — Ashfall Warning"),
+ ("EQW", "EQW — Earthquake Warning"),
+ ("AQA", "AQA — Air Quality Alert"),
+ ("CDW", "CDW — Civil Danger Warning"),
+ ("CEM", "CEM — Civil Emergency Message"),
+ ("LAE", "LAE — Local Area Emergency"),
+ ("TST", "TST — Test Message"),
+ ],
+ default="",
+ help_text="NWS three-letter event code (drives main-app event type mapping).",
+ max_length=8,
+ ),
+ ),
+ (
+ "event_name",
+ models.CharField(
+ default="Test Alert",
+ help_text='Human-readable event name (e.g. "Air Quality Alert").',
+ max_length=128,
+ ),
+ ),
+ (
+ "severity_str",
+ models.CharField(
+ choices=[
+ ("Extreme", "Extreme"),
+ ("Severe", "Severe"),
+ ("Moderate", "Moderate"),
+ ("Minor", "Minor"),
+ ("Unknown", "Unknown"),
+ ],
+ default="Minor",
+ max_length=16,
+ ),
+ ),
+ (
+ "certainty_str",
+ models.CharField(
+ choices=[
+ ("Observed", "Observed"),
+ ("Likely", "Likely"),
+ ("Possible", "Possible"),
+ ("Unlikely", "Unlikely"),
+ ("Unknown", "Unknown"),
+ ],
+ default="Possible",
+ max_length=16,
+ ),
+ ),
+ (
+ "urgency_str",
+ models.CharField(
+ choices=[
+ ("Immediate", "Immediate"),
+ ("Expected", "Expected"),
+ ("Future", "Future"),
+ ("Unknown", "Unknown"),
+ ],
+ default="Expected",
+ max_length=16,
+ ),
+ ),
+ (
+ "status_str",
+ models.CharField(
+ choices=[
+ ("Actual", "Actual"),
+ ("Exercise", "Exercise"),
+ ("System", "System"),
+ ("Test", "Test"),
+ ("Draft", "Draft"),
+ ],
+ default="Actual",
+ max_length=16,
+ ),
+ ),
+ (
+ "category_str",
+ models.CharField(
+ choices=[
+ ("met", "Meteorological"),
+ ("geo", "Geological"),
+ ("safety", "Public Safety"),
+ ("security", "Security"),
+ ("rescue", "Rescue"),
+ ("fire", "Fire"),
+ ("health", "Health"),
+ ("env", "Environmental"),
+ ("transport", "Transportation"),
+ ("infra", "Infrastructure"),
+ ("other", "Other"),
+ ],
+ default="met",
+ max_length=16,
+ ),
+ ),
+ ("headline", models.CharField(default="", max_length=512)),
+ ("description", models.TextField(default="")),
+ ("instruction", models.TextField(blank=True, default="")),
+ (
+ "area_desc",
+ models.CharField(default="Simulator Test Area", max_length=255),
+ ),
+ (
+ "effective_offset_secs",
+ models.IntegerField(
+ default=-60,
+ help_text='When the alert becomes effective, relative to "now" in seconds. Negative = in the past, positive = in the future.',
+ ),
+ ),
+ (
+ "expires_offset_secs",
+ models.IntegerField(
+ default=3600,
+ help_text='When the alert expires, relative to "now" in seconds.',
+ ),
+ ),
+ ("created_datetime", models.DateTimeField(auto_now_add=True)),
+ ("updated_datetime", models.DateTimeField(auto_now=True)),
+ (
+ "sim_profile",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="nws_sim_alerts",
+ to="simulator_profile.simprofile",
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "NWS Sim Alert",
+ "verbose_name_plural": "NWS Sim Alerts",
+ "ordering": ["-created_datetime"],
+ },
+ ),
+ ]
diff --git a/src/hi/simulator/weather_sources/nws/migrations/__init__.py b/src/hi/simulator/weather_sources/nws/migrations/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/simulator/weather_sources/nws/models.py b/src/hi/simulator/weather_sources/nws/models.py
new file mode 100644
index 00000000..c440c83f
--- /dev/null
+++ b/src/hi/simulator/weather_sources/nws/models.py
@@ -0,0 +1,86 @@
+from django.db import models
+
+from hi.simulator.profile.models import SimProfile
+
+from . import constants
+
+
+class NwsSimAlert( models.Model ):
+ """One operator-managed simulated NWS alert.
+
+ The alerts/active API endpoint converts active rows to NWS-shaped
+ GeoJSON on each request, so ``effective`` and ``expires`` stay
+ fresh (relative offsets, not stored timestamps).
+ """
+
+ class Meta:
+ verbose_name = 'NWS Sim Alert'
+ verbose_name_plural = 'NWS Sim Alerts'
+ ordering = [ '-created_datetime' ]
+
+ sim_profile = models.ForeignKey(
+ SimProfile,
+ related_name = 'nws_sim_alerts',
+ on_delete = models.CASCADE,
+ )
+ is_active = models.BooleanField(
+ default = True,
+ help_text = 'Include this alert in the simulated active-alerts feed.',
+ )
+ event_code = models.CharField(
+ max_length = 8,
+ choices = constants.EVENT_CODE_CHOICES,
+ blank = True,
+ default = '',
+ help_text = 'NWS three-letter event code (drives main-app event type mapping).',
+ )
+ event_name = models.CharField(
+ max_length = 128,
+ default = 'Test Alert',
+ help_text = 'Human-readable event name (e.g. "Air Quality Alert").',
+ )
+ severity_str = models.CharField(
+ max_length = 16,
+ choices = constants.SEVERITY_CHOICES,
+ default = 'Minor',
+ )
+ certainty_str = models.CharField(
+ max_length = 16,
+ choices = constants.CERTAINTY_CHOICES,
+ default = 'Possible',
+ )
+ urgency_str = models.CharField(
+ max_length = 16,
+ choices = constants.URGENCY_CHOICES,
+ default = 'Expected',
+ )
+ status_str = models.CharField(
+ max_length = 16,
+ choices = constants.STATUS_CHOICES,
+ default = 'Actual',
+ )
+ category_str = models.CharField(
+ max_length = 16,
+ choices = constants.CATEGORY_CHOICES,
+ default = 'met',
+ )
+ headline = models.CharField( max_length = 512, default = '' )
+ description = models.TextField( default = '' )
+ instruction = models.TextField( blank = True, default = '' )
+ area_desc = models.CharField( max_length = 255, default = 'Simulator Test Area' )
+ effective_offset_secs = models.IntegerField(
+ default = -60,
+ help_text = (
+ 'When the alert becomes effective, relative to "now" in seconds. '
+ 'Negative = in the past, positive = in the future.'
+ ),
+ )
+ expires_offset_secs = models.IntegerField(
+ default = 3600,
+ help_text = 'When the alert expires, relative to "now" in seconds.',
+ )
+ created_datetime = models.DateTimeField( auto_now_add = True )
+ # Bumped on every save so the NWS-shaped feature id changes each
+ # time the row is modified, matching real NWS behavior where any
+ # Update / Cancel issuance carries a new identifier.
+ updated_datetime = models.DateTimeField( auto_now = True )
diff --git a/src/hi/simulator/weather_sources/nws/templates/weather_sources/nws/modals/alert_delete.html b/src/hi/simulator/weather_sources/nws/templates/weather_sources/nws/modals/alert_delete.html
new file mode 100644
index 00000000..ae1d268d
--- /dev/null
+++ b/src/hi/simulator/weather_sources/nws/templates/weather_sources/nws/modals/alert_delete.html
@@ -0,0 +1,32 @@
+{% extends "modals/action_with_cancel.html" %}
+{% load icons %}
+
+{% block preamble %}
+<form action="{% url 'simulator_weather_nws_alert_delete' alert_id=alert.id %}"
+ method="post" class="form" data-async="modal">
+ {% csrf_token %}
+{% endblock %}
+
+{% block title_text %}
+Delete NWS Alert
+{% endblock %}
+
+{% block body %}
+<div>
+ <p>
+ Delete simulated alert
+ <strong>{{ alert.event_name }}</strong>
+ ({{ alert.severity_str }})?
+ </p>
+</div>
+{% endblock %}
+
+{% block action_right %}
+<button type="submit" class="btn btn-danger" name="action" value="delete">
+ {% icon "delete" size="sm" css_class="hi-icon-left" %}DELETE
+</button>
+{% endblock %}
+
+{% block postamble %}
+</form>
+{% endblock %}
diff --git a/src/hi/simulator/weather_sources/nws/templates/weather_sources/nws/modals/alert_form.html b/src/hi/simulator/weather_sources/nws/templates/weather_sources/nws/modals/alert_form.html
new file mode 100644
index 00000000..840aad2c
--- /dev/null
+++ b/src/hi/simulator/weather_sources/nws/templates/weather_sources/nws/modals/alert_form.html
@@ -0,0 +1,53 @@
+{% extends "modals/action_with_cancel.html" %}
+{% load icons %}
+
+{% block modal_dialog_class %}hi-modal-dialog-600{% endblock %}
+
+{% block preamble %}
+<form action="{% if is_add %}{% url 'simulator_weather_nws_alert_add' %}{% else %}{% url 'simulator_weather_nws_alert_edit' alert_id=alert.id %}{% endif %}"
+ method="post" class="form" data-async="modal">
+ {% csrf_token %}
+{% endblock %}
+
+{% block title_text %}
+{% if is_add %}New NWS Alert{% else %}Edit NWS Alert{% endif %}
+{% endblock %}
+
+{% block body %}
+<div>
+ {% if form.non_field_errors %}
+ <div class="non-field-errors">
+ {% for err in form.non_field_errors %}
+ <p class="form-error text-danger">ERROR: {{ err }}</p>
+ {% endfor %}
+ </div>
+ {% endif %}
+
+ <div class="form-group">
+ {{ form.is_active }}
+ <label for="{{ form.is_active.id_for_label }}">Active (include in feed)</label>
+ </div>
+
+ {% for field in form %}
+ {% if field.name != 'is_active' %}
+ <div class="form-group">
+ <label for="{{ field.id_for_label }}">{{ field.label }}</label>
+ {{ field }}
+ {% if field.help_text %}<small class="text-muted">{{ field.help_text }}</small>{% endif %}
+ {% if field.errors %}<small class="form-error text-danger">{{ field.errors }}</small>{% endif %}
+ </div>
+ {% endif %}
+ {% endfor %}
+</div>
+{% endblock %}
+
+{% block action_right %}
+<button type="submit" class="btn btn-primary"
+ name="action" value="{% if is_add %}add{% else %}edit{% endif %}">
+ {% icon "save" size="sm" css_class="hi-icon-left" %}{% if is_add %}ADD{% else %}UPDATE{% endif %}
+</button>
+{% endblock %}
+
+{% block postamble %}
+</form>
+{% endblock %}
diff --git a/src/hi/simulator/weather_sources/nws/templates/weather_sources/nws/tab.html b/src/hi/simulator/weather_sources/nws/templates/weather_sources/nws/tab.html
new file mode 100644
index 00000000..b658a502
--- /dev/null
+++ b/src/hi/simulator/weather_sources/nws/templates/weather_sources/nws/tab.html
@@ -0,0 +1,80 @@
+{% load icons %}
+<div class="nws-sim-alert-tab">
+ <div class="d-flex justify-content-between align-items-center my-3">
+ <div class="text-muted small">
+ To route NWS API calls here, paste this into the main app's
+ Weather settings under <em>NWS Base URL</em>:
+ <code>{{ request.scheme }}://{{ request.get_host }}/weather/nws/api/</code>
+ </div>
+ <a class="btn btn-sm btn-outline-primary" data-async="modal"
+ href="{% url 'simulator_weather_nws_alert_add' %}">
+ {% icon "plus" size="sm" css_class="hi-icon-left" %}Add Alert
+ </a>
+ </div>
+
+ {% load nws_sim_alert_tags %}
+ {% nws_sim_alert_list as nws_sim_alert_list %}
+
+ {% if nws_sim_alert_list %}
+ <table class="table table-sm">
+ <thead>
+ <tr>
+ <th style="width: 4rem;">Active</th>
+ <th>Event</th>
+ <th>Severity</th>
+ <th>Certainty</th>
+ <th>Urgency</th>
+ <th>Effective / Expires</th>
+ <th style="width: 6rem;"></th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for alert in nws_sim_alert_list %}
+ <tr>
+ <td>
+ <form action="{% url 'simulator_weather_nws_alert_toggle' alert_id=alert.id %}"
+ method="post" class="form m-0" data-async="true">
+ {% csrf_token %}
+ <label class="switch">
+ <input type="checkbox" {% if alert.is_active %}checked{% endif %}
+ onchange-async="true">
+ <span class="slider"></span>
+ </label>
+ </form>
+ </td>
+ <td>
+ <div><strong>{{ alert.event_name }}</strong></div>
+ {% if alert.event_code %}
+ <small class="text-muted">{{ alert.event_code }}</small>
+ {% endif %}
+ </td>
+ <td>{{ alert.severity_str }}</td>
+ <td>{{ alert.certainty_str }}</td>
+ <td>{{ alert.urgency_str }}</td>
+ <td>
+ <small>
+ {{ alert.effective_offset_secs }}s / +{{ alert.expires_offset_secs }}s
+ </small>
+ </td>
+ <td class="text-right">
+ <a class="btn btn-sm btn-primary sim-icon-btn" data-async="modal"
+ href="{% url 'simulator_weather_nws_alert_edit' alert_id=alert.id %}"
+ title="Edit">
+ {% icon "edit" size="sm" %}
+ </a>
+ <a class="btn btn-sm btn-danger sim-icon-btn" data-async="modal"
+ href="{% url 'simulator_weather_nws_alert_delete' alert_id=alert.id %}"
+ title="Delete">
+ {% icon "delete" size="sm" %}
+ </a>
+ </td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ {% else %}
+ <div class="alert alert-info">
+ No simulated alerts defined. Use <strong>Add Alert</strong> to create one.
+ </div>
+ {% endif %}
+</div>
diff --git a/src/hi/simulator/weather_sources/nws/templatetags/__init__.py b/src/hi/simulator/weather_sources/nws/templatetags/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/simulator/weather_sources/nws/templatetags/nws_sim_alert_tags.py b/src/hi/simulator/weather_sources/nws/templatetags/nws_sim_alert_tags.py
new file mode 100644
index 00000000..0f981ded
--- /dev/null
+++ b/src/hi/simulator/weather_sources/nws/templatetags/nws_sim_alert_tags.py
@@ -0,0 +1,19 @@
+from django import template
+
+from hi.simulator.profile.profile_manager import ProfileManager
+
+from ..apps import NwsWeatherSimConfig
+from ..models import NwsSimAlert
+
+register = template.Library()
+
+
+def nws_sim_alert_list():
+ """Alerts under NWS's currently-selected profile, newest first."""
+ current_profile = ProfileManager().get_current( NwsWeatherSimConfig.name )
+ return list(
+ NwsSimAlert.objects
+ .filter( sim_profile = current_profile )
+ .order_by( '-created_datetime' )
+ )
diff --git a/src/hi/simulator/weather_sources/nws/urls.py b/src/hi/simulator/weather_sources/nws/urls.py
new file mode 100644
index 00000000..4284d066
--- /dev/null
+++ b/src/hi/simulator/weather_sources/nws/urls.py
@@ -0,0 +1,26 @@
+from django.urls import path
+
+from . import views
+
+
+urlpatterns = [
+ path( 'api/alerts/active',
+ views.NwsAlertsActiveView.as_view(),
+ name = 'simulator_weather_nws_alerts_active' ),
+
+ path( 'alert/add',
+ views.NwsSimAlertAddView.as_view(),
+ name = 'simulator_weather_nws_alert_add' ),
+
+ path( 'alert/<int:alert_id>/edit',
+ views.NwsSimAlertEditView.as_view(),
+ name = 'simulator_weather_nws_alert_edit' ),
+
+ path( 'alert/<int:alert_id>/delete',
+ views.NwsSimAlertDeleteView.as_view(),
+ name = 'simulator_weather_nws_alert_delete' ),
+
+ path( 'alert/<int:alert_id>/toggle',
+ views.NwsSimAlertToggleView.as_view(),
+ name = 'simulator_weather_nws_alert_toggle' ),
+]
diff --git a/src/hi/simulator/weather_sources/nws/views.py b/src/hi/simulator/weather_sources/nws/views.py
new file mode 100644
index 00000000..544116b5
--- /dev/null
+++ b/src/hi/simulator/weather_sources/nws/views.py
@@ -0,0 +1,133 @@
+import logging
+from datetime import timedelta
+from typing import Any, Dict, List
+
+from django.http import JsonResponse
+from django.shortcuts import get_object_or_404, render
+from django.views.generic import View
+
+import hi.apps.common.antinode as antinode
+import hi.apps.common.datetimeproxy as datetimeproxy
+
+from .forms import NwsSimAlertForm
+from .models import NwsSimAlert
+
+logger = logging.getLogger(__name__)
+
+
+class NwsAlertsActiveView( View ):
+ """NWS-shaped /alerts/active endpoint backed by NwsSimAlert rows."""
+
+ def get( self, request, *args, **kwargs ):
+ features : List[ Dict[str, Any] ] = []
+ now = datetimeproxy.now()
+ for alert in NwsSimAlert.objects.filter( is_active = True ):
+ effective = now + timedelta( seconds = alert.effective_offset_secs )
+ expires = now + timedelta( seconds = alert.expires_offset_secs )
+ properties : Dict[ str, Any ] = {
+ 'event': alert.event_name,
+ 'headline': alert.headline,
+ 'description': alert.description,
+ 'instruction': alert.instruction,
+ 'areaDesc': alert.area_desc,
+ 'status': alert.status_str,
+ 'severity': alert.severity_str,
+ 'urgency': alert.urgency_str,
+ 'certainty': alert.certainty_str,
+ 'category': alert.category_str,
+ 'effective': effective.isoformat(),
+ 'expires': expires.isoformat(),
+ 'onset': effective.isoformat(),
+ 'ends': expires.isoformat(),
+ }
+ if alert.event_code:
+ properties['eventCode'] = {
+ 'NationalWeatherService': [ alert.event_code ],
+ }
+ # Feature id changes on each row save (toggle / edit) so
+ # the main app treats each issuance as distinct, matching
+ # real NWS where every Update / Cancel publishes a new
+ # identifier. Repeat polls of an unchanged row share the
+ # same id.
+ issuance = int( alert.updated_datetime.timestamp() )
+ features.append({
+ 'id': f'sim-nws-alert-{alert.id}-{issuance}',
+ 'properties': properties,
+ })
+ return JsonResponse( { 'features': features } )
+
+
+class NwsSimAlertAddView( View ):
+
+ MODAL_TEMPLATE = 'weather_sources/nws/modals/alert_form.html'
+
+ def get( self, request, *args, **kwargs ):
+ context = {
+ 'form': NwsSimAlertForm(),
+ 'is_add': True,
+ }
+ return render( request, self.MODAL_TEMPLATE, context )
+
+ def post( self, request, *args, **kwargs ):
+ form = NwsSimAlertForm( request.POST )
+ if not form.is_valid():
+ return render( request, self.MODAL_TEMPLATE, {
+ 'form': form,
+ 'is_add': True,
+ })
+ form.save()
+ return antinode.refresh_response()
+
+
+class NwsSimAlertEditView( View ):
+
+ MODAL_TEMPLATE = 'weather_sources/nws/modals/alert_form.html'
+
+ def get( self, request, alert_id, *args, **kwargs ):
+ alert = get_object_or_404( NwsSimAlert, id = alert_id )
+ context = {
+ 'form': NwsSimAlertForm( instance = alert ),
+ 'alert': alert,
+ 'is_add': False,
+ }
+ return render( request, self.MODAL_TEMPLATE, context )
+
+ def post( self, request, alert_id, *args, **kwargs ):
+ alert = get_object_or_404( NwsSimAlert, id = alert_id )
+ form = NwsSimAlertForm( request.POST, instance = alert )
+ if not form.is_valid():
+ return render( request, self.MODAL_TEMPLATE, {
+ 'form': form,
+ 'alert': alert,
+ 'is_add': False,
+ })
+ form.save()
+ return antinode.refresh_response()
+
+
+class NwsSimAlertDeleteView( View ):
+
+ MODAL_TEMPLATE = 'weather_sources/nws/modals/alert_delete.html'
+
+ def get( self, request, alert_id, *args, **kwargs ):
+ alert = get_object_or_404( NwsSimAlert, id = alert_id )
+ return render( request, self.MODAL_TEMPLATE, { 'alert': alert })
+
+ def post( self, request, alert_id, *args, **kwargs ):
+ alert = get_object_or_404( NwsSimAlert, id = alert_id )
+ alert.delete()
+ return antinode.refresh_response()
+
+
+class NwsSimAlertToggleView( View ):
+
+ def post( self, request, alert_id, *args, **kwargs ):
+ alert = get_object_or_404( NwsSimAlert, id = alert_id )
+ alert.is_active = not alert.is_active
+ # Save the whole row (not just is_active) so the auto_now
+ # ``updated_datetime`` is bumped — that timestamp drives the
+ # NWS-shaped feature id, and the main app's alarm dedup needs
+ # to see a fresh id when a previously-inactive alert is
+ # re-activated.
+ alert.save()
+ return antinode.refresh_response()
diff --git a/src/hi/simulator/weather_sources/registry.py b/src/hi/simulator/weather_sources/registry.py
new file mode 100644
index 00000000..932942a2
--- /dev/null
+++ b/src/hi/simulator/weather_sources/registry.py
@@ -0,0 +1,57 @@
+"""Registry/discovery for simulator weather-source apps.
+
+Each weather-source simulator is a Django app under
+``hi.simulator.weather_sources.<short_name>``. Its ``AppConfig`` carries the
+display metadata the simulator's weather page uses to build per-source
+tabs:
+
+* ``weather_source_short_name`` — slug used in URLs (e.g. ``nws``)
+* ``weather_source_label`` — human label for the tab (e.g.
+ ``National Weather Service``)
+* ``weather_source_tab_template`` — template included into the
+ weather page for that source's tab body
+
+Parallels ``hi.simulator.services.*`` discovery used by the services
+page.
+"""
+import logging
+from dataclasses import dataclass
+from typing import List
+
+from django.apps import apps as django_apps
+
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class WeatherSourceData:
+ module_key : str # full AppConfig.name; passes to profile URLs
+ short_name : str
+ label : str
+ tab_template : str
+
+
+def get_weather_source_data_list() -> List[ WeatherSourceData ]:
+ results : List[ WeatherSourceData ] = []
+ for app_config in django_apps.get_app_configs():
+ if not app_config.name.startswith( 'hi.simulator.weather_sources.' ):
+ continue
+ try:
+ results.append(
+ WeatherSourceData(
+ module_key = app_config.name,
+ short_name = app_config.weather_source_short_name,
+ label = app_config.weather_source_label,
+ tab_template = app_config.weather_source_tab_template,
+ )
+ )
+ except AttributeError:
+ logger.warning(
+ f'Weather simulator app {app_config.name} is missing one of '
+ 'weather_source_short_name / weather_source_label / '
+ 'weather_source_tab_template attributes; skipping.'
+ )
+ continue
+ results.sort( key = lambda item : item.label )
+ return results
diff --git a/src/hi/simulator/weather_sources/templates/weather_sources/pages/empty.html b/src/hi/simulator/weather_sources/templates/weather_sources/pages/empty.html
new file mode 100644
index 00000000..b2fa1613
--- /dev/null
+++ b/src/hi/simulator/weather_sources/templates/weather_sources/pages/empty.html
@@ -0,0 +1,14 @@
+{% extends "pages/tabbed.html" %}
+
+{% block tab_body %}
+<div class="container-fluid sim-placeholder">
+ <div class="sim-placeholder-card">
+ <h2>Weather Simulators</h2>
+ <p class="text-muted mb-0">
+ No weather source simulators are registered. Add a
+ <code>hi.simulator.weather_sources.&lt;source&gt;</code> app to
+ INSTALLED_APPS to start simulating a weather API.
+ </p>
+ </div>
+</div>
+{% endblock %}
diff --git a/src/hi/simulator/weather_sources/templates/weather_sources/pages/source.html b/src/hi/simulator/weather_sources/templates/weather_sources/pages/source.html
new file mode 100644
index 00000000..d96d605a
--- /dev/null
+++ b/src/hi/simulator/weather_sources/templates/weather_sources/pages/source.html
@@ -0,0 +1,8 @@
+{% extends "pages/tabbed.html" %}
+
+{% block tab_body %}
+<div class="d-flex align-items-center mb-2">
+ {% include "profile/panes/profile_selector.html" with module=module profile_list=profile_list current_profile=current_profile %}
+</div>
+{% include source_data.tab_template %}
+{% endblock %}
diff --git a/src/hi/simulator/weather_sources/urls.py b/src/hi/simulator/weather_sources/urls.py
new file mode 100644
index 00000000..2d90a6de
--- /dev/null
+++ b/src/hi/simulator/weather_sources/urls.py
@@ -0,0 +1,48 @@
+import logging
+
+from django.apps import apps
+from django.urls import include, path, re_path
+
+from hi.apps.common.module_utils import import_module_safe
+
+from . import views
+
+logger = logging.getLogger(__name__)
+
+
+urlpatterns = [
+ path( '',
+ views.WeatherIndexView.as_view(),
+ name = 'simulator_weather' ),
+
+ path( 'tab/<slug:short_name>/',
+ views.WeatherSourceView.as_view(),
+ name = 'simulator_weather_source' ),
+]
+
+
+def discover_weather_source_urls():
+ """ Add urls (if any) from all simulated weather-source apps """
+ discovered_url_modules = dict()
+ for app_config in apps.get_app_configs():
+ if not app_config.name.startswith( 'hi.simulator.weather_sources.' ):
+ continue
+ module_name = f'{app_config.name}.urls'
+ short_name = app_config.name.split('.')[-1]
+ try:
+ urls_module = import_module_safe( module_name = module_name )
+ if not urls_module:
+ continue
+ discovered_url_modules[short_name] = urls_module
+ except Exception:
+ logger.exception( f'Problem importing URL module: {module_name}' )
+ pass
+ continue
+ return discovered_url_modules
+
+
+for short_name, urls_module in discover_weather_source_urls().items():
+ urlpatterns.append(
+ re_path( f"{short_name}/", include( urls_module ))
+ )
+ continue
diff --git a/src/hi/simulator/weather_sources/views.py b/src/hi/simulator/weather_sources/views.py
new file mode 100644
index 00000000..fec29e48
--- /dev/null
+++ b/src/hi/simulator/weather_sources/views.py
@@ -0,0 +1,69 @@
+from django.http import Http404, HttpResponseRedirect
+from django.shortcuts import render
+from django.urls import reverse
+from django.views.generic import View
+
+from hi.simulator.profile.profile_manager import ProfileManager
+
+from .registry import get_weather_source_data_list
+
+
+def _build_weather_tab_specs( active_short_name : str ):
+ """Tab strip data for the Weather section. Each entry routes to
+ its own URL (``simulator_weather_source``)."""
+ specs = []
+ for source_data in get_weather_source_data_list():
+ specs.append({
+ 'label': source_data.label,
+ 'url': reverse( 'simulator_weather_source',
+ kwargs = { 'short_name': source_data.short_name } ),
+ 'is_active': ( source_data.short_name == active_short_name ),
+ })
+ continue
+ return specs
+
+
+class WeatherIndexView( View ):
+ """Default ``/weather/`` route — redirects to the first registered
+ weather source's per-tab URL."""
+
+ def get(self, request, *args, **kwargs):
+ source_data_list = get_weather_source_data_list()
+ if not source_data_list:
+ return render( request, 'weather_sources/pages/empty.html',
+ { 'active_section': 'weather',
+ 'tab_specs': [] } )
+ first = source_data_list[0]
+ return HttpResponseRedirect(
+ reverse( 'simulator_weather_source',
+ kwargs = { 'short_name': first.short_name } )
+ )
+
+
+class WeatherSourceView( View ):
+ """Renders a single weather source's tab body."""
+
+ def get(self, request, short_name, *args, **kwargs):
+ source_data = next(
+ ( s for s in get_weather_source_data_list()
+ if s.short_name == short_name ),
+ None,
+ )
+ if source_data is None:
+ raise Http404( f'Unknown weather source: {short_name!r}' )
+
+ profile_manager = ProfileManager()
+ context = {
+ 'active_section': 'weather',
+ 'tab_specs': _build_weather_tab_specs(
+ active_short_name = source_data.short_name,
+ ),
+ 'source_data': source_data,
+ 'module': {
+ 'module_key': source_data.module_key,
+ 'label': source_data.label,
+ },
+ 'profile_list': profile_manager.list_profiles( source_data.module_key ),
+ 'current_profile': profile_manager.get_current( source_data.module_key ),
+ }
+ return render( request, 'weather_sources/pages/source.html', context )
diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.css
index c4c1f89d..d715c178 100644
--- a/src/hi/static/css/main.css
+++ b/src/hi/static/css/main.css
@@ -590,6 +590,8 @@ a.clickable-card:active {
.btn-control {
width: 100%;
white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
font-size: 0.75rem;
font-weight: bold;
}
@@ -750,8 +752,14 @@ g[status="on"] path.hi-state-bg {
background-color: var(--status-on-color);
}
g[status="dim"] {
- filter: drop-shadow(0 0 5px var(--status-on-color));
- opacity: 0.5;
+ /* Smaller blur than "on" so the glow reads as less intense.
+ * The opacity for the fill is handled on the .hi-state-bg path
+ * below (via fill-opacity) so the SVG outline stays solid. */
+ filter: drop-shadow(0 0 3px var(--status-on-color));
+}
+g[status="dim"] path.hi-state-bg {
+ fill: var(--status-on-color);
+ fill-opacity: 0.5;
}
.hi-status-display[status="dim"] {
color: var(--on-status-on-color);
@@ -2232,3 +2240,87 @@ g[hover] {
background: rgba(0, 0, 0, 0.9);
transform: scale(0.92);
}
+
+/* ===== Event definition (trigger rule) edit modal ===== */
+
+.event-edit-field {
+ margin-bottom: 0.6rem;
+}
+.event-edit-field .input-group-text {
+ min-width: 9rem;
+ background-color: #f5f5f5;
+ border-color: var(--line-color);
+}
+.event-edit-field .form-control,
+.event-edit-field .custom-select {
+ flex: 1 1 auto;
+}
+.event-edit-field .form-error {
+ display: block;
+ margin-top: 0.15rem;
+ padding-left: 0.25rem;
+}
+
+.event-edit-toggle {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ margin: 0.75rem 0 1rem;
+}
+.event-edit-toggle label {
+ margin: 0;
+}
+
+.event-edit-section {
+ margin-top: 1.25rem;
+ padding-top: 0.75rem;
+ border-top: 1px solid var(--line-color);
+}
+.event-edit-section-heading {
+ color: var(--primary-color);
+ font-size: 1rem;
+ font-weight: 600;
+ letter-spacing: 0.03em;
+ text-transform: uppercase;
+ margin: 0 0 0.5rem;
+}
+
+.event-edit-action-card {
+ border: 1px solid var(--line-color);
+ border-radius: 0.25rem;
+ background-color: #fafafa;
+ padding: 0.6rem 0.75rem;
+ margin-bottom: 0.6rem;
+}
+.event-edit-action-card-head {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 0.5rem;
+}
+.event-edit-action-card-label {
+ font-weight: 600;
+ color: var(--primary-color);
+ font-size: 0.9rem;
+}
+.event-edit-action-card-new {
+ background-color: var(--white-bg-color);
+}
+
+.event-edit-remove {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+ margin: 0;
+ font-size: 0.8rem;
+ color: var(--muted-color);
+ cursor: pointer;
+}
+.event-edit-remove input[type="checkbox"]:checked + span {
+ color: var(--error-color);
+ font-weight: 600;
+}
+
+.event-edit-add {
+ margin: 0.5rem 0;
+}
diff --git a/src/hi/static/css/simulator.css b/src/hi/static/css/simulator.css
index 30f132d2..3d492907 100644
--- a/src/hi/static/css/simulator.css
+++ b/src/hi/static/css/simulator.css
@@ -27,6 +27,169 @@
--top-buttons-height: 2.5rem;
--bottom-buttons-height: 2.5rem;
+
+ --sim-top-nav-height: 3rem;
+}
+
+.sim-top-nav {
+ display: flex;
+ align-items: center;
+ height: var(--sim-top-nav-height);
+ padding: 0 1rem;
+ background-color: var(--primary-color);
+ color: var(--on-primary-color);
+ border-bottom: 2px solid var(--secondary-color);
+}
+.sim-top-nav-brand {
+ display: flex;
+ align-items: center;
+ margin-right: 1.5rem;
+}
+.sim-top-nav-logo {
+ width: 1.5rem;
+ height: 1.5rem;
+ margin-right: 0.5rem;
+}
+.sim-top-nav-title {
+ font-weight: bold;
+ font-size: 1.05rem;
+ letter-spacing: 0.02em;
+}
+.sim-top-nav-links {
+ display: flex;
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ height: 100%;
+}
+.sim-top-nav-links li {
+ height: 100%;
+}
+.sim-top-nav-link {
+ display: flex;
+ align-items: center;
+ height: 100%;
+ padding: 0 1rem;
+ color: var(--on-primary-color);
+ text-decoration: none;
+ border-bottom: 3px solid transparent;
+}
+.sim-top-nav-link:hover,
+.sim-top-nav-link:focus {
+ color: var(--on-primary-color);
+ background-color: rgba(255, 255, 255, 0.08);
+ text-decoration: none;
+ opacity: 1;
+}
+.sim-top-nav-link.active {
+ border-bottom-color: var(--secondary-color);
+ background-color: rgba(0, 0, 0, 0.15);
+}
+
+.sim-main {
+ padding: 1rem 1.25rem;
+}
+
+.sim-profile-header {
+ padding: 0.5rem 0.25rem 0.75rem;
+ margin-bottom: 0.5rem;
+ border-bottom: 1px solid var(--line-color);
+ gap: 0.75rem 1rem;
+}
+.sim-profile-name {
+ display: inline-flex;
+ align-items: baseline;
+ gap: 0.5rem;
+}
+.sim-profile-name small {
+ font-size: 0.7rem;
+ letter-spacing: 0.05em;
+}
+.sim-profile-name-value {
+ font-size: 1.15rem;
+ font-weight: 600;
+}
+.sim-profile-actions .btn + .btn {
+ margin-left: 0;
+}
+.sim-profile-actions .btn {
+ display: inline-flex;
+ align-items: center;
+ line-height: 1.2;
+}
+.sim-profile-actions .btn .hi-icon {
+ vertical-align: middle;
+ width: 0.875rem;
+ height: 0.875rem;
+ flex: 0 0 auto;
+}
+
+.sim-main .nav-tabs {
+ margin-top: 1rem;
+ border-bottom-color: var(--line-color);
+}
+.sim-main .nav-tabs .nav-link {
+ color: var(--tertiary-color);
+ border: none;
+ border-bottom: 2px solid transparent;
+ padding: 0.5rem 1rem;
+}
+.sim-main .nav-tabs .nav-link:hover {
+ color: var(--primary-color);
+ background-color: transparent;
+ border-color: transparent transparent var(--line-color);
+}
+.sim-main .nav-tabs .nav-link.active {
+ color: var(--primary-color);
+ background-color: transparent;
+ border-color: transparent transparent var(--primary-color);
+ font-weight: 600;
+}
+.sim-main .tab-content {
+ padding-top: 0.75rem;
+}
+
+.sim-entity-row {
+ align-items: center;
+ padding: 0.4rem 0;
+ margin: 0;
+ border-bottom: 1px solid var(--line-color);
+}
+.sim-entity-row:last-child {
+ border-bottom: none;
+}
+.sim-entity-name {
+ font-weight: 500;
+}
+.sim-entity-actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: 0.4rem;
+}
+.sim-icon-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0.4rem 0.65rem;
+ line-height: 1;
+}
+.sim-icon-btn .hi-icon {
+ margin: 0;
+ width: 1.1rem;
+ height: 1.1rem;
+}
+
+.sim-placeholder {
+ padding-top: 2rem;
+}
+.sim-placeholder-card {
+ max-width: 36rem;
+ margin: 2rem auto;
+ padding: 2rem;
+ background-color: var(--white-bg-color);
+ border: 1px solid var(--line-color);
+ border-radius: 0.25rem;
+ text-align: center;
}
html, body {
diff --git a/src/hi/static/js/entity_state_status.js b/src/hi/static/js/entity_state_status.js
index 6fa1319e..f5df8bd0 100644
--- a/src/hi/static/js/entity_state_status.js
+++ b/src/hi/static/js/entity_state_status.js
@@ -150,6 +150,12 @@
}
function applyControllerValue( element, value ) {
+ // Skip if the user currently has this control focused: prevents
+ // poll updates from clobbering a value mid-edit on selects,
+ // text/number inputs, and freshly-clicked checkboxes. Slider
+ // drag does not always keep :focus, so the activeSliders
+ // WeakSet still handles that case below.
+ if ( element === document.activeElement ) return;
const tag = element.tagName;
if ( tag === 'INPUT' ) {
const type = element.type;
diff --git a/src/hi/static/js/simulator.js b/src/hi/static/js/simulator.js
index a6479b95..e533b311 100644
--- a/src/hi/static/js/simulator.js
+++ b/src/hi/static/js/simulator.js
@@ -1,5 +1,7 @@
(function() {
-
+
+ const POLL_INTERVAL_MS = 3000;
+
const HiSimulator = {
DEBUG: true,
@@ -13,8 +15,11 @@
submitForm: function( formElement ) {
return _submitForm( formElement );
},
+ startStatePolling: function( statesUrl, intervalMs ) {
+ return _startStatePolling( statesUrl, intervalMs );
+ },
};
-
+
window.HiSimulator = HiSimulator;
function _setCookie( name, value, days, sameSite ) {
@@ -34,13 +39,93 @@
return decodeURIComponent( cookie.substring( nameEQ.length ));
}
}
- return null;
+ return null;
}
-
+
function _submitForm( formElement ) {
let form = $(formElement).closest('form');
if ( Hi.DEBUG ) { console.debug( 'Submitting form:', formElement, form ); }
$(form).submit();
}
-
-})();
+
+ function _startStatePolling( statesUrl, intervalMs ) {
+ if ( ! statesUrl ) { return; }
+ const interval = intervalMs || POLL_INTERVAL_MS;
+ const poll = function() {
+ $.ajax({
+ url: statesUrl,
+ dataType: 'json',
+ global: false,
+ success: function( data ) {
+ if ( data && data.states ) {
+ _applyStates( data.states );
+ }
+ },
+ error: function( jqXHR, textStatus ) {
+ if ( HiSimulator.DEBUG ) {
+ console.warn( 'Simulator state poll failed:', textStatus );
+ }
+ },
+ });
+ };
+ setInterval( poll, interval );
+ }
+
+ function _applyStates( states ) {
+ Object.keys( states ).forEach( function( containerId ) {
+ const container = document.getElementById( containerId );
+ if ( ! container ) { return; }
+ if ( container.contains( document.activeElement )) { return; }
+ _updateStateValue( container, states[containerId] );
+ });
+ }
+
+ function _updateStateValue( container, value ) {
+ const range = container.querySelector( 'input[type="range"][name="value"]' );
+ if ( range ) {
+ if ( range.value !== value ) {
+ range.value = value;
+ const output = range.nextElementSibling;
+ if ( output && output.tagName === 'OUTPUT' ) {
+ const formatted = _formatNumericDisplay( value );
+ if ( output.value !== formatted ) { output.value = formatted; }
+ }
+ }
+ return;
+ }
+ const checkbox = container.querySelector( 'input[type="checkbox"][name="value"]' );
+ if ( checkbox ) {
+ const desired = _truthy( value );
+ if ( checkbox.checked !== desired ) { checkbox.checked = desired; }
+ return;
+ }
+ const select = container.querySelector( 'select[name="value"]' );
+ if ( select ) {
+ if ( select.value !== value ) { select.value = value; }
+ return;
+ }
+ }
+
+ function _formatNumericDisplay( value ) {
+ const num = parseFloat( value );
+ if ( Number.isNaN( num )) { return value; }
+ // Mirror Django's |floatformat:"-1" — strip trailing .0 for ints
+ return ( num % 1 === 0 ) ? String( num ) : String( num );
+ }
+
+ function _truthy( value ) {
+ if ( typeof value === 'boolean' ) { return value; }
+ const lowered = String( value ).trim().toLowerCase();
+ return ( lowered === 'true' || lowered === '1'
+ || lowered === 'on' || lowered === 'yes'
+ || lowered === 'open' || lowered === 'movement' );
+ }
+
+ $(document).ready( function() {
+ const main = document.querySelector( '.sim-main[data-states-url]' );
+ if ( main ) {
+ _startStatePolling( main.getAttribute( 'data-states-url' ));
+ }
+ });
+
+})();
diff --git a/src/hi/templates/icons/copy.html b/src/hi/templates/icons/copy.html
new file mode 100644
index 00000000..e186dafc
--- /dev/null
+++ b/src/hi/templates/icons/copy.html
@@ -0,0 +1,3 @@
+<svg class="{{ class_attr }}" viewBox="0 0 24 24" fill="currentColor" {{ accessibility_attrs }}>
+ <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
+</svg>
diff --git a/src/hi/templates/panes/top_buttons.html b/src/hi/templates/panes/top_buttons.html
index 489da8ec..83cdce46 100644
--- a/src/hi/templates/panes/top_buttons.html
+++ b/src/hi/templates/panes/top_buttons.html
@@ -20,7 +20,7 @@
<a class="btn btn-primary btn-control" role="button"
href="{% url 'location_edit_location_edit' location_id=request.view_parameters.location.id %}"
data-async="true" >
- {{ request.view_parameters.location.name }}
+ {% icon "info-circle" size="sm" css_class="hi-icon-left" %}{{ request.view_parameters.location.name }}
</a>
{% endif %}
</div>