Skip to content

Home Information - Your home, your data, organized.

Python

Issue #323: Per-EntityState merged history view with intent-observation correlation (#325)

Tony C3f384a1d529f
diff --git a/src/hi/apps/common/datetimeproxy.py b/src/hi/apps/common/datetimeproxy.py
index 7c6a56bb..5116d8ac 100644
--- a/src/hi/apps/common/datetimeproxy.py
+++ b/src/hi/apps/common/datetimeproxy.py
@@ -101,6 +101,22 @@ def datetime_to_rfc2822( the_dt = None ):
return format_datetime(the_dt)
+def iso_str_to_datetime( iso_string : str ):
+ """Parse an ISO 8601 string into a timezone-aware datetime.
+ Raises ValueError if not parsable. Naive inputs are interpreted
+ as UTC to match the convention used elsewhere in this module."""
+ parsed = datetime.datetime.fromisoformat( iso_string )
+ if parsed.tzinfo is None:
+ parsed = parsed.replace( tzinfo = pytz.utc )
+ return parsed
+
+
+def datetime_to_iso_str( the_dt : datetime.datetime ) -> str:
+ """Format a datetime for URL-safe cursor passing. Round-trips
+ with ``iso_str_to_datetime``."""
+ return the_dt.isoformat()
+
+
def rfc2822_to_datetime(rfc2822_string):
"""
Parses a date/time string in the RFC 2822 format into a time-aware
diff --git a/src/hi/apps/common/tests/test_utils.py b/src/hi/apps/common/tests/test_utils.py
index 20ed106f..0ed05135 100644
--- a/src/hi/apps/common/tests/test_utils.py
+++ b/src/hi/apps/common/tests/test_utils.py
@@ -279,3 +279,57 @@ class CommonUtilsTestCase(TestCase):
continue
return
+
+
+class TestStripParentNamePrefix(TestCase):
+ """``strip_parent_name_prefix`` removes a leading parent-name prefix
+ so list contexts that already display the parent name don't repeat
+ it on every child row."""
+
+ def test_strips_with_space_separator(self):
+ self.assertEqual(
+ utils.strip_parent_name_prefix( 'Zoo Heater Fan Mode', 'Zoo Heater' ),
+ 'Fan Mode',
+ )
+
+ def test_strips_with_dash_separator(self):
+ self.assertEqual(
+ utils.strip_parent_name_prefix( 'Zoo Heater - Fan Mode', 'Zoo Heater' ),
+ 'Fan Mode',
+ )
+
+ def test_case_insensitive_prefix_match(self):
+ self.assertEqual(
+ utils.strip_parent_name_prefix( 'zoo heater fan mode', 'Zoo Heater' ),
+ 'fan mode',
+ )
+
+ def test_returns_full_when_no_prefix_match(self):
+ self.assertEqual(
+ utils.strip_parent_name_prefix( 'Outdoor Temperature', 'Zoo Heater' ),
+ 'Outdoor Temperature',
+ )
+
+ def test_returns_full_when_stripping_leaves_nothing(self):
+ self.assertEqual(
+ utils.strip_parent_name_prefix( 'Zoo Heater', 'Zoo Heater' ),
+ 'Zoo Heater',
+ )
+
+ def test_returns_full_when_parent_name_empty(self):
+ self.assertEqual(
+ utils.strip_parent_name_prefix( 'Zoo Heater Fan Mode', '' ),
+ 'Zoo Heater Fan Mode',
+ )
+
+ def test_returns_empty_string_when_full_name_empty(self):
+ self.assertEqual(
+ utils.strip_parent_name_prefix( '', 'Zoo Heater' ),
+ '',
+ )
+
+ def test_handles_none_full_name(self):
+ self.assertEqual(
+ utils.strip_parent_name_prefix( None, 'Zoo Heater' ),
+ '',
+ )
diff --git a/src/hi/apps/common/utils.py b/src/hi/apps/common/utils.py
index f7e81601..aca0f812 100644
--- a/src/hi/apps/common/utils.py
+++ b/src/hi/apps/common/utils.py
@@ -190,4 +190,20 @@ def to_dict_or_none( obj ):
return None
return obj.to_dict()
+
+def strip_parent_name_prefix( full_name : str, parent_name : str ) -> str:
+ """Strip a leading parent-name prefix from ``full_name``
+ (case-insensitive, tolerating common separator characters).
+ Falls back to ``full_name`` when stripping would leave nothing
+ meaningful. Used by display contexts where the parent name is
+ already visible elsewhere in the surrounding chrome."""
+ full = full_name or ''
+ if not parent_name:
+ return full
+ if full.lower().startswith( parent_name.lower() ):
+ remainder = full[ len( parent_name ): ].lstrip( ' -:_/' ).strip()
+ if remainder:
+ return remainder
+ return full
+
diff --git a/src/hi/apps/control/controller_history_manager.py b/src/hi/apps/control/controller_history_manager.py
index 864c36b0..2b3f3f59 100644
--- a/src/hi/apps/control/controller_history_manager.py
+++ b/src/hi/apps/control/controller_history_manager.py
@@ -1,8 +1,6 @@
import logging
-from typing import Dict, List
from hi.apps.common.singleton import Singleton
-from hi.apps.entity.models import Entity
from .models import Controller, ControllerHistory
@@ -10,12 +8,10 @@ logger = logging.getLogger(__name__)
class ControllerHistoryManager( Singleton ):
-
- ENTITY_STATE_HISTORY_ITEM_MAX = 5
-
+
def __init_singleton__( self ):
return
-
+
def add_to_controller_history( self, controller : Controller, value : str ):
if not controller.persist_history:
return
@@ -24,25 +20,3 @@ class ControllerHistoryManager( Singleton ):
controller = controller,
value = value,
)
-
- def get_latest_entity_controller_history(
- self,
- entity : Entity,
- max_items : int = 5 ) -> Dict[ Controller, List[ ControllerHistory ] ]:
-
- entity_state_list = list( entity.states.all() )
- entity_state_delegations = entity.entity_state_delegations.select_related('entity_state').all()
- entity_state_list.extend([ x.entity_state for x in entity_state_delegations ])
-
- controller_list = list()
- for entity_state in entity_state_list:
- controller_list.extend( entity_state.controllers.all() )
- continue
-
- controller_history_list_map = dict()
- for controller in controller_list:
- controller_history_list = ControllerHistory.objects.filter( controller = controller )[0:max_items]
- controller_history_list_map[controller] = controller_history_list
- continue
-
- return controller_history_list_map
diff --git a/src/hi/apps/control/models.py b/src/hi/apps/control/models.py
index 37877942..de95c611 100644
--- a/src/hi/apps/control/models.py
+++ b/src/hi/apps/control/models.py
@@ -1,5 +1,6 @@
from django.db import models
+from hi.apps.common.utils import strip_parent_name_prefix
from hi.apps.entity.models import EntityState
from hi.integrations.models import IntegrationDetailsModel
@@ -59,6 +60,12 @@ class Controller( IntegrationDetailsModel ):
def choices(self):
return self.entity_state.choices()
+ @property
+ def short_name(self):
+ """Name with the leading entity-name prefix stripped, for
+ display contexts where the entity name is already visible."""
+ return strip_parent_name_prefix( self.name, self.entity_state.entity.name )
+
class ControllerHistory(models.Model):
diff --git a/src/hi/apps/control/templates/control/modals/controller_history.html b/src/hi/apps/control/templates/control/modals/controller_history.html
deleted file mode 100644
index bee74f9d..00000000
--- a/src/hi/apps/control/templates/control/modals/controller_history.html
+++ /dev/null
@@ -1,14 +0,0 @@
-{% extends "modals/action_done.html" %}
-
-{% block title_text %}
-{{ controller.name }}
-{% endblock %}
-
-{% block body %}
-<h5>Controller History</h5>
-<div class="py-2">
- {% include "control/panes/controller_history_list.html" with controller_response_list=controller_response_list %}
-</div>
-{% include "common/panes/pagination.html" with pagination=pagination %}
-
-{% endblock %}
diff --git a/src/hi/apps/control/templates/control/panes/controller_data_row.html b/src/hi/apps/control/templates/control/panes/controller_data_row.html
index f7ca7c50..b10b8a6f 100644
--- a/src/hi/apps/control/templates/control/panes/controller_data_row.html
+++ b/src/hi/apps/control/templates/control/panes/controller_data_row.html
@@ -3,11 +3,11 @@
<div class="row my-2">
<div class="col-6 align-self-center">
<div class="h6 text-center">
- {{ controller_data.controller.name }}
+ {{ controller_data.controller.short_name }}
</div>
<div class="d-flex justify-content-around mt-2">
<div>
- <a href="{{ controller_data.controller_history_url }}"
+ <a href="{{ controller_data.entity_state_history_url }}"
class="btn btn-sm btn-outline-primary"
data-async="true">
{% icon "history" size="sm" %} History
diff --git a/src/hi/apps/control/templates/control/panes/controller_history_list.html b/src/hi/apps/control/templates/control/panes/controller_history_list.html
deleted file mode 100644
index 203599a8..00000000
--- a/src/hi/apps/control/templates/control/panes/controller_history_list.html
+++ /dev/null
@@ -1,31 +0,0 @@
-{% load tz %}
-{% load common_tags %}
-{% timezone USER_TIMEZONE %}
-{# Dispatches through value_template_name (read-only value display), #}
-{# NOT controller_template_name's old role (interactive form widget). #}
-{# Controllers and their paired sensors share an EntityState — so their #}
-{# values share a value space — and history is always read-only. #}
-<div class="table-responsive">
- <table class="table table-striped">
- <tbody>
- {% for sensor_response in controller_response_list %}
- <tr>
- <td>
- {% include_with_fallback sensor_response.sensor.entity_state.entity_state_type.value_template_name "sense/panes/sensor_response_value_default.html" %}
- </td>
- <td>{{ sensor_response.timestamp|localtime }}</td>
- </tr>
- {% empty %}
- <tr><td colspan="2"><div class="alert alert-info" >No history.</div></td></tr>
- {% endfor %}
- </tbody>
- </table>
-</div>
-
-{% if show_all_link and controller_response_list %}
-<div>
- <a href="{% url 'control_controller_history' controller_id=controller.id %}"
- data-async="true">&gt;&gt; See All</a>
-</div>
-{% endif %}
-{% endtimezone %}
diff --git a/src/hi/apps/control/tests/test_controller_history_manager.py b/src/hi/apps/control/tests/test_controller_history_manager.py
index 5228e469..86212f5d 100644
--- a/src/hi/apps/control/tests/test_controller_history_manager.py
+++ b/src/hi/apps/control/tests/test_controller_history_manager.py
@@ -2,7 +2,7 @@ import logging
from hi.apps.control.controller_history_manager import ControllerHistoryManager
from hi.apps.control.models import Controller, ControllerHistory
-from hi.apps.entity.models import Entity, EntityState, EntityStateDelegation
+from hi.apps.entity.models import Entity, EntityState
from hi.testing.base_test_case import BaseTestCase
logging.disable(logging.CRITICAL)
@@ -81,142 +81,4 @@ class TestControllerHistoryManager(BaseTestCase):
self.assertEqual(ControllerHistory.objects.filter(controller=controller).count(), 0)
return
- def test_get_latest_entity_controller_history_direct_states(self):
- """Test entity controller history retrieval for direct states - complex data aggregation."""
- entity = Entity.objects.create(
- name='Test Entity',
- entity_type_str='CAMERA'
- )
- entity_state = EntityState.objects.create(
- entity=entity,
- entity_state_type_str='ON_OFF'
- )
-
- controller = Controller.objects.create(
- name='Test Controller',
- entity_state=entity_state,
- controller_type_str='DEFAULT',
- integration_id='test_id',
- integration_name='test_integration'
- )
-
- # Create history records
- history1 = ControllerHistory.objects.create(
- controller=controller,
- value='on'
- )
- history2 = ControllerHistory.objects.create(
- controller=controller,
- value='off'
- )
-
- manager = ControllerHistoryManager()
- history_map = manager.get_latest_entity_controller_history(entity, max_items=5)
-
- # Should return map with controller history
- self.assertIn(controller, history_map)
- controller_history = list(history_map[controller])
-
- # Should be ordered newest first
- self.assertEqual(len(controller_history), 2)
- self.assertEqual(controller_history[0], history2) # Most recent
- self.assertEqual(controller_history[1], history1)
- return
-
- def test_get_latest_entity_controller_history_delegated_states(self):
- """Test entity controller history for delegated states - complex relationship handling."""
- # Create primary entity
- primary_entity = Entity.objects.create(
- name='Primary Entity',
- entity_type_str='CAMERA'
- )
-
- # Create delegated entity and state
- delegated_entity = Entity.objects.create(
- name='Delegated Entity',
- entity_type_str='LIGHT'
- )
- delegated_state = EntityState.objects.create(
- entity=delegated_entity,
- entity_state_type_str='ON_OFF'
- )
-
- # Create delegation
- EntityStateDelegation.objects.create(
- delegate_entity=primary_entity,
- entity_state=delegated_state
- )
-
- # Create controller for delegated state
- controller = Controller.objects.create(
- name='Delegated Controller',
- entity_state=delegated_state,
- controller_type_str='DEFAULT',
- integration_id='test_id',
- integration_name='test_integration'
- )
-
- # Create history
- history = ControllerHistory.objects.create(
- controller=controller,
- value='on'
- )
-
- manager = ControllerHistoryManager()
- history_map = manager.get_latest_entity_controller_history(primary_entity, max_items=5)
-
- # Should include controllers from delegated states
- self.assertIn(controller, history_map)
- controller_history = list(history_map[controller])
- self.assertEqual(len(controller_history), 1)
- self.assertEqual(controller_history[0], history)
- return
-
- def test_get_latest_entity_controller_history_max_items_limit(self):
- """Test history retrieval max items limit - performance optimization."""
- entity = Entity.objects.create(
- name='Test Entity',
- entity_type_str='CAMERA'
- )
- entity_state = EntityState.objects.create(
- entity=entity,
- entity_state_type_str='ON_OFF'
- )
-
- controller = Controller.objects.create(
- name='Test Controller',
- entity_state=entity_state,
- controller_type_str='DEFAULT',
- integration_id='test_id',
- integration_name='test_integration'
- )
-
- # Create more history records than the limit
- for i in range(10):
- ControllerHistory.objects.create(
- controller=controller,
- value=f'value_{i}'
- )
-
- manager = ControllerHistoryManager()
- history_map = manager.get_latest_entity_controller_history(entity, max_items=3)
-
- # Should limit to max_items
- controller_history = list(history_map[controller])
- self.assertEqual(len(controller_history), 3)
-
- # Should be the most recent ones
- self.assertEqual(controller_history[0].value, 'value_9') # Most recent
- self.assertEqual(controller_history[1].value, 'value_8')
- self.assertEqual(controller_history[2].value, 'value_7')
- return
-
- def test_entity_state_history_item_max_constant(self):
- """Test ENTITY_STATE_HISTORY_ITEM_MAX constant - important for default behavior."""
- manager = ControllerHistoryManager()
-
- # Should have reasonable default limit
- self.assertEqual(manager.ENTITY_STATE_HISTORY_ITEM_MAX, 5)
- self.assertGreater(manager.ENTITY_STATE_HISTORY_ITEM_MAX, 0)
- self.assertLess(manager.ENTITY_STATE_HISTORY_ITEM_MAX, 100)
return
diff --git a/src/hi/apps/control/tests/test_views.py b/src/hi/apps/control/tests/test_views.py
index ffe9371e..dce33084 100644
--- a/src/hi/apps/control/tests/test_views.py
+++ b/src/hi/apps/control/tests/test_views.py
@@ -5,11 +5,11 @@ from django.urls import reverse
from hi.apps.control.controller_history_manager import ControllerHistoryManager
from hi.apps.control.controller_manager import ControllerManager
-from hi.apps.control.models import Controller, ControllerHistory
+from hi.apps.control.models import Controller
from hi.apps.entity.models import Entity, EntityState
from hi.apps.entity.enums import EntityStateType, EntityStateValue
from hi.apps.monitor.status_display_manager import StatusDisplayManager
-from hi.testing.view_test_base import SyncViewTestCase, DualModeViewTestCase
+from hi.testing.view_test_base import SyncViewTestCase
logging.disable(logging.CRITICAL)
@@ -145,183 +145,3 @@ class TestControllerView(SyncViewTestCase):
result = view._get_value_for_missing_input(test_controller)
self.assertEqual(result, str(expected_value))
-
-
-class TestControllerHistoryView(DualModeViewTestCase):
- """
- Tests for ControllerHistoryView - demonstrates HiModalView with pagination testing.
- This view displays the history of controller actions.
- """
-
- def setUp(self):
- super().setUp()
- # Create test entity and controller
- self.entity = Entity.objects.create(
- name='Test Switch',
- entity_type_str='SWITCH'
- )
- self.entity_state = EntityState.objects.create(
- entity=self.entity,
- name='state',
- entity_state_type_str='ON_OFF'
- )
- self.controller = Controller.objects.create(
- entity_state=self.entity_state,
- controller_type_str='SWITCH',
- integration_payload='{"device_id": "test_switch"}'
- )
-
- # Create some test history entries
- for i in range(5):
- ControllerHistory.objects.create(
- controller=self.controller,
- value=f'test_value_{i}',
- created_datetime=f'2023-01-0{i+1}T12:00:00Z'
- )
-
- def test_get_controller_history_sync(self):
- """Test getting controller history with synchronous request."""
- url = reverse('control_controller_history', kwargs={'controller_id': self.controller.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- self.assertHtmlResponse(response)
- self.assertTemplateRendered(response, 'control/modals/controller_history.html')
-
- def test_get_controller_history_async(self):
- """Test getting controller history with AJAX request."""
- url = reverse('control_controller_history', kwargs={'controller_id': self.controller.id})
- response = self.async_get(url)
-
- self.assertSuccessResponse(response)
- self.assertJsonResponse(response)
-
- # HiModalView returns JSON with modal content for AJAX requests
- data = response.json()
- self.assertIn('modal', data)
-
- def test_controller_and_history_in_context(self):
- """Test that controller and history are passed to template context."""
- url = reverse('control_controller_history', kwargs={'controller_id': self.controller.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- self.assertEqual(response.context['controller'], self.controller)
- self.assertIn('controller_response_list', response.context)
- self.assertIn('pagination', response.context)
-
- def test_pagination_context(self):
- """Test that pagination is properly configured."""
- url = reverse('control_controller_history', kwargs={'controller_id': self.controller.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- pagination = response.context['pagination']
- self.assertIsNotNone(pagination)
- # Should have base URL for controller history
- self.assertIn(str(self.controller.id), pagination.base_url)
-
- def test_history_filtered_by_controller(self):
- """Test that history is filtered to only this controller."""
- # Create another controller with history
- other_entity = Entity.objects.create(
- name='Other Device',
- entity_type_str='LIGHT'
- )
- other_entity_state = EntityState.objects.create(
- entity=other_entity,
- name='brightness',
- entity_state_type_str='NUMERIC'
- )
- other_controller = Controller.objects.create(
- entity_state=other_entity_state,
- controller_type_str='DIMMER',
- integration_payload='{"device_id": "other_device"}'
- )
- ControllerHistory.objects.create(
- controller=other_controller,
- value='other_value',
- created_datetime='2023-01-10T12:00:00Z'
- )
-
- url = reverse('control_controller_history', kwargs={'controller_id': self.controller.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- history_list = response.context['controller_response_list']
-
- # All adapted responses should reference our controller
- for response_entry in history_list:
- self.assertEqual(response_entry.controller, self.controller)
-
- def test_nonexistent_controller_returns_404(self):
- """Test that accessing nonexistent controller returns 404."""
- url = reverse('control_controller_history', kwargs={'controller_id': 99999})
- response = self.client.get(url)
-
- self.assertEqual(response.status_code, 404)
-
- def test_pagination_with_many_entries(self):
- """Test pagination when there are many history entries."""
- # Create many more history entries to test pagination
- for i in range(50):
- ControllerHistory.objects.create(
- controller=self.controller,
- value=f'bulk_value_{i}',
- created_datetime=f'2023-02-{(i % 28) + 1:02d}T12:00:00Z'
- )
-
- url = reverse('control_controller_history', kwargs={'controller_id': self.controller.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- history_list = response.context['controller_response_list']
-
- # Should be limited by page size (25)
- self.assertLessEqual(len(history_list), 25)
-
- def test_post_not_allowed(self):
- """Test that POST requests are not allowed."""
- url = reverse('control_controller_history', kwargs={'controller_id': self.controller.id})
- response = self.client.post(url)
-
- self.assertEqual(response.status_code, 405)
-
-
-class TestControllerHistoryRendering(DualModeViewTestCase):
- """Controller history dispatches each row through
- ``EntityStateType.value_template_name`` (the read-only value
- display) — not ``controller_template_name``'s old role
- (interactive widget). Discrete-enum stored values render as
- their human-readable labels."""
-
- def test_discrete_value_renders_as_human_readable_label(self):
- import json
- entity = Entity.objects.create( name = 'Switch', entity_type_str = 'WALL_SWITCH' )
- state = EntityState.objects.create(
- entity = entity,
- name = 'on_off',
- entity_state_type_str = 'ON_OFF',
- value_range_str = json.dumps([ 'on', 'off' ]),
- )
- controller = Controller.objects.create(
- entity_state = state,
- controller_type_str = 'DEFAULT',
- integration_payload = '{"device_id": "sw1"}',
- )
- ControllerHistory.objects.create(
- controller = controller, value = 'on',
- created_datetime = '2024-03-01T12:00:00Z',
- )
-
- url = reverse( 'control_controller_history',
- kwargs = { 'controller_id': controller.id } )
- response = self.client.get( url )
- self.assertSuccessResponse( response )
- body = response.content.decode()
- # 'on' is an EntityStateValue enum member → its label is 'On'.
- self.assertIn( 'On', body )
- # The interactive widget chrome (the toggle switch class from
- # controller_on_off.html) must NOT appear in history rendering.
- self.assertNotIn( 'switch-modern', body )
-
diff --git a/src/hi/apps/control/transient_models.py b/src/hi/apps/control/transient_models.py
index df24ea90..7a9cf81f 100644
--- a/src/hi/apps/control/transient_models.py
+++ b/src/hi/apps/control/transient_models.py
@@ -1,12 +1,11 @@
from dataclasses import dataclass
-from datetime import datetime
from typing import List
from django.urls import reverse
from hi.apps.sense.transient_models import SensorResponse
-from .models import Controller, ControllerHistory
+from .models import Controller
@dataclass
@@ -24,44 +23,13 @@ class ControllerData:
return self.controller.entity_state
@property
- def controller_history_url(self):
- return reverse( 'control_controller_history',
- kwargs = { 'controller_id': self.controller.id })
-
+ def entity_state_history_url(self):
+ return reverse( 'entity_state_history',
+ kwargs = { 'entity_state_id': self.controller.entity_state.id })
+
@property
def css_class(self):
return self.controller.entity_state.css_class
-
-
-@dataclass
-class ControllerHistoryResponse:
- """Adapter exposing a ControllerHistory row through the surface the
- per-state-type value templates read from a SensorResponse:
- ``.value``, ``.timestamp``, ``.entity_state``. Used by the controller
- history list so it dispatches through
- ``EntityStateType.value_template_name`` — the canonical read-only
- value display — instead of the interactive controller widget.
-
- The loop-variable name ``sensor_response`` in the per-state-type
- templates is a duck-typed slot: both ``SensorResponse`` and this
- adapter satisfy the access pattern. A neutral rename of the
- template variable lives with the merged-history work in #323."""
-
- value : str
- timestamp : datetime
- controller : Controller
-
- @classmethod
- def from_controller_history( cls, controller_history : ControllerHistory ) -> 'ControllerHistoryResponse':
- return cls(
- value = controller_history.value,
- timestamp = controller_history.created_datetime,
- controller = controller_history.controller,
- )
-
- @property
- def entity_state(self):
- return self.controller.entity_state
@dataclass
@@ -69,8 +37,7 @@ class ControllerOutcome:
controller : Controller
new_value : str
error_list : List[ str ] = None
-
+
@property
def has_errors(self):
return bool( self.error_list )
-
diff --git a/src/hi/apps/control/urls.py b/src/hi/apps/control/urls.py
index 24dafd29..04eea420 100644
--- a/src/hi/apps/control/urls.py
+++ b/src/hi/apps/control/urls.py
@@ -5,11 +5,7 @@ from . import views
urlpatterns = [
- re_path( r'^controller/(?P<controller_id>\d+)$',
- views.ControllerView.as_view(),
+ re_path( r'^controller/(?P<controller_id>\d+)$',
+ views.ControllerView.as_view(),
name='control_controller'),
-
- re_path( r'^controller/history/(?P<controller_id>\d+)$',
- views.ControllerHistoryView.as_view(),
- name='control_controller_history'),
]
diff --git a/src/hi/apps/control/views.py b/src/hi/apps/control/views.py
index 22c50bed..b4b278a9 100644
--- a/src/hi/apps/control/views.py
+++ b/src/hi/apps/control/views.py
@@ -1,17 +1,12 @@
import logging
-from django.urls import reverse
from django.views.generic import View
-from hi.apps.common.pagination import compute_pagination_from_queryset
from hi.apps.entity.enums import EntityStateType, EntityStateValue
from hi.apps.monitor.status_display_manager import StatusDisplayManager
-from hi.hi_async_view import HiModalView
-
from .control_mixins import ControllerMixin
-from .models import Controller, ControllerHistory
-from .transient_models import ControllerHistoryResponse
+from .models import Controller
from .view_mixins import ControlViewMixin
logger = logging.getLogger(__name__)
@@ -89,34 +84,3 @@ class ControllerView( View, ControlViewMixin, ControllerMixin ):
if controller.entity_state.entity_state_type in self.MISSING_VALUE_MAP:
return str( self.MISSING_VALUE_MAP.get( controller.entity_state.entity_state_type ))
return 'unknown'
-
-
-class ControllerHistoryView( HiModalView, ControlViewMixin ):
-
- CONTROLLER_HISTORY_PAGE_SIZE = 25
-
- def get_template_name( self ) -> str:
- return 'control/modals/controller_history.html'
-
- def get( self, request, *args, **kwargs ):
-
- controller = self.get_controller( request, *args, **kwargs )
- base_url = reverse( 'control_controller_history', kwargs = { 'controller_id': controller.id } )
-
- queryset = ControllerHistory.objects.filter( controller = controller )
- pagination = compute_pagination_from_queryset( request = request,
- queryset = queryset,
- base_url = base_url,
- page_size = self.CONTROLLER_HISTORY_PAGE_SIZE,
- async_urls = True )
- controller_history_list = queryset[pagination.start_offset:pagination.end_offset + 1]
- controller_response_list = [
- ControllerHistoryResponse.from_controller_history( h ) for h in controller_history_list
- ]
-
- context = {
- 'controller': controller,
- 'controller_response_list': controller_response_list,
- 'pagination': pagination,
- }
- return self.modal_response( request, context )
diff --git a/src/hi/apps/entity/entity_state_history.py b/src/hi/apps/entity/entity_state_history.py
new file mode 100644
index 00000000..dcecc880
--- /dev/null
+++ b/src/hi/apps/entity/entity_state_history.py
@@ -0,0 +1,224 @@
+"""Per-EntityState merged history: a chronological view of an
+EntityState's value over time, combining sensor observations and
+controller intents on a single timeline.
+
+An observation that occurs shortly after a controller intent with
+the same value absorbs that intent as an annotation. Unmatched
+intents (control actions that produced no confirming observation
+within the merge window) emit as standalone rows so failed or
+yet-to-be-confirmed commands stay visible."""
+
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+from typing import Dict, List, Optional
+
+from hi.apps.common.enums import LabeledEnum
+from hi.apps.control.models import ControllerHistory
+from hi.apps.entity.models import EntityState
+from hi.apps.sense.models import SensorHistory
+
+
+# Maximum delay between a controller intent and a subsequent matching
+# sensor observation for the two to collapse into a single row.
+# Bounds typical polling jitter and the local force-set write HI
+# performs at control time.
+MERGE_WINDOW_SECONDS = 10
+
+
+class StateHistoryValueType(LabeledEnum):
+
+ OBSERVATION = ( 'Observation' , '' )
+ INTENT = ( 'Intent' , '' )
+
+
+class InstrumentType(LabeledEnum):
+
+ SENSOR = ( 'Sensor' , '' )
+ CONTROLLER = ( 'Controller' , '' )
+
+
+@dataclass
+class Instrument:
+ """Display projection of a history value's source. Carries only
+ the fields the merged-history view renders, so the row type
+ stays insulated from sensor- vs controller-specific model
+ structure."""
+
+ id : int
+ name : str
+ instrument_type : InstrumentType
+
+
+@dataclass
+class MatchedIntent:
+ """Annotation on an observation: an HI control action confirmed
+ by this reading within the merge window. Its instrument is the
+ controller that issued the intent."""
+
+ instrument : Instrument
+ timestamp : datetime
+
+
+@dataclass
+class EntityStateHistoryValue:
+ """A row in the per-EntityState merged timeline.
+
+ OBSERVATION rows record what was sensed. ``matched_intent`` is
+ set when an HI control action with the same value was confirmed
+ by this reading within the merge window.
+
+ INTENT rows record an HI control action that produced no
+ confirming observation within the window (or where the
+ observation's value did not match)."""
+
+ value : str
+ timestamp : datetime
+ entity_state : EntityState
+ instrument : Instrument
+ history_value_type : StateHistoryValueType
+ matched_intent : Optional[ MatchedIntent ] = None
+
+
+def get_entity_state_history_page(
+ entity_state : EntityState,
+ page_size : int = 25,
+ before : Optional[datetime] = None,
+ window_seconds : int = MERGE_WINDOW_SECONDS,
+) -> List[ EntityStateHistoryValue ]:
+ """Sensor-anchored page of merged history for ``entity_state``.
+
+ Fetches the ``page_size`` most-recent observations older than
+ ``before`` (or most-recent overall if None), then fetches every
+ controller intent older than ``before`` and not older than the
+ page's oldest observation (minus the merge-window buffer so
+ in-window intents at the page's tail can still match).
+
+ Falls back to controller-only when the state has no observations
+ in range: returns the ``page_size`` most-recent intents older
+ than ``before``.
+
+ Returned rows are descending by timestamp; the caller derives
+ the next-page cursor from the oldest row's timestamp."""
+
+ obs_query = SensorHistory.objects.filter( sensor__entity_state = entity_state )
+ if before is not None:
+ obs_query = obs_query.filter( response_datetime__lt = before )
+ observation_rows = list(
+ obs_query.order_by( '-response_datetime' )[ : page_size ]
+ )
+
+ intent_query = ControllerHistory.objects.filter(
+ controller__entity_state = entity_state,
+ )
+ if before is not None:
+ intent_query = intent_query.filter( created_datetime__lt = before )
+
+ if observation_rows:
+ t_oldest = min( o.response_datetime for o in observation_rows )
+ intent_query = intent_query.filter(
+ created_datetime__gte = t_oldest - timedelta( seconds = window_seconds ),
+ )
+ intent_rows = list( intent_query )
+ else:
+ intent_rows = list(
+ intent_query.order_by( '-created_datetime' )[ : page_size ]
+ )
+
+ return merge_history(
+ entity_state = entity_state,
+ observation_rows = observation_rows,
+ intent_rows = intent_rows,
+ window_seconds = window_seconds,
+ )
+
+
+def merge_history(
+ entity_state : EntityState,
+ observation_rows : List[ SensorHistory ],
+ intent_rows : List[ ControllerHistory ],
+ window_seconds : int = MERGE_WINDOW_SECONDS,
+) -> List[ EntityStateHistoryValue ]:
+ """Collapse intents and observations into merged rows in
+ descending timestamp order.
+
+ Each intent claims the chronologically-earliest unclaimed
+ observation that occurs within ``window_seconds`` after it
+ (inclusive) and whose stored value matches by exact string
+ equality. Claimed observations carry the intent as an
+ annotation; unclaimed intents emit standalone."""
+
+ observations_asc = sorted( observation_rows, key = lambda h: h.response_datetime )
+ intents_asc = sorted( intent_rows, key = lambda h: h.created_datetime )
+
+ window = timedelta( seconds = window_seconds )
+ claimed_obs : Dict[ int, ControllerHistory ] = {}
+ unmatched_intents : List[ ControllerHistory ] = []
+
+ for intent in intents_asc:
+ matched = False
+ for i, obs in enumerate( observations_asc ):
+ if i in claimed_obs:
+ continue
+ if obs.response_datetime < intent.created_datetime:
+ continue
+ if obs.response_datetime > intent.created_datetime + window:
+ # Ascending sort: no later observation can fall in window.
+ break
+ if obs.value == intent.value:
+ claimed_obs[ i ] = intent
+ matched = True
+ break
+ continue
+ if not matched:
+ unmatched_intents.append( intent )
+ continue
+
+ rows : List[ EntityStateHistoryValue ] = []
+ for i, obs in enumerate( observations_asc ):
+ matched_intent : Optional[ MatchedIntent ] = None
+ claim = claimed_obs.get( i )
+ if claim is not None:
+ matched_intent = MatchedIntent(
+ instrument = _controller_instrument( claim ),
+ timestamp = claim.created_datetime,
+ )
+ rows.append( EntityStateHistoryValue(
+ value = obs.value,
+ timestamp = obs.response_datetime,
+ entity_state = entity_state,
+ instrument = _sensor_instrument( obs ),
+ history_value_type = StateHistoryValueType.OBSERVATION,
+ matched_intent = matched_intent,
+ ))
+ continue
+ for intent_history in unmatched_intents:
+ rows.append( EntityStateHistoryValue(
+ value = intent_history.value,
+ timestamp = intent_history.created_datetime,
+ entity_state = entity_state,
+ instrument = _controller_instrument( intent_history ),
+ history_value_type = StateHistoryValueType.INTENT,
+ matched_intent = None,
+ ))
+ continue
+
+ rows.sort( key = lambda r: r.timestamp, reverse = True )
+ return rows
+
+
+def _sensor_instrument( sensor_history : SensorHistory ) -> Instrument:
+ sensor = sensor_history.sensor
+ return Instrument(
+ id = sensor.id,
+ name = sensor.name,
+ instrument_type = InstrumentType.SENSOR,
+ )
+
+
+def _controller_instrument( controller_history : ControllerHistory ) -> Instrument:
+ controller = controller_history.controller
+ return Instrument(
+ id = controller.id,
+ name = controller.name,
+ instrument_type = InstrumentType.CONTROLLER,
+ )
diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.py
index 2e52f0c6..bbad086e 100644
--- a/src/hi/apps/entity/models.py
+++ b/src/hi/apps/entity/models.py
@@ -11,7 +11,7 @@ from hi.apps.location.models import (
LocationView,
)
from hi.apps.attribute.models import AttributeModel, SoftDeleteAttributeModel, AttributeValueHistoryModel
-from hi.apps.common.utils import get_humanized_name
+from hi.apps.common.utils import get_humanized_name, strip_parent_name_prefix
from hi.integrations.models import IntegrationDetailsModel
from hi.enums import ItemType
@@ -224,6 +224,12 @@ class EntityState( models.Model ):
def css_class(self):
return f'hi-entity-state-{self.id}'
+ @property
+ def short_name(self):
+ """Name suitable for display when the entity name is already
+ visible elsewhere in the surrounding chrome."""
+ return strip_parent_name_prefix( self.name, self.entity.name )
+
@property
def value_range_dict(self):
try:
diff --git a/src/hi/apps/entity/templates/entity/modals/entity_history.html b/src/hi/apps/entity/templates/entity/modals/entity_history.html
new file mode 100644
index 00000000..8a58f12a
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/modals/entity_history.html
@@ -0,0 +1,54 @@
+{% extends "modals/action_3.html" %}
+{% load common_tags %}
+{% load icons %}
+
+{% block title_text %}
+{{ entity.name }}
+{% endblock %}
+
+{% block body %}
+{% if state_to_rows %}
+ {% for state, rows in state_to_rows.items %}
+ <div class="mb-4">
+ <div class="hi-section-banner px-3 py-2 mb-2 d-flex justify-content-between align-items-center">
+ <span class="font-weight-bold">{{ state.short_name }}</span>
+ <a class="btn btn-sm btn-outline-primary"
+ href="{% url 'entity_state_history' entity_state_id=state.id %}"
+ data-async="modal">
+ {% icon "history" size="sm" css_class="hi-icon-left" %}See All
+ </a>
+ </div>
+ {% include "entity/panes/entity_state_history_table.html" with history_rows=rows annotate_sources=False %}
+ </div>
+ {% endfor %}
+{% else %}
+ <div class="card border-0 bg-light">
+ <div class="card-body text-center py-4">
+ {% icon "clock" size="xl" color="muted" css_class="mb-3" %}
+ <h6 class="text-muted">No States</h6>
+ <p class="text-muted mb-0">This entity has no states to show history for.</p>
+ </div>
+ </div>
+{% endif %}
+{% endblock %}
+
+{% block action_left %}
+<a class="btn btn-primary"
+ href="{% url 'entity_edit' entity_id=entity.id %}"
+ data-async="modal">
+ {% icon "edit" size="sm" css_class="hi-icon-left" %}EDIT
+</a>
+{% endblock %}
+
+{% block action_center %}
+<a class="btn btn-primary"
+ href="{% url 'entity_status' entity_id=entity.id %}"
+ data-async="modal">
+ {% icon "info-circle" size="sm" css_class="hi-icon-left" %}STATUS
+</a>
+{% endblock %}
+
+{% block action_right %}
+<a id="hi-modal-done" role="button" {% if autofocus %}autofocus="autofocus"{% endif %}
+ class="btn btn-primary" href="#" data-dismiss="modal">DONE</a>
+{% endblock %}
diff --git a/src/hi/apps/entity/templates/entity/modals/entity_state_history.html b/src/hi/apps/entity/templates/entity/modals/entity_state_history.html
index ab91fedc..3be1707d 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
@@ -1,40 +1,43 @@
{% extends "modals/action_3.html" %}
-{% load common_tags %}
{% load icons %}
{% block title_text %}
-{{ entity.name }}: History
+{{ entity_state.entity.name }}
{% endblock %}
{% block body %}
-
-{% if sensor_response_list_map %}
-<div>
- {% for sensor, sensor_response_list in sensor_response_list_map.items %}
- <div>
- <div class="h5">{{ sensor.name }} <small class="text-muted">[sensor]</small></div>
- {% include "sense/panes/sensor_history_list.html" with sensor_response_list=sensor_response_list show_all_link=True %}
- </div>
- {% endfor %}
+<h6 class="mb-3">{{ entity_state.short_name }}</h6>
+
+{% include "entity/panes/entity_state_history_table.html" with history_rows=history_rows annotate_sources=annotate_sources %}
+
+{% if older_cursor or newer_cursor %}
+<div class="d-flex justify-content-between mt-3">
+ {% if newer_cursor %}
+ <a class="btn btn-sm btn-outline-primary"
+ href="{% url 'entity_state_history' entity_state_id=entity_state.id %}"
+ data-async="modal">
+ {% icon "chevron-double-left" size="sm" css_class="hi-icon-left" %}Newest
+ </a>
+ {% else %}
+ <span></span>
+ {% endif %}
+
+ {% if older_cursor %}
+ <a class="btn btn-sm btn-outline-primary"
+ href="{% url 'entity_state_history' entity_state_id=entity_state.id %}?before={{ older_cursor|urlencode }}"
+ data-async="modal">
+ Older{% icon "chevron-right" size="sm" css_class="hi-icon-right" %}
+ </a>
+ {% else %}
+ <span></span>
+ {% endif %}
</div>
{% endif %}
-
-{% if controller_response_list_map %}
-<div>
- {% for controller, controller_response_list in controller_response_list_map.items %}
- <div>
- <div class="h5">{{ controller.name }} <small class="text-muted">[controller]</small></div>
- {% include "control/panes/controller_history_list.html" with controller_response_list=controller_response_list show_all_link=True %}
- </div>
- {% endfor %}
-</div>
-{% endif %}
-
{% endblock %}
{% block action_left %}
<a class="btn btn-primary"
- href="{% url 'entity_edit' entity_id=entity.id %}"
+ href="{% url 'entity_edit' entity_id=entity_state.entity.id %}"
data-async="modal">
{% icon "edit" size="sm" css_class="hi-icon-left" %}EDIT
</a>
@@ -42,7 +45,7 @@
{% block action_center %}
<a class="btn btn-primary"
- href="{% url 'entity_status' entity_id=entity.id %}"
+ href="{% url 'entity_status' entity_id=entity_state.entity.id %}"
data-async="modal">
{% icon "info-circle" size="sm" css_class="hi-icon-left" %}STATUS
</a>
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 76d6506c..314d6eae 100644
--- a/src/hi/apps/entity/templates/entity/modals/entity_status.html
+++ b/src/hi/apps/entity/templates/entity/modals/entity_status.html
@@ -22,7 +22,7 @@ Status
{% block action_center %}
<a class="btn btn-primary"
- href="{% url 'entity_state_history' entity_id=entity.id %}"
+ href="{% url 'entity_history' entity_id=entity.id %}"
data-async="modal">
{% icon "history" size="sm" css_class="hi-icon-left" %}HISTORY
</a>
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
new file mode 100644
index 00000000..363e7375
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/panes/entity_state_history_row.html
@@ -0,0 +1,48 @@
+{% load tz %}
+{% load static %}
+{% load common_tags %}
+{% load humanize %}
+{% load icons %}
+<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">
+ <div class="row align-items-center">
+ <div class="col-md-4 col-sm-5">
+ <div class="text-center">
+ <strong class="text-primary d-block">{{ row.timestamp|localtime|date:"l, M j" }}</strong>
+ <span class="text-primary">{{ row.timestamp|localtime|date:"g:i:s A" }}</span>
+ <small class="text-muted d-block">{{ row.timestamp|localtime|naturaltime }}</small>
+ </div>
+ </div>
+ <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>
+ {% if row.history_value_type.name == 'INTENT' or row.matched_intent %}
+ <img src="{% static 'img/hi-icon-16x16.png' %}"
+ alt="HI"
+ title="{% if row.history_value_type.name == 'INTENT' %}HI command — no matching observation{% else %}Observation confirmed an HI command{% endif %}"
+ class="ml-2"
+ width="16" height="16">
+ {% 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>
+ {% endif %}
+ </div>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/src/hi/apps/entity/templates/entity/panes/entity_state_history_table.html b/src/hi/apps/entity/templates/entity/panes/entity_state_history_table.html
new file mode 100644
index 00000000..2aa17f32
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/panes/entity_state_history_table.html
@@ -0,0 +1,22 @@
+{% load tz %}
+{% load static %}
+{% load common_tags %}
+{% load humanize %}
+{% load icons %}
+{% timezone USER_TIMEZONE %}
+{% if history_rows %}
+ <div class="timeline-items">
+ {% for row in history_rows %}
+ {% include "entity/panes/entity_state_history_row.html" with row=row annotate_sources=annotate_sources %}
+ {% endfor %}
+ </div>
+{% else %}
+ <div class="card border-0 bg-light">
+ <div class="card-body text-center py-4">
+ {% icon "clock" size="xl" color="muted" css_class="mb-3" %}
+ <h6 class="text-muted">No History</h6>
+ <p class="text-muted mb-0">No observations or control actions recorded for this state yet.</p>
+ </div>
+ </div>
+{% endif %}
+{% endtimezone %}
diff --git a/src/hi/apps/entity/templates/entity/panes/entity_state_status_row.html b/src/hi/apps/entity/templates/entity/panes/entity_state_status_row.html
index f26947da..9719235f 100644
--- a/src/hi/apps/entity/templates/entity/panes/entity_state_status_row.html
+++ b/src/hi/apps/entity/templates/entity/panes/entity_state_status_row.html
@@ -11,10 +11,10 @@
{% include "sense/panes/sensor_response_status_row.html" with sensor_response=entity_state_status_data.latest_sensor_response %}
{% elif entity_state_status_data.has_sensor %}
- <div class="alert alert-info">{{ entity_state_status_data.entity_state.name }}: awaiting sensor reading.</div>
+ <div class="alert alert-info">{{ entity_state_status_data.entity_state.short_name }}: awaiting sensor reading.</div>
{% else %}
- <div class="alert alert-info">{{ entity_state_status_data.entity_state.name }}: no sensors or controllers defined.</div>
+ <div class="alert alert-info">{{ entity_state_status_data.entity_state.short_name }}: no sensors or controllers defined.</div>
{% endif %}
</div>
diff --git a/src/hi/apps/entity/tests/test_entity_state_history.py b/src/hi/apps/entity/tests/test_entity_state_history.py
new file mode 100644
index 00000000..92531230
--- /dev/null
+++ b/src/hi/apps/entity/tests/test_entity_state_history.py
@@ -0,0 +1,495 @@
+import logging
+from datetime import datetime, timedelta, timezone
+
+from hi.apps.control.models import Controller, ControllerHistory
+from hi.apps.entity.entity_state_history import (
+ InstrumentType,
+ StateHistoryValueType,
+ get_entity_state_history_page,
+ merge_history,
+)
+from hi.apps.entity.models import Entity, EntityState
+from hi.apps.sense.models import Sensor, SensorHistory
+from hi.testing.base_test_case import BaseTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+BASE_TIME = datetime( 2024, 3, 1, 12, 0, 0, tzinfo = timezone.utc )
+
+
+def _at( seconds_offset : int ) -> datetime:
+ return BASE_TIME + timedelta( seconds = seconds_offset )
+
+
+class TestMergeHistory( BaseTestCase ):
+ """``merge_history`` is the pure foundation of the per-EntityState
+ merged history view. It collapses controller intents that were
+ confirmed by a subsequent sensor reading into annotated
+ observations, leaves unmatched intents standalone, and returns
+ rows in descending timestamp order."""
+
+ def setUp(self):
+ super().setUp()
+ self.entity = Entity.objects.create(
+ name = 'Test Entity', entity_type_str = 'WALL_SWITCH',
+ )
+ self.state = EntityState.objects.create(
+ entity = self.entity,
+ name = 'on_off',
+ entity_state_type_str = 'ON_OFF',
+ )
+ self.sensor = Sensor.objects.create(
+ entity_state = self.state,
+ name = 'sw-sensor',
+ sensor_type_str = 'DEFAULT',
+ integration_payload = '{}',
+ )
+ self.controller = Controller.objects.create(
+ entity_state = self.state,
+ name = 'sw-ctrl',
+ controller_type_str = 'DEFAULT',
+ integration_payload = '{}',
+ )
+
+ # ------------------------------------------------------------------
+ # Helpers
+
+ def _observation( self, value : str, at : datetime, sensor : Sensor = None ):
+ return SensorHistory.objects.create(
+ sensor = sensor or self.sensor,
+ value = value,
+ response_datetime = at,
+ )
+
+ def _intent( self, value : str, at : datetime, controller : Controller = None ):
+ ctrl = controller or self.controller
+ # ControllerHistory.created_datetime is auto_now_add; need to
+ # override after create for deterministic test timestamps.
+ h = ControllerHistory.objects.create( controller = ctrl, value = value )
+ ControllerHistory.objects.filter( pk = h.pk ).update( created_datetime = at )
+ h.refresh_from_db()
+ return h
+
+ # ------------------------------------------------------------------
+ # Base cases
+
+ def test_empty_inputs_returns_empty_list(self):
+ result = merge_history(
+ entity_state = self.state,
+ observation_rows = [],
+ intent_rows = [],
+ )
+ self.assertEqual( result, [] )
+
+ def test_lone_observation_emits_plain_observation_row(self):
+ obs = self._observation( 'on', _at( 0 ) )
+
+ result = merge_history(
+ entity_state = self.state,
+ observation_rows = [ obs ],
+ intent_rows = [],
+ )
+
+ self.assertEqual( len( result ), 1 )
+ row = result[ 0 ]
+ self.assertEqual( row.history_value_type, StateHistoryValueType.OBSERVATION )
+ self.assertEqual( row.value, 'on' )
+ self.assertEqual( row.instrument.instrument_type, InstrumentType.SENSOR )
+ self.assertEqual( row.instrument.id, self.sensor.id )
+ self.assertIsNone( row.matched_intent )
+
+ def test_lone_unmatched_intent_emits_intent_row(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.assertEqual( row.history_value_type, StateHistoryValueType.INTENT )
+ self.assertEqual( row.value, 'on' )
+ self.assertEqual( row.instrument.instrument_type, InstrumentType.CONTROLLER )
+ self.assertEqual( row.instrument.id, self.controller.id )
+ self.assertIsNone( row.matched_intent )
+
+ # ------------------------------------------------------------------
+ # Matching semantics
+
+ def test_intent_with_matching_observation_in_window_collapses(self):
+ # Intent at T=0, observation at T=3 with same value. Within 10s
+ # window — observation absorbs the intent.
+ intent = self._intent( 'on', _at( 0 ) )
+ obs = self._observation( 'on', _at( 3 ) )
+
+ result = merge_history(
+ entity_state = self.state,
+ observation_rows = [ obs ],
+ intent_rows = [ intent ],
+ )
+
+ # Single row: the observation, annotated.
+ self.assertEqual( len( result ), 1 )
+ row = result[ 0 ]
+ self.assertEqual( row.history_value_type, StateHistoryValueType.OBSERVATION )
+ self.assertEqual( row.timestamp, _at( 3 ) )
+ self.assertIsNotNone( row.matched_intent )
+ self.assertEqual( row.matched_intent.timestamp, _at( 0 ) )
+ self.assertEqual( row.matched_intent.instrument.id, self.controller.id )
+
+ def test_intent_with_non_matching_value_within_window_keeps_both(self):
+ # Same time window, different values — no merge.
+ intent = self._intent( 'on', _at( 0 ) )
+ obs = self._observation( 'off', _at( 3 ) )
+
+ result = merge_history(
+ entity_state = self.state,
+ observation_rows = [ obs ],
+ intent_rows = [ intent ],
+ )
+
+ self.assertEqual( len( result ), 2 )
+ kinds = sorted( r.history_value_type.name for r in result )
+ self.assertEqual( kinds, [ 'INTENT', 'OBSERVATION' ] )
+
+ def test_intent_with_matching_observation_past_window_keeps_both(self):
+ # Observation is past the merge window — no match.
+ intent = self._intent( 'on', _at( 0 ) )
+ obs = self._observation( 'on', _at( 15 ) )
+
+ result = merge_history(
+ entity_state = self.state,
+ observation_rows = [ obs ],
+ intent_rows = [ intent ],
+ window_seconds = 10,
+ )
+
+ self.assertEqual( len( result ), 2 )
+ kinds = sorted( r.history_value_type.name for r in result )
+ self.assertEqual( kinds, [ 'INTENT', 'OBSERVATION' ] )
+ for row in result:
+ self.assertIsNone( row.matched_intent )
+
+ def test_observation_before_intent_does_not_match(self):
+ # Sensor reading occurs BEFORE the intent — cannot have been
+ # caused by it. No match.
+ obs = self._observation( 'on', _at( 0 ) )
+ intent = self._intent( 'on', _at( 3 ) )
+
+ result = merge_history(
+ entity_state = self.state,
+ observation_rows = [ obs ],
+ intent_rows = [ intent ],
+ )
+
+ self.assertEqual( len( result ), 2 )
+ for row in result:
+ self.assertIsNone( row.matched_intent )
+
+ def test_window_boundary_is_inclusive(self):
+ # Observation exactly at intent_time + window_seconds matches.
+ intent = self._intent( 'on', _at( 0 ) )
+ obs = self._observation( 'on', _at( 10 ) )
+
+ result = merge_history(
+ entity_state = self.state,
+ observation_rows = [ obs ],
+ intent_rows = [ intent ],
+ window_seconds = 10,
+ )
+
+ self.assertEqual( len( result ), 1 )
+ self.assertIsNotNone( result[ 0 ].matched_intent )
+
+ # ------------------------------------------------------------------
+ # Multi-instrument and multi-intent cases
+
+ def test_two_intents_in_window_only_second_matches(self):
+ # I1=off at T=0, I2=on at T=2, O=on at T=5. I2 matches; I1
+ # standalone.
+ intent_1 = self._intent( 'off', _at( 0 ) )
+ intent_2 = self._intent( 'on', _at( 2 ) )
+ obs = self._observation( 'on', _at( 5 ) )
+
+ result = merge_history(
+ entity_state = self.state,
+ observation_rows = [ obs ],
+ intent_rows = [ intent_1, intent_2 ],
+ )
+
+ self.assertEqual( len( result ), 2 )
+ # Sorted descending: observation (annotated) at T=5, then intent_1 at T=0.
+ self.assertEqual( result[ 0 ].history_value_type, StateHistoryValueType.OBSERVATION )
+ self.assertIsNotNone( result[ 0 ].matched_intent )
+ self.assertEqual( result[ 0 ].matched_intent.timestamp, _at( 2 ) )
+ self.assertEqual( result[ 1 ].history_value_type, StateHistoryValueType.INTENT )
+ self.assertEqual( result[ 1 ].value, 'off' )
+
+ def test_two_intents_same_value_claim_distinct_observations(self):
+ # I1=on at T=0, I2=on at T=2, O1=on at T=4, O2=on at T=6.
+ # First-claim-wins: I1 claims O1; I2 claims O2. Both
+ # observations annotated, both intents matched.
+ intent_1 = self._intent( 'on', _at( 0 ) )
+ intent_2 = self._intent( 'on', _at( 2 ) )
+ obs_1 = self._observation( 'on', _at( 4 ) )
+ obs_2 = self._observation( 'on', _at( 6 ) )
+
+ result = merge_history(
+ entity_state = self.state,
+ observation_rows = [ obs_1, obs_2 ],
+ intent_rows = [ intent_1, intent_2 ],
+ )
+
+ self.assertEqual( len( result ), 2 )
+ for row in result:
+ self.assertEqual( row.history_value_type, StateHistoryValueType.OBSERVATION )
+ self.assertIsNotNone( row.matched_intent )
+ # Newest first: O2 (matched to I2) then O1 (matched to I1).
+ self.assertEqual( result[ 0 ].timestamp, _at( 6 ) )
+ self.assertEqual( result[ 0 ].matched_intent.timestamp, _at( 2 ) )
+ self.assertEqual( result[ 1 ].timestamp, _at( 4 ) )
+ self.assertEqual( result[ 1 ].matched_intent.timestamp, _at( 0 ) )
+
+ def test_redundant_intent_with_single_observation_leaves_one_unmatched(self):
+ # I1=on at T=0, I2=on at T=1 (redundant), O=on at T=3.
+ # First-claim-wins: I1 claims O. I2 has no remaining
+ # observation in its window and emits standalone.
+ intent_1 = self._intent( 'on', _at( 0 ) )
+ intent_2 = self._intent( 'on', _at( 1 ) )
+ obs = self._observation( 'on', _at( 3 ) )
+
+ result = merge_history(
+ entity_state = self.state,
+ observation_rows = [ obs ],
+ intent_rows = [ intent_1, intent_2 ],
+ )
+
+ self.assertEqual( len( result ), 2 )
+ # Newest first: the annotated observation, then the unmatched I2.
+ self.assertEqual( result[ 0 ].history_value_type, StateHistoryValueType.OBSERVATION )
+ self.assertEqual( result[ 0 ].matched_intent.timestamp, _at( 0 ) )
+ self.assertEqual( result[ 1 ].history_value_type, StateHistoryValueType.INTENT )
+ self.assertEqual( result[ 1 ].timestamp, _at( 1 ) )
+
+ def test_multiple_sensors_observations_merge_into_single_timeline(self):
+ # Two sensors on the same state both contribute observations.
+ other_sensor = Sensor.objects.create(
+ entity_state = self.state,
+ name = 'sw-sensor-b',
+ sensor_type_str = 'DEFAULT',
+ integration_payload = '{}',
+ )
+ obs_a = self._observation( 'on', _at( 0 ) )
+ obs_b = self._observation( 'off', _at( 5 ), sensor = other_sensor )
+
+ result = merge_history(
+ entity_state = self.state,
+ observation_rows = [ obs_a, obs_b ],
+ intent_rows = [],
+ )
+
+ self.assertEqual( len( result ), 2 )
+ sensor_ids = { r.instrument.id for r in result }
+ self.assertEqual( sensor_ids, { self.sensor.id, other_sensor.id } )
+
+ def test_multiple_controllers_intents_considered_separately(self):
+ # Two controllers; only one of their intents matches an
+ # observation. The unmatched intent on the other controller
+ # still emits standalone.
+ other_controller = Controller.objects.create(
+ entity_state = self.state,
+ name = 'sw-ctrl-b',
+ controller_type_str = 'DEFAULT',
+ integration_payload = '{}',
+ )
+ intent_a = self._intent( 'on', _at( 0 ) )
+ intent_b = self._intent( 'off', _at( 1 ), controller = other_controller )
+ obs = self._observation( 'on', _at( 4 ) )
+
+ result = merge_history(
+ entity_state = self.state,
+ observation_rows = [ obs ],
+ intent_rows = [ intent_a, intent_b ],
+ )
+
+ self.assertEqual( len( result ), 2 )
+ # Annotated observation absorbed intent_a (from self.controller).
+ annotated = [ r for r in result
+ if r.history_value_type == StateHistoryValueType.OBSERVATION ][ 0 ]
+ self.assertIsNotNone( annotated.matched_intent )
+ self.assertEqual( annotated.matched_intent.instrument.id, self.controller.id )
+ # Unmatched intent retained its other-controller identity.
+ unmatched = [ r for r in result
+ if r.history_value_type == StateHistoryValueType.INTENT ][ 0 ]
+ self.assertEqual( unmatched.instrument.id, other_controller.id )
+ self.assertEqual( unmatched.value, 'off' )
+
+ # ------------------------------------------------------------------
+ # Output ordering
+
+ def test_result_is_sorted_descending_by_timestamp(self):
+ # Out-of-order input still produces newest-first output.
+ obs_old = self._observation( 'on', _at( 0 ) )
+ obs_new = self._observation( 'off', _at( 100 ) )
+ intent_mid = self._intent( 'idle', _at( 50 ) )
+
+ result = merge_history(
+ entity_state = self.state,
+ observation_rows = [ obs_old, obs_new ],
+ intent_rows = [ intent_mid ],
+ )
+
+ timestamps = [ r.timestamp for r in result ]
+ self.assertEqual( timestamps, sorted( timestamps, reverse = True ) )
+
+
+class TestGetEntityStateHistoryPage( BaseTestCase ):
+ """``get_entity_state_history_page`` is the sensor-anchored page
+ fetcher that the per-EntityState merged history view consumes.
+ Bounds the controller-history fetch to the observation page's
+ time range so the merge sees a coherent window of both sides."""
+
+ def setUp(self):
+ super().setUp()
+ self.entity = Entity.objects.create(
+ name = 'Test Entity', entity_type_str = 'WALL_SWITCH',
+ )
+ self.state = EntityState.objects.create(
+ entity = self.entity,
+ name = 'on_off',
+ entity_state_type_str = 'ON_OFF',
+ )
+ self.sensor = Sensor.objects.create(
+ entity_state = self.state,
+ name = 'sw-sensor',
+ sensor_type_str = 'DEFAULT',
+ integration_payload = '{}',
+ )
+ self.controller = Controller.objects.create(
+ entity_state = self.state,
+ name = 'sw-ctrl',
+ controller_type_str = 'DEFAULT',
+ integration_payload = '{}',
+ )
+
+ def _observation( self, value : str, at : datetime ):
+ return SensorHistory.objects.create(
+ sensor = self.sensor, value = value, response_datetime = at,
+ )
+
+ def _intent( self, value : str, at : datetime ):
+ h = ControllerHistory.objects.create( controller = self.controller, value = value )
+ ControllerHistory.objects.filter( pk = h.pk ).update( created_datetime = at )
+ h.refresh_from_db()
+ return h
+
+ def test_empty_state_returns_empty(self):
+ result = get_entity_state_history_page(
+ entity_state = self.state, page_size = 25,
+ )
+ self.assertEqual( result, [] )
+
+ def test_page_returns_descending_observations_and_matching_intents(self):
+ # Five observations recent; two intents matching the first
+ # two observations within window.
+ obs_recent = [ self._observation( f'v{i}', _at( 100 - i ) ) for i in range( 5 ) ]
+ # observations: v0 at 100, v1 at 99, v2 at 98, v3 at 97, v4 at 96
+ # Match intents to the two oldest observations in the page.
+ self._intent( 'v4', _at( 90 ) ) # within 10s of v4@96
+ self._intent( 'v3', _at( 89 ) ) # within 10s of v3@97 (97-89=8)
+
+ rows = get_entity_state_history_page(
+ entity_state = self.state, page_size = 5,
+ )
+
+ self.assertEqual( len( rows ), 5 )
+ # Descending timestamps: 100, 99, 98, 97, 96.
+ timestamps = [ r.timestamp for r in rows ]
+ self.assertEqual( timestamps, sorted( timestamps, reverse = True ) )
+ # The two oldest rows in the page carry intent annotations.
+ annotated = [ r for r in rows if r.matched_intent is not None ]
+ self.assertEqual( len( annotated ), 2 )
+ # Smoke-check: the page's observations are the ones we created.
+ observation_values = [ r.value for r in rows ]
+ self.assertEqual( observation_values, [ 'v0', 'v1', 'v2', 'v3', 'v4' ] )
+ # And we didn't accidentally drop them — keep tied to fixture.
+ for obs in obs_recent:
+ self.assertIn( obs.value, observation_values )
+
+ def test_before_cursor_filters_older_rows(self):
+ # Ten observations spaced 10 seconds apart; ask for 3 older
+ # than a cursor in the middle.
+ for i in range( 10 ):
+ self._observation( f'v{i}', _at( 100 + 10 * i ) )
+ cursor = _at( 150 ) # corresponds to v5
+
+ rows = get_entity_state_history_page(
+ entity_state = self.state, page_size = 3, before = cursor,
+ )
+
+ self.assertEqual( len( rows ), 3 )
+ # All returned rows must be strictly older than the cursor.
+ for r in rows:
+ self.assertLess( r.timestamp, cursor )
+ # The newest of the three is the observation at T=140 (v4).
+ self.assertEqual( rows[ 0 ].value, 'v4' )
+
+ def test_state_with_controllers_only_falls_back_to_intent_anchored(self):
+ # No sensors / no observations exist — only intents. The
+ # function returns up to page_size most-recent intents.
+ for i in range( 5 ):
+ self._intent( f'i{i}', _at( 100 - i * 10 ) )
+
+ rows = get_entity_state_history_page(
+ entity_state = self.state, page_size = 3,
+ )
+
+ self.assertEqual( len( rows ), 3 )
+ for r in rows:
+ self.assertEqual( r.history_value_type, StateHistoryValueType.INTENT )
+ self.assertEqual( r.instrument.instrument_type, InstrumentType.CONTROLLER )
+
+ def test_gap_intents_between_observation_and_cursor_appear_in_page(self):
+ # Page's newest observation is at T=50; an unmatched intent
+ # fires at T=80 — between the page's observations and the
+ # before-cursor (T=100). It must appear on this page rather
+ # than disappear into a coverage gap.
+ self._observation( 'on', _at( 50 ) )
+ self._observation( 'on', _at( 40 ) )
+ gap_intent = self._intent( 'mystery', _at( 80 ) )
+
+ rows = get_entity_state_history_page(
+ entity_state = self.state, page_size = 5, before = _at( 100 ),
+ )
+
+ intents = [ r for r in rows if r.history_value_type == StateHistoryValueType.INTENT ]
+ self.assertEqual( len( intents ), 1 )
+ self.assertEqual( intents[ 0 ].timestamp, gap_intent.created_datetime )
+
+ def test_other_entity_state_history_is_not_returned(self):
+ # A second EntityState with its own instruments should not
+ # leak into the queried state's page.
+ other_entity = Entity.objects.create( name = 'Other', entity_type_str = 'WALL_SWITCH' )
+ other_state = EntityState.objects.create(
+ entity = other_entity, name = 'on_off', entity_state_type_str = 'ON_OFF',
+ )
+ other_sensor = Sensor.objects.create(
+ entity_state = other_state, name = 'other-sensor',
+ sensor_type_str = 'DEFAULT', integration_payload = '{}',
+ )
+ SensorHistory.objects.create(
+ sensor = other_sensor, value = 'should-not-appear',
+ response_datetime = _at( 0 ),
+ )
+ self._observation( 'mine', _at( 0 ) )
+
+ rows = get_entity_state_history_page(
+ entity_state = self.state, page_size = 25,
+ )
+
+ values = [ r.value for r in rows ]
+ self.assertIn( 'mine', values )
+ self.assertNotIn( 'should-not-appear', values )
diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.py
index 97597340..884d0f71 100644
--- a/src/hi/apps/entity/tests/test_views.py
+++ b/src/hi/apps/entity/tests/test_views.py
@@ -9,12 +9,10 @@ from django.test import override_settings
from django.urls import reverse
from hi.apps.attribute.enums import AttributeValueType
-from hi.apps.control.controller_history_manager import ControllerHistoryManager
from hi.apps.entity.enums import EntityType, EntityStateType
from hi.apps.entity.models import Entity, EntityAttribute
from hi.apps.location.models import Location, LocationView
from hi.apps.location.enums import LocationViewType
-from hi.apps.sense.sensor_history_manager import SensorHistoryManager
from hi.enums import ViewType
from hi.testing.view_test_base import SyncViewTestCase, DualModeViewTestCase
from .synthetic_data import EntityAttributeSyntheticData
@@ -708,83 +706,58 @@ class TestEntityStatusView(DualModeViewTestCase):
self.assertEqual(response.status_code, 405)
-class TestEntityStateHistoryView(DualModeViewTestCase):
- """
- Tests for EntityStateHistoryView - demonstrates history data testing.
- This view displays sensor and controller history for an entity.
- """
+class TestEntityHistoryView(DualModeViewTestCase):
+ """EntityHistoryView is the per-entity overview modal showing
+ each state's most recent merged history rows."""
def setUp(self):
super().setUp()
- # Create test entity
self.entity = Entity.objects.create(
integration_id='test.entity',
integration_name='test_integration',
name='Test Entity',
- entity_type_str=str(EntityType.THERMOSTAT)
+ entity_type_str=str(EntityType.THERMOSTAT),
)
def test_get_history_sync(self):
- """Test getting entity state history with synchronous request."""
- # Test the view responds appropriately without complex mocking
- url = reverse('entity_state_history', kwargs={'entity_id': self.entity.id})
+ url = reverse('entity_history', kwargs={'entity_id': self.entity.id})
response = self.client.get(url)
+ self.assertSuccessResponse(response)
- # View should respond (may be 500 due to manager issues, but shouldn't crash)
- self.assertIn(response.status_code, [200, 500]) # Accept either for now
-
- @patch.object(SensorHistoryManager, 'get_latest_entity_sensor_history')
- @patch.object(ControllerHistoryManager, 'get_latest_entity_controller_history')
- def test_get_history_async(self, mock_get_controller_history, mock_get_sensor_history):
- """Test getting entity state history with AJAX request."""
- # Mock history data
- mock_get_sensor_history.return_value = {}
- mock_get_controller_history.return_value = {}
-
- url = reverse('entity_state_history', kwargs={'entity_id': self.entity.id})
+ def test_get_history_async(self):
+ url = reverse('entity_history', kwargs={'entity_id': self.entity.id})
response = self.async_get(url)
-
self.assertSuccessResponse(response)
self.assertJsonResponse(response)
-
- # HiModalView returns JSON with modal content for AJAX requests
data = response.json()
self.assertIn('modal', data)
- @patch.object(SensorHistoryManager, 'get_latest_entity_sensor_history')
- @patch.object(ControllerHistoryManager, 'get_latest_entity_controller_history')
- def test_history_uses_correct_max_items(self, mock_get_controller_history, mock_get_sensor_history):
- """Test that history requests use the correct max items limit."""
- mock_get_sensor_history.return_value = {}
- mock_get_controller_history.return_value = {}
+ def test_renders_one_block_per_state(self):
+ """Each EntityState produces an entry in state_to_rows."""
+ from hi.apps.entity.models import EntityState
+ EntityState.objects.create(
+ entity=self.entity, name='temperature',
+ entity_state_type_str='TEMPERATURE',
+ )
+ EntityState.objects.create(
+ entity=self.entity, name='hvac_mode',
+ entity_state_type_str='DISCRETE',
+ )
- url = reverse('entity_state_history', kwargs={'entity_id': self.entity.id})
+ url = reverse('entity_history', kwargs={'entity_id': self.entity.id})
response = self.client.get(url)
-
self.assertSuccessResponse(response)
-
- # Both managers should be called with max_items=5
- mock_get_sensor_history.assert_called_once_with(
- entity=self.entity,
- max_items=5
- )
- mock_get_controller_history.assert_called_once_with(
- entity=self.entity,
- max_items=5
- )
+ state_to_rows = response.context['state_to_rows']
+ self.assertEqual(len(state_to_rows), 2)
def test_nonexistent_entity_returns_404(self):
- """Test that accessing nonexistent entity returns 404."""
- url = reverse('entity_state_history', kwargs={'entity_id': 99999})
+ url = reverse('entity_history', kwargs={'entity_id': 99999})
response = self.client.get(url)
-
self.assertEqual(response.status_code, 404)
def test_post_not_allowed(self):
- """Test that POST requests are not allowed."""
- url = reverse('entity_state_history', kwargs={'entity_id': self.entity.id})
+ url = reverse('entity_history', kwargs={'entity_id': self.entity.id})
response = self.client.post(url)
-
self.assertEqual(response.status_code, 405)
@@ -1151,3 +1124,103 @@ class TestEntityEditViewFileUploadIntegration(DualModeViewTestCase):
# Verify no file attributes were created due to transaction rollback
self.assertEqual(self.entity.attributes.filter(value_type_str=str(AttributeValueType.FILE)).count(), 0)
+
+
+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."""
+
+ def setUp(self):
+ super().setUp()
+ import json
+ self.entity = Entity.objects.create(
+ name = 'Switch', entity_type_str = 'WALL_SWITCH',
+ )
+ from hi.apps.entity.models import EntityState
+ self.state = EntityState.objects.create(
+ entity = self.entity,
+ name = 'on_off',
+ entity_state_type_str = 'ON_OFF',
+ value_range_str = json.dumps([ 'on', 'off' ]),
+ )
+ from hi.apps.sense.models import Sensor, SensorHistory
+ from hi.apps.control.models import Controller, ControllerHistory
+ self.sensor = Sensor.objects.create(
+ entity_state = self.state, name = 'sw-sensor',
+ sensor_type_str = 'DEFAULT', integration_payload = '{}',
+ )
+ self.controller = Controller.objects.create(
+ entity_state = self.state, name = 'sw-ctrl',
+ controller_type_str = 'DEFAULT', integration_payload = '{}',
+ )
+ SensorHistory.objects.create(
+ sensor = self.sensor, value = 'on',
+ response_datetime = '2024-03-01T12:00:00Z',
+ )
+ ControllerHistory.objects.create(
+ controller = self.controller, value = 'off',
+ )
+
+ def test_renders_observation_with_human_readable_label(self):
+ """The stored value 'on' renders as the EntityStateValue label 'On'."""
+ 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( 'On', body )
+
+ def test_returns_404_for_unknown_entity_state(self):
+ url = reverse(
+ 'entity_state_history',
+ kwargs = { 'entity_state_id': 999999 },
+ )
+ response = self.client.get(url)
+ self.assertEqual(response.status_code, 404)
+
+ def test_pagination_cursor_filters_older(self):
+ """A `before` query param filters rows to those strictly
+ older than the given ISO timestamp."""
+ from hi.apps.sense.models import SensorHistory
+ SensorHistory.objects.all().delete()
+ for i in range(5):
+ SensorHistory.objects.create(
+ sensor = self.sensor, value = 'on',
+ response_datetime = f'2024-03-0{i+1}T12:00:00Z',
+ )
+
+ url = reverse(
+ 'entity_state_history',
+ kwargs = { 'entity_state_id': self.state.id },
+ )
+ # Cursor at 2024-03-04 should yield only rows from days 1-3.
+ response = self.client.get(url, { 'before': '2024-03-04T00:00:00+00:00' })
+ self.assertSuccessResponse(response)
+ rows = response.context['history_rows']
+ for row in rows:
+ self.assertLess( row.timestamp.isoformat(), '2024-03-04T00:00:00+00:00' )
+
+ def test_older_link_uses_url_encoded_cursor(self):
+ """The HTML link for "Older" must URL-encode the ISO cursor;
+ an unencoded ``+`` becomes a space when re-parsed and the
+ next page falls back to most-recent."""
+ from hi.apps.sense.models import SensorHistory
+ for i in range(30):
+ SensorHistory.objects.create(
+ sensor = self.sensor, value = 'on',
+ response_datetime = f'2024-03-0{(i % 9) + 1}T12: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()
+ # 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 )
diff --git a/src/hi/apps/entity/transient_models.py b/src/hi/apps/entity/transient_models.py
index 227664b4..05aa5e6b 100644
--- a/src/hi/apps/entity/transient_models.py
+++ b/src/hi/apps/entity/transient_models.py
@@ -1,15 +1,12 @@
from dataclasses import dataclass, field
from typing import Any, Dict, List
-from hi.apps.control.models import Controller
-from hi.apps.control.transient_models import ControllerHistoryResponse
from hi.apps.entity.edit.forms import EntityPositionForm
-from hi.apps.sense.models import Sensor
-from hi.apps.sense.transient_models import SensorResponse
+from .entity_state_history import EntityStateHistoryValue
from .enums import EntityGroupType, EntityPairingType, VideoStreamType
from .forms import EntityForm
-from .models import Entity
+from .models import Entity, EntityState
@dataclass
@@ -85,17 +82,14 @@ class EntityEditModeData:
@dataclass
-class EntityStateHistoryData:
+class EntityHistoryData:
- entity : Entity
- sensor_response_list_map : Dict[ Sensor, List[ SensorResponse ] ]
- controller_response_list_map : Dict[ Controller, List[ ControllerHistoryResponse ] ]
+ entity : Entity
+ state_to_rows : Dict[ EntityState, List[ EntityStateHistoryValue ] ]
def to_template_context(self):
- context = {
+ return {
'entity': self.entity,
- 'sensor_response_list_map': self.sensor_response_list_map,
- 'controller_response_list_map': self.controller_response_list_map,
+ 'state_to_rows': self.state_to_rows,
}
- return context
diff --git a/src/hi/apps/entity/urls.py b/src/hi/apps/entity/urls.py
index 50acb884..9fc967f5 100644
--- a/src/hi/apps/entity/urls.py
+++ b/src/hi/apps/entity/urls.py
@@ -13,8 +13,12 @@ urlpatterns = [
views.EntityStatusView.as_view(),
name='entity_status' ),
- re_path( r'^state/history/(?P<entity_id>\d+)$',
- views.EntityStateHistoryView.as_view(),
+ re_path( r'^history/(?P<entity_id>\d+)$',
+ views.EntityHistoryView.as_view(),
+ name='entity_history' ),
+
+ re_path( r'^state/(?P<entity_state_id>\d+)/history$',
+ views.EntityStateHistoryView.as_view(),
name='entity_state_history' ),
re_path( r'^attribute/upload/(?P<entity_id>\d+)$',
diff --git a/src/hi/apps/entity/view_mixins.py b/src/hi/apps/entity/view_mixins.py
index 4087c10d..dcd0abf4 100644
--- a/src/hi/apps/entity/view_mixins.py
+++ b/src/hi/apps/entity/view_mixins.py
@@ -1,7 +1,7 @@
from django.core.exceptions import BadRequest
from django.http import Http404
-from hi.apps.entity.models import Entity
+from hi.apps.entity.models import Entity, EntityState
class EntityViewMixin:
@@ -16,3 +16,17 @@ class EntityViewMixin:
return Entity.objects.get( id = entity_id )
except Entity.DoesNotExist:
raise Http404( request )
+
+
+class EntityStateViewMixin:
+
+ def get_entity_state( self, request, *args, **kwargs ) -> EntityState:
+ """ Assumes there is a required entity_state_id in kwargs """
+ try:
+ entity_state_id = int( kwargs.get( 'entity_state_id' ))
+ except (TypeError, ValueError):
+ raise BadRequest( 'Invalid entity state id.' )
+ try:
+ return EntityState.objects.get( id = entity_state_id )
+ except EntityState.DoesNotExist:
+ raise Http404( request )
diff --git a/src/hi/apps/entity/views.py b/src/hi/apps/entity/views.py
index 4f9765f1..3610d581 100644
--- a/src/hi/apps/entity/views.py
+++ b/src/hi/apps/entity/views.py
@@ -1,24 +1,25 @@
import logging
-from typing import Any, Dict
+from datetime import datetime
+from typing import Any, Dict, List, Optional
from django.http import HttpRequest, HttpResponse
from django.views.generic import View
+from hi.apps.common import datetimeproxy
+
from hi.apps.attribute.view_mixins import AttributeEditViewMixin
from hi.apps.attribute.edit_response_renderer import AttributeEditResponseRenderer
-from hi.apps.control.controller_history_manager import ControllerHistoryManager
-from hi.apps.control.transient_models import ControllerHistoryResponse
from hi.apps.monitor.status_display_manager import StatusDisplayManager
-from hi.apps.sense.sensor_history_manager import SensorHistoryMixin
-from hi.apps.sense.transient_models import SensorResponse
from hi.views import page_not_found_response
from hi.hi_async_view import HiModalView
from hi.apps.entity.edit.entity_type_transition_handler import EntityTypeTransitionHandler
+from .entity_state_history import get_entity_state_history_page
+from .entity_state_role_order import ENTITY_STATUS_VIEW_ORDERING
from .models import Entity, EntityAttribute
-from .transient_models import EntityStateHistoryData
-from .view_mixins import EntityViewMixin
+from .transient_models import EntityHistoryData
+from .view_mixins import EntityStateViewMixin, EntityViewMixin
from .entity_attribute_edit_context import EntityAttributeItemEditContext
@@ -44,40 +45,108 @@ class EntityStatusView( HiModalView, EntityViewMixin ):
return self.modal_response( request, context )
-class EntityStateHistoryView( HiModalView, EntityViewMixin, SensorHistoryMixin ):
+class EntityHistoryView( HiModalView, EntityViewMixin ):
+ """Per-entity overview modal. Renders one block per EntityState
+ (the entity's own states plus delegated states) showing each
+ state's most recent merged history rows. Each block links to
+ the per-state EntityStateHistoryView for deeper navigation."""
+
+ PER_STATE_ROW_COUNT = 5
- ENTITY_STATE_HISTORY_ITEM_MAX = 5
-
def get_template_name( self ) -> str:
- return 'entity/modals/entity_state_history.html'
+ return 'entity/modals/entity_history.html'
- def get( self, request,*args, **kwargs ):
+ def get( self, request, *args, **kwargs ):
entity: Entity = self.get_entity( request, *args, **kwargs )
- sensor_history_list_map = self.sensor_history_manager().get_latest_entity_sensor_history(
+
+ states = list( entity.states.all() )
+ for delegation in entity.entity_state_delegations.select_related('entity_state').all():
+ if delegation.entity_state not in states:
+ states.append( delegation.entity_state )
+ continue
+
+ states.sort( key = lambda s: ENTITY_STATUS_VIEW_ORDERING.sort_key(
+ s.entity_state_role, entity.entity_type,
+ ))
+
+ state_to_rows : Dict[ Any, List[ Any ] ] = {}
+ for state in states:
+ rows = get_entity_state_history_page(
+ entity_state = state,
+ page_size = self.PER_STATE_ROW_COUNT,
+ )
+ state_to_rows[ state ] = rows[ : self.PER_STATE_ROW_COUNT ]
+ continue
+
+ entity_history_data = EntityHistoryData(
entity = entity,
- max_items = self.ENTITY_STATE_HISTORY_ITEM_MAX,
+ state_to_rows = state_to_rows,
)
- controller_history_list_map = ControllerHistoryManager().get_latest_entity_controller_history(
- entity = entity,
- max_items = self.ENTITY_STATE_HISTORY_ITEM_MAX,
+ context: Dict[ str, Any ] = entity_history_data.to_template_context()
+ return self.modal_response( request, context )
+
+
+class EntityStateHistoryView( HiModalView, EntityStateViewMixin ):
+ """Paginated per-EntityState merged history. The "History" anchor
+ in the EntityStatus modal (both sensor and controller rows) and
+ the "See All" link in the EntityHistoryView land here. Pagination
+ is next/prev only, anchored on sensor observation timestamps with
+ controller intents fetched in the same time range."""
+
+ PAGE_SIZE = 25
+
+ def get_template_name( self ) -> str:
+ return 'entity/modals/entity_state_history.html'
+
+ def get( self, request, *args, **kwargs ):
+ entity_state = self.get_entity_state( request, *args, **kwargs )
+
+ before = _parse_iso_cursor( request.GET.get( 'before' ) )
+
+ rows = get_entity_state_history_page(
+ entity_state = entity_state,
+ page_size = self.PAGE_SIZE,
+ before = before,
)
- sensor_response_list_map = {
- sensor: [ SensorResponse.from_sensor_history( h ) for h in history_list ]
- for sensor, history_list in sensor_history_list_map.items()
- }
- controller_response_list_map = {
- controller: [ ControllerHistoryResponse.from_controller_history( h ) for h in history_list ]
- for controller, history_list in controller_history_list_map.items()
- }
- entity_state_history_data = EntityStateHistoryData(
- entity = entity,
- sensor_response_list_map = sensor_response_list_map,
- controller_response_list_map = controller_response_list_map,
+
+ # Multi-instrument source annotation surfaces only when the
+ # state has more than one sensor or more than one controller,
+ # i.e., when the row's instrument identity is ambiguous.
+ multi_sensor = entity_state.sensors.count() > 1
+ multi_controller = entity_state.controllers.count() > 1
+ annotate_sources = multi_sensor or multi_controller
+
+ # The oldest row's timestamp drives the "older" navigation
+ # link; the cursor we paged from drives the "newer" link
+ # back toward the most-recent page.
+ older_cursor : Optional[ str ] = (
+ datetimeproxy.datetime_to_iso_str( rows[ -1 ].timestamp )
+ if rows else None
)
- context: Dict[str, Any] = entity_state_history_data.to_template_context()
+ newer_cursor : Optional[ str ] = (
+ datetimeproxy.datetime_to_iso_str( before )
+ if before is not None else None
+ )
+
+ context = {
+ 'entity_state' : entity_state,
+ 'history_rows' : rows,
+ 'annotate_sources' : annotate_sources,
+ 'older_cursor' : older_cursor,
+ 'newer_cursor' : newer_cursor,
+ }
return self.modal_response( request, context )
+def _parse_iso_cursor( raw : Optional[ str ] ) -> Optional[ datetime ]:
+ if not raw:
+ return None
+ try:
+ return datetimeproxy.iso_str_to_datetime( raw )
+ except ValueError:
+ return None
+
+
class EntityEditView( HiModalView, EntityViewMixin, AttributeEditViewMixin ):
"""
This view uses a dual response pattern:
diff --git a/src/hi/apps/sense/models.py b/src/hi/apps/sense/models.py
index d230f040..c7b84894 100644
--- a/src/hi/apps/sense/models.py
+++ b/src/hi/apps/sense/models.py
@@ -3,6 +3,7 @@ import json
from django.db import models
from django.urls import reverse
+from hi.apps.common.utils import strip_parent_name_prefix
from hi.apps.entity.models import EntityState
from hi.integrations.models import IntegrationDetailsModel
@@ -84,6 +85,12 @@ class Sensor( IntegrationDetailsModel ):
def css_class(self):
return f'hi-sensor-{self.id}'
+ @property
+ def short_name(self):
+ """Name with the leading entity-name prefix stripped, for
+ display contexts where the entity name is already visible."""
+ return strip_parent_name_prefix( self.name, self.entity_state.entity.name )
+
class SensorHistory(models.Model):
diff --git a/src/hi/apps/sense/sensor_history_manager.py b/src/hi/apps/sense/sensor_history_manager.py
index e4436f65..75176413 100644
--- a/src/hi/apps/sense/sensor_history_manager.py
+++ b/src/hi/apps/sense/sensor_history_manager.py
@@ -1,11 +1,10 @@
from asgiref.sync import sync_to_async
import logging
-from typing import Dict, List
+from typing import List
from hi.apps.common.singleton import Singleton
-from hi.apps.entity.models import Entity
-from .models import Sensor, SensorHistory
+from .models import SensorHistory
from .transient_models import SensorResponse
logger = logging.getLogger(__name__)
@@ -81,24 +80,3 @@ class SensorHistoryManager( Singleton ):
thread_sensitive = True)( sensor_history_list )
return created_objects
- def get_latest_entity_sensor_history( self,
- entity : Entity,
- max_items : int = 5 ) -> Dict[ Sensor, List[ SensorHistory ] ]:
-
- entity_state_list = list( entity.states.all() )
- entity_state_delegations = entity.entity_state_delegations.select_related('entity_state').all()
- entity_state_list.extend([ x.entity_state for x in entity_state_delegations ])
-
- sensor_list = list()
- for entity_state in entity_state_list:
- sensor_list.extend( entity_state.sensors.all() )
- continue
-
- sensor_history_list_map = dict()
- for sensor in sensor_list:
- sensor_history_list = SensorHistory.objects.filter( sensor = sensor )[0:max_items]
- sensor_history_list_map[sensor] = sensor_history_list
- continue
-
- return sensor_history_list_map
-
diff --git a/src/hi/apps/sense/templates/sense/modals/sensor_history.html b/src/hi/apps/sense/templates/sense/modals/sensor_history.html
deleted file mode 100644
index d945ffb7..00000000
--- a/src/hi/apps/sense/templates/sense/modals/sensor_history.html
+++ /dev/null
@@ -1,25 +0,0 @@
-{% extends "modals/action_done.html" %}
-{% load icons %}
-
-{% block title_text %}
-{{ sensor.name }}
-{% endblock %}
-
-{% block body %}
-<div class="d-flex justify-content-between">
- <h5>Sensor History</h5>
- <div>
- {% if sensor.provides_video_stream %}
- <a href="{% url 'console_entity_video_sensor_history' entity_id=sensor.entity_state.entity.id sensor_id=sensor.id %}"
- data-async="true" class="btn btn-sm btn-outline-primary">
- {% icon "video" size="sm" css_class="hi-icon-left" %}Browse Videos
- </a>
- {% endif %}
- </div>
-</div>
-<div class="py-2" >
- {% include "sense/panes/sensor_history_list.html" with sensor_response_list=sensor_response_list %}
-</div>
-{% include "common/panes/pagination.html" with pagination=pagination %}
-
-{% endblock %}
diff --git a/src/hi/apps/sense/templates/sense/panes/sensor_history_list.html b/src/hi/apps/sense/templates/sense/panes/sensor_history_list.html
deleted file mode 100644
index 350f32f7..00000000
--- a/src/hi/apps/sense/templates/sense/panes/sensor_history_list.html
+++ /dev/null
@@ -1,53 +0,0 @@
-{% load tz %}
-{% load common_tags %}
-{% timezone USER_TIMEZONE %}
-<div class="table-responsive">
- <table class="table table-striped">
- <tbody>
- {% for sensor_response in sensor_response_list %}
- {% if sensor_response.has_video_stream %}
- <tr>
- <td>
- <a href="{{ sensor_response.video_browse_url }}" data-async="true">
- {% include_with_fallback sensor_response.sensor.entity_state.entity_state_type.value_template_name "sense/panes/sensor_response_value_default.html" %}
- </a>
- </td>
- <td>{{ sensor_response.timestamp|localtime }}</td>
- </tr>
- {% elif sensor_response.has_details %}
- <tr>
- <td>
- <a href="{{ sensor_response.details_url }}" data-async="true">
- {% include_with_fallback sensor_response.sensor.entity_state.entity_state_type.value_template_name "sense/panes/sensor_response_value_default.html" %}
- </a>
- </td>
- <td>{{ sensor_response.timestamp|localtime }}</td>
- </tr>
- {% else %}
- <tr>
- <td>
- {% include_with_fallback sensor_response.sensor.entity_state.entity_state_type.value_template_name "sense/panes/sensor_response_value_default.html" %}
- </td>
- <td>{{ sensor_response.timestamp|localtime }}</td>
- </tr>
- {% endif %}
- {% empty %}
- <tr><td colspan="2"><div class="alert alert-info" >No history.</div></td></tr>
- {% endfor %}
- </tbody>
- </table>
-</div>
-
-{% if show_all_link and sensor_response_list %}
-<div>
- {% if sensor.provides_video_stream %}
- <a href="{% url 'console_entity_video_sensor_history' entity_id=sensor.entity_state.entity.id sensor_id=sensor.id %}"
- data-async="true">&gt;&gt; See All</a>
- {% else %}
- {# Use existing sensor history modal for non-video sensors #}
- <a href="{% url 'sense_sensor_history' sensor_id=sensor.id %}"
- data-async="true">&gt;&gt; See All</a>
- {% endif %}
-</div>
-{% endif %}
-{% endtimezone %}
diff --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.html
index afd9a2dd..275e8e2d 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
@@ -3,7 +3,7 @@
<div class="row">
<div class="col-6 align-self-center">
<div class="h6 text-center">
- {{ sensor_response.sensor.name }}
+ {{ sensor_response.sensor.short_name }}
</div>
<div class="d-flex justify-content-around mt-2">
{% if sensor_response.has_video_stream %}
@@ -25,7 +25,7 @@
</div>
{% endif %}
<div>
- <a href="{{ sensor_response.sensor_history_url }}"
+ <a href="{{ sensor_response.entity_state_history_url }}"
class="btn btn-sm btn-outline-primary"
data-async="true">
{% icon "history" size="sm" %} History
diff --git a/src/hi/apps/sense/tests/test_sensor_history_manager.py b/src/hi/apps/sense/tests/test_sensor_history_manager.py
index 7a3a1217..d8ba39b9 100644
--- a/src/hi/apps/sense/tests/test_sensor_history_manager.py
+++ b/src/hi/apps/sense/tests/test_sensor_history_manager.py
@@ -7,7 +7,7 @@ from asgiref.sync import sync_to_async
from django.utils import timezone
from hi.testing.async_task_utils import AsyncTaskTestCase
-from hi.apps.entity.models import Entity, EntityState, EntityStateDelegation
+from hi.apps.entity.models import Entity, EntityState
from hi.apps.sense.models import Sensor, SensorHistory
from hi.apps.sense.sensor_history_manager import SensorHistoryManager
from hi.apps.sense.transient_models import SensorResponse
@@ -221,121 +221,6 @@ class AsyncSensorHistoryManagerTestCase(AsyncTaskTestCase):
self.run_async(async_test_logic())
- def test_get_latest_entity_sensor_history_direct_states(self):
- """Test retrieval of sensor history for entity's direct states."""
- # Create history records
- SensorHistory.objects.create(
- sensor=self.sensor,
- value='value1',
- response_datetime=timezone.make_aware(datetime(2023, 1, 1, 12, 0, 0))
- )
- SensorHistory.objects.create(
- sensor=self.sensor,
- value='value2',
- response_datetime=timezone.make_aware(datetime(2023, 1, 1, 13, 0, 0))
- )
-
- result = self.manager.get_latest_entity_sensor_history(self.entity, max_items=5)
-
- self.assertIn(self.sensor, result)
- history_list = result[self.sensor]
- self.assertEqual(len(history_list), 2)
- # Should be ordered by most recent first
- self.assertEqual(history_list[0].value, 'value2')
- self.assertEqual(history_list[1].value, 'value1')
-
- def test_get_latest_entity_sensor_history_with_delegations(self):
- """Test retrieval includes sensors from delegated entity states."""
- # Create delegated entity and state
- delegated_entity = Entity.objects.create(
- name='Delegated Entity',
- entity_type_str='SENSOR'
- )
- delegated_state = EntityState.objects.create(
- entity=delegated_entity,
- entity_state_type_str='NUMERIC'
- )
- delegated_sensor = Sensor.objects.create(
- name='Delegated Sensor',
- entity_state=delegated_state,
- sensor_type_str='DEFAULT',
- integration_id='delegated_123',
- integration_name='test_integration'
- )
-
- # Create delegation relationship
- EntityStateDelegation.objects.create(
- entity_state=delegated_state,
- delegate_entity=self.entity
- )
-
- # Create history for delegated sensor
- SensorHistory.objects.create(
- sensor=delegated_sensor,
- value='delegated_value',
- response_datetime=timezone.now()
- )
-
- result = self.manager.get_latest_entity_sensor_history(self.entity, max_items=5)
-
- # Should include both direct and delegated sensors
- sensor_keys = list(result.keys())
- self.assertIn(self.sensor, sensor_keys)
- self.assertIn(delegated_sensor, sensor_keys)
-
- def test_get_latest_entity_sensor_history_respects_max_items(self):
- """Test max_items parameter limits history records per sensor."""
- # Create multiple history records
- for i in range(10):
- SensorHistory.objects.create(
- sensor=self.sensor,
- value=f'value_{i}',
- response_datetime=timezone.make_aware(datetime(2023, 1, 1, 12, i, 0))
- )
-
- result = self.manager.get_latest_entity_sensor_history(self.entity, max_items=3)
-
- self.assertIn(self.sensor, result)
- history_list = result[self.sensor]
- self.assertEqual(len(history_list), 3)
- # Should return most recent records
- self.assertEqual(history_list[0].value, 'value_9')
-
- def test_get_latest_entity_sensor_history_handles_no_sensors(self):
- """Test handles entities with no sensors gracefully."""
- entity_no_sensors = Entity.objects.create(
- name='No Sensors Entity',
- entity_type_str='LIGHT'
- )
-
- result = self.manager.get_latest_entity_sensor_history(entity_no_sensors)
-
- self.assertEqual(result, {})
-
- def test_get_latest_entity_sensor_history_query_optimization(self):
- """Test query uses select_related for performance optimization."""
- # Create delegation to test select_related usage
- delegated_entity = Entity.objects.create(
- name='Delegated Entity',
- entity_type_str='SENSOR'
- )
- delegated_state = EntityState.objects.create(
- entity=delegated_entity,
- entity_state_type_str='NUMERIC'
- )
- EntityStateDelegation.objects.create(
- entity_state=delegated_state,
- delegate_entity=self.entity
- )
-
- with patch('hi.apps.entity.models.Entity.entity_state_delegations') as mock_delegations:
- mock_delegations.select_related.return_value.all.return_value = []
-
- self.manager.get_latest_entity_sensor_history(self.entity)
-
- # Verify select_related is used for optimization
- mock_delegations.select_related.assert_called_once_with('entity_state')
-
def test_concurrent_history_addition_thread_safety(self):
"""Test manager handles concurrent access safely."""
import threading
diff --git a/src/hi/apps/sense/tests/test_views.py b/src/hi/apps/sense/tests/test_views.py
index d9ad1f6d..c0053cf8 100644
--- a/src/hi/apps/sense/tests/test_views.py
+++ b/src/hi/apps/sense/tests/test_views.py
@@ -1,4 +1,3 @@
-import json
import logging
from django.urls import reverse
@@ -10,185 +9,6 @@ from hi.testing.view_test_base import DualModeViewTestCase
logging.disable(logging.CRITICAL)
-class TestSensorHistoryView(DualModeViewTestCase):
- """
- Tests for SensorHistoryView - demonstrates HiModalView with pagination testing.
- This view displays the history of sensor readings.
- """
-
- def setUp(self):
- super().setUp()
- # Create test entity and sensor
- self.entity = Entity.objects.create(
- name='Test Sensor Entity',
- entity_type_str='SENSOR'
- )
- self.entity_state = EntityState.objects.create(
- entity=self.entity,
- name='temperature',
- entity_state_type_str='NUMERIC'
- )
- self.sensor = Sensor.objects.create(
- entity_state=self.entity_state,
- sensor_type_str='TEMPERATURE',
- integration_payload='{"device_id": "temp_01"}'
- )
-
- # Create test sensor history entries
- for i in range(5):
- SensorHistory.objects.create(
- sensor=self.sensor,
- value=f'{20 + i}.5',
- response_datetime=f'2023-01-0{i+1}T12:00:00Z'
- )
-
- def test_get_sensor_history_sync(self):
- """Test getting sensor history with synchronous request."""
- url = reverse('sense_sensor_history', kwargs={'sensor_id': self.sensor.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- self.assertHtmlResponse(response)
- self.assertTemplateRendered(response, 'sense/modals/sensor_history.html')
-
- def test_get_sensor_history_async(self):
- """Test getting sensor history with AJAX request."""
- url = reverse('sense_sensor_history', kwargs={'sensor_id': self.sensor.id})
- response = self.async_get(url)
-
- self.assertSuccessResponse(response)
- self.assertJsonResponse(response)
-
- # HiModalView returns JSON with modal content for AJAX requests
- data = response.json()
- self.assertIn('modal', data)
-
- def test_sensor_and_history_in_context(self):
- """Test that sensor and history are passed to template context."""
- url = reverse('sense_sensor_history', kwargs={'sensor_id': self.sensor.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- self.assertEqual(response.context['sensor'], self.sensor)
- self.assertIn('sensor_response_list', response.context)
- self.assertIn('pagination', response.context)
-
- # Should have our test entries
- history_list = response.context['sensor_response_list']
- self.assertEqual(len(history_list), 5)
-
- def test_pagination_context(self):
- """Test that pagination is properly configured."""
- url = reverse('sense_sensor_history', kwargs={'sensor_id': self.sensor.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- pagination = response.context['pagination']
- self.assertIsNotNone(pagination)
- # Should have base URL for sensor history
- self.assertIn(str(self.sensor.id), pagination.base_url)
-
- def test_history_filtered_by_sensor(self):
- """Test that history is filtered to only this sensor."""
- # Create another sensor with history
- other_entity = Entity.objects.create(
- name='Other Sensor',
- entity_type_str='SENSOR'
- )
- other_entity_state = EntityState.objects.create(
- entity=other_entity,
- name='humidity',
- entity_state_type_str='NUMERIC'
- )
- other_sensor = Sensor.objects.create(
- entity_state=other_entity_state,
- sensor_type_str='HUMIDITY',
- integration_payload='{"device_id": "hum_01"}'
- )
- SensorHistory.objects.create(
- sensor=other_sensor,
- value='45.0',
- response_datetime='2023-01-10T12:00:00Z'
- )
-
- url = reverse('sense_sensor_history', kwargs={'sensor_id': self.sensor.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- history_list = response.context['sensor_response_list']
-
- # All response entries should belong to our sensor
- for sensor_response in history_list:
- self.assertEqual(sensor_response.sensor, self.sensor)
-
- def test_pagination_with_many_entries(self):
- """Test pagination when there are many sensor history entries."""
- # Create many more history entries to test pagination
- for i in range(50):
- SensorHistory.objects.create(
- sensor=self.sensor,
- value=f'{30 + i}.0',
- response_datetime=f'2023-02-{(i % 28) + 1:02d}T12:00:00Z'
- )
-
- url = reverse('sense_sensor_history', kwargs={'sensor_id': self.sensor.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- history_list = response.context['sensor_response_list']
-
- # Should be limited by page size (25)
- self.assertLessEqual(len(history_list), 25)
-
- def test_pagination_page_size_constant(self):
- """Test that the page size constant is used correctly."""
- from hi.apps.sense.views import SensorHistoryView
- self.assertEqual(SensorHistoryView.SENSOR_HISTORY_PAGE_SIZE, 25)
-
- def test_empty_sensor_response_list(self):
- """Test page displays correctly when no sensor history exists."""
- # Delete all sensor history
- SensorHistory.objects.all().delete()
-
- url = reverse('sense_sensor_history', kwargs={'sensor_id': self.sensor.id})
- response = self.client.get(url)
-
- self.assertSuccessResponse(response)
- history_list = response.context['sensor_response_list']
- self.assertEqual(len(history_list), 0)
-
- def test_pagination_with_page_parameter(self):
- """Test pagination with specific page parameter."""
- # Create enough entries to have multiple pages
- for i in range(30):
- SensorHistory.objects.create(
- sensor=self.sensor,
- value=f'{40 + i}.0',
- response_datetime=f'2023-03-{(i % 28) + 1:02d}T12:00:00Z'
- )
-
- url = reverse('sense_sensor_history', kwargs={'sensor_id': self.sensor.id})
- response = self.client.get(url, {'page': '2'})
-
- self.assertSuccessResponse(response)
- # Should still return valid response for page 2
- self.assertIn('sensor_response_list', response.context)
-
- def test_nonexistent_sensor_returns_404(self):
- """Test that accessing nonexistent sensor returns 404."""
- url = reverse('sense_sensor_history', kwargs={'sensor_id': 99999})
- response = self.client.get(url)
-
- self.assertEqual(response.status_code, 404)
-
- def test_post_not_allowed(self):
- """Test that POST requests are not allowed."""
- url = reverse('sense_sensor_history', kwargs={'sensor_id': self.sensor.id})
- response = self.client.post(url)
-
- self.assertEqual(response.status_code, 405)
-
-
class TestSensorHistoryDetailsView(DualModeViewTestCase):
"""
Tests for SensorHistoryDetailsView - demonstrates sensor history detail testing.
@@ -212,7 +32,7 @@ class TestSensorHistoryDetailsView(DualModeViewTestCase):
sensor_type_str='PRESSURE',
integration_payload='{"device_id": "press_01"}'
)
-
+
# Create test sensor history entry
self.sensor_history = SensorHistory.objects.create(
sensor=self.sensor,
@@ -236,7 +56,7 @@ class TestSensorHistoryDetailsView(DualModeViewTestCase):
self.assertSuccessResponse(response)
self.assertJsonResponse(response)
-
+
# HiModalView returns JSON with modal content for AJAX requests
data = response.json()
self.assertIn('modal', data)
@@ -289,37 +109,3 @@ class TestSensorHistoryDetailsView(DualModeViewTestCase):
self.assertSuccessResponse(response)
self.assertEqual(response.context['sensor_history'], other_history)
self.assertNotEqual(response.context['sensor_history'], self.sensor_history)
-
-
-class TestSensorHistoryRendering(DualModeViewTestCase):
- """The history list dispatches per row through
- ``EntityStateType.value_template_name``, so discrete-enum stored
- values render as their human-readable labels in the rendered HTML
- rather than the raw stored string."""
-
- def test_discrete_value_renders_as_human_readable_label(self):
- entity = Entity.objects.create( name = 'Motion', entity_type_str = 'MOTION_SENSOR' )
- state = EntityState.objects.create(
- entity = entity,
- name = 'movement',
- entity_state_type_str = 'MOVEMENT',
- value_range_str = json.dumps([ 'active', 'idle' ]),
- )
- sensor = Sensor.objects.create(
- entity_state = state,
- sensor_type_str = 'MOTION',
- integration_payload = '{"device_id": "m1"}',
- )
- SensorHistory.objects.create(
- sensor = sensor, value = 'active',
- response_datetime = '2024-03-01T12:00:00Z',
- )
-
- url = reverse( 'sense_sensor_history', kwargs = { 'sensor_id': sensor.id } )
- response = self.client.get( url )
- self.assertSuccessResponse( response )
- body = response.content.decode()
- # The raw stored value 'active' is humanized to 'Active' by the
- # value_template_name dispatch's default template.
- self.assertIn( 'Active', body )
-
diff --git a/src/hi/apps/sense/transient_models.py b/src/hi/apps/sense/transient_models.py
index 17387a5a..ae989611 100644
--- a/src/hi/apps/sense/transient_models.py
+++ b/src/hi/apps/sense/transient_models.py
@@ -74,9 +74,9 @@ class SensorResponse:
return None
@property
- def sensor_history_url(self) -> str:
- return reverse( 'sense_sensor_history',
- kwargs = { 'sensor_id': self.sensor.id })
+ def entity_state_history_url(self) -> str:
+ return reverse( 'entity_state_history',
+ kwargs = { 'entity_state_id': self.sensor.entity_state.id })
@property
def click_url(self):
@@ -84,7 +84,7 @@ class SensorResponse:
return self.video_browse_url
if self.sensor_history_id and self.has_details:
return self.details_url
- return self.sensor_history_url
+ return self.entity_state_history_url
def to_dict(self):
return {
diff --git a/src/hi/apps/sense/urls.py b/src/hi/apps/sense/urls.py
index 8ccceccd..edd1d33b 100644
--- a/src/hi/apps/sense/urls.py
+++ b/src/hi/apps/sense/urls.py
@@ -5,11 +5,7 @@ from . import views
urlpatterns = [
- re_path( r'^sensor/history/(?P<sensor_id>\d+)$',
- views.SensorHistoryView.as_view(),
- name='sense_sensor_history'),
-
- re_path( r'^sensor/response/details/(?P<sensor_history_id>\d+)$',
- views.SensorHistoryDetailsView.as_view(),
+ re_path( r'^sensor/response/details/(?P<sensor_history_id>\d+)$',
+ views.SensorHistoryDetailsView.as_view(),
name='sense_sensor_history_details'),
]
diff --git a/src/hi/apps/sense/views.py b/src/hi/apps/sense/views.py
index a7f1f518..23bb31f4 100644
--- a/src/hi/apps/sense/views.py
+++ b/src/hi/apps/sense/views.py
@@ -1,64 +1,28 @@
import logging
-from django.urls import reverse
-
-from hi.apps.common.pagination import compute_pagination_from_queryset
-
from hi.hi_async_view import HiModalView
-from .models import SensorHistory
from .transient_models import SensorResponse
from .view_mixins import SenseViewMixin
logger = logging.getLogger(__name__)
-
-
-class SensorHistoryView( HiModalView, SenseViewMixin ):
-
- SENSOR_HISTORY_PAGE_SIZE = 25
-
- def get_template_name( self ) -> str:
- return 'sense/modals/sensor_history.html'
-
- def get( self, request, *args, **kwargs ):
-
- sensor = self.get_sensor( request, *args, **kwargs )
- base_url = reverse( 'sense_sensor_history', kwargs = { 'sensor_id': sensor.id } )
-
- queryset = SensorHistory.objects.filter( sensor = sensor )
- pagination = compute_pagination_from_queryset( request = request,
- queryset = queryset,
- base_url = base_url,
- page_size = self.SENSOR_HISTORY_PAGE_SIZE,
- async_urls = True )
- sensor_history_list = queryset[pagination.start_offset:pagination.end_offset + 1]
- sensor_response_list = [
- SensorResponse.from_sensor_history( h ) for h in sensor_history_list
- ]
-
- context = {
- 'sensor': sensor,
- 'sensor_response_list': sensor_response_list,
- 'pagination': pagination,
- }
- return self.modal_response( request, context )
class SensorHistoryDetailsView( HiModalView, SenseViewMixin ):
def get_template_name( self ) -> str:
return 'sense/modals/sensor_history_details.html'
-
+
def get(self, request, *args, **kwargs):
sensor_history = self.get_sensor_history( request, *args, **kwargs )
-
+
# Create SensorResponse from sensor_history for video URL generation
sensor_response = None
try:
sensor_response = SensorResponse.from_sensor_history(sensor_history)
except Exception as e:
logger.error(f"Error creating SensorResponse from sensor_history: {e}")
-
+
context = {
'sensor_history': sensor_history,
'sensor_response': sensor_response,
diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.css
index 20af12f2..69c33208 100644
--- a/src/hi/static/css/main.css
+++ b/src/hi/static/css/main.css
@@ -2209,6 +2209,16 @@ g[hover] {
border-left-color: var(--danger-color);
}
+/* Light primary-tinted banner used as a section header (e.g., the
+ entity-history modal's per-state group headers). Uses the same
+ tint as ``.timeline-item:hover`` so the section header reads as
+ part of the same visual family as the cards it groups. */
+.hi-section-banner {
+ background-color: var(--info-bg-light);
+ border-left: 3px solid var(--primary-color);
+ border-radius: 0.25rem;
+}
+
.hi-sync-result-item-list {
max-height: 160px;
overflow-y: auto;