Home Information - Your home, your data, organized.
Python
Restore click-through to video / details from entity state history rows (#330)
Tony Cc3cab1fec856
diff --git a/src/hi/apps/control/templatetags/control_tags.py b/src/hi/apps/control/templatetags/control_tags.pyindex d7c3402b..1e9262f5 100644--- a/src/hi/apps/control/templatetags/control_tags.py+++ b/src/hi/apps/control/templatetags/control_tags.py@@ -14,9 +14,9 @@ def include_controller_widget( context, controller : Controller ):controller's EntityStateType, falling back to``control/panes/controller_default.html``. This is the per-state-typewidget *layout* used by the EntityStatus row-list — a template-layer- concern, not a model-layer one (it assumes an inline form snippet inside- a row). Read-only value display dispatches through the model's- ``EntityStateType.value_template_name`` instead."""+ concern, not a model-layer one (it assumes an inline form snippet+ inside a row). The read-only value-display analogue is+ ``sense_tags.render_state_value_text``."""state_type_name = controller.entity_state.entity_state_type.name.lower()template_name = f'control/panes/controller_{state_type_name}.html'try:diff --git a/src/hi/apps/entity/entity_state_history.py b/src/hi/apps/entity/entity_state_history.pyindex dcecc880..63d19452 100644--- a/src/hi/apps/entity/entity_state_history.py+++ b/src/hi/apps/entity/entity_state_history.py@@ -16,6 +16,10 @@ from hi.apps.common.enums import LabeledEnumfrom hi.apps.control.models import ControllerHistoryfrom hi.apps.entity.models import EntityStatefrom hi.apps.sense.models import SensorHistory+from hi.apps.sense.sensor_history_urls import (+ sensor_history_details_url,+ sensor_history_video_browse_url,+)# Maximum delay between a controller intent and a subsequent matching@@ -69,14 +73,58 @@ class EntityStateHistoryValue:INTENT rows record an HI control action that produced noconfirming observation within the window (or where the- observation's value did not match)."""+ observation's value did not match).++ Click-through metadata (``sensor_history_id``, ``has_video_stream``,+ ``has_details``, ``provides_video_stream``) is populated on+ OBSERVATION rows from the underlying ``SensorHistory`` and the+ parent ``Sensor``. INTENT rows leave these at defaults since+ controllers don't have video or details to link to."""++ value : str+ timestamp : datetime+ entity_state : EntityState+ instrument : Instrument+ history_value_type : StateHistoryValueType+ matched_intent : Optional[ MatchedIntent ] = None+ sensor_history_id : Optional[ int ] = None+ has_video_stream : bool = False+ has_details : bool = False+ provides_video_stream : bool = False++ @property+ def video_browse_url(self) -> Optional[ str ]:+ """Click-through to the video event browser for this row.+ OBSERVATION rows route via the sensor; INTENT rows return+ ``None`` (controllers don't have video)."""+ if self.history_value_type != StateHistoryValueType.OBSERVATION:+ return None+ return sensor_history_video_browse_url(+ entity_id = self.entity_state.entity.id,+ sensor_id = self.instrument.id,+ sensor_history_id = self.sensor_history_id,+ has_video_stream = self.has_video_stream,+ provides_video_stream = self.provides_video_stream,+ )++ @property+ def details_url(self) -> Optional[ str ]:+ """Click-through to the per-row details modal for this row.+ OBSERVATION rows with detail attributes route to the details+ modal; INTENT rows return ``None``."""+ if self.history_value_type != StateHistoryValueType.OBSERVATION:+ return None+ return sensor_history_details_url(+ sensor_history_id = self.sensor_history_id,+ has_details = self.has_details,+ )- value : str- timestamp : datetime- entity_state : EntityState- instrument : Instrument- history_value_type : StateHistoryValueType- matched_intent : Optional[ MatchedIntent ] = None+ @property+ def click_url(self) -> Optional[ str ]:+ """Composite: prefers the video URL over the details URL.+ ``None`` when neither applies (e.g., INTENT rows, or+ OBSERVATION rows with no video and no details)."""+ return self.video_browse_url or self.details_urldef get_entity_state_history_page(@@ -189,6 +237,10 @@ def merge_history(instrument = _sensor_instrument( obs ),history_value_type = StateHistoryValueType.OBSERVATION,matched_intent = matched_intent,+ sensor_history_id = obs.id,+ has_video_stream = obs.has_video_stream,+ has_details = bool( obs.detail_attrs ),+ provides_video_stream = obs.sensor.provides_video_stream,))continuefor intent_history in unmatched_intents:diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.pyindex a5787579..53144358 100644--- a/src/hi/apps/entity/enums.py+++ b/src/hi/apps/entity/enums.py@@ -469,15 +469,6 @@ class EntityStateType(LabeledEnum):def toggle_values(self) -> List[str]:return [ str(x) for x in self.entity_state_value_list ]-- def value_template_name(self):- """- Template used to render a sensor's value for this state. Create the- template at the given location to define a state-specific rendering, else- it will fallback to the default template of- "entity/panes/sensor_response_value_default.html"- """- return f'sense/panes/sensor_response_value_{self.name.lower()}.html'def default_role(self) -> EntityStateRole:"""The default EntityStateRole for an EntityState of this type.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.htmlindex 363e7375..2ea734f2 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@@ -3,6 +3,7 @@{% load common_tags %}{% load humanize %}{% load icons %}+{% load sense_tags %}<div class="timeline-item mb-2"><div class="card{% if row.history_value_type.name == 'INTENT' %} border-left-warning{% else %} border-left-primary{% endif %}"><div class="card-body py-2 px-3">@@ -17,9 +18,7 @@<div class="col-md-5 col-sm-7"><div class="d-flex align-items-center"><div class="flex-grow-1">- {% with sensor_response=row %}- {% include_with_fallback row.entity_state.entity_state_type.value_template_name "sense/panes/sensor_response_value_default.html" %}- {% endwith %}+ <div class="hi-status-display text-center px-2" status="{{ 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' %}"@@ -30,16 +29,51 @@{% endif %}</div></div>- <div class="col-md-3 col-12">- {% if annotate_sources %}- <small class="text-muted d-block text-md-right mt-1 mt-md-0">- {{ row.instrument.name }}- </small>- {% endif %}- {% if row.matched_intent and annotate_sources %}- <small class="text-muted d-block text-md-right">- commanded by {{ row.matched_intent.instrument.name }}- </small>+ <div class="col-md-3 col-12 d-flex align-items-center justify-content-md-end">+ <div class="flex-grow-1 text-md-right mr-2">+ {% if annotate_sources %}+ <small class="text-muted d-block mt-1 mt-md-0">+ {{ row.instrument.name }}+ </small>+ {% endif %}+ {% if row.matched_intent and annotate_sources %}+ <small class="text-muted d-block">+ commanded by {{ row.matched_intent.instrument.name }}+ </small>+ {% endif %}+ </div>+ {% if row.video_browse_url or row.details_url %}+ <div class="hi-history-row-actions d-flex align-items-center">+ {# Render both video and details slots when the row has #}+ {# at least one click-through URL. Whichever URL is #}+ {# absent gets an invisible placeholder of the same #}+ {# dimensions so icons of the same type line up #}+ {# vertically across rows. #}+ {% if row.video_browse_url %}+ <a href="{{ row.video_browse_url }}" data-async="true"+ title="View video for this event"+ class="btn btn-sm btn-outline-primary ml-1">+ {% icon "video" size="sm" %}+ </a>+ {% else %}+ <span class="btn btn-sm btn-outline-primary ml-1 invisible"+ aria-hidden="true">+ {% icon "video" size="sm" %}+ </span>+ {% endif %}+ {% if row.details_url %}+ <a href="{{ row.details_url }}" data-async="true"+ title="View details for this event"+ class="btn btn-sm btn-outline-primary ml-1">+ {% icon "info-circle" size="sm" %}+ </a>+ {% else %}+ <span class="btn btn-sm btn-outline-primary ml-1 invisible"+ aria-hidden="true">+ {% icon "info-circle" size="sm" %}+ </span>+ {% endif %}+ </div>{% endif %}</div></div>diff --git a/src/hi/apps/entity/tests/test_entity_state_history.py b/src/hi/apps/entity/tests/test_entity_state_history.pyindex 92531230..d09ed30d 100644--- a/src/hi/apps/entity/tests/test_entity_state_history.py+++ b/src/hi/apps/entity/tests/test_entity_state_history.py@@ -345,6 +345,175 @@ class TestMergeHistory( BaseTestCase ):timestamps = [ r.timestamp for r in result ]self.assertEqual( timestamps, sorted( timestamps, reverse = True ) )+ # ------------------------------------------------------------------+ # Click-through metadata on OBSERVATION rows.++ def test_observation_row_carries_sensor_history_id(self):+ obs = self._observation( 'on', _at( 0 ) )++ result = merge_history(+ entity_state = self.state,+ observation_rows = [ obs ],+ intent_rows = [],+ )++ self.assertEqual( len( result ), 1 )+ self.assertEqual( result[ 0 ].sensor_history_id, obs.id )++ def test_observation_row_reflects_has_video_stream_from_source(self):+ obs_with = SensorHistory.objects.create(+ sensor = self.sensor, value = 'on',+ response_datetime = _at( 0 ), has_video_stream = True,+ )+ obs_without = SensorHistory.objects.create(+ sensor = self.sensor, value = 'on',+ response_datetime = _at( 1 ), has_video_stream = False,+ )++ result = merge_history(+ entity_state = self.state,+ observation_rows = [ obs_with, obs_without ],+ intent_rows = [],+ )++ by_id = { r.sensor_history_id: r for r in result }+ self.assertTrue( by_id[ obs_with.id ].has_video_stream )+ self.assertFalse( by_id[ obs_without.id ].has_video_stream )++ def test_observation_row_has_details_when_details_present(self):+ obs_with = SensorHistory.objects.create(+ sensor = self.sensor, value = 'on',+ response_datetime = _at( 0 ),+ details = '{"trigger": "motion"}',+ )+ obs_without = self._observation( 'on', _at( 1 ) )++ result = merge_history(+ entity_state = self.state,+ observation_rows = [ obs_with, obs_without ],+ intent_rows = [],+ )++ by_id = { r.sensor_history_id: r for r in result }+ self.assertTrue( by_id[ obs_with.id ].has_details )+ self.assertFalse( by_id[ obs_without.id ].has_details )++ def test_observation_row_reflects_provides_video_stream_from_sensor(self):+ # Two sensors on the same state, one with provides_video_stream+ # set. Each observation row carries its sensor's flag.+ video_sensor = Sensor.objects.create(+ entity_state = self.state,+ name = 'cam-sensor',+ sensor_type_str = 'DEFAULT',+ integration_payload = '{}',+ provides_video_stream = True,+ )+ obs_video = self._observation( 'on', _at( 0 ), sensor = video_sensor )+ obs_plain = self._observation( 'on', _at( 1 ) )++ result = merge_history(+ entity_state = self.state,+ observation_rows = [ obs_video, obs_plain ],+ intent_rows = [],+ )++ by_id = { r.sensor_history_id: r for r in result }+ self.assertTrue( by_id[ obs_video.id ].provides_video_stream )+ self.assertFalse( by_id[ obs_plain.id ].provides_video_stream )++ def test_intent_row_click_through_fields_at_defaults(self):+ intent = self._intent( 'on', _at( 0 ) )++ result = merge_history(+ entity_state = self.state,+ observation_rows = [],+ intent_rows = [ intent ],+ )++ self.assertEqual( len( result ), 1 )+ row = result[ 0 ]+ self.assertIsNone( row.sensor_history_id )+ self.assertFalse( row.has_video_stream )+ self.assertFalse( row.has_details )+ self.assertFalse( row.provides_video_stream )++ # ------------------------------------------------------------------+ # Click-through URL properties on the row type.++ def test_observation_with_video_stream_has_video_browse_url(self):+ obs = SensorHistory.objects.create(+ sensor = self.sensor, value = 'on',+ response_datetime = _at( 0 ), has_video_stream = True,+ )++ result = merge_history(+ entity_state = self.state,+ observation_rows = [ obs ],+ intent_rows = [],+ )++ self.assertIsNotNone( result[ 0 ].video_browse_url )++ def test_observation_with_details_has_details_url(self):+ obs = SensorHistory.objects.create(+ sensor = self.sensor, value = 'on',+ response_datetime = _at( 0 ),+ details = '{"trigger": "motion"}',+ )++ result = merge_history(+ entity_state = self.state,+ observation_rows = [ obs ],+ intent_rows = [],+ )++ self.assertIsNotNone( result[ 0 ].details_url )++ def test_observation_without_video_or_details_has_no_click_url(self):+ obs = self._observation( 'on', _at( 0 ) )++ result = merge_history(+ entity_state = self.state,+ observation_rows = [ obs ],+ intent_rows = [],+ )++ row = result[ 0 ]+ self.assertIsNone( row.video_browse_url )+ self.assertIsNone( row.details_url )+ self.assertIsNone( row.click_url )++ def test_intent_row_has_no_click_through_urls(self):+ intent = self._intent( 'on', _at( 0 ) )++ result = merge_history(+ entity_state = self.state,+ observation_rows = [],+ intent_rows = [ intent ],+ )++ row = result[ 0 ]+ self.assertIsNone( row.video_browse_url )+ self.assertIsNone( row.details_url )+ self.assertIsNone( row.click_url )++ def test_click_url_prefers_video_over_details(self):+ obs = SensorHistory.objects.create(+ sensor = self.sensor, value = 'on',+ response_datetime = _at( 0 ),+ has_video_stream = True,+ details = '{"trigger": "motion"}',+ )++ result = merge_history(+ entity_state = self.state,+ observation_rows = [ obs ],+ intent_rows = [],+ )++ row = result[ 0 ]+ self.assertEqual( row.click_url, row.video_browse_url )+class TestGetEntityStateHistoryPage( BaseTestCase ):"""``get_entity_state_history_page`` is the sensor-anchored pagediff --git a/src/hi/apps/entity/tests/test_enums.py b/src/hi/apps/entity/tests/test_enums.pyindex f125e02d..29d836f1 100644--- a/src/hi/apps/entity/tests/test_enums.py+++ b/src/hi/apps/entity/tests/test_enums.py@@ -10,27 +10,6 @@ from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)-class TestEntityStateType(BaseTestCase):-- def test_value_template_name_generation_supports_ui_customization(self):- """``value_template_name`` is the model-layer template-dispatch- primitive for read-only value display. Per-state-type templates- are resolved by the lowercased enum name."""- on_off_template = EntityStateType.ON_OFF.value_template_name()- temperature_template = EntityStateType.TEMPERATURE.value_template_name()-- self.assertNotEqual(on_off_template, temperature_template)-- self.assertTrue(on_off_template.startswith('sense/panes/sensor_response_value_'))- self.assertTrue(on_off_template.endswith('.html'))-- multivalued_template = EntityStateType.MULTIVALUED.value_template_name()- self.assertTrue(multivalued_template.startswith('sense/panes/sensor_response_value_'))- self.assertIn('multivalued', multivalued_template)-- return--class TestEntityStateTypeDefaultRole(BaseTestCase):def test_every_entity_state_type_resolves_to_a_role(self):diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.pyindex 884d0f71..1f64be05 100644--- a/src/hi/apps/entity/tests/test_views.py+++ b/src/hi/apps/entity/tests/test_views.py@@ -1128,8 +1128,8 @@ class TestEntityEditViewFileUploadIntegration(DualModeViewTestCase):class TestEntityStateHistoryView(DualModeViewTestCase):"""The per-EntityState history modal renders observations and- unmatched intents through the value_template_name dispatch and- supports next/prev cursor navigation."""+ unmatched intents through the ``render_state_value_text``+ templatetag dispatch and supports next/prev cursor navigation."""def setUp(self):super().setUp()@@ -1224,3 +1224,82 @@ class TestEntityStateHistoryView(DualModeViewTestCase):# Encoded "+" is "%2B"; the cursor in the Older link must be# encoded so the round-trip through the query parser preserves it.self.assertIn( '%2B00%3A00', body )++ def test_video_browse_affordance_rendered_for_video_stream_rows(self):+ """Rows whose underlying SensorHistory has_video_stream render a+ click-through to the per-event video browser; rows without it+ do not."""+ from django.urls import reverse as _reverse+ from hi.apps.sense.models import SensorHistory+ SensorHistory.objects.all().delete()+ video_obs = SensorHistory.objects.create(+ sensor = self.sensor, value = 'on',+ response_datetime = '2024-03-01T12:00:00Z',+ has_video_stream = True,+ )+ expected_url = _reverse(+ 'console_entity_video_sensor_history_detail',+ kwargs = {+ 'entity_id': self.entity.id,+ 'sensor_id': self.sensor.id,+ 'sensor_history_id': video_obs.id,+ },+ )++ url = reverse(+ 'entity_state_history',+ kwargs = { 'entity_state_id': self.state.id },+ )+ response = self.client.get(url)+ self.assertSuccessResponse(response)+ body = response.content.decode()+ self.assertIn( expected_url, body )+ self.assertIn( 'hi-history-row-actions', body )++ def test_details_affordance_rendered_for_rows_with_details(self):+ """Rows whose underlying SensorHistory has detail attributes+ render a click-through to the per-event details modal."""+ from django.urls import reverse as _reverse+ from hi.apps.sense.models import SensorHistory+ SensorHistory.objects.all().delete()+ details_obs = SensorHistory.objects.create(+ sensor = self.sensor, value = 'on',+ response_datetime = '2024-03-01T12:00:00Z',+ details = '{"trigger": "motion"}',+ )+ expected_url = _reverse(+ 'sense_sensor_history_details',+ kwargs = { 'sensor_history_id': details_obs.id },+ )++ url = reverse(+ 'entity_state_history',+ kwargs = { 'entity_state_id': self.state.id },+ )+ response = self.client.get(url)+ self.assertSuccessResponse(response)+ body = response.content.decode()+ self.assertIn( expected_url, body )+ self.assertIn( 'hi-history-row-actions', body )++ def test_no_affordances_rendered_for_plain_observation(self):+ """An observation with no video and no details has no+ click-through icons in its row."""+ from hi.apps.sense.models import SensorHistory+ SensorHistory.objects.all().delete()+ SensorHistory.objects.create(+ sensor = self.sensor, value = 'on',+ response_datetime = '2024-03-01T12:00:00Z',+ )++ url = reverse(+ 'entity_state_history',+ kwargs = { 'entity_state_id': self.state.id },+ )+ response = self.client.get(url)+ self.assertSuccessResponse(response)+ body = response.content.decode()+ # The history-row-actions wrapper only renders when at least+ # one affordance applies. A plain observation should have no+ # such wrapper.+ self.assertNotIn( 'hi-history-row-actions', body )diff --git a/src/hi/apps/sense/sensor_history_urls.py b/src/hi/apps/sense/sensor_history_urls.pynew file mode 100644index 00000000..98f358bc--- /dev/null+++ b/src/hi/apps/sense/sensor_history_urls.py@@ -0,0 +1,59 @@+"""URL-construction helpers for click-through from a sensor-history+data point (live ``SensorResponse``, persisted ``SensorHistory``, or a+merged-timeline row) to the corresponding video event browser or+details modal. Kept as pure functions of the values they need so any+data shape carrying sensor-history-derived fields can drive these+URLs without inheriting from a specific class or coupling to a+specific transient model."""++from typing import Optional++from django.urls import reverse+++def sensor_history_video_browse_url(+ *,+ entity_id : int,+ sensor_id : int,+ sensor_history_id : Optional[ int ],+ has_video_stream : bool,+ provides_video_stream : bool,+) -> Optional[ str ]:+ """Best URL to the video event browser for a given sensor-history+ data point. Returns the per-event detail URL when the data point+ itself has a stream; falls back to the sensor's event-timeline URL+ when the sensor produces streams generally; returns ``None`` when+ no video affordance is appropriate."""+ if has_video_stream and sensor_history_id:+ return reverse(+ 'console_entity_video_sensor_history_detail',+ kwargs = {+ 'entity_id': entity_id,+ 'sensor_id': sensor_id,+ 'sensor_history_id': sensor_history_id,+ },+ )+ if provides_video_stream:+ return reverse(+ 'console_entity_video_sensor_history',+ kwargs = {+ 'entity_id': entity_id,+ 'sensor_id': sensor_id,+ },+ )+ return None+++def sensor_history_details_url(+ *,+ sensor_history_id : Optional[ int ],+ has_details : bool,+) -> Optional[ str ]:+ """URL to the per-row details modal when the data point carries+ detail attributes; ``None`` otherwise."""+ if has_details and sensor_history_id:+ return reverse(+ 'sense_sensor_history_details',+ kwargs = { 'sensor_history_id': sensor_history_id },+ )+ return Nonediff --git a/src/hi/apps/sense/templates/sense/panes/sensor_response_status_row.html b/src/hi/apps/sense/templates/sense/panes/sensor_response_status_row.htmlindex 49359428..61e67189 100644--- a/src/hi/apps/sense/templates/sense/panes/sensor_response_status_row.html+++ b/src/hi/apps/sense/templates/sense/panes/sensor_response_status_row.html@@ -1,5 +1,6 @@{% load common_tags %}{% load icons %}+{% load sense_tags %}<div class="row"><div class="col-6 align-self-center"><div class="h6 text-center">@@ -35,7 +36,10 @@</div><div class="col-6 align-self-center"><a href="{{ sensor_response.click_url }}" title="See details" data-async="true">- {% include_with_fallback sensor_response.sensor.entity_state.entity_state_type.value_template_name "sense/panes/sensor_response_value_default.html" %}+ <div class="hi-status-display text-center px-2"+ data-state-id="{{ sensor_response.entity_state.id }}"+ data-status data-display-text+ status="{{ sensor_response.value }}">{% render_state_value_text sensor_response.entity_state sensor_response.value %}</div></a></div></div>diff --git a/src/hi/apps/sense/templates/sense/panes/sensor_response_value_default.html b/src/hi/apps/sense/templates/sense/panes/sensor_response_value_default.htmldeleted file mode 100644index ae3d62b9..00000000--- a/src/hi/apps/sense/templates/sense/panes/sensor_response_value_default.html+++ /dev/null@@ -1,2 +0,0 @@-{% load entity_tags units %}-<div class="hi-status-display text-center px-2" data-state-id="{{ sensor_response.sensor.entity_state.id }}" data-status data-display-text status="{{ sensor_response.value }}">{% if sensor_response.entity_state.units %}{{ sensor_response.value|as_display_value:sensor_response.entity_state }}{% else %}{{ sensor_response.value|value_label }}{% endif %}</div>diff --git a/src/hi/apps/sense/templates/sense/panes/sensor_response_value_temperature.html b/src/hi/apps/sense/templates/sense/panes/sensor_response_value_temperature.htmldeleted file mode 100644index a591e0ab..00000000--- a/src/hi/apps/sense/templates/sense/panes/sensor_response_value_temperature.html+++ /dev/null@@ -1,11 +0,0 @@-{% load units %}-{% comment %}-Temperature sensor value rendering. Server-side-``sensor_response.value`` is in the EntityState's stored unit;-the ``as_display_value`` filter goes through ``ConsoleConverterHelper``-to produce a ``DisplayValue`` whose ``__str__`` combines the-user-display magnitude and unit symbol.-{% endcomment %}-<div class="hi-status-display text-center px-2" data-state-id="{{ sensor_response.sensor.entity_state.id }}" data-status data-display-text status="{{ sensor_response.value }}">- {{ sensor_response.value|as_display_value:sensor_response.entity_state }}-</div>diff --git a/src/hi/apps/sense/templates/sense/panes/value_text_default.html b/src/hi/apps/sense/templates/sense/panes/value_text_default.htmlnew file mode 100644index 00000000..2c2f95eb--- /dev/null+++ b/src/hi/apps/sense/templates/sense/panes/value_text_default.html@@ -0,0 +1 @@+{% load entity_tags units %}{% if entity_state.units %}{{ value|as_display_value:entity_state }}{% else %}{{ value|value_label }}{% endif %}diff --git a/src/hi/apps/sense/templates/sense/panes/value_text_temperature.html b/src/hi/apps/sense/templates/sense/panes/value_text_temperature.htmlnew file mode 100644index 00000000..1675b106--- /dev/null+++ b/src/hi/apps/sense/templates/sense/panes/value_text_temperature.html@@ -0,0 +1,6 @@+{% load units %}+{# Temperature value rendering. Server-side ``value`` is in the #}+{# EntityState's stored unit; the ``as_display_value`` filter goes #}+{# through ConsoleConverterHelper to produce a DisplayValue whose #}+{# ``__str__`` combines the user-display magnitude and unit symbol. #}+{{ value|as_display_value:entity_state }}diff --git a/src/hi/apps/sense/templatetags/__init__.py b/src/hi/apps/sense/templatetags/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/sense/templatetags/sense_tags.py b/src/hi/apps/sense/templatetags/sense_tags.pynew file mode 100644index 00000000..a97aaee0--- /dev/null+++ b/src/hi/apps/sense/templatetags/sense_tags.py@@ -0,0 +1,36 @@+from django import template+from django.template.loader import get_template++from hi.apps.entity.models import EntityState++register = template.Library()++[email protected]_tag( takes_context = True )+def render_state_value_text( context, entity_state : EntityState, value : str ):+ """Render the formatted display text for a single EntityState value.++ Resolves ``sense/panes/value_text_{state_type}.html`` for the+ entity_state's type, falling back to+ ``sense/panes/value_text_default.html``. The dispatched template+ emits the formatted display text only — no outer wrapping, no+ polling markers, no click-through. The caller (e.g., the live+ sensor row or the per-state history row) supplies whatever+ outer chrome is appropriate for its context.++ This is the read-only value-display analogue of+ ``include_controller_widget`` (which dispatches interactive+ controller widgets); both are template-layer dispatches kept+ off the domain enum to avoid coupling+ ``hi.apps.entity.enums.EntityStateType`` to frontend template+ directory conventions."""+ state_type_name = entity_state.entity_state_type.name.lower()+ template_name = f'sense/panes/value_text_{state_type_name}.html'+ try:+ template_obj = get_template( template_name )+ except Exception:+ template_obj = get_template( 'sense/panes/value_text_default.html' )+ flat = context.flatten()+ flat[ 'entity_state' ] = entity_state+ flat[ 'value' ] = value+ return template_obj.render( flat )diff --git a/src/hi/apps/sense/tests/test_sense_tags.py b/src/hi/apps/sense/tests/test_sense_tags.pynew file mode 100644index 00000000..474d4543--- /dev/null+++ b/src/hi/apps/sense/tests/test_sense_tags.py@@ -0,0 +1,54 @@+import logging++from django.template import Context, Template++from hi.apps.entity.models import Entity, EntityState+from hi.testing.base_test_case import BaseTestCase++logging.disable( logging.CRITICAL )+++class TestRenderStateValueText( BaseTestCase ):+ """``render_state_value_text`` is the EntityStatus-layer dispatch+ that resolves the per-state-type value-text template, with+ fallback to the default. Lives in the sense app rather than on+ ``EntityStateType`` because the path scheme is a frontend+ convention, not a model property — parallel to+ ``include_controller_widget`` for the interactive controller side."""++ def _render( self, entity_state, value ):+ return Template(+ '{% load sense_tags %}'+ '{% render_state_value_text entity_state value %}'+ ).render( Context({ 'entity_state': entity_state, 'value': value }) )++ def test_resolves_per_state_type_template_when_present( self ):+ entity = Entity.objects.create(+ name = 'Thermometer', entity_type_str = 'THERMOMETER',+ )+ state = EntityState.objects.create(+ entity = entity, entity_state_type_str = 'TEMPERATURE', units = '°C',+ )+ # ``value_text_temperature.html`` exists; rendering should+ # produce its content (the as_display_value filter output),+ # not the default template's output. The filter passes through+ # ConsoleConverterHelper which converts to the user's preferred+ # display unit — assert a temperature unit symbol is present,+ # confirming the temperature-specific template ran.+ output = self._render( state, '21' ).strip()+ self.assertTrue( output )+ self.assertIn( '°', output )++ def test_falls_back_to_default_for_unimplemented_state_type( self ):+ # No ``value_text_on_off.html`` exists — must fall through to+ # ``value_text_default.html`` without raising.+ entity = Entity.objects.create(+ name = 'Switch', entity_type_str = 'WALL_SWITCH',+ )+ state = EntityState.objects.create(+ entity = entity, entity_state_type_str = 'ON_OFF',+ )+ output = self._render( state, 'on' ).strip()+ # Default template renders through value_label filter for+ # unit-less values — output is non-empty.+ self.assertTrue( output )diff --git a/src/hi/apps/sense/tests/test_sensor_history_urls.py b/src/hi/apps/sense/tests/test_sensor_history_urls.pynew file mode 100644index 00000000..8125147f--- /dev/null+++ b/src/hi/apps/sense/tests/test_sensor_history_urls.py@@ -0,0 +1,89 @@+import logging++from hi.apps.sense.sensor_history_urls import (+ sensor_history_details_url,+ sensor_history_video_browse_url,+)+from hi.testing.base_test_case import BaseTestCase++logging.disable( logging.CRITICAL )+++class TestSensorHistoryVideoBrowseUrl( BaseTestCase ):+ """``sensor_history_video_browse_url`` returns the most-specific+ appropriate URL: the per-event detail URL when the data point+ itself has a stream, else the per-sensor timeline URL when the+ sensor produces streams generally, else ``None``."""++ def test_specific_event_url_when_data_point_has_stream(self):+ url = sensor_history_video_browse_url(+ entity_id = 1, sensor_id = 2, sensor_history_id = 3,+ has_video_stream = True, provides_video_stream = True,+ )+ self.assertIsNotNone( url )+ self.assertIn( '3', url )++ def test_per_sensor_timeline_when_only_sensor_provides(self):+ # No data-point-level stream, but the sensor produces streams.+ # Fall back to the per-sensor timeline URL (no sensor_history_id+ # in the path).+ url = sensor_history_video_browse_url(+ entity_id = 1, sensor_id = 2, sensor_history_id = 3,+ has_video_stream = False, provides_video_stream = True,+ )+ self.assertIsNotNone( url )+ self.assertNotIn( '3', url )++ def test_none_when_neither_stream_capability(self):+ url = sensor_history_video_browse_url(+ entity_id = 1, sensor_id = 2, sensor_history_id = 3,+ has_video_stream = False, provides_video_stream = False,+ )+ self.assertIsNone( url )++ def test_none_when_has_stream_but_no_history_id(self):+ # has_video_stream=True without a sensor_history_id can't form+ # a per-event URL; the fallback (provides_video_stream=False)+ # also doesn't apply, so the result is None.+ url = sensor_history_video_browse_url(+ entity_id = 1, sensor_id = 2, sensor_history_id = None,+ has_video_stream = True, provides_video_stream = False,+ )+ self.assertIsNone( url )++ def test_falls_back_to_per_sensor_when_has_stream_but_no_history_id(self):+ # Edge: has_video_stream=True but sensor_history_id missing.+ # If the sensor itself provides streams, fall back to the+ # per-sensor timeline.+ url = sensor_history_video_browse_url(+ entity_id = 1, sensor_id = 2, sensor_history_id = None,+ has_video_stream = True, provides_video_stream = True,+ )+ self.assertIsNotNone( url )+ self.assertIn( '1', url )+ self.assertIn( '2', url )+++class TestSensorHistoryDetailsUrl( BaseTestCase ):+ """``sensor_history_details_url`` returns the details modal URL+ when both a sensor_history_id and detail attributes are present;+ ``None`` otherwise."""++ def test_url_returned_when_has_details_and_id(self):+ url = sensor_history_details_url(+ sensor_history_id = 42, has_details = True,+ )+ self.assertIsNotNone( url )+ self.assertIn( '42', url )++ def test_none_when_no_details(self):+ url = sensor_history_details_url(+ sensor_history_id = 42, has_details = False,+ )+ self.assertIsNone( url )++ def test_none_when_no_history_id(self):+ url = sensor_history_details_url(+ sensor_history_id = None, has_details = True,+ )+ self.assertIsNone( url )diff --git a/src/hi/apps/sense/transient_models.py b/src/hi/apps/sense/transient_models.pyindex ae989611..ca5c409d 100644--- a/src/hi/apps/sense/transient_models.py+++ b/src/hi/apps/sense/transient_models.py@@ -11,6 +11,10 @@ from hi.integrations.transient_models import IntegrationKeyfrom .models import Sensor, SensorHistoryfrom .enums import CorrelationRole+from .sensor_history_urls import (+ sensor_history_details_url,+ sensor_history_video_browse_url,+)@dataclass@@ -54,24 +58,21 @@ class SensorResponse:return bool( self.value == str(EntityStateValue.OPEN) )@property- def video_browse_url(self) -> str:- if self.has_video_stream and self.sensor_history_id:- return reverse( 'console_entity_video_sensor_history_detail',- kwargs = { 'entity_id': self.entity.id,- 'sensor_id': self.sensor.id,- 'sensor_history_id': self.sensor_history_id })- if self.sensor.provides_video_stream:- return reverse( 'console_entity_video_sensor_history',- kwargs = { 'entity_id': self.entity.id,- 'sensor_id': self.sensor.id })- return None-+ def video_browse_url(self) -> Optional[ str ]:+ return sensor_history_video_browse_url(+ entity_id = self.entity.id,+ sensor_id = self.sensor.id,+ sensor_history_id = self.sensor_history_id,+ has_video_stream = self.has_video_stream,+ provides_video_stream = self.sensor.provides_video_stream,+ )+@property- def details_url(self) -> str:- if self.has_details:- return reverse( 'sense_sensor_history_details',- kwargs = { 'sensor_history_id': self.sensor_history_id })- return None+ def details_url(self) -> Optional[ str ]:+ return sensor_history_details_url(+ sensor_history_id = self.sensor_history_id,+ has_details = self.has_details,+ )@propertydef entity_state_history_url(self) -> str: