Skip to content

Home Information - Your home, your data, organized.

Python

Post-release tweaks: simulator Scenes/video, status display, and UI refinements (#398)

Tony Cc77d81bcab55
diff --git a/src/hi/apps/alert/templates/alert/modals/alert_details.html b/src/hi/apps/alert/templates/alert/modals/alert_details.html
index df87a3bb..a58527c7 100644
--- a/src/hi/apps/alert/templates/alert/modals/alert_details.html
+++ b/src/hi/apps/alert/templates/alert/modals/alert_details.html
@@ -4,7 +4,7 @@
{% load video_tags %}
{% load icons %}
-{% block modal_dialog_class %}hi-modal-dialog-600{% endblock %}
+{% block modal_dialog_class %}hi-modal-dialog-600 hi-video-compact{% endblock %}
{% block header_class %}bg-secondary{% endblock %}
{% block title_text %}
diff --git a/src/hi/apps/collection/templates/collection/panes/collection_view.html b/src/hi/apps/collection/templates/collection/panes/collection_view.html
index c622ae3b..a83531df 100644
--- a/src/hi/apps/collection/templates/collection/panes/collection_view.html
+++ b/src/hi/apps/collection/templates/collection/panes/collection_view.html
@@ -1,4 +1,4 @@
-<div id="hi-collection-view-main" class="hi-collection-view draggable-container">
+<div id="hi-collection-view-main" class="hi-collection-view draggable-container hi-video-compact">
<div class="h4 pt-3"><small>Collection:</small> {{ collection.name }}</div>
{% if state_panel_data_list %}
diff --git a/src/hi/apps/common/svg_models.py b/src/hi/apps/common/svg_models.py
index d3f599ba..9a7a6787 100644
--- a/src/hi/apps/common/svg_models.py
+++ b/src/hi/apps/common/svg_models.py
@@ -228,6 +228,14 @@ class SvgStatusStyle:
@dataclass
class SvgItemPositionBounds:
+
+ # Canonical scale clamps for auto-placed/edited SVG items. These are
+ # placement policy, not per-Location data - both Location.svg_position_bounds
+ # and the placement scale heuristic reference them so the values stay in
+ # one place.
+ DEFAULT_MIN_SCALE = 0.1
+ DEFAULT_MAX_SCALE = 25.0
+
min_x : float
min_y : float
max_x : float
diff --git a/src/hi/apps/console/console_helper.py b/src/hi/apps/console/console_helper.py
index ee8eb5ac..8d73a502 100644
--- a/src/hi/apps/console/console_helper.py
+++ b/src/hi/apps/console/console_helper.py
@@ -70,6 +70,18 @@ class ConsoleSettingsHelper( Singleton, SettingsMixin ):
def get_auto_view_duration( self ) -> int:
return int( self.settings_manager().get_setting_value( ConsoleSetting.AUTO_VIEW_DURATION ) )
+ DEFAULT_STATUS_POLLING_INTERVAL_MS = 3000
+
+ def get_status_polling_interval_ms( self ) -> int:
+ # Stored in seconds (user-friendly); the client contract is in ms.
+ # Robust to an uninitialized/blank setting so the per-request
+ # context processor can call this unconditionally.
+ raw_value = self.settings_manager().get_setting_value( ConsoleSetting.STATUS_POLLING_INTERVAL )
+ try:
+ return int( raw_value ) * 1000
+ except ( TypeError, ValueError ):
+ return self.DEFAULT_STATUS_POLLING_INTERVAL_MS
+
@staticmethod
def compute_camera_short_names( entity_list : Iterable[ Entity ] ) -> Dict[ int, str ]:
"""Return a ``{entity.id: short_name}`` mapping for camera-button
diff --git a/src/hi/apps/console/settings.py b/src/hi/apps/console/settings.py
index a74bbe33..2d186445 100644
--- a/src/hi/apps/console/settings.py
+++ b/src/hi/apps/console/settings.py
@@ -86,4 +86,13 @@ class ConsoleSetting( SettingEnum ):
is_required = True,
initial_value = '30',
)
-
+ STATUS_POLLING_INTERVAL = SettingDefinition(
+ label = 'Status Polling Interval (seconds)',
+ description = 'How often the console polls the server for status and alerts',
+ value_type = AttributeValueType.INTEGER,
+ value_range = [ 1, 3600 ],
+ is_editable = True,
+ is_required = True,
+ initial_value = '3',
+ )
+
diff --git a/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html b/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html
index 606248d5..b09b7d62 100644
--- a/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html
+++ b/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html
@@ -147,7 +147,7 @@
<div class="response-details-bar">
<a class="details-expander" data-toggle="collapse" href="#eventDetails"
role="button" aria-expanded="false" aria-controls="eventDetails">
- <span class="details-label">Integration Details</span>
+ <span class="details-label">Event Details</span>
<span class="details-chevron">▼</span>
</a>
<div class="collapse" id="eventDetails">
diff --git a/src/hi/apps/edit/entity_membership.py b/src/hi/apps/edit/entity_membership.py
new file mode 100644
index 00000000..ad1acb4b
--- /dev/null
+++ b/src/hi/apps/edit/entity_membership.py
@@ -0,0 +1,95 @@
+from abc import ABC, abstractmethod
+from typing import Optional
+
+from django.http import HttpRequest
+from django.urls import reverse
+
+from hi.apps.collection.collection_manager import CollectionManager
+from hi.apps.collection.models import Collection
+from hi.apps.entity.entity_placement import EntityPlacer
+from hi.apps.entity.models import Entity
+from hi.apps.location.location_manager import LocationManager
+from hi.apps.location.models import LocationView
+
+
+class EntityViewMembership( ABC ):
+ """The active container (LocationView or Collection) that an entity can
+ belong to in the current request.
+ """
+
+ @classmethod
+ def for_request( cls, request : HttpRequest ) -> Optional[ 'EntityViewMembership' ]:
+
+ view_type = request.view_parameters.view_type
+ if view_type.is_location_view:
+ location_view = LocationManager().get_default_location_view( request = request )
+ return LocationViewEntityMembership( location_view = location_view )
+ if view_type.is_collection:
+ try:
+ collection = CollectionManager().get_default_collection( request = request )
+ except Collection.DoesNotExist:
+ return None
+ return CollectionEntityMembership( collection = collection )
+ return None
+
+ def toggle_url( self, entity : Entity ) -> str:
+ # Context-agnostic: the toggle view re-resolves the active
+ # container from the request, so only the entity id is needed.
+ return reverse(
+ 'edit_entity_view_membership_toggle',
+ kwargs = { 'entity_id': entity.id },
+ )
+
+ @abstractmethod
+ def is_member( self, entity : Entity ) -> bool:
+ ...
+
+ @abstractmethod
+ def toggle( self, entity : Entity ) -> bool:
+ """Add the entity to / remove it from the active container,
+ returning the new membership state."""
+ ...
+
+ @property
+ @abstractmethod
+ def target_label( self ) -> str:
+ """Human label for the container, e.g. ``'View'`` / ``'Collection'``."""
+ ...
+
+
+class LocationViewEntityMembership( EntityViewMembership ):
+
+ def __init__( self, location_view : LocationView ):
+ self._location_view = location_view
+
+ def is_member( self, entity : Entity ) -> bool:
+ return self._location_view.entity_views.filter( entity = entity ).exists()
+
+ def toggle( self, entity : Entity ) -> bool:
+ return EntityPlacer().toggle_entity_in_view(
+ entity = entity,
+ location_view = self._location_view,
+ )
+
+ @property
+ def target_label( self ) -> str:
+ return 'View'
+
+
+class CollectionEntityMembership( EntityViewMembership ):
+
+ def __init__( self, collection : Collection ):
+ self._collection = collection
+
+ def is_member( self, entity : Entity ) -> bool:
+ return self._collection.entities.filter( entity = entity ).exists()
+
+ def toggle( self, entity : Entity ) -> bool:
+ return CollectionManager().toggle_entity_in_collection(
+ entity = entity,
+ collection = self._collection,
+ )
+
+ @property
+ def target_label( self ) -> str:
+ return 'Collection'
diff --git a/src/hi/apps/edit/templatetags/__init__.py b/src/hi/apps/edit/templatetags/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/edit/templatetags/edit_tags.py b/src/hi/apps/edit/templatetags/edit_tags.py
new file mode 100644
index 00000000..9439e4c6
--- /dev/null
+++ b/src/hi/apps/edit/templatetags/edit_tags.py
@@ -0,0 +1,26 @@
+from django import template
+
+from hi.apps.entity.models import Entity
+
+from hi.apps.edit.entity_membership import EntityViewMembership
+
+register = template.Library()
+
+
[email protected]_tag( takes_context = True )
+def active_entity_membership( context, entity : Entity ):
+ """Resolve the add/remove-from-view control descriptor for ``entity``
+ in the request's active view/collection, or None when the active view
+ has no membership concept.
+ """
+ request = context.get( 'request' )
+ if request is None:
+ return None
+ membership = EntityViewMembership.for_request( request )
+ if membership is None:
+ return None
+ return {
+ 'is_member': membership.is_member( entity ),
+ 'toggle_url': membership.toggle_url( entity ),
+ 'target_label': membership.target_label,
+ }
diff --git a/src/hi/apps/edit/tests/test_entity_membership.py b/src/hi/apps/edit/tests/test_entity_membership.py
new file mode 100644
index 00000000..bfc665b6
--- /dev/null
+++ b/src/hi/apps/edit/tests/test_entity_membership.py
@@ -0,0 +1,76 @@
+import logging
+from types import SimpleNamespace
+
+from hi.apps.collection.enums import CollectionType, CollectionViewType
+from hi.apps.collection.models import Collection
+from hi.apps.entity.enums import EntityType
+from hi.apps.entity.models import Entity
+from hi.apps.location.models import Location, LocationView
+from hi.enums import ViewType
+from hi.testing.base_test_case import BaseTestCase
+
+from hi.apps.edit.entity_membership import (
+ EntityViewMembership,
+ LocationViewEntityMembership,
+ CollectionEntityMembership,
+)
+
+logging.disable(logging.CRITICAL)
+
+
+class TestEntityViewMembership(BaseTestCase):
+ """The edit-app bridge that toggles an entity's membership in the
+ active LocationView / Collection. Verifies the factory branch by view
+ type and the membership round-trip (geometry is per-Location, so the
+ toggle is pure membership)."""
+
+ def test_for_request_returns_none_for_non_membership_view_type(self):
+ # Configuration / video views have no entity-membership concept, so
+ # no add/remove control should be offered.
+ request = SimpleNamespace(
+ view_parameters = SimpleNamespace( view_type = ViewType.CONFIGURATION ),
+ )
+ self.assertIsNone( EntityViewMembership.for_request( request ) )
+
+ def test_location_view_membership_toggle_round_trip(self):
+ location = Location.objects.create(
+ name = 'L',
+ svg_fragment_filename = 'l.svg',
+ svg_view_box_str = '0 0 100 100',
+ )
+ location_view = LocationView.objects.create(
+ location = location,
+ name = 'V',
+ location_view_type_str = 'MAIN',
+ svg_view_box_str = '0 0 100 100',
+ svg_rotate = 0.0,
+ )
+ entity = Entity.objects.create(
+ name = 'E', entity_type_str = str(EntityType.LIGHT),
+ )
+ membership = LocationViewEntityMembership( location_view = location_view )
+
+ self.assertEqual( membership.target_label, 'View' )
+ self.assertFalse( membership.is_member( entity ) )
+ self.assertTrue( membership.toggle( entity ) ) # added
+ self.assertTrue( membership.is_member( entity ) )
+ self.assertFalse( membership.toggle( entity ) ) # removed
+ self.assertFalse( membership.is_member( entity ) )
+
+ def test_collection_membership_toggle_round_trip(self):
+ collection = Collection.objects.create(
+ name = 'C',
+ collection_type_str = str(CollectionType.OTHER),
+ collection_view_type_str = str(CollectionViewType.GRID),
+ )
+ entity = Entity.objects.create(
+ name = 'E2', entity_type_str = str(EntityType.LIGHT),
+ )
+ membership = CollectionEntityMembership( collection = collection )
+
+ self.assertEqual( membership.target_label, 'Collection' )
+ self.assertFalse( membership.is_member( entity ) )
+ self.assertTrue( membership.toggle( entity ) ) # added
+ self.assertTrue( membership.is_member( entity ) )
+ self.assertFalse( membership.toggle( entity ) ) # removed
+ self.assertFalse( membership.is_member( entity ) )
diff --git a/src/hi/apps/edit/urls.py b/src/hi/apps/edit/urls.py
index 03c6f06a..23f8e6a9 100644
--- a/src/hi/apps/edit/urls.py
+++ b/src/hi/apps/edit/urls.py
@@ -18,11 +18,15 @@ urlpatterns = [
views.ReorderItemsView.as_view(),
name='edit_reorder_items' ),
- path( 'item/details/close',
- views.ItemDetailsCloseView.as_view(),
+ path( 'item/details/close',
+ views.ItemDetailsCloseView.as_view(),
name='edit_item_details_close' ),
- re_path( r'^entity/state/values/(?P<instance_name>\w+)/(?P<instance_id>\d+)$',
+ path( 'entity/view-membership/toggle/<int:entity_id>',
+ views.EntityViewMembershipToggleView.as_view(),
+ name='edit_entity_view_membership_toggle' ),
+
+ re_path( r'^entity/state/values/(?P<instance_name>\w+)/(?P<instance_id>\d+)$',
views.EntityStateValueChoicesView.as_view(),
name='edit_entity_state_value_choices' ),
diff --git a/src/hi/apps/edit/views.py b/src/hi/apps/edit/views.py
index d92705d1..955ba553 100644
--- a/src/hi/apps/edit/views.py
+++ b/src/hi/apps/edit/views.py
@@ -14,8 +14,10 @@ from hi.apps.collection.edit.views import (
CollectionReorder,
CollectionReorderEntitiesView,
)
+import hi.apps.common.antinode as antinode
from hi.apps.control.models import Controller
from hi.apps.entity.models import EntityState
+from hi.apps.entity.view_mixins import EntityViewMixin
from hi.apps.location.edit.views import (
LocationViewManageItemsView,
LocationViewReorder,
@@ -26,6 +28,8 @@ from hi.decorators import edit_required
from hi.enums import ItemType, ViewMode
from hi.hi_async_view import HiSideView
+from .entity_membership import EntityViewMembership
+
logger = logging.getLogger(__name__)
@@ -186,3 +190,28 @@ class EntityStateValueChoicesView( View ):
return HttpResponse( json.dumps( entity_state.choices() ),
content_type='application/json' )
+
+
+@method_decorator( edit_required, name = 'dispatch' )
+class EntityViewMembershipToggleView( View, EntityViewMixin ):
+ """Toggle an entity in/out of the active LocationView or Collection
+ from the entity edit sidebar.
+
+ Cross-cutting (entity <-> location/collection), so it lives in the edit
+ app and delegates the container-specific work to ``EntityViewMembership``
+ -- no branching here on view type.
+
+ Responds with a full-page refresh. The current URL already carries the
+ live pan/zoom (kept in sync by svg-entity-edit.js via replaceState) and
+ the open entity editor (the ``details`` param), so reloading restores
+ both the view box and the editing context -- the flipped add/remove
+ control included. A partial re-render would instead snap the canvas back
+ to the LocationView's stored geometry."""
+
+ def post( self, request, *args, **kwargs ):
+ entity = self.get_entity( request, *args, **kwargs )
+ membership = EntityViewMembership.for_request( request )
+ if membership is None:
+ raise BadRequest( 'No active view or collection to modify.' )
+ membership.toggle( entity = entity )
+ return antinode.refresh_response()
diff --git a/src/hi/apps/entity/edit/views.py b/src/hi/apps/entity/edit/views.py
index ecb6e8b4..034ddf54 100644
--- a/src/hi/apps/entity/edit/views.py
+++ b/src/hi/apps/entity/edit/views.py
@@ -12,6 +12,7 @@ from django.views.generic import View
from hi.apps.collection.collection_manager import CollectionManager
import hi.apps.common.antinode as antinode
+from hi.apps.common.svg_models import SvgViewBox
from hi.apps.entity.entity_manager import EntityManager
from hi.apps.entity.entity_pairing_manager import EntityPairingManager, EntityPairingError
from hi.apps.entity.entity_placement import EntityPlacer
@@ -64,7 +65,7 @@ class EntityEditModeView( HiSideView, EntityViewMixin ):
@method_decorator( edit_required, name='dispatch' )
-class EntityAddView( HiModalView ):
+class EntityAddView( HiModalView, EntityViewMixin ):
def get_template_name( self ) -> str:
return 'entity/edit/modals/entity_add.html'
@@ -83,6 +84,10 @@ class EntityAddView( HiModalView ):
}
return self.modal_response( request, context )
+ # Preserve the user's current pan/zoom both for the post-add reload
+ # (query params, below) and for where the new items are placed.
+ svg_view_box_override = request.view_parameters.last_svg_view_box
+
with transaction.atomic():
created_entities = self._create_entities_bulk( entity_form = entity_form )
for i, entity in enumerate( created_entities ):
@@ -91,11 +96,11 @@ class EntityAddView( HiModalView ):
entity = entity,
bulk_grid_index = i,
bulk_grid_total = len( created_entities ),
+ svg_view_box_override = svg_view_box_override,
)
continue
-
- redirect_url = reverse('home')
- return self.redirect_response( request, redirect_url )
+
+ return self.redirect_home_w_geometry( request )
def _create_entities_bulk(self, entity_form: EntityAddForm) -> List[Entity]:
base_name = entity_form.cleaned_data['name']
@@ -122,8 +127,9 @@ class EntityAddView( HiModalView ):
request,
entity : Entity,
bulk_grid_index : Optional[int] = None,
- bulk_grid_total : Optional[int] = None ):
-
+ bulk_grid_total : Optional[int] = None,
+ svg_view_box_override : Optional[SvgViewBox] = None ):
+
if request.view_parameters.view_type.is_location_view:
try:
current_location_view = LocationManager().get_default_location_view( request = request )
@@ -132,6 +138,7 @@ class EntityAddView( HiModalView ):
location_view = current_location_view,
bulk_grid_index = bulk_grid_index,
bulk_grid_total = bulk_grid_total,
+ svg_view_box_override = svg_view_box_override,
)
except LocationView.DoesNotExist:
logger.warning( 'No current location view to add new entity to.')
@@ -181,8 +188,7 @@ class EntityDeleteView( HiModalView, EntityViewMixin ):
entity.delete()
- redirect_url = reverse('home')
- return self.redirect_response( request, redirect_url )
+ return self.redirect_home_w_geometry( request )
@method_decorator( edit_required, name='dispatch' )
diff --git a/src/hi/apps/entity/entity_placement.py b/src/hi/apps/entity/entity_placement.py
index bd2555ac..441f4907 100644
--- a/src/hi/apps/entity/entity_placement.py
+++ b/src/hi/apps/entity/entity_placement.py
@@ -35,6 +35,7 @@ from typing import Callable, Dict, List, Optional, Tuple, Union
from django.db import transaction
+from hi.apps.common.svg_models import SvgViewBox
from hi.apps.entity.edit.forms import EntityPositionForm
from hi.apps.entity.enums import (
EntityGroupType,
@@ -421,29 +422,31 @@ class EntityPlacementService:
class EntityPlacementCalculator:
- """Orchestrates per-entity shape selection. Pure-functional;
- performs no DB writes. The geometry math lives in
- ``PositionGeometry`` (where) and ``PathGeometry`` (how a path
- looks); this class branches on entity_type to decide which
+ """Orchestrates per-entity shape selection against a fixed viewbox.
+ Pure-functional; performs no DB writes and has no model coupling -
+ constructed with the ``SvgViewBox`` to position/size against (the
+ LocationView's stored geometry, or an override). The geometry math
+ lives in ``PositionGeometry`` (where) and ``PathGeometry`` (how a
+ path looks); this class branches on entity_type to decide which
output shape applies.
"""
- def shape_for_entity( self,
- entity : Entity,
- location_view : LocationView ) -> PlacementShape:
+ def __init__( self, view_box : SvgViewBox ):
+ self._view_box = view_box
+ return
+
+ @property
+ def view_box( self ) -> SvgViewBox:
+ return self._view_box
+
+ def shape_for_entity( self, entity : Entity ) -> PlacementShape:
"""Return the placement shape for a single entity centered on
- the current viewbox."""
- svg_x, svg_y = PositionGeometry.view_center( location_view )
- return self._shape_at_point(
- entity = entity,
- location_view = location_view,
- svg_x = svg_x,
- svg_y = svg_y,
- )
+ the viewbox."""
+ svg_x, svg_y = PositionGeometry.view_center( self._view_box )
+ return self._shape_at_point( entity = entity, svg_x = svg_x, svg_y = svg_y )
def shapes_for_entities( self,
- entities : List[Entity],
- location_view : LocationView ) -> List[PlacementShape]:
+ entities : List[Entity] ) -> List[PlacementShape]:
"""Return one shape per entity in input order. Single-entity
input degenerates to ``shape_for_entity``. Larger groups get
a centered grid; each entity's slot becomes either a Point
@@ -453,55 +456,44 @@ class EntityPlacementCalculator:
if total == 0:
return []
if total == 1:
- return [ self.shape_for_entity(
- entity = entities[0], location_view = location_view ) ]
+ return [ self.shape_for_entity( entity = entities[0] ) ]
return [
self._shape_at_grid_slot(
entity = entity,
- location_view = location_view,
grid_index = index,
grid_total = total,
)
for index, entity in enumerate( entities )
]
- def default_icon_scale( self,
- entity : Entity,
- location_view : LocationView ) -> Decimal:
+ def default_icon_scale( self, entity : Entity ) -> Decimal:
"""Default scale for an icon entity. Delegates to
``PositionGeometry.default_icon_scale``."""
return PositionGeometry.default_icon_scale(
- entity = entity, location_view = location_view )
+ entity = entity, view_box = self._view_box )
# ----- internal shape routing (no DB) -----
def _shape_at_grid_slot( self,
entity : Entity,
- location_view : LocationView,
grid_index : int,
grid_total : int ) -> PlacementShape:
svg_x, svg_y = PositionGeometry.grid_slot(
- location_view = location_view,
+ view_box = self._view_box,
grid_index = grid_index,
grid_total = grid_total,
)
- return self._shape_at_point(
- entity = entity,
- location_view = location_view,
- svg_x = svg_x,
- svg_y = svg_y,
- )
+ return self._shape_at_point( entity = entity, svg_x = svg_x, svg_y = svg_y )
def _shape_at_point( self,
entity : Entity,
- location_view : LocationView,
svg_x : float,
svg_y : float ) -> PlacementShape:
entity_type = entity.entity_type
if entity_type.requires_path():
svg_path = PathGeometry.create_default_path_string(
- location_view = location_view,
+ view_box = self._view_box,
is_path_closed = entity_type.requires_closed_path(),
center_x = svg_x,
center_y = svg_y,
@@ -512,8 +504,7 @@ class EntityPlacementCalculator:
return PlacementPoint(
svg_x = svg_x,
svg_y = svg_y,
- svg_scale = self.default_icon_scale(
- entity = entity, location_view = location_view ),
+ svg_scale = self.default_icon_scale( entity = entity ),
)
@@ -524,20 +515,26 @@ class EntityPlacer:
user-drawn-path persistence, edit-form construction, and
entity-type transitions (icon ↔ path)."""
- def __init__( self ):
- self._calculator = EntityPlacementCalculator()
- return
-
- @property
- def calculator(self) -> EntityPlacementCalculator:
- return self._calculator
+ @staticmethod
+ def _calculator_for( location_view : LocationView,
+ svg_view_box_override : Optional[SvgViewBox] = None
+ ) -> EntityPlacementCalculator:
+ """Build a calculator bound to the geometry placement should use:
+ the override viewbox when given (e.g. the user's current
+ pan/zoom), otherwise the LocationView's stored viewbox. The real
+ location_view is never handed to the calculator - it is only the
+ linkage target for persisted rows."""
+ view_box = ( svg_view_box_override if svg_view_box_override is not None
+ else location_view.svg_view_box )
+ return EntityPlacementCalculator( view_box = view_box )
def place_entity_in_view( self,
entity : Entity,
location_view : LocationView,
placement_shape : Optional[PlacementShape] = None,
- bulk_grid_index : Optional[int] = None,
- bulk_grid_total : Optional[int] = None ):
+ bulk_grid_index : Optional[int] = None,
+ bulk_grid_total : Optional[int] = None,
+ svg_view_box_override : Optional[SvgViewBox] = None ):
"""Place a single entity into a location view, including its
delegate entities. Idempotent: existing position/path/view rows
are preserved.
@@ -549,10 +546,21 @@ class EntityPlacer:
(legacy form-driven flow) — calculator picks the slot.
3. Otherwise — calculator centers the shape on the viewbox.
+ ``svg_view_box_override`` optionally overrides the geometry the
+ calculator positions/sizes against (e.g. the user's current
+ pan/zoom) without changing the linkage target. Ignored when
+ ``placement_shape`` is given. Applies to modes (2) and (3);
+ delegates still center on the same (possibly overridden) viewbox.
+
Delegates always go through mode (3): each delegate is placed
at the viewbox center. See module docstring on the
delegate-overlap limitation.
"""
+ # The calculator positions/sizes against the override viewbox when
+ # given, else the view's stored viewbox; the real location_view is
+ # only the linkage target for the persisted rows below.
+ calculator = self._calculator_for( location_view, svg_view_box_override )
+
with transaction.atomic():
if not entity.entity_views.all().exists():
delegate_entity_list = (
@@ -566,8 +574,8 @@ class EntityPlacer:
if placement_shape is None:
placement_shape = self._derive_placement_shape(
+ calculator = calculator,
entity = entity,
- location_view = location_view,
bulk_grid_index = bulk_grid_index,
bulk_grid_total = bulk_grid_total,
)
@@ -578,10 +586,10 @@ class EntityPlacer:
)
for delegate_entity in delegate_entity_list:
delegate_shape = self._build_delegate_shape(
+ calculator = calculator,
principal_entity = entity,
principal_shape = placement_shape,
delegate_entity = delegate_entity,
- location_view = location_view,
)
self._create_entity_view(
entity = delegate_entity,
@@ -599,10 +607,10 @@ class EntityPlacer:
def _build_delegate_shape(
self,
+ calculator : EntityPlacementCalculator,
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
@@ -610,10 +618,7 @@ class EntityPlacer:
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,
- )
+ default_shape = calculator.shape_for_entity( entity = delegate_entity )
if delegate_entity.entity_type != EntityType.AREA:
return default_shape
if not isinstance( principal_shape, PlacementPoint ):
@@ -640,7 +645,7 @@ class EntityPlacer:
apex_y = float( principal_shape.svg_y ) + ( dy * apex_offset )
svg_path = PathGeometry.create_coverage_triangle_path_string(
- location_view = location_view,
+ view_box = calculator.view_box,
apex_x = apex_x,
apex_y = apex_y,
direction = icon_direction.value,
@@ -655,9 +660,8 @@ class EntityPlacer:
items in a result group together. The grid is computed once
across the entire group; per-entity delegates are placed by
the single-entity flow."""
- shapes = self._calculator.shapes_for_entities(
+ shapes = self._calculator_for( location_view ).shapes_for_entities(
entities = entities,
- location_view = location_view,
)
with transaction.atomic():
for entity, shape in zip( entities, shapes ):
@@ -694,9 +698,8 @@ class EntityPlacer:
Used by entity-type transition flows that already have an
EntityView and just need a shape row to exist (e.g., a type
change to a path-based type when no path row exists yet)."""
- shape = self._calculator.shape_for_entity(
+ shape = self._calculator_for( location_view ).shape_for_entity(
entity = entity,
- location_view = location_view,
)
self._persist_placement_shape(
entity = entity,
@@ -860,8 +863,8 @@ class EntityPlacer:
# ----- internal helpers -----
def _derive_placement_shape( self,
+ calculator : EntityPlacementCalculator,
entity : Entity,
- location_view : LocationView,
bulk_grid_index : Optional[int],
bulk_grid_total : Optional[int] ) -> PlacementShape:
if (
@@ -869,14 +872,12 @@ class EntityPlacer:
and bulk_grid_total > 1
and bulk_grid_index is not None
):
- return self._calculator._shape_at_grid_slot(
+ return calculator._shape_at_grid_slot(
entity = entity,
- location_view = location_view,
grid_index = bulk_grid_index,
grid_total = bulk_grid_total,
)
- return self._calculator.shape_for_entity(
- entity = entity, location_view = location_view )
+ return calculator.shape_for_entity( entity = entity )
def _create_entity_view( self,
entity : Entity,
@@ -987,7 +988,7 @@ class EntityPlacer:
center_y = float( entity_position.svg_y )
svg_path = PathGeometry.create_default_path_string(
- location_view = location_view,
+ view_box = location_view.svg_view_box,
is_path_closed = is_path_closed,
center_x = center_x,
center_y = center_y,
@@ -1013,10 +1014,10 @@ class EntityPlacer:
verbatim."""
center_x, center_y = PositionGeometry.path_center( entity_path.svg_path )
if center_x is None or center_y is None:
- center_x, center_y = PositionGeometry.view_center( location_view )
+ center_x, center_y = PositionGeometry.view_center( location_view.svg_view_box )
- svg_scale = self._calculator.default_icon_scale(
- entity = entity, location_view = location_view )
+ svg_scale = self._calculator_for( location_view ).default_icon_scale(
+ entity = entity )
EntityPosition.objects.get_or_create(
entity = entity,
location = location_view.location,
diff --git a/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html b/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html
index ab4f162f..648ed71b 100644
--- a/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html
+++ b/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html
@@ -1,6 +1,7 @@
{% extends "edit/panes/sidebar_tabbed.html" %}
{% load icons static %}
{% load integration_tags %}
+{% load edit_tags %}
{% comment %}
Drilled-in entity detail. Reached by clicking an icon in the main
pane (not by a tab), so the Items tab stays marked active to show
@@ -39,6 +40,32 @@ the user where they are within the sidebar's domain model.
{% include "entity/edit/panes/entity_properties_edit.html" %}
</div>
+{% comment %}
+Add/remove this entity from the active view/collection -- the most frequent
+in-context action, so it leads the actions below the properties. The control
+descriptor is resolved by the edit-app tag (None for view types without a
+membership concept), keeping this template free of location/collection
+branching.
+{% endcomment %}
+{% active_entity_membership entity as view_membership %}
+{% if view_membership %}
+<hr />
+<form method="post" action="{{ view_membership.toggle_url }}" data-async="true">
+ {% csrf_token %}
+ {% if view_membership.is_member %}
+ <button type="submit" class="btn btn-outline-secondary btn-block btn-control"
+ title="Remove from this {{ view_membership.target_label|lower }}. The item stays in your inventory and can be re-added.">
+ {% icon "close" size="sm" css_class="hi-icon-left" %}REMOVE FROM {{ view_membership.target_label|upper }}
+ </button>
+ {% else %}
+ <button type="submit" class="btn btn-add btn-block btn-control"
+ title="Add to this {{ view_membership.target_label|lower }}.">
+ {% icon "plus" size="sm" css_class="hi-icon-left" %}ADD TO {{ view_membership.target_label|upper }}
+ </button>
+ {% endif %}
+</form>
+{% endif %}
+
<hr />
<div class="h5">Paired Items</div>
<div id="hi-edit-entity-principals">
@@ -57,9 +84,14 @@ the user where they are within the sidebar's domain model.
{% if entity_position_form %}
<hr />
-<div class="h5">Geometry</div>
-<div id="{{ DIVID.ENTITY_POSITION_EDIT_PANE }}">
- {% include "entity/edit/panes/entity_position_edit.html" %}
+<a class="h5 d-block text-decoration-none" data-toggle="collapse" href="#hi-edit-entity-geometry"
+ role="button" aria-expanded="false" aria-controls="hi-edit-entity-geometry">
+ {% icon "chevron-down" size="sm" css_class="hi-icon-left" %}Geometry
+</a>
+<div class="collapse" id="hi-edit-entity-geometry">
+ <div id="{{ DIVID.ENTITY_POSITION_EDIT_PANE }}">
+ {% include "entity/edit/panes/entity_position_edit.html" %}
+ </div>
</div>
{% endif %}
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 f2f2c725..0b59ba73 100644
--- a/src/hi/apps/entity/templates/entity/modals/entity_edit.html
+++ b/src/hi/apps/entity/templates/entity/modals/entity_edit.html
@@ -5,7 +5,7 @@
{% block title_text %}{{ entity.name }}{% endblock %}
{% block subheader %}
- {% include "entity/panes/entity_modal_subheader.html" with entity=entity modal_name="Edit" %}
+ {% include "entity/panes/entity_modal_subheader.html" with entity=entity modal_name="Info" %}
{% endblock %}
{% block body %}
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 7b5041a6..ab8bc76a 100644
--- a/src/hi/apps/entity/templates/entity/modals/entity_history.html
+++ b/src/hi/apps/entity/templates/entity/modals/entity_history.html
@@ -40,7 +40,7 @@
<a class="btn btn-primary"
href="{% url 'entity_edit' entity_id=entity.id %}"
data-async="modal">
- {% icon "edit" css_class="hi-icon-left" %}EDIT
+ {% icon "info-circle" css_class="hi-icon-left" %}INFO
</a>
{% endblock %}
diff --git a/src/hi/apps/entity/templates/entity/modals/entity_state_history.html b/src/hi/apps/entity/templates/entity/modals/entity_state_history.html
index 11ef0114..4e6a5caf 100644
--- a/src/hi/apps/entity/templates/entity/modals/entity_state_history.html
+++ b/src/hi/apps/entity/templates/entity/modals/entity_state_history.html
@@ -39,7 +39,7 @@
<a class="btn btn-primary"
href="{% url 'entity_edit' entity_id=entity_state.entity.id %}"
data-async="modal">
- {% icon "edit" css_class="hi-icon-left" %}EDIT
+ {% icon "info-circle" css_class="hi-icon-left" %}INFO
</a>
{% endblock %}
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 5a0519e8..24cb5a16 100644
--- a/src/hi/apps/entity/templates/entity/modals/entity_status.html
+++ b/src/hi/apps/entity/templates/entity/modals/entity_status.html
@@ -31,7 +31,7 @@ Panel dispatch trace:
<a class="btn btn-primary"
href="{% url 'entity_edit' entity_id=state_panel_data.entity.id %}"
data-async="modal">
- {% icon "edit" css_class="hi-icon-left" %}EDIT
+ {% icon "info-circle" css_class="hi-icon-left" %}INFO
</a>
{% endblock %}
diff --git a/src/hi/apps/entity/templates/entity/panes/entity_state_history_row.html b/src/hi/apps/entity/templates/entity/panes/entity_state_history_row.html
index 2ea734f2..65aa6fa6 100644
--- a/src/hi/apps/entity/templates/entity/panes/entity_state_history_row.html
+++ b/src/hi/apps/entity/templates/entity/panes/entity_state_history_row.html
@@ -18,7 +18,7 @@
<div class="col-md-5 col-sm-7">
<div class="d-flex align-items-center">
<div class="flex-grow-1">
- <div class="hi-status-display text-center px-2" status="{{ row.value }}">{% render_state_value_text row.entity_state row.value %}</div>
+ <div class="hi-status-display text-center px-2" status="{% state_value_status row.entity_state row.value %}">{% render_state_value_text row.entity_state row.value %}</div>
</div>
{% if row.history_value_type.name == 'INTENT' or row.matched_intent %}
<img src="{% static 'img/hi-icon-16x16.png' %}"
diff --git a/src/hi/apps/entity/tests/test_entity_placement.py b/src/hi/apps/entity/tests/test_entity_placement.py
index 5ac5849e..b48a1d21 100644
--- a/src/hi/apps/entity/tests/test_entity_placement.py
+++ b/src/hi/apps/entity/tests/test_entity_placement.py
@@ -54,11 +54,11 @@ class TestEntityPlacerPersistence(BaseTestCase):
location_view.svg_view_box = view_box
placer = EntityPlacer()
- # Compute the shape via the calculator, then persist directly
- # (skipping place_entity_in_view to avoid delegate-pairing
+ # Compute the shape via a viewbox-bound calculator, then persist
+ # directly (skipping place_entity_in_view to avoid delegate-pairing
# side effects that need a real EntityView).
- placement_shape = placer.calculator.shape_for_entity(
- entity=entity, location_view=location_view,
+ placement_shape = EntityPlacementCalculator(view_box=view_box).shape_for_entity(
+ entity=entity,
)
self.assertIsInstance(placement_shape, PlacementPoint)
placer._persist_placement_shape(
@@ -107,37 +107,24 @@ class TestEntityPlacementCalculatorBulkShapes(BaseTestCase):
The grid math itself is tested in test_position_geometry; this
class verifies the calculator's entity-routing wrapper."""
- def _make_location_view(self):
+ def _view_box(self):
from hi.apps.common.svg_models import SvgViewBox
- from hi.apps.location.models import Location
-
- location = Location.objects.create(
- name='Bulk Test Location',
- svg_view_box_str='0 0 1000 1000',
- )
- location_view = Mock()
- location_view.location = location
- location_view.svg_view_box = SvgViewBox(x=0, y=0, width=1000, height=1000)
- return location_view
+ return SvgViewBox(x=0, y=0, width=1000, height=1000)
def test_empty_input_yields_empty_shapes(self):
- calculator = EntityPlacementCalculator()
- location_view = self._make_location_view()
+ calculator = EntityPlacementCalculator(view_box=self._view_box())
self.assertEqual(
- calculator.shapes_for_entities(entities=[], location_view=location_view),
+ calculator.shapes_for_entities(entities=[]),
[],
)
def test_single_entity_falls_back_to_single_shape(self):
- calculator = EntityPlacementCalculator()
- location_view = self._make_location_view()
+ calculator = EntityPlacementCalculator(view_box=self._view_box())
entity = Entity.objects.create(
name='Single Camera',
entity_type_str=str(EntityType.CAMERA),
)
- shapes = calculator.shapes_for_entities(
- entities=[entity], location_view=location_view,
- )
+ shapes = calculator.shapes_for_entities(entities=[entity])
self.assertEqual(len(shapes), 1)
self.assertIsInstance(shapes[0], PlacementPoint)
# Centered on viewbox.
@@ -145,8 +132,7 @@ class TestEntityPlacementCalculatorBulkShapes(BaseTestCase):
self.assertAlmostEqual(shapes[0].svg_y, 500.0)
def test_multiple_icon_entities_each_get_a_grid_slot(self):
- calculator = EntityPlacementCalculator()
- location_view = self._make_location_view()
+ calculator = EntityPlacementCalculator(view_box=self._view_box())
entities = [
Entity.objects.create(
name=f'Cam {i}',
@@ -156,9 +142,7 @@ class TestEntityPlacementCalculatorBulkShapes(BaseTestCase):
)
for i in range(4)
]
- shapes = calculator.shapes_for_entities(
- entities=entities, location_view=location_view,
- )
+ shapes = calculator.shapes_for_entities(entities=entities)
self.assertEqual(len(shapes), len(entities))
for shape in shapes:
self.assertIsInstance(shape, PlacementPoint)
@@ -538,3 +522,51 @@ class TestPlacementInputBuilder(BaseTestCase):
item_key_fn=self._key,
)
self.assertEqual(placement_input.heading, PLACEMENT_DEFAULT_HEADING)
+
+
+class TestPlacerCalculatorForOverride(BaseTestCase):
+ """The override path that lets placement follow the user's current
+ pan/zoom: the calculator is bound to the override viewbox when given,
+ else the LocationView's stored viewbox - the real LocationView is
+ never handed to the calculator (it is only the linkage target)."""
+
+ def test_no_override_uses_stored_view_box(self):
+ from hi.apps.common.svg_models import SvgViewBox
+ from hi.apps.location.tests.synthetic_data import LocationSyntheticData
+
+ location_view = LocationSyntheticData.create_test_location_view(
+ svg_view_box_str='0 0 800 600')
+ calculator = EntityPlacer._calculator_for(location_view)
+ self.assertEqual(
+ calculator.view_box.to_dict(),
+ SvgViewBox.from_attribute_value('0 0 800 600').to_dict(),
+ )
+
+ def test_override_takes_precedence_without_mutating_view(self):
+ from hi.apps.common.svg_models import SvgViewBox
+ from hi.apps.location.tests.synthetic_data import LocationSyntheticData
+
+ location_view = LocationSyntheticData.create_test_location_view(
+ svg_view_box_str='0 0 800 600')
+ override = SvgViewBox(x=100, y=50, width=200, height=150)
+
+ calculator = EntityPlacer._calculator_for(
+ location_view, svg_view_box_override=override)
+
+ self.assertEqual(calculator.view_box.to_dict(), override.to_dict())
+ # The real view (the linkage target) is untouched.
+ self.assertEqual(location_view.svg_view_box_str, '0 0 800 600')
+
+ def test_calculator_centers_shape_on_override_view_box(self):
+ from hi.apps.common.svg_models import SvgViewBox
+
+ override = SvgViewBox(x=100, y=50, width=200, height=150)
+ entity = Entity.objects.create(
+ name='Override Cam', entity_type_str=str(EntityType.CAMERA))
+
+ shape = EntityPlacementCalculator(view_box=override).shape_for_entity(
+ entity=entity)
+
+ # Centered on the override viewbox: 100 + 200/2 = 200, 50 + 150/2 = 125.
+ self.assertAlmostEqual(shape.svg_x, 200.0)
+ self.assertAlmostEqual(shape.svg_y, 125.0)
diff --git a/src/hi/apps/entity/transient_models.py b/src/hi/apps/entity/transient_models.py
index 73bb0356..332d5125 100644
--- a/src/hi/apps/entity/transient_models.py
+++ b/src/hi/apps/entity/transient_models.py
@@ -90,7 +90,7 @@ class EntityEditModeData:
self.entity_form = EntityForm(
instance = self.entity,
)
-
+
def to_template_context(self):
return {
'entity': self.entity,
diff --git a/src/hi/apps/entity/view_mixins.py b/src/hi/apps/entity/view_mixins.py
index dcd0abf4..f79571a5 100644
--- a/src/hi/apps/entity/view_mixins.py
+++ b/src/hi/apps/entity/view_mixins.py
@@ -1,5 +1,8 @@
+from urllib.parse import urlencode
+
from django.core.exceptions import BadRequest
from django.http import Http404
+from django.urls import reverse
from hi.apps.entity.models import Entity, EntityState
@@ -17,6 +20,24 @@ class EntityViewMixin:
except Entity.DoesNotExist:
raise Http404( request )
+ def redirect_home_w_geometry( self, request ):
+ """Redirect to home, carrying the user's current pan/zoom (from the
+ session) as query params, so an edit operation's full reload keeps
+ the view where the user left it instead of snapping back to the
+ LocationView's stored geometry. Scoped to the triggering operation:
+ a bare home redirect when no geometry is tracked (e.g. acting from a
+ collection view, or before any pan/zoom). The host view supplies
+ ``redirect_response`` (HiModalView)."""
+ redirect_url = reverse('home')
+ svg_view_box = request.view_parameters.last_svg_view_box
+ if svg_view_box is not None:
+ params = { 'svg_view_box': str(svg_view_box) }
+ svg_rotate = request.view_parameters.last_svg_rotate
+ if svg_rotate is not None:
+ params['svg_rotate'] = svg_rotate
+ redirect_url = f'{redirect_url}?{urlencode(params)}'
+ return self.redirect_response( request, redirect_url )
+
class EntityStateViewMixin:
diff --git a/src/hi/apps/location/edit/tests/test_views.py b/src/hi/apps/location/edit/tests/test_views.py
index eec37fc4..8275906c 100644
--- a/src/hi/apps/location/edit/tests/test_views.py
+++ b/src/hi/apps/location/edit/tests/test_views.py
@@ -4,13 +4,17 @@ from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
from hi.apps.collection.collection_manager import CollectionManager
+from hi.apps.common.svg_models import SvgViewBox
from hi.apps.entity.entity_manager import EntityManager
from hi.apps.entity.enums import EntityType
+from hi.apps.location.edit.views import LocationViewGeometryView
from hi.apps.location.location_manager import LocationManager
from hi.apps.location.models import Location, LocationView
from hi.apps.location.tests.synthetic_data import LocationSyntheticData
from hi.enums import ItemType, ViewMode
+from hi.testing.base_test_case import BaseTestCase, MockRequest
from hi.testing.view_test_base import SyncViewTestCase, DualModeViewTestCase
+from hi.view_parameters import ViewParameters
logging.disable(logging.CRITICAL)
@@ -1015,3 +1019,36 @@ class TestLocationItemPathView(SyncViewTestCase):
self.assertEqual(response.status_code, 405)
+
+
+class TestLocationViewGeometrySessionTracking(BaseTestCase):
+ """LocationViewGeometryView._track_session_geometry - records the
+ posted pan/zoom in the session view parameters, rejecting malformed
+ input (best-effort UX state, never authoritative)."""
+
+ def _track(self, **post_params):
+ request = MockRequest(POST=dict(post_params))
+ request.view_parameters = ViewParameters()
+ LocationViewGeometryView()._track_session_geometry(request)
+ return request.view_parameters
+
+ def test_valid_geometry_recorded(self):
+ view_parameters = self._track(
+ svg_view_box_str='10 20 30 40', svg_rotate='45')
+ self.assertEqual(view_parameters.last_svg_view_box.to_dict(),
+ SvgViewBox(x=10, y=20, width=30, height=40).to_dict())
+ self.assertEqual(view_parameters.last_svg_rotate, '45')
+
+ def test_missing_viewbox_records_nothing(self):
+ view_parameters = self._track(svg_rotate='45')
+ self.assertIsNone(view_parameters.last_svg_view_box)
+
+ def test_malformed_viewbox_records_nothing(self):
+ view_parameters = self._track(svg_view_box_str='garbage')
+ self.assertIsNone(view_parameters.last_svg_view_box)
+
+ def test_valid_viewbox_with_malformed_rotate_drops_only_rotate(self):
+ view_parameters = self._track(
+ svg_view_box_str='10 20 30 40', svg_rotate='tilt')
+ self.assertIsNotNone(view_parameters.last_svg_view_box)
+ self.assertIsNone(view_parameters.last_svg_rotate)
diff --git a/src/hi/apps/location/edit/views.py b/src/hi/apps/location/edit/views.py
index 947b007f..d039d4c8 100644
--- a/src/hi/apps/location/edit/views.py
+++ b/src/hi/apps/location/edit/views.py
@@ -18,6 +18,7 @@ from hi.apps.collection.edit.views import CollectionPositionEditView
from hi.apps.collection.models import Collection
import hi.apps.common.antinode as antinode
from hi.apps.common.svg_models import SvgViewBox
+from hi.apps.common.utils import str_to_bool
from hi.apps.entity.edit.views import EntityPositionEditView
from hi.apps.entity.entity_manager import EntityManager
from hi.apps.entity.entity_placement import EntityPlacer
@@ -411,6 +412,20 @@ class LocationViewGeometryView( View, LocationViewMixin, LocationEditViewMixin )
def post(self, request, *args, **kwargs):
location_view = self.get_location_view( request, *args, **kwargs )
+ # Always remember the latest explored geometry in the session so
+ # full-reload operations (e.g. adding an entity) can preserve the
+ # user's current pan/zoom. This never touches the LocationView's
+ # stored geometry.
+ self._track_session_geometry( request )
+
+ # 'view_edit_active' is context, not instruction: it reports that
+ # the LocationView properties editor is open, which is the only
+ # case where a pan/zoom should overwrite the stored geometry. All
+ # other pan/zoom is ephemeral - the session tracking above is
+ # enough, so we are done.
+ if not str_to_bool( request.POST.get( 'view_edit_active' ) ):
+ return antinode.response( status = 200 )
+
location_view_geometry_form = forms.LocationViewGeometryForm( request.POST, instance = location_view )
if location_view_geometry_form.is_valid():
location_view_geometry_form.save()
@@ -427,13 +442,39 @@ class LocationViewGeometryView( View, LocationViewMixin, LocationEditViewMixin )
location_view_edit_data = LocationViewEditModeData(
location_view = location_view,
- )
+ )
return self.location_view_edit_mode_response(
request = request,
location_view_edit_data = location_view_edit_data,
status_code = status_code,
)
+ def _track_session_geometry( self, request ):
+ """Record the posted pan/zoom geometry in the session view
+ parameters (validated), regardless of whether it will also be
+ persisted to the LocationView. Silently ignores malformed input -
+ this is best-effort UX state, not authoritative data."""
+ svg_view_box_str = request.POST.get( 'svg_view_box_str' )
+ if not svg_view_box_str:
+ return
+ try:
+ svg_view_box = SvgViewBox.from_attribute_value( svg_view_box_str )
+ except ( ValueError, TypeError ):
+ return
+
+ svg_rotate = request.POST.get( 'svg_rotate' )
+ try:
+ float( svg_rotate )
+ except ( ValueError, TypeError ):
+ svg_rotate = None
+
+ request.view_parameters.set_last_svg_geometry(
+ svg_view_box = svg_view_box,
+ svg_rotate = svg_rotate,
+ )
+ request.view_parameters.to_session( request )
+ return
+
@method_decorator( edit_required, name='dispatch' )
class LocationViewManageItemsView( HiSideView ):
diff --git a/src/hi/apps/location/location_view_data.py b/src/hi/apps/location/location_view_data.py
index 0c454ef4..c78df4da 100644
--- a/src/hi/apps/location/location_view_data.py
+++ b/src/hi/apps/location/location_view_data.py
@@ -107,14 +107,23 @@ class LocationViewData:
return
def _get_state_id_map(self):
- # One state id per entity — the primary state's id. Drives
- # the ``data-state-id`` attribute on the SVG icon / path
- # elements so the polling dispatcher can target them.
- # Entities without a primary state (no states with sensor
- # responses) get no entry and render without data-state-id.
+ # One state id per entity — the primary state's id — so the SVG
+ # icon/path elements carry ``data-state-id`` and the polling
+ # dispatcher can target them. Entities with a current response keep
+ # their responded primary (so the marker and the rendered status
+ # value reference the same state); entities with states but no current
+ # response fall back to their configured primary, rendered with the
+ # existing empty/unknown status, so a later state change is picked up
+ # live by polling instead of being stuck until a full re-render.
state_id_map = dict()
- for entity, picked in self._latest_entity_state_status_data_map.items():
- state_id_map[entity] = picked.entity_state.id
+ for entity, status_data_list in self.entity_to_entity_state_status_data_list.items():
+ responded = self._latest_entity_state_status_data_map.get( entity )
+ if responded is not None:
+ state_id_map[entity] = responded.entity_state.id
+ continue
+ primary = self._pick_primary_status_data( entity, status_data_list )
+ if primary is not None:
+ state_id_map[entity] = primary.entity_state.id
continue
return state_id_map
@@ -129,16 +138,24 @@ class LocationViewData:
# the time-latest response across all of that state's sensors.
latest_entity_state_status_data_map = dict()
for entity, entity_state_status_data_list in self.entity_to_entity_state_status_data_list.items():
- if not entity_state_status_data_list:
- continue
with_responses_list = [ x for x in entity_state_status_data_list if x.latest_sensor_response ]
- if not with_responses_list:
- continue
- with_responses_list.sort(
- key = lambda d: ENTITY_PRIMARY_STATE_ORDERING.sort_key(
- d.entity_state.entity_state_role, entity.entity_type,
- ),
- )
- latest_entity_state_status_data_map[entity] = with_responses_list[0]
+ primary = self._pick_primary_status_data( entity, with_responses_list )
+ if primary is not None:
+ latest_entity_state_status_data_map[entity] = primary
continue
return latest_entity_state_status_data_map
+
+ def _pick_primary_status_data(self, entity, status_data_list):
+ # Single source of the primary-state selection: from a list of the
+ # entity's EntityStateStatusData, pick the one whose state role ranks
+ # highest in ``ENTITY_PRIMARY_STATE_ORDERING`` for the entity's type.
+ # Callers choose the candidate set (response-only vs. all states); this
+ # owns the ordering. Returns None for an empty list.
+ if not status_data_list:
+ return None
+ return min(
+ status_data_list,
+ key = lambda d: ENTITY_PRIMARY_STATE_ORDERING.sort_key(
+ d.entity_state.entity_state_role, entity.entity_type,
+ ),
+ )
diff --git a/src/hi/apps/location/models.py b/src/hi/apps/location/models.py
index ed86f31e..566f549f 100644
--- a/src/hi/apps/location/models.py
+++ b/src/hi/apps/location/models.py
@@ -77,8 +77,8 @@ class Location( models.Model, ItemTypeModelMixin ):
min_y = svg_view_box.y,
max_x = svg_view_box.x + svg_view_box.width,
max_y = svg_view_box.y + svg_view_box.height,
- min_scale = 0.1,
- max_scale = 25.0,
+ min_scale = SvgItemPositionBounds.DEFAULT_MIN_SCALE,
+ max_scale = SvgItemPositionBounds.DEFAULT_MAX_SCALE,
)
def delete( self, *args, **kwargs ):
diff --git a/src/hi/apps/location/path_geometry.py b/src/hi/apps/location/path_geometry.py
index 7f2a613f..00b7c486 100644
--- a/src/hi/apps/location/path_geometry.py
+++ b/src/hi/apps/location/path_geometry.py
@@ -1,9 +1,8 @@
from typing import Optional, Tuple
-from hi.apps.common.svg_models import SvgRadius
+from hi.apps.common.svg_models import SvgRadius, SvgViewBox
from hi.apps.entity.enums import EntityType
from hi.apps.collection.enums import CollectionType
-from hi.apps.location.models import LocationView
class PathGeometry:
@@ -48,7 +47,7 @@ class PathGeometry:
@classmethod
def create_default_path_string(cls,
- location_view: LocationView,
+ view_box: SvgViewBox,
is_path_closed: bool,
center_x: Optional[float] = None,
center_y: Optional[float] = None,
@@ -56,29 +55,29 @@ class PathGeometry:
collection_type: Optional[CollectionType] = None,
radius_multiplier: float = 1.0) -> str:
"""Create a default SVG path string with configurable positioning and sizing.
-
+
Args:
- location_view: LocationView for calculating dimensions
+ view_box: SvgViewBox for calculating dimensions
is_path_closed: Whether to create closed (rectangle) or open (line) path
center_x: X position for path center (defaults to view center)
- center_y: Y position for path center (defaults to view center)
+ center_y: Y position for path center (defaults to view center)
entity_type: EntityType for entity-specific radius (optional)
collection_type: CollectionType for collection-specific radius (optional)
radius_multiplier: Multiplier for radius size (e.g., 2.0 for double size)
-
+
Returns:
SVG path string
"""
# Default to view center if no center provided
if center_x is None:
- center_x = location_view.svg_view_box.x + (location_view.svg_view_box.width / 2.0)
+ center_x = view_box.x + (view_box.width / 2.0)
if center_y is None:
- center_y = location_view.svg_view_box.y + (location_view.svg_view_box.height / 2.0)
-
+ center_y = view_box.y + (view_box.height / 2.0)
+
# Get type-specific radius if provided, otherwise use default calculation
radius_x = None
radius_y = None
-
+
if entity_type:
entity_radius = cls.get_entity_radius(entity_type)
radius_x = entity_radius.x
@@ -87,12 +86,12 @@ class PathGeometry:
collection_radius = cls.get_collection_radius(collection_type)
radius_x = collection_radius.x
radius_y = collection_radius.y
-
+
# Apply default calculation for None values
if radius_x is None:
- radius_x = location_view.svg_view_box.width * (cls.DEFAULT_RADIUS_PERCENT / 50.0)
+ radius_x = view_box.width * (cls.DEFAULT_RADIUS_PERCENT / 50.0)
if radius_y is None:
- radius_y = location_view.svg_view_box.height * (cls.DEFAULT_RADIUS_PERCENT / 50.0)
+ radius_y = view_box.height * (cls.DEFAULT_RADIUS_PERCENT / 50.0)
# Apply radius multiplier
radius_x *= radius_multiplier
@@ -120,7 +119,7 @@ class PathGeometry:
@classmethod
def create_coverage_triangle_path_string(
cls,
- location_view : LocationView,
+ view_box : SvgViewBox,
apex_x : float,
apex_y : float,
direction : Tuple[float, float],
@@ -136,8 +135,8 @@ class PathGeometry:
# 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
+ height = view_box.width * size_fraction * 2.0
+ base_half_width = view_box.height * size_fraction
# Perpendicular to direction (rotate 90° counter-clockwise in
# SVG coordinates).
diff --git a/src/hi/apps/location/position_geometry.py b/src/hi/apps/location/position_geometry.py
index 2282288a..0c8a7c1c 100644
--- a/src/hi/apps/location/position_geometry.py
+++ b/src/hi/apps/location/position_geometry.py
@@ -11,16 +11,15 @@ like once you've decided where").
viewbox; used to lay out a group of entities arriving together.
* ``clamp_to_viewbox`` — keep a point inside the viewbox margin.
* ``default_icon_scale`` — entity-aware icon scale: ~10% of the
- viewbox's smaller dimension, clamped to the location's
- svg_position_bounds.
+ viewbox's smaller dimension, clamped to the canonical scale bounds.
* ``path_center`` — geometric center of an existing SVG path
string. Lives here because the *output* is a position even
though the input is a path string.
-Performs no DB writes and has no opinions about Entity vs
-Collection: callers in either domain pass in a ``LocationView`` (or
-view box) and receive geometry. Constants for the placement
-heuristic live here as the canonical home.
+Performs no DB writes and has no opinions about Entity vs Collection,
+and no coupling to any model: callers pass in a bare ``SvgViewBox``
+and receive geometry. Constants for the placement heuristic live here
+as the canonical home (scale clamps live on ``SvgItemPositionBounds``).
"""
from decimal import Decimal
@@ -28,7 +27,7 @@ import math
import re
from typing import Optional, Tuple
-from hi.apps.location.models import LocationView
+from hi.apps.common.svg_models import SvgItemPositionBounds, SvgViewBox
from hi.hi_styles import EntityStyle
@@ -43,8 +42,7 @@ class PositionGeometry:
DEFAULT_VIEWBOX_MARGIN_FRACTION = 0.05
@classmethod
- def view_center( cls, location_view : LocationView ) -> Tuple[float, float]:
- view_box = location_view.svg_view_box
+ def view_center( cls, view_box : SvgViewBox ) -> Tuple[float, float]:
return (
view_box.x + ( view_box.width / 2.0 ),
view_box.y + ( view_box.height / 2.0 ),
@@ -52,11 +50,10 @@ class PositionGeometry:
@classmethod
def grid_slot( cls,
- location_view : LocationView,
+ view_box : SvgViewBox,
grid_index : int,
grid_total : int ) -> Tuple[float, float]:
- view_box = location_view.svg_view_box
- center_x, center_y = cls.view_center( location_view )
+ center_x, center_y = cls.view_center( view_box )
if grid_total <= 1:
return center_x, center_y
@@ -135,19 +132,18 @@ class PositionGeometry:
@classmethod
def default_icon_scale( cls,
entity,
- location_view : LocationView ) -> Decimal:
+ view_box : SvgViewBox ) -> Decimal:
"""Default scale for an icon entity: ~10% of the viewbox'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
+ Automobile — override it), clamped to the canonical
+ SvgItemPositionBounds.DEFAULT_MIN_SCALE / DEFAULT_MAX_SCALE."""
icon_view_box = EntityStyle.get_svg_icon_viewbox( entity.entity_type )
icon_max_dimension = max( icon_view_box.width, icon_view_box.height )
if icon_max_dimension <= 0:
- return Decimal( str( location_view.location.svg_position_bounds.min_scale ) )
+ return Decimal( str( SvgItemPositionBounds.DEFAULT_MIN_SCALE ) )
viewbox_min_dimension = min( view_box.width, view_box.height )
size_fraction = cls.DEFAULT_ICON_SIZE_PERCENT_OF_VIEWBOX / 100.0
@@ -155,9 +151,8 @@ class PositionGeometry:
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
- scale = max( position_bounds.min_scale,
- min( scale, position_bounds.max_scale ) )
+ scale = max( SvgItemPositionBounds.DEFAULT_MIN_SCALE,
+ min( scale, SvgItemPositionBounds.DEFAULT_MAX_SCALE ) )
return Decimal( str( scale ) )
diff --git a/src/hi/apps/location/svg_item_factory.py b/src/hi/apps/location/svg_item_factory.py
index a077f78e..cd193206 100644
--- a/src/hi/apps/location/svg_item_factory.py
+++ b/src/hi/apps/location/svg_item_factory.py
@@ -116,7 +116,7 @@ class SvgItemFactory( Singleton ):
location_view : LocationView,
is_path_closed : bool ) -> str:
return PathGeometry.create_default_path_string(
- location_view=location_view,
+ view_box=location_view.svg_view_box,
is_path_closed=is_path_closed,
entity_type=entity.entity_type,
)
@@ -127,7 +127,7 @@ class SvgItemFactory( Singleton ):
is_path_closed : bool ) -> str:
# Use unified PathGeometry approach for collections
return PathGeometry.create_default_path_string(
- location_view=location_view,
+ view_box=location_view.svg_view_box,
is_path_closed=is_path_closed,
collection_type=collection.collection_type,
)
diff --git a/src/hi/apps/location/templates/location/edit/pages/location_svg_edit.html b/src/hi/apps/location/templates/location/edit/pages/location_svg_edit.html
index def5cc96..e46810ab 100644
--- a/src/hi/apps/location/templates/location/edit/pages/location_svg_edit.html
+++ b/src/hi/apps/location/templates/location/edit/pages/location_svg_edit.html
@@ -51,11 +51,7 @@
<button type="submit" class="btn btn-sm btn-outline-primary ms-2 mx-1">Apply</button>
</form>
<span class="text-muted mx-2" style="font-size: 0.85rem;">|</span>
- <label class="me-1 mb-0 mx-1" style="font-size: 0.85rem;"><b>Snap:</b></label>
- <input type="number" id="hi-svg-edit-snap-grid" class="form-control form-control-sm"
- style="width: 4rem;" value="5" min="0" max="50" step="1"
- title="Snap grid in screen pixels (0 to disable, hold Shift for fine mode)">
- <label class="ms-1 mb-0" style="font-size: 0.85rem;">px</label>
+ {% include "panes/snap_grid_input.html" %}
</div>
<div class="d-flex flex-nowrap gap-2 align-items-center">
<a href="{% url 'location_svg_edit_revert' location_id=location.id %}"
diff --git a/src/hi/apps/location/templates/location/panes/location_view.html b/src/hi/apps/location/templates/location/panes/location_view.html
index 7b19ea14..b47f4f59 100644
--- a/src/hi/apps/location/templates/location/panes/location_view.html
+++ b/src/hi/apps/location/templates/location/panes/location_view.html
@@ -6,11 +6,11 @@
class="hi-location-view-svg"
location-view-id="{{ location_view.id }}"
xmlns="http://www.w3.org/2000/svg"
- viewBox="{{ location_view.svg_view_box }}"
- extents="{{ location_view.location.svg_view_box }}"
+ viewBox="{{ svg_view_box_override|default:location_view.svg_view_box }}"
+ extents="{{ location_view.location.svg_view_box }}"
width="100%" height="100%" preserveAspectRatio="xMidYMid meet"
- style="transform-origin: 50% 50%; transform: rotate( {{ location_view.svg_rotate }}deg );"
- transform="rotate({{ location_view.svg_rotate }})">
+ style="transform-origin: 50% 50%; transform: rotate( {{ svg_rotate_override|default:location_view.svg_rotate }}deg );"
+ transform="rotate({{ svg_rotate_override|default:location_view.svg_rotate }})">
<defs>
{% include location_view.svg_style_name.svg_defs_template_name %}
</defs>
diff --git a/src/hi/apps/location/tests/test_path_geometry.py b/src/hi/apps/location/tests/test_path_geometry.py
index 8edbba82..5a15a387 100644
--- a/src/hi/apps/location/tests/test_path_geometry.py
+++ b/src/hi/apps/location/tests/test_path_geometry.py
@@ -1,9 +1,9 @@
import logging
from django.test import TestCase
+from hi.apps.common.svg_models import SvgViewBox
from hi.apps.entity.enums import EntityType
from hi.apps.collection.enums import CollectionType
-from hi.apps.location.models import Location, LocationView
from hi.apps.location.path_geometry import PathGeometry
logging.disable(logging.CRITICAL)
@@ -14,21 +14,8 @@ class TestPathGeometry(TestCase):
def setUp(self):
"""Set up test data."""
- self.location = Location.objects.create(
- name='Test Location',
- svg_fragment_filename='test.svg',
- svg_view_box_str='0 0 200 100',
- order_id=1
- )
-
- self.location_view = LocationView.objects.create(
- location=self.location,
- location_view_type_str='DEFAULT',
- name='Test View',
- svg_view_box_str='0 0 200 100', # Width=200, Height=100, Center=(100,50)
- svg_rotate=0,
- svg_style_name_str='COLOR'
- )
+ # Width=200, Height=100, Center=(100,50)
+ self.view_box = SvgViewBox(x=0, y=0, width=200, height=100)
def test_get_entity_radius_configured_types(self):
"""Test entity-specific radius configurations."""
@@ -62,7 +49,7 @@ class TestPathGeometry(TestCase):
def test_create_default_path_closed_no_entity_type(self):
"""Test closed path creation with default settings."""
svg_path = PathGeometry.create_default_path_string(
- location_view=self.location_view,
+ view_box=self.view_box,
is_path_closed=True
)
@@ -86,7 +73,7 @@ class TestPathGeometry(TestCase):
def test_create_default_path_open_no_entity_type(self):
"""Test open path creation with default settings."""
svg_path = PathGeometry.create_default_path_string(
- location_view=self.location_view,
+ view_box=self.view_box,
is_path_closed=False
)
@@ -103,7 +90,7 @@ class TestPathGeometry(TestCase):
def test_create_default_path_with_entity_type_door(self):
"""Test path creation with entity-specific radius (DOOR: y=16)."""
svg_path = PathGeometry.create_default_path_string(
- location_view=self.location_view,
+ view_box=self.view_box,
is_path_closed=True,
entity_type=EntityType.DOOR
)
@@ -122,7 +109,7 @@ class TestPathGeometry(TestCase):
def test_create_default_path_with_entity_type_wall(self):
"""Test path creation with entity-specific radius (WALL: x=16)."""
svg_path = PathGeometry.create_default_path_string(
- location_view=self.location_view,
+ view_box=self.view_box,
is_path_closed=True,
entity_type=EntityType.WALL
)
@@ -141,7 +128,7 @@ class TestPathGeometry(TestCase):
def test_create_default_path_custom_center(self):
"""Test path creation with custom center position."""
svg_path = PathGeometry.create_default_path_string(
- location_view=self.location_view,
+ view_box=self.view_box,
is_path_closed=False,
center_x=150.0,
center_y=25.0
@@ -155,7 +142,7 @@ class TestPathGeometry(TestCase):
def test_create_default_path_radius_multiplier(self):
"""Test path creation with radius multiplier."""
svg_path = PathGeometry.create_default_path_string(
- location_view=self.location_view,
+ view_box=self.view_box,
is_path_closed=True,
radius_multiplier=2.0
)
@@ -174,7 +161,7 @@ class TestPathGeometry(TestCase):
def test_create_default_path_entity_type_with_multiplier(self):
"""Test path creation with entity type and radius multiplier."""
svg_path = PathGeometry.create_default_path_string(
- location_view=self.location_view,
+ view_box=self.view_box,
is_path_closed=True,
entity_type=EntityType.APPLIANCE, # x=32, y=32
radius_multiplier=0.5
@@ -211,7 +198,7 @@ class TestPathGeometry(TestCase):
def test_create_default_path_with_collection_type(self):
"""Test path creation with collection type uses default behavior."""
svg_path = PathGeometry.create_default_path_string(
- location_view=self.location_view,
+ view_box=self.view_box,
is_path_closed=True,
collection_type=CollectionType.APPLIANCES
)
@@ -236,7 +223,7 @@ class TestPathGeometry(TestCase):
def test_entity_type_and_collection_type_mutual_exclusion(self):
"""Test that entity_type takes precedence over collection_type if both provided."""
svg_path = PathGeometry.create_default_path_string(
- location_view=self.location_view,
+ view_box=self.view_box,
is_path_closed=True,
entity_type=EntityType.DOOR, # Has y=16 radius
collection_type=CollectionType.APPLIANCES # Should be ignored
diff --git a/src/hi/apps/location/tests/test_position_geometry.py b/src/hi/apps/location/tests/test_position_geometry.py
index 7091be66..0bdcbe31 100644
--- a/src/hi/apps/location/tests/test_position_geometry.py
+++ b/src/hi/apps/location/tests/test_position_geometry.py
@@ -1,14 +1,14 @@
"""
Tests for PositionGeometry.
-Pure-functional layout math. No DB writes; some methods take a
-``LocationView`` (mockable) or a Location row.
+Pure-functional layout math. No DB writes and no model coupling:
+methods take a bare ``SvgViewBox`` and return geometry.
"""
import logging
from decimal import Decimal
-from unittest.mock import Mock
+from hi.apps.common.svg_models import SvgItemPositionBounds, SvgViewBox
from hi.apps.entity.models import Entity
from hi.apps.entity.enums import EntityType
from hi.apps.location.position_geometry import PositionGeometry
@@ -20,35 +20,24 @@ logging.disable(logging.CRITICAL)
class TestPositionGeometryViewCenter(BaseTestCase):
def test_view_center_respects_origin(self):
- from hi.apps.common.svg_models import SvgViewBox
-
- location_view = Mock()
- location_view.svg_view_box = SvgViewBox(x=200, y=300, width=1000, height=1000)
-
- x, y = PositionGeometry.view_center(location_view)
+ view_box = SvgViewBox(x=200, y=300, width=1000, height=1000)
+ x, y = PositionGeometry.view_center(view_box)
self.assertAlmostEqual(x, 700.0)
self.assertAlmostEqual(y, 800.0)
class TestPositionGeometryGridSlot(BaseTestCase):
- def _make_view(self, x, y, width, height):
- from hi.apps.common.svg_models import SvgViewBox
-
- location_view = Mock()
- location_view.svg_view_box = SvgViewBox(x=x, y=y, width=width, height=height)
- return location_view
-
def test_single_entity_returns_center(self):
- view = self._make_view(0, 0, 1000, 1000)
- x, y = PositionGeometry.grid_slot(location_view=view, grid_index=0, grid_total=1)
+ view_box = SvgViewBox(x=0, y=0, width=1000, height=1000)
+ x, y = PositionGeometry.grid_slot(view_box=view_box, grid_index=0, grid_total=1)
self.assertAlmostEqual(x, 500.0)
self.assertAlmostEqual(y, 500.0)
def test_multiple_entities_distributed_around_center(self):
- view = self._make_view(0, 0, 1000, 1000)
+ view_box = SvgViewBox(x=0, y=0, width=1000, height=1000)
positions = [
- PositionGeometry.grid_slot(location_view=view, grid_index=i, grid_total=4)
+ PositionGeometry.grid_slot(view_box=view_box, grid_index=i, grid_total=4)
for i in range(4)
]
# All four positions are distinct, all sit inside the viewbox
@@ -69,9 +58,9 @@ class TestPositionGeometryGridSlot(BaseTestCase):
self.assertAlmostEqual(mean_y, 500.0)
def test_grid_wraps_to_multiple_rows(self):
- view = self._make_view(0, 0, 1000, 1000)
+ view_box = SvgViewBox(x=0, y=0, width=1000, height=1000)
positions = [
- PositionGeometry.grid_slot(location_view=view, grid_index=i, grid_total=8)
+ PositionGeometry.grid_slot(view_box=view_box, grid_index=i, grid_total=8)
for i in range(8)
]
# Grid spans multiple rows AND multiple columns (eight items
@@ -83,8 +72,8 @@ class TestPositionGeometryGridSlot(BaseTestCase):
self.assertGreater(len(distinct_ys), 1)
def test_clamps_to_viewbox_margin(self):
- view = self._make_view(0, 0, 100, 100)
- x, y = PositionGeometry.grid_slot(location_view=view, grid_index=0, grid_total=16)
+ view_box = SvgViewBox(x=0, y=0, width=100, height=100)
+ x, y = PositionGeometry.grid_slot(view_box=view_box, grid_index=0, grid_total=16)
margin_fraction = PositionGeometry.DEFAULT_VIEWBOX_MARGIN_FRACTION
margin = 100 * margin_fraction
self.assertGreaterEqual(x, margin)
@@ -96,44 +85,27 @@ class TestPositionGeometryGridSlot(BaseTestCase):
class TestPositionGeometryDefaultIconScale(BaseTestCase):
def _fixtures(self, viewbox_width, viewbox_height):
- from hi.apps.common.svg_models import SvgViewBox
- from hi.apps.location.models import Location
-
entity = Entity.objects.create(
name='Scale Test Entity',
entity_type_str=str(EntityType.CAMERA),
)
- location = Location.objects.create(
- name='Test Location',
- svg_view_box_str=f'0 0 {viewbox_width} {viewbox_height}',
- )
- location_view = Mock()
- location_view.location = location
- location_view.svg_view_box = SvgViewBox(
- x=0, y=0, width=viewbox_width, height=viewbox_height,
- )
- return entity, location, location_view
+ view_box = SvgViewBox(x=0, y=0, width=viewbox_width, height=viewbox_height)
+ return entity, view_box
def test_zero_viewbox_clamps_to_min_scale(self):
- entity, location, location_view = self._fixtures(0, 0)
- scale = PositionGeometry.default_icon_scale(
- entity=entity, location_view=location_view,
- )
- self.assertEqual(scale, Decimal(str(location.svg_position_bounds.min_scale)))
+ entity, view_box = self._fixtures(0, 0)
+ scale = PositionGeometry.default_icon_scale(entity=entity, view_box=view_box)
+ self.assertEqual(scale, Decimal(str(SvgItemPositionBounds.DEFAULT_MIN_SCALE)))
def test_very_large_viewbox_clamps_to_max_scale(self):
- entity, location, location_view = self._fixtures(100000, 100000)
- scale = PositionGeometry.default_icon_scale(
- entity=entity, location_view=location_view,
- )
- self.assertEqual(scale, Decimal(str(location.svg_position_bounds.max_scale)))
+ entity, view_box = self._fixtures(100000, 100000)
+ scale = PositionGeometry.default_icon_scale(entity=entity, view_box=view_box)
+ self.assertEqual(scale, Decimal(str(SvgItemPositionBounds.DEFAULT_MAX_SCALE)))
def test_very_small_viewbox_clamps_to_min_scale(self):
- entity, location, location_view = self._fixtures(10, 10)
- scale = PositionGeometry.default_icon_scale(
- entity=entity, location_view=location_view,
- )
- self.assertEqual(scale, Decimal(str(location.svg_position_bounds.min_scale)))
+ entity, view_box = self._fixtures(10, 10)
+ scale = PositionGeometry.default_icon_scale(entity=entity, view_box=view_box)
+ self.assertEqual(scale, Decimal(str(SvgItemPositionBounds.DEFAULT_MIN_SCALE)))
class TestPositionGeometryPathCenter(BaseTestCase):
diff --git a/src/hi/apps/location/tests/test_views.py b/src/hi/apps/location/tests/test_views.py
index b927ad71..98566b80 100644
--- a/src/hi/apps/location/tests/test_views.py
+++ b/src/hi/apps/location/tests/test_views.py
@@ -8,10 +8,13 @@ from hi.apps.control.models import Controller
from hi.apps.control.one_click_control_service import (
OneClickNotSupported,
)
+from hi.apps.common.svg_models import SvgViewBox
from hi.apps.entity.models import Entity, EntityState
from hi.apps.location.location_manager import LocationManager
from hi.apps.location.models import Location, LocationView
+from hi.apps.location.views import LocationViewView
from hi.enums import ViewType
+from hi.testing.base_test_case import BaseTestCase, MockRequest
from hi.testing.view_test_base import SyncViewTestCase, AsyncViewTestCase, DualModeViewTestCase
logging.disable(logging.CRITICAL)
@@ -896,3 +899,36 @@ class TestLocationItemEditModeView(SyncViewTestCase):
self.assertEqual(response.status_code, 405)
+
+
+class TestLocationViewGeometryOverride(BaseTestCase):
+ """LocationViewView._get_geometry_override - validates the optional
+ pan/zoom override carried on the query string, rejecting malformed
+ input so it can never inject a bad viewBox attribute."""
+
+ def _override(self, **get_params):
+ request = MockRequest(GET=dict(get_params))
+ return LocationViewView()._get_geometry_override(request)
+
+ def test_no_params_returns_none(self):
+ view_box, rotate = self._override()
+ self.assertIsNone(view_box)
+ self.assertIsNone(rotate)
+
+ def test_valid_viewbox_and_rotate(self):
+ view_box, rotate = self._override(
+ svg_view_box='10 20 30 40', svg_rotate='45')
+ self.assertEqual(view_box.to_dict(),
+ SvgViewBox(x=10, y=20, width=30, height=40).to_dict())
+ self.assertEqual(rotate, '45')
+
+ def test_malformed_viewbox_rejected(self):
+ view_box, rotate = self._override(svg_view_box='not a box')
+ self.assertIsNone(view_box)
+ self.assertIsNone(rotate)
+
+ def test_valid_viewbox_with_malformed_rotate_drops_only_rotate(self):
+ view_box, rotate = self._override(
+ svg_view_box='10 20 30 40', svg_rotate='sideways')
+ self.assertIsNotNone(view_box)
+ self.assertIsNone(rotate)
diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.py
index d000cb52..a94b7fd1 100644
--- a/src/hi/apps/location/views.py
+++ b/src/hi/apps/location/views.py
@@ -6,6 +6,7 @@ from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.shortcuts import reverse
from django.views.generic import View
+from hi.apps.common.svg_models import SvgViewBox
from hi.apps.common.utils import is_ajax, str_to_bool
import hi.apps.common.antinode as antinode
@@ -100,12 +101,40 @@ class LocationViewView( HiGridView, LocationViewMixin ):
include_status_display_data = bool( not request.view_parameters.is_editing ),
)
+ svg_view_box_override, svg_rotate_override = self._get_geometry_override( request )
+
return {
'is_async_request': is_ajax( request ),
'location_view': location_view,
'location_view_data': location_view_data,
+ # Optional pan/zoom override carried by operations that preserve
+ # the user's current view (e.g. EntityAddView). Absent on normal
+ # navigation, so the template falls back to the stored geometry.
+ 'svg_view_box_override': svg_view_box_override,
+ 'svg_rotate_override': svg_rotate_override,
}
+ def _get_geometry_override( self, request ):
+ """Parse and validate an optional SVG geometry override from the
+ query string. Returns (SvgViewBox|None, rotate_str|None). The
+ rotate override is only honored alongside a valid viewbox, since
+ the two together represent one explored geometry."""
+ svg_view_box_str = request.GET.get( 'svg_view_box' )
+ if not svg_view_box_str:
+ return ( None, None )
+ try:
+ svg_view_box_override = SvgViewBox.from_attribute_value( svg_view_box_str )
+ except ( ValueError, TypeError ):
+ return ( None, None )
+
+ svg_rotate_override = request.GET.get( 'svg_rotate' )
+ try:
+ float( svg_rotate_override )
+ except ( ValueError, TypeError ):
+ svg_rotate_override = None
+
+ return ( svg_view_box_override, svg_rotate_override )
+
class LocationSwitchView( View, LocationViewMixin ):
diff --git a/src/hi/apps/monitor/display_data.py b/src/hi/apps/monitor/display_data.py
index 8e957ec7..bbb9b009 100644
--- a/src/hi/apps/monitor/display_data.py
+++ b/src/hi/apps/monitor/display_data.py
@@ -23,8 +23,10 @@ from hi.apps.console.console_converter_helper import (
from hi.apps.entity.entity_state_role_order import ENTITY_STATUS_VIEW_ORDERING
from hi.apps.entity.enums import EntityStateRole, EntityStateType, EntityStateValue
from hi.apps.entity.models import Entity
+from hi.apps.sense.transient_models import SensorResponse
from hi.hi_styles import StatusStyle
+from hi.units import UnitQuantity
from .enums import EntityDisplayCategory
from .status_data import EntityStateStatusData, EntityStatusData
@@ -113,6 +115,27 @@ class EntityStateDisplayData:
self._controller_data_value = self._get_controller_data_value()
return
+ @classmethod
+ def for_value( cls, entity_state, value ) -> 'EntityStateDisplayData':
+ """Build a display projection for a single discrete value (e.g. a
+ historical reading) so callers color it through the SAME status
+ dispatch as the live display, rather than re-deriving the status
+ token from the raw value. No time-decay is applied — a lone value
+ has no penultimate to decay from — so the result reflects the
+ value's own bucket/token (e.g. a TEMPERATURE reading's color band,
+ a BATTERY level's low/ok)."""
+ synthetic_response = SensorResponse(
+ integration_key = None,
+ value = None if value is None else str( value ),
+ timestamp = datetimeproxy.now(),
+ )
+ status_data = EntityStateStatusData(
+ entity_state = entity_state,
+ sensor_response_list = [ synthetic_response ],
+ controller_data_list = [],
+ )
+ return cls( status_data )
+
def __getattr__( self, name ):
# Fall through to the wrapped raw data for any accessor not
# defined here (e.g. ``latest_sensor_response``, ``has_sensor``,
@@ -177,6 +200,18 @@ class EntityStateDisplayData:
return self.sensor_response_list[0].value
return None
+ @property
+ def latest_sensor_timestamp(self):
+ # Responses are deduplicated by value change upstream, so the
+ # latest response is the most recent *transition*. In the decay
+ # handlers this branch is only reached once the entity has left
+ # the value of interest, making this timestamp the moment that
+ # event ENDED — the correct anchor for the recent/past decay
+ # window (independent of how long the event lasted).
+ if self.sensor_response_list:
+ return self.sensor_response_list[0].timestamp
+ return None
+
@property
def latest_display_value(self) -> DisplayValue:
"""Latest sensor value translated to the user's preferred
@@ -278,13 +313,7 @@ class EntityStateDisplayData:
if len(self.sensor_response_list) > 1:
return self.sensor_response_list[1].value
return None
-
- @property
- def penultimate_sensor_timestamp(self):
- if len(self.sensor_response_list) > 1:
- return self.sensor_response_list[1].timestamp
- return None
-
+
def _get_controller_data_value(self):
"""Compute the controller-shaped value for this state.
@@ -358,6 +387,9 @@ class EntityStateDisplayData:
if self.entity_state.entity_state_type == EntityStateType.BATTERY_LEVEL:
return self._get_battery_level_status_style()
+ if self.entity_state.entity_state_type == EntityStateType.TEMPERATURE:
+ return self._get_temperature_status_style()
+
# TODO: These should map the latest value into a continuous range of colors/opacity
#
# EntityStateType.AIR_PRESSURE
@@ -367,10 +399,12 @@ class EntityStateDisplayData:
# EntityStateType.LIGHT_LEVEL
# EntityStateType.MOISTURE
# EntityStateType.SOUND_LEVEL
- # EntityStateType.TEMPERATURE
# EntityStateType.WATER_FLOW
# EntityStateType.WIND_SPEED
+ return self._get_default_status_style()
+
+ def _get_default_status_style( self ):
# Use the display-unit text so the polling refresh of the
# status display matches what the initial server-side
# template render produced (combined magnitude + unit
@@ -378,16 +412,15 @@ class EntityStateDisplayData:
status_value = str( self.latest_display_value )
if not status_value:
status_value = StatusStyle.DEFAULT_STATUS_VALUE
-
return StatusStyle.default( status_value = status_value )
-
+
def _get_movement_status_style( self ):
if self.latest_sensor_value == str(EntityStateValue.ACTIVE):
return StatusStyle.MovementActive
if self.penultimate_sensor_value == str(EntityStateValue.ACTIVE):
- movement_timedelta = datetimeproxy.now() - self.penultimate_sensor_timestamp
+ movement_timedelta = datetimeproxy.now() - self.latest_sensor_timestamp
if movement_timedelta.total_seconds() < self.RECENT_MOVEMENT_THRESHOLD_SECS:
return StatusStyle.MovementRecent
@@ -402,7 +435,7 @@ class EntityStateDisplayData:
return StatusStyle.MovementActive
if self.penultimate_sensor_value == str(EntityStateValue.ACTIVE):
- presence_timedelta = datetimeproxy.now() - self.penultimate_sensor_timestamp
+ presence_timedelta = datetimeproxy.now() - self.latest_sensor_timestamp
if presence_timedelta.total_seconds() < self.RECENT_MOVEMENT_THRESHOLD_SECS:
return StatusStyle.MovementRecent
@@ -425,7 +458,7 @@ class EntityStateDisplayData:
if ( self.penultimate_sensor_value
and self.penultimate_sensor_value != object_none_value ):
- object_timedelta = datetimeproxy.now() - self.penultimate_sensor_timestamp
+ object_timedelta = datetimeproxy.now() - self.latest_sensor_timestamp
if object_timedelta.total_seconds() < self.RECENT_MOVEMENT_THRESHOLD_SECS:
return StatusStyle.MovementRecent
@@ -440,7 +473,7 @@ class EntityStateDisplayData:
return StatusStyle.SmokeDetected
if self.penultimate_sensor_value == str(EntityStateValue.SMOKE_DETECTED):
- smoke_timedelta = datetimeproxy.now() - self.penultimate_sensor_timestamp
+ smoke_timedelta = datetimeproxy.now() - self.latest_sensor_timestamp
if smoke_timedelta.total_seconds() < self.RECENT_SMOKE_THRESHOLD_SECS:
return StatusStyle.SmokeRecent
@@ -455,7 +488,7 @@ class EntityStateDisplayData:
return StatusStyle.MoistureDetected
if self.penultimate_sensor_value == str(EntityStateValue.MOISTURE_DETECTED):
- moisture_timedelta = datetimeproxy.now() - self.penultimate_sensor_timestamp
+ moisture_timedelta = datetimeproxy.now() - self.latest_sensor_timestamp
if moisture_timedelta.total_seconds() < self.RECENT_MOISTURE_THRESHOLD_SECS:
return StatusStyle.MoistureRecent
@@ -470,7 +503,7 @@ class EntityStateDisplayData:
return StatusStyle.CoDetected
if self.penultimate_sensor_value == str(EntityStateValue.CO_DETECTED):
- co_timedelta = datetimeproxy.now() - self.penultimate_sensor_timestamp
+ co_timedelta = datetimeproxy.now() - self.latest_sensor_timestamp
if co_timedelta.total_seconds() < self.RECENT_CO_THRESHOLD_SECS:
return StatusStyle.CoRecent
@@ -485,7 +518,7 @@ class EntityStateDisplayData:
return StatusStyle.GasDetected
if self.penultimate_sensor_value == str(EntityStateValue.GAS_DETECTED):
- gas_timedelta = datetimeproxy.now() - self.penultimate_sensor_timestamp
+ gas_timedelta = datetimeproxy.now() - self.latest_sensor_timestamp
if gas_timedelta.total_seconds() < self.RECENT_GAS_THRESHOLD_SECS:
return StatusStyle.GasRecent
@@ -528,7 +561,7 @@ class EntityStateDisplayData:
return StatusStyle.Open
if self.penultimate_sensor_value == str(EntityStateValue.OPEN):
- open_timedelta = datetimeproxy.now() - self.penultimate_sensor_timestamp
+ open_timedelta = datetimeproxy.now() - self.latest_sensor_timestamp
if open_timedelta.total_seconds() < self.RECENT_OPEN_THRESHOLD_SECS:
return StatusStyle.OpenRecent
@@ -567,7 +600,30 @@ class EntityStateDisplayData:
if magnitude < self.BATTERY_LOW_THRESHOLD_PCT:
return StatusStyle.BatteryLow
return StatusStyle.BatteryOk
-
+
+ def _get_temperature_status_style( self ):
+ # Bucket on the absolute temperature (cold -> pleasant -> hot).
+ # Normalize to the canonical °C first so the bucket thresholds are
+ # unit-agnostic regardless of whether this state is stored in °F,
+ # °C, etc. If the value or units can't be resolved, fall back to the
+ # plain numeric status display.
+ celsius = self._latest_temperature_celsius()
+ if celsius is None:
+ return self._get_default_status_style()
+ return StatusStyle.temperature( celsius )
+
+ def _latest_temperature_celsius( self ):
+ """The latest sensor value converted to canonical °C using the
+ EntityState's stored ``units``, or None when it can't be resolved
+ (no value, no/unknown units, non-numeric)."""
+ raw_value = self.latest_sensor_value
+ units = self.entity_state.units
+ if raw_value is None or not units:
+ return None
+ try:
+ return UnitQuantity( float( raw_value ), units ).to( 'degC' ).magnitude
+ except Exception:
+ return None
@dataclass
diff --git a/src/hi/apps/monitor/status_display_manager.py b/src/hi/apps/monitor/status_display_manager.py
index 544b4b08..5ec122c0 100644
--- a/src/hi/apps/monitor/status_display_manager.py
+++ b/src/hi/apps/monitor/status_display_manager.py
@@ -12,6 +12,7 @@ from hi.apps.location.svg_item_factory import SvgItemFactory
from hi.apps.sense.models import Sensor
from hi.apps.sense.sensor_response_manager import SensorResponseMixin
from hi.apps.sense.transient_models import SensorResponse
+from hi.testing.dev_injection import DevInjectionManager
from hi.testing.dev_overrides import DevOverrideManager
from .display_data import EntityStateDisplayData
@@ -55,7 +56,6 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
return status_map
-
def get_all_entity_state_status_data_list( self ) -> List[ EntityStateStatusData ]:
"""
Gets the latest sensor responses for all EntityStates. Used by client
@@ -395,6 +395,13 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
sensor_list = sensor_list,
)
+ # Dev-only: let the simulator's 'Clear States' drop pre-cutoff
+ # responses so lingering recent/past visuals don't block re-runs.
+ if settings.DEBUG and getattr( settings, 'DEBUG_FORCE_SENSOR_RESPONSE_CUTOFF', False ):
+ sensor_to_sensor_response_list = DevInjectionManager.apply_sensor_response_cutoff(
+ sensor_to_sensor_response_list,
+ )
+
# Apply overrides into a fresh dict so neither the
# SensorResponse objects nor the response lists owned by
# SensorResponseManager's cache are touched. Mutating
diff --git a/src/hi/apps/monitor/tests/test_status_display_data.py b/src/hi/apps/monitor/tests/test_status_display_data.py
index e590fc44..69f62f02 100644
--- a/src/hi/apps/monitor/tests/test_status_display_data.py
+++ b/src/hi/apps/monitor/tests/test_status_display_data.py
@@ -142,21 +142,24 @@ class TestEntityStateDisplayData(BaseTestCase):
"""Test MOVEMENT state returns MovementRecent for recently active state."""
base_time = datetime(2023, 1, 1, 12, 0, 0)
mock_now.return_value = base_time
-
- # Penultimate was active 60 seconds ago (within 90 second threshold)
- recent_response = self._create_mock_sensor_response(
+
+ # Decay is anchored on when the event ENDED (the latest, post-event
+ # transition), not when it started. Movement ended (returned to idle)
+ # 60s ago — within the 90s recent window — even though it began long
+ # before that. Start-anchoring would mis-classify this as idle.
+ latest_response = self._create_mock_sensor_response(
str(EntityStateValue.IDLE),
- base_time
+ base_time - timedelta(seconds=60)
)
- past_response = self._create_mock_sensor_response(
+ prior_response = self._create_mock_sensor_response(
str(EntityStateValue.ACTIVE),
- base_time - timedelta(seconds=60)
+ base_time - timedelta(seconds=600)
)
-
- status_data = self._create_entity_state_status_data('MOVEMENT', [recent_response, past_response])
-
+
+ status_data = self._create_entity_state_status_data('MOVEMENT', [latest_response, prior_response])
+
display_data = EntityStateDisplayData(status_data)
-
+
self.assertEqual(display_data.svg_status_style, StatusStyle.MovementRecent)
@patch('hi.apps.common.datetimeproxy.now')
@@ -164,21 +167,23 @@ class TestEntityStateDisplayData(BaseTestCase):
"""Test MOVEMENT state returns MovementPast for past active state."""
base_time = datetime(2023, 1, 1, 12, 0, 0)
mock_now.return_value = base_time
-
- # Penultimate was active 120 seconds ago (between 90-180 second threshold)
- recent_response = self._create_mock_sensor_response(
+
+ # Movement ended 120s ago (between the 90s recent and 180s past
+ # thresholds); it began long before. Start-anchoring would call
+ # this idle.
+ latest_response = self._create_mock_sensor_response(
str(EntityStateValue.IDLE),
- base_time
+ base_time - timedelta(seconds=120)
)
- past_response = self._create_mock_sensor_response(
+ prior_response = self._create_mock_sensor_response(
str(EntityStateValue.ACTIVE),
- base_time - timedelta(seconds=120)
+ base_time - timedelta(seconds=600)
)
-
- status_data = self._create_entity_state_status_data('MOVEMENT', [recent_response, past_response])
-
+
+ status_data = self._create_entity_state_status_data('MOVEMENT', [latest_response, prior_response])
+
display_data = EntityStateDisplayData(status_data)
-
+
self.assertEqual(display_data.svg_status_style, StatusStyle.MovementPast)
@patch('hi.apps.common.datetimeproxy.now')
@@ -186,21 +191,22 @@ class TestEntityStateDisplayData(BaseTestCase):
"""Test MOVEMENT state returns MovementIdle beyond all thresholds."""
base_time = datetime(2023, 1, 1, 12, 0, 0)
mock_now.return_value = base_time
-
- # Penultimate was active 200 seconds ago (beyond 180 second threshold)
- recent_response = self._create_mock_sensor_response(
+
+ # Movement ended 200s ago — beyond the 180s past threshold — so the
+ # decay has fully elapsed and it reads idle again.
+ latest_response = self._create_mock_sensor_response(
str(EntityStateValue.IDLE),
- base_time
+ base_time - timedelta(seconds=200)
)
- past_response = self._create_mock_sensor_response(
+ prior_response = self._create_mock_sensor_response(
str(EntityStateValue.ACTIVE),
- base_time - timedelta(seconds=200)
+ base_time - timedelta(seconds=600)
)
-
- status_data = self._create_entity_state_status_data('MOVEMENT', [recent_response, past_response])
-
+
+ status_data = self._create_entity_state_status_data('MOVEMENT', [latest_response, prior_response])
+
display_data = EntityStateDisplayData(status_data)
-
+
self.assertEqual(display_data.svg_status_style, StatusStyle.MovementIdle)
# SMOKE State Type Tests with Time Thresholds
@@ -224,21 +230,23 @@ class TestEntityStateDisplayData(BaseTestCase):
@patch('hi.apps.common.datetimeproxy.now')
def test_smoke_state_recent_within_threshold(self, mock_now):
- # Penultimate detected 5 minutes ago (within the 10-minute
- # RECENT threshold); current is clear.
+ # Smoke cleared 5 minutes ago (within the 10-minute RECENT
+ # threshold), having been detected long before. Decay anchors on
+ # the clear (event end), so start-anchoring would call this clear.
base_time = datetime(2023, 1, 1, 12, 0, 0)
mock_now.return_value = base_time
- recent_response = self._create_mock_sensor_response(
- str(EntityStateValue.SMOKE_CLEAR), base_time,
+ latest_response = self._create_mock_sensor_response(
+ str(EntityStateValue.SMOKE_CLEAR),
+ base_time - timedelta(seconds=300),
)
- past_response = self._create_mock_sensor_response(
+ prior_response = self._create_mock_sensor_response(
str(EntityStateValue.SMOKE_DETECTED),
- base_time - timedelta(seconds=300),
+ base_time - timedelta(seconds=5400),
)
status_data = self._create_entity_state_status_data(
- 'SMOKE', [recent_response, past_response],
+ 'SMOKE', [latest_response, prior_response],
)
display_data = EntityStateDisplayData(status_data)
@@ -247,21 +255,22 @@ class TestEntityStateDisplayData(BaseTestCase):
@patch('hi.apps.common.datetimeproxy.now')
def test_smoke_state_past_beyond_recent_within_past(self, mock_now):
- # Penultimate detected 20 minutes ago (between RECENT 10
- # min and PAST 30 min thresholds).
+ # Smoke cleared 20 minutes ago (between the RECENT 10-min and PAST
+ # 30-min thresholds), having been detected long before.
base_time = datetime(2023, 1, 1, 12, 0, 0)
mock_now.return_value = base_time
- recent_response = self._create_mock_sensor_response(
- str(EntityStateValue.SMOKE_CLEAR), base_time,
+ latest_response = self._create_mock_sensor_response(
+ str(EntityStateValue.SMOKE_CLEAR),
+ base_time - timedelta(seconds=1200),
)
- past_response = self._create_mock_sensor_response(
+ prior_response = self._create_mock_sensor_response(
str(EntityStateValue.SMOKE_DETECTED),
- base_time - timedelta(seconds=1200),
+ base_time - timedelta(seconds=5400),
)
status_data = self._create_entity_state_status_data(
- 'SMOKE', [recent_response, past_response],
+ 'SMOKE', [latest_response, prior_response],
)
display_data = EntityStateDisplayData(status_data)
@@ -270,20 +279,22 @@ class TestEntityStateDisplayData(BaseTestCase):
@patch('hi.apps.common.datetimeproxy.now')
def test_smoke_state_clear_after_past_threshold(self, mock_now):
- # Penultimate detected 1 hour ago (beyond PAST 30 min).
+ # Smoke cleared 40 minutes ago — beyond the PAST 30-min threshold —
+ # so the decay has fully elapsed and it reads clear.
base_time = datetime(2023, 1, 1, 12, 0, 0)
mock_now.return_value = base_time
- recent_response = self._create_mock_sensor_response(
- str(EntityStateValue.SMOKE_CLEAR), base_time,
+ latest_response = self._create_mock_sensor_response(
+ str(EntityStateValue.SMOKE_CLEAR),
+ base_time - timedelta(seconds=2400),
)
- past_response = self._create_mock_sensor_response(
+ prior_response = self._create_mock_sensor_response(
str(EntityStateValue.SMOKE_DETECTED),
- base_time - timedelta(seconds=3600),
+ base_time - timedelta(seconds=5400),
)
status_data = self._create_entity_state_status_data(
- 'SMOKE', [recent_response, past_response],
+ 'SMOKE', [latest_response, prior_response],
)
display_data = EntityStateDisplayData(status_data)
@@ -352,17 +363,18 @@ class TestEntityStateDisplayData(BaseTestCase):
def test_object_presence_recent_within_threshold(self, mock_now):
base_time = datetime(2023, 1, 1, 12, 0, 0)
mock_now.return_value = base_time
- # Penultimate detected a class 60s ago (within RECENT 90s);
- # current is NONE.
- recent_response = self._create_mock_sensor_response(
- str(EntityStateValue.OBJECT_NONE), base_time,
+ # Detection cleared (returned to NONE) 60s ago (within RECENT 90s),
+ # having begun long before. Start-anchoring would call this idle.
+ latest_response = self._create_mock_sensor_response(
+ str(EntityStateValue.OBJECT_NONE),
+ base_time - timedelta(seconds=60),
)
- past_response = self._create_mock_sensor_response(
+ prior_response = self._create_mock_sensor_response(
str(EntityStateValue.OBJECT_ANIMAL),
- base_time - timedelta(seconds=60),
+ base_time - timedelta(seconds=600),
)
status_data = self._create_entity_state_status_data(
- 'OBJECT_PRESENCE', [recent_response, past_response],
+ 'OBJECT_PRESENCE', [latest_response, prior_response],
)
display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.MovementRecent)
@@ -371,16 +383,18 @@ class TestEntityStateDisplayData(BaseTestCase):
def test_object_presence_past_within_threshold(self, mock_now):
base_time = datetime(2023, 1, 1, 12, 0, 0)
mock_now.return_value = base_time
- # Penultimate detected a class 120s ago (between 90s and 180s).
- recent_response = self._create_mock_sensor_response(
- str(EntityStateValue.OBJECT_NONE), base_time,
+ # Detection cleared 120s ago (between the 90s and 180s thresholds),
+ # having begun long before.
+ latest_response = self._create_mock_sensor_response(
+ str(EntityStateValue.OBJECT_NONE),
+ base_time - timedelta(seconds=120),
)
- past_response = self._create_mock_sensor_response(
+ prior_response = self._create_mock_sensor_response(
str(EntityStateValue.OBJECT_CAR),
- base_time - timedelta(seconds=120),
+ base_time - timedelta(seconds=600),
)
status_data = self._create_entity_state_status_data(
- 'OBJECT_PRESENCE', [recent_response, past_response],
+ 'OBJECT_PRESENCE', [latest_response, prior_response],
)
display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.MovementPast)
@@ -389,16 +403,18 @@ class TestEntityStateDisplayData(BaseTestCase):
def test_object_presence_idle_beyond_threshold(self, mock_now):
base_time = datetime(2023, 1, 1, 12, 0, 0)
mock_now.return_value = base_time
- # Penultimate detected a class 200s ago (beyond PAST 180s).
- recent_response = self._create_mock_sensor_response(
- str(EntityStateValue.OBJECT_NONE), base_time,
+ # Detection cleared 200s ago — beyond the PAST 180s threshold — so
+ # the decay has fully elapsed and it reads idle.
+ latest_response = self._create_mock_sensor_response(
+ str(EntityStateValue.OBJECT_NONE),
+ base_time - timedelta(seconds=200),
)
- past_response = self._create_mock_sensor_response(
+ prior_response = self._create_mock_sensor_response(
str(EntityStateValue.OBJECT_PACKAGE),
- base_time - timedelta(seconds=200),
+ base_time - timedelta(seconds=600),
)
status_data = self._create_entity_state_status_data(
- 'OBJECT_PRESENCE', [recent_response, past_response],
+ 'OBJECT_PRESENCE', [latest_response, prior_response],
)
display_data = EntityStateDisplayData(status_data)
self.assertEqual(display_data.svg_status_style, StatusStyle.MovementIdle)
@@ -422,21 +438,23 @@ class TestEntityStateDisplayData(BaseTestCase):
"""Test OPEN_CLOSE state returns OpenRecent for recently open state."""
base_time = datetime(2023, 1, 1, 12, 0, 0)
mock_now.return_value = base_time
-
- # Was open 60 seconds ago (within 90 second threshold)
- recent_response = self._create_mock_sensor_response(
+
+ # Closed 60 seconds ago (within the 90s recent window) after having
+ # been open for a long time. Decay anchors on the close (event end),
+ # so a long open no longer suppresses the "recently open" cue.
+ latest_response = self._create_mock_sensor_response(
str(EntityStateValue.CLOSED),
- base_time
+ base_time - timedelta(seconds=60)
)
- past_response = self._create_mock_sensor_response(
+ prior_response = self._create_mock_sensor_response(
str(EntityStateValue.OPEN),
- base_time - timedelta(seconds=60)
+ base_time - timedelta(seconds=600)
)
-
- status_data = self._create_entity_state_status_data('OPEN_CLOSE', [recent_response, past_response])
-
+
+ status_data = self._create_entity_state_status_data('OPEN_CLOSE', [latest_response, prior_response])
+
display_data = EntityStateDisplayData(status_data)
-
+
self.assertEqual(display_data.svg_status_style, StatusStyle.OpenRecent)
@patch('hi.apps.common.datetimeproxy.now')
@@ -444,21 +462,22 @@ class TestEntityStateDisplayData(BaseTestCase):
"""Test OPEN_CLOSE state returns OpenPast for past open state."""
base_time = datetime(2023, 1, 1, 12, 0, 0)
mock_now.return_value = base_time
-
- # Was open 120 seconds ago (between 90-180 second threshold)
- recent_response = self._create_mock_sensor_response(
+
+ # Closed 120 seconds ago (between the 90s and 180s thresholds) after
+ # having been open for a long time.
+ latest_response = self._create_mock_sensor_response(
str(EntityStateValue.CLOSED),
- base_time
+ base_time - timedelta(seconds=120)
)
- past_response = self._create_mock_sensor_response(
+ prior_response = self._create_mock_sensor_response(
str(EntityStateValue.OPEN),
- base_time - timedelta(seconds=120)
+ base_time - timedelta(seconds=600)
)
-
- status_data = self._create_entity_state_status_data('OPEN_CLOSE', [recent_response, past_response])
-
+
+ status_data = self._create_entity_state_status_data('OPEN_CLOSE', [latest_response, prior_response])
+
display_data = EntityStateDisplayData(status_data)
-
+
self.assertEqual(display_data.svg_status_style, StatusStyle.OpenPast)
@patch('hi.apps.common.datetimeproxy.now')
@@ -466,21 +485,22 @@ class TestEntityStateDisplayData(BaseTestCase):
"""Test OPEN_CLOSE state returns Closed beyond all thresholds."""
base_time = datetime(2023, 1, 1, 12, 0, 0)
mock_now.return_value = base_time
-
- # Was open 200 seconds ago (beyond 180 second threshold)
- recent_response = self._create_mock_sensor_response(
+
+ # Closed 200 seconds ago — beyond the 180s past threshold — so the
+ # decay has fully elapsed and it reads closed.
+ latest_response = self._create_mock_sensor_response(
str(EntityStateValue.CLOSED),
- base_time
+ base_time - timedelta(seconds=200)
)
- past_response = self._create_mock_sensor_response(
+ prior_response = self._create_mock_sensor_response(
str(EntityStateValue.OPEN),
- base_time - timedelta(seconds=200)
+ base_time - timedelta(seconds=600)
)
-
- status_data = self._create_entity_state_status_data('OPEN_CLOSE', [recent_response, past_response])
-
+
+ status_data = self._create_entity_state_status_data('OPEN_CLOSE', [latest_response, prior_response])
+
display_data = EntityStateDisplayData(status_data)
-
+
self.assertEqual(display_data.svg_status_style, StatusStyle.Closed)
# OPEN_CLOSE_POSITION State Type Tests (continuous-position cover)
@@ -617,7 +637,7 @@ class TestEntityStateDisplayData(BaseTestCase):
def test_unmapped_entity_type_returns_default_style(self):
"""Test unmapped entity types return default style with sensor value."""
sensor_response = self._create_mock_sensor_response('25.5')
- status_data = self._create_entity_state_status_data('TEMPERATURE', [sensor_response])
+ status_data = self._create_entity_state_status_data('HUMIDITY', [sensor_response])
with patch.object(StatusStyle, 'default') as mock_default:
expected_style = Mock()
@@ -638,7 +658,6 @@ class TestEntityStateDisplayData(BaseTestCase):
# Should return idle since no penultimate active state
self.assertEqual(display_data.svg_status_style, StatusStyle.MovementIdle)
self.assertIsNone(display_data.penultimate_sensor_value)
- self.assertIsNone(display_data.penultimate_sensor_timestamp)
# Property Access Tests
@@ -1032,3 +1051,70 @@ class TestToPollingUpdateDict(BaseTestCase):
self.assertNotIn( 'status', row )
self.assertNotIn( 'svg_style', row )
self.assertIn( 'display', row )
+
+
+class TestTemperatureStatusStyle(BaseTestCase):
+ """TEMPERATURE buckets the absolute reading onto a cold→pleasant→hot
+ color ramp. The reading is normalized to canonical °C first, so the
+ bucket thresholds hold regardless of the EntityState's stored units;
+ an unresolvable reading (no/unknown units, non-numeric) falls back to
+ the plain numeric status display."""
+
+ def setUp(self):
+ super().setUp()
+ self.entity = Entity.objects.create(
+ name = 'Test Entity',
+ entity_type_str = 'SENSOR',
+ )
+
+ def _make_display_data(self, value, units):
+ entity_state = EntityState.objects.create(
+ entity = self.entity,
+ entity_state_type_str = 'TEMPERATURE',
+ units = units,
+ )
+ response = Mock(spec=SensorResponse)
+ response.value = value
+ response.timestamp = datetime.now()
+ status_data = EntityStateStatusData(
+ entity_state = entity_state,
+ sensor_response_list = [ response ],
+ controller_data_list = [],
+ )
+ return EntityStateDisplayData( status_data )
+
+ def test_fahrenheit_buckets_span_cold_to_hot(self):
+ # °F readings normalize to °C before bucketing; comfortable room
+ # temperatures (68-75°F) land in the green "pleasant" band while
+ # only outdoor extremes reach the blue/red ends.
+ cases = [
+ ( '10', StatusStyle.TemperatureCold ),
+ ( '45', StatusStyle.TemperatureCool ),
+ ( '70', StatusStyle.TemperaturePleasant ),
+ ( '85', StatusStyle.TemperatureWarm ),
+ ( '95', StatusStyle.TemperatureHot ),
+ ]
+ for value, expected_style in cases:
+ with self.subTest( fahrenheit = value ):
+ display_data = self._make_display_data( value, '°F' )
+ self.assertEqual( display_data.svg_status_style, expected_style )
+
+ def test_celsius_uses_same_thresholds(self):
+ # The same canonical-°C thresholds apply when the state is
+ # already stored in °C (no indoor/outdoor distinction needed).
+ display_data = self._make_display_data( '21', '°C' )
+ self.assertEqual(
+ display_data.svg_status_style, StatusStyle.TemperaturePleasant,
+ )
+
+ def test_missing_units_falls_back_to_default_style(self):
+ # Without units the reading can't be placed on the scale, so the
+ # plain numeric status display is used (status == the value text).
+ display_data = self._make_display_data( '21', None )
+ self.assertEqual( display_data.svg_status_style.status_value, '21' )
+
+ def test_non_numeric_value_falls_back_to_default_style(self):
+ display_data = self._make_display_data( 'unavailable', '°F' )
+ self.assertEqual(
+ display_data.svg_status_style.status_value, 'unavailable',
+ )
diff --git a/src/hi/apps/sense/templatetags/sense_tags.py b/src/hi/apps/sense/templatetags/sense_tags.py
index a97aaee0..47639cb2 100644
--- a/src/hi/apps/sense/templatetags/sense_tags.py
+++ b/src/hi/apps/sense/templatetags/sense_tags.py
@@ -34,3 +34,21 @@ def render_state_value_text( context, entity_state : EntityState, value : str ):
flat[ 'entity_state' ] = entity_state
flat[ 'value' ] = value
return template_obj.render( flat )
+
+
+def state_value_status( entity_state : EntityState, value : str ) -> str:
+ """The CSS status token for a single EntityState value, via the same
+ dispatch the live display uses (``EntityStateDisplayData``), so a
+ bucketed type (TEMPERATURE, BATTERY, dimmer, position) colors the
+ same way it does on the SVG icon / status panels. Falls back to the
+ raw value when the dispatch yields no token (unrecognized value), so
+ callers can always render a ``status="..."`` attribute.
+
+ Imported lazily to keep the sense template tags free of a load-time
+ dependency on the monitor display layer."""
+ from hi.apps.monitor.display_data import EntityStateDisplayData
+ svg_status_style = EntityStateDisplayData.for_value( entity_state, value ).svg_status_style
+ if svg_status_style and svg_status_style.status_value:
+ return svg_status_style.status_value
+ return value
diff --git a/src/hi/apps/sense/tests/test_sense_tags.py b/src/hi/apps/sense/tests/test_sense_tags.py
index 474d4543..1a8f4767 100644
--- a/src/hi/apps/sense/tests/test_sense_tags.py
+++ b/src/hi/apps/sense/tests/test_sense_tags.py
@@ -52,3 +52,48 @@ class TestRenderStateValueText( BaseTestCase ):
# Default template renders through value_label filter for
# unit-less values — output is non-empty.
self.assertTrue( output )
+
+
+class TestStateValueStatus( BaseTestCase ):
+ """``state_value_status`` routes a single (history) value through the
+ same ``EntityStateDisplayData`` dispatch the live display uses, so a
+ bucketed numeric type colors the same way it does on the SVG icon /
+ status panels instead of emitting the raw value as the status token."""
+
+ def _render( self, entity_state, value ):
+ return Template(
+ '{% load sense_tags %}'
+ '{% state_value_status entity_state value %}'
+ ).render( Context({ 'entity_state': entity_state, 'value': value }) ).strip()
+
+ def test_bucketed_type_emits_dispatched_token_not_raw_value( self ):
+ # A TEMPERATURE reading's raw value ("72") is not its CSS token;
+ # the dispatch buckets it to the absolute-temperature band.
+ entity = Entity.objects.create(
+ name = 'Thermometer', entity_type_str = 'THERMOMETER',
+ )
+ state = EntityState.objects.create(
+ entity = entity, entity_state_type_str = 'TEMPERATURE', units = '°F',
+ )
+ self.assertEqual( self._render( state, '72' ), 'temperature_pleasant' )
+
+ def test_enum_type_token_matches_raw_value( self ):
+ entity = Entity.objects.create(
+ name = 'Switch', entity_type_str = 'WALL_SWITCH',
+ )
+ state = EntityState.objects.create(
+ entity = entity, entity_state_type_str = 'ON_OFF',
+ )
+ self.assertEqual( self._render( state, 'on' ), 'on' )
+
+ def test_unrecognized_value_falls_back_to_raw_value( self ):
+ # ON_OFF with an invalid value dispatches to no style; the tag
+ # falls back to the raw value so a status attribute is always
+ # renderable.
+ entity = Entity.objects.create(
+ name = 'Switch', entity_type_str = 'WALL_SWITCH',
+ )
+ state = EntityState.objects.create(
+ entity = entity, entity_state_type_str = 'ON_OFF',
+ )
+ self.assertEqual( self._render( state, 'bogus' ), 'bogus' )
diff --git a/src/hi/environment/client.py b/src/hi/environment/client.py
index 0e3347df..05edd5f1 100644
--- a/src/hi/environment/client.py
+++ b/src/hi/environment/client.py
@@ -11,14 +11,16 @@ class ClientConfig:
needed.
"""
- DEBUG : bool
- ENVIRONMENT : str
- VERSION : str
- VIEW_MODE : str
- VIEW_TYPE : str
- IS_EDIT_MODE : bool
- API_STATUS_URL : str = ''
- CONSOLE_UNLOCK_URL : str = ''
+ DEBUG : bool
+ ENVIRONMENT : str
+ VERSION : str
+ VIEW_MODE : str
+ VIEW_TYPE : str
+ IS_EDIT_MODE : bool
+ SVG_SNAP_GRID_PIXELS : int
+ API_STATUS_URL : str = ''
+ CONSOLE_UNLOCK_URL : str = ''
+ API_STATUS_POLLING_INTERVAL_MS : int = 3000
def to_json_dict(self) -> dict:
"""
diff --git a/src/hi/environment/context_processors.py b/src/hi/environment/context_processors.py
index a95174b0..0b93c891 100644
--- a/src/hi/environment/context_processors.py
+++ b/src/hi/environment/context_processors.py
@@ -1,6 +1,8 @@
from django.conf import settings
from django.urls import reverse
+from hi.apps.console.console_helper import ConsoleSettingsHelper
+
from .client import ClientConfig
@@ -24,8 +26,10 @@ def client_config(request):
VIEW_MODE = str(request.view_parameters.view_mode),
VIEW_TYPE = str(request.view_parameters.view_type) if request.view_parameters.view_type else None,
IS_EDIT_MODE = request.view_parameters.is_editing,
+ SVG_SNAP_GRID_PIXELS = request.view_parameters.svg_snap_grid_pixels,
API_STATUS_URL = reverse( 'api_status' ),
CONSOLE_UNLOCK_URL = reverse( 'console_unlock' ),
+ API_STATUS_POLLING_INTERVAL_MS = ConsoleSettingsHelper().get_status_polling_interval_ms(),
)
return {
diff --git a/src/hi/hi_async_view.py b/src/hi/hi_async_view.py
index a0d64029..90c8bc6f 100644
--- a/src/hi/hi_async_view.py
+++ b/src/hi/hi_async_view.py
@@ -98,7 +98,10 @@ class HiSideView( HiAsyncView ):
else:
del referrer_query_params[self.SIDE_URL_PARAM_NAME]
- updated_query_string = urllib.parse.urlencode( referrer_query_params )
+ # parse_qs returns list-valued params; doseq=True emits each value
+ # correctly (single-element lists become clean scalars) instead of
+ # str()'ing the list into "['value']".
+ updated_query_string = urllib.parse.urlencode( referrer_query_params, doseq = True )
return f"{referrer_url.path}?{updated_query_string}"
diff --git a/src/hi/hi_styles.py b/src/hi/hi_styles.py
index bde8e49a..1b19922f 100644
--- a/src/hi/hi_styles.py
+++ b/src/hi/hi_styles.py
@@ -826,6 +826,63 @@ class StatusStyle:
fill_opacity = 0.15,
)
+ # Temperature: a single absolute-temperature scale, bucketed into a
+ # blue (cold) -> green (pleasant) -> orange/red (hot) ramp. One scale
+ # serves both thermostats and outdoor thermometers because comfortable
+ # indoor temperatures naturally land in the green band while only the
+ # outdoors reaches the blue/red extremes — so the same reading always
+ # gets the same color, no indoor/outdoor distinction needed. The
+ # extremes also carry higher fill_opacity (more intense) than the
+ # subtle pleasant band, reinforcing "how far from comfortable" at a
+ # glance. Thresholds live in EntityStateDisplayData (in canonical °C);
+ # these are just the finite palette the CSS rules key off.
+ STATUS_TEMP_COLD_COLOR = '#2c7fb8' # blue
+ STATUS_TEMP_COOL_COLOR = '#74add1' # light blue
+ STATUS_TEMP_PLEASANT_COLOR = '#1a9850' # green
+ STATUS_TEMP_WARM_COLOR = '#fdae61' # orange
+ STATUS_TEMP_HOT_COLOR = '#d73027' # red
+
+ TemperatureCold = SvgStatusStyle(
+ status_value = 'temperature_cold',
+ stroke_color = STATUS_TEMP_COLD_COLOR,
+ stroke_width = DEFAULT_STROKE_WIDTH,
+ stroke_dasharray = DEFAULT_STROKE_DASHARRAY,
+ fill_color = STATUS_TEMP_COLD_COLOR,
+ fill_opacity = 0.5,
+ )
+ TemperatureCool = SvgStatusStyle(
+ status_value = 'temperature_cool',
+ stroke_color = STATUS_TEMP_COOL_COLOR,
+ stroke_width = DEFAULT_STROKE_WIDTH,
+ stroke_dasharray = DEFAULT_STROKE_DASHARRAY,
+ fill_color = STATUS_TEMP_COOL_COLOR,
+ fill_opacity = 0.35,
+ )
+ TemperaturePleasant = SvgStatusStyle(
+ status_value = 'temperature_pleasant',
+ stroke_color = STATUS_TEMP_PLEASANT_COLOR,
+ stroke_width = DEFAULT_STROKE_WIDTH,
+ stroke_dasharray = DEFAULT_STROKE_DASHARRAY,
+ fill_color = STATUS_TEMP_PLEASANT_COLOR,
+ fill_opacity = 0.2,
+ )
+ TemperatureWarm = SvgStatusStyle(
+ status_value = 'temperature_warm',
+ stroke_color = STATUS_TEMP_WARM_COLOR,
+ stroke_width = DEFAULT_STROKE_WIDTH,
+ stroke_dasharray = DEFAULT_STROKE_DASHARRAY,
+ fill_color = STATUS_TEMP_WARM_COLOR,
+ fill_opacity = 0.35,
+ )
+ TemperatureHot = SvgStatusStyle(
+ status_value = 'temperature_hot',
+ stroke_color = STATUS_TEMP_HOT_COLOR,
+ stroke_width = DEFAULT_STROKE_WIDTH,
+ stroke_dasharray = DEFAULT_STROKE_DASHARRAY,
+ fill_color = STATUS_TEMP_HOT_COLOR,
+ fill_opacity = 0.5,
+ )
+
@classmethod
def default( cls, status_value : str = DEFAULT_STATUS_VALUE ):
return SvgStatusStyle(
@@ -860,3 +917,21 @@ class StatusStyle:
fill_color = 'yellow',
fill_opacity = opacity,
)
+
+ # Upper bound (exclusive, in canonical °C) for each temperature bucket,
+ # paired with the style to use below that bound; the final entry is the
+ # open-ended "hot" catch-all. Bounds are chosen so human-comfortable
+ # readings (~19-24°C) land in the green "pleasant" band.
+ TEMPERATURE_BUCKETS_CELSIUS = [
+ ( 5.0, TemperatureCold ), # below freezing-ish / bitter
+ ( 16.0, TemperatureCool ), # chilly
+ ( 25.0, TemperaturePleasant ), # comfortable
+ ( 31.0, TemperatureWarm ), # warm
+ ]
+
+ @classmethod
+ def temperature( cls, celsius : float ):
+ for upper_bound_celsius, status_style in cls.TEMPERATURE_BUCKETS_CELSIUS:
+ if celsius < upper_bound_celsius:
+ return status_style
+ return cls.TemperatureHot
diff --git a/src/hi/integrations/templates/integrations/external_data/entity/structured.html b/src/hi/integrations/templates/integrations/external_data/entity/structured.html
index 99260979..f37ad038 100644
--- a/src/hi/integrations/templates/integrations/external_data/entity/structured.html
+++ b/src/hi/integrations/templates/integrations/external_data/entity/structured.html
@@ -1,4 +1,5 @@
{% load icons %}
+{% load attribute_extras %}
<div class="attr-v2-external-structured">
@@ -59,7 +60,7 @@
</div>
</div>
<div class="attr-v2-attribute-value">
- <div class="attr-ext-value attr-ext-value--clamped">{{ pair.value }}</div>
+ <div class="attr-ext-value attr-ext-value--clamped">{{ pair.value|attribute_text_linkify }}</div>
</div>
</div>
{% endfor %}
diff --git a/src/hi/settings/development.py b/src/hi/settings/development.py
index cd684483..bf1d77f9 100644
--- a/src/hi/settings/development.py
+++ b/src/hi/settings/development.py
@@ -159,6 +159,16 @@ SUPPRESS_MONITORS = False
# Allows injecting transient view data for testing auto-view functionality
DEBUG_FORCE_TRANSIENT_VIEW_OVERRIDE = False # Set to True to enable
+# Enables the simulator's Scenes "Clear States" action to make the status
+# display drop sensor responses older than its cutoff (avoids waiting out the
+# recent/past decay between sequence runs). Dev-only.
+DEBUG_FORCE_SENSOR_RESPONSE_CUTOFF = True
+# Shared cache key holding the "Clear States" cutoff epoch: the independent
+# simulator process writes it; the main app reads it (DevInjectionManager
+# .apply_sensor_response_cutoff). The *only* contract between the two processes
+# for this feature — both inherit it here, so neither imports the other's code.
+SENSOR_RESPONSE_CUTOFF_CACHE_KEY = 'hi.dev.sensor_response_cutoff'
+
# For testing UI error display of the various attribute editing form errors.
DEBUG_INJECT_ATTRIBUTE_FORM_ERRORS = False
diff --git a/src/hi/settings/simulator.py b/src/hi/settings/simulator.py
index 1b5f52a1..d30b3532 100644
--- a/src/hi/settings/simulator.py
+++ b/src/hi/settings/simulator.py
@@ -16,6 +16,8 @@ INSTALLED_APPS = [
'hi.simulator',
'hi.simulator.profile',
'hi.simulator.services',
+ 'hi.simulator.scenes',
+ 'hi.simulator.video_playback',
'hi.simulator.weather_sources',
'hi.simulator.settings',
'hi.simulator.services.frigate',
@@ -70,3 +72,20 @@ DATABASES = {
'NAME': os.path.join( ENV.DATABASES_NAME_PATH, 'simulator.sqlite3' ),
}
}
+
+
+# Well-known directory of pre-canned camera clips. Each immediate subdirectory
+# is a clip; its alphabetically-ordered ``*.jpg`` files are the frames. The
+# subdirectory names become the camera ``live_clip`` / ``event_clip`` choices
+# (scanned once at startup). Restart the simulator to pick up new clips.
+SIMULATOR_VIDEO_DIR = str( BASE_DIR.parent.parent / 'data' / 'demo' / 'videos' )
+
+
+# The LOGGING inherited from development wires a request-log suppression filter
+# for the *main app's* endpoints (whose URL names don't resolve in this
+# process). Swap in the simulator's own filter on the same console handler so
+# the simulator's frequently-polled integration / weather / status endpoints
+# stop flooding the dev console.
+LOGGING[ 'filters' ][ 'suppress_select_request_endpoints' ][ '()' ] = (
+ 'hi.simulator.log_filters.SuppressSimulatorPollingFilter'
+)
diff --git a/src/hi/simulator/log_filters.py b/src/hi/simulator/log_filters.py
new file mode 100644
index 00000000..c67f932f
--- /dev/null
+++ b/src/hi/simulator/log_filters.py
@@ -0,0 +1,63 @@
+"""Simulator-only logging filters.
+
+Kept separate from the main app's ``hi.testing.utils.log_filters`` because the
+noisy endpoints differ entirely: the simulator is polled by HI's integration
+and weather pollers plus the Scenes status poll, and those URL names only
+resolve against the simulator's urlconf. Wired in via
+``hi.settings.simulator``'s LOGGING override.
+"""
+import logging
+import re
+
+from django.conf import settings
+from django.urls import resolve
+
+
+class SuppressSimulatorPollingFilter( logging.Filter ):
+ """Drop ``django.server`` request logs for the simulator's frequently-polled
+ endpoints so they don't drown out everything else in the dev console.
+
+ Matches by URL name (resolved against the simulator urlconf), not hardcoded
+ paths, so route changes don't silently re-enable the noise. Gated on
+ ``settings.SUPPRESS_SELECT_REQUEST_ENPOINTS_LOGGING`` (shared toggle), and
+ fail-open: any parsing/resolution hiccup keeps the log line.
+ """
+
+ URL_NAMES_TO_SUPPRESS = {
+ # HI integration pollers (Home Assistant, ZoneMinder, Frigate states)
+ 'hass_api_states',
+ 'zm_api_events_index',
+ 'simulator_api_states',
+ # Weather-source pollers
+ 'simulator_weather_usno_api',
+ 'simulator_weather_sunrise_sunset_api',
+ 'simulator_weather_nws_observations',
+ 'simulator_weather_nws_points',
+ 'simulator_weather_nws_forecast_hourly',
+ 'simulator_weather_nws_alerts_active',
+ 'simulator_weather_openmeteo_forecast',
+ 'simulator_weather_openmeteo_archive',
+ # Simulator UI live polling
+ 'simulator_scene_status',
+ }
+
+ def filter( self, record ):
+ if not getattr( settings, 'SUPPRESS_SELECT_REQUEST_ENPOINTS_LOGGING', True ):
+ return True
+ try:
+ args = getattr( record, 'args', None )
+ if not args:
+ return True
+ request_line = args[ 0 ]
+ if not isinstance( request_line, str ):
+ # For request logs this is the "GET /path HTTP/1.1" string; other
+ # records (e.g. a PosixPath arg) are left alone.
+ return True
+ match = re.match( r'^[A-Z]+ (/[^ ?]*)', request_line )
+ if not match:
+ return True
+ if resolve( match.group( 1 )).url_name in self.URL_NAMES_TO_SUPPRESS:
+ return False
+ except Exception:
+ pass
+ return True
diff --git a/src/hi/simulator/scenes/__init__.py b/src/hi/simulator/scenes/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/simulator/scenes/apps.py b/src/hi/simulator/scenes/apps.py
new file mode 100644
index 00000000..ee90ed40
--- /dev/null
+++ b/src/hi/simulator/scenes/apps.py
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class ScenesConfig( AppConfig ):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'hi.simulator.scenes'
+ label = 'simulator_scenes'
diff --git a/src/hi/simulator/scenes/control_grid.py b/src/hi/simulator/scenes/control_grid.py
new file mode 100644
index 00000000..2eb188cd
--- /dev/null
+++ b/src/hi/simulator/scenes/control_grid.py
@@ -0,0 +1,61 @@
+"""The scene dashboard's curated state-control grid.
+
+Curated controls are stored by a re-seed-proof stable key
+(``module_key | entity_name | sim_state_id``) and resolved to the live
+(simulator, sim_state) at render time. This module owns that codec and
+resolution; no HTTP.
+"""
+from hi.simulator.services.service_simulator_manager import ServiceSimulatorManager
+
+
+def simulator_by_module():
+ return {
+ simulator_data.simulator.module_key: simulator_data.simulator
+ for simulator_data in ServiceSimulatorManager().get_simulator_data_list()
+ }
+
+
+def control_key( module_key, entity_name, sim_state_id ):
+ return f'{module_key}|{entity_name}|{sim_state_id}'
+
+
+def split_control_key( key ):
+ # module_key (dotted) and sim_state_id (slug) are '|'-free, so take
+ # them from the ends; entity_name (the middle) may contain '|'.
+ parts = key.split( '|' )
+ return parts[0], '|'.join( parts[1:-1] ), parts[-1]
+
+
+def resolve_control( control, simulator_by_module_map ):
+ """Resolve a SimSceneControl's stable key to the live (simulator,
+ sim_state); None if the entity/state isn't currently loaded."""
+ simulator = simulator_by_module_map.get( control.module_key )
+ if simulator is None:
+ return None
+ sim_entity = next(
+ ( e for e in simulator.sim_entities if e.name == control.entity_name ),
+ None,
+ )
+ if sim_entity is None:
+ return None
+ sim_state = next(
+ ( s for s in sim_entity.sim_state_list if s.sim_state_id == control.sim_state_id ),
+ None,
+ )
+ if sim_state is None:
+ return None
+ # The scenes grid shows the entity name in its own column, so drop a
+ # redundant leading "<entity> " from the state label (e.g. hass's
+ # "Front Door Motion" -> "Motion"). Labels without that prefix (frigate's
+ # "Detected Object") are left as-is.
+ entity_name = sim_entity.name
+ state_label = sim_state.name
+ prefix = f'{entity_name} '
+ if state_label.startswith( prefix ) and len( state_label ) > len( prefix ):
+ state_label = state_label[ len( prefix ): ]
+ return {
+ 'simulator': simulator,
+ 'sim_state': sim_state,
+ 'entity_name': entity_name,
+ 'state_label': state_label,
+ }
diff --git a/src/hi/simulator/scenes/initial_state.py b/src/hi/simulator/scenes/initial_state.py
new file mode 100644
index 00000000..6b106223
--- /dev/null
+++ b/src/hi/simulator/scenes/initial_state.py
@@ -0,0 +1,84 @@
+"""Per-Sequence initial-state snapshot — capture and apply.
+
+A Scene's profile bindings give each module a clean baseline on apply
+(``SceneController.apply``). That baseline is generic; for filming, each
+beat needs a tailored starting state on top of it (e.g. garage door
+already open, a light already on). The snapshot fills that gap: capture
+the current sim states as the selected Sequence's overlay, and apply it
+after the scene baseline whenever that sequence loads.
+
+Captures all currently-loaded states (simple, predictable; SimState
+already no-ops on unchanged values). Stored on ``SimStateSequence`` as
+``initial_state_json``, in the same dict shape as a ``steps_json`` entry
+without ``t``: ``{module, entity, state, value}``.
+"""
+import logging
+from typing import List
+
+from hi.simulator.services.service_simulator_manager import ServiceSimulatorManager
+
+logger = logging.getLogger(__name__)
+
+
+def capture_current_state() -> List[ dict ]:
+ """Snapshot every currently-loaded sim state across all modules.
+
+ Values are stringified so the overlay round-trips through the same
+ ``value_str`` path that recorded steps use."""
+ entries : List[ dict ] = []
+ for simulator_data in ServiceSimulatorManager().get_simulator_data_list():
+ simulator = simulator_data.simulator
+ for sim_entity in simulator.sim_entities:
+ for sim_state in sim_entity.sim_state_list:
+ entries.append({
+ 'module': simulator.module_key,
+ 'entity': sim_entity.name,
+ 'state': sim_state.sim_state_id,
+ 'value': '' if sim_state.value is None else str( sim_state.value ),
+ })
+ continue
+ continue
+ continue
+ return entries
+
+
+def apply_initial_state( initial_state_json : List[ dict ] ) -> List[ dict ]:
+ """Apply each entry via the simulator's ``set_sim_state``. Returns a
+ miss list (same shape as ``SimPlayer``'s misses) for entries whose
+ module/entity/state isn't currently loaded — surfaced via the
+ player's status when called from playback."""
+ if not initial_state_json:
+ return []
+ simulator_by_module = {
+ data.simulator.module_key: data.simulator
+ for data in ServiceSimulatorManager().get_simulator_data_list()
+ }
+ misses : List[ dict ] = []
+ for entry in initial_state_json:
+ module_key = entry.get( 'module' )
+ entity_name = entry.get( 'entity' )
+ sim_state_id = entry.get( 'state' )
+ value_str = entry.get( 'value' )
+ simulator = simulator_by_module.get( module_key )
+ sim_entity = None
+ if simulator is not None:
+ sim_entity = next(
+ ( e for e in simulator.sim_entities if e.name == entity_name ),
+ None,
+ )
+ if simulator is None or sim_entity is None:
+ misses.append({ 'module': module_key, 'entity': entity_name, 'state': sim_state_id })
+ continue
+ try:
+ simulator.set_sim_state(
+ sim_entity_id = sim_entity.id,
+ sim_state_id = sim_state_id,
+ value_str = value_str,
+ )
+ except Exception:
+ logger.exception(
+ f'apply_initial_state: failed {module_key}/{entity_name}/{sim_state_id}'
+ )
+ misses.append({ 'module': module_key, 'entity': entity_name, 'state': sim_state_id })
+ continue
+ return misses
diff --git a/src/hi/simulator/scenes/migrations/0001_initial.py b/src/hi/simulator/scenes/migrations/0001_initial.py
new file mode 100644
index 00000000..4361a6c9
--- /dev/null
+++ b/src/hi/simulator/scenes/migrations/0001_initial.py
@@ -0,0 +1,168 @@
+# Generated by Django 5.2.14 on 2026-06-05 14:02
+
+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="SimScene",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "name",
+ models.CharField(
+ max_length=64, unique=True, verbose_name="Scene Name"
+ ),
+ ),
+ (
+ "description",
+ models.TextField(blank=True, null=True, verbose_name="Description"),
+ ),
+ (
+ "created_datetime",
+ models.DateTimeField(auto_now_add=True, verbose_name="Created"),
+ ),
+ ],
+ options={
+ "ordering": ["name"],
+ },
+ ),
+ migrations.CreateModel(
+ name="SimSceneBinding",
+ 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"),
+ ),
+ (
+ "profile",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ to="simulator_profile.simprofile",
+ verbose_name="Profile",
+ ),
+ ),
+ (
+ "scene",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="bindings",
+ to="simulator_scenes.simscene",
+ verbose_name="Scene",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ["module_key"],
+ "unique_together": {("scene", "module_key")},
+ },
+ ),
+ migrations.CreateModel(
+ name="SimSceneControl",
+ 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"),
+ ),
+ (
+ "entity_name",
+ models.CharField(max_length=128, verbose_name="Entity Name"),
+ ),
+ (
+ "sim_state_id",
+ models.CharField(max_length=128, verbose_name="Sim State Id"),
+ ),
+ (
+ "order_id",
+ models.PositiveIntegerField(default=0, verbose_name="Order"),
+ ),
+ (
+ "scene",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="controls",
+ to="simulator_scenes.simscene",
+ verbose_name="Scene",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ["order_id", "module_key", "entity_name"],
+ "unique_together": {
+ ("scene", "module_key", "entity_name", "sim_state_id")
+ },
+ },
+ ),
+ migrations.CreateModel(
+ name="SimStateSequence",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("name", models.CharField(max_length=128, verbose_name="Name")),
+ ("steps_json", models.JSONField(default=list, verbose_name="Steps")),
+ (
+ "created_datetime",
+ models.DateTimeField(auto_now_add=True, verbose_name="Created"),
+ ),
+ (
+ "updated_datetime",
+ models.DateTimeField(auto_now=True, verbose_name="Updated"),
+ ),
+ (
+ "scene",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="state_sequences",
+ to="simulator_scenes.simscene",
+ verbose_name="Scene",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ["scene", "-updated_datetime"],
+ "unique_together": {("scene", "name")},
+ },
+ ),
+ ]
diff --git a/src/hi/simulator/scenes/migrations/0002_simstatesequence_initial_state_json.py b/src/hi/simulator/scenes/migrations/0002_simstatesequence_initial_state_json.py
new file mode 100644
index 00000000..0b99f027
--- /dev/null
+++ b/src/hi/simulator/scenes/migrations/0002_simstatesequence_initial_state_json.py
@@ -0,0 +1,18 @@
+# Generated by Django 5.2.14 on 2026-06-07 00:45
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("simulator_scenes", "0001_initial"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="simstatesequence",
+ name="initial_state_json",
+ field=models.JSONField(default=list, verbose_name="Initial State"),
+ ),
+ ]
diff --git a/src/hi/simulator/scenes/migrations/__init__.py b/src/hi/simulator/scenes/migrations/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/simulator/scenes/models.py b/src/hi/simulator/scenes/models.py
new file mode 100644
index 00000000..99998806
--- /dev/null
+++ b/src/hi/simulator/scenes/models.py
@@ -0,0 +1,140 @@
+from django.db import models
+
+from hi.simulator.profile.models import SimProfile
+
+
+class SimScene( models.Model ):
+ """A named, reusable demo setup: the per-module profile combination to
+ apply, plus an operator-curated subset of state controls to surface on
+ the Scenes dashboard. State changes are captured/replayed within a
+ scene as SimStateSequence rows.
+ """
+
+ name = models.CharField(
+ 'Scene Name',
+ max_length = 64,
+ unique = True,
+ )
+ description = models.TextField(
+ 'Description',
+ null = True, blank = True,
+ )
+ created_datetime = models.DateTimeField(
+ 'Created',
+ auto_now_add = True,
+ )
+
+ class Meta:
+ ordering = [ 'name' ]
+
+ def __str__(self):
+ return self.name
+
+
+class SimSceneBinding( models.Model ):
+ """Which SimProfile a given module uses when this scene is applied.
+ Modules with no binding are left under individual control ("Off"
+ behavior per module).
+ """
+
+ scene = models.ForeignKey(
+ SimScene,
+ verbose_name = 'Scene',
+ related_name = 'bindings',
+ on_delete = models.CASCADE,
+ )
+ module_key = models.CharField(
+ 'Module Key',
+ max_length = 96,
+ )
+ profile = models.ForeignKey(
+ SimProfile,
+ verbose_name = 'Profile',
+ on_delete = models.CASCADE,
+ )
+
+ class Meta:
+ unique_together = ( 'scene', 'module_key' )
+ ordering = [ 'module_key' ]
+
+ def __str__(self):
+ return f'{self.scene.name}: [{self.module_key}] -> {self.profile.name}'
+
+
+class SimSceneControl( models.Model ):
+ """An operator-curated state control surfaced on the scene's dashboard.
+ Referenced by stable key (module_key / entity_name / sim_state_id) so
+ the curated set survives profile re-seeds; resolved to the live
+ SimState at render time.
+ """
+
+ scene = models.ForeignKey(
+ SimScene,
+ verbose_name = 'Scene',
+ related_name = 'controls',
+ on_delete = models.CASCADE,
+ )
+ module_key = models.CharField(
+ 'Module Key',
+ max_length = 96,
+ )
+ entity_name = models.CharField(
+ 'Entity Name',
+ max_length = 128,
+ )
+ sim_state_id = models.CharField(
+ 'Sim State Id',
+ max_length = 128,
+ )
+ order_id = models.PositiveIntegerField(
+ 'Order',
+ default = 0,
+ )
+
+ class Meta:
+ unique_together = ( 'scene', 'module_key', 'entity_name', 'sim_state_id' )
+ ordering = [ 'order_id', 'module_key', 'entity_name' ]
+
+ def __str__(self):
+ return f'{self.scene.name}: [{self.module_key}] {self.entity_name}.{self.sim_state_id}'
+
+
+class SimStateSequence( models.Model ):
+ """A captured, replayable sequence of operator state changes (with
+ optional markers) within a scene. Steps reference entities by stable
+ key and are stored as a JSON list; played back server-side.
+ """
+
+ scene = models.ForeignKey(
+ SimScene,
+ verbose_name = 'Scene',
+ related_name = 'state_sequences',
+ on_delete = models.CASCADE,
+ )
+ name = models.CharField(
+ 'Name',
+ max_length = 128,
+ )
+ steps_json = models.JSONField(
+ 'Steps',
+ default = list,
+ )
+ initial_state_json = models.JSONField(
+ 'Initial State',
+ default = list,
+ )
+ created_datetime = models.DateTimeField(
+ 'Created',
+ auto_now_add = True,
+ )
+ updated_datetime = models.DateTimeField(
+ 'Updated',
+ auto_now = True,
+ )
+
+ class Meta:
+ unique_together = ( 'scene', 'name' )
+ ordering = [ 'scene', '-updated_datetime' ]
+
+ def __str__(self):
+ return f'{self.scene.name}: {self.name}'
diff --git a/src/hi/simulator/scenes/player.py b/src/hi/simulator/scenes/player.py
new file mode 100644
index 00000000..25ec8a62
--- /dev/null
+++ b/src/hi/simulator/scenes/player.py
@@ -0,0 +1,341 @@
+"""Server-side playback of a SimStateSequence.
+
+Singleton. A sequence is *loaded* (its scene baseline applied, playhead at
+0) on first PLAY/STEP/SEEK, and a persistent playhead lets the filming
+controls drive it across requests:
+
+- ``play`` — run continuously from the playhead to the end.
+- ``step`` — run to the next marker (or end), then auto-pause.
+- ``pause`` — interrupt the run, leaving the playhead in place.
+- ``seek`` — re-apply the baseline, fold steps ``t <= T`` instantly, pause at T.
+- ``mark`` — insert a marker at the playhead (paused only); persists to the sequence.
+- ``stop`` — halt and rewind the playhead to the start.
+
+The timed walk runs on a daemon thread; ``pause``/``seek``/``stop`` cancel it
+via an event. Steps resolve ``(module, name, state_id)`` -> live entity ->
+``simulator.set_sim_state``; unresolved steps land in a miss-log surfaced via
+status.
+"""
+import logging
+import threading
+import time
+from typing import List, Optional
+
+from django import db
+
+from hi.apps.common.singleton import Singleton
+from hi.simulator.services.service_simulator_manager import ServiceSimulatorManager
+
+from .initial_state import apply_initial_state
+from .models import SimStateSequence
+from .scene_controller import SceneController
+
+logger = logging.getLogger(__name__)
+
+
+class SimPlayer( Singleton ):
+
+ def __init_singleton__(self):
+ self._lock = threading.Lock()
+ self._thread : Optional[ threading.Thread ] = None
+ self._cancel_event = threading.Event()
+ self._reset_locked()
+ return
+
+ def _reset_locked( self ):
+ # caller holds self._lock (or single-threaded init)
+ self._sequence_id : Optional[ int ] = None
+ self._sequence_name : Optional[ str ] = None
+ self._steps : List[ dict ] = []
+ self._index = 0
+ self._playhead_t = 0.0
+ self._total = 0.0
+ self._mode = 'idle' # idle | paused | playing | stepping
+ self._misses : List[ dict ] = []
+ # Wall-clock anchor for the continuous playhead during PLAY: the
+ # reported position is _clock_base_t + (now - _clock_base_monotonic),
+ # so the playhead glides through inter-event gaps instead of snapping
+ # to applied steps.
+ self._clock_base_t = 0.0
+ self._clock_base_monotonic : Optional[ float ] = None
+ return
+
+ def _live_playhead_locked( self ) -> float:
+ """The continuous wall-clock position; falls back to the discrete
+ playhead when no clock anchor is set. While stepping it is bounded by
+ the next marker (the segment's stop point) rather than the full
+ duration, so the cursor never runs past the mark. Caller holds the lock."""
+ if self._clock_base_monotonic is None:
+ return self._playhead_t
+ live = self._clock_base_t + ( time.monotonic() - self._clock_base_monotonic )
+ ceiling = self._next_marker_t_locked() if self._mode == 'stepping' else self._total
+ return round( min( ceiling, max( 0.0, live )), 3 )
+
+ def _next_marker_t_locked( self ) -> float:
+ """t of the next marker at/after the playhead — STEP's stop point; the
+ full duration if none remain. Caller holds the lock."""
+ for step in self._steps[ self._index : ]:
+ if 'marker' in step:
+ return float( step[ 't' ] ) if 't' in step else self._total
+ return self._total
+
+ # ----- status -----
+
+ def is_playing( self ) -> bool:
+ with self._lock:
+ return self._mode in ( 'playing', 'stepping' )
+
+ def get_status( self ) -> dict:
+ with self._lock:
+ # PLAY and STEP both report a live wall-clock position (the thread
+ # waits real t-deltas in either mode); paused/idle hold the frozen
+ # position. Reporting discrete here while the client interpolates
+ # makes the cursor jitter (snap back each poll), so they must agree.
+ playhead = (
+ self._live_playhead_locked() if self._mode in ( 'playing', 'stepping' )
+ else self._playhead_t
+ )
+ # Ceiling for the client's interpolation: the next marker while
+ # stepping (so it stops on the mark), else the full duration.
+ playhead_limit = (
+ self._next_marker_t_locked() if self._mode == 'stepping'
+ else self._total
+ )
+ return {
+ 'mode': self._mode,
+ 'playing': self._mode in ( 'playing', 'stepping' ),
+ 'paused': self._mode == 'paused',
+ 'loaded': self._sequence_id is not None,
+ 'sequence_id': self._sequence_id,
+ 'sequence_name': self._sequence_name,
+ 'playhead': playhead,
+ 'playhead_limit': round( playhead_limit, 3 ),
+ 'total': self._total,
+ 'step_index': self._index,
+ 'step_count': len( self._steps ),
+ 'next_marker': self._next_marker_locked(),
+ 'misses': list( self._misses ),
+ }
+
+ def _next_marker_locked( self ):
+ for step in self._steps[ self._index : ]:
+ if 'marker' in step:
+ return step[ 'marker' ]
+ return None
+
+ # ----- transport commands -----
+
+ def play( self, sequence : SimStateSequence ):
+ self._cancel_and_join()
+ if self._load_if_needed( sequence ):
+ SceneController().apply( sequence.scene )
+ self._apply_initial_state_locked( sequence )
+ self._start_thread( stepping = False )
+ return
+
+ def step( self, sequence : SimStateSequence ):
+ self._cancel_and_join()
+ if self._load_if_needed( sequence ):
+ SceneController().apply( sequence.scene )
+ self._apply_initial_state_locked( sequence )
+ self._start_thread( stepping = True )
+ return
+
+ def pause( self ):
+ self._cancel_and_join()
+ with self._lock:
+ if self._sequence_id is not None:
+ # Freeze at the true wall-clock position, not the last applied
+ # event — so pausing mid-gap holds where you actually paused.
+ if self._mode in ( 'playing', 'stepping' ):
+ self._playhead_t = self._live_playhead_locked()
+ self._mode = 'paused'
+ self._clock_base_monotonic = None
+ return
+
+ def stop( self ):
+ self._cancel_and_join()
+ with self._lock:
+ self._index = 0
+ self._playhead_t = 0.0
+ self._mode = 'idle'
+ return
+
+ def seek( self, sequence : SimStateSequence, t : float ):
+ self._cancel_and_join()
+ self._load_if_needed( sequence )
+ # Seeking (incl. backward) always rebuilds from the baseline.
+ SceneController().apply( sequence.scene )
+ self._apply_initial_state_locked( sequence )
+ simulator_by_module = self._simulator_by_module()
+ misses : List[ dict ] = []
+ with self._lock:
+ steps = list( self._steps )
+ index = len( steps )
+ for i, step in enumerate( steps ):
+ if 't' in step and float( step[ 't' ] ) > t:
+ index = i
+ break
+ if 'marker' not in step and not step.get( 'end' ):
+ self._apply_step( step, simulator_by_module, misses )
+ continue
+ with self._lock:
+ self._index = index
+ self._playhead_t = t
+ self._mode = 'paused'
+ self._misses = misses
+ db.close_old_connections()
+ return
+
+ def mark( self, name = None ) -> bool:
+ """Insert a timestamped marker at the playhead (paused only) and persist it."""
+ with self._lock:
+ if self._mode != 'paused' or self._sequence_id is None:
+ return False
+ self._steps.insert( self._index, {
+ 'marker': ( name or '' ).strip() or 'mark',
+ 't': round( self._playhead_t, 3 ),
+ })
+ self._index += 1 # marker now sits behind the playhead
+ steps_copy = list( self._steps )
+ sequence_id = self._sequence_id
+ SimStateSequence.objects.filter( id = sequence_id ).update( steps_json = steps_copy )
+ return True
+
+ # ----- internals -----
+
+ def _load_if_needed( self, sequence : SimStateSequence ) -> bool:
+ """Load the sequence unless it's the same one and merely paused
+ mid-way (in which case we resume). Returns True if (re)loaded."""
+ with self._lock:
+ if sequence.id == self._sequence_id and self._mode == 'paused':
+ return False
+ self._sequence_id = sequence.id
+ self._sequence_name = sequence.name
+ self._steps = list( sequence.steps_json or [] )
+ self._index = 0
+ self._playhead_t = 0.0
+ self._total = max(
+ ( float( s[ 't' ] ) for s in self._steps if 't' in s ), default = 0.0,
+ )
+ self._misses = []
+ self._mode = 'paused'
+ return True
+
+ def _start_thread( self, stepping : bool ):
+ self._cancel_event = threading.Event()
+ with self._lock:
+ if self._index >= len( self._steps ):
+ self._mode = 'idle'
+ return
+ self._mode = 'stepping' if stepping else 'playing'
+ # Anchor the wall clock at the current playhead so the live
+ # position advances from here (the thread waits real t-deltas).
+ self._clock_base_t = self._playhead_t
+ self._clock_base_monotonic = time.monotonic()
+ self._thread = threading.Thread(
+ target = self._run,
+ args = ( stepping, ),
+ name = 'SimPlayer',
+ daemon = True,
+ )
+ self._thread.start()
+ return
+
+ def _cancel_and_join( self ):
+ self._cancel_event.set()
+ thread = self._thread
+ if ( thread is not None and thread.is_alive()
+ and thread is not threading.current_thread() ):
+ thread.join( timeout = 2.0 )
+ self._thread = None
+ return
+
+ def _run( self, stepping : bool ):
+ simulator_by_module = self._simulator_by_module()
+ misses : List[ dict ] = []
+ reached_marker = False
+ try:
+ while not self._cancel_event.is_set():
+ with self._lock:
+ index = self._index
+ steps = self._steps
+ prev_t = self._playhead_t
+ if index >= len( steps ):
+ break
+ step = steps[ index ]
+ # Uniform timed walk: wait this step's t-delta, then act by
+ # kind. State changes apply; the end sentinel just advances
+ # (its wait is the trailing time); markers are STEP cue stops.
+ step_t = float( step.get( 't', prev_t ))
+ delay = step_t - prev_t
+ if delay > 0 and self._cancel_event.wait( timeout = delay ):
+ break # cancelled mid-wait; leave playhead/index for resume
+ is_marker = 'marker' in step
+ if not is_marker and not step.get( 'end' ):
+ self._apply_step( step, simulator_by_module, misses )
+ with self._lock:
+ self._index = index + 1
+ self._playhead_t = step_t
+ if is_marker and stepping:
+ reached_marker = True
+ break
+ continue
+ except Exception:
+ logger.exception( 'SimPlayer run failed' )
+ finally:
+ with self._lock:
+ self._misses = misses
+ if not self._cancel_event.is_set():
+ if reached_marker:
+ self._mode = 'paused'
+ else:
+ self._mode = 'idle'
+ self._index = len( self._steps )
+ self._playhead_t = self._total
+ db.close_old_connections()
+ return
+
+ def _simulator_by_module( self ):
+ return {
+ data.simulator.module_key: data.simulator
+ for data in ServiceSimulatorManager().get_simulator_data_list()
+ }
+
+ def _apply_initial_state_locked( self, sequence : SimStateSequence ):
+ """Overlay the sequence's captured initial state onto the just-applied
+ scene baseline. Misses (unloaded entities) are merged into the player's
+ miss list so the transport surfaces them like step misses."""
+ misses = apply_initial_state( sequence.initial_state_json or [] )
+ if misses:
+ with self._lock:
+ self._misses.extend( misses )
+ return
+
+ def _apply_step( self, step, simulator_by_module, misses ):
+ module_key = step.get( 'module' )
+ entity_name = step.get( 'entity' )
+ sim_state_id = step.get( 'state' )
+ value_str = step.get( 'value' )
+ simulator = simulator_by_module.get( module_key )
+ sim_entity = None
+ if simulator is not None:
+ sim_entity = next(
+ ( e for e in simulator.sim_entities if e.name == entity_name ),
+ None,
+ )
+ if simulator is None or sim_entity is None:
+ misses.append({ 'module': module_key, 'entity': entity_name, 'state': sim_state_id })
+ return
+ try:
+ simulator.set_sim_state(
+ sim_entity_id = sim_entity.id,
+ sim_state_id = sim_state_id,
+ value_str = value_str,
+ )
+ except Exception:
+ logger.exception(
+ f'SimPlayer: failed to apply {module_key}/{entity_name}/{sim_state_id}'
+ )
+ misses.append({ 'module': module_key, 'entity': entity_name, 'state': sim_state_id })
+ return
diff --git a/src/hi/simulator/scenes/recorder.py b/src/hi/simulator/scenes/recorder.py
new file mode 100644
index 00000000..0fe25f97
--- /dev/null
+++ b/src/hi/simulator/scenes/recorder.py
@@ -0,0 +1,175 @@
+"""Operator state-change capture for the simulator.
+
+Singleton. While recording, the ``SimStateSetView`` hook appends a step
+per operator state change with an active-time ``t`` (seconds since
+start). ``stop()`` finalizes the captured steps into a *working* sequence
+held in memory; ``save()`` persists it as a ``SimStateSequence`` under
+the scene being recorded.
+
+Capture is operator-only: it runs in the HTTP set-state path. Playback
+(SimPlayer) applies state via the simulator method directly, bypassing
+that path, so playback is never self-captured.
+"""
+import logging
+import threading
+import time
+from typing import List, Optional
+
+from hi.apps.common.singleton import Singleton
+
+from .models import SimScene, SimStateSequence
+
+logger = logging.getLogger(__name__)
+
+
+class SimRecorder( Singleton ):
+
+ def __init_singleton__(self):
+ self._lock = threading.Lock()
+ self._recording = False
+ self._paused = False
+ self._scene_id : Optional[ int ] = None
+ # Pause-aware clock: active (unpaused) seconds = accumulated + (now -
+ # resumed_at) while running, frozen at accumulated while paused. This
+ # excludes staging "dead time" from step timestamps.
+ self._accumulated : float = 0.0
+ self._resumed_at : Optional[ float ] = None
+ self._steps : List[ dict ] = []
+ # Finalized-but-unsaved steps after stop(), until save()/discard().
+ self._working_steps : Optional[ List[ dict ] ] = None
+ self._working_scene_id : Optional[ int ] = None
+ return
+
+ def is_recording( self ) -> bool:
+ return self._recording
+
+ def is_paused( self ) -> bool:
+ return self._recording and self._paused
+
+ def start( self, scene : SimScene ):
+ with self._lock:
+ self._recording = True
+ self._paused = False
+ self._scene_id = scene.id
+ self._accumulated = 0.0
+ self._resumed_at = time.monotonic()
+ self._steps = []
+ self._working_steps = None
+ self._working_scene_id = None
+ return
+
+ def _active_t_locked( self ) -> float:
+ # caller holds self._lock
+ if self._paused or self._resumed_at is None:
+ return round( self._accumulated, 3 )
+ return round( self._accumulated + ( time.monotonic() - self._resumed_at ), 3 )
+
+ def toggle_pause( self ):
+ """PAUSE while recording stops the clock; pressing it again resumes."""
+ with self._lock:
+ if not self._recording:
+ return
+ if self._paused:
+ self._resumed_at = time.monotonic()
+ self._paused = False
+ else:
+ self._accumulated += time.monotonic() - self._resumed_at
+ self._paused = True
+ return
+
+ def mark( self, name = None ) -> bool:
+ """Insert a timestamped marker at the current position; allowed only
+ while paused (so it stamps the frozen pause time)."""
+ with self._lock:
+ if not self._recording or not self._paused:
+ return False
+ self._steps.append({
+ 'marker': ( name or '' ).strip() or 'mark',
+ 't': self._active_t_locked(),
+ })
+ return True
+
+ def record_step( self, module_key, entity_name, sim_state_id, value_str ):
+ with self._lock:
+ if not self._recording:
+ return
+ t = self._active_t_locked()
+ self._steps.append({
+ 't': t,
+ 'module': module_key,
+ 'entity': entity_name,
+ 'state': sim_state_id,
+ 'value': value_str,
+ })
+ return
+
+ def stop( self ):
+ with self._lock:
+ if not self._recording:
+ return
+ # Append an end sentinel at the true stop time. It carries no
+ # state but participates in playback (the player waits out its t),
+ # so trailing time is preserved and an empty recording still has a
+ # span. Start is implicit at t=0 — no start sentinel.
+ self._steps.append({ 't': self._active_t_locked(), 'end': True })
+ self._recording = False
+ self._paused = False
+ self._working_steps = self._steps
+ self._working_scene_id = self._scene_id
+ self._steps = []
+ return
+
+ def discard( self ):
+ with self._lock:
+ self._working_steps = None
+ self._working_scene_id = None
+ return
+
+ def save( self, name : Optional[ str ] = None ) -> Optional[ SimStateSequence ]:
+ with self._lock:
+ steps = self._working_steps
+ scene_id = self._working_scene_id
+ if steps is None or scene_id is None:
+ return None
+ try:
+ scene = SimScene.objects.get( id = scene_id )
+ except SimScene.DoesNotExist:
+ self.discard()
+ return None
+ name = ( name or '' ).strip() or self._auto_name( scene )
+ name = self._unique_name( scene, name )
+ sequence = SimStateSequence.objects.create(
+ scene = scene,
+ name = name,
+ steps_json = steps,
+ )
+ self.discard()
+ return sequence
+
+ def get_status( self ) -> dict:
+ with self._lock:
+ return {
+ 'recording': self._recording,
+ 'paused': self._recording and self._paused,
+ 'scene_id': self._scene_id if self._recording else None,
+ 'step_count': len( self._steps ),
+ 'has_working': self._working_steps is not None,
+ 'working_step_count': len( self._working_steps ) if self._working_steps else 0,
+ 'working_scene_id': self._working_scene_id,
+ }
+
+ def _auto_name( self, scene : SimScene ) -> str:
+ return f'Sequence {scene.state_sequences.count() + 1}'
+
+ def _unique_name( self, scene : SimScene, name : str ) -> str:
+ """Append a numeric suffix when the name is already used in the scene,
+ so a save never collides with the (scene, name) unique constraint (a
+ duplicate name previously raised IntegrityError). Quick capture action
+ — uniquify rather than block; the operator can rename afterward."""
+ if not scene.state_sequences.filter( name = name ).exists():
+ return name
+ index = 2
+ while scene.state_sequences.filter( name = f'{name} ({index})' ).exists():
+ index += 1
+ continue
+ return f'{name} ({index})'
diff --git a/src/hi/simulator/scenes/scene_controller.py b/src/hi/simulator/scenes/scene_controller.py
new file mode 100644
index 00000000..4aecb771
--- /dev/null
+++ b/src/hi/simulator/scenes/scene_controller.py
@@ -0,0 +1,70 @@
+"""Active-scene orchestration for the simulator.
+
+A ``SimScene`` names a per-module profile combination. Applying it drives
+each bound module's ``ProfileManager`` to the scene's chosen profile,
+which rehydrates that module's entities to a clean baseline. Modules with
+no binding are left under individual control. "Off" is the absence of an
+active scene (apply nothing; leave per-module control).
+
+Singleton: the active scene is process-local session state (lost on
+simulator restart, which is fine — the operator re-applies).
+"""
+import logging
+import threading
+from typing import Optional
+
+from hi.apps.common.singleton import Singleton
+from hi.simulator.profile.profile_manager import ProfileManager
+
+from .models import SimScene
+
+logger = logging.getLogger(__name__)
+
+
+class SceneController( Singleton ):
+
+ def __init_singleton__(self):
+ self._active_scene_id : Optional[ int ] = None
+ self._lock = threading.Lock()
+ return
+
+ def apply( self, scene : SimScene ):
+ """Switch each bound module to its profile (rehydrating that
+ module's entities to a clean baseline). A single bad binding is
+ logged and skipped rather than aborting the whole scene."""
+ profile_manager = ProfileManager()
+ for binding in scene.bindings.select_related( 'profile' ).all():
+ try:
+ profile_manager.set_current(
+ module_key = binding.module_key,
+ profile = binding.profile,
+ )
+ except Exception:
+ logger.exception(
+ f'Scene {scene.name!r}: failed to apply binding'
+ f' {binding.module_key!r} -> profile {binding.profile_id}'
+ )
+ continue
+ with self._lock:
+ self._active_scene_id = scene.id
+ logger.info( f'Applied scene: {scene.name!r}' )
+ return
+
+ def clear( self ):
+ """"Off": stop enforcing a scene. Leaves each module on its current
+ profile under individual control (no profile changes)."""
+ with self._lock:
+ self._active_scene_id = None
+ return
+
+ def get_active_scene( self ) -> Optional[ SimScene ]:
+ with self._lock:
+ scene_id = self._active_scene_id
+ if scene_id is None:
+ return None
+ try:
+ return SimScene.objects.get( id = scene_id )
+ except SimScene.DoesNotExist:
+ with self._lock:
+ self._active_scene_id = None
+ return None
diff --git a/src/hi/simulator/scenes/sequence_io.py b/src/hi/simulator/scenes/sequence_io.py
new file mode 100644
index 00000000..3aac50c7
--- /dev/null
+++ b/src/hi/simulator/scenes/sequence_io.py
@@ -0,0 +1,62 @@
+"""Sequence step-JSON validation and export naming.
+
+Shared by the edit / import (validate ``steps_json``) and export (filename)
+sequence endpoints. No HTTP.
+"""
+import json
+import re
+
+
+def parse_steps( raw ):
+ """Validate edited/imported sequence JSON. Accepts either a bare list of
+ steps or an export envelope ({name, steps}); returns (steps, error)."""
+ try:
+ data = json.loads( raw )
+ except ( ValueError, TypeError ):
+ return None, 'Not valid JSON.'
+ if isinstance( data, dict ) and 'steps' in data:
+ data = data[ 'steps' ]
+ if not isinstance( data, list ):
+ return None, 'Expected a JSON list of steps.'
+ cleaned = []
+ for index, step in enumerate( data ):
+ if not isinstance( step, dict ):
+ return None, f'Step {index} is not an object.'
+ if step.get( 'end' ):
+ if 't' not in step:
+ return None, f'Step {index} (end) is missing "t".'
+ try:
+ cleaned.append({ 't': float( step[ 't' ] ), 'end': True })
+ except ( TypeError, ValueError ):
+ return None, f'Step {index} (end) has a non-numeric "t".'
+ continue
+ if 'marker' in step:
+ marker = { 'marker': str( step[ 'marker' ] ) }
+ if 't' in step:
+ try:
+ marker[ 't' ] = float( step[ 't' ] )
+ except ( TypeError, ValueError ):
+ return None, f'Marker {index} has a non-numeric "t".'
+ cleaned.append( marker )
+ continue
+ missing = [ k for k in ( 't', 'module', 'entity', 'state' ) if k not in step ]
+ if missing:
+ return None, f'Step {index} is missing field(s): {", ".join( missing )}.'
+ try:
+ t = float( step[ 't' ] )
+ except ( TypeError, ValueError ):
+ return None, f'Step {index} has a non-numeric "t".'
+ cleaned.append({
+ 't': t,
+ 'module': str( step[ 'module' ] ),
+ 'entity': str( step[ 'entity' ] ),
+ 'state': str( step[ 'state' ] ),
+ 'value': step.get( 'value' ),
+ })
+ continue
+ return cleaned, None
+
+
+def safe_filename( name ):
+ slug = re.sub( r'[^A-Za-z0-9._-]+', '_', name.strip() ).strip( '_' )
+ return slug or 'sequence'
diff --git a/src/hi/simulator/scenes/templates/scenes/modals/clear_states_confirm.html b/src/hi/simulator/scenes/templates/scenes/modals/clear_states_confirm.html
new file mode 100644
index 00000000..773b92c3
--- /dev/null
+++ b/src/hi/simulator/scenes/templates/scenes/modals/clear_states_confirm.html
@@ -0,0 +1,34 @@
+{% extends "modals/action_with_cancel.html" %}
+{% load icons %}
+
+{% block preamble %}
+<form action="{% url 'simulator_scene_clear_states' %}" method="post" class="form" data-async="modal">
+ {% csrf_token %}
+{% endblock %}
+
+{% block title_text %}
+Clear States
+{% endblock %}
+
+{% block body %}
+<p>Reset all simulator states to their defaults and clear the main app's
+ lingering “recent / past” visuals, so a fresh sequence run starts clean.</p>
+{% if not cutoff_enabled %}
+<div class="alert alert-warning py-2 mb-0 small">
+ <strong>Heads up:</strong> <code>DEBUG_FORCE_SENSOR_RESPONSE_CUTOFF</code> is off, so the
+ main app will ignore the cutoff. This will reset the simulator, but the console's
+ recent/past decay will <em>not</em> clear. Set it to <code>True</code> in
+ <code>settings/development.py</code> to enable that.
+</div>
+{% endif %}
+{% endblock %}
+
+{% block action_right %}
+<button type="submit" class="btn btn-warning" name="action" value="clear">
+ Clear States
+</button>
+{% endblock %}
+
+{% block postamble %}
+</form>
+{% endblock %}
diff --git a/src/hi/simulator/scenes/templates/scenes/modals/edit_sequence.html b/src/hi/simulator/scenes/templates/scenes/modals/edit_sequence.html
new file mode 100644
index 00000000..c9ffe049
--- /dev/null
+++ b/src/hi/simulator/scenes/templates/scenes/modals/edit_sequence.html
@@ -0,0 +1,44 @@
+{% extends "modals/action_with_cancel.html" %}
+{% load icons %}
+
+{% block preamble %}
+<form action="{% url 'simulator_sequence_edit' scene_id=scene.id sequence_id=sequence.id %}"
+ method="post" class="form" data-async="modal">
+ {% csrf_token %}
+{% endblock %}
+
+{% block title_text %}
+Edit Sequence
+{% endblock %}
+
+{% block body %}
+<div class="sim-edit-sequence">
+ {% if error %}
+ <div class="alert alert-danger py-2">{{ error }}</div>
+ {% endif %}
+ <div class="form-group">
+ <label class="small text-muted mb-1">Name</label>
+ <input type="text" name="name" class="form-control" value="{{ name_value }}">
+ </div>
+ <div class="form-group mb-0">
+ <label class="small text-muted mb-1">Steps (JSON)</label>
+ <textarea name="steps" class="form-control text-monospace" rows="16"
+ spellcheck="false" style="font-size:0.85rem;">{{ steps_text }}</textarea>
+ <small class="form-text text-muted">
+ A list of steps: timed steps
+ <code>{"t": 0.0, "module": "...", "entity": "...", "state": "...", "value": "..."}</code>
+ and markers <code>{"marker": "name"}</code>.
+ </small>
+ </div>
+</div>
+{% endblock %}
+
+{% block action_right %}
+<button type="submit" class="btn btn-primary" name="action" value="save">
+ {% icon "edit" size="sm" css_class="hi-icon-left" %}SAVE
+</button>
+{% endblock %}
+
+{% block postamble %}
+</form>
+{% endblock %}
diff --git a/src/hi/simulator/scenes/templates/scenes/modals/edit_states.html b/src/hi/simulator/scenes/templates/scenes/modals/edit_states.html
new file mode 100644
index 00000000..67bc623e
--- /dev/null
+++ b/src/hi/simulator/scenes/templates/scenes/modals/edit_states.html
@@ -0,0 +1,52 @@
+{% extends "modals/action_with_cancel.html" %}
+{% load icons %}
+
+{% block preamble %}
+<form action="{% url 'simulator_scene_edit_states' scene_id=scene.id %}"
+ method="post" class="form" data-async="modal">
+ {% csrf_token %}
+{% endblock %}
+
+{% block title_text %}
+Select States for {{ scene.name }}
+{% endblock %}
+
+{% block body %}
+<div class="sim-edit-states">
+ <p class="text-muted small">
+ Showing currently-loaded states. If a scene's entities are missing,
+ apply the scene first so its profiles load, then re-open this dialog.
+ </p>
+ {% for module in module_state_tree %}
+ <div class="sim-edit-states-module mb-3">
+ <div class="font-weight-bold">{{ module.label }}</div>
+ {% for entity in module.entities %}
+ <div class="ml-3 mt-1">
+ <div class="text-muted small">{{ entity.name }}</div>
+ {% for state in entity.states %}
+ <div class="form-check ml-3">
+ <input class="form-check-input" type="checkbox" name="state"
+ id="{{ state.dom_id }}" value="{{ state.key }}"
+ {% if state.selected %}checked{% endif %}>
+ <label class="form-check-label" for="{{ state.dom_id }}">{{ state.name }}</label>
+ </div>
+ {% endfor %}
+ </div>
+ {% endfor %}
+ </div>
+ {% empty %}
+ <p class="text-warning">No states are currently loaded. Apply a scene (or
+ add entities to the modules' profiles) and try again.</p>
+ {% endfor %}
+</div>
+{% endblock %}
+
+{% block action_right %}
+<button type="submit" class="btn btn-primary" name="action" value="save">
+ {% icon "edit" size="sm" css_class="hi-icon-left" %}SAVE STATES
+</button>
+{% endblock %}
+
+{% block postamble %}
+</form>
+{% endblock %}
diff --git a/src/hi/simulator/scenes/templates/scenes/modals/import_sequence.html b/src/hi/simulator/scenes/templates/scenes/modals/import_sequence.html
new file mode 100644
index 00000000..3327f15e
--- /dev/null
+++ b/src/hi/simulator/scenes/templates/scenes/modals/import_sequence.html
@@ -0,0 +1,48 @@
+{% extends "modals/action_with_cancel.html" %}
+{% load icons %}
+
+{% block preamble %}
+<form action="{% url 'simulator_sequence_import' scene_id=scene.id %}"
+ method="post" class="form" enctype="multipart/form-data" data-async="modal">
+ {% csrf_token %}
+{% endblock %}
+
+{% block title_text %}
+Import Sequence into {{ scene.name }}
+{% endblock %}
+
+{% block body %}
+<div class="sim-import-sequence">
+ {% if error %}
+ <div class="alert alert-danger py-2">{{ error }}</div>
+ {% endif %}
+ <div class="form-group">
+ <label class="small text-muted mb-1">Name (optional)</label>
+ <input type="text" name="name" class="form-control" value="{{ name_value }}"
+ placeholder="From file / auto">
+ </div>
+ <div class="form-group">
+ <label class="small text-muted mb-1">Upload an exported .json file</label>
+ <input type="file" name="file" class="form-control-file" accept=".json,application/json">
+ </div>
+ <div class="form-group mb-0">
+ <label class="small text-muted mb-1">…or paste JSON</label>
+ <textarea name="steps" class="form-control text-monospace" rows="12"
+ spellcheck="false" style="font-size:0.85rem;">{{ steps_text }}</textarea>
+ <small class="form-text text-muted">
+ Accepts an export envelope <code>{"name": "...", "steps": [...]}</code> or a bare step list.
+ A file upload takes precedence over pasted text.
+ </small>
+ </div>
+</div>
+{% endblock %}
+
+{% block action_right %}
+<button type="submit" class="btn btn-primary" name="action" value="import">
+ {% icon "edit" size="sm" css_class="hi-icon-left" %}IMPORT
+</button>
+{% endblock %}
+
+{% block postamble %}
+</form>
+{% endblock %}
diff --git a/src/hi/simulator/scenes/templates/scenes/pages/scenes.html b/src/hi/simulator/scenes/templates/scenes/pages/scenes.html
new file mode 100644
index 00000000..5d138b04
--- /dev/null
+++ b/src/hi/simulator/scenes/templates/scenes/pages/scenes.html
@@ -0,0 +1,176 @@
+{% extends "simulator/pages/base.html" %}
+{% load icons %}
+{% block head_title %}Scenes — Home Information Simulator{% endblock %}
+
+{% block content %}
+{# Marker for simulator.js's state-value poller — keeps the control grid live. #}
+<div class="sim-main" data-states-url="{% url 'simulator_api_states' %}" hidden></div>
+<div class="sim-scenes container-fluid py-3">
+
+ {% comment %}
+ Scene header: scene picker + active badge on the left, current-scene actions
+ (apply / off / rename / delete) grouped after a divider, new-scene creation
+ pushed to the right. One wrapping row.
+ {% endcomment %}
+ <div class="d-flex align-items-center flex-wrap mb-3">
+ <h4 class="mr-3 mb-0">Scenes</h4>
+
+ {% if scene_list %}
+ <div class="dropdown mr-2 mb-1">
+ <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button"
+ id="hi-scene-select" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
+ Scene: <strong>{{ scene.name|default:"(none)" }}</strong>
+ </button>
+ <div class="dropdown-menu" aria-labelledby="hi-scene-select">
+ {% for s in scene_list %}
+ <a class="dropdown-item plain {% if scene and s.id == scene.id %}active{% endif %}"
+ href="{% url 'simulator_scenes' %}?scene={{ s.id }}">{{ s.name }}</a>
+ {% endfor %}
+ </div>
+ </div>
+ {% endif %}
+
+ {% if active_scene %}
+ <span class="badge badge-success mr-2 mb-1">Active: {{ active_scene.name }}</span>
+ {% else %}
+ <span class="badge badge-secondary mr-2 mb-1">No active scene (Off)</span>
+ {% endif %}
+
+ {% if scene %}
+ <span class="border-left mr-2 mb-1" style="height: 1.6rem;"></span>
+ <form method="post" action="{% url 'simulator_scene_apply' scene_id=scene.id %}" class="mr-1 mb-1">
+ {% csrf_token %}
+ {% if selected_sequence %}
+ <input type="hidden" name="sequence" value="{{ selected_sequence.id }}">
+ {% endif %}
+ <button type="submit" class="btn btn-sm btn-primary"
+ {% if selected_sequence and initial_state_count %}title="Applies scene baseline, then overlays the selected sequence's {{ initial_state_count }}-entry initial state"{% endif %}>
+ Apply Scene
+ </button>
+ </form>
+ <form method="post" action="{% url 'simulator_scene_off' %}" class="mr-1 mb-1">
+ {% csrf_token %}
+ <input type="hidden" name="scene" value="{{ scene.id }}">
+ <button type="submit" class="btn btn-sm btn-outline-secondary">Off</button>
+ </form>
+ <form method="post" action="{% url 'simulator_scene_rename' scene_id=scene.id %}"
+ class="form-inline mr-1 mb-1">
+ {% csrf_token %}
+ <input type="text" name="name" class="form-control form-control-sm mr-1"
+ style="max-width: 10rem;" value="{{ scene.name }}">
+ <button type="submit" class="btn btn-sm btn-outline-secondary">Rename</button>
+ </form>
+ <form method="post" action="{% url 'simulator_scene_delete' scene_id=scene.id %}" class="mr-1 mb-1"
+ onsubmit="return confirm('Delete scene ‘{{ scene.name|escapejs }}’?');">
+ {% csrf_token %}
+ <button type="submit" class="btn btn-sm btn-outline-danger">
+ {% icon "delete" size="sm" css_class="hi-icon-left" %}Delete
+ </button>
+ </form>
+ {% endif %}
+
+ <form method="post" action="{% url 'simulator_scene_create' %}" class="form-inline ml-auto mb-1">
+ {% csrf_token %}
+ <input type="text" name="name" class="form-control form-control-sm mr-1"
+ placeholder="New scene name" required>
+ <button type="submit" class="btn btn-sm btn-outline-success">
+ {% icon "plus" size="sm" css_class="hi-icon-left" %}New Scene
+ </button>
+ </form>
+ </div>
+
+ {% if scene %}
+
+ {% comment %} Transport (record / playback + timeline) — sticky so it stays in view while working the states grid below. {% endcomment %}
+ {% include "scenes/panes/transport.html" %}
+
+ <div class="d-flex align-items-center flex-wrap mt-4 mb-2">
+ <h6 class="text-muted mb-0 mr-2">States</h6>
+ <a class="btn btn-sm btn-outline-secondary mb-1" data-async="modal"
+ href="{% url 'simulator_scene_edit_states' scene_id=scene.id %}">
+ {% icon "edit" size="sm" css_class="hi-icon-left" %}Edit States
+ </a>
+ <a class="btn btn-sm btn-outline-warning ml-2 mb-1" data-async="modal"
+ href="{% url 'simulator_scene_clear_states_confirm' %}">
+ Clear States
+ </a>
+ <form method="post" action="{% url 'simulator_scene_restore_states' %}" class="ml-1 mb-1">
+ {% csrf_token %}
+ <input type="hidden" name="scene" value="{{ scene.id }}">
+ <button type="submit" class="btn btn-sm btn-outline-secondary"
+ title="Remove the cutoff override so the main app reverts to normal behavior">
+ Restore States
+ </button>
+ </form>
+ {% if missing_control_count %}
+ <span class="text-warning small ml-3 mb-1">
+ {{ missing_control_count }} selected control(s) not loaded — apply the scene so its entities load.
+ </span>
+ {% endif %}
+ </div>
+
+ {% if control_grid %}
+ {% comment %} Dense responsive grid: 1 / 2 / 3 columns as width allows, so all controls stay reachable without scrolling while recording. {% endcomment %}
+ <div class="row sim-scene-controls">
+ {% for item in control_grid %}
+ <div class="col-12 col-md-6 col-xl-4 mb-2">
+ <div class="border rounded p-2 h-100">
+ <div class="font-weight-bold text-truncate small mb-1"
+ title="{{ item.entity_name }}">{{ item.entity_name }}</div>
+ {% include "services/panes/sim_state.html" with simulator=item.simulator sim_state=item.sim_state label=item.state_label %}
+ </div>
+ </div>
+ {% endfor %}
+ </div>
+ {% else %}
+ <p class="text-muted">No states selected. Use “Edit States” to choose the controls for this scene.</p>
+ {% endif %}
+
+ {% comment %}
+ Module Profiles: per-integration profile bindings. Set up once per scene and
+ rarely revisited, so demoted to a collapsed section at the foot of the page.
+ {% endcomment %}
+ <details class="sim-scene-bindings mt-4 border-top pt-2">
+ <summary class="text-muted font-weight-bold" style="cursor: pointer;">
+ Module Profiles
+ <span class="font-weight-normal small">— per-integration profile bindings (set up once)</span>
+ </summary>
+ <table class="table table-sm mt-2" style="max-width: 640px;">
+ <tbody>
+ {% for row in module_rows %}
+ <tr>
+ <td class="align-middle"><strong>{{ row.label }}</strong></td>
+ <td class="align-middle">
+ <div class="dropdown">
+ <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button"
+ id="hi-binding-{{ forloop.counter }}"
+ data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
+ {% if row.bound_profile %}{{ row.bound_profile.name }}{% else %}— (individual control){% endif %}
+ </button>
+ <div class="dropdown-menu" aria-labelledby="hi-binding-{{ forloop.counter }}">
+ <a class="dropdown-item plain {% if not row.bound_profile %}active{% endif %}"
+ href="{% url 'simulator_scene_binding_set' scene_id=scene.id module_key=row.module_key profile_id='none' %}">
+ — (individual control)
+ </a>
+ <div class="dropdown-divider"></div>
+ {% for profile in row.profile_list %}
+ <a class="dropdown-item plain {% if row.bound_profile and profile.id == row.bound_profile.id %}active{% endif %}"
+ href="{% url 'simulator_scene_binding_set' scene_id=scene.id module_key=row.module_key profile_id=profile.id %}">
+ {{ profile.name }}
+ </a>
+ {% endfor %}
+ </div>
+ </div>
+ </td>
+ </tr>
+ {% endfor %}
+ </tbody>
+ </table>
+ </details>
+
+ {% else %}
+ <p class="text-muted">No scenes yet. Create one above to begin.</p>
+ {% endif %}
+
+</div>
+{% endblock %}
diff --git a/src/hi/simulator/scenes/templates/scenes/panes/timeline.html b/src/hi/simulator/scenes/templates/scenes/panes/timeline.html
new file mode 100644
index 00000000..a73a850f
--- /dev/null
+++ b/src/hi/simulator/scenes/templates/scenes/panes/timeline.html
@@ -0,0 +1,51 @@
+{% comment %}
+Annotated, click-to-jump SVG timeline for the selected sequence.
+Static render from steps_json; the playhead element is repositioned live
+by scene_timeline.js once status polling is added.
+{% endcomment %}
+<div class="sim-timeline mt-2"
+ data-total="{{ timeline.total|floatformat:3 }}"
+ data-x0="{{ timeline.x0 }}" data-x1="{{ timeline.x1 }}" data-vbw="{{ timeline.vbw }}">
+ <svg class="sim-timeline-svg" viewBox="0 0 {{ timeline.vbw }} {{ timeline.height }}"
+ preserveAspectRatio="none" width="100%" height="{{ timeline.height }}"
+ role="img" aria-label="Sequence timeline (click to jump)">
+
+ <line class="sim-timeline-axis" x1="{{ timeline.x0 }}" y1="{{ timeline.axis_y }}"
+ x2="{{ timeline.x1 }}" y2="{{ timeline.axis_y }}"/>
+
+ {% for e in timeline.entries %}
+ {% if e.kind == 'end' %}
+ <g class="sim-timeline-end" data-t="{{ e.t }}" data-title="{{ e.title }}">
+ <line class="sim-timeline-end-rule" x1="{{ e.x }}" y1="{{ timeline.end_y1 }}"
+ x2="{{ e.x }}" y2="{{ timeline.end_y2 }}"/>
+ <rect class="sim-timeline-hit" x="{{ e.hit_x }}" y="{{ e.hit_y }}"
+ width="{{ timeline.hit_w }}" height="{{ e.hit_h }}"/>
+ </g>
+ {% else %}
+ <g class="sim-timeline-{{ e.kind }}" data-t="{{ e.t }}" data-title="{{ e.title }}">
+ <polygon class="sim-timeline-glyph" points="{{ e.points }}"/>
+ <rect class="sim-timeline-hit" x="{{ e.hit_x }}" y="{{ e.hit_y }}"
+ width="{{ timeline.hit_w }}" height="{{ e.hit_h }}"/>
+ </g>
+ {% endif %}
+ {% endfor %}
+
+ <line class="sim-timeline-playhead" data-role="playhead"
+ x1="{{ timeline.playhead_x }}" y1="{{ timeline.playhead_y1 }}"
+ x2="{{ timeline.playhead_x }}" y2="{{ timeline.playhead_y2 }}"
+ {% if not timeline.active %}style="display:none;"{% endif %}/>
+ </svg>
+
+ <div class="d-flex justify-content-between sim-timeline-scale">
+ <span>0s</span>
+ <span class="text-muted">click to jump · hover a mark for detail</span>
+ <span>{{ timeline.total|floatformat:1 }}s</span>
+ </div>
+
+ <form class="sim-timeline-seek-form"
+ method="post"
+ action="{% url 'simulator_scene_seek' scene_id=scene.id sequence_id=selected_sequence.id %}">
+ {% csrf_token %}
+ <input type="hidden" name="t" value="">
+ </form>
+</div>
diff --git a/src/hi/simulator/scenes/templates/scenes/panes/transport.html b/src/hi/simulator/scenes/templates/scenes/panes/transport.html
new file mode 100644
index 00000000..dbc2a650
--- /dev/null
+++ b/src/hi/simulator/scenes/templates/scenes/panes/transport.html
@@ -0,0 +1,184 @@
+{% load icons %}
+{% comment %}
+Recording / playback transport pane. Server-rendered, and live-refreshed by
+scene_status.js: the .js-playhead / .js-rec-steps spans and the timeline
+playhead update every poll, and the whole pane is re-fetched (this partial)
+when the transport signature changes.
+{% endcomment %}
+<div class="sim-scene-transport sticky-top shadow-sm border rounded bg-light mb-3 p-2"
+ data-status-url="{% url 'simulator_scene_status' %}"
+ data-transport-url="{% url 'simulator_scene_transport' scene_id=scene.id %}{% if selected_sequence %}?sequence={{ selected_sequence.id }}{% endif %}">
+ <div class="d-flex align-items-center flex-wrap">
+ {# --- status badge --- #}
+ {% if recorder_status.paused %}
+ <span class="badge badge-warning mr-3">⏸ Recording paused — <span class="js-rec-steps">{{ recorder_status.step_count }}</span> step(s)</span>
+ {% elif recorder_status.recording %}
+ <span class="badge badge-danger mr-3">● Recording — <span class="js-rec-steps">{{ recorder_status.step_count }}</span> step(s)</span>
+ {% elif player_status.playing %}
+ <span class="badge badge-info mr-3">▶ {{ player_status.sequence_name }} — <span class="js-playhead">{{ player_status.playhead|floatformat:1 }}</span>/{{ player_status.total|floatformat:1 }}s</span>
+ {% elif player_status.paused %}
+ <span class="badge badge-primary mr-3">⏸ {{ player_status.sequence_name }} — <span class="js-playhead">{{ player_status.playhead|floatformat:1 }}</span>/{{ player_status.total|floatformat:1 }}s{% if player_status.next_marker %} → {{ player_status.next_marker }}{% endif %}</span>
+ {% elif recorder_status.has_working %}
+ <span class="badge badge-warning mr-3">Unsaved recording — {{ recorder_status.working_step_count }} step(s)</span>
+ {% else %}
+ <span class="badge badge-secondary mr-3">Idle</span>
+ {% endif %}
+
+ {% if recorder_status.recording %}
+ {# --- recording controls --- #}
+ <form method="post" action="{% url 'simulator_scene_pause' scene_id=scene.id %}" class="mr-2">
+ {% csrf_token %}
+ <button type="submit" class="btn btn-sm btn-outline-dark">{% if recorder_status.paused %}▶ Resume{% else %}⏸ Pause{% endif %}</button>
+ </form>
+ {% if recorder_status.paused %}
+ <form method="post" action="{% url 'simulator_scene_mark' scene_id=scene.id %}" class="form-inline mr-2">
+ {% csrf_token %}
+ <input type="text" name="name" class="form-control form-control-sm mr-1" placeholder="Marker name">
+ <button type="submit" class="btn btn-sm btn-outline-info">⚑ Mark</button>
+ </form>
+ {% endif %}
+ <form method="post" action="{% url 'simulator_scene_stop' scene_id=scene.id %}" class="mr-2">
+ {% csrf_token %}
+ <button type="submit" class="btn btn-sm btn-dark">■ Stop</button>
+ </form>
+ {% elif recorder_status.has_working %}
+ {# --- finalize the just-stopped recording --- #}
+ <form method="post" action="{% url 'simulator_scene_record_save' scene_id=scene.id %}" class="form-inline mr-2">
+ {% csrf_token %}
+ <input type="text" name="name" class="form-control form-control-sm mr-1" placeholder="Name (auto)">
+ <button type="submit" class="btn btn-sm btn-success">Save</button>
+ </form>
+ <form method="post" action="{% url 'simulator_scene_record_discard' scene_id=scene.id %}" class="mr-2">
+ {% csrf_token %}
+ <button type="submit" class="btn btn-sm btn-outline-secondary">Discard</button>
+ </form>
+ {% else %}
+ {# --- idle: start a new recording (each recording is a new sequence) --- #}
+ <form method="post" action="{% url 'simulator_scene_record_start' scene_id=scene.id %}" class="mr-2">
+ {% csrf_token %}
+ {% if selected_sequence %}
+ <input type="hidden" name="sequence" value="{{ selected_sequence.id }}">
+ {% endif %}
+ <button type="submit" class="btn btn-sm btn-danger"
+ {% if selected_sequence and initial_state_count %}title="Applies scene baseline + ‘{{ selected_sequence.name|escapejs }}’ initial state ({{ initial_state_count }}), then starts recording"{% else %}title="Start recording a new sequence"{% endif %}>
+ ● Record New Sequence
+ </button>
+ </form>
+ {% endif %}
+
+ {# --- playback panel (hidden while recording) --- #}
+ {% if not recorder_status.recording and not recorder_status.has_working %}
+ <div class="ml-auto d-flex align-items-center">
+ {% if sequence_list %}
+ <div class="dropdown mr-2">
+ <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button"
+ id="hi-sequence-select" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
+ Sequence: <strong>{{ selected_sequence.name|default:"(none)" }}</strong>
+ </button>
+ <div class="dropdown-menu dropdown-menu-right" aria-labelledby="hi-sequence-select">
+ {% for seq in sequence_list %}
+ <a class="dropdown-item plain {% if selected_sequence and seq.id == selected_sequence.id %}active{% endif %}"
+ href="{% url 'simulator_scenes' %}?scene={{ scene.id }}&sequence={{ seq.id }}">{{ seq.name }}</a>
+ {% endfor %}
+ </div>
+ </div>
+ {% if selected_sequence %}
+ <span class="badge {% if initial_state_count %}badge-info{% else %}badge-light{% endif %} mr-2"
+ title="Captured initial state applied after the scene baseline on load / Apply Scene">
+ Initial: {% if initial_state_count %}{{ initial_state_count }}{% else %}—{% endif %}
+ </span>
+ {% endif %}
+ {% if selected_sequence %}
+ {% if player_status.playing %}
+ <form method="post" action="{% url 'simulator_scene_pause' scene_id=scene.id %}" class="mr-1">
+ {% csrf_token %}
+ <input type="hidden" name="sequence" value="{{ selected_sequence.id }}">
+ <button type="submit" class="btn btn-sm btn-secondary">⏸ Pause</button>
+ </form>
+ <form method="post" action="{% url 'simulator_scene_stop' scene_id=scene.id %}" class="mr-1">
+ {% csrf_token %}
+ <input type="hidden" name="sequence" value="{{ selected_sequence.id }}">
+ <button type="submit" class="btn btn-sm btn-dark">■ Stop</button>
+ </form>
+ {% else %}
+ <form method="post" action="{% url 'simulator_scene_play' scene_id=scene.id sequence_id=selected_sequence.id %}" class="mr-1">
+ {% csrf_token %}
+ <button type="submit" class="btn btn-sm btn-primary">▶ Play</button>
+ </form>
+ <form method="post" action="{% url 'simulator_scene_step' scene_id=scene.id sequence_id=selected_sequence.id %}" class="mr-1">
+ {% csrf_token %}
+ <button type="submit" class="btn btn-sm btn-outline-primary">⏭ Step</button>
+ </form>
+ {% if player_status.paused and player_status.sequence_id == selected_sequence.id %}
+ <form method="post" action="{% url 'simulator_scene_mark' scene_id=scene.id %}" class="form-inline mr-1">
+ {% csrf_token %}
+ <input type="hidden" name="sequence" value="{{ selected_sequence.id }}">
+ <input type="text" name="name" class="form-control form-control-sm mr-1" placeholder="Marker name" style="max-width:9em;">
+ <button type="submit" class="btn btn-sm btn-outline-info">⚑ Mark</button>
+ </form>
+ <form method="post" action="{% url 'simulator_scene_stop' scene_id=scene.id %}" class="mr-1">
+ {% csrf_token %}
+ <input type="hidden" name="sequence" value="{{ selected_sequence.id }}">
+ <button type="submit" class="btn btn-sm btn-dark">■ Stop</button>
+ </form>
+ {% else %}
+ <span class="border-left mr-2" style="height: 1.6rem;"></span>
+ <form method="post" action="{% url 'simulator_sequence_set_initial' sequence_id=selected_sequence.id %}" class="mr-1">
+ {% csrf_token %}
+ <button type="submit" class="btn btn-sm btn-outline-info"
+ title="Snapshot all currently-loaded sim states as this sequence's initial-state overlay"
+ onclick="return confirm('Snapshot all current sim states as initial state for ‘{{ selected_sequence.name|escapejs }}’?{% if initial_state_count %}\n\nThis replaces the existing snapshot ({{ initial_state_count }} entries).{% endif %}');">
+ Set As Initial
+ </button>
+ </form>
+ {% if initial_state_count %}
+ <form method="post" action="{% url 'simulator_sequence_clear_initial' sequence_id=selected_sequence.id %}" class="mr-1">
+ {% csrf_token %}
+ <button type="submit" class="btn btn-sm btn-outline-secondary"
+ title="Wipe this sequence's initial-state overlay"
+ onclick="return confirm('Clear the initial-state snapshot for ‘{{ selected_sequence.name|escapejs }}’?');">
+ Clear Initial
+ </button>
+ </form>
+ {% endif %}
+ <a class="btn btn-sm btn-outline-secondary mr-1" data-async="modal"
+ href="{% url 'simulator_sequence_edit' scene_id=scene.id sequence_id=selected_sequence.id %}"
+ title="Rename / edit JSON">{% icon "edit" size="sm" %}</a>
+ <a class="btn btn-sm btn-outline-secondary mr-1"
+ href="{% url 'simulator_sequence_export' scene_id=scene.id sequence_id=selected_sequence.id %}"
+ title="Export JSON">Export</a>
+ <form method="post" action="{% url 'simulator_sequence_delete' sequence_id=selected_sequence.id %}">
+ {% csrf_token %}
+ <button type="submit" class="btn btn-sm btn-outline-danger"
+ onclick="return confirm('Delete sequence ‘{{ selected_sequence.name|escapejs }}’?');">{% icon "delete" size="sm" %}</button>
+ </form>
+ {% endif %}
+ {% endif %}
+ {% endif %}
+ {% else %}
+ <span class="text-muted small mr-2">No saved sequences yet.</span>
+ {% endif %}
+ <a class="btn btn-sm btn-outline-secondary ml-1" data-async="modal"
+ href="{% url 'simulator_sequence_import' scene_id=scene.id %}"
+ title="Import a sequence">Import</a>
+ </div>
+ {% endif %}
+ </div>
+
+ {# --- annotated, click-to-jump timeline for the selected sequence --- #}
+ {% if timeline and not recorder_status.recording %}
+ {% include "scenes/panes/timeline.html" %}
+ {% endif %}
+
+ {% if player_status.misses %}
+ <details class="text-warning small mt-1">
+ <summary>Last playback: {{ player_status.misses|length }} step(s) could not be resolved
+ — entity not loaded (apply the matching scene/profile).</summary>
+ <ul class="mb-0 mt-1">
+ {% for miss in player_status.misses %}
+ <li><code>[{{ miss.module }}]</code> {{ miss.entity }}.{{ miss.state }}</li>
+ {% endfor %}
+ </ul>
+ </details>
+ {% endif %}
+</div>
diff --git a/src/hi/simulator/scenes/timeline.py b/src/hi/simulator/scenes/timeline.py
new file mode 100644
index 00000000..1e8266f8
--- /dev/null
+++ b/src/hi/simulator/scenes/timeline.py
@@ -0,0 +1,129 @@
+"""SVG timeline render model for a scene's state sequence.
+
+Pure presentation: turns a ``SimStateSequence``'s ``steps_json`` (plus the
+player's status) into the geometry the timeline template renders. No HTTP.
+Geometry is in SVG viewBox units — the SVG scales to fit via
+``preserveAspectRatio="none"`` and the click handler maps pixels back to time.
+"""
+
+# Timeline geometry, in SVG viewBox units.
+TIMELINE_VBW = 1000
+TIMELINE_HEIGHT = 72
+TIMELINE_X0 = 48
+TIMELINE_X1 = 952
+TIMELINE_AXIS_Y = 44
+TIMELINE_MARKER_TOP = TIMELINE_AXIS_Y - 22 # event arrows above the axis
+TIMELINE_STEP_TIP_Y = TIMELINE_AXIS_Y + 3 # state-change arrows below the axis
+TIMELINE_STEP_BASE_Y = TIMELINE_AXIS_Y + 21
+TIMELINE_GLYPH_HALF = 8
+TIMELINE_HIT_HALF = 10 # generous transparent hover/click column
+
+
+SERVICE_MODULE_PREFIX = 'hi.simulator.services.'
+
+
+def _short_module( module ):
+ module = module or ''
+ if module.startswith( SERVICE_MODULE_PREFIX ):
+ return module[ len( SERVICE_MODULE_PREFIX ): ]
+ return module
+
+
+def _timeline_x( t, total ):
+ if total <= 0:
+ return TIMELINE_X0
+ frac = min( 1.0, max( 0.0, t / total ))
+ return round( TIMELINE_X0 + frac * ( TIMELINE_X1 - TIMELINE_X0 ), 2 )
+
+
+def timeline_model( sequence, player_status ):
+ """Parse a sequence's steps into a render model for the SVG timeline.
+ Markers are down-arrows above the axis; state changes are up-arrows below
+ it; the end sentinel is an end-rule at the right edge. Each glyph gets a
+ wide transparent hit column so it is easy to hover/click. Timed items sit
+ at their own t; a legacy marker without a t falls back to the preceding
+ timed step (start is the implicit 0, never materialized)."""
+ steps = sequence.steps_json or []
+ total = max( ( float( s[ 't' ] ) for s in steps if 't' in s ), default = 0.0 )
+ entries = []
+ last_t = 0.0
+ for step in steps:
+ if step.get( 'end' ):
+ et = float( step.get( 't', last_t ))
+ last_t = max( last_t, et )
+ x = _timeline_x( et, total )
+ entries.append({
+ 'kind': 'end',
+ 't': round( et, 3 ),
+ 'x': x,
+ 'hit_x': round( x - TIMELINE_HIT_HALF, 2 ),
+ 'hit_y': 0,
+ 'hit_h': TIMELINE_HEIGHT,
+ 'title': 'End (@{:.2f}s)'.format( et ),
+ })
+ continue
+ if 'marker' in step:
+ mt = float( step[ 't' ] ) if 't' in step else last_t
+ last_t = max( last_t, mt )
+ x = _timeline_x( mt, total )
+ entries.append({
+ 'kind': 'marker',
+ 't': round( mt, 3 ),
+ 'x': x,
+ 'hit_x': round( x - TIMELINE_HIT_HALF, 2 ),
+ 'hit_y': 0,
+ 'hit_h': TIMELINE_AXIS_Y, # events: above the axis only
+ 'points': '{x0},{top} {x1},{top} {x},{tip}'.format(
+ x0 = x - TIMELINE_GLYPH_HALF, x1 = x + TIMELINE_GLYPH_HALF,
+ top = TIMELINE_MARKER_TOP, x = x, tip = TIMELINE_AXIS_Y,
+ ),
+ 'title': '⚑ {} (@{:.2f}s)'.format( step[ 'marker' ], mt ),
+ })
+ continue
+ try:
+ t = float( step.get( 't', last_t ))
+ except ( TypeError, ValueError ):
+ t = last_t
+ last_t = max( last_t, t )
+ x = _timeline_x( t, total )
+ entries.append({
+ 'kind': 'step',
+ 't': round( t, 3 ),
+ 'x': x,
+ 'hit_x': round( x - TIMELINE_HIT_HALF, 2 ),
+ 'hit_y': TIMELINE_AXIS_Y, # transitions: below the axis only
+ 'hit_h': TIMELINE_HEIGHT - TIMELINE_AXIS_Y,
+ 'points': '{x},{tip} {x0},{base} {x1},{base}'.format(
+ x = x, tip = TIMELINE_STEP_TIP_Y,
+ x0 = x - TIMELINE_GLYPH_HALF, x1 = x + TIMELINE_GLYPH_HALF,
+ base = TIMELINE_STEP_BASE_Y,
+ ),
+ 'title': '{:.2f}s [{}] {}.{} = {}'.format(
+ t, _short_module( step.get( 'module' )), step.get( 'entity' ),
+ step.get( 'state' ), step.get( 'value' ),
+ ),
+ })
+ continue
+
+ active = bool(
+ player_status.get( 'loaded' )
+ and player_status.get( 'sequence_id' ) == sequence.id
+ )
+ playhead_t = player_status.get( 'playhead', 0.0 ) if active else 0.0
+ return {
+ 'total': total,
+ 'entries': entries,
+ 'vbw': TIMELINE_VBW,
+ 'height': TIMELINE_HEIGHT,
+ 'x0': TIMELINE_X0,
+ 'x1': TIMELINE_X1,
+ 'axis_y': TIMELINE_AXIS_Y,
+ 'hit_w': 2 * TIMELINE_HIT_HALF,
+ 'end_y1': 2,
+ 'end_y2': TIMELINE_HEIGHT - 2,
+ 'playhead_y1': 6,
+ 'playhead_y2': TIMELINE_HEIGHT - 6,
+ 'playhead_t': round( playhead_t, 3 ),
+ 'playhead_x': _timeline_x( playhead_t, total ),
+ 'active': active,
+ }
diff --git a/src/hi/simulator/scenes/transport.py b/src/hi/simulator/scenes/transport.py
new file mode 100644
index 00000000..a4de64e3
--- /dev/null
+++ b/src/hi/simulator/scenes/transport.py
@@ -0,0 +1,53 @@
+"""Transport-pane context: the recording/playback bar + its timeline.
+
+Assembles the context shared by the full Scenes dashboard render and the live
+fragment-refresh endpoint, so the two can't drift. Also the button-relevant
+signature the client polls to decide when to fragment-refresh.
+"""
+from .player import SimPlayer
+from .recorder import SimRecorder
+from .timeline import timeline_model
+
+
+def _resolve_sequence( sequence_param, sequence_list ):
+ if sequence_param:
+ match = next(
+ ( s for s in sequence_list if str( s.id ) == str( sequence_param )), None,
+ )
+ if match is not None:
+ return match
+ return sequence_list[ 0 ] if sequence_list else None
+
+
+def build_transport_context( scene, sequence_param ):
+ """Context for the transport pane (badge, controls, timeline) — shared by
+ the full dashboard and the live fragment-refresh endpoint."""
+ sequence_list = list( scene.state_sequences.all() )
+ selected_sequence = _resolve_sequence( sequence_param, sequence_list )
+ player_status = SimPlayer().get_status()
+ timeline = None
+ initial_state_count = 0
+ if selected_sequence is not None:
+ timeline = timeline_model( selected_sequence, player_status )
+ initial_state_count = len( selected_sequence.initial_state_json or [] )
+ return {
+ 'scene': scene,
+ 'sequence_list': sequence_list,
+ 'selected_sequence': selected_sequence,
+ 'recorder_status': SimRecorder().get_status(),
+ 'player_status': player_status,
+ 'timeline': timeline,
+ 'initial_state_count': initial_state_count,
+ }
+
+
+def transport_signature( recorder_status, player_status ):
+ """A token of the *button-relevant* state, so the client only fragment-
+ refreshes the transport when the available controls actually change (not
+ on every playhead tick or step-count bump)."""
+ return '{}|{}|{}|{}'.format(
+ int( recorder_status[ 'recording' ] ),
+ int( recorder_status[ 'paused' ] ),
+ player_status[ 'mode' ],
+ int( recorder_status[ 'has_working' ] ),
+ )
diff --git a/src/hi/simulator/scenes/urls.py b/src/hi/simulator/scenes/urls.py
new file mode 100644
index 00000000..1ba6cb14
--- /dev/null
+++ b/src/hi/simulator/scenes/urls.py
@@ -0,0 +1,119 @@
+from django.urls import path, re_path
+
+from . import views
+
+
+urlpatterns = [
+ path( '',
+ views.ScenesIndexView.as_view(),
+ name = 'simulator_scenes' ),
+
+ path( 'create',
+ views.SceneCreateView.as_view(),
+ name = 'simulator_scene_create' ),
+
+ path( '<int:scene_id>/rename',
+ views.SceneRenameView.as_view(),
+ name = 'simulator_scene_rename' ),
+
+ path( '<int:scene_id>/delete',
+ views.SceneDeleteView.as_view(),
+ name = 'simulator_scene_delete' ),
+
+ path( '<int:scene_id>/apply',
+ views.SceneApplyView.as_view(),
+ name = 'simulator_scene_apply' ),
+
+ path( 'off',
+ views.SceneOffView.as_view(),
+ name = 'simulator_scene_off' ),
+
+ path( 'clear-states',
+ views.SceneClearStatesView.as_view(),
+ name = 'simulator_scene_clear_states' ),
+
+ path( 'clear-states/confirm',
+ views.SceneClearStatesConfirmView.as_view(),
+ name = 'simulator_scene_clear_states_confirm' ),
+
+ path( 'restore-states',
+ views.SceneRestoreStatesView.as_view(),
+ name = 'simulator_scene_restore_states' ),
+
+ path( 'status',
+ views.SceneStatusView.as_view(),
+ name = 'simulator_scene_status' ),
+
+ path( '<int:scene_id>/transport',
+ views.SceneTransportView.as_view(),
+ name = 'simulator_scene_transport' ),
+
+ path( '<int:scene_id>/states',
+ views.SceneEditStatesView.as_view(),
+ name = 'simulator_scene_edit_states' ),
+
+ path( '<int:scene_id>/record/start',
+ views.SceneRecordStartView.as_view(),
+ name = 'simulator_scene_record_start' ),
+
+ path( '<int:scene_id>/stop',
+ views.SceneStopView.as_view(),
+ name = 'simulator_scene_stop' ),
+
+ path( '<int:scene_id>/record/save',
+ views.SceneRecordSaveView.as_view(),
+ name = 'simulator_scene_record_save' ),
+
+ path( '<int:scene_id>/record/discard',
+ views.SceneRecordDiscardView.as_view(),
+ name = 'simulator_scene_record_discard' ),
+
+ path( '<int:scene_id>/play/<int:sequence_id>',
+ views.ScenePlayView.as_view(),
+ name = 'simulator_scene_play' ),
+
+ path( '<int:scene_id>/step/<int:sequence_id>',
+ views.SceneStepView.as_view(),
+ name = 'simulator_scene_step' ),
+
+ path( '<int:scene_id>/seek/<int:sequence_id>',
+ views.SceneSeekView.as_view(),
+ name = 'simulator_scene_seek' ),
+
+ path( '<int:scene_id>/pause',
+ views.ScenePauseView.as_view(),
+ name = 'simulator_scene_pause' ),
+
+ path( '<int:scene_id>/mark',
+ views.SceneMarkView.as_view(),
+ name = 'simulator_scene_mark' ),
+
+ path( 'sequence/<int:sequence_id>/delete',
+ views.SequenceDeleteView.as_view(),
+ name = 'simulator_sequence_delete' ),
+
+ path( 'sequence/<int:sequence_id>/initial/set',
+ views.SequenceSetInitialView.as_view(),
+ name = 'simulator_sequence_set_initial' ),
+
+ path( 'sequence/<int:sequence_id>/initial/clear',
+ views.SequenceClearInitialView.as_view(),
+ name = 'simulator_sequence_clear_initial' ),
+
+ path( '<int:scene_id>/sequence/<int:sequence_id>/edit',
+ views.SceneSequenceEditView.as_view(),
+ name = 'simulator_sequence_edit' ),
+
+ path( '<int:scene_id>/sequence/<int:sequence_id>/export',
+ views.SceneSequenceExportView.as_view(),
+ name = 'simulator_sequence_export' ),
+
+ path( '<int:scene_id>/sequence/import',
+ views.SceneSequenceImportView.as_view(),
+ name = 'simulator_sequence_import' ),
+
+ # module_key contains dots/colons, so use a permissive pattern.
+ re_path( r'^(?P<scene_id>\d+)/binding/(?P<module_key>[\w_\-\.\:]+)/(?P<profile_id>\d+|none)$',
+ views.SceneBindingSetView.as_view(),
+ name = 'simulator_scene_binding_set' ),
+]
diff --git a/src/hi/simulator/scenes/views.py b/src/hi/simulator/scenes/views.py
new file mode 100644
index 00000000..6c734e32
--- /dev/null
+++ b/src/hi/simulator/scenes/views.py
@@ -0,0 +1,586 @@
+import json
+import logging
+
+from django.conf import settings
+from django.core.cache import cache
+from django.db import transaction
+from django.http import Http404, HttpResponse, 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.apps.common import datetimeproxy
+from hi.simulator.profile.models import SimProfile
+from hi.simulator.profile.profile_manager import ProfileManager
+from hi.simulator.services.service_simulator_manager import ServiceSimulatorManager
+
+from .models import SimScene, SimSceneBinding, SimSceneControl, SimStateSequence
+from .player import SimPlayer
+from .recorder import SimRecorder
+from .scene_controller import SceneController
+from .control_grid import control_key, resolve_control, simulator_by_module, split_control_key
+from .initial_state import apply_initial_state, capture_current_state
+from .sequence_io import parse_steps, safe_filename
+from .transport import build_transport_context, transport_signature
+
+logger = logging.getLogger(__name__)
+
+
+def _scenes_redirect( scene_id = None, sequence_id = None ):
+ url = reverse( 'simulator_scenes' )
+ params = []
+ if scene_id is not None:
+ params.append( f'scene={scene_id}' )
+ if sequence_id is not None:
+ params.append( f'sequence={sequence_id}' )
+ if params:
+ url = f'{url}?' + '&'.join( params )
+ return HttpResponseRedirect( url )
+
+
+def _get_scene( scene_id ) -> SimScene:
+ try:
+ return SimScene.objects.get( id = scene_id )
+ except SimScene.DoesNotExist:
+ raise Http404( 'Scene not found.' )
+
+
+class ScenesIndexView( View ):
+ """The Scenes dashboard: compose a scene (per-module profile bindings),
+ apply it, and drive the scene's curated state controls. (Record/
+ playback lands in later phases.)"""
+
+ def get( self, request, *args, **kwargs ):
+ scene_list = list( SimScene.objects.all() )
+ scene = self._resolve_selected_scene( request, scene_list )
+ active_scene = SceneController().get_active_scene()
+
+ context = {
+ 'active_section': 'scenes',
+ 'scene_list': scene_list,
+ 'scene': scene,
+ 'active_scene': active_scene,
+ 'module_rows': [],
+ 'control_grid': [],
+ 'missing_control_count': 0,
+ 'sequence_list': [],
+ 'selected_sequence': None,
+ 'recorder_status': SimRecorder().get_status(),
+ 'player_status': SimPlayer().get_status(),
+ 'timeline': None,
+ }
+ if scene is not None:
+ simulator_by_module_map = simulator_by_module()
+ context[ 'module_rows' ] = self._build_module_rows( scene, simulator_by_module_map )
+ for control in scene.controls.all():
+ resolved = resolve_control( control, simulator_by_module_map )
+ if resolved is not None:
+ context[ 'control_grid' ].append( resolved )
+ else:
+ context[ 'missing_control_count' ] += 1
+ continue
+ context.update( build_transport_context( scene, request.GET.get( 'sequence' )))
+ return render( request, 'scenes/pages/scenes.html', context )
+
+ def _resolve_selected_scene( self, request, scene_list ):
+ scene_id = request.GET.get( 'scene' )
+ if scene_id:
+ try:
+ return SimScene.objects.get( id = int( scene_id ))
+ except ( ValueError, SimScene.DoesNotExist ):
+ pass
+ active = SceneController().get_active_scene()
+ if active is not None:
+ return active
+ return scene_list[0] if scene_list else None
+
+ def _build_module_rows( self, scene, simulator_by_module_map ):
+ binding_by_module = {
+ binding.module_key: binding
+ for binding in scene.bindings.select_related( 'profile' ).all()
+ }
+ rows = []
+ for module_key, simulator in simulator_by_module_map.items():
+ binding = binding_by_module.get( module_key )
+ rows.append({
+ 'module_key': module_key,
+ 'label': simulator.label,
+ 'profile_list': ProfileManager().list_profiles( module_key ),
+ 'bound_profile': binding.profile if binding else None,
+ })
+ continue
+ rows.sort( key = lambda row : row['label'] )
+ return rows
+
+
+class SceneCreateView( View ):
+ def post( self, request, *args, **kwargs ):
+ name = ( request.POST.get( 'name' ) or '' ).strip()
+ if not name:
+ return _scenes_redirect()
+ scene, _created = SimScene.objects.get_or_create( name = name )
+ return _scenes_redirect( scene.id )
+
+
+class SceneRenameView( View ):
+ def post( self, request, scene_id, *args, **kwargs ):
+ scene = _get_scene( scene_id )
+ name = ( request.POST.get( 'name' ) or '' ).strip()
+ if name:
+ scene.name = name
+ scene.save( update_fields = [ 'name' ] )
+ return _scenes_redirect( scene.id )
+
+
+class SceneDeleteView( View ):
+ def post( self, request, scene_id, *args, **kwargs ):
+ scene = _get_scene( scene_id )
+ scene.delete()
+ return _scenes_redirect()
+
+
+class SceneApplyView( View ):
+ """Apply the scene's profile bindings (clean baseline). If a sequence
+ is currently selected, overlay its captured initial state on top so the
+ operator lands at the sequence's intended starting point in one click."""
+
+ def post( self, request, scene_id, *args, **kwargs ):
+ scene = _get_scene( scene_id )
+ SceneController().apply( scene )
+ sequence_id = request.POST.get( 'sequence' )
+ if sequence_id:
+ try:
+ sequence = SimStateSequence.objects.get(
+ id = int( sequence_id ), scene_id = scene.id,
+ )
+ except ( ValueError, SimStateSequence.DoesNotExist ):
+ sequence = None
+ if sequence is not None:
+ apply_initial_state( sequence.initial_state_json or [] )
+ return _scenes_redirect( scene.id, sequence_id or None )
+
+
+class SceneOffView( View ):
+ def post( self, request, *args, **kwargs ):
+ SceneController().clear()
+ return _scenes_redirect( request.POST.get( 'scene' ) )
+
+
+class SceneClearStatesView( View ):
+ """Reset the simulator's states to defaults and signal the (independent)
+ main HI app to drop sensor responses from before now — so its lingering
+ 'recent/past' visuals don't force a wait before re-running a sequence.
+
+ The two processes stay decoupled: the simulator only writes a cutoff epoch
+ to the shared cache key; the main app owns reading/filtering it."""
+
+ CUTOFF_TTL_SECS = 2 * 60 * 60 # past the main app's longest decay window
+
+ def post( self, request, *args, **kwargs ):
+ cache.set(
+ settings.SENSOR_RESPONSE_CUTOFF_CACHE_KEY,
+ datetimeproxy.now().timestamp(),
+ self.CUTOFF_TTL_SECS,
+ )
+ ServiceSimulatorManager().reset_all_to_defaults()
+ return antinode.refresh_response()
+
+
+class SceneClearStatesConfirmView( View ):
+ """Server-rendered confirmation modal for Clear States. Warns when the
+ cutoff is disabled in settings, so the operator knows the main app will
+ ignore it (simulator resets, but the console's recent/past won't clear)."""
+
+ MODAL_TEMPLATE_NAME = 'scenes/modals/clear_states_confirm.html'
+
+ def get( self, request, *args, **kwargs ):
+ context = {
+ 'cutoff_enabled': bool( getattr(
+ settings, 'DEBUG_FORCE_SENSOR_RESPONSE_CUTOFF', False,
+ )),
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+
+class SceneRestoreStatesView( View ):
+ """Complement to Clear States: drop the cutoff override from the shared
+ cache so the main app reverts to normal (shows all cached sensor responses
+ again). A debug aid for comparing cleared vs. normal behavior."""
+
+ def post( self, request, *args, **kwargs ):
+ cache.delete( settings.SENSOR_RESPONSE_CUTOFF_CACHE_KEY )
+ return _scenes_redirect( request.POST.get( 'scene' ) )
+
+
+class SceneBindingSetView( View ):
+ """Set (or clear, with profile_id='none') the profile a module uses in
+ a scene. GET-href driven, mirroring the existing profile-switch UI."""
+
+ def get( self, request, scene_id, module_key, profile_id, *args, **kwargs ):
+ scene = _get_scene( scene_id )
+ if profile_id == 'none':
+ SimSceneBinding.objects.filter(
+ scene = scene, module_key = module_key,
+ ).delete()
+ return _scenes_redirect( scene.id )
+ try:
+ profile = SimProfile.objects.get(
+ id = int( profile_id ), module_key = module_key,
+ )
+ except ( ValueError, SimProfile.DoesNotExist ):
+ raise Http404( 'Profile not found for module.' )
+ SimSceneBinding.objects.update_or_create(
+ scene = scene, module_key = module_key,
+ defaults = { 'profile': profile },
+ )
+ return _scenes_redirect( scene.id )
+
+
+class SceneEditStatesView( View ):
+ """Curate the scene's dashboard control set: a modal of all currently
+ loaded states as checkboxes; checked items become SimSceneControl rows
+ (in submission order). Lists currently-loaded states, so apply the
+ scene first if its entities aren't loaded yet."""
+
+ MODAL_TEMPLATE_NAME = 'scenes/modals/edit_states.html'
+
+ def get( self, request, scene_id, *args, **kwargs ):
+ scene = _get_scene( scene_id )
+ context = {
+ 'scene': scene,
+ 'module_state_tree': self._build_state_tree( scene ),
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+ def post( self, request, scene_id, *args, **kwargs ):
+ scene = _get_scene( scene_id )
+ keys = request.POST.getlist( 'state' )
+ with transaction.atomic():
+ scene.controls.all().delete()
+ controls = []
+ for order_id, key in enumerate( keys ):
+ module_key, entity_name, sim_state_id = split_control_key( key )
+ controls.append( SimSceneControl(
+ scene = scene,
+ module_key = module_key,
+ entity_name = entity_name,
+ sim_state_id = sim_state_id,
+ order_id = order_id,
+ ))
+ continue
+ SimSceneControl.objects.bulk_create( controls )
+ return antinode.refresh_response()
+
+ def _build_state_tree( self, scene ):
+ selected_keys = {
+ control_key( c.module_key, c.entity_name, c.sim_state_id )
+ for c in scene.controls.all()
+ }
+ tree = []
+ dom_counter = 0
+ for simulator_data in ServiceSimulatorManager().get_simulator_data_list():
+ simulator = simulator_data.simulator
+ entities = []
+ for sim_entity in simulator.sim_entities:
+ states = []
+ for sim_state in sim_entity.sim_state_list:
+ key = control_key(
+ simulator.module_key, sim_entity.name, sim_state.sim_state_id,
+ )
+ dom_counter += 1
+ states.append({
+ 'dom_id': f'edit-state-{dom_counter}',
+ 'key': key,
+ 'name': sim_state.name,
+ 'selected': key in selected_keys,
+ })
+ continue
+ if states:
+ entities.append({ 'name': sim_entity.name, 'states': states })
+ continue
+ if entities:
+ tree.append({ 'label': simulator.label, 'entities': entities })
+ continue
+ return tree
+
+
+class SceneRecordStartView( View ):
+ """Apply the scene's clean baseline, then start recording so the
+ captured sequence is reproducible (playback applies the same baseline
+ before replaying steps). If a sequence is currently selected, overlay
+ its captured initial state too — re-records of a beat sequence start
+ from the same starting world the playback would."""
+
+ def post( self, request, scene_id, *args, **kwargs ):
+ scene = _get_scene( scene_id )
+ SceneController().apply( scene )
+ sequence_id = request.POST.get( 'sequence' )
+ if sequence_id:
+ try:
+ sequence = SimStateSequence.objects.get(
+ id = int( sequence_id ), scene_id = scene.id,
+ )
+ except ( ValueError, SimStateSequence.DoesNotExist ):
+ sequence = None
+ if sequence is not None:
+ apply_initial_state( sequence.initial_state_json or [] )
+ SimRecorder().start( scene )
+ return _scenes_redirect( scene.id, sequence_id or None )
+
+
+class SceneStopView( View ):
+ """Single STOP for both recording and playback (per the UI)."""
+
+ def post( self, request, scene_id, *args, **kwargs ):
+ SimRecorder().stop()
+ SimPlayer().stop()
+ return _scenes_redirect( scene_id, request.POST.get( 'sequence' ) )
+
+
+class SceneRecordSaveView( View ):
+ def post( self, request, scene_id, *args, **kwargs ):
+ sequence = SimRecorder().save( request.POST.get( 'name' ) )
+ return _scenes_redirect(
+ scene_id, sequence.id if sequence is not None else None,
+ )
+
+
+class SceneRecordDiscardView( View ):
+ def post( self, request, scene_id, *args, **kwargs ):
+ SimRecorder().discard()
+ return _scenes_redirect( scene_id )
+
+
+def _get_sequence( scene_id, sequence_id ) -> SimStateSequence:
+ try:
+ return SimStateSequence.objects.get( id = sequence_id, scene_id = scene_id )
+ except SimStateSequence.DoesNotExist:
+ raise Http404( 'Sequence not found.' )
+
+
+class ScenePlayView( View ):
+ def post( self, request, scene_id, sequence_id, *args, **kwargs ):
+ SimPlayer().play( _get_sequence( scene_id, sequence_id ))
+ return _scenes_redirect( scene_id, sequence_id )
+
+
+class SceneStepView( View ):
+ def post( self, request, scene_id, sequence_id, *args, **kwargs ):
+ SimPlayer().step( _get_sequence( scene_id, sequence_id ))
+ return _scenes_redirect( scene_id, sequence_id )
+
+
+class SceneSeekView( View ):
+ def post( self, request, scene_id, sequence_id, *args, **kwargs ):
+ sequence = _get_sequence( scene_id, sequence_id )
+ try:
+ t = float( request.POST.get( 't' ) or 0.0 )
+ except ( TypeError, ValueError ):
+ t = 0.0
+ SimPlayer().seek( sequence, t )
+ return _scenes_redirect( scene_id, sequence_id )
+
+
+class ScenePauseView( View ):
+ """Single PAUSE: toggles the record clock while recording, otherwise
+ pauses playback."""
+
+ def post( self, request, scene_id, *args, **kwargs ):
+ recorder = SimRecorder()
+ if recorder.is_recording():
+ recorder.toggle_pause()
+ else:
+ SimPlayer().pause()
+ return _scenes_redirect( scene_id, request.POST.get( 'sequence' ))
+
+
+class SceneMarkView( View ):
+ """Single MARK (paused only): marks the recording while recording,
+ otherwise marks the loaded playback sequence."""
+
+ def post( self, request, scene_id, *args, **kwargs ):
+ name = request.POST.get( 'name' )
+ recorder = SimRecorder()
+ if recorder.is_recording():
+ recorder.mark( name )
+ return _scenes_redirect( scene_id )
+ SimPlayer().mark( name )
+ return _scenes_redirect( scene_id, request.POST.get( 'sequence' ))
+
+
+class SequenceDeleteView( View ):
+ def post( self, request, sequence_id, *args, **kwargs ):
+ try:
+ sequence = SimStateSequence.objects.get( id = sequence_id )
+ except SimStateSequence.DoesNotExist:
+ raise Http404( 'Sequence not found.' )
+ scene_id = sequence.scene_id
+ sequence.delete()
+ return _scenes_redirect( scene_id )
+
+
+class SequenceSetInitialView( View ):
+ """Snapshot all currently-loaded sim states and save them as the
+ sequence's initial-state overlay. Refreshes the page so the operator
+ sees the updated count badge in the transport pane."""
+
+ def post( self, request, sequence_id, *args, **kwargs ):
+ try:
+ sequence = SimStateSequence.objects.get( id = sequence_id )
+ except SimStateSequence.DoesNotExist:
+ raise Http404( 'Sequence not found.' )
+ sequence.initial_state_json = capture_current_state()
+ sequence.save( update_fields = [ 'initial_state_json', 'updated_datetime' ] )
+ return _scenes_redirect( sequence.scene_id, sequence.id )
+
+
+class SequenceClearInitialView( View ):
+ """Wipe the sequence's initial-state overlay so it loads against pure
+ profile baseline."""
+
+ def post( self, request, sequence_id, *args, **kwargs ):
+ try:
+ sequence = SimStateSequence.objects.get( id = sequence_id )
+ except SimStateSequence.DoesNotExist:
+ raise Http404( 'Sequence not found.' )
+ sequence.initial_state_json = []
+ sequence.save( update_fields = [ 'initial_state_json', 'updated_datetime' ] )
+ return _scenes_redirect( sequence.scene_id, sequence.id )
+
+
+class SceneSequenceEditView( View ):
+ """Rename a sequence and/or edit its raw step JSON (markers + timing)."""
+
+ MODAL_TEMPLATE_NAME = 'scenes/modals/edit_sequence.html'
+
+ def get( self, request, scene_id, sequence_id, *args, **kwargs ):
+ sequence = _get_sequence( scene_id, sequence_id )
+ context = {
+ 'scene': sequence.scene,
+ 'sequence': sequence,
+ 'name_value': sequence.name,
+ 'steps_text': json.dumps( sequence.steps_json or [], indent = 2 ),
+ }
+ return render( request, self.MODAL_TEMPLATE_NAME, context )
+
+ def post( self, request, scene_id, sequence_id, *args, **kwargs ):
+ sequence = _get_sequence( scene_id, sequence_id )
+ name = ( request.POST.get( 'name' ) or '' ).strip()
+ raw = request.POST.get( 'steps' ) or ''
+ steps, error = parse_steps( raw )
+ if not error and not name:
+ error = 'Name is required.'
+ if not error and SimStateSequence.objects.filter(
+ scene = sequence.scene, name = name ).exclude( id = sequence.id ).exists():
+ error = 'A sequence with that name already exists.'
+ if error:
+ return render( request, self.MODAL_TEMPLATE_NAME, {
+ 'scene': sequence.scene,
+ 'sequence': sequence,
+ 'name_value': name or sequence.name,
+ 'steps_text': raw,
+ 'error': error,
+ })
+ sequence.name = name
+ sequence.steps_json = steps
+ sequence.save()
+ return antinode.refresh_response()
+
+
+class SceneSequenceExportView( View ):
+ def get( self, request, scene_id, sequence_id, *args, **kwargs ):
+ sequence = _get_sequence( scene_id, sequence_id )
+ payload = { 'name': sequence.name, 'steps': sequence.steps_json or [] }
+ response = HttpResponse(
+ json.dumps( payload, indent = 2 ),
+ content_type = 'application/json',
+ )
+ response[ 'Content-Disposition' ] = (
+ f'attachment; filename="{safe_filename( sequence.name )}.json"'
+ )
+ return response
+
+
+class SceneSequenceImportView( View ):
+ """Create a new sequence from a pasted/uploaded export (or bare step list)."""
+
+ MODAL_TEMPLATE_NAME = 'scenes/modals/import_sequence.html'
+
+ def get( self, request, scene_id, *args, **kwargs ):
+ scene = _get_scene( scene_id )
+ return render( request, self.MODAL_TEMPLATE_NAME, { 'scene': scene } )
+
+ def post( self, request, scene_id, *args, **kwargs ):
+ scene = _get_scene( scene_id )
+ upload = request.FILES.get( 'file' )
+ if upload is not None:
+ raw = upload.read().decode( 'utf-8', errors = 'replace' )
+ else:
+ raw = request.POST.get( 'steps' ) or ''
+ steps, error = parse_steps( raw )
+ name = ( request.POST.get( 'name' ) or '' ).strip() or self._name_from_payload( raw )
+ if not name:
+ name = f'Sequence {scene.state_sequences.count() + 1}'
+ if not error:
+ while SimStateSequence.objects.filter( scene = scene, name = name ).exists():
+ name = f'{name} (imported)'
+ if error:
+ return render( request, self.MODAL_TEMPLATE_NAME, {
+ 'scene': scene,
+ 'name_value': name,
+ 'steps_text': raw,
+ 'error': error,
+ })
+ SimStateSequence.objects.create(
+ scene = scene, name = name, steps_json = steps,
+ )
+ return antinode.refresh_response()
+
+ def _name_from_payload( self, raw ):
+ try:
+ payload = json.loads( raw )
+ except ( ValueError, TypeError ):
+ return ''
+ if isinstance( payload, dict ):
+ return ( payload.get( 'name' ) or '' ).strip()
+ return ''
+
+
+class SceneStatusView( View ):
+ """Lightweight JSON poll for live transport: player/recorder status plus a
+ button-relevant signature the client uses to decide when to fragment-
+ refresh the transport pane. Player/recorder are process singletons, so
+ this needs no scene id."""
+
+ def get( self, request, *args, **kwargs ):
+ recorder_status = SimRecorder().get_status()
+ player_status = SimPlayer().get_status()
+ return JsonResponse({
+ 'signature': transport_signature( recorder_status, player_status ),
+ 'player': {
+ 'mode': player_status[ 'mode' ],
+ 'playing': player_status[ 'playing' ],
+ 'paused': player_status[ 'paused' ],
+ 'playhead': player_status[ 'playhead' ],
+ 'playhead_limit': player_status[ 'playhead_limit' ],
+ 'total': player_status[ 'total' ],
+ 'sequence_id': player_status[ 'sequence_id' ],
+ },
+ 'recorder': {
+ 'recording': recorder_status[ 'recording' ],
+ 'paused': recorder_status[ 'paused' ],
+ 'step_count': recorder_status[ 'step_count' ],
+ 'has_working': recorder_status[ 'has_working' ],
+ },
+ })
+
+
+class SceneTransportView( View ):
+ """Render just the transport pane (badge, controls, timeline) for live
+ fragment-refresh when the transport signature changes."""
+
+ def get( self, request, scene_id, *args, **kwargs ):
+ scene = _get_scene( scene_id )
+ context = build_transport_context( scene, request.GET.get( 'sequence' ))
+ return render( request, 'scenes/panes/transport.html', context )
diff --git a/src/hi/simulator/services/forms.py b/src/hi/simulator/services/forms.py
index 98dc91e4..f19a5aa3 100644
--- a/src/hi/simulator/services/forms.py
+++ b/src/hi/simulator/services/forms.py
@@ -36,16 +36,23 @@ class SimEntityFieldsForm( forms.Form ):
def __init__(self, sim_entity_fields_class: Type[ SimEntityFields ], *args, initial = None, **kwargs):
super().__init__(*args, **kwargs)
- # Track which fields use the CSV-choices round-trip so
- # ``clean()`` can rejoin the multi-select list back into a
- # CSV string for the dataclass consumer.
+ # Fields rendered as multi-checkbox pickers (csv_choices metadata).
self._csv_choice_field_names = set()
+ # Fields whose dataclass type is ``list``. clean() coerces these
+ # back to a list regardless of widget (checkbox or text input), so
+ # the dataclass keeps its list shape. A ``str`` field with
+ # csv_choices is NOT in this set and stays a CSV string (HomeBox).
+ self._list_field_names = set()
+
for field in fields( sim_entity_fields_class ):
metadata = field.metadata or {}
help_text = metadata.get( 'help_text', '' )
csv_choices = metadata.get( 'csv_choices' )
+ if field.type is list:
+ self._list_field_names.add( field.name )
+
if csv_choices is not None:
self._add_csv_choice_field(
field = field,
@@ -55,6 +62,14 @@ class SimEntityFieldsForm( forms.Form ):
)
continue
+ if field.type is list:
+ self._add_list_field(
+ field = field,
+ help_text = help_text,
+ initial = initial,
+ )
+ continue
+
field_type = field.type
form_field_class = self.DATA_TYPE_TO_FORM_FIELD.get( field_type, None )
if not form_field_class:
@@ -73,10 +88,11 @@ class SimEntityFieldsForm( forms.Form ):
return
def _add_csv_choice_field(self, field, choices_source, help_text, initial):
- """Render a CSV-string dataclass field as a multi-checkbox
- picker. The dataclass keeps its plain ``str`` shape; the
- form converts initial CSV → list at render time and
- ``clean()`` converts list → CSV at submit time."""
+ """Render a dataclass field as a multi-checkbox picker. The
+ widget converts initial CSV-or-list → list at render time; at
+ submit time ``clean()`` coerces the selection back to the
+ dataclass's shape — a list for a ``list`` field, or a CSV string
+ for a ``str`` field (e.g. HomeBox ``attachment_keys``)."""
choices = choices_source() if callable( choices_source ) else list( choices_source )
default_value = '' if field.default is MISSING else ( field.default or '' )
@@ -101,13 +117,53 @@ class SimEntityFieldsForm( forms.Form ):
self._csv_choice_field_names.add( field.name )
return
+ def _add_list_field(self, field, help_text, initial):
+ """Fallback for a plain ``list`` field that has no ``csv_choices``:
+ a comma-separated text input. ``clean()`` splits it back to a list
+ so the dataclass keeps its ``list`` shape. (List fields are tracked
+ as list-typed in ``__init__``, not here.)"""
+ if field.default_factory is not MISSING:
+ default_value = field.default_factory()
+ elif field.default is not MISSING:
+ default_value = field.default
+ else:
+ default_value = []
+ raw_initial = initial.get( field.name, default_value ) if initial else default_value
+ if isinstance( raw_initial, (list, tuple) ):
+ field_initial = ', '.join( str( item ) for item in raw_initial )
+ else:
+ field_initial = raw_initial or ''
+
+ self.fields[field.name] = forms.CharField(
+ initial = field_initial,
+ required = False,
+ label = field.name.replace("_", " ").capitalize(),
+ help_text = help_text or 'Comma-separated list.',
+ )
+ return
+
def clean(self):
cleaned = super().clean()
- # Rejoin multi-select lists back into CSV so consumers
- # (the dataclass build path) see the same shape regardless
- # of widget choice.
- for name in self._csv_choice_field_names:
+ # Coerce multi-value fields to the shape the dataclass expects.
+ # A ``list``-typed field becomes a list; a ``str``-typed
+ # csv_choices field (e.g. HomeBox attachment_keys) becomes a CSV
+ # string. The widget (checkbox vs text) is independent of the
+ # target shape. Must be idempotent: the view calls clean() again
+ # after is_valid() has already run it once, so each branch leaves
+ # an already-coerced value unchanged.
+ for name in ( self._csv_choice_field_names | self._list_field_names ):
value = cleaned.get( name )
- if isinstance( value, (list, tuple) ):
+ if name in self._list_field_names:
+ # Target shape: list. From the text widget it is a CSV
+ # string; from the checkbox widget it is already a list.
+ if isinstance( value, str ):
+ cleaned[name] = [
+ token.strip() for token in value.split(',') if token.strip()
+ ]
+ elif isinstance( value, (list, tuple) ):
+ cleaned[name] = list( value )
+ elif isinstance( value, (list, tuple) ):
+ # str-typed csv_choices field: join the selection to CSV
+ # (already a string on a second pass -> left untouched).
cleaned[name] = ','.join( value )
return cleaned
diff --git a/src/hi/simulator/services/frigate/api/views.py b/src/hi/simulator/services/frigate/api/views.py
index 313a5ac8..e3986ee2 100644
--- a/src/hi/simulator/services/frigate/api/views.py
+++ b/src/hi/simulator/services/frigate/api/views.py
@@ -13,8 +13,10 @@ from django.http import FileResponse, Http404, HttpResponse, JsonResponse
from django.views.generic import View
from hi.simulator.media import render_jpeg_frame
+from hi.simulator.services.frigate.event_history import camera_name_from_event_id
from hi.simulator.services.frigate.event_manager import FrigateSimEventManager
from hi.simulator.services.frigate.simulator import FrigateSimulator
+from hi.simulator.video_playback.video_clip_manager import VideoClipManager
# Pre-generated short MP4 (~14 KB, H.264 baseline) ships alongside
@@ -38,6 +40,25 @@ def _apply_no_cache_headers( response ) -> None:
return
+def _find_sim_camera( camera_name : str ):
+ for sim_camera in FrigateSimulator().get_sim_cameras():
+ if sim_camera.camera_name == camera_name:
+ return sim_camera
+ continue
+ return None
+
+
+def _find_sim_camera_for_event( event_id : str ):
+ """Resolve the camera for an event-media request from the event id alone
+ (the id encodes the camera name), so it works even for historical events
+ the ephemeral event manager no longer holds. None when the id predates the
+ camera-encoded format or the camera no longer exists."""
+ camera_name = camera_name_from_event_id( event_id )
+ if camera_name is None:
+ return None
+ return _find_sim_camera( camera_name = camera_name )
+
+
class ConfigView( View ):
"""``GET /api/config`` — Frigate's effective configuration.
@@ -125,45 +146,49 @@ class CameraLatestJpegView( View ):
inside HI are obviously coming from the simulator."""
def get(self, request, camera_name : str, *args, **kwargs):
- text_lines = [ 'Live Snapshot (simulator)' ]
- sim_camera = self._find_sim_camera( camera_name = camera_name )
- if sim_camera is None:
- text_lines.append( f'camera "{camera_name}" (no record)' )
- else:
- text_lines.append( f'camera: {sim_camera.display_name}' )
- text_lines.append( f'name: {sim_camera.camera_name}' )
- response = HttpResponse(
- render_jpeg_frame( text_lines = text_lines ),
- content_type = 'image/jpeg',
- )
+ sim_camera = _find_sim_camera( camera_name = camera_name )
+
+ # Serve a frame from the selected live clip; fall through to the
+ # synthesized placeholder when "synthetic" (or the clip is missing).
+ frame_bytes = None
+ if sim_camera is not None:
+ frame_bytes = VideoClipManager().live_frame_bytes( sim_camera.live_clip )
+ if frame_bytes is None:
+ text_lines = [ 'Live Snapshot (simulator)' ]
+ if sim_camera is None:
+ text_lines.append( f'camera "{camera_name}" (no record)' )
+ else:
+ text_lines.append( f'camera: {sim_camera.display_name}' )
+ text_lines.append( f'name: {sim_camera.camera_name}' )
+ frame_bytes = render_jpeg_frame( text_lines = text_lines )
+
+ response = HttpResponse( frame_bytes, content_type = 'image/jpeg' )
_apply_no_cache_headers( response )
return response
- @staticmethod
- def _find_sim_camera( camera_name : str ):
- for sim_camera in FrigateSimulator().get_sim_cameras():
- if sim_camera.camera_name == camera_name:
- return sim_camera
- continue
- return None
-
class EventClipMp4View( View ):
"""``GET /api/events/<id>/clip.mp4`` — event clip playback.
- Real Frigate streams an MP4 of the event's clip. The simulator
- serves a fixed-content placeholder MP4 (frame-counter + clock
- overlay) so HI's Video Browse can demonstrate the round-trip
- without runtime media synthesis. 404s for unknown event ids."""
+ Serves the pre-rendered ``clip.mp4`` of the event camera's selected
+ ``event_clip`` (built offline by the import tool — no runtime transcoding).
+ Falls back to the fixed-content placeholder MP4 when the clip has no mp4,
+ the selection is ``synthetic``, or the event is unknown.
+
+ Unknown event ids are NOT 404'd: HI history/alarms persist and can
+ reference events the (ephemeral, in-memory) simulator no longer has after
+ a restart, and a 404 here renders as an unplayable ``<video>`` ("No video
+ with supported format")."""
def get(self, request, event_id : str, *args, **kwargs):
- event = FrigateSimEventManager().find_event_by_id( event_id = event_id )
- if event is None:
- raise Http404( f'Unknown Frigate event id: {event_id!r}' )
- response = FileResponse(
- open( _EVENT_PLAYBACK_MP4_PATH, 'rb' ),
- content_type = 'video/mp4',
- )
+ mp4_path = None
+ sim_camera = _find_sim_camera_for_event( event_id )
+ if sim_camera is not None:
+ mp4_path = VideoClipManager().clip_mp4_path( sim_camera.event_clip )
+ if mp4_path is None:
+ mp4_path = _EVENT_PLAYBACK_MP4_PATH
+
+ response = FileResponse( open( mp4_path, 'rb' ), content_type = 'video/mp4' )
_apply_no_cache_headers( response )
return response
@@ -175,26 +200,25 @@ class EventSnapshotJpegView( View ):
detection. HI's Frigate gateway builds this URL on demand from
the event id (the SensorResponse carries the existence flag
``has_event_video_snapshot``) so the alert / history views can
- show what the camera saw. The simulator returns a placeholder
- JPEG stamped with the event id and label.
+ show what the camera saw.
- 404s for unknown event ids so the HI client distinguishes "event
- missing" from "simulator broken" — same posture as ``GET
- /api/events/<id>``."""
+ Unknown event ids are NOT 404'd (a 404 renders as a broken ``<img>``):
+ HI history/alarms persist and can reference events the (ephemeral,
+ in-memory) simulator no longer has after a restart. Serve the event
+ camera's selected event-clip frame when the event is known; otherwise a
+ placeholder."""
def get(self, request, event_id : str, *args, **kwargs):
- event = FrigateSimEventManager().find_event_by_id( event_id = event_id )
- if event is None:
- raise Http404( f'Unknown Frigate event id: {event_id!r}' )
- text_lines = [
- 'Event Snapshot (simulator)',
- f'camera: {event.camera_name}',
- f'event id: {event.event_id}',
- f'label: {event.label}',
- ]
- response = HttpResponse(
- render_jpeg_frame( text_lines = text_lines ),
- content_type = 'image/jpeg',
- )
+ frame_bytes = None
+ sim_camera = _find_sim_camera_for_event( event_id )
+ if sim_camera is not None:
+ frame_bytes = VideoClipManager().event_frame_bytes( sim_camera.event_clip )
+ if frame_bytes is None:
+ frame_bytes = render_jpeg_frame( text_lines = [
+ 'Event Snapshot (simulator)',
+ f'event id: {event_id}',
+ ] )
+
+ response = HttpResponse( frame_bytes, content_type = 'image/jpeg' )
_apply_no_cache_headers( response )
return response
diff --git a/src/hi/simulator/services/frigate/event_history.py b/src/hi/simulator/services/frigate/event_history.py
index 0ed0235a..44e3235f 100644
--- a/src/hi/simulator/services/frigate/event_history.py
+++ b/src/hi/simulator/services/frigate/event_history.py
@@ -3,6 +3,7 @@
Per-camera ring buffer of events. Events are synthesized from the
operator's ObjectPresence sim-state changes — no DB row, no CRUD UI.
"""
+import re
from collections import deque
from datetime import datetime
from typing import Callable, List, Optional
@@ -12,6 +13,25 @@ import hi.apps.common.datetimeproxy as datetimeproxy
from .sim_models import FrigateSimCamera, FrigateSimEvent
+# Simulator event ids encode the camera name so the event-media endpoints
+# (clip.mp4 / snapshot.jpg) — which receive only an event id — can resolve the
+# camera, and thus its selected clip, even for historical events the ephemeral
+# in-memory manager no longer holds (e.g. after a restart). Real Frigate ids
+# are opaque, so any unique, URL-safe format is fine. Format is
+# ``<camera_name>-<sequence>``; decoding peels the trailing ``-<digits>``, so a
+# camera name containing ``-`` (or even a trailing ``-<digits>``) round-trips.
+_EVENT_ID_RE = re.compile( r'^(?P<camera_name>.+)-(?P<sequence>\d+)$' )
+
+
+def make_event_id( camera_name : str, sequence : str ) -> str:
+ return f'{camera_name}-{sequence}'
+
+
+def camera_name_from_event_id( event_id : str ) -> Optional[ str ]:
+ match = _EVENT_ID_RE.match( event_id or '' )
+ return match.group( 'camera_name' ) if match else None
+
+
class FrigateSimEventHistory:
"""Per-camera ring buffer of events.
@@ -65,7 +85,10 @@ class FrigateSimEventHistory:
def _open_event( self, object_label : str ) -> FrigateSimEvent:
event = FrigateSimEvent(
- event_id = self._event_id_allocator(),
+ event_id = make_event_id(
+ self._frigate_sim_camera.camera_name,
+ self._event_id_allocator(),
+ ),
camera_name = self._frigate_sim_camera.camera_name,
label = object_label,
start_datetime = datetimeproxy.now(),
diff --git a/src/hi/simulator/services/frigate/sim_models.py b/src/hi/simulator/services/frigate/sim_models.py
index 92b89bc1..081efd63 100644
--- a/src/hi/simulator/services/frigate/sim_models.py
+++ b/src/hi/simulator/services/frigate/sim_models.py
@@ -20,6 +20,11 @@ from hi.simulator.services.base_models import (
)
from hi.simulator.services.enums import SimEntityType, SimStateType
from hi.simulator.services.sim_entity import SimEntity
+from hi.simulator.video_playback.sim_states import (
+ CameraEventClipState,
+ CameraLiveClipState,
+)
+from hi.simulator.video_playback.video_clip_manager import SYNTHETIC_CLIP_VALUE
@dataclass( frozen = True )
@@ -115,6 +120,21 @@ class FrigateSimCamera:
f'No object-presence sim state for Frigate camera {self.sim_entity}'
)
+ @property
+ def live_clip(self) -> str:
+ return self._clip_value( CameraLiveClipState )
+
+ @property
+ def event_clip(self) -> str:
+ return self._clip_value( CameraEventClipState )
+
+ def _clip_value(self, sim_state_class) -> str:
+ for sim_state in self.sim_entity.sim_state_list:
+ if isinstance( sim_state, sim_state_class ):
+ return sim_state.value
+ continue
+ return SYNTHETIC_CLIP_VALUE
+
@dataclass
class FrigateSimEvent:
@@ -181,6 +201,8 @@ FRIGATE_SIM_ENTITY_DEFINITION_LIST: List[ SimEntityDefinition ] = [
sim_entity_fields_class = FrigateCameraSimEntityFields,
sim_state_class_list = [
FrigateCameraObjectPresenceState,
+ CameraLiveClipState,
+ CameraEventClipState,
],
),
]
diff --git a/src/hi/simulator/services/hass/sim_models.py b/src/hi/simulator/services/hass/sim_models.py
index 1d9ad4ec..76849ed0 100644
--- a/src/hi/simulator/services/hass/sim_models.py
+++ b/src/hi/simulator/services/hass/sim_models.py
@@ -179,7 +179,8 @@ class HassInsteonDimmerLightLightState( HassInsteonState ):
# HASS-imported dimmers.
sim_state_type : SimStateType = SimStateType.CONTINUOUS
sim_state_id : str = 'light'
- value : str = '255'
+ # Default off (brightness 0); operator raises it via the slider.
+ value : str = '0'
@property
def min_value(self):
@@ -428,7 +429,8 @@ class HassSmartBulbState( HassState ):
sim_entity_fields : HassSmartBulbFields
sim_state_type : SimStateType = SimStateType.CONTINUOUS
sim_state_id : str = 'light'
- value : str = '255'
+ # Default off (brightness 0); operator raises it via the slider.
+ value : str = '0'
@property
def min_value(self):
@@ -489,7 +491,8 @@ class HassColorSmartBulbBrightnessState( HassState ):
sim_entity_fields : HassColorSmartBulbFields
sim_state_type : SimStateType = SimStateType.CONTINUOUS
sim_state_id : str = 'brightness'
- value : str = '255'
+ # Default off (brightness 0); operator raises it via the slider.
+ value : str = '0'
@property
def min_value(self):
@@ -2427,6 +2430,38 @@ _THERMOSTAT_HVAC_ACTION_CHOICES = [
]
+# Closed value sets for the multi-axis thermostat's mode lists. Rendered as
+# checkbox pickers in the simulator edit form (via the ``csv_choices`` hook);
+# the dataclass fields stay plain lists of the selected wire values.
+HASS_HVAC_MODE_CHOICES = [
+ ( 'off', 'Off' ),
+ ( 'heat', 'Heat' ),
+ ( 'cool', 'Cool' ),
+ ( 'heat_cool', 'Heat/Cool' ),
+ ( 'auto', 'Auto' ),
+ ( 'dry', 'Dry' ),
+ ( 'fan_only', 'Fan only' ),
+]
+HASS_FAN_MODE_CHOICES = [
+ ( 'auto', 'Auto' ),
+ ( 'low', 'Low' ),
+ ( 'medium', 'Medium' ),
+ ( 'high', 'High' ),
+ ( 'on', 'On' ),
+ ( 'off', 'Off' ),
+]
+HASS_PRESET_MODE_CHOICES = [
+ ( 'none', 'None' ),
+ ( 'eco', 'Eco' ),
+ ( 'away', 'Away' ),
+ ( 'home', 'Home' ),
+ ( 'sleep', 'Sleep' ),
+ ( 'comfort', 'Comfort' ),
+ ( 'boost', 'Boost' ),
+ ( 'activity', 'Activity' ),
+]
+
+
@dataclass( frozen = True )
class HassThermostatFields( SimEntityFields ):
"""A multi-axis thermostat. Composed of multiple SimStates
@@ -2446,12 +2481,24 @@ class HassThermostatFields( SimEntityFields ):
hvac_modes : list = field(
default_factory = lambda : [ 'heat', 'cool', 'heat_cool', 'off' ],
+ metadata = {
+ 'csv_choices': HASS_HVAC_MODE_CHOICES,
+ 'help_text': 'HVAC modes this thermostat exposes.',
+ },
)
fan_modes : list = field(
default_factory = lambda : [ 'auto', 'low', 'medium', 'high' ],
+ metadata = {
+ 'csv_choices': HASS_FAN_MODE_CHOICES,
+ 'help_text': 'Fan modes (leave empty to omit the fan-mode axis).',
+ },
)
preset_modes : list = field(
default_factory = lambda : [ 'eco', 'away', 'home', 'sleep' ],
+ metadata = {
+ 'csv_choices': HASS_PRESET_MODE_CHOICES,
+ 'help_text': 'Preset modes this thermostat exposes.',
+ },
)
temperature_unit : str = '°F'
diff --git a/src/hi/simulator/services/service_simulator_manager.py b/src/hi/simulator/services/service_simulator_manager.py
index 964276b3..c23c69bc 100644
--- a/src/hi/simulator/services/service_simulator_manager.py
+++ b/src/hi/simulator/services/service_simulator_manager.py
@@ -48,6 +48,13 @@ class ServiceSimulatorManager( Singleton ):
simulator_data_list.sort( key = lambda item : item.simulator.label )
return simulator_data_list
+ def reset_all_to_defaults( self ):
+ """Re-hydrate every simulator to its current profile's defaults. Sim
+ state values aren't persisted, so a reload resets them — used by the
+ Scenes 'Clear States' action to start a fresh sequence run clean."""
+ self._load_entities_for_all_simulators()
+ return
+
def add_sim_entity( self,
simulator : ServiceSimulator,
sim_entity_definition : SimEntityDefinition,
diff --git a/src/hi/simulator/services/templates/services/panes/sim_state.html b/src/hi/simulator/services/templates/services/panes/sim_state.html
index 28d4ed73..adb416c5 100644
--- a/src/hi/simulator/services/templates/services/panes/sim_state.html
+++ b/src/hi/simulator/services/templates/services/panes/sim_state.html
@@ -1,7 +1,7 @@
{% 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 }}
+ {{ label|default: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 %}"
diff --git a/src/hi/simulator/services/views.py b/src/hi/simulator/services/views.py
index 0b8c1ac8..d7d0a84e 100644
--- a/src/hi/simulator/services/views.py
+++ b/src/hi/simulator/services/views.py
@@ -1,3 +1,5 @@
+import logging
+
from django.core.exceptions import BadRequest
from django.http import Http404, HttpResponseRedirect, JsonResponse
from django.shortcuts import render
@@ -17,6 +19,8 @@ from .service_simulator_manager import ServiceSimulatorManager
from .sim_entity import SimEntity
from hi.simulator.services.view_mixins import ServiceSimulatorViewMixin
+logger = logging.getLogger(__name__)
+
def _build_service_tab_specs( active_simulator_id : str ):
"""Tab strip data for the Services section. Each entry routes to
@@ -325,8 +329,31 @@ class SimStateSetView( View, ServiceSimulatorViewMixin ):
sim_state_id = sim_state_id,
value_str = value_str,
)
+ self._record_if_active( simulator, sim_entity_id, sim_state_id, value_str )
context = {
'simulator': simulator,
'sim_state': sim_state,
}
return render( request, self.TEMPLATE_NAME, context )
+
+ def _record_if_active( self, simulator, sim_entity_id, sim_state_id, value_str ):
+ """Append this operator state change to the active scene recording,
+ if any. Lazy import keeps the services app decoupled from scenes."""
+ from hi.simulator.scenes.recorder import SimRecorder
+ recorder = SimRecorder()
+ if not recorder.is_recording():
+ return
+ try:
+ entity_name = simulator.get_sim_entity_by_id(
+ sim_entity_id = sim_entity_id,
+ ).name
+ except Exception:
+ logger.exception( 'Recorder: failed to resolve entity for capture.' )
+ return
+ recorder.record_step(
+ module_key = simulator.module_key,
+ entity_name = entity_name,
+ sim_state_id = sim_state_id,
+ value_str = value_str,
+ )
+ return
diff --git a/src/hi/simulator/services/zoneminder/sim_models.py b/src/hi/simulator/services/zoneminder/sim_models.py
index 775ac772..26ea19f0 100644
--- a/src/hi/simulator/services/zoneminder/sim_models.py
+++ b/src/hi/simulator/services/zoneminder/sim_models.py
@@ -6,6 +6,11 @@ import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.common.utils import str_to_bool
from hi.simulator.services.base_models import SimEntityFields, SimState, SimEntityDefinition
+from hi.simulator.video_playback.sim_states import (
+ CameraEventClipState,
+ CameraLiveClipState,
+)
+from hi.simulator.video_playback.video_clip_manager import SYNTHETIC_CLIP_VALUE
from hi.simulator.services.enums import SimEntityType, SimStateType
from hi.simulator.services.sim_entity import SimEntity
@@ -135,7 +140,23 @@ class ZmSimMonitor:
return sim_state
continue
raise ValueError( f'No motion sim state for ZM monitor {self.sim_entity}' )
-
+
+ @property
+ def live_clip(self) -> str:
+ return self._clip_value( CameraLiveClipState )
+
+ @property
+ def event_clip(self) -> str:
+ return self._clip_value( CameraEventClipState )
+
+ def _clip_value(self, sim_state_class) -> str:
+ for sim_state in self.sim_entity.sim_state_list:
+ if isinstance( sim_state, sim_state_class ):
+ return sim_state.value
+ continue
+ return SYNTHETIC_CLIP_VALUE
+
+
def to_api_dict(self):
fields = self.sim_entity.sim_entity_fields
@@ -421,6 +442,8 @@ ZONEMINDER_SIM_ENTITY_DEFINITION_LIST = [
sim_state_class_list = [
ZmMonitorFunctionState,
ZmMonitorMotionState,
+ CameraLiveClipState,
+ CameraEventClipState,
],
),
SimEntityDefinition(
diff --git a/src/hi/simulator/services/zoneminder/views.py b/src/hi/simulator/services/zoneminder/views.py
index 021b9417..c6211830 100644
--- a/src/hi/simulator/services/zoneminder/views.py
+++ b/src/hi/simulator/services/zoneminder/views.py
@@ -20,14 +20,28 @@ long-lived streams open against Django's dev server.
from django.http import HttpResponse, StreamingHttpResponse
from django.views.generic import View
+from hi.simulator.video_playback.video_clip_manager import VideoClipManager
+
from .simulator import ZoneMinderSimulator
+from .zm_event_history import monitor_id_from_event_id
from .zm_event_manager import ZmSimEventManager
from .zm_media import (
iter_bounded_mjpeg_parts,
+ iter_mjpeg_parts_from_frames,
mjpeg_content_type,
render_thumbnail_jpeg,
)
+# Bounded live-feed window (frames) served from a pre-canned clip's current
+# wall-clock position; advances on each reconnect. Keeps the MJPEG short.
+_LIVE_CLIP_FRAME_COUNT = 25
+
+# Inter-frame delay for real-footage MJPEG (live + event), matching the clip's
+# render rate so the streams play at the same speed as clip.mp4 / latest.jpg
+# (the synthesized placeholder stream keeps its own slower, counter-readable
+# cadence).
+_CLIP_FRAME_INTERVAL = 1.0 / VideoClipManager.VIDEO_FPS
+
class HomeView( View ):
@@ -95,6 +109,7 @@ class NphZmsView( View ):
def _monitor_snapshot_response( self, monitor_id_str : str ) -> HttpResponse:
text_lines = [ 'Monitor Snapshot (simulator)' ]
+ frame_bytes = None
try:
monitor_id = int( monitor_id_str )
except ValueError:
@@ -106,34 +121,32 @@ class NphZmsView( View ):
if zm_sim_monitor is None:
text_lines.append( f'monitor {monitor_id} (no record)' )
else:
+ frame_bytes = VideoClipManager().live_frame_bytes( zm_sim_monitor.live_clip )
text_lines.append( f'monitor: {zm_sim_monitor.name}' )
text_lines.append( f'id: {monitor_id}' )
- response = HttpResponse(
- render_thumbnail_jpeg( text_lines = text_lines ),
- content_type = 'image/jpeg',
- )
+ if frame_bytes is None:
+ frame_bytes = render_thumbnail_jpeg( text_lines = text_lines )
+ response = HttpResponse( frame_bytes, content_type = 'image/jpeg' )
_apply_no_cache_headers( response )
return response
def _event_snapshot_response( self, event_id_str : str ) -> HttpResponse:
text_lines = [ 'Event Snapshot (simulator)' ]
+ frame_bytes = None
try:
event_id = int( event_id_str )
except ValueError:
text_lines.append( f'unknown event "{event_id_str}"' )
else:
- zm_sim_event = ZmSimEventManager().find_event_by_id( event_id = event_id )
- if zm_sim_event is None:
- text_lines.append( f'event {event_id} (no record)' )
- else:
- text_lines.append(
- f'monitor: {zm_sim_event.zm_sim_monitor.name}',
+ zm_sim_monitor = _find_zm_monitor_for_event( event_id )
+ if zm_sim_monitor is not None:
+ frame_bytes = VideoClipManager().event_frame_bytes(
+ zm_sim_monitor.event_clip,
)
- text_lines.append( f'event id: {event_id}' )
- response = HttpResponse(
- render_thumbnail_jpeg( text_lines = text_lines ),
- content_type = 'image/jpeg',
- )
+ text_lines.append( f'event id: {event_id}' )
+ if frame_bytes is None:
+ frame_bytes = render_thumbnail_jpeg( text_lines = text_lines )
+ response = HttpResponse( frame_bytes, content_type = 'image/jpeg' )
_apply_no_cache_headers( response )
return response
@@ -146,14 +159,18 @@ class NphZmsView( View ):
except ValueError:
text_lines.append( f'unknown event "{event_id_str}"' )
else:
- zm_sim_event = ZmSimEventManager().find_event_by_id( event_id = event_id )
- if zm_sim_event is None:
- text_lines.append( f'event {event_id} (no record)' )
- else:
- text_lines.append(
- f'monitor: {zm_sim_event.zm_sim_monitor.name}',
+ zm_sim_monitor = _find_zm_monitor_for_event( event_id )
+ if ( zm_sim_monitor is not None
+ and VideoClipManager().has_clip_frames( zm_sim_monitor.event_clip )):
+ # Play the selected event clip's frames as MJPEG.
+ return _streaming_clip_response(
+ VideoClipManager().clip_frame_iter( zm_sim_monitor.event_clip )
)
- text_lines.append( f'event id: {event_id}' )
+ text_lines.append( f'event id: {event_id}' )
+ # No clip selected — fall back to the synthesized stream, with
+ # event-time interpolation when the event is still in the manager.
+ zm_sim_event = ZmSimEventManager().find_event_by_id( event_id = event_id )
+ if zm_sim_event is not None:
playback_start = zm_sim_event.start_datetime
# ``length_secs`` is an event-driven value the
# simulator updates as the event is closed; it can
@@ -182,6 +199,13 @@ class NphZmsView( View ):
)
if zm_sim_monitor is None:
text_lines.append( f'monitor {monitor_id} (no record)' )
+ elif VideoClipManager().has_clip_frames( zm_sim_monitor.live_clip ):
+ # Stream a bounded window of the selected live clip's frames.
+ return _streaming_clip_response(
+ VideoClipManager().live_frame_iter(
+ zm_sim_monitor.live_clip, _LIVE_CLIP_FRAME_COUNT,
+ )
+ )
else:
text_lines.append( f'monitor: {zm_sim_monitor.name}' )
text_lines.append( f'id: {monitor_id}' )
@@ -215,6 +239,17 @@ def _streaming_mjpeg_response(
return response
+def _streaming_clip_response( jpeg_frames ) -> StreamingHttpResponse:
+ """Streaming MJPEG response built from real pre-canned clip frames, with the
+ same cache-busting headers as the synthesized stream."""
+ response = StreamingHttpResponse(
+ iter_mjpeg_parts_from_frames( jpeg_frames, frame_interval = _CLIP_FRAME_INTERVAL ),
+ content_type = mjpeg_content_type(),
+ )
+ _apply_no_cache_headers( response )
+ return response
+
+
def _apply_no_cache_headers( response ) -> None:
response['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'
response['Pragma'] = 'no-cache'
@@ -222,9 +257,18 @@ def _apply_no_cache_headers( response ) -> None:
return
+def _find_zm_monitor_for_event( event_id : int ):
+ """Resolve the monitor for an event-media request from the event id alone
+ (the id encodes the monitor id), independent of the ephemeral event
+ manager. None when no such monitor exists (e.g. a legacy/pre-encoding id)."""
+ monitor_id = monitor_id_from_event_id( event_id )
+ return ZoneMinderSimulator().find_zm_monitor_by_id( monitor_id = monitor_id )
+
+
def _event_image_response( request ) -> HttpResponse:
event_id_str = request.GET.get( 'eid' )
text_lines = [ 'Event Snapshot (simulator)' ]
+ frame_bytes = None
try:
event_id = int( event_id_str ) if event_id_str else None
except ValueError:
@@ -232,15 +276,14 @@ def _event_image_response( request ) -> HttpResponse:
if event_id is None:
text_lines.append( f'unknown event "{event_id_str}"' )
else:
- zm_sim_event = ZmSimEventManager().find_event_by_id( event_id = event_id )
- if zm_sim_event is None:
- text_lines.append( f'event {event_id} (no record)' )
- else:
- text_lines.append( f'monitor: {zm_sim_event.zm_sim_monitor.name}' )
- text_lines.append( f'event id: {event_id}' )
- response = HttpResponse(
- render_thumbnail_jpeg( text_lines = text_lines ),
- content_type = 'image/jpeg',
- )
+ zm_sim_monitor = _find_zm_monitor_for_event( event_id )
+ if zm_sim_monitor is not None:
+ frame_bytes = VideoClipManager().event_frame_bytes(
+ zm_sim_monitor.event_clip,
+ )
+ text_lines.append( f'event id: {event_id}' )
+ if frame_bytes is None:
+ frame_bytes = render_thumbnail_jpeg( text_lines = text_lines )
+ response = HttpResponse( frame_bytes, content_type = 'image/jpeg' )
_apply_no_cache_headers( response )
return response
diff --git a/src/hi/simulator/services/zoneminder/zm_event_history.py b/src/hi/simulator/services/zoneminder/zm_event_history.py
index 4f5d223b..3525bfbe 100644
--- a/src/hi/simulator/services/zoneminder/zm_event_history.py
+++ b/src/hi/simulator/services/zoneminder/zm_event_history.py
@@ -7,6 +7,23 @@ import hi.apps.common.datetimeproxy as datetimeproxy
from .sim_models import ZmSimEvent, ZmSimMonitor
+# Encode the monitor id into the (integer, native-ZM) event id so the
+# event-media endpoints — which receive only an event id — can resolve the
+# monitor, and thus its selected clip, even for historical events the ephemeral
+# in-memory manager no longer holds. ``monitor_id * STRIDE + sequence`` keeps
+# the id a plain integer (real ZM ids are integers; HI treats them opaquely and
+# orders events by time, not id). Assumes < STRIDE events per simulator session.
+_EVENT_ID_MONITOR_STRIDE = 1_000_000
+
+
+def make_event_id( monitor_id : int, sequence : int ) -> int:
+ return monitor_id * _EVENT_ID_MONITOR_STRIDE + sequence
+
+
+def monitor_id_from_event_id( event_id : int ) -> int:
+ return event_id // _EVENT_ID_MONITOR_STRIDE
+
+
class ZmSimEventHistory:
def __init__( self,
@@ -40,7 +57,10 @@ class ZmSimEventHistory:
return latest_zm_sim_event
def add_zm_sim_event( self ) -> ZmSimEvent:
- event_id = self._event_id_allocator()
+ event_id = make_event_id(
+ self._zm_sim_monitor.monitor_id,
+ self._event_id_allocator(),
+ )
zm_sim_event = ZmSimEvent(
zm_sim_monitor = self._zm_sim_monitor,
event_id = event_id,
diff --git a/src/hi/simulator/services/zoneminder/zm_media.py b/src/hi/simulator/services/zoneminder/zm_media.py
index 8a0bb55f..bd3c1267 100644
--- a/src/hi/simulator/services/zoneminder/zm_media.py
+++ b/src/hi/simulator/services/zoneminder/zm_media.py
@@ -67,6 +67,32 @@ def mjpeg_content_type() -> str:
)
+def _mjpeg_part( jpeg_bytes : bytes ) -> bytes:
+ """One ``multipart/x-mixed-replace`` chunk wrapping a JPEG frame."""
+ return (
+ b'--' + _MJPEG_BOUNDARY + b'\r\n'
+ + b'Content-Type: image/jpeg\r\n'
+ + f'Content-Length: {len(jpeg_bytes)}\r\n\r\n'.encode( 'latin-1' )
+ + jpeg_bytes
+ + b'\r\n'
+ )
+
+
+def iter_mjpeg_parts_from_frames(
+ jpeg_frames : Iterator[ bytes ],
+ frame_interval : float = _DEFAULT_FRAME_INTERVAL_SECS,
+) -> Iterator[ bytes ]:
+ """Bounded MJPEG from pre-rendered JPEG frames (real pre-canned footage),
+ sleeping between frames so the browser animates rather than collapsing to
+ the last frame. Mirrors ``iter_bounded_mjpeg_parts`` but serves given
+ frames instead of synthesized placeholders."""
+ for jpeg_bytes in jpeg_frames:
+ yield _mjpeg_part( jpeg_bytes )
+ time.sleep( frame_interval )
+ continue
+ yield b'--' + _MJPEG_BOUNDARY + b'--\r\n'
+
+
def iter_bounded_mjpeg_parts(
text_lines : List[str],
frame_count : int = _DEFAULT_FRAME_COUNT,
@@ -92,7 +118,6 @@ def iter_bounded_mjpeg_parts(
closes naturally after the last frame so we don't hold an
open-ended live feed against the Django dev server.
"""
- boundary = _MJPEG_BOUNDARY
for index in range( frame_count ):
frame_text = list( text_lines ) + [
f'frame {index + 1}/{frame_count}',
@@ -106,20 +131,14 @@ def iter_bounded_mjpeg_parts(
frame_count = frame_count,
),
)
- part = (
- b'--' + boundary + b'\r\n'
- + b'Content-Type: image/jpeg\r\n'
- + f'Content-Length: {len(jpeg_bytes)}\r\n\r\n'.encode( 'latin-1' )
- + jpeg_bytes
- + b'\r\n'
- )
- yield part
+ yield _mjpeg_part( jpeg_bytes )
# Sleep AFTER yielding the frame so the browser sees a
# cadence between frames; the final frame still gets
# displayed for ``frame_interval`` before the closing
# boundary tells the browser the stream has ended.
time.sleep( frame_interval )
- yield b'--' + boundary + b'--\r\n'
+ continue
+ yield b'--' + _MJPEG_BOUNDARY + b'--\r\n'
def _interpolated_frame_time(
diff --git a/src/hi/simulator/templates/simulator/pages/base.html b/src/hi/simulator/templates/simulator/pages/base.html
index 1bd4cf45..8539769d 100644
--- a/src/hi/simulator/templates/simulator/pages/base.html
+++ b/src/hi/simulator/templates/simulator/pages/base.html
@@ -25,6 +25,8 @@
<script type="text/javascript" src="{% static 'js/antinode.js' %}" charset="utf-8"></script>
<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>
+ <script type="text/javascript" src="{% static 'js/scene_timeline.js' %}" charset="utf-8"></script>
+ <script type="text/javascript" src="{% static 'js/scene_status.js' %}" charset="utf-8"></script>
{% include "simulator/panes/top_nav.html" %}
diff --git a/src/hi/simulator/templates/simulator/panes/top_nav.html b/src/hi/simulator/templates/simulator/panes/top_nav.html
index 54fc9228..33cc6309 100644
--- a/src/hi/simulator/templates/simulator/panes/top_nav.html
+++ b/src/hi/simulator/templates/simulator/panes/top_nav.html
@@ -17,6 +17,12 @@
Weather
</a>
</li>
+ <li>
+ <a href="{% url 'simulator_scenes' %}"
+ class="sim-top-nav-link {% if active_section == 'scenes' %}active{% endif %}">
+ Scenes
+ </a>
+ </li>
<li>
<a href="{% url 'simulator_settings' %}"
class="sim-top-nav-link {% if active_section == 'settings' %}active{% endif %}">
diff --git a/src/hi/simulator/urls.py b/src/hi/simulator/urls.py
index 0f75334b..4b20f296 100644
--- a/src/hi/simulator/urls.py
+++ b/src/hi/simulator/urls.py
@@ -12,6 +12,7 @@ urlpatterns = [
path( 'services/', include( 'hi.simulator.services.urls' )),
path( 'weather/', include( 'hi.simulator.weather_sources.urls' )),
+ path( 'scenes/', include( 'hi.simulator.scenes.urls' )),
path( 'settings/', include( 'hi.simulator.settings.urls' )),
path( 'profile/', include( 'hi.simulator.profile.urls' )),
]
diff --git a/src/hi/simulator/video_playback/__init__.py b/src/hi/simulator/video_playback/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/simulator/video_playback/apps.py b/src/hi/simulator/video_playback/apps.py
new file mode 100644
index 00000000..3cd0b199
--- /dev/null
+++ b/src/hi/simulator/video_playback/apps.py
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class VideoPlaybackConfig( AppConfig ):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'hi.simulator.video_playback'
+ label = 'simulator_video_playback'
diff --git a/src/hi/simulator/video_playback/sim_states.py b/src/hi/simulator/video_playback/sim_states.py
new file mode 100644
index 00000000..38ffe59f
--- /dev/null
+++ b/src/hi/simulator/video_playback/sim_states.py
@@ -0,0 +1,57 @@
+"""Platform-neutral camera sim_states for pre-canned footage.
+
+A camera's live feed and event feed each select a clip by name. These are plain
+DISCRETE sim_states (choices from the ``VideoClipManager`` pool, default
+``synthetic`` = today's placeholder), so they record/replay in a scenario like
+any other state. Shared by the Frigate and ZoneMinder camera definitions so the
+two platforms expose an identical clip-selection control.
+"""
+from dataclasses import dataclass
+from typing import ClassVar, List, Tuple
+
+from hi.simulator.services.base_models import SimEntityFields, SimState
+from hi.simulator.services.enums import SimStateType
+
+from .video_clip_manager import SYNTHETIC_CLIP_VALUE, VideoClipManager
+
+
+@dataclass
+class CameraLiveClipState( SimState ):
+ """Pre-canned clip backing a camera's live feed."""
+
+ LIVE_CLIP_SIM_STATE_ID : ClassVar[ str ] = 'live_clip'
+
+ sim_entity_fields : SimEntityFields
+ sim_state_type : SimStateType = SimStateType.DISCRETE
+ sim_state_id : str = LIVE_CLIP_SIM_STATE_ID
+ value : str = SYNTHETIC_CLIP_VALUE
+
+ @property
+ def name(self):
+ return 'Live Clip'
+
+ @property
+ def choices(self) -> List[ Tuple[ str, str ] ]:
+ return VideoClipManager().get_clip_choices()
+
+
+@dataclass
+class CameraEventClipState( SimState ):
+ """Pre-canned clip backing a camera's event snapshot/clip. Separate from the
+ live clip so a scenario can show the live scene and a matching event feed
+ independently."""
+
+ EVENT_CLIP_SIM_STATE_ID : ClassVar[ str ] = 'event_clip'
+
+ sim_entity_fields : SimEntityFields
+ sim_state_type : SimStateType = SimStateType.DISCRETE
+ sim_state_id : str = EVENT_CLIP_SIM_STATE_ID
+ value : str = SYNTHETIC_CLIP_VALUE
+
+ @property
+ def name(self):
+ return 'Event Clip'
+
+ @property
+ def choices(self) -> List[ Tuple[ str, str ] ]:
+ return VideoClipManager().get_clip_choices()
diff --git a/src/hi/simulator/video_playback/video_clip_manager.py b/src/hi/simulator/video_playback/video_clip_manager.py
new file mode 100644
index 00000000..8e49a3d5
--- /dev/null
+++ b/src/hi/simulator/video_playback/video_clip_manager.py
@@ -0,0 +1,160 @@
+"""Pre-canned camera footage: discovery + frame serving for the simulator.
+
+A clip is a directory of alphabetically-ordered JPEG frames under
+``settings.SIMULATOR_VIDEO_DIR``; the subdirectory names are the operator's
+``live_clip`` / ``event_clip`` choices. The clip set is scanned once per
+process (restart the simulator to pick up new clips); each clip's frame list is
+listed lazily and cached. Platform-neutral so the Frigate and ZoneMinder
+simulators serve from the identical source.
+"""
+import logging
+import os
+import time
+from typing import Dict, List, Optional, Tuple
+
+from django.conf import settings
+
+from hi.apps.common.singleton import Singleton
+
+logger = logging.getLogger(__name__)
+
+# Reserved value meaning "no clip selected — use the synthesized placeholder"
+# (today's behavior). Never a directory name.
+SYNTHETIC_CLIP_VALUE = 'synthetic'
+
+
+class VideoClipManager( Singleton ):
+
+ VIDEO_FPS = 5 # frames/sec for the looping live-feed illusion
+ _JPEG_EXTENSIONS = ( '.jpg', '.jpeg' )
+
+ def __init_singleton__( self ):
+ self._clip_names : Optional[ List[ str ] ] = None
+ self._frames_by_clip : Dict[ str, List[ str ] ] = {}
+ self._mp4_by_clip : Dict[ str, Optional[ str ] ] = {}
+ return
+
+ def get_clip_choices( self ) -> List[ Tuple[ str, str ] ]:
+ """Discrete-state choices: the synthetic placeholder plus every clip."""
+ choices = [ ( SYNTHETIC_CLIP_VALUE, 'Synthetic (placeholder)' ) ]
+ for clip_name in self.get_clip_names():
+ choices.append( ( clip_name, clip_name ) )
+ continue
+ return choices
+
+ def get_clip_names( self ) -> List[ str ]:
+ """Sorted clip (subdirectory) names, scanned once per process."""
+ if self._clip_names is None:
+ self._clip_names = self._scan_clip_names()
+ return self._clip_names
+
+ def live_frame_bytes( self, clip_name : str ) -> Optional[ bytes ]:
+ """Frame at the current wall-clock index (looping at VIDEO_FPS) — the
+ moving live-feed illusion. None when synthetic / missing / empty."""
+ frames = self._selectable_frames( clip_name )
+ if not frames:
+ return None
+ index = int( time.monotonic() * self.VIDEO_FPS ) % len( frames )
+ return self._read_frame( frames[ index ] )
+
+ def event_frame_bytes( self, clip_name : str ) -> Optional[ bytes ]:
+ """A single representative frame (the middle of the clip). None when
+ synthetic / missing / empty."""
+ frames = self._selectable_frames( clip_name )
+ if not frames:
+ return None
+ return self._read_frame( frames[ len( frames ) // 2 ] )
+
+ def has_clip_frames( self, clip_name : str ) -> bool:
+ return bool( self._selectable_frames( clip_name ))
+
+ def clip_mp4_path( self, clip_name : str ) -> Optional[ str ]:
+ """Path to the clip's pre-rendered MP4 (the single ``*.mp4`` in its
+ directory), or None when synthetic / missing / no mp4 present. Lets
+ Frigate's event-clip endpoint serve a pre-canned file directly — no
+ runtime transcoding; the mp4 is built offline by the import tool."""
+ if not clip_name or clip_name == SYNTHETIC_CLIP_VALUE:
+ return None
+ if clip_name not in self._mp4_by_clip:
+ self._mp4_by_clip[ clip_name ] = self._scan_clip_mp4( clip_name )
+ return self._mp4_by_clip[ clip_name ]
+
+ def _scan_clip_mp4( self, clip_name : str ) -> Optional[ str ]:
+ clip_dir = os.path.join( self._video_dir(), clip_name )
+ if not os.path.isdir( clip_dir ):
+ return None
+ mp4_paths = sorted(
+ os.path.join( clip_dir, entry )
+ for entry in os.listdir( clip_dir )
+ if entry.lower().endswith( '.mp4' )
+ )
+ return mp4_paths[ 0 ] if mp4_paths else None
+
+ def live_frame_iter( self, clip_name : str, count : int ):
+ """Yield ``count`` JPEG byte-frames starting at the current wall-clock
+ index, looping through the clip — a bounded live-feed window for the
+ ZoneMinder MJPEG stream. Yields nothing when synthetic / missing /
+ empty. Lazy (one frame read at a time), so it never holds the whole
+ clip in memory."""
+ frames = self._selectable_frames( clip_name )
+ if not frames:
+ return
+ start = int( time.monotonic() * self.VIDEO_FPS ) % len( frames )
+ for offset in range( count ):
+ data = self._read_frame( frames[ ( start + offset ) % len( frames ) ] )
+ if data is not None:
+ yield data
+ continue
+ return
+
+ def clip_frame_iter( self, clip_name : str ):
+ """Yield every frame of the clip once, in order (lazy) — for event
+ playback, which plays the whole event clip. Yields nothing when
+ synthetic / missing / empty."""
+ for path in self._selectable_frames( clip_name ):
+ data = self._read_frame( path )
+ if data is not None:
+ yield data
+ continue
+ return
+
+ def _selectable_frames( self, clip_name : str ) -> List[ str ]:
+ if not clip_name or clip_name == SYNTHETIC_CLIP_VALUE:
+ return []
+ if clip_name not in self._frames_by_clip:
+ self._frames_by_clip[ clip_name ] = self._scan_clip_frames( clip_name )
+ return self._frames_by_clip[ clip_name ]
+
+ def _scan_clip_names( self ) -> List[ str ]:
+ video_dir = self._video_dir()
+ if not video_dir or not os.path.isdir( video_dir ):
+ return []
+ names = [
+ entry for entry in os.listdir( video_dir )
+ if os.path.isdir( os.path.join( video_dir, entry ))
+ ]
+ names.sort()
+ return names
+
+ def _scan_clip_frames( self, clip_name : str ) -> List[ str ]:
+ clip_dir = os.path.join( self._video_dir(), clip_name )
+ if not os.path.isdir( clip_dir ):
+ return []
+ frames = [
+ os.path.join( clip_dir, entry )
+ for entry in os.listdir( clip_dir )
+ if entry.lower().endswith( self._JPEG_EXTENSIONS )
+ ]
+ frames.sort()
+ return frames
+
+ def _read_frame( self, path : str ) -> Optional[ bytes ]:
+ try:
+ with open( path, 'rb' ) as frame_file:
+ return frame_file.read()
+ except OSError:
+ logger.warning( 'Failed to read clip frame: %s', path )
+ return None
+
+ def _video_dir( self ) -> str:
+ return getattr( settings, 'SIMULATOR_VIDEO_DIR', '' ) or ''
diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.css
index cd8f416a..75e61816 100644
--- a/src/hi/static/css/main.css
+++ b/src/hi/static/css/main.css
@@ -71,6 +71,20 @@
--on-status-bad-color: white;
--on-status-idle-color: black;
+ /* Temperature ramp: blue (cold) -> green (pleasant) -> orange/red (hot).
+ These should match those in hi.hi_styles.StatusStyle (STATUS_TEMP_*). */
+ --status-temp-cold-color: #2c7fb8;
+ --status-temp-cool-color: #74add1;
+ --status-temp-pleasant-color: #1a9850;
+ --status-temp-warm-color: #fdae61;
+ --status-temp-hot-color: #d73027;
+
+ --on-status-temp-cold-color: white;
+ --on-status-temp-cool-color: black;
+ --on-status-temp-pleasant-color: white;
+ --on-status-temp-warm-color: black;
+ --on-status-temp-hot-color: white;
+
/* Panel size budgets. Soft enforcement: collection wrappers reference
these via auto-fit/minmax for adaptive column counts; panels
reference them when their content scales with the budget.
@@ -85,6 +99,29 @@
--hi-panel-row-max-height: 128px;
--hi-panel-default-tile-min-size: 160px;
+ /* Ceiling for a video-pane image/clip's rendered height. Landscape
+ cameras stay well under this (so they fill width as before); portrait
+ cameras are clamped here and letterboxed via object-fit so they fit
+ on screen instead of overflowing to ~2x the height. The two named
+ tokens are the menu of sizes; --hi-video-max-height is the active one,
+ defaulting to standard and re-pointed to compact by .hi-video-compact. */
+ --hi-video-max-height-standard: 60vh;
+ --hi-video-max-height-compact: 40vh;
+ --hi-video-max-height: var(--hi-video-max-height-standard);
+
+ /* Ceiling for the hi_grid side panel width. Its content is designed for
+ a narrow column and looks sparse past this, so on wide screens the
+ side clamps here and MAIN reclaims the freed width. A no-op on
+ small/medium screens, where the Bootstrap col-3 (25%) is already
+ narrower than this. */
+ --hi-side-max-width: 375px;
+
+ /* Letterbox/backdrop fill behind a video that doesn't fill its container
+ (e.g. a portrait clip in a landscape pane). A very dark, lightly
+ teal-tinted neutral — softer than pure black and cohesive with
+ --primary-color (#177072) — so the frame recedes without being stark. */
+ --hi-video-letterbox-bg: #13201f;
+
}
html, body {
@@ -545,6 +582,10 @@ a.clickable-card:active {
.hi-side {
padding-left: 0;
padding-right: 0;
+ /* Clamp to min(col-3 25%, --hi-side-max-width): the cap only engages
+ on wide screens; below it the 25% flex-basis governs unchanged.
+ Paired with .scrollable-column flex-grow so MAIN reclaims the gap. */
+ max-width: var(--hi-side-max-width);
}
#hi-side-content {
height: calc(100vh - var(--top-buttons-height) - var(--bottom-buttons-height));
@@ -595,6 +636,11 @@ a.clickable-card:active {
max-height: 100vh;
padding-top: var(--top-buttons-height);
padding-bottom: var(--bottom-buttons-height);
+ /* Grow past the col-9 75% to absorb the width freed when .hi-side is
+ clamped on wide screens; no free space exists below the clamp, so
+ this is a no-op there. */
+ flex-grow: 1;
+ max-width: none;
}
.fixed-column {
overflow-y: auto;
@@ -934,6 +980,19 @@ g[status="past"] {
g[status="off"] path.hi-state-bg {
fill: var(--status-off-color);
}
+/* Base for every status-display chip. MUST precede the specific
+ * .hi-status-display[status="..."] rules below: they share its
+ * specificity (class + one attribute), so they only override it by
+ * source order. Previously this sat after on/off/dim and silently
+ * clobbered them. */
+.hi-status-display[status] {
+ color: var(--black);
+ background-color: var(--white);
+ border-color: var(--black);
+ border-style: solid;
+ border-width: 2px;
+ border-radius: 8px;
+}
.hi-status-display[status="off"] {
color: var(--on-status-off-color);
background-color: var(--status-off-color);
@@ -944,6 +1003,34 @@ g[status="on"] {
g[status="on"] path.hi-state-bg {
fill: var(--status-on-color);
}
+/* Fan icons: spin the blades while "on" as a live state cue alongside the
+ * on-glow. We rotate the blade path(s) -- NOT the placed <g> wrapper, whose
+ * transform attribute carries the icon's position/scale (a CSS transform on
+ * it would override that and move the icon). transform-box: fill-box pivots
+ * relative to the path's own bounding box. */
+@keyframes hi-fan-spin {
+ to { transform: rotate( 360deg ); }
+}
+@media (prefers-reduced-motion: no-preference) {
+ /* Ceiling fan: blades are their own path. The top blade reaches higher
+ * than the bottom blades reach low, so the bbox center sits ~4% above
+ * the hub -- nudge the y origin down to match. Eyeball-tune the second
+ * value (try 52-56%) if it still wobbles. */
+ g[status="on"] path.hi-entity-ceiling-fan-blades {
+ transform-box: fill-box;
+ transform-origin: 50% 54%;
+ animation: hi-fan-spin 3s linear infinite;
+ }
+ /* Exhaust fan: blades, outer ring and center hub share one path, but the
+ * ring and hub are circular so only the blades read as moving. The
+ * dominant circular ring keeps the bbox centered on the true axis, so
+ * plain center works without a tuned offset. */
+ g[status="on"] path.hi-entity-exhaust-fan-lines {
+ transform-box: fill-box;
+ transform-origin: center;
+ animation: hi-fan-spin 3s linear infinite;
+ }
+}
.hi-status-display[status="on"] {
color: var(--on-status-on-color);
background-color: var(--status-on-color);
@@ -991,16 +1078,23 @@ g[status="co_detected"] {
g[status="gas_detected"] {
filter: drop-shadow(0 0 5px var(--status-bad-color));
}
+g[status="temperature_cold"] {
+ filter: drop-shadow(0 0 5px var(--status-temp-cold-color));
+}
+g[status="temperature_cool"] {
+ filter: drop-shadow(0 0 5px var(--status-temp-cool-color));
+}
+g[status="temperature_pleasant"] {
+ filter: drop-shadow(0 0 5px var(--status-temp-pleasant-color));
+}
+g[status="temperature_warm"] {
+ filter: drop-shadow(0 0 5px var(--status-temp-warm-color));
+}
+g[status="temperature_hot"] {
+ filter: drop-shadow(0 0 5px var(--status-temp-hot-color));
+}
-.hi-status-display[status] {
- color: var(--black);
- background-color: var(--white);
- border-color: var(--black);
- border-style: solid;
- border-width: 2px;
- border-radius: 8px;
-}
.hi-status-display[status="active"] {
color: var(--on-status-active-color);
background-color: var(--status-active-color);
@@ -1038,6 +1132,7 @@ g[status="gas_detected"] {
color: var(--on-status-bad-color);
background-color: var(--status-bad-color);
}
+.hi-status-display[status="ok"],
.hi-status-display[status="high"] {
color: var(--on-status-ok-color);
background-color: var(--status-ok-color);
@@ -1078,6 +1173,38 @@ g[status="gas_detected"] {
color: var(--on-status-bad-color);
background-color: var(--status-bad-color);
}
+.hi-status-display[status="object_person"],
+.hi-status-display[status="object_car"],
+.hi-status-display[status="object_animal"],
+.hi-status-display[status="object_package"],
+.hi-status-display[status="object_other"] {
+ color: var(--on-status-active-color);
+ background-color: var(--status-active-color);
+}
+.hi-status-display[status="object_none"] {
+ color: var(--on-status-ok-color);
+ background-color: var(--status-ok-color);
+}
+.hi-status-display[status="temperature_cold"] {
+ color: var(--on-status-temp-cold-color);
+ background-color: var(--status-temp-cold-color);
+}
+.hi-status-display[status="temperature_cool"] {
+ color: var(--on-status-temp-cool-color);
+ background-color: var(--status-temp-cool-color);
+}
+.hi-status-display[status="temperature_pleasant"] {
+ color: var(--on-status-temp-pleasant-color);
+ background-color: var(--status-temp-pleasant-color);
+}
+.hi-status-display[status="temperature_warm"] {
+ color: var(--on-status-temp-warm-color);
+ background-color: var(--status-temp-warm-color);
+}
+.hi-status-display[status="temperature_hot"] {
+ color: var(--on-status-temp-hot-color);
+ background-color: var(--status-temp-hot-color);
+}
g[hover] {
filter: drop-shadow(0 0 10px var(--status-hover-color)) !important;
diff --git a/src/hi/static/css/simulator.css b/src/hi/static/css/simulator.css
index 3d492907..7e38b3c9 100644
--- a/src/hi/static/css/simulator.css
+++ b/src/hi/static/css/simulator.css
@@ -364,3 +364,87 @@ a.underline:visited {
.switch input:checked + .slider:before {
transform: translateX(26px);
}
+
+/* ----- Scene sequence timeline ----- */
+.sim-timeline {
+ width: 100%;
+ position: relative;
+}
+.sim-timeline-svg {
+ display: block;
+ cursor: pointer;
+ background: #fbfbfd;
+ border: 1px solid #e3e3e8;
+ border-radius: 4px;
+}
+.sim-timeline-axis {
+ stroke: #b6b6c0;
+ stroke-width: 2;
+ vector-effect: non-scaling-stroke;
+}
+/* Wide transparent column makes each glyph easy to hover/click. */
+.sim-timeline-hit {
+ fill: transparent;
+ cursor: pointer;
+}
+.sim-timeline-glyph {
+ pointer-events: none;
+ transition: fill 0.1s ease;
+}
+.sim-timeline-step .sim-timeline-glyph {
+ fill: #6c8cd5;
+}
+.sim-timeline-step:hover .sim-timeline-glyph {
+ fill: #21407f;
+}
+.sim-timeline-marker .sim-timeline-glyph {
+ fill: #d99a2b;
+}
+.sim-timeline-marker:hover .sim-timeline-glyph {
+ fill: #9c6606;
+}
+.sim-timeline-end-rule {
+ stroke: #6c757d;
+ stroke-width: 3;
+ vector-effect: non-scaling-stroke;
+}
+.sim-timeline-end:hover .sim-timeline-end-rule {
+ stroke: #343a40;
+}
+.sim-timeline-playhead {
+ stroke: #d9534f;
+ stroke-width: 2;
+ vector-effect: non-scaling-stroke;
+ pointer-events: none;
+}
+.sim-timeline-scale {
+ font-size: 0.72rem;
+ color: #888;
+ padding: 0 2px;
+}
+.sim-timeline-tooltip {
+ position: absolute;
+ z-index: 20;
+ pointer-events: none;
+ background: rgba(33, 37, 41, 0.95);
+ color: #fff;
+ font-size: 0.74rem;
+ line-height: 1.25;
+ padding: 4px 8px;
+ border-radius: 4px;
+ white-space: nowrap;
+ max-width: 95%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25);
+}
+
+/* Bootstrap's .sticky-top is z-index 1020, which sits ABOVE dropdown
+ menus (z-index 1000). The scene selector lives in the header above this
+ sticky transport, so its open menu would be shadowed by the bar. Drop
+ the transport below the dropdown layer while keeping it above the
+ scrolling states grid. The transport's own dropdowns (sequence select)
+ still open fine over the grid via this element's stacking context. */
+.sim-scene-transport.sticky-top {
+ z-index: 100;
+}
diff --git a/src/hi/static/css/stream-browser.css b/src/hi/static/css/stream-browser.css
index b37c6496..4b452800 100644
--- a/src/hi/static/css/stream-browser.css
+++ b/src/hi/static/css/stream-browser.css
@@ -139,14 +139,41 @@
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
- background-color: var(--black);
+ background-color: var(--hi-video-letterbox-bg);
min-height: 400px;
}
-.video-container img {
+/* Covers both the MJPEG/snapshot <img> and the finite-clip <video>
+ (an mp4 clip renders as <video class="img-fluid">, wrapped in
+ .hi-video-clip). */
+.video-container img,
+.video-container video {
display: block;
width: 100%;
height: auto;
+ /* Width-driven sizing (landscape fills the pane, height follows the
+ aspect ratio) until the height would exceed the cap — then clamp and
+ letterbox so a portrait camera fits on screen rather than overflowing
+ to ~2x the height. Landscape stays well under the cap, so object-fit
+ is a no-op there and its sizing is unchanged. */
+ max-height: var(--hi-video-max-height);
+ object-fit: contain;
+}
+
+/* Compact variant for denser contexts (collection grid, alert-detail
+ modal): a shorter cap so portrait media stays manageable where there is
+ less room. Set on a container; it re-points the active cap variable to
+ the compact token, which the .video-container media above (collection
+ camera panels) pick up by inheritance, AND caps bare <img>/<video> media
+ that aren't wrapped in a .video-container (the alert modal renders media
+ directly in .hi-video-clip / a card body). */
+.hi-video-compact {
+ --hi-video-max-height: var(--hi-video-max-height-compact);
+}
+.hi-video-compact img,
+.hi-video-compact video {
+ max-height: var(--hi-video-max-height);
+ object-fit: contain;
}
/* Event Header */
diff --git a/src/hi/static/js/antinode.js b/src/hi/static/js/antinode.js
index 8042defe..5b032a34 100644
--- a/src/hi/static/js/antinode.js
+++ b/src/hi/static/js/antinode.js
@@ -168,16 +168,23 @@
});
},
- post: function( url, data ) {
+ post: function( url, data, options ) {
+ options = options || {};
$.ajax({
type: 'POST',
url: url,
data: data,
async: true,
cache: false,
+ // suppressLoader: behind-the-scenes saves (e.g. snap-grid,
+ // pan/zoom geometry) opt out of the loading interstitial.
+ // global:false also keeps the request out of the shared
+ // ajaxStart/ajaxStop counter, so it never affects a
+ // concurrent user-initiated request's interstitial.
+ global: ( options.suppressLoader !== true ),
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
processData: true,
-
+
success: function(data, status, xhr) {
asyncUpdateData( null, null, data, xhr );
return false;
diff --git a/src/hi/static/js/main.js b/src/hi/static/js/main.js
index 6c34e88f..16fe45ab 100644
--- a/src/hi/static/js/main.js
+++ b/src/hi/static/js/main.js
@@ -11,11 +11,15 @@
//
DEBUG: window.HiClientConfig?.DEBUG ?? false,
isEditMode: window.HiClientConfig?.IS_EDIT_MODE ?? false,
+ svgSnapGridPixels: window.HiClientConfig?.SVG_SNAP_GRID_PIXELS ?? 5,
// Server-provided URLs (via ClientConfig context processor)
API_STATUS_URL: window.HiClientConfig?.API_STATUS_URL ?? '/api/status',
CONSOLE_UNLOCK_URL: window.HiClientConfig?.CONSOLE_UNLOCK_URL ?? '/console/unlock',
+ // Status polling cadence (ms), user-configurable via ConsoleSetting.
+ API_STATUS_POLLING_INTERVAL_MS: window.HiClientConfig?.API_STATUS_POLLING_INTERVAL_MS ?? 3000,
+
MAIN_AREA_SELECTOR: '#hi-main-content',
LOCATION_VIEW_AREA_SELECTOR: '#hi-location-view-main',
LOCATION_VIEW_SVG_CLASS: 'hi-location-view-svg',
@@ -37,7 +41,8 @@
API_LOCATION_ITEM_EDIT_MODE_URL: '/location/edit/item/edit-mode',
API_LOCATION_ITEM_STATUS_URL: '/location/item/status',
ENTITY_STATE_VALUE_CHOICES_URL_PREFIX: '/edit/entity/state/values',
-
+ API_SET_SNAP_GRID_URL: '/snap-grid',
+
generateUniqueId: function() {
return _generateUniqueId();
},
@@ -221,6 +226,30 @@
window.Hi = Hi;
+ // Snap-grid preference. Owned here (rather than duplicated in each SVG
+ // editor) so there is a single implementation. Seed the live edit value
+ // from the server-delivered preference (Hi.svgSnapGridPixels), then own
+ // the change handler via one delegated binding keyed on a shared class -
+ // delegated so it survives async re-renders of the editor chrome and
+ // works on whichever editor page is shown.
+ window.Hi.SvgEdit = window.Hi.SvgEdit || {};
+ window.Hi.SvgEdit.snapGridPixels = Hi.svgSnapGridPixels;
+
+ $(function() {
+ var snapSaveTimer = null;
+ $(document).on( 'input', '.hi-snap-grid', function() {
+ var value = parseInt( $( this ).val(), 10 ) || 0;
+ window.Hi.SvgEdit.snapGridPixels = value; // live snapping
+ window.Hi.svgSnapGridPixels = value; // keep the relay in sync
+ // Debounced persist so a spinner-arrow burst is one save.
+ clearTimeout( snapSaveTimer );
+ snapSaveTimer = setTimeout( function() {
+ AN.post( Hi.API_SET_SNAP_GRID_URL, { snap_grid_pixels: value },
+ { suppressLoader: true } );
+ }, 400 );
+ });
+ });
+
function _generateUniqueId() {
return 'id-' + Date.now() + '-' + Math.floor(Math.random() * 1000);
}
diff --git a/src/hi/static/js/scene_status.js b/src/hi/static/js/scene_status.js
new file mode 100644
index 00000000..87a8f76c
--- /dev/null
+++ b/src/hi/static/js/scene_status.js
@@ -0,0 +1,102 @@
+(function() {
+
+ // Live transport poller for the Scenes page. Companion to simulator.js's
+ // state-value poller (which keeps the control grid live); this one keeps
+ // the playback/record transport live:
+ // - smoothly advances the timeline playhead + badge time (rAF between polls),
+ // - updates the recording step count,
+ // - fragment-refreshes the transport pane when its button set changes.
+
+ const POLL_INTERVAL_MS = 1000;
+
+ const State = {
+ signature: null,
+ playing: false,
+ baseT: 0,
+ baseAt: 0,
+ limit: 0, // interpolation ceiling: next mark while stepping, else total
+ };
+
+ function _transport() {
+ return document.querySelector( '.sim-scene-transport[data-status-url]' );
+ }
+
+ function _renderPlayhead( t ) {
+ const badge = document.querySelector( '.sim-scene-transport .js-playhead' );
+ if ( badge ) { badge.textContent = ( Math.round( t * 10 ) / 10 ).toFixed( 1 ); }
+ document.querySelectorAll( '.sim-timeline' ).forEach( function( container ) {
+ if ( window.HiSceneTimeline ) { HiSceneTimeline.setPlayhead( container, t ); }
+ });
+ }
+
+ function _tick() {
+ if ( State.playing ) {
+ const elapsed = ( window.performance.now() - State.baseAt ) / 1000;
+ const t = Math.min( State.limit, State.baseT + elapsed );
+ _renderPlayhead( t );
+ }
+ window.requestAnimationFrame( _tick );
+ }
+
+ function _refreshTransport( url ) {
+ if ( ! url ) { return; }
+ $.ajax({
+ url: url, global: false, cache: false,
+ success: function( html ) {
+ const region = _transport();
+ if ( region ) {
+ const wrap = document.createElement( 'div' );
+ wrap.innerHTML = html;
+ const fresh = wrap.firstElementChild;
+ if ( fresh ) { region.parentNode.replaceChild( fresh, region ); }
+ }
+ if ( window.HiSceneTimeline ) { HiSceneTimeline.refresh(); }
+ },
+ });
+ }
+
+ function _poll() {
+ const region = _transport();
+ if ( ! region ) { return; }
+ const statusUrl = region.getAttribute( 'data-status-url' );
+ const transportUrl = region.getAttribute( 'data-transport-url' );
+ $.ajax({
+ url: statusUrl, dataType: 'json', global: false, cache: false,
+ success: function( data ) {
+ // A button-relevant change: swap the whole pane, then resync
+ // the playhead on the next poll against the fresh DOM.
+ if ( State.signature !== null && data.signature !== State.signature ) {
+ State.signature = data.signature;
+ State.playing = false;
+ _refreshTransport( transportUrl );
+ return;
+ }
+ State.signature = data.signature;
+
+ const rec = data.recorder;
+ const player = data.player;
+ if ( rec.recording ) {
+ const steps = document.querySelector( '.sim-scene-transport .js-rec-steps' );
+ if ( steps ) { steps.textContent = rec.step_count; }
+ }
+ State.playing = !! player.playing;
+ State.limit = ( player.playhead_limit != null )
+ ? player.playhead_limit : ( player.total || 0 );
+ State.baseT = player.playhead || 0;
+ State.baseAt = window.performance.now();
+ if ( ! State.playing ) { _renderPlayhead( State.baseT ); }
+ },
+ error: function( jqXHR, textStatus ) {
+ if ( window.console ) { console.warn( 'Scene status poll failed:', textStatus ); }
+ },
+ });
+ }
+
+ $(document).ready( function() {
+ if ( ! _transport() ) { return; }
+ window.setInterval( _poll, POLL_INTERVAL_MS );
+ window.requestAnimationFrame( _tick );
+ _poll();
+ });
+
+})();
diff --git a/src/hi/static/js/scene_timeline.js b/src/hi/static/js/scene_timeline.js
new file mode 100644
index 00000000..47734748
--- /dev/null
+++ b/src/hi/static/js/scene_timeline.js
@@ -0,0 +1,122 @@
+(function() {
+
+ // Annotated sequence timeline: click-to-jump (posts a seek), plus a
+ // setPlayhead() hook the status poller will drive once polling lands.
+ const HiSceneTimeline = {
+ setPlayhead: function( container, t ) { return _setPlayhead( container, t ); },
+ refresh: function() { return _initAll(); },
+ };
+ window.HiSceneTimeline = HiSceneTimeline;
+
+ function _geom( container ) {
+ return {
+ total: parseFloat( container.getAttribute( 'data-total' )) || 0,
+ x0: parseFloat( container.getAttribute( 'data-x0' )),
+ x1: parseFloat( container.getAttribute( 'data-x1' )),
+ vbw: parseFloat( container.getAttribute( 'data-vbw' )),
+ };
+ }
+
+ function _timeToX( g, t ) {
+ if ( g.total <= 0 ) { return g.x0; }
+ let frac = Math.max( 0, Math.min( 1, t / g.total ));
+ return g.x0 + frac * ( g.x1 - g.x0 );
+ }
+
+ function _xToTime( container, clientX ) {
+ const svg = container.querySelector( '.sim-timeline-svg' );
+ const g = _geom( container );
+ const rect = svg.getBoundingClientRect();
+ if ( rect.width <= 0 || g.total <= 0 ) { return 0; }
+ const userX = (( clientX - rect.left ) / rect.width ) * g.vbw;
+ const t = ( userX - g.x0 ) / ( g.x1 - g.x0 ) * g.total;
+ return Math.max( 0, Math.min( g.total, t ));
+ }
+
+ function _submitSeek( container, t ) {
+ const form = container.querySelector( '.sim-timeline-seek-form' );
+ if ( ! form ) { return; }
+ const field = form.querySelector( 'input[name="t"]' );
+ if ( ! field ) { return; }
+ field.value = t.toFixed( 3 );
+ form.submit();
+ }
+
+ function _setPlayhead( container, t ) {
+ const line = container.querySelector( '[data-role="playhead"]' );
+ if ( ! line ) { return; }
+ const x = _timeToX( _geom( container ), t );
+ line.setAttribute( 'x1', x );
+ line.setAttribute( 'x2', x );
+ line.style.display = '';
+ }
+
+ function _ancestorAttr( container, target, attr ) {
+ // Walk up from the event target to the glyph group carrying attr.
+ let node = target;
+ while ( node && node !== container ) {
+ if ( node.getAttribute && node.hasAttribute && node.hasAttribute( attr )) {
+ return node.getAttribute( attr );
+ }
+ node = node.parentNode;
+ }
+ return null;
+ }
+
+ function _exactTimeFromTarget( container, target ) {
+ const value = _ancestorAttr( container, target, 'data-t' );
+ return ( value === null ) ? null : parseFloat( value );
+ }
+
+ function _tooltip( container ) {
+ let tip = container.querySelector( '.sim-timeline-tooltip' );
+ if ( ! tip ) {
+ tip = document.createElement( 'div' );
+ tip.className = 'sim-timeline-tooltip';
+ tip.style.display = 'none';
+ container.appendChild( tip );
+ }
+ return tip;
+ }
+
+ function _showTip( container, evt ) {
+ const text = _ancestorAttr( container, evt.target, 'data-title' );
+ const tip = _tooltip( container );
+ if ( text === null ) { tip.style.display = 'none'; return; }
+ tip.textContent = text;
+ tip.style.display = 'block';
+ const rect = container.getBoundingClientRect();
+ let left = evt.clientX - rect.left + 12;
+ let top = evt.clientY - rect.top + 14;
+ const maxLeft = container.clientWidth - tip.offsetWidth - 4;
+ if ( left > maxLeft ) { left = Math.max( 0, maxLeft ); }
+ tip.style.left = left + 'px';
+ tip.style.top = top + 'px';
+ }
+
+ function _hideTip( container ) {
+ const tip = container.querySelector( '.sim-timeline-tooltip' );
+ if ( tip ) { tip.style.display = 'none'; }
+ }
+
+ function _onClick( container, evt ) {
+ let t = _exactTimeFromTarget( container, evt.target );
+ if ( t === null ) { t = _xToTime( container, evt.clientX ); }
+ _submitSeek( container, t );
+ }
+
+ function _initAll() {
+ document.querySelectorAll( '.sim-timeline' ).forEach( function( container ) {
+ if ( container.__hiTimelineBound ) { return; }
+ container.__hiTimelineBound = true;
+ const svg = container.querySelector( '.sim-timeline-svg' );
+ if ( ! svg ) { return; }
+ svg.addEventListener( 'click', function( evt ) { _onClick( container, evt ); });
+ svg.addEventListener( 'mousemove', function( evt ) { _showTip( container, evt ); });
+ svg.addEventListener( 'mouseleave', function() { _hideTip( container ); });
+ });
+ }
+
+ $(document).ready( _initAll );
+
+})();
diff --git a/src/hi/static/js/status.js b/src/hi/static/js/status.js
index d44aeb6a..5129b357 100644
--- a/src/hi/static/js/status.js
+++ b/src/hi/static/js/status.js
@@ -23,7 +23,7 @@
const ServerPollingWatchdogType = 'serverPolling';
const ServerPollingStartDelayMs = 1000;
- const ServerPollingIntervalMs = 3 * 1000;
+ const ServerPollingIntervalMs = Hi.API_STATUS_POLLING_INTERVAL_MS ?? (3 * 1000);
const PollingErrorNotifyTimeMs = 60 * 1000;
const ServerErrorMessageSelector = '#hi-server-error-msg';
const ServerPollingUrl = Hi.API_STATUS_URL;
diff --git a/src/hi/static/js/svg-bg-edit.js b/src/hi/static/js/svg-bg-edit.js
index 5ba67b0b..cc44be8c 100644
--- a/src/hi/static/js/svg-bg-edit.js
+++ b/src/hi/static/js/svg-bg-edit.js
@@ -4,7 +4,6 @@
window.Hi = window.Hi || {};
window.Hi.SvgEdit = window.Hi.SvgEdit || {};
- window.Hi.SvgEdit.snapGridPixels = 5;
const SVG_NS = 'http://www.w3.org/2000/svg';
@@ -633,10 +632,6 @@
/* Seed undo cache so the first edit has a valid pre-edit state. */
gLastSavedSnapshot = getCleanSnapshot();
-
- $( '#hi-svg-edit-snap-grid' ).on( 'change input', function() {
- Hi.SvgEdit.snapGridPixels = parseInt( $( this ).val(), 10 ) || 0;
- });
});
})();
diff --git a/src/hi/static/js/svg-entity-edit.js b/src/hi/static/js/svg-entity-edit.js
index 1f60ae0d..410aa5f9 100644
--- a/src/hi/static/js/svg-entity-edit.js
+++ b/src/hi/static/js/svg-entity-edit.js
@@ -16,7 +16,6 @@
window.Hi = window.Hi || {};
window.Hi.edit = window.Hi.edit || {};
window.Hi.SvgEdit = window.Hi.SvgEdit || {};
- window.Hi.SvgEdit.snapGridPixels = window.Hi.SvgEdit.snapGridPixels || 5;
var API_EDIT_LOCATION_ITEM_POSITION_URL = '/location/edit/item/position';
@@ -264,13 +263,35 @@
var data = {
svg_view_box_str: saveData.viewBoxStr,
svg_rotate: saveData.rotationAngle || 0,
+ // Context, not instruction: signals the LocationView
+ // properties editor is open. The server decides what
+ // to do with it (persist to the LocationView vs. only
+ // track the session pan/zoom).
+ view_edit_active: ( $( LOCATION_VIEW_EDIT_PANE_SELECTOR ).length > 0 ),
};
- AN.post( API_EDIT_LOCATION_VIEW_GEOMETRY_URL + '/' + locationViewId, data );
+ AN.post( API_EDIT_LOCATION_VIEW_GEOMETRY_URL + '/' + locationViewId, data,
+ { suppressLoader: true } );
+
+ // Keep this page's URL query params in sync with the latest
+ // pan/zoom so any reload of the current view (e.g. antinode's
+ // refresh_response after an edit) restores the geometry
+ // instead of snapping to the stored viewbox. A deliberate
+ // navigation to another view replaces the URL (no params)
+ // and correctly resets to stored.
+ try {
+ var url = new URL( window.location.href );
+ url.searchParams.set( 'svg_view_box', saveData.viewBoxStr );
+ url.searchParams.set( 'svg_rotate', saveData.rotationAngle || 0 );
+ window.history.replaceState( window.history.state, '', url.toString() );
+ } catch ( e ) { /* URL/History unavailable; non-critical */ }
},
shouldSave: function() {
+ // Send pan/zoom to the server throughout edit mode so the
+ // session always holds the latest geometry. Whether it
+ // overwrites the stored LocationView geometry is the
+ // server's call (see view_edit_active above).
return ( Hi.isEditMode
- && $( Hi.BASE_SVG_SELECTOR ).length > 0
- && $( LOCATION_VIEW_EDIT_PANE_SELECTOR ).length > 0 );
+ && $( Hi.BASE_SVG_SELECTOR ).length > 0 );
},
});
@@ -350,10 +371,4 @@
window.Hi.location = HiSvgLocation;
HiSvgLocation.init();
- $(document).ready(function() {
- $( '#hi-entity-snap-grid' ).on( 'change input', function() {
- Hi.SvgEdit.snapGridPixels = parseInt( $( this ).val(), 10 ) || 0;
- });
- });
-
})();
diff --git a/src/hi/static/js/svg-entity-event-listeners.js b/src/hi/static/js/svg-entity-event-listeners.js
index dab5437c..05086e4d 100644
--- a/src/hi/static/js/svg-entity-event-listeners.js
+++ b/src/hi/static/js/svg-entity-event-listeners.js
@@ -468,6 +468,17 @@
}
}
+ function targetMatchesSelector( target, selector ) {
+ // event.target is not always an Element with .closest(): it can be a
+ // text node (resolve to its parent element) or a non-Element node such
+ // as the document (no enclosing element). Guard so a stray event over
+ // such a target doesn't throw "closest is not a function".
+ const element = ( target instanceof Element )
+ ? target
+ : ( target && target.parentElement );
+ return Boolean( element && element.closest( selector ));
+ }
+
function addPointerListener( eventType, selector, handler, passive = true ) {
// N.B.
// - "passive = false" ensures preventDefault() works for pointer events.
@@ -475,7 +486,7 @@
$(document).each( function() {
this.addEventListener( eventType, function( event ) {
- if ( event.target.closest( selector )) {
+ if ( targetMatchesSelector( event.target, selector )) {
handler( event );
}
}, { passive: passive });
@@ -494,7 +505,7 @@
// default, which silently ignores preventDefault() (jQuery also has
// no way to set the passive option). See addPointerListener above.
document.addEventListener( 'wheel', function( event ) {
- if ( ! event.target.closest( Hi.LOCATION_VIEW_AREA_SELECTOR )) { return; }
+ if ( ! targetMatchesSelector( event.target, Hi.LOCATION_VIEW_AREA_SELECTOR )) { return; }
let handled = Hi.edit.icon.handleMouseWheel( event );
if ( ! handled ) {
handled = Hi.location.handleMouseWheel( event );
diff --git a/src/hi/static/js/svg-pan-zoom-core.js b/src/hi/static/js/svg-pan-zoom-core.js
index 49b6456c..5d5c32e0 100644
--- a/src/hi/static/js/svg-pan-zoom-core.js
+++ b/src/hi/static/js/svg-pan-zoom-core.js
@@ -73,8 +73,7 @@
size.
*/
fitViewBoxToContainer: function() {
- if ( ! gSvgElement ) { HiSvgPanZoomCore.refresh(); }
- if ( ! gSvgElement || ! gConfig ) { return; }
+ if ( ! ensureSvgElement() || ! gConfig ) { return; }
var areaElement = $( gConfig.areaSelector )[0];
if ( ! areaElement ) { return; }
var rect = areaElement.getBoundingClientRect();
@@ -85,7 +84,7 @@
},
handleSinglePointerEventStart: function( event ) {
- if ( ! gSvgElement ) { return false; }
+ if ( ! ensureSvgElement() ) { return false; }
var svgViewBox = Hi.svgUtils.getSvgViewBox( gSvgElement );
gTransformData = {
@@ -145,7 +144,7 @@
},
handleDoublePointerEventStart: function( doublePointerEvent ) {
- if ( ! gSvgElement ) { return false; }
+ if ( ! ensureSvgElement() ) { return false; }
var svgViewBox = Hi.svgUtils.getSvgViewBox( gSvgElement );
gTransformData = {
@@ -189,7 +188,7 @@
},
handleMouseWheel: function( event ) {
- if ( ! gSvgElement ) { return false; }
+ if ( ! ensureSvgElement() ) { return false; }
if ( ! isEventInArea( event ) ) { return false; }
if ( gConfig.enableCanvasRotation && gTransformType === SvgTransformType.ROTATE ) {
@@ -214,7 +213,7 @@
},
handleKeyDown: function( event ) {
- if ( ! gSvgElement ) { return false; }
+ if ( ! ensureSvgElement() ) { return false; }
if ( $( event.target ).is( 'input, textarea' ) ) { return false; }
if ( $( event.target ).closest( '.modal' ).length > 0 ) { return false; }
if ( ! isEventInArea( event ) ) { return false; }
@@ -558,6 +557,23 @@
/* Utilities */
/* ==================== */
+ /*
+ Re-resolve the cached SVG element if it is missing OR has been
+ detached from the document by an async DOM swap (e.g. toggling an
+ entity/collection into the view replaces #hi-location-view-main, so
+ the SVG element this module cached at init() is now an orphaned
+ ghost). Without this, every pan/zoom/click silently operates on the
+ detached element and the live background stops responding until a
+ full page reload. Called at each gesture entry point so the core
+ self-heals no matter which code path replaced the SVG.
+ */
+ function ensureSvgElement() {
+ if ( ! gSvgElement || ! gSvgElement.isConnected ) {
+ gSvgElement = gConfig ? ( $( gConfig.baseSvgSelector )[0] || null ) : null;
+ }
+ return gSvgElement;
+ }
+
function isEventInArea( event ) {
if ( ! gConfig || ! gConfig.areaSelector ) {
return true;
diff --git a/src/hi/templates/panes/bottom_buttons.html b/src/hi/templates/panes/bottom_buttons.html
index d05d4ffe..d90ed57c 100644
--- a/src/hi/templates/panes/bottom_buttons.html
+++ b/src/hi/templates/panes/bottom_buttons.html
@@ -14,11 +14,7 @@
<div class="d-flex justify-content-end hi-button-bar-fixed">
{% if request.view_parameters.is_editing %}
<div class="mx-1 d-flex align-items-center">
- <label class="mb-0 mx-1" style="font-size: 0.85rem;"><b>Snap:</b></label>
- <input type="number" id="hi-entity-snap-grid" class="form-control form-control-sm"
- style="width: 4rem;" value="5" min="0" max="50" step="1"
- title="Snap grid in screen pixels (0 to disable, hold Shift for fine mode)">
- <label class="ms-1 mb-0" style="font-size: 0.85rem;">px</label>
+ {% include "panes/snap_grid_input.html" %}
</div>
<div class="mx-1">
<a href="{% url 'profiles_edit_reference_help' %}"
diff --git a/src/hi/templates/panes/snap_grid_input.html b/src/hi/templates/panes/snap_grid_input.html
new file mode 100644
index 00000000..9d83d238
--- /dev/null
+++ b/src/hi/templates/panes/snap_grid_input.html
@@ -0,0 +1,11 @@
+{% comment %}
+Shared SVG-editor snap-grid control. The `hi-snap-grid` class is the JS hook
+(delegated handler lives in main.js); both editors include this so the markup
+and the JS binding cannot drift. No id - nothing references one.
+{% endcomment %}
+<label class="mb-0 mx-1" style="font-size: 0.85rem;"><b>Snap:</b></label>
+<input type="number" class="hi-snap-grid form-control form-control-sm"
+ style="width: 4rem;" value="{{ request.view_parameters.svg_snap_grid_pixels }}"
+ min="0" max="50" step="1"
+ title="Snap grid in screen pixels (0 to disable, hold Shift for fine mode)">
+<label class="ms-1 mb-0" style="font-size: 0.85rem;">px</label>
diff --git a/src/hi/testing/dev_injection.py b/src/hi/testing/dev_injection.py
index 1d6eaeb7..539c266e 100644
--- a/src/hi/testing/dev_injection.py
+++ b/src/hi/testing/dev_injection.py
@@ -1,9 +1,15 @@
import os
import json
import logging
+from datetime import datetime, timezone
+from typing import Dict, List, Optional
+
from django.conf import settings
from django.core.cache import cache
+from hi.apps.sense.models import Sensor
+from hi.apps.sense.transient_models import SensorResponse
+
logger = logging.getLogger(__name__)
@@ -34,6 +40,66 @@ class DevInjectionManager:
CACHE_PREFIX = 'dev_inject_'
DATA_DIR = '/tmp/hi_dev_overrides'
+
+ @classmethod
+ def apply_sensor_response_cutoff(
+ cls,
+ sensor_to_sensor_response_list : Dict[ Sensor, List[ SensorResponse ] ],
+ ) -> Dict[ Sensor, List[ SensorResponse ] ]:
+ """Encapsulates the 'Clear States' cutoff logic for the status display.
+
+ When a cutoff has been poked into the shared cache, return a copy of
+ the ``{sensor: [SensorResponse, ...]}`` map in which each sensor keeps
+ its latest response plus any older responses at/after the cutoff, and
+ drops the older *pre-cutoff* ones. Returns the input unchanged when off
+ or no cutoff is set. Never mutates the caller's (cache-owned) lists.
+ The caller gates this dev-only path on ``settings.DEBUG`` and
+ ``DEBUG_FORCE_SENSOR_RESPONSE_CUTOFF``.
+
+ Why keep the latest and only drop older pre-cutoff responses: the
+ 'recent/past' decay styling fires only when the *penultimate* response
+ is an active/triggered value (see display_data._get_movement_status_
+ style et al.). Dropping a stale pre-cutoff active entry makes the
+ penultimate either absent or a post-cutoff response, so the lingering
+ decay clears. Keeping the latest preserves a current value to display
+ and keeps the sensor in the polling payload, so the cleared status is
+ actually pushed to the UI. Post-cutoff history is left intact, so
+ genuine events after the cutoff still show recent/past normally."""
+ cutoff = cls._get_sensor_response_cutoff()
+ if cutoff is None:
+ return sensor_to_sensor_response_list
+
+ filtered = dict()
+ for sensor, response_list in sensor_to_sensor_response_list.items():
+ if not response_list:
+ continue
+
+ # Responses are newest-first. Always keep the latest one so the
+ # sensor still has a current value. Among the older responses, keep
+ # only those at/after the cutoff and drop the rest.
+ latest_response = response_list[ 0 ]
+ kept_responses = [ latest_response ]
+ for older_response in response_list[ 1: ]:
+ if older_response.timestamp >= cutoff:
+ kept_responses.append( older_response )
+ continue
+
+ filtered[ sensor ] = kept_responses
+ continue
+ return filtered
+
+ @classmethod
+ def _get_sensor_response_cutoff( cls ) -> Optional[ datetime ]:
+ cache_key = getattr( settings, 'SENSOR_RESPONSE_CUTOFF_CACHE_KEY', None )
+ if not cache_key:
+ return None
+ epoch = cache.get( cache_key )
+ if epoch is None:
+ return None
+ try:
+ return datetime.fromtimestamp( float( epoch ), tz = timezone.utc )
+ except ( TypeError, ValueError, OSError ):
+ return None
@classmethod
def _ensure_data_dir(cls):
diff --git a/src/hi/tests/test_view_parameters.py b/src/hi/tests/test_view_parameters.py
new file mode 100644
index 00000000..cffb35b5
--- /dev/null
+++ b/src/hi/tests/test_view_parameters.py
@@ -0,0 +1,119 @@
+"""
+Focused tests for ViewParameters' transient SVG geometry tracking - the
+pan/zoom state that operations like EntityAddView preserve. The behavior
+under test is the clear-on-context-shift logic and session round-trip; the
+rest of ViewParameters (view/collection resolution) is covered elsewhere.
+"""
+import logging
+
+from hi.apps.common.svg_models import SvgViewBox
+from hi.apps.location.tests.synthetic_data import LocationSyntheticData
+from hi.testing.base_test_case import BaseTestCase, MockRequest
+from hi.view_parameters import ViewParameters
+
+logging.disable(logging.CRITICAL)
+
+
+class TestViewParametersLastSvgGeometry(BaseTestCase):
+
+ def _view_parameters_with_geometry(self, location_view) -> ViewParameters:
+ view_parameters = ViewParameters()
+ view_parameters.location_view_id = location_view.id
+ view_parameters.set_last_svg_geometry(
+ svg_view_box = SvgViewBox( x = 10, y = 20, width = 30, height = 40 ),
+ svg_rotate = '15',
+ )
+ return view_parameters
+
+ def test_switching_location_view_clears_geometry(self):
+ # A different LocationView frames the same coordinate space
+ # differently, so the preserved pan/zoom must be dropped.
+ location_view_1 = LocationSyntheticData.create_test_location_view()
+ location_view_2 = LocationSyntheticData.create_test_location_view(
+ location = location_view_1.location )
+ view_parameters = self._view_parameters_with_geometry( location_view_1 )
+
+ view_parameters.update_location_view( location_view_2 )
+
+ self.assertIsNone( view_parameters.last_svg_view_box )
+ self.assertIsNone( view_parameters.last_svg_rotate )
+
+ def test_same_location_view_preserves_geometry(self):
+ # Same-id re-render (e.g. the post-add redirect) must NOT clear,
+ # or the geometry it is preserving would be lost.
+ location_view = LocationSyntheticData.create_test_location_view()
+ view_parameters = self._view_parameters_with_geometry( location_view )
+
+ view_parameters.update_location_view( location_view )
+
+ self.assertIsNotNone( view_parameters.last_svg_view_box )
+ self.assertEqual( view_parameters.last_svg_rotate, '15' )
+
+ def test_unsetting_location_view_clears_geometry(self):
+ location_view = LocationSyntheticData.create_test_location_view()
+ view_parameters = self._view_parameters_with_geometry( location_view )
+
+ view_parameters.update_location_view( None )
+
+ self.assertIsNone( view_parameters.last_svg_view_box )
+ self.assertIsNone( view_parameters.last_svg_rotate )
+
+ def test_switching_to_collection_clears_geometry(self):
+ # Any move to a Collection view is a context shift; location
+ # pan/zoom no longer applies.
+ location_view = LocationSyntheticData.create_test_location_view()
+ view_parameters = self._view_parameters_with_geometry( location_view )
+
+ view_parameters.update_collection( None )
+
+ self.assertIsNone( view_parameters.last_svg_view_box )
+ self.assertIsNone( view_parameters.last_svg_rotate )
+
+ def test_session_round_trip_preserves_geometry(self):
+ location_view = LocationSyntheticData.create_test_location_view()
+ view_parameters = self._view_parameters_with_geometry( location_view )
+ request = MockRequest()
+
+ view_parameters.to_session( request )
+ restored = ViewParameters.from_session( request )
+
+ self.assertEqual( restored.last_svg_view_box.to_dict(),
+ view_parameters.last_svg_view_box.to_dict() )
+ self.assertEqual( restored.last_svg_rotate, '15' )
+
+ def test_session_round_trip_without_geometry(self):
+ request = MockRequest()
+
+ ViewParameters().to_session( request )
+ restored = ViewParameters.from_session( request )
+
+ self.assertIsNone( restored.last_svg_view_box )
+ self.assertIsNone( restored.last_svg_rotate )
+
+
+class TestViewParametersSnapGrid(BaseTestCase):
+ """The snap-grid user preference: round-trips through the session,
+ preserves an explicit 0 (snapping disabled), and falls back to the
+ default only when the key is missing/malformed."""
+
+ def test_round_trip_preserves_value(self):
+ view_parameters = ViewParameters()
+ view_parameters.svg_snap_grid_pixels = 12
+ request = MockRequest()
+ view_parameters.to_session( request )
+ self.assertEqual(
+ ViewParameters.from_session( request ).svg_snap_grid_pixels, 12 )
+
+ def test_explicit_zero_preserved(self):
+ view_parameters = ViewParameters()
+ view_parameters.svg_snap_grid_pixels = 0
+ request = MockRequest()
+ view_parameters.to_session( request )
+ self.assertEqual(
+ ViewParameters.from_session( request ).svg_snap_grid_pixels, 0 )
+
+ def test_missing_key_falls_back_to_default(self):
+ restored = ViewParameters.from_session( MockRequest() )
+ self.assertEqual(
+ restored.svg_snap_grid_pixels,
+ ViewParameters.DEFAULT_SVG_SNAP_GRID_PIXELS )
diff --git a/src/hi/tests/test_views.py b/src/hi/tests/test_views.py
index f9ffb3a1..402ead2f 100644
--- a/src/hi/tests/test_views.py
+++ b/src/hi/tests/test_views.py
@@ -225,3 +225,30 @@ class TestHealthView(SyncViewTestCase):
# Should return 405 Method Not Allowed
self.assertEqual(response.status_code, 405)
+
+
+class TestSetSnapGridView(SyncViewTestCase):
+ """SetSnapGridView persists the snap-grid preference to the session,
+ clamped to the UI input's range (0 = disabled); malformed input is
+ rejected so a crafted POST cannot store garbage."""
+
+ def test_valid_value_persisted(self):
+ response = self.client.post(reverse('set_snap_grid'), {'snap_grid_pixels': '10'})
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(self.client.session['svg_snap_grid_pixels'], 10)
+
+ def test_value_clamped_to_max(self):
+ self.client.post(reverse('set_snap_grid'), {'snap_grid_pixels': '999'})
+ self.assertEqual(self.client.session['svg_snap_grid_pixels'], 50)
+
+ def test_value_clamped_to_min(self):
+ self.client.post(reverse('set_snap_grid'), {'snap_grid_pixels': '-5'})
+ self.assertEqual(self.client.session['svg_snap_grid_pixels'], 0)
+
+ def test_explicit_zero_disables(self):
+ self.client.post(reverse('set_snap_grid'), {'snap_grid_pixels': '0'})
+ self.assertEqual(self.client.session['svg_snap_grid_pixels'], 0)
+
+ def test_malformed_rejected(self):
+ response = self.client.post(reverse('set_snap_grid'), {'snap_grid_pixels': 'abc'})
+ self.assertEqual(response.status_code, 400)
diff --git a/src/hi/urls.py b/src/hi/urls.py
index 7af5cb8c..2ec0523b 100644
--- a/src/hi/urls.py
+++ b/src/hi/urls.py
@@ -29,6 +29,7 @@ urlpatterns = [
path( 'index.html', views.HomeView.as_view(), name='home_index' ),
path( 'start', views.StartView.as_view(), name='start' ),
path( 'health', views.HealthView.as_view(), name='health' ),
+ path( 'snap-grid', views.SetSnapGridView.as_view(), name='set_snap_grid' ),
path( 'env/', include('hi.environment.urls' )),
path( 'user/', include('hi.apps.user.urls' )),
diff --git a/src/hi/view_parameters.py b/src/hi/view_parameters.py
index ac79cd47..182d7b9d 100644
--- a/src/hi/view_parameters.py
+++ b/src/hi/view_parameters.py
@@ -3,6 +3,7 @@ from dataclasses import dataclass
from django.http import HttpRequest
from hi.apps.collection.models import Collection
+from hi.apps.common.svg_models import SvgViewBox
from hi.apps.location.models import Location, LocationView
from .enums import ViewMode, ViewType
@@ -11,17 +12,39 @@ from .enums import ViewMode, ViewType
@dataclass
class ViewParameters:
+ # Default SVG-editor snap grid in screen pixels (0 disables snapping).
+ # Single source of truth for the value, seeded to the client via
+ # ClientConfig and shared by both SVG editors.
+ DEFAULT_SVG_SNAP_GRID_PIXELS = 5
+
# For anything in this view state that needs to be kept in sync with
# Javascript, add global variables in the base.html template at start
# of body and reference in Javascript as needed. e.g., The editing mode
# requires additional event registrations to handle mouse and gesture
# events..
-
+
view_type : ViewType = None
view_mode : ViewMode = None
location_view_id : int = None # Last LocationView viewed
collection_id : int = None # Last Collection viewed
ref_picker_integration_id : str = None # Last referencer the operator successfully linked from
+
+ # User preference: snap-grid size (screen pixels) for the SVG editors,
+ # persisted across reloads. 0 = snapping disabled. Delivered to JS via
+ # ClientConfig; both snap inputs render and write it back.
+ svg_snap_grid_pixels : int = DEFAULT_SVG_SNAP_GRID_PIXELS
+
+ # Transient pan/zoom state for the current LocationView. Pan/zoom is
+ # normally ephemeral (a full reload restores the LocationView's stored
+ # viewbox), but specific operations (e.g. adding an entity) want to
+ # preserve where the user is looking. This holds the last-explored SVG
+ # geometry so those operations can opt in to it; it is NOT a render
+ # default - consumers apply it explicitly (see EntityAddView). It is
+ # cleared whenever the view context shifts (different LocationView, or
+ # any Collection view), since the geometry is meaningless elsewhere.
+ # Serialized to/from the session as its SVG attribute string.
+ last_svg_view_box : SvgViewBox = None
+ last_svg_rotate : str = None
def __post_init__(self):
if self.view_type is None:
@@ -74,12 +97,30 @@ class ViewParameters:
self.location_view_id = None
return None
+ def set_last_svg_geometry( self, svg_view_box : SvgViewBox, svg_rotate : str ):
+ self.last_svg_view_box = svg_view_box
+ self.last_svg_rotate = svg_rotate
+ return
+
+ def clear_last_svg_geometry( self ):
+ self.last_svg_view_box = None
+ self.last_svg_rotate = None
+ return
+
def update_location_view( self, location_view : LocationView ):
if not location_view:
+ if self.location_view_id is not None:
+ self.clear_last_svg_geometry()
self.location_view_id = None
self._location_view = None
self._location = None
else:
+ # Switching to a different LocationView invalidates any preserved
+ # pan/zoom (sibling views share a Location's coordinate space but
+ # frame it differently). Same-id re-renders must NOT clear it, or
+ # the post-add redirect would lose the geometry it is preserving.
+ if self.location_view_id != location_view.id:
+ self.clear_last_svg_geometry()
self.location_view_id = location_view.id
self._location_view = location_view
self._location = location_view.location
@@ -105,6 +146,9 @@ class ViewParameters:
return None
def update_collection( self, collection : Collection ):
+ # Moving to a Collection view is a context shift away from any
+ # LocationView; preserved location pan/zoom no longer applies.
+ self.clear_last_svg_geometry()
if not collection:
self.collection_id = None
self._collection = None
@@ -127,6 +171,11 @@ class ViewParameters:
request.session['location_view_id'] = self.location_view_id
request.session['collection_id'] = self.collection_id
request.session['ref_picker_integration_id'] = self.ref_picker_integration_id
+ request.session['last_svg_view_box_str'] = (
+ str(self.last_svg_view_box) if self.last_svg_view_box is not None else None
+ )
+ request.session['last_svg_rotate'] = self.last_svg_rotate
+ request.session['svg_snap_grid_pixels'] = self.svg_snap_grid_pixels
return
@staticmethod
@@ -152,11 +201,29 @@ class ViewParameters:
'ref_picker_integration_id',
)
+ last_svg_view_box = None
+ last_svg_view_box_str = request.session.get( 'last_svg_view_box_str' )
+ if last_svg_view_box_str:
+ try:
+ last_svg_view_box = SvgViewBox.from_attribute_value( last_svg_view_box_str )
+ except ( ValueError, TypeError ):
+ last_svg_view_box = None
+
+ # Preserve an explicit 0 (snapping disabled); fall back to the
+ # default only when the key is missing or malformed.
+ try:
+ svg_snap_grid_pixels = int( request.session.get( 'svg_snap_grid_pixels' ) )
+ except ( TypeError, ValueError ):
+ svg_snap_grid_pixels = ViewParameters.DEFAULT_SVG_SNAP_GRID_PIXELS
+
return ViewParameters(
view_type = view_type,
view_mode = view_mode,
location_view_id = location_view_id,
collection_id = collection_id,
ref_picker_integration_id = ref_picker_integration_id,
+ last_svg_view_box = last_svg_view_box,
+ last_svg_rotate = request.session.get( 'last_svg_rotate' ),
+ svg_snap_grid_pixels = svg_snap_grid_pixels,
)
diff --git a/src/hi/views.py b/src/hi/views.py
index f52384e3..f1f9e12e 100644
--- a/src/hi/views.py
+++ b/src/hi/views.py
@@ -183,8 +183,28 @@ class HomeView( View ):
if query_string:
redirect_url = redirect_url + '?' + query_string
return HttpResponseRedirect( redirect_url )
-
-
+
+
+class SetSnapGridView( View ):
+ """Persist the SVG-editor snap-grid preference (screen pixels) to the
+ session view parameters so it survives reloads. Both SVG editors post
+ here on change. Value is clamped to the same range as the UI input
+ (0 = snapping disabled); malformed input is rejected."""
+
+ MIN_PIXELS = 0
+ MAX_PIXELS = 50
+
+ def post( self, request, *args, **kwargs ):
+ try:
+ value = int( request.POST.get( 'snap_grid_pixels' ) )
+ except ( TypeError, ValueError ):
+ return antinode.response( status = 400 )
+ value = max( self.MIN_PIXELS, min( value, self.MAX_PIXELS ) )
+ request.view_parameters.svg_snap_grid_pixels = value
+ request.view_parameters.to_session( request )
+ return antinode.response( status = 200 )
+
+
class StartView( View ):
def get(self, request, *args, **kwargs):
diff --git a/src/simulator.py b/src/simulator.py
index fd9a5efd..1f7b8bf5 100755
--- a/src/simulator.py
+++ b/src/simulator.py
@@ -22,11 +22,17 @@ def main():
print( "Usage: simulator.py <command> [options]" )
sys.exit(1)
- # Different default port for simulator's "runserver"
+ # Different default port for simulator's "runserver". Only supply the
+ # default when the user gave no address/port of their own. The addrport
+ # is runserver's sole positional (non-flag) argument, and it may be a
+ # bare port ("7411"), "host:port" ("192.168.100.6:7411"), or
+ # "0.0.0.0:7411" -- so detect "was an addrport given?" as "is there any
+ # non-flag argument?" rather than "is any argument all digits?".
command = sys.argv[1]
command_args = sys.argv[2:]
if command == "runserver":
- if not any( arg.isdigit() for arg in command_args ):
+ has_addrport = any( not arg.startswith( '-' ) for arg in command_args )
+ if not has_addrport:
command_args.append( "7411" )
full_command = [ 'python', manage_py_path, command ] + command_args + [ f'--settings={settings_module}' ]