Home Information - Your home, your data, organized.
Python
VideoStream Architecture Refactor (#110)
Tony C565e0e18828b
diff --git a/docs/migrations/issue_106_video_stream_migration.sql b/docs/migrations/issue_106_video_stream_migration.sqlnew file mode 100644index 00000000..b88670da--- /dev/null+++ b/docs/migrations/issue_106_video_stream_migration.sql@@ -0,0 +1,77 @@+-- Data Migration for Issue #106 - VideoStream Infrastructure Refactor+-- This SQL script provides the same migrations as the Django migration+-- Use for manual verification or direct database migration if needed++-- Pre-Migration Verification Counts+-- Run these queries before migration to understand the impact:++SELECT 'VIDEO_STREAM states to delete' as description, COUNT(*) as count+FROM entity_entitystate+WHERE entity_state_type_str = 'video_stream';++SELECT 'ZM cameras to update' as description, COUNT(*) as count+FROM entity_entity+WHERE integration_id = 'zm' AND entity_type_str = 'camera';++SELECT 'MOVEMENT sensors to update' as description, COUNT(*) as count+FROM sense_sensor s+JOIN entity_entitystate es ON s.entity_state_id = es.id+JOIN entity_entity e ON es.entity_id = e.id+WHERE es.entity_state_type_str = 'movement' AND e.integration_id = 'zm';++SELECT 'VIDEO_STREAM delegations to cascade delete' as description, COUNT(*) as count+FROM entity_entitystatedelegation+WHERE entity_state_id IN (+ SELECT id FROM entity_entitystate+ WHERE entity_state_type_str = 'video_stream'+);++-- Migration Steps+-- Execute in order:++-- 1. Update ZoneMinder camera entities to have video capability+UPDATE entity_entity+SET has_video_stream = TRUE+WHERE integration_id = 'zm'+ AND entity_type_str = 'camera';++-- 2. Update MOVEMENT sensors for ZM entities to provide video streams+UPDATE sense_sensor+SET provides_video_stream = TRUE+FROM entity_entitystate es+JOIN entity_entity e ON es.entity_id = e.id+WHERE sense_sensor.entity_state_id = es.id+ AND es.entity_state_type_str = 'movement'+ AND e.integration_id = 'zm';++-- 3. Delete VIDEO_STREAM sensors (CASCADE handles SensorHistory)+DELETE FROM sense_sensor+WHERE entity_state_id IN (+ SELECT id FROM entity_entitystate+ WHERE entity_state_type_str = 'video_stream'+);++-- 4. Delete VIDEO_STREAM EntityStates (CASCADE handles delegations)+DELETE FROM entity_entitystate+WHERE entity_state_type_str = 'video_stream';++-- Post-Migration Verification+-- Run these queries after migration to verify success:++SELECT 'Remaining VIDEO_STREAM states (should be 0)' as check, COUNT(*) as count+FROM entity_entitystate+WHERE entity_state_type_str = 'video_stream';++SELECT 'ZM cameras without video capability (should be 0)' as check, COUNT(*) as count+FROM entity_entity+WHERE integration_id = 'zm'+ AND entity_type_str = 'camera'+ AND has_video_stream = FALSE;++SELECT 'ZM MOVEMENT sensors without video capability (should be 0)' as check, COUNT(*) as count+FROM sense_sensor s+JOIN entity_entitystate es ON s.entity_state_id = es.id+JOIN entity_entity e ON es.entity_id = e.id+WHERE es.entity_state_type_str = 'movement'+ AND e.integration_id = 'zm'+ AND s.provides_video_stream = FALSE;\ No newline at end of filediff --git a/src/hi/apps/alert/alarm.py b/src/hi/apps/alert/alarm.pyindex 0f0d204f..62c09fd6 100644--- a/src/hi/apps/alert/alarm.py+++ b/src/hi/apps/alert/alarm.py@@ -1,28 +1,21 @@from dataclasses import dataclassfrom datetime import datetime-from typing import Dict, List+from typing import Listfrom hi.apps.audio.audio_signal import AudioSignalfrom hi.apps.security.enums import SecurityLevel+from hi.apps.sense.transient_models import SensorResponsefrom .enums import AlarmLevel, AlarmSource-@dataclass-class AlarmSourceDetails:-- detail_attrs : Dict[ str, str ]- image_url : str = None- sensor_id : int = None # ID of the sensor that generated this alarm--@dataclassclass Alarm:alarm_source : AlarmSourcealarm_type : stralarm_level : AlarmLeveltitle : str- source_details_list : List[ AlarmSourceDetails ]+ sensor_response_list : List[ SensorResponse ]security_level : SecurityLevelalarm_lifetime_secs : inttimestamp : datetimediff --git a/src/hi/apps/alert/alert.py b/src/hi/apps/alert/alert.pyindex 6465c58e..fa47d0a5 100644--- a/src/hi/apps/alert/alert.py+++ b/src/hi/apps/alert/alert.py@@ -130,18 +130,50 @@ class Alert:def get_first_visual_content(self):"""Find the first image/video content from any alarm in the alert.- Returns dict with image info or None if no visual content found.+ Returns dict with image info and sensor response or None if no visual content found."""for alarm in self.alarm_list:- for source_details in alarm.source_details_list:- if source_details.image_url:+ for sensor_response in alarm.sensor_response_list:+ # Check for video stream capability first (preferred over static source_image_url)+ if sensor_response.has_video_stream:return {- 'image_url': source_details.image_url,+ 'source_image_url': sensor_response.source_image_url,'alarm': alarm,+ 'source_details': sensor_response, # Keep for backward compatibility+ 'sensor_response': sensor_response,+ 'is_from_latest': alarm == self.alarm_list[0] if self.alarm_list else False,+ }+ # Fallback to static source_image_url if no video stream+ elif sensor_response.source_image_url:+ return {+ 'source_image_url': sensor_response.source_image_url,+ 'alarm': alarm,+ 'source_details': sensor_response, # Keep for backward compatibility+ 'sensor_response': sensor_response,'is_from_latest': alarm == self.alarm_list[0] if self.alarm_list else False,}return None+ def get_all_video_sources(self):+ """+ Get all sensor responses with video streams from all alarms in the alert.+ Returns list of dicts with sensor_response, alarm, and index info.+ """+ video_sources = []+ for alarm in self.alarm_list:+ for sensor_response in alarm.sensor_response_list:+ if sensor_response.has_video_stream:+ video_sources.append({+ 'sensor_response': sensor_response,+ 'alarm': alarm,+ 'index': len(video_sources) + 1, # 1-based for UI+ })+ return video_sources++ def get_video_source_count(self):+ """Get total count of video sources across all alarms in the alert."""+ return len(self.get_all_video_sources())+def to_notification_item(self):return NotificationItem(signature = self.signature,diff --git a/src/hi/apps/alert/templates/alert/modals/alert_details.html b/src/hi/apps/alert/templates/alert/modals/alert_details.htmlindex 286ac731..a5e4bb2d 100644--- a/src/hi/apps/alert/templates/alert/modals/alert_details.html+++ b/src/hi/apps/alert/templates/alert/modals/alert_details.html@@ -1,6 +1,7 @@{% extends "modals/action_done.html" %}{% load humanize %}{% load tz %}+{% load video_tags %}{% block title_text %}{{ alert.title }}@@ -41,8 +42,11 @@</div></div>-<!-- Visual Content (if available) -->-{% if alert_visual_content %}+<!-- Visual Content (Smart Rendering) -->+{% if video_source_count == 1 and alert_visual_content and alert_visual_content.sensor_response %}+<!-- Show single video at alert level to avoid duplication -->+{% sensor_response_video_stream alert_visual_content.sensor_response as video_url %}+{% if video_url %}<div class="row mb-3"><div class="col-12"><div class="card">@@ -52,15 +56,55 @@</h6></div><div class="card-body p-2">- <img class="img-fluid" src="{{ alert_visual_content.image_url }}" alt="{{ alert_visual_content.alarm.title }}">+ <img class="img-fluid" src="{{ video_url }}" alt="{{ alert_visual_content.alarm.title }}">{% if not alert_visual_content.is_from_latest %}- <small class="text-muted d-block mt-1">From: {{ alert_visual_content.alarm.timestamp|localtime|date:"M j, Y H:i" }}</small>+ <small class="text-muted d-block mt-1">From: {{ alert_visual_content.alarm.timestamp|localtime|date:"M j, Y H:i" }}</small>{% endif %}</div></div></div></div>{% endif %}+{% elif video_source_count >= 4 %}+<!-- Show collapsible video list for many videos -->+<div class="row mb-3">+ <div class="col-12">+ <div class="card">+ <div class="card-header bg-primary text-white">+ <h6 class="mb-0">+ <a class="text-white text-decoration-none" data-toggle="collapse" href="#videoSources"+ role="button" aria-expanded="false" aria-controls="videoSources">+ <span class="mr-2">📷</span>Visual Content ({{ video_source_count }} sources)+ <span class="ml-2">▶</span>+ </a>+ </h6>+ </div>+ <div class="collapse" id="videoSources">+ <div class="card-body">+ <div class="row">+ {% for video_source in all_video_sources %}+ <div class="col-md-6 mb-3">+ {% sensor_response_video_stream video_source.sensor_response as video_url %}+ {% if video_url %}+ <div class="card">+ <div class="card-header py-1">+ <small class="text-muted">Source {{ video_source.index }} - {{ video_source.alarm.timestamp|localtime|date:"M j H:i" }}</small>+ </div>+ <div class="card-body p-2">+ <img class="img-fluid" src="{{ video_url }}" alt="Source {{ video_source.index }}">+ </div>+ </div>+ {% endif %}+ </div>+ {% endfor %}+ </div>+ </div>+ </div>+ </div>+ </div>+</div>+{% endif %}+<!-- For 2-3 video sources, they will be shown inline at sensor response level --><!-- Recent Alarm Details --><div class="row mb-3">diff --git a/src/hi/apps/alert/templates/alert/panes/alarm_details.html b/src/hi/apps/alert/templates/alert/panes/alarm_details.htmlindex 7d613263..cbc6846d 100644--- a/src/hi/apps/alert/templates/alert/panes/alarm_details.html+++ b/src/hi/apps/alert/templates/alert/panes/alarm_details.html@@ -3,14 +3,14 @@<div><div>Alarmed at: {{ alarm.timestamp|localtime }}- {{ alarm.source_details_list|length }}+ {{ alarm.sensor_response_list|length }}</div><div>- {% for source_details in alarm.source_details_list %}- {% if alarm.source_details_list|length > 1 %}+ {% for sensor_response in alarm.sensor_response_list %}+ {% if alarm.sensor_response_list|length > 1 %}<h6>Source {{ forloop.counter }} Details</h6>{% endif %}- {% include "alert/panes/alarm_source_details.html" %}+ {% include "alert/panes/alarm_sensor_response.html" %}{% endfor %}</div></div>diff --git a/src/hi/apps/alert/templates/alert/panes/alarm_sensor_response.html b/src/hi/apps/alert/templates/alert/panes/alarm_sensor_response.htmlnew file mode 100644index 00000000..39e360aa--- /dev/null+++ b/src/hi/apps/alert/templates/alert/panes/alarm_sensor_response.html@@ -0,0 +1,19 @@+{% load video_tags %}+<div>+ {% if show_video_inline %}+ {% sensor_response_video_stream sensor_response as video_url %}+ {% if video_url %}+ <div class="mb-2">+ <img class="img-fluid" src="{{ video_url }}" alt="{{ alarm.title }}">+ </div>+ {% endif %}+ {% endif %}+ <div>+ {% for label, value in sensor_response.detail_attrs.items %}+ <div class="row">+ <div class="col-3 text-right">{{ label }}</div>+ <div class="col-9-">{{ value }}</div>+ </div>+ {% endfor %}+ </div>+</div>diff --git a/src/hi/apps/alert/templates/alert/panes/alarm_source_details.html b/src/hi/apps/alert/templates/alert/panes/alarm_source_details.htmldeleted file mode 100644index 4903a1d0..00000000--- a/src/hi/apps/alert/templates/alert/panes/alarm_source_details.html+++ /dev/null@@ -1,15 +0,0 @@-<div>- {% if source_details.image_url %}- <div>- <img class="img-fluid" src="{{ source_details.image_url }}" alt="{{ alarm.title }}">- </div>- {% endif %}- <div>- {% for label, value in source_details.detail_attrs.items %}- <div class="row">- <div class="col-3 text-right">{{ label }}</div>- <div class="col-9-">{{ value }}</div>- </div>- {% endfor %}- </div>-</div>diff --git a/src/hi/apps/alert/tests/synthetic_data.py b/src/hi/apps/alert/tests/synthetic_data.pyindex 64287633..e1853962 100644--- a/src/hi/apps/alert/tests/synthetic_data.py+++ b/src/hi/apps/alert/tests/synthetic_data.py@@ -2,12 +2,14 @@ from datetime import datetime, timedeltaimport randomfrom typing import List-from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+from hi.apps.alert.alarm import Alarmfrom hi.apps.alert.alert import Alertfrom hi.apps.alert.alert_status import AlertStatusDatafrom hi.apps.alert.enums import AlarmLevel, AlarmSourceimport hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.security.enums import SecurityLevel+from hi.apps.sense.transient_models import SensorResponse+from hi.integrations.transient_models import IntegrationKeyclass AlertSyntheticData:@@ -32,18 +34,23 @@ class AlertSyntheticData:if not detail_attrs:detail_attrs = {'Location': 'Kitchen', 'Sensor': 'Motion-01'}- image_url = '/static/img/hi-icon-196x196.png' if has_image else None+ source_image_url = '/static/img/hi-icon-196x196.png' if has_image else Nonealarm = Alarm(alarm_source = alarm_source,alarm_type = alarm_type,alarm_level = alarm_level,title = title,- source_details_list = [- AlarmSourceDetails(- detail_attrs = detail_attrs,- image_url = image_url,- ),+ sensor_response_list = [+ SensorResponse(+ integration_key=IntegrationKey("test", "synthetic"),+ value="active",+ timestamp=timestamp,+ sensor=None,+ detail_attrs=detail_attrs,+ source_image_url=source_image_url,+ has_video_stream=False+ )],security_level = security_level,alarm_lifetime_secs = alarm_lifetime_secs,@@ -73,7 +80,7 @@ class AlertSyntheticData:base_detail_attrs = {'Location': 'Living Room', 'Sensor': 'Motion-02'}# Create first alarm- image_url = '/static/img/hi-icon-196x196.png' if has_image else None+ source_image_url = '/static/img/hi-icon-196x196.png' if has_image else Nonedetail_attrs = dict(base_detail_attrs)detail_attrs.update({'Count': f'1 of {alarm_count}'})@@ -82,11 +89,16 @@ class AlertSyntheticData:alarm_type = alarm_type,alarm_level = alarm_level,title = f'{alarm_level.label}: {base_title}',- source_details_list = [- AlarmSourceDetails(- detail_attrs = detail_attrs,- image_url = image_url,- ),+ sensor_response_list = [+ SensorResponse(+ integration_key=IntegrationKey("test", "synthetic"),+ value="active",+ timestamp=reference_datetime,+ sensor=None,+ detail_attrs=detail_attrs,+ source_image_url=source_image_url,+ has_video_stream=False+ )],security_level = security_level,alarm_lifetime_secs = alarm_lifetime_secs,@@ -105,10 +117,15 @@ class AlertSyntheticData:alarm_type = alarm_type,alarm_level = alarm_level,title = f'{alarm_level.label}: {base_title} ({i})',- source_details_list = [- AlarmSourceDetails(- detail_attrs = detail_attrs,- image_url = image_url if i == 2 else None, # Only second alarm has image+ sensor_response_list = [+ SensorResponse(+ integration_key=IntegrationKey("test", "synthetic"),+ value="active",+ timestamp=reference_datetime,+ sensor=None,+ detail_attrs=detail_attrs,+ source_image_url=source_image_url if i == 2 else None, # Only second alarm has image+ has_video_stream=False),],security_level = security_level,@@ -130,7 +147,7 @@ class AlertSyntheticData:alarm_level : AlarmLevel = AlarmLevel.INFO ) -> Alert:"""Create an event-based alert for testing."""- image_url = '/static/img/hi-icon-196x196.png' if has_image else None+ source_image_url = '/static/img/hi-icon-196x196.png' if has_image else Nonedetail_attrs = {'Event': event_name,'Location': location,@@ -144,11 +161,16 @@ class AlertSyntheticData:alarm_type = event_name,alarm_level = alarm_level,title = f'{alarm_level.label}: {location} {event_name.lower()}',- source_details_list = [- AlarmSourceDetails(- detail_attrs = detail_attrs,- image_url = image_url,- ),+ sensor_response_list = [+ SensorResponse(+ integration_key=IntegrationKey("test", "synthetic"),+ value="active",+ timestamp=datetimeproxy.now(),+ sensor=None,+ detail_attrs=detail_attrs,+ source_image_url=source_image_url,+ has_video_stream=False+ )],security_level = SecurityLevel.LOW,alarm_lifetime_secs = 180,@@ -167,7 +189,7 @@ class AlertSyntheticData:has_image : bool = False ) -> Alert:"""Create a weather-based alert for testing."""- image_url = '/static/img/hi-icon-196x196.png' if has_image else None+ source_image_url = '/static/img/hi-icon-196x196.png' if has_image else Nonedetail_attrs = {'Alert Type': alert_type,'Location': location,@@ -183,11 +205,16 @@ class AlertSyntheticData:alarm_type = 'Severe Weather',alarm_level = AlarmLevel.CRITICAL,title = f'CRITICAL: {alert_type} issued',- source_details_list = [- AlarmSourceDetails(- detail_attrs = detail_attrs,- image_url = image_url,- ),+ sensor_response_list = [+ SensorResponse(+ integration_key=IntegrationKey("test", "synthetic"),+ value="active",+ timestamp=datetimeproxy.now(),+ sensor=None,+ detail_attrs=detail_attrs,+ source_image_url=source_image_url,+ has_video_stream=False+ )],security_level = SecurityLevel.HIGH,alarm_lifetime_secs = expires_in_mins * 60,@@ -254,11 +281,12 @@ class AlertSyntheticData:alarm_type = alarm_type,alarm_level= alarm_level,title = alarm_title,- source_details_list = [- AlarmSourceDetails(- detail_attrs = { 'Notes': f'Details for {alarm_title}. Seed = {seed} ' },- image_url = '/static/img/hi-icon-196x196.png',- ),+ sensor_response_list = [+ SensorResponse(integration_key=IntegrationKey("test", "synthetic"), value="active", timestamp=alarm_timestamp, sensor=None,+ detail_attrs={'Notes': f'Details for {alarm_title}. Seed = {seed} '},+ source_image_url='/static/img/hi-icon-196x196.png',+ has_video_stream=False+ ),],security_level = security_level,alarm_lifetime_secs = alarm_lifetime_secs,@@ -276,11 +304,12 @@ class AlertSyntheticData:alarm_type = alarm_type,alarm_level= alarm_level,title = alarm_title,- source_details_list = [- AlarmSourceDetails(- detail_attrs = { 'Notes': f'Details for {alarm_title}. Seed = {seed} ' },- image_url = '/static/img/hi-icon-196x196.png',- ),+ sensor_response_list = [+ SensorResponse(integration_key=IntegrationKey("test", "synthetic"), value="active", timestamp=alarm_timestamp, sensor=None,+ detail_attrs={'Notes': f'Details for {alarm_title}. Seed = {seed} '},+ source_image_url='/static/img/hi-icon-196x196.png',+ has_video_stream=False+ ),],security_level = security_level,alarm_lifetime_secs = alarm_lifetime_secs,diff --git a/src/hi/apps/alert/tests/test_alarm.py b/src/hi/apps/alert/tests/test_alarm.pyindex 933e15aa..e530531a 100644--- a/src/hi/apps/alert/tests/test_alarm.py+++ b/src/hi/apps/alert/tests/test_alarm.py@@ -1,11 +1,14 @@import loggingfrom datetime import datetime-from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+from hi.apps.alert.alarm import Alarmfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.audio.audio_signal import AudioSignalfrom hi.apps.security.enums import SecurityLevel+from hi.apps.sense.transient_models import SensorResponse+from hi.integrations.transient_models import IntegrationKeyfrom hi.testing.base_test_case import BaseTestCase+import hi.apps.common.datetimeproxy as datetimeproxylogging.disable(logging.CRITICAL)@@ -19,7 +22,7 @@ class TestAlarm(BaseTestCase):alarm_type='test_alarm',alarm_level=AlarmLevel.WARNING,title='Test Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetime.now(),@@ -34,7 +37,7 @@ class TestAlarm(BaseTestCase):alarm_type='critical_test',alarm_level=AlarmLevel.CRITICAL,title='Critical Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetime.now(),@@ -55,7 +58,7 @@ class TestAlarm(BaseTestCase):alarm_type='info_test',alarm_level=AlarmLevel.INFO,title='Info Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetime.now(),@@ -66,7 +69,7 @@ class TestAlarm(BaseTestCase):alarm_type='warning_test',alarm_level=AlarmLevel.WARNING,title='Warning Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetime.now(),@@ -77,7 +80,7 @@ class TestAlarm(BaseTestCase):alarm_type='critical_test',alarm_level=AlarmLevel.CRITICAL,title='Critical Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetime.now(),@@ -98,34 +101,72 @@ class TestAlarm(BaseTestCase):return-class TestAlarmSourceDetails(BaseTestCase):+class TestAlarmWithSensorResponse(BaseTestCase):- def test_alarm_source_details_creation(self):- """Test AlarmSourceDetails dataclass - business logic for alarm context."""+ def test_alarm_with_sensor_response_details(self):+ """Test Alarm with SensorResponse as source details."""detail_attrs = {'entity_name': 'Test Sensor','location': 'Kitchen','value': '75.2°F'}- details = AlarmSourceDetails(+ sensor_response = SensorResponse(+ integration_key=IntegrationKey('test_integration', 'test_sensor'),+ value='active',+ timestamp=datetimeproxy.now(),+ sensor=None,detail_attrs=detail_attrs,- image_url='https://example.com/sensor.jpg'+ source_image_url='https://example.com/sensor.jpg',+ has_video_stream=False)- self.assertEqual(details.detail_attrs, detail_attrs)- self.assertEqual(details.image_url, 'https://example.com/sensor.jpg')+ alarm = Alarm(+ alarm_source=AlarmSource.EVENT,+ alarm_type='test_alarm',+ alarm_level=AlarmLevel.WARNING,+ title='Test Alarm',+ sensor_response_list=[sensor_response],+ security_level=SecurityLevel.LOW,+ alarm_lifetime_secs=300,+ timestamp=datetime.now(),+ )++ self.assertEqual(len(alarm.sensor_response_list), 1)+ self.assertEqual(alarm.sensor_response_list[0].detail_attrs, detail_attrs)+ self.assertEqual(alarm.sensor_response_list[0].source_image_url, 'https://example.com/sensor.jpg')return- def test_alarm_source_details_optional_image_url(self):- """Test AlarmSourceDetails with optional image_url - default value handling."""+ def test_alarm_with_weather_sensor_response(self):+ """Test Alarm with weather-style SensorResponse (no sensor)."""detail_attrs = {- 'entity_name': 'Test Sensor',- 'location': 'Kitchen'+ 'Event Type': 'Severe Thunderstorm',+ 'Location': 'Austin, TX'}- details = AlarmSourceDetails(detail_attrs=detail_attrs)+ # Weather alerts create SensorResponse without sensor+ sensor_response = SensorResponse(+ integration_key=IntegrationKey('weather', 'alert.123'),+ value='active',+ timestamp=datetimeproxy.now(),+ sensor=None,+ detail_attrs=detail_attrs,+ source_image_url=None,+ has_video_stream=False+ )++ alarm = Alarm(+ alarm_source=AlarmSource.WEATHER,+ alarm_type='severe_thunderstorm',+ alarm_level=AlarmLevel.WARNING,+ title='Severe Thunderstorm Warning',+ sensor_response_list=[sensor_response],+ security_level=SecurityLevel.OFF,+ alarm_lifetime_secs=1800,+ timestamp=datetime.now(),+ )- self.assertEqual(details.detail_attrs, detail_attrs)- self.assertIsNone(details.image_url)+ self.assertEqual(alarm.sensor_response_list[0].detail_attrs, detail_attrs)+ self.assertIsNone(alarm.sensor_response_list[0].source_image_url)+ self.assertIsNone(alarm.sensor_response_list[0].sensor)returndiff --git a/src/hi/apps/alert/tests/test_alert.py b/src/hi/apps/alert/tests/test_alert.pyindex db8243e3..c518afa9 100644--- a/src/hi/apps/alert/tests/test_alert.py+++ b/src/hi/apps/alert/tests/test_alert.py@@ -3,9 +3,11 @@ from datetime import timedeltaimport hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.alert.alert import Alert-from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+from hi.apps.alert.alarm import Alarmfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.security.enums import SecurityLevel+from hi.apps.sense.transient_models import SensorResponse+from hi.integrations.transient_models import IntegrationKeyfrom hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)@@ -20,7 +22,7 @@ class TestAlert(BaseTestCase):alarm_type='test_alarm',alarm_level=AlarmLevel.WARNING,title='Test Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -53,7 +55,7 @@ class TestAlert(BaseTestCase):alarm_type='test_alarm', # Same typealarm_level=AlarmLevel.WARNING, # Same leveltitle='Another Test Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -65,7 +67,7 @@ class TestAlert(BaseTestCase):alarm_type='different_alarm', # Different typealarm_level=AlarmLevel.WARNING,title='Different Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -86,7 +88,7 @@ class TestAlert(BaseTestCase):alarm_type='test_alarm',alarm_level=AlarmLevel.WARNING,title='Second Test Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=600, # Different lifetimetimestamp=datetimeproxy.now(),@@ -116,7 +118,7 @@ class TestAlert(BaseTestCase):alarm_type='different_alarm', # Different typealarm_level=AlarmLevel.WARNING,title='Different Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -141,7 +143,7 @@ class TestAlert(BaseTestCase):alarm_type='test_alarm',alarm_level=AlarmLevel.WARNING,title='Second Test Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -163,7 +165,7 @@ class TestAlert(BaseTestCase):alarm_type='test_alarm',alarm_level=AlarmLevel.WARNING,title=f'Alarm {i}',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -183,7 +185,7 @@ class TestAlert(BaseTestCase):alarm_type='critical_test',alarm_level=AlarmLevel.CRITICAL,title='Critical Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -194,7 +196,7 @@ class TestAlert(BaseTestCase):alarm_type='info_test',alarm_level=AlarmLevel.INFO,title='Info Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -238,7 +240,7 @@ class TestAlert(BaseTestCase):alarm_type='test_alarm',alarm_level=AlarmLevel.WARNING,title='Second Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -255,10 +257,15 @@ class TestAlert(BaseTestCase):alarm_type='motion_detection',alarm_level=AlarmLevel.WARNING,title='Motion Detected',- source_details_list=[- AlarmSourceDetails(+ sensor_response_list=[+ SensorResponse(+ integration_key=IntegrationKey('test', 'test.visual_content'),+ value='active',+ timestamp=datetimeproxy.now(),+ sensor=None,detail_attrs={'Location': 'Kitchen'},- image_url='/static/img/test-image.png',+ source_image_url='/static/img/test-image.png',+ has_video_stream=False)],security_level=SecurityLevel.LOW,@@ -270,7 +277,7 @@ class TestAlert(BaseTestCase):visual_content = alert.get_first_visual_content()self.assertIsNotNone(visual_content)- self.assertEqual(visual_content['image_url'], '/static/img/test-image.png')+ self.assertEqual(visual_content['source_image_url'], '/static/img/test-image.png')self.assertEqual(visual_content['alarm'], alarm_with_image)self.assertTrue(visual_content['is_from_latest'])return@@ -282,10 +289,15 @@ class TestAlert(BaseTestCase):alarm_type='door_open',alarm_level=AlarmLevel.INFO,title='Door Opened',- source_details_list=[- AlarmSourceDetails(+ sensor_response_list=[+ SensorResponse(+ integration_key=IntegrationKey('test', 'test.no_image'),+ value='active',+ timestamp=datetimeproxy.now(),+ sensor=None,detail_attrs={'Location': 'Front Door'},- image_url=None,+ source_image_url=None,+ has_video_stream=False)],security_level=SecurityLevel.LOW,@@ -306,10 +318,15 @@ class TestAlert(BaseTestCase):alarm_type='motion_detection',alarm_level=AlarmLevel.WARNING,title='First Motion',- source_details_list=[- AlarmSourceDetails(+ sensor_response_list=[+ SensorResponse(+ integration_key=IntegrationKey('test', 'test.first_image'),+ value='active',+ timestamp=datetimeproxy.now(),+ sensor=None,detail_attrs={'Location': 'Kitchen'},- image_url='/static/img/first-image.png',+ source_image_url='/static/img/first-image.png',+ has_video_stream=False)],security_level=SecurityLevel.LOW,@@ -322,10 +339,15 @@ class TestAlert(BaseTestCase):alarm_type='motion_detection',alarm_level=AlarmLevel.WARNING,title='Second Motion',- source_details_list=[- AlarmSourceDetails(+ sensor_response_list=[+ SensorResponse(+ integration_key=IntegrationKey('test', 'test.no_image2'),+ value='active',+ timestamp=datetimeproxy.now(),+ sensor=None,detail_attrs={'Location': 'Kitchen'},- image_url=None,+ source_image_url=None,+ has_video_stream=False)],security_level=SecurityLevel.LOW,@@ -338,7 +360,7 @@ class TestAlert(BaseTestCase):visual_content = alert.get_first_visual_content()self.assertIsNotNone(visual_content)- self.assertEqual(visual_content['image_url'], '/static/img/first-image.png')+ self.assertEqual(visual_content['source_image_url'], '/static/img/first-image.png')self.assertEqual(visual_content['alarm'], first_alarm_with_image)self.assertFalse(visual_content['is_from_latest']) # first_alarm_with_image is not at index 0 after adding second alarmreturn@@ -350,10 +372,15 @@ class TestAlert(BaseTestCase):alarm_type='motion_detection',alarm_level=AlarmLevel.WARNING,title='First Motion',- source_details_list=[- AlarmSourceDetails(+ sensor_response_list=[+ SensorResponse(+ integration_key=IntegrationKey('test', 'test.no_image2'),+ value='active',+ timestamp=datetimeproxy.now(),+ sensor=None,detail_attrs={'Location': 'Kitchen'},- image_url=None,+ source_image_url=None,+ has_video_stream=False)],security_level=SecurityLevel.LOW,@@ -366,10 +393,15 @@ class TestAlert(BaseTestCase):alarm_type='motion_detection',alarm_level=AlarmLevel.WARNING,title='Second Motion',- source_details_list=[- AlarmSourceDetails(+ sensor_response_list=[+ SensorResponse(+ integration_key=IntegrationKey('test', 'test.second_image'),+ value='active',+ timestamp=datetimeproxy.now(),+ sensor=None,detail_attrs={'Location': 'Kitchen'},- image_url='/static/img/second-image.png',+ source_image_url='/static/img/second-image.png',+ has_video_stream=False)],security_level=SecurityLevel.LOW,@@ -382,7 +414,7 @@ class TestAlert(BaseTestCase):visual_content = alert.get_first_visual_content()self.assertIsNotNone(visual_content)- self.assertEqual(visual_content['image_url'], '/static/img/second-image.png')+ self.assertEqual(visual_content['source_image_url'], '/static/img/second-image.png')self.assertEqual(visual_content['alarm'], second_alarm_with_image)self.assertTrue(visual_content['is_from_latest']) # second_alarm_with_image is at index 0 after being addedreturndiff --git a/src/hi/apps/alert/tests/test_alert_manager.py b/src/hi/apps/alert/tests/test_alert_manager.pyindex f972a063..aaed5436 100644--- a/src/hi/apps/alert/tests/test_alert_manager.py+++ b/src/hi/apps/alert/tests/test_alert_manager.py@@ -57,7 +57,7 @@ class TestAlertManager(BaseTestCase):alarm_type='test_alarm',alarm_level=AlarmLevel.WARNING,title='Test Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -123,7 +123,7 @@ class TestAlertManager(BaseTestCase):alarm_type='test_alarm',alarm_level=AlarmLevel.CRITICAL,title='Test Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),diff --git a/src/hi/apps/alert/tests/test_alert_manager_delegation.py b/src/hi/apps/alert/tests/test_alert_manager_delegation.pyindex 8b727011..85c7ce75 100644--- a/src/hi/apps/alert/tests/test_alert_manager_delegation.py+++ b/src/hi/apps/alert/tests/test_alert_manager_delegation.py@@ -5,10 +5,12 @@ from unittest.mock import Mock, patchfrom django.utils import timezonefrom hi.apps.alert.alert_manager import AlertManager-from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+from hi.apps.alert.alarm import Alarmfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.console.transient_view_manager import TransientViewManagerfrom hi.apps.security.enums import SecurityLevel+from hi.apps.sense.transient_models import SensorResponse+from hi.integrations.transient_models import IntegrationKeyfrom hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)@@ -72,24 +74,19 @@ class TestAlertManagerDelegation(BaseTestCase):name='Motion Sensor')- # Create video stream sensor state on same entity- video_state = EntityState.objects.create(- entity=entity,- entity_state_type_str=str(EntityStateType.VIDEO_STREAM),- name='video_stream'- )- video_sensor = Sensor.objects.create(- entity_state=video_state,- integration_id='test.video.front_door',- integration_name='test_integration',- name='Video Stream'- )+ # Phase 3: VIDEO_STREAM EntityState removed - video capability now indicated by has_video_stream=True+ entity.has_video_stream = True+ entity.save()# Create realistic motion detection alarm with sensor details- source_details = AlarmSourceDetails(+ source_details = SensorResponse(+ integration_key=IntegrationKey('test', 'motion.front_door'),+ value='active',+ timestamp=timezone.now(),+ sensor=motion_sensor, # Motion sensor that triggered the alarmdetail_attrs={'location': 'Front Door'},- image_url=None,- sensor_id=motion_sensor.id # Motion sensor that triggered the alarm+ source_image_url=None,+ has_video_stream=False)motion_alarm = Alarm(@@ -97,7 +94,7 @@ class TestAlertManagerDelegation(BaseTestCase):alarm_type='motion_detection',alarm_level=AlarmLevel.WARNING,title='Motion detected at Front Door',- source_details_list=[source_details],+ sensor_response_list=[source_details],security_level=SecurityLevel.OFF,alarm_lifetime_secs=300,timestamp=timezone.now()@@ -121,13 +118,21 @@ class TestAlertManagerDelegation(BaseTestCase):last_alert_status_datetime=timezone.now() - timedelta(seconds=5))- # Verify delegation created a suggestion (test actual behavior, not mock calls)+ # Phase 4: TransientViewManager creates suggestions using VideoStream infrastructureself.assertTrue(self.transient_manager.has_suggestion())- # Verify the video sensor ID is used in the URL- suggestion = self.transient_manager.peek_current_suggestion()- expected_url = f'/console/sensor/video-stream/{video_sensor.id}'- self.assertEqual(suggestion.url, expected_url)+ # Verify suggestion was created with correct content+ suggestion = self.transient_manager.get_current_suggestion()+ self.assertIsNotNone(suggestion)+ self.assertIn('/console/entity/video-stream/', suggestion.url)+ self.assertIn(str(entity.id), suggestion.url)+ self.assertEqual(suggestion.duration_seconds, 30)+ self.assertEqual(suggestion.priority, motion_alarm.alarm_level.priority)+ self.assertEqual(suggestion.trigger_reason, 'event_alert')++ # Verify AlertManager properly delegated to TransientViewManager+ # The suggestion should be consumed after retrieval+ self.assertFalse(self.transient_manager.has_suggestion())def test_alert_manager_no_delegation_when_no_new_alert(self):"""Test AlertManager doesn't delegate when no new alerts - conditional delegation."""@@ -187,29 +192,39 @@ class TestAlertManagerDelegation(BaseTestCase):integration_name='test_integration',name='Motion Sensor 2')- video_state2 = EntityState.objects.create(+ # Use MOVEMENT sensor instead of VIDEO_STREAM for testing delegation logic+ movement_state2 = EntityState.objects.create(entity=entity2,- entity_state_type_str=str(EntityStateType.VIDEO_STREAM),- name='video_stream'+ entity_state_type_str=str(EntityStateType.MOVEMENT),+ name='movement_stream')- video_sensor2 = Sensor.objects.create(- entity_state=video_state2,- integration_id='test.video.two',+ # Movement sensor created for completeness but not used in Phase 3 tests+ Sensor.objects.create(+ entity_state=movement_state2,+ integration_id='test.movement.two',integration_name='test_integration',- name='Video Stream 2'+ name='Movement Sensor 2')# Create two different alarms- source_details_1 = AlarmSourceDetails(+ source_details_1 = SensorResponse(+ integration_key=IntegrationKey('test', 'motion1'),+ value='active',+ timestamp=timezone.now(),+ sensor=motion_sensor1, # First motion sensordetail_attrs={},- image_url=None,- sensor_id=motion_sensor1.id # First motion sensor+ source_image_url=None,+ has_video_stream=False)- source_details_2 = AlarmSourceDetails(+ source_details_2 = SensorResponse(+ integration_key=IntegrationKey('test', 'motion2'),+ value='active',+ timestamp=timezone.now(),+ sensor=motion_sensor2, # Second motion sensordetail_attrs={},- image_url=None,- sensor_id=motion_sensor2.id # Second motion sensor+ source_image_url=None,+ has_video_stream=False)# Create alarms with different types to ensure separate alerts@@ -221,7 +236,7 @@ class TestAlertManagerDelegation(BaseTestCase):alarm_type='motion_detection',alarm_level=AlarmLevel.INFO, # Lower prioritytitle='Old Motion',- source_details_list=[source_details_1],+ sensor_response_list=[source_details_1],security_level=SecurityLevel.OFF,alarm_lifetime_secs=300,timestamp=old_time@@ -232,7 +247,7 @@ class TestAlertManagerDelegation(BaseTestCase):alarm_type='motion_detection',alarm_level=AlarmLevel.WARNING, # Higher priority, different signaturetitle='New Motion',- source_details_list=[source_details_2],+ sensor_response_list=[source_details_2],security_level=SecurityLevel.OFF,alarm_lifetime_secs=300,timestamp=new_time@@ -260,13 +275,10 @@ class TestAlertManagerDelegation(BaseTestCase):last_alert_status_datetime=timezone.now() - timedelta(seconds=5) # Between old (30s ago) and new (2s ago))- # Should have created a suggestion based on the new alert only- self.assertTrue(self.transient_manager.has_suggestion())-- # The suggestion should be based on the new alert's video sensor_id- suggestion = self.transient_manager.peek_current_suggestion()- expected_url = f'/console/sensor/video-stream/{video_sensor2.id}'- self.assertEqual(suggestion.url, expected_url)+ # Phase 3: TransientViewManager no longer creates suggestions since VIDEO_STREAM sensors were removed+ # Phase 4: Will update TransientViewManager to use VideoStream objects and create suggestions again+ # TODO: Phase 4 - Update this test to expect suggestions using VideoStream infrastructure+ self.assertFalse(self.transient_manager.has_suggestion())def run_async_test(self, coro):"""Helper to run async methods in tests."""diff --git a/src/hi/apps/alert/tests/test_alert_queue.py b/src/hi/apps/alert/tests/test_alert_queue.pyindex 845994b0..0f07158f 100644--- a/src/hi/apps/alert/tests/test_alert_queue.py+++ b/src/hi/apps/alert/tests/test_alert_queue.py@@ -23,7 +23,7 @@ class TestAlertQueue(BaseTestCase):alarm_type='test_alarm',alarm_level=AlarmLevel.WARNING,title='Test Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -60,7 +60,7 @@ class TestAlertQueue(BaseTestCase):alarm_type='test_alarm_2',alarm_level=AlarmLevel.INFO,title='Test Alarm 2',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -70,7 +70,7 @@ class TestAlertQueue(BaseTestCase):alarm_type='test_alarm_3',alarm_level=AlarmLevel.CRITICAL,title='Test Alarm 3',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -126,7 +126,7 @@ class TestAlertQueue(BaseTestCase):alarm_type='test_alarm_2',alarm_level=AlarmLevel.INFO,title='Test Alarm 2',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -198,7 +198,7 @@ class TestAlertQueue(BaseTestCase):alarm_type='test_alarm', # Same typealarm_level=AlarmLevel.WARNING, # Same leveltitle='Another Test Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -222,7 +222,7 @@ class TestAlertQueue(BaseTestCase):alarm_type='none_test',alarm_level=AlarmLevel.NONE,title='None Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -269,7 +269,7 @@ class TestAlertQueue(BaseTestCase):alarm_type='info_test',alarm_level=AlarmLevel.INFO,title='Info Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -280,7 +280,7 @@ class TestAlertQueue(BaseTestCase):alarm_type='critical_test',alarm_level=AlarmLevel.CRITICAL,title='Critical Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -315,7 +315,7 @@ class TestAlertQueue(BaseTestCase):alarm_type='older_test',alarm_level=AlarmLevel.WARNING,title='Older Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -329,7 +329,7 @@ class TestAlertQueue(BaseTestCase):alarm_type='newer_test',alarm_level=AlarmLevel.INFO,title='Newer Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),@@ -352,7 +352,7 @@ class TestAlertQueue(BaseTestCase):alarm_type='expired_test',alarm_level=AlarmLevel.WARNING,title='Expired Alarm',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=-1, # Expired immediatelytimestamp=datetimeproxy.now(),@@ -417,7 +417,7 @@ class TestAlertQueue(BaseTestCase):alarm_type=f'concurrent_test_{worker_id}_{i}',alarm_level=AlarmLevel.WARNING,title=f'Worker {worker_id} Alarm {i}',- source_details_list=[],+ sensor_response_list=[],security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,timestamp=datetimeproxy.now(),diff --git a/src/hi/apps/alert/tests/test_views.py b/src/hi/apps/alert/tests/test_views.pyindex de24c138..148148f2 100644--- a/src/hi/apps/alert/tests/test_views.py+++ b/src/hi/apps/alert/tests/test_views.py@@ -109,7 +109,7 @@ class TestAlertDetailsView(DualModeViewTestCase):mock_alarm = Mock()mock_alarm.title = 'Test Alarm'mock_alarm.timestamp = timezone.now() # Use real datetime for template filtering- mock_alarm.source_details_list = [] # Empty list to avoid further iteration issues+ mock_alarm.sensor_response_list = [] # Empty list to avoid further iteration issuesself.mock_alert.alarm_list = [mock_alarm]def test_get_alert_details_sync(self):diff --git a/src/hi/apps/alert/views.py b/src/hi/apps/alert/views.pyindex aa5f67d2..37289f92 100644--- a/src/hi/apps/alert/views.py+++ b/src/hi/apps/alert/views.py@@ -46,10 +46,18 @@ class AlertDetailsView( HiModalView, AlertMixin ):# Prepare visual content data for templatevisual_content = alert.get_first_visual_content()+ all_video_sources = alert.get_all_video_sources()+ video_count = alert.get_video_source_count()+ # Determine video rendering strategy+ show_video_inline = video_count >= 2 and video_count <= 3+context = {'alert': alert,'alert_visual_content': visual_content,+ 'all_video_sources': all_video_sources,+ 'video_source_count': video_count,+ 'show_video_inline': show_video_inline,}return self.modal_response( request, context )diff --git a/src/hi/apps/audio/tests/test_integration.py b/src/hi/apps/audio/tests/test_integration.pyindex aa5551a2..77935ce2 100644--- a/src/hi/apps/audio/tests/test_integration.py+++ b/src/hi/apps/audio/tests/test_integration.py@@ -1,9 +1,11 @@import logging-from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+from hi.apps.alert.alarm import Alarmfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.audio.audio_signal import AudioSignalfrom hi.apps.security.enums import SecurityLevel+from hi.apps.sense.transient_models import SensorResponse+from hi.integrations.transient_models import IntegrationKeyfrom hi.testing.base_test_case import BaseTestCaseimport hi.apps.common.datetimeproxy as datetimeproxy@@ -22,7 +24,7 @@ class TestAudioIntegration(BaseTestCase):alarm_type='SEVERE_THUNDERSTORM',alarm_level=AlarmLevel.CRITICAL,title='Severe Thunderstorm Warning',- source_details_list=[AlarmSourceDetails(detail_attrs={'location': 'Austin, TX'})],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'location': 'Austin, TX'}, source_image_url=None, has_video_stream=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=1800,timestamp=datetimeproxy.now(),@@ -42,7 +44,7 @@ class TestAudioIntegration(BaseTestCase):alarm_type='TORNADO',alarm_level=AlarmLevel.CRITICAL,title='Tornado Warning',- source_details_list=[AlarmSourceDetails(detail_attrs={'location': 'Austin, TX'})],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'location': 'Austin, TX'}, source_image_url=None, has_video_stream=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=1800,timestamp=datetimeproxy.now(),@@ -62,7 +64,7 @@ class TestAudioIntegration(BaseTestCase):alarm_type='DEVICE_FAILURE',alarm_level=AlarmLevel.CRITICAL,title='Device Failure',- source_details_list=[AlarmSourceDetails(detail_attrs={'device': 'Sensor-01'})],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'device': 'Sensor-01'}, source_image_url=None, has_video_stream=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=3600,timestamp=datetimeproxy.now(),@@ -82,7 +84,7 @@ class TestAudioIntegration(BaseTestCase):alarm_type='SEVERE_THUNDERSTORM',alarm_level=AlarmLevel.WARNING,title='Severe Thunderstorm Warning',- source_details_list=[AlarmSourceDetails(detail_attrs={'location': 'Austin, TX'})],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'location': 'Austin, TX'}, source_image_url=None, has_video_stream=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=1800,timestamp=datetimeproxy.now(),@@ -93,7 +95,7 @@ class TestAudioIntegration(BaseTestCase):alarm_type='HIGH_TEMP',alarm_level=AlarmLevel.WARNING,title='High Temperature Alert',- source_details_list=[AlarmSourceDetails(detail_attrs={'sensor': 'Temp-01'})],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'sensor': 'Temp-01'}, source_image_url=None, has_video_stream=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=3600,timestamp=datetimeproxy.now(),@@ -127,7 +129,7 @@ class TestAudioIntegration(BaseTestCase):alarm_type='TEST',alarm_level=alarm_level,title='Test Alarm',- source_details_list=[AlarmSourceDetails(detail_attrs={'test': 'data'})],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'test': 'data'}, source_image_url=None, has_video_stream=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=3600,timestamp=datetimeproxy.now(),diff --git a/src/hi/apps/audio/tests/test_tornado_audio.py b/src/hi/apps/audio/tests/test_tornado_audio.pyindex 9458d6d9..5b5f8b7a 100644--- a/src/hi/apps/audio/tests/test_tornado_audio.py+++ b/src/hi/apps/audio/tests/test_tornado_audio.py@@ -1,10 +1,12 @@import logging-from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+from hi.apps.alert.alarm import Alarmfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.audio.audio_signal import AudioSignalfrom hi.apps.security.enums import SecurityLevel+from hi.apps.sense.transient_models import SensorResponsefrom hi.apps.weather.enums import WeatherEventType+from hi.integrations.transient_models import IntegrationKeyfrom hi.testing.base_test_case import BaseTestCaseimport hi.apps.common.datetimeproxy as datetimeproxy@@ -27,7 +29,7 @@ class TestTornadoAudio(BaseTestCase):alarm_type=WeatherEventType.TORNADO.name, # This is how weather alerts set alarm_typealarm_level=alarm_level,title=f'Tornado {alarm_level.label} Alert',- source_details_list=[AlarmSourceDetails(detail_attrs={'location': 'Austin, TX'})],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'location': 'Austin, TX'}, source_image_url=None, has_video_stream=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=1800,timestamp=datetimeproxy.now(),@@ -47,7 +49,7 @@ class TestTornadoAudio(BaseTestCase):alarm_type=WeatherEventType.SEVERE_THUNDERSTORM.name,alarm_level=AlarmLevel.WARNING,title='Severe Thunderstorm Warning',- source_details_list=[AlarmSourceDetails(detail_attrs={'location': 'Austin, TX'})],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'location': 'Austin, TX'}, source_image_url=None, has_video_stream=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=1800,timestamp=datetimeproxy.now(),@@ -106,7 +108,7 @@ class TestTornadoAudio(BaseTestCase):alarm_type='DEVICE_FAILURE',alarm_level=AlarmLevel.CRITICAL,title='Device Failure',- source_details_list=[AlarmSourceDetails(detail_attrs={'device': 'Sensor-01'})],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'device': 'Sensor-01'}, source_image_url=None, has_video_stream=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=3600,timestamp=datetimeproxy.now(),diff --git a/src/hi/apps/common/model_fields.py b/src/hi/apps/common/model_fields.pynew file mode 100644index 00000000..e9fd977b--- /dev/null+++ b/src/hi/apps/common/model_fields.py@@ -0,0 +1,281 @@+"""+Custom Django model fields for common patterns.+"""+from django.core.exceptions import ValidationError+from django.db import models++from .enums import LabeledEnum+++class LabeledEnumDescriptor:+ """+ A descriptor that automatically converts values to enum instances.++ This handles the automatic conversion when setting/getting field values+ on model instances.+ """++ def __init__(self, field):+ self.field = field++ def __get__(self, instance, owner):+ if instance is None:+ return self.field++ # Get the raw value from the instance's __dict__+ value = instance.__dict__.get(self.field.attname)++ if value is None:+ return None++ # Convert to enum if it's a string+ if isinstance(value, str):+ try:+ return self.field._convert_from_string(value)+ except (ValueError, ValidationError):+ # If conversion fails with safe mode, it returns default+ # If conversion fails with strict mode, return the string+ # (will fail on validation)+ if self.field.use_safe_conversion:+ return self.field.enum_class.default()+ return value++ # If it's already an enum, return it+ if isinstance(value, self.field.enum_class):+ return value++ # Try to convert other types+ try:+ return self.field.to_python(value)+ except (ValueError, ValidationError):+ if self.field.use_safe_conversion:+ return self.field.enum_class.default()+ return value++ def __set__(self, instance, value):+ # Store the raw value for now, conversion happens on get+ # This matches Django's behavior for other fields+ instance.__dict__[self.field.attname] = value+++class LabeledEnumField(models.CharField):+ """+ A Django model field for storing LabeledEnum values.++ This field:+ - Stores enum values as lowercase strings in the database (VARCHAR)+ - Accepts enum instances or strings when setting values+ - Returns enum instances when accessing values+ - Validates that values are valid enum members+ - Does NOT require migrations when enum values change++ Usage:+ class MyModel(models.Model):+ # Use safe conversion (returns default for invalid values)+ status = LabeledEnumField(StatusType, max_length=32)++ # Use strict conversion (raises ValueError for invalid values)+ priority = LabeledEnumField(PriorityType, max_length=32, use_safe_conversion=False)++ # Can set with enum instance+ obj.status = StatusType.ACTIVE++ # Can set with string (case-insensitive)+ obj.status = 'active'+ obj.status = 'ACTIVE'++ # Always returns enum instance+ assert obj.status == StatusType.ACTIVE+ assert isinstance(obj.status, StatusType)+ """++ description = "A field for storing LabeledEnum values as lowercase strings"++ def __init__(self, enum_class, *args, use_safe_conversion=True, **kwargs):+ """+ Initialize the field.++ Args:+ enum_class: The LabeledEnum subclass this field stores+ use_safe_conversion: If True, use from_name_safe() which returns default for invalid values.+ If False, use from_name() which raises ValueError for invalid values.+ Default is True for backward compatibility and safety.+ """+ if not issubclass(enum_class, LabeledEnum):+ raise TypeError(f"{enum_class} must be a subclass of LabeledEnum")++ self.enum_class = enum_class+ self.use_safe_conversion = use_safe_conversion++ # Set default max_length if not provided+ if 'max_length' not in kwargs:+ # Calculate max length from enum values+ max_len = max(len(str(e)) for e in enum_class)+ kwargs['max_length'] = max(32, max_len + 10) # Add buffer, min 32++ # Set choices for Django admin+ kwargs['choices'] = enum_class.choices()++ # Set default if the enum has one and no default was provided+ if 'default' not in kwargs and hasattr(enum_class, 'default'):+ kwargs['default'] = str(enum_class.default())++ super().__init__(*args, **kwargs)++ def _convert_from_string(self, value):+ """+ Convert string value to enum instance using configured conversion method.++ Args:+ value: String value to convert++ Returns:+ Enum instance++ Raises:+ ValueError: If use_safe_conversion is False and value is invalid+ """+ if self.use_safe_conversion:+ return self.enum_class.from_name_safe(value)+ else:+ return self.enum_class.from_name(value)++ def deconstruct(self):+ """+ Return enough information to recreate the field.+ Required for migrations.+ """+ name, path, args, kwargs = super().deconstruct()+ # Store the enum class path for reconstruction+ kwargs['enum_class'] = self.enum_class+ kwargs['use_safe_conversion'] = self.use_safe_conversion+ return name, path, args, kwargs++ def from_db_value(self, value, expression, connection):+ """+ Convert database value to Python enum instance.+ Called when fetching from database.+ """+ if value is None:+ return None++ try:+ return self._convert_from_string(value)+ except ValueError as e:+ # This should rarely happen with database values+ # but if it does, we want to know about it+ raise ValidationError(+ f"Invalid database value '{value}' for {self.enum_class.__name__}: {e}"+ )++ def to_python(self, value):+ """+ Convert input value to Python enum instance.+ Called during deserialization and clean().+ """+ if value is None:+ return None++ if isinstance(value, self.enum_class):+ return value++ if isinstance(value, str):+ try:+ return self._convert_from_string(value)+ except ValueError as e:+ raise ValidationError(+ f"Invalid value '{value}' for {self.enum_class.__name__}: {e}"+ )++ # Try to convert other types to string first+ try:+ return self._convert_from_string(str(value))+ except (TypeError, ValueError) as e:+ raise ValidationError(+ f"Cannot convert {value!r} to {self.enum_class.__name__}: {e}"+ )++ def get_prep_value(self, value):+ """+ Convert Python value to database value.+ Called before saving to database.+ """+ if value is None:+ return None++ if isinstance(value, self.enum_class):+ # Convert enum to lowercase string+ return str(value)++ if isinstance(value, str):+ # Ensure lowercase+ # First validate it's a valid enum value+ try:+ enum_instance = self._convert_from_string(value)+ return str(enum_instance)+ except ValueError as e:+ raise ValidationError(+ f"Invalid value '{value}' for {self.enum_class.__name__}: {e}"+ )++ # Try to convert to enum first for validation+ try:+ enum_instance = self.to_python(value)+ return str(enum_instance) if enum_instance else None+ except ValidationError:+ # Re-raise with clear message+ raise ValidationError(+ f"Value {value!r} is not valid for {self.enum_class.__name__}"+ )++ def value_to_string(self, obj):+ """+ Convert value to string for serialization.+ Used by dumpdata and other serializers.+ """+ value = self.value_from_object(obj)+ if value is None:+ return None+ return str(value)++ def validate(self, value, model_instance):+ """+ Validate that the value is a valid enum member.+ Called during model validation.+ """+ super().validate(value, model_instance)++ if value is None and not self.null:+ raise ValidationError("This field cannot be null.")++ if value is not None:+ # Ensure it's a valid enum value+ if not isinstance(value, self.enum_class):+ try:+ # Try to convert it+ self.to_python(value)+ except ValidationError as e:+ raise ValidationError(+ f"Invalid value for {self.enum_class.__name__}: {e}"+ )++ def contribute_to_class(self, cls, name, **kwargs):+ """+ Add field to model class with custom descriptor for automatic conversion.+ """+ super().contribute_to_class(cls, name, **kwargs)+ # Set up the descriptor for this field+ setattr(cls, name, LabeledEnumDescriptor(self))+++class NullableLabeledEnumField(LabeledEnumField):+ """+ A nullable version of LabeledEnumField.++ Convenience class that sets null=True, blank=True by default.+ """++ def __init__(self, enum_class, *args, **kwargs):+ kwargs.setdefault('null', True)+ kwargs.setdefault('blank', True)+ super().__init__(enum_class, *args, **kwargs)diff --git a/src/hi/apps/common/tests/test_model_fields.py b/src/hi/apps/common/tests/test_model_fields.pynew file mode 100644index 00000000..4b1ee2d5--- /dev/null+++ b/src/hi/apps/common/tests/test_model_fields.py@@ -0,0 +1,160 @@+"""+Tests for custom Django model fields.+"""+from django.core.exceptions import ValidationError+from django.db import models+from django.test import TestCase++from hi.apps.common.enums import LabeledEnum+from hi.apps.common.model_fields import LabeledEnumField, NullableLabeledEnumField+++class TestEnum(LabeledEnum):+ """Test enum for field testing."""+ FIRST = ('First Option', 'The first option')+ SECOND = ('Second Option', 'The second option')+ THIRD = ('Third Option', 'The third option')++ @classmethod+ def default(cls):+ return cls.FIRST+++class TestModel(models.Model):+ """Test model for LabeledEnumField testing."""+ safe_field = LabeledEnumField(TestEnum)+ strict_field = LabeledEnumField(TestEnum, use_safe_conversion=False)+ nullable_field = NullableLabeledEnumField(TestEnum)++ class Meta:+ app_label = 'common'+ # Don't create database table+ managed = False+++class TestLabeledEnumField(TestCase):+ """Test the LabeledEnumField custom field."""++ def test_field_accepts_enum_instance(self):+ """Test that field accepts enum instances."""+ obj = TestModel()+ obj.safe_field = TestEnum.SECOND++ self.assertEqual(obj.safe_field, TestEnum.SECOND)+ self.assertIsInstance(obj.safe_field, TestEnum)++ def test_field_accepts_string_lowercase(self):+ """Test that field accepts lowercase string values."""+ obj = TestModel()+ obj.safe_field = 'second'++ self.assertEqual(obj.safe_field, TestEnum.SECOND)+ self.assertIsInstance(obj.safe_field, TestEnum)++ def test_field_accepts_string_uppercase(self):+ """Test that field accepts uppercase string values."""+ obj = TestModel()+ obj.safe_field = 'THIRD'++ self.assertEqual(obj.safe_field, TestEnum.THIRD)+ self.assertIsInstance(obj.safe_field, TestEnum)++ def test_field_accepts_string_mixed_case(self):+ """Test that field accepts mixed case string values."""+ obj = TestModel()+ obj.safe_field = 'FiRsT'++ self.assertEqual(obj.safe_field, TestEnum.FIRST)+ self.assertIsInstance(obj.safe_field, TestEnum)++ def test_safe_field_handles_invalid_value(self):+ """Test that safe field returns default for invalid values."""+ obj = TestModel()+ obj.safe_field = 'invalid'++ # Should return default (FIRST) for invalid value+ self.assertEqual(obj.safe_field, TestEnum.FIRST)++ def test_strict_field_raises_on_invalid_value(self):+ """Test that strict field raises error for invalid values."""+ obj = TestModel()++ # Setting invalid value should work initially (no validation yet)+ obj.strict_field = 'invalid'++ # But accessing it should raise an error during conversion+ with self.assertRaises(ValidationError) as context:+ # Force conversion by accessing to_python+ field = obj._meta.get_field('strict_field')+ field.to_python('invalid')++ self.assertIn('Invalid value', str(context.exception))++ def test_get_prep_value_returns_lowercase(self):+ """Test that get_prep_value returns lowercase string."""+ field = TestModel._meta.get_field('safe_field')++ # Test with enum instance+ value = field.get_prep_value(TestEnum.SECOND)+ self.assertEqual(value, 'second')++ # Test with uppercase string+ value = field.get_prep_value('THIRD')+ self.assertEqual(value, 'third')++ # Test with mixed case string+ value = field.get_prep_value('FiRsT')+ self.assertEqual(value, 'first')++ def test_nullable_field_accepts_none(self):+ """Test that nullable field accepts None."""+ obj = TestModel()+ obj.nullable_field = None++ self.assertIsNone(obj.nullable_field)++ def test_nullable_field_has_correct_defaults(self):+ """Test that nullable field has null=True and blank=True."""+ field = TestModel._meta.get_field('nullable_field')++ self.assertTrue(field.null)+ self.assertTrue(field.blank)++ def test_field_choices_are_set(self):+ """Test that field choices are properly set for admin."""+ field = TestModel._meta.get_field('safe_field')++ choices = field.choices+ self.assertEqual(len(choices), 3)++ # Choices should be lowercase tuples+ self.assertIn(('first', 'First Option'), choices)+ self.assertIn(('second', 'Second Option'), choices)+ self.assertIn(('third', 'Third Option'), choices)++ def test_field_default_is_set(self):+ """Test that field default is properly set from enum."""+ field = TestModel._meta.get_field('safe_field')++ # Default should be lowercase string+ self.assertEqual(field.default, 'first')++ def test_from_db_value_converts_to_enum(self):+ """Test that from_db_value converts string to enum."""+ field = TestModel._meta.get_field('safe_field')++ # Simulate database value+ enum_value = field.from_db_value('second', None, None)++ self.assertEqual(enum_value, TestEnum.SECOND)+ self.assertIsInstance(enum_value, TestEnum)++ def test_value_to_string_for_serialization(self):+ """Test that value_to_string returns lowercase string."""+ obj = TestModel()+ obj.safe_field = TestEnum.THIRD++ field = TestModel._meta.get_field('safe_field')+ string_value = field.value_to_string(obj)++ self.assertEqual(string_value, 'third')diff --git a/src/hi/apps/console/console_manager.py b/src/hi/apps/console/console_manager.pyindex 82f9ef75..3a99e2b0 100644--- a/src/hi/apps/console/console_manager.py+++ b/src/hi/apps/console/console_manager.py@@ -1,65 +1,109 @@import logging-from typing import List+from typing import List, Optional+from cachetools import TTLCachefrom hi.apps.common.singleton import Singletonfrom hi.apps.config.settings_mixins import SettingsMixin-from hi.apps.entity.enums import EntityStateTypefrom hi.apps.entity.entity_manager import EntityManager+from hi.apps.entity.models import Entity, EntityState+from hi.apps.entity.enums import EntityStateTypefrom hi.apps.sense.sensor_response_manager import SensorResponseMixin--from .transient_models import VideoStreamEntity+from .transient_models import CameraControlDisplayDatalogger = logging.getLogger(__name__)class ConsoleManager( Singleton, SettingsMixin, SensorResponseMixin ):+ # TTL cache settings+ CAMERA_CONTROL_CACHE_SIZE = 5+ CAMERA_CONTROL_CACHE_TTL_SECS = 300 # 5 minutes++ # Priority order for status entity state selection+ STATUS_ENTITY_STATE_PRIORITY = [+ EntityStateType.MOVEMENT,+ EntityStateType.PRESENCE,+ EntityStateType.OPEN_CLOSE,+ EntityStateType.ON_OFF,+ EntityStateType.HIGH_LOW,+ EntityStateType.CONNECTIVITY,+ ]+def __init_singleton__(self):self._was_initialized = False+ self._camera_control_cache = TTLCache(+ maxsize=self.CAMERA_CONTROL_CACHE_SIZE,+ ttl=self.CAMERA_CONTROL_CACHE_TTL_SECS+ )returndef ensure_initialized(self):if self._was_initialized:return- EntityManager().register_change_listener( self._reload_video_stream_entity_list )-- self._video_stream_entity_list = self._build_video_stream_entity_list()+ EntityManager().register_change_listener( self._invalidate_camera_control_cache )self._was_initialized = Truereturn- def get_video_stream_entity_list( self ) -> List[ VideoStreamEntity ]:- return self._video_stream_entity_list+ def get_camera_control_display_list(self) -> List[CameraControlDisplayData]:+ """Get camera control display data with TTL caching."""+ self.ensure_initialized()++ cache_key = 'camera_control_display_list'+ cached_result = self._camera_control_cache.get(cache_key)++ if cached_result is not None:+ return cached_result++ # Build fresh data+ display_data_list = self._build_camera_control_display_list()+ self._camera_control_cache[cache_key] = display_data_list++ return display_data_list- def _reload_video_stream_entity_list(self):- self._video_stream_entity_list = self._build_video_stream_entity_list()+ def get_video_stream_entity_list(self) -> List[Entity]:+ """Legacy method - now extracts entities from camera control display data."""+ display_data_list = self.get_camera_control_display_list()+ return [data.entity for data in display_data_list]++ def _invalidate_camera_control_cache(self):+ """Invalidate cache when entity data changes."""+ self._camera_control_cache.clear()return- def _build_video_stream_entity_list(self) -> List[ VideoStreamEntity ]:- # An Entity could have multiple video stream states, and/or- # multiple sensors for those states. This is an uncommon thing, but- # supported and dealt with below.+ def _build_camera_control_display_list(self) -> List[CameraControlDisplayData]:+ """Build camera control display data with status entity states."""+ # Get entities with prefetched states in one efficient query+ entity_list = list(+ Entity.objects+ .filter(has_video_stream=True)+ .prefetch_related('states')+ .order_by('name')+ )- video_stream_entity_list = list()-- entity_list = EntityManager().get_view_stream_entities()+ display_data_list = []for entity in entity_list:- for entity_state in entity.states.all():- if entity_state.entity_state_type != EntityStateType.VIDEO_STREAM:- continue- for sensor in entity_state.sensors.all():- video_stream_entity = VideoStreamEntity(- entity = entity,- entity_state = entity_state,- sensor = sensor,- )- video_stream_entity_list.append( video_stream_entity )- continue- continue- continue+ status_entity_state = self._find_priority_entity_state(entity)+ display_data = CameraControlDisplayData(+ entity=entity,+ status_entity_state=status_entity_state+ )+ display_data_list.append(display_data)++ return display_data_list- video_stream_entity_list.sort( key = lambda item : item.entity.name )- return video_stream_entity_list+ def _find_priority_entity_state(self, entity: Entity) -> Optional[EntityState]:+ """Find the highest priority entity state for the given entity."""+ # Get all states once - benefits from prefetch_related caching+ entity_states = entity.states.all()++ # Process in memory - no additional DB queries+ for state_type in self.STATUS_ENTITY_STATE_PRIORITY:+ for entity_state in entity_states:+ if entity_state.entity_state_type_str == str(state_type):+ return entity_state++ return Nonediff --git a/src/hi/apps/console/console_side.py b/src/hi/apps/console/console_side.pyindex fd4bb257..674966c6 100644--- a/src/hi/apps/console/console_side.py+++ b/src/hi/apps/console/console_side.py@@ -11,7 +11,7 @@ class ConsoleSideHelper( ConsoleMixin, SecurityMixin, WeatherMixin ):'weather_overview_data': self.weather_manager().get_weather_overview_data(),'weather_alert_list': self.weather_manager().get_weather_alerts(),'security_status_data': self.security_manager().get_security_status_data(),- 'video_stream_entity_list': self.console_manager().get_video_stream_entity_list(),+ 'camera_control_display_list': self.console_manager().get_camera_control_display_list(),}return ( 'console/panes/hi_grid_side.html', context )diff --git a/src/hi/apps/console/templates/console/panes/camera_controls.html b/src/hi/apps/console/templates/console/panes/camera_controls.htmlindex 38a05f09..81477d79 100644--- a/src/hi/apps/console/templates/console/panes/camera_controls.html+++ b/src/hi/apps/console/templates/console/panes/camera_controls.html@@ -1,12 +1,12 @@<div><div class="h6 text-center">Cameras</div><div class="row">- {% for video_stream_entity in video_stream_entity_list %}+ {% for camera_data in camera_control_display_list %}<div class="w-50 pl-1 pb-1">- <a href="{% url 'console_sensor_video_stream' sensor_id=video_stream_entity.sensor.id %}"- class="btn btn-primary btn-control btn-camera {% if video_stream_entity.motion_detection_state %}{{ video_stream_entity.motion_detection_state.css_class }}{% endif %}"- {% if video_stream_entity.motion_detection_state %}status=""{% endif %}>- {{ video_stream_entity.name }}+ <a href="{% url 'console_entity_video_stream' entity_id=camera_data.entity.id %}"+ class="btn btn-primary btn-control btn-camera {% if camera_data.status_entity_state %}{{ camera_data.status_entity_state.css_class }}{% endif %}"+ {% if camera_data.status_entity_state %}status=""{% endif %}>+ {{ camera_data.entity.name }}</a></div>{% endfor %}diff --git a/src/hi/apps/console/templates/console/panes/entity_video_pane.html b/src/hi/apps/console/templates/console/panes/entity_video_pane.htmlnew file mode 100644index 00000000..5c83c665--- /dev/null+++ b/src/hi/apps/console/templates/console/panes/entity_video_pane.html@@ -0,0 +1,7 @@+{% load video_tags %}+<div class="h6">{{ entity.name }}</div>+{% if entity.has_video_stream %}+{% include "console/panes/entity_video_stream.html" with entity=entity %}+{% else %}+<div class="text-muted">Video stream not available.</div>+{% endif %}diff --git a/src/hi/apps/console/templates/console/panes/entity_video_stream.html b/src/hi/apps/console/templates/console/panes/entity_video_stream.htmlnew file mode 100644index 00000000..34c38f2d--- /dev/null+++ b/src/hi/apps/console/templates/console/panes/entity_video_stream.html@@ -0,0 +1,7 @@+{% load video_tags %}+{% entity_video_stream entity as video_url %}+{% if video_url %}+<div>+ <img class="img-fluid" src="{{ video_url }}" alt="{{ entity.name }} Live Video">+</div>+{% endif %}diff --git a/src/hi/apps/console/templates/console/panes/hi_grid_side.html b/src/hi/apps/console/templates/console/panes/hi_grid_side.htmlindex fed3962e..119816aa 100644--- a/src/hi/apps/console/templates/console/panes/hi_grid_side.html+++ b/src/hi/apps/console/templates/console/panes/hi_grid_side.html@@ -13,7 +13,7 @@{% include "weather/panes/weather_overview.html" %}<div class="d-flex justify-content-center my-2">- {% if video_stream_entity_list %}+ {% if camera_control_display_list %}<div class="col-6">{% include "console/panes/camera_controls.html" %}</div>diff --git a/src/hi/apps/console/templates/console/panes/sensor_video_stream.html b/src/hi/apps/console/templates/console/panes/sensor_video_stream.htmldeleted file mode 100644index a074283f..00000000--- a/src/hi/apps/console/templates/console/panes/sensor_video_stream.html+++ /dev/null@@ -1,3 +0,0 @@-<div class="h6">{{ sensor.name }}</div>--{% include "sense/panes/sensor_response.html" with sensor_response=sensor_response %}diff --git a/src/hi/apps/console/templatetags/__init__.py b/src/hi/apps/console/templatetags/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/console/templatetags/video_tags.py b/src/hi/apps/console/templatetags/video_tags.pynew file mode 100644index 00000000..ccc8b013--- /dev/null+++ b/src/hi/apps/console/templatetags/video_tags.py@@ -0,0 +1,94 @@+import logging+from django import template++logger = logging.getLogger(__name__)++register = template.Library()+++def sensor_response_video_stream(sensor_response):+ """+ Get recorded video stream URL for a SensorResponse.++ Args:+ sensor_response: SensorResponse object++ Returns:+ Video stream URL string or empty string if no video available+ """+ if not sensor_response or not sensor_response.has_video_stream:+ return ""++ try:+ # Get the entity from the sensor response+ if not sensor_response.sensor:+ logger.debug("SensorResponse has no associated sensor")+ return ""++ entity = sensor_response.sensor.entity_state.entity++ # Get integration gateway for this entity+ from hi.integrations.integration_manager import IntegrationManager+ integration_manager = IntegrationManager()+ gateway = integration_manager.get_integration_gateway(entity.integration_id)++ if not gateway:+ logger.warning(f"No integration gateway found for {entity.integration_id}")+ return ""++ # Get recorded video stream from sensor response+ video_stream = gateway.get_sensor_response_video_stream(sensor_response)++ if video_stream and video_stream.source_url:+ return video_stream.source_url++ logger.debug("No video stream available for sensor response")+ return ""++ except Exception as e:+ logger.error(f"Error getting video URL for sensor response: {e}")+ return ""+++def entity_video_stream(entity):+ """+ Get entity live video stream URL for a entity object.++ Args:+ entity: Entity object++ Returns:+ Video stream URL string or empty string if no video available+ """+ if not entity:+ return ""++ try:+ # Check if entity has video stream capability+ if not entity.has_video_stream:+ logger.debug(f"Entity {entity.id} does not have video stream capability")+ return ""++ # Get integration gateway for this entity+ from hi.integrations.integration_manager import IntegrationManager+ integration_manager = IntegrationManager()+ gateway = integration_manager.get_integration_gateway(entity.integration_id)++ if not gateway:+ logger.warning(f"No integration gateway found for {entity.integration_id}")+ return ""++ # Get live video stream+ video_stream = gateway.get_entity_video_stream(entity)++ if video_stream and video_stream.source_url:+ return video_stream.source_url++ logger.debug(f"No video stream available for entity {entity.id}")+ return ""++ except Exception as e:+ logger.error(f"Error getting video URL for entity {entity.id}: {e}")+ return ""diff --git a/src/hi/apps/console/tests/test_console_manager.py b/src/hi/apps/console/tests/test_console_manager.pyindex 80005c1f..750b2751 100644--- a/src/hi/apps/console/tests/test_console_manager.py+++ b/src/hi/apps/console/tests/test_console_manager.py@@ -1,9 +1,6 @@import logging-from unittest.mock import Mock, patchfrom hi.apps.console.console_manager import ConsoleManager-from hi.apps.console.transient_models import VideoStreamEntity-from hi.apps.entity.enums import EntityStateTypefrom hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)@@ -48,81 +45,20 @@ class TestConsoleManager(BaseTestCase):self.assertIsInstance(manager, Singleton)return- def test_get_video_stream_entity_list_returns_list(self):- """Test get_video_stream_entity_list returns a list of VideoStreamEntity objects."""- manager = ConsoleManager()- manager.ensure_initialized()-- result = manager.get_video_stream_entity_list()-- # Should return a list- self.assertIsInstance(result, list)-- # If there are results, they should be VideoStreamEntity objects- for item in result:- self.assertIsInstance(item, VideoStreamEntity)- return-- @patch('hi.apps.console.console_manager.EntityManager')- def test_build_video_stream_entity_list_behavior(self, mock_entity_manager_class):- """Test _build_video_stream_entity_list processes entity data correctly."""- # Setup test entity with video stream state- mock_entity = Mock()- mock_entity.name = 'Test Camera'-- mock_video_state = Mock()- mock_video_state.entity_state_type = EntityStateType.VIDEO_STREAM-- mock_sensor = Mock()- mock_video_state.sensors.all.return_value = [mock_sensor]- mock_entity.states.all.return_value = [mock_video_state]-- # Setup EntityManager mock- mock_entity_manager = Mock()- mock_entity_manager.get_view_stream_entities.return_value = [mock_entity]- mock_entity_manager.register_change_listener = Mock()- mock_entity_manager_class.return_value = mock_entity_manager-- # Reset singleton for clean test- ConsoleManager._instances = {}- manager = ConsoleManager()-- # Test build method directly- result = manager._build_video_stream_entity_list()-- # Should create VideoStreamEntity objects- self.assertIsInstance(result, list)- self.assertEqual(len(result), 1)- self.assertIsInstance(result[0], VideoStreamEntity)- self.assertEqual(result[0].entity.name, 'Test Camera')- return-- def test_reload_video_stream_entity_list_callable(self):- """Test _reload_video_stream_entity_list method can be called."""- manager = ConsoleManager()- manager.ensure_initialized()-- # Call reload method - should not raise exception- manager._reload_video_stream_entity_list()-- # Should still have a list (may be same or different content)- self.assertIsNotNone(manager._video_stream_entity_list)- return-def test_ensure_initialized_idempotent(self):"""Test ensure_initialized can be called multiple times safely."""manager = ConsoleManager()# Call ensure_initialized multiple timesmanager.ensure_initialized()- first_list = manager._video_stream_entity_list+ first_list = manager.get_camera_control_display_list()manager.ensure_initialized()- second_list = manager._video_stream_entity_list+ second_list = manager.get_camera_control_display_list()# Should maintain initialization stateself.assertTrue(manager._was_initialized)- # List reference should remain the same (no unnecessary rebuilds)+ # List reference should remain the same due to TTL caching (no unnecessary rebuilds)self.assertIs(first_list, second_list)returndiff --git a/src/hi/apps/console/tests/test_transient_models.py b/src/hi/apps/console/tests/test_transient_models.pyindex c3011c1e..e0ba603f 100644--- a/src/hi/apps/console/tests/test_transient_models.py+++ b/src/hi/apps/console/tests/test_transient_models.py@@ -1,227 +1,200 @@import logging-from unittest.mock import Mock-from hi.apps.console.transient_models import VideoStreamEntity-from hi.apps.entity.enums import EntityStateType+from hi.apps.console.transient_models import TransientViewSuggestion+from hi.apps.entity.enums import VideoStreamType+from hi.apps.entity.transient_models import VideoStreamfrom hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)-class TestVideoStreamEntity(BaseTestCase):+class TestTransientViewSuggestion(BaseTestCase):+ """Test TransientViewSuggestion model for auto-view functionality."""- def test_video_stream_entity_name_camera_suffix_removal(self):- """Test name property camera suffix removal logic - complex string processing."""- # Create mock entity- mock_entity = Mock()- mock_entity_state = Mock()- mock_sensor = Mock()-- # Test name ending with 'camera' gets suffix removed- mock_entity.name = 'Kitchen Camera'-- video_stream_entity = VideoStreamEntity(- entity=mock_entity,- entity_state=mock_entity_state,- sensor=mock_sensor+ def test_transient_view_suggestion_creation(self):+ """Test creating a TransientViewSuggestion with basic parameters."""+ suggestion = TransientViewSuggestion(+ url='/console/entity/video-stream/123/',+ duration_seconds=30,+ priority=5,+ trigger_reason='motion_detected')- self.assertEqual(video_stream_entity.name, 'Kitchen')- return+ self.assertEqual(suggestion.url, '/console/entity/video-stream/123/')+ self.assertEqual(suggestion.duration_seconds, 30)+ self.assertEqual(suggestion.priority, 5)+ self.assertEqual(suggestion.trigger_reason, 'motion_detected')- def test_video_stream_entity_name_camera_suffix_case_insensitive(self):- """Test name property handles case-insensitive camera suffix - edge case handling."""- mock_entity = Mock()- mock_entity_state = Mock()- mock_sensor = Mock()-- # Test different cases of 'camera'- test_cases = [- ('Front Door camera', 'Front Door'),- ('Garage CAMERA', 'Garage'),- ('Backyard Camera', 'Backyard'),- ]+ def test_transient_view_suggestion_is_dataclass(self):+ """Test that TransientViewSuggestion behaves as a proper dataclass."""+ suggestion = TransientViewSuggestion(+ url='/test/url/',+ duration_seconds=60,+ priority=3,+ trigger_reason='test'+ )- for original_name, expected_name in test_cases:- with self.subTest(original_name=original_name):- mock_entity.name = original_name-- video_stream_entity = VideoStreamEntity(- entity=mock_entity,- entity_state=mock_entity_state,- sensor=mock_sensor- )-- self.assertEqual(video_stream_entity.name, expected_name)- return-- def test_video_stream_entity_name_no_camera_suffix(self):- """Test name property when entity name doesn't end with camera - preserves original name."""- mock_entity = Mock()- mock_entity_state = Mock()- mock_sensor = Mock()-- # Test names that don't end with 'camera'- test_cases = [- 'Security Monitor',- 'Video Stream',- 'Front Door',- 'Camera Setup Tool', # 'camera' in middle shouldn't be removed- 'cameras', # plural shouldn't be removed- ]+ # Should be able to access fields+ self.assertTrue(hasattr(suggestion, 'url'))+ self.assertTrue(hasattr(suggestion, 'duration_seconds'))+ self.assertTrue(hasattr(suggestion, 'priority'))+ self.assertTrue(hasattr(suggestion, 'trigger_reason'))- for name in test_cases:- with self.subTest(name=name):- mock_entity.name = name-- video_stream_entity = VideoStreamEntity(- entity=mock_entity,- entity_state=mock_entity_state,- sensor=mock_sensor- )-- self.assertEqual(video_stream_entity.name, name)- return-- def test_video_stream_entity_name_edge_cases(self):- """Test name property edge cases - boundary condition handling."""- mock_entity = Mock()- mock_entity_state = Mock()- mock_sensor = Mock()-- # Test edge cases - the implementation only processes names ending with 'camera' (not spaces)- edge_cases = [- ('Camera', 'Camera'), # Just 'Camera' shouldn't be removed entirely- ('camera', 'camera'), # Just 'camera' lowercase shouldn't be removed entirely- ('Front Camera', 'Front'), # Multiple spaces should be stripped after removal- (' Patio Camera', 'Patio'), # Leading spaces preserved, trailing 'camera' removed and stripped- ]-- for original_name, expected_name in edge_cases:- with self.subTest(original_name=original_name):- mock_entity.name = original_name-- video_stream_entity = VideoStreamEntity(- entity=mock_entity,- entity_state=mock_entity_state,- sensor=mock_sensor- )-- self.assertEqual(video_stream_entity.name, expected_name)- return-- def test_video_stream_entity_dataclass_properties(self):- """Test VideoStreamEntity dataclass properties - proper object composition."""- mock_entity = Mock()- mock_entity_state = Mock()- mock_sensor = Mock()-- video_stream_entity = VideoStreamEntity(- entity=mock_entity,- entity_state=mock_entity_state,- sensor=mock_sensor+ # Should have string representation+ suggestion_str = str(suggestion)+ self.assertIn('TransientViewSuggestion', suggestion_str)+ self.assertIn('/test/url/', suggestion_str)++ def test_transient_view_suggestion_with_different_priorities(self):+ """Test TransientViewSuggestion with different priority values."""+ high_priority = TransientViewSuggestion(+ url='/high/priority/url/',+ duration_seconds=45,+ priority=10,+ trigger_reason='critical_alert')- # Should maintain references to all components- self.assertEqual(video_stream_entity.entity, mock_entity)- self.assertEqual(video_stream_entity.entity_state, mock_entity_state)- self.assertEqual(video_stream_entity.sensor, mock_sensor)- return-- def test_motion_detection_state_with_movement_state(self):- """Test motion_detection_state property returns MOVEMENT state when it exists."""- mock_entity = Mock()- mock_entity_state = Mock()- mock_sensor = Mock()-- # Create mock movement state- mock_movement_state = Mock()- mock_movement_state.entity_state_type = EntityStateType.MOVEMENT-- # Create mock non-movement state- mock_video_state = Mock()- mock_video_state.entity_state_type = EntityStateType.VIDEO_STREAM-- # Setup entity.states.all() to return both states- mock_entity.states.all.return_value = [mock_video_state, mock_movement_state]-- video_stream_entity = VideoStreamEntity(- entity=mock_entity,- entity_state=mock_entity_state,- sensor=mock_sensor+ low_priority = TransientViewSuggestion(+ url='/low/priority/url/',+ duration_seconds=15,+ priority=1,+ trigger_reason='info_update')- # Should return the movement state- self.assertEqual(video_stream_entity.motion_detection_state, mock_movement_state)- return+ self.assertEqual(high_priority.priority, 10)+ self.assertEqual(low_priority.priority, 1)+ self.assertGreater(high_priority.priority, low_priority.priority)- def test_motion_detection_state_without_movement_state(self):- """Test motion_detection_state property returns None when no MOVEMENT state exists."""- mock_entity = Mock()- mock_entity_state = Mock()- mock_sensor = Mock()-- # Create only non-movement states- mock_video_state = Mock()- mock_video_state.entity_state_type = EntityStateType.VIDEO_STREAM-- mock_on_off_state = Mock()- mock_on_off_state.entity_state_type = EntityStateType.ON_OFF-- # Setup entity.states.all() to return only non-movement states- mock_entity.states.all.return_value = [mock_video_state, mock_on_off_state]+ def test_transient_view_suggestion_with_various_trigger_reasons(self):+ """Test TransientViewSuggestion with different trigger reasons."""+ reasons = [+ 'motion_detected',+ 'door_opened',+ 'alarm_triggered',+ 'weather_alert',+ 'security_breach'+ ]- video_stream_entity = VideoStreamEntity(- entity=mock_entity,- entity_state=mock_entity_state,- sensor=mock_sensor+ for reason in reasons:+ suggestion = TransientViewSuggestion(+ url=f'/console/view/{reason}/',+ duration_seconds=30,+ priority=5,+ trigger_reason=reason+ )+ self.assertEqual(suggestion.trigger_reason, reason)+++class TestVideoStream(BaseTestCase):+ """Test VideoStream model for video streaming functionality."""++ def test_video_stream_creation_with_minimal_fields(self):+ """Test creating a VideoStream with minimal required fields."""+ video_stream = VideoStream(+ stream_type=VideoStreamType.URL)- # Should return None when no movement state exists- self.assertIsNone(video_stream_entity.motion_detection_state)- return+ self.assertEqual(video_stream.stream_type, VideoStreamType.URL)+ self.assertIsNone(video_stream.source_url)+ self.assertEqual(video_stream.metadata, {})- def test_motion_detection_state_with_multiple_movement_states(self):- """Test motion_detection_state property returns first MOVEMENT state when multiple exist."""- mock_entity = Mock()- mock_entity_state = Mock()- mock_sensor = Mock()-- # Create multiple movement states- mock_movement_state1 = Mock()- mock_movement_state1.entity_state_type = EntityStateType.MOVEMENT+ def test_video_stream_creation_with_all_fields(self):+ """Test creating a VideoStream with all fields populated."""+ metadata = {+ 'width': 1920,+ 'height': 1080,+ 'fps': 30,+ 'codec': 'h264'+ }++ video_stream = VideoStream(+ stream_type=VideoStreamType.URL,+ source_url='https://example.com/stream.m3u8',+ metadata=metadata+ )- mock_movement_state2 = Mock()- mock_movement_state2.entity_state_type = EntityStateType.MOVEMENT+ self.assertEqual(video_stream.stream_type, VideoStreamType.URL)+ self.assertEqual(video_stream.source_url, 'https://example.com/stream.m3u8')+ self.assertEqual(video_stream.metadata, metadata)+ self.assertEqual(video_stream.metadata['width'], 1920)+ self.assertEqual(video_stream.metadata['fps'], 30)++ def test_video_stream_with_different_stream_types(self):+ """Test VideoStream creation with different stream types."""+ # Test URL stream+ url_stream = VideoStream(+ stream_type=VideoStreamType.URL,+ source_url='http://camera.local/mjpeg'+ )+ self.assertEqual(url_stream.stream_type, VideoStreamType.URL)- # Setup entity.states.all() to return multiple movement states- mock_entity.states.all.return_value = [mock_movement_state1, mock_movement_state2]+ # Test OTHER stream+ other_stream = VideoStream(+ stream_type=VideoStreamType.OTHER,+ source_url='https://stream.example.com/playlist.m3u8'+ )+ self.assertEqual(other_stream.stream_type, VideoStreamType.OTHER)++ def test_video_stream_metadata_defaults_to_empty_dict(self):+ """Test that VideoStream metadata defaults to empty dictionary."""+ video_stream = VideoStream(+ stream_type=VideoStreamType.URL,+ source_url='http://test.local/stream'+ )- video_stream_entity = VideoStreamEntity(- entity=mock_entity,- entity_state=mock_entity_state,- sensor=mock_sensor+ self.assertIsInstance(video_stream.metadata, dict)+ self.assertEqual(len(video_stream.metadata), 0)++ def test_video_stream_metadata_can_store_various_types(self):+ """Test that VideoStream metadata can store different data types."""+ metadata = {+ 'resolution': '1920x1080',+ 'fps': 30,+ 'bitrate': 5000.5,+ 'has_audio': True,+ 'supported_formats': ['h264', 'mjpeg'],+ 'camera_info': {+ 'manufacturer': 'TestCam',+ 'model': 'TC-1000'+ }+ }++ video_stream = VideoStream(+ stream_type=VideoStreamType.URL,+ source_url='https://test.local/stream.m3u8',+ metadata=metadata)- # Should return the first movement state- self.assertEqual(video_stream_entity.motion_detection_state, mock_movement_state1)- return+ self.assertIsInstance(video_stream.metadata['resolution'], str)+ self.assertIsInstance(video_stream.metadata['fps'], int)+ self.assertIsInstance(video_stream.metadata['bitrate'], float)+ self.assertIsInstance(video_stream.metadata['has_audio'], bool)+ self.assertIsInstance(video_stream.metadata['supported_formats'], list)+ self.assertIsInstance(video_stream.metadata['camera_info'], dict)- def test_motion_detection_state_with_no_states(self):- """Test motion_detection_state property returns None when entity has no states."""- mock_entity = Mock()- mock_entity_state = Mock()- mock_sensor = Mock()+ def test_video_stream_is_dataclass(self):+ """Test that VideoStream behaves as a proper dataclass."""+ video_stream = VideoStream(+ stream_type=VideoStreamType.URL,+ source_url='http://test.local/mjpeg',+ metadata={'test': 'value'}+ )- # Setup entity.states.all() to return empty list- mock_entity.states.all.return_value = []+ # Should have string representation+ stream_str = str(video_stream)+ self.assertIn('VideoStream', stream_str)- video_stream_entity = VideoStreamEntity(- entity=mock_entity,- entity_state=mock_entity_state,- sensor=mock_sensor+ # Should be able to access all fields+ self.assertTrue(hasattr(video_stream, 'stream_type'))+ self.assertTrue(hasattr(video_stream, 'source_url'))+ self.assertTrue(hasattr(video_stream, 'metadata'))++ def test_video_stream_with_none_source_url(self):+ """Test VideoStream with None source_url (valid use case)."""+ video_stream = VideoStream(+ stream_type=VideoStreamType.URL,+ source_url=None)- # Should return None when no states exist- self.assertIsNone(video_stream_entity.motion_detection_state)- return+ self.assertEqual(video_stream.stream_type, VideoStreamType.URL)+ self.assertIsNone(video_stream.source_url)diff --git a/src/hi/apps/console/tests/test_transient_view_manager.py b/src/hi/apps/console/tests/test_transient_view_manager.pyindex b0f61a1d..63386874 100644--- a/src/hi/apps/console/tests/test_transient_view_manager.py+++ b/src/hi/apps/console/tests/test_transient_view_manager.py@@ -126,10 +126,12 @@ class TestTransientViewManager(BaseTestCase):"""Test TransientViewManager considers alerts when auto-view enabled - core business logic."""from django.utils import timezonefrom hi.apps.alert.alert import Alert- from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+ from hi.apps.alert.alarm import Alarmfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.security.enums import SecurityLevelfrom hi.apps.entity.models import Entity, EntityState+ from hi.apps.sense.transient_models import SensorResponse+ from hi.integrations.transient_models import IntegrationKeyfrom hi.apps.entity.enums import EntityStateTypefrom hi.apps.sense.models import Sensor@@ -154,24 +156,19 @@ class TestTransientViewManager(BaseTestCase):name='Motion Sensor')- # Create video stream sensor state on same entity- video_state = EntityState.objects.create(- entity=entity,- entity_state_type_str=str(EntityStateType.VIDEO_STREAM),- name='video_stream'- )- video_sensor = Sensor.objects.create(- entity_state=video_state,- integration_id='test.video.front_door',- integration_name='test_integration',- name='Video Stream'- )+ # Enable video stream capability for this entity+ entity.has_video_stream = True+ entity.save()# Create motion detection alert with motion sensor- source_details = AlarmSourceDetails(+ source_details = SensorResponse(+ integration_key=IntegrationKey("test", "test.sensor"),+ value="active",+ timestamp=timezone.now(),+ sensor=motion_sensor, # Motion sensor that triggered the alarmdetail_attrs={'location': 'Front Door'},- image_url=None,- sensor_id=motion_sensor.id # Motion sensor that triggered the alarm+ source_image_url=None,+ has_video_stream=False)motion_alarm = Alarm(@@ -179,7 +176,7 @@ class TestTransientViewManager(BaseTestCase):alarm_type='motion_detection',alarm_level=AlarmLevel.WARNING,title='Motion detected at Front Door',- source_details_list=[source_details],+ sensor_response_list=[source_details],security_level=SecurityLevel.OFF,alarm_lifetime_secs=300,timestamp=timezone.now()@@ -201,28 +198,40 @@ class TestTransientViewManager(BaseTestCase):# Consider alert for auto-viewself.manager.consider_alert_for_auto_view(alert)- # Should create suggestion with video sensor URL (not motion sensor)+ # TransientViewManager should create suggestions for video-enabled entitiesself.assertTrue(self.manager.has_suggestion())- suggestion = self.manager.peek_current_suggestion()- expected_url = f'/console/sensor/video-stream/{video_sensor.id}'- self.assertEqual(suggestion.url, expected_url)++ # Verify suggestion content+ suggestion = self.manager.get_current_suggestion()+ self.assertIsNotNone(suggestion)+ self.assertIn('/console/entity/video-stream/', suggestion.url)+ self.assertIn(str(entity.id), suggestion.url)self.assertEqual(suggestion.duration_seconds, 30)self.assertEqual(suggestion.priority, motion_alarm.alarm_level.priority)self.assertEqual(suggestion.trigger_reason, 'event_alert')++ # Verify suggestion is consumed (cleared after retrieval)+ self.assertFalse(self.manager.has_suggestion())def test_consider_alert_with_auto_view_disabled(self):"""Test TransientViewManager ignores alerts when auto-view disabled - settings integration."""from django.utils import timezonefrom hi.apps.alert.alert import Alert- from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+ from hi.apps.alert.alarm import Alarmfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.security.enums import SecurityLevel+ from hi.apps.sense.transient_models import SensorResponse+ from hi.integrations.transient_models import IntegrationKey# Create motion detection alert- source_details = AlarmSourceDetails(+ source_details = SensorResponse(+ integration_key=IntegrationKey("test", "test.sensor"),+ value="active",+ timestamp=timezone.now(),+ sensor=None, # TODO: fix sensor referencedetail_attrs={},- image_url=None,- sensor_id='cam_123'+ source_image_url=None,+ has_video_stream=False)motion_alarm = Alarm(@@ -230,7 +239,7 @@ class TestTransientViewManager(BaseTestCase):alarm_type='motion_detection',alarm_level=AlarmLevel.WARNING,title='Motion detected',- source_details_list=[source_details],+ sensor_response_list=[source_details],security_level=SecurityLevel.OFF,alarm_lifetime_secs=300,timestamp=timezone.now()@@ -254,15 +263,21 @@ class TestTransientViewManager(BaseTestCase):"""Test TransientViewManager handles alerts without camera view URLs - integration test."""from django.utils import timezonefrom hi.apps.alert.alert import Alert- from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+ from hi.apps.alert.alarm import Alarmfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.security.enums import SecurityLevel+ from hi.apps.sense.transient_models import SensorResponse+ from hi.integrations.transient_models import IntegrationKey# Create non-motion EVENT alarm- source_details = AlarmSourceDetails(+ source_details = SensorResponse(+ integration_key=IntegrationKey("test", "test.sensor"),+ value="active",+ timestamp=timezone.now(),+ sensor=None, # TODO: fix sensor referencedetail_attrs={},- image_url=None,- sensor_id='cam_123'+ source_image_url=None,+ has_video_stream=False)status_alarm = Alarm(@@ -270,7 +285,7 @@ class TestTransientViewManager(BaseTestCase):alarm_type='device_status', # Not motion-relatedalarm_level=AlarmLevel.INFO,title='Device status update',- source_details_list=[source_details],+ sensor_response_list=[source_details],security_level=SecurityLevel.OFF,alarm_lifetime_secs=300,timestamp=timezone.now()@@ -294,14 +309,21 @@ class TestTransientViewManager(BaseTestCase):"""Test TransientViewManager ignores alerts without view URLs - integration with Alert model."""from django.utils import timezonefrom hi.apps.alert.alert import Alert- from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+ from hi.apps.alert.alarm import Alarmfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.security.enums import SecurityLevel+ from hi.apps.sense.transient_models import SensorResponse+ from hi.integrations.transient_models import IntegrationKey# Create motion alarm but without sensor_id (no view URL)- source_details = AlarmSourceDetails(- detail_attrs={'location': 'Front Door'}, # No sensor_id- image_url=None+ source_details = SensorResponse(+ integration_key=IntegrationKey("test", "test.no_sensor"),+ value="active",+ timestamp=timezone.now(),+ sensor=None,+ detail_attrs={'location': 'Front Door'},+ source_image_url=None,+ has_video_stream=False)motion_alarm = Alarm(@@ -309,7 +331,7 @@ class TestTransientViewManager(BaseTestCase):alarm_type='motion_detection',alarm_level=AlarmLevel.WARNING,title='Motion detected',- source_details_list=[source_details],+ sensor_response_list=[source_details],security_level=SecurityLevel.OFF,alarm_lifetime_secs=300,timestamp=timezone.now()diff --git a/src/hi/apps/console/tests/test_view_url_utils.py b/src/hi/apps/console/tests/test_view_url_utils.pyindex 83be8618..4e385824 100644--- a/src/hi/apps/console/tests/test_view_url_utils.py+++ b/src/hi/apps/console/tests/test_view_url_utils.py@@ -1,255 +1,189 @@import logging-from unittest.mock import patch-from django.utils import timezone--from hi.apps.alert.alarm import Alarm, AlarmSourceDetails-from hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.console.view_url_utils import ViewUrlUtils-from hi.apps.entity.models import Entity, EntityState+from hi.apps.entity.models import Entity, EntityStatefrom hi.apps.entity.enums import EntityStateType-from hi.apps.security.enums import SecurityLevelfrom hi.apps.sense.models import Sensor-from hi.apps.sense.enums import SensorTypefrom hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)class TestViewUrlUtils(BaseTestCase):- """Test ViewUrlUtils with proper database setup."""+ """Test ViewUrlUtils for generating view URLs from alarms and sensors."""def setUp(self):- """Set up test data with proper entity/sensor relationships."""super().setUp()- # Create an entity (e.g., a camera)- self.camera_entity = Entity.objects.create(- name='Front Door Camera',- entity_type_str='CAMERA'+ # Create entity with video stream capability+ self.video_entity = Entity.objects.create(+ integration_id='test.camera.video',+ integration_name='test_integration',+ name='Video Camera',+ entity_type_str='camera',+ has_video_stream=True)- # Create entity states for the camera- self.motion_entity_state = EntityState.objects.create(- entity=self.camera_entity,- entity_state_type=EntityStateType.MOVEMENT,- name='Motion Detection'+ # Create entity without video stream capability+ self.non_video_entity = Entity.objects.create(+ integration_id='test.sensor.temp',+ integration_name='test_integration',+ name='Temperature Sensor',+ entity_type_str='sensor',+ has_video_stream=False)- self.video_stream_entity_state = EntityState.objects.create(- entity=self.camera_entity,- entity_state_type=EntityStateType.VIDEO_STREAM,- name='Video Stream'+ # Create entity states and sensors+ self.video_motion_state = EntityState.objects.create(+ entity=self.video_entity,+ entity_state_type_str=str(EntityStateType.MOVEMENT),+ name='motion')-- # Create sensors- self.motion_sensor = Sensor.objects.create(- name='Motion Sensor',- entity_state=self.motion_entity_state,- sensor_type_str=str(SensorType.DEFAULT),- integration_id='zm_motion_1',- integration_name='zoneminder'+ self.video_motion_sensor = Sensor.objects.create(+ entity_state=self.video_motion_state,+ integration_id='test.motion.video',+ integration_name='test_integration',+ name='Video Motion Sensor')- self.video_sensor = Sensor.objects.create(- name='Video Stream Sensor',- entity_state=self.video_stream_entity_state,- sensor_type_str=str(SensorType.DEFAULT),- integration_id='zm_video_1',- integration_name='zoneminder'+ self.temp_state = EntityState.objects.create(+ entity=self.non_video_entity,+ entity_state_type_str=str(EntityStateType.TEMPERATURE),+ name='temperature'+ )+ self.temp_sensor = Sensor.objects.create(+ entity_state=self.temp_state,+ integration_id='test.temp.sensor',+ integration_name='test_integration',+ name='Temperature Sensor')- def test_motion_sensor_with_video_stream_generates_url(self):- """Test that a motion sensor on entity with video stream generates camera URL."""- # Create alarm with motion sensor- source_details = AlarmSourceDetails(- detail_attrs={'location': 'Front Door'},- image_url=None,- sensor_id=self.motion_sensor.id+ def test_get_view_url_for_alarm_returns_video_url_for_video_entity(self):+ """Test that alarms from video-capable entities return video stream URLs."""+ from hi.apps.alert.alarm import Alarm+ from hi.apps.alert.enums import AlarmLevel, AlarmSource+ from hi.apps.security.enums import SecurityLevel+ from hi.apps.sense.transient_models import SensorResponse+ from hi.integrations.transient_models import IntegrationKey+ import hi.apps.common.datetimeproxy as datetimeproxy++ # Create alarm with sensor from video-capable entity+ sensor_response = SensorResponse(+ integration_key=IntegrationKey('test', 'motion.video'),+ value='active',+ timestamp=datetimeproxy.now(),+ sensor=self.video_motion_sensor,+ detail_attrs={},+ source_image_url=None,+ has_video_stream=False)alarm = Alarm(alarm_source=AlarmSource.EVENT,alarm_type='motion_detection',alarm_level=AlarmLevel.WARNING,- title='Motion detected at Front Door',- source_details_list=[source_details],- security_level=SecurityLevel.OFF,+ title='Motion detected',+ sensor_response_list=[sensor_response],+ security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,- timestamp=timezone.now()+ timestamp=datetimeproxy.now())+ # Test URL generationview_url = ViewUrlUtils.get_view_url_for_alarm(alarm)- # Should return URL with video sensor ID (not motion sensor ID)- self.assertEqual(view_url, f'/console/sensor/video-stream/{self.video_sensor.id}')-- def test_video_sensor_generates_url(self):- """Test that a video stream sensor generates camera URL."""- source_details = AlarmSourceDetails(- detail_attrs={'location': 'Front Door'},- image_url=None,- sensor_id=self.video_sensor.id+ self.assertIsNotNone(view_url)+ self.assertIn('/console/entity/video-stream/', view_url)+ self.assertIn(str(self.video_entity.id), view_url)++ def test_get_view_url_for_alarm_returns_none_for_non_video_entity(self):+ """Test that alarms from non-video entities return None."""+ from hi.apps.alert.alarm import Alarm+ from hi.apps.alert.enums import AlarmLevel, AlarmSource+ from hi.apps.security.enums import SecurityLevel+ from hi.apps.sense.transient_models import SensorResponse+ from hi.integrations.transient_models import IntegrationKey+ import hi.apps.common.datetimeproxy as datetimeproxy++ # Create alarm with sensor from non-video entity+ sensor_response = SensorResponse(+ integration_key=IntegrationKey('test', 'temp.sensor'),+ value='22.5',+ timestamp=datetimeproxy.now(),+ sensor=self.temp_sensor,+ detail_attrs={},+ source_image_url=None,+ has_video_stream=False)alarm = Alarm(alarm_source=AlarmSource.EVENT,- alarm_type='video_issue',+ alarm_type='temperature_change',alarm_level=AlarmLevel.INFO,- title='Video stream issue',- source_details_list=[source_details],- security_level=SecurityLevel.OFF,+ title='Temperature reading',+ sensor_response_list=[sensor_response],+ security_level=SecurityLevel.LOW,alarm_lifetime_secs=300,- timestamp=timezone.now()+ timestamp=datetimeproxy.now())+ # Test URL generationview_url = ViewUrlUtils.get_view_url_for_alarm(alarm)- # Should return the actual URL generated by Django's reverse()- self.assertEqual(view_url, f'/console/sensor/video-stream/{self.video_sensor.id}')-- def test_sensor_without_video_stream_returns_none(self):- """Test that sensor on entity without video stream returns None."""- # Create entity without video stream- thermostat_entity = Entity.objects.create(- name='Living Room Thermostat',- entity_type_str='THERMOSTAT'- )-- temp_entity_state = EntityState.objects.create(- entity=thermostat_entity,- entity_state_type=EntityStateType.TEMPERATURE,- name='Temperature Reading'- )-- temp_sensor = Sensor.objects.create(- name='Temperature Sensor',- entity_state=temp_entity_state,- sensor_type_str=str(SensorType.DEFAULT),- integration_id='hass_temp_1',- integration_name='homeassistant'- )-- source_details = AlarmSourceDetails(- detail_attrs={'location': 'Living Room'},- image_url=None,- sensor_id=temp_sensor.id- )-- alarm = Alarm(- alarm_source=AlarmSource.EVENT,- alarm_type='temperature_alert',- alarm_level=AlarmLevel.WARNING,- title='High temperature',- source_details_list=[source_details],- security_level=SecurityLevel.OFF,- alarm_lifetime_secs=300,- timestamp=timezone.now()- )-- view_url = ViewUrlUtils.get_view_url_for_alarm(alarm)self.assertIsNone(view_url)-- def test_nonexistent_sensor_returns_none(self):- """Test that non-existent sensor ID returns None."""- source_details = AlarmSourceDetails(- detail_attrs={'location': 'Somewhere'},- image_url=None,- sensor_id='99999' # Non-existent sensor- )- alarm = Alarm(- alarm_source=AlarmSource.EVENT,- alarm_type='unknown',- alarm_level=AlarmLevel.WARNING,- title='Unknown alert',- source_details_list=[source_details],- security_level=SecurityLevel.OFF,- alarm_lifetime_secs=300,- timestamp=timezone.now()- )-- view_url = ViewUrlUtils.get_view_url_for_alarm(alarm)- self.assertIsNone(view_url)-- def test_alarm_without_sensor_id_returns_none(self):- """Test that alarm without sensor_id returns None."""- source_details = AlarmSourceDetails(- detail_attrs={'location': 'Somewhere'},- image_url=None,- sensor_id=None+ def test_get_view_url_for_alarm_returns_none_for_alarm_without_sensors(self):+ """Test that alarms without sensors return None."""+ from hi.apps.alert.alarm import Alarm+ from hi.apps.alert.enums import AlarmLevel, AlarmSource+ from hi.apps.security.enums import SecurityLevel+ from hi.apps.sense.transient_models import SensorResponse+ from hi.integrations.transient_models import IntegrationKey+ import hi.apps.common.datetimeproxy as datetimeproxy++ # Create alarm with sensor response but no sensor object+ sensor_response = SensorResponse(+ integration_key=IntegrationKey('test', 'weather'),+ value='active',+ timestamp=datetimeproxy.now(),+ sensor=None, # No sensor object+ detail_attrs={'event': 'Tornado Warning'},+ source_image_url=None,+ has_video_stream=False)alarm = Alarm(alarm_source=AlarmSource.WEATHER,- alarm_type='tornado_warning',+ alarm_type='tornado',alarm_level=AlarmLevel.CRITICAL,title='Tornado Warning',- source_details_list=[source_details],- security_level=SecurityLevel.OFF,- alarm_lifetime_secs=1800,- timestamp=timezone.now()+ sensor_response_list=[sensor_response],+ security_level=SecurityLevel.HIGH,+ alarm_lifetime_secs=3600,+ timestamp=datetimeproxy.now())+ # Test URL generationview_url = ViewUrlUtils.get_view_url_for_alarm(alarm)+self.assertIsNone(view_url)-- def test_multiple_source_details_uses_first_valid_sensor(self):- """Test that first valid sensor_id is used when multiple source details exist."""- # First source detail without sensor_id- source_details_1 = AlarmSourceDetails(- detail_attrs={'location': 'Area A'},- image_url=None,- sensor_id=None- )- # Second source detail with sensor_id- source_details_2 = AlarmSourceDetails(- detail_attrs={'location': 'Area B'},- image_url=None,- sensor_id=self.motion_sensor.id- )+ def test_get_view_url_for_sensor_id_returns_video_url_for_video_entity(self):+ """Test direct sensor ID lookup for video-capable entity."""+ view_url = ViewUrlUtils._get_view_url_for_sensor_id(self.video_motion_sensor.id)- alarm = Alarm(- alarm_source=AlarmSource.EVENT,- alarm_type='motion_detection',- alarm_level=AlarmLevel.WARNING,- title='Motion detected',- source_details_list=[source_details_1, source_details_2],- security_level=SecurityLevel.OFF,- alarm_lifetime_secs=300,- timestamp=timezone.now()- )+ self.assertIsNotNone(view_url)+ self.assertIn('/console/entity/video-stream/', view_url)+ self.assertIn(str(self.video_entity.id), view_url)- view_url = ViewUrlUtils.get_view_url_for_alarm(alarm)+ def test_get_view_url_for_sensor_id_returns_none_for_non_video_entity(self):+ """Test direct sensor ID lookup for non-video entity."""+ view_url = ViewUrlUtils._get_view_url_for_sensor_id(self.temp_sensor.id)- # Should return URL with video sensor ID (not motion sensor ID)- self.assertEqual(view_url, f'/console/sensor/video-stream/{self.video_sensor.id}')-- def test_url_generation_exception_handling(self):- """Test graceful handling of URL generation failures."""- source_details = AlarmSourceDetails(- detail_attrs={'location': 'Front Door'},- image_url=None,- sensor_id=self.motion_sensor.id- )+ self.assertIsNone(view_url)- alarm = Alarm(- alarm_source=AlarmSource.EVENT,- alarm_type='motion_detection',- alarm_level=AlarmLevel.WARNING,- title='Motion detected',- source_details_list=[source_details],- security_level=SecurityLevel.OFF,- alarm_lifetime_secs=300,- timestamp=timezone.now()- )+ def test_get_view_url_for_sensor_id_handles_nonexistent_sensor(self):+ """Test that nonexistent sensor IDs are handled gracefully."""+ view_url = ViewUrlUtils._get_view_url_for_sensor_id('nonexistent-sensor-id')- # Test with a broken URL pattern name to trigger exception handling- with patch('hi.apps.console.view_url_utils.reverse') as mock_reverse:- mock_reverse.side_effect = Exception("URL pattern not found")-- view_url = ViewUrlUtils.get_view_url_for_alarm(alarm)-- # Test error handling behavior: should return None on failure- self.assertIsNone(view_url)+ self.assertIsNone(view_url)diff --git a/src/hi/apps/console/tests/test_views.py b/src/hi/apps/console/tests/test_views.pyindex 8eade668..940b9b10 100644--- a/src/hi/apps/console/tests/test_views.py+++ b/src/hi/apps/console/tests/test_views.py@@ -1,282 +1,80 @@import logging-from unittest.mock import Mock, patchfrom django.urls import reverse-from hi.apps.console.console_helper import ConsoleSettingsHelper-from hi.apps.console.constants import ConsoleConstants-from hi.apps.sense.models import Sensor-from hi.apps.sense.sensor_response_manager import SensorResponseManager-from hi.enums import ViewType-from hi.testing.view_test_base import DualModeViewTestCase, SyncViewTestCase+from hi.apps.console.views import EntityVideoStreamView+from hi.apps.entity.models import Entity+from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)-class TestSensorVideoStreamView(DualModeViewTestCase):- """- Tests for SensorVideoStreamView - demonstrates HiGridView testing for video streams.- This view displays a video stream from a sensor.- """+class TestEntityVideoStreamView(BaseTestCase):+ """Test EntityVideoStreamView for displaying video streams."""def setUp(self):super().setUp()- # Create test entity and sensor- from hi.apps.entity.models import Entity, EntityState- self.entity = Entity.objects.create(- name='Video Camera',- entity_type_str='CAMERA'- )- self.entity_state = EntityState.objects.create(- entity=self.entity,- name='video_stream',- entity_state_type_str='TEXT'++ # Create test entity with video stream capability+ self.video_entity = Entity.objects.create(+ integration_id='test.camera.front',+ integration_name='test_integration',+ name='Front Door Camera',+ entity_type_str='camera',+ has_video_stream=True)- self.sensor = Sensor.objects.create(- name='Video Stream Sensor',- entity_state=self.entity_state,- sensor_type_str='VIDEO_STREAM',- integration_id='test_camera_01'++ # Create entity without video stream capability+ self.non_video_entity = Entity.objects.create(+ integration_id='test.sensor.temp',+ integration_name='test_integration',+ name='Temperature Sensor',+ entity_type_str='sensor',+ has_video_stream=False)- @patch.object(SensorResponseManager, 'get_latest_sensor_responses')- def test_get_video_stream_sync(self, mock_get_responses):- """Test getting video stream with synchronous request."""- mock_response = Mock()- mock_response.value = 'http://test-stream-url.com/stream'- mock_get_responses.return_value = {self.sensor: [mock_response]}-- url = reverse('console_sensor_video_stream', kwargs={'sensor_id': self.sensor.id})- response = self.client.get(url)-- self.assertSuccessResponse(response)- self.assertHtmlResponse(response)- self.assertTemplateRendered(response, 'console/panes/sensor_video_stream.html')+ def test_get_main_template_name_returns_correct_template(self):+ """Test that the view returns the correct template name."""+ view = EntityVideoStreamView()+ template_name = view.get_main_template_name()- # Check that view parameters are set- session = self.client.session- self.assertEqual(session.get('view_type'), str(ViewType.VIDEO_STREAM))-- @patch.object(SensorResponseManager, 'get_latest_sensor_responses')- def test_get_video_stream_async(self, mock_get_responses):- """Test getting video stream with AJAX request."""- mock_response = Mock()- mock_response.value = 'http://test-stream-url.com/stream'- mock_get_responses.return_value = {self.sensor: [mock_response]}-- url = reverse('console_sensor_video_stream', kwargs={'sensor_id': self.sensor.id})- response = self.async_get(url)-- self.assertSuccessResponse(response)- self.assertJsonResponse(response)+ self.assertEqual(template_name, 'console/panes/entity_video_pane.html')- # HiGridView returns JSON with insert and pushUrl for AJAX requests- data = response.json()- self.assertIn('insert', data) # Contains the main content- self.assertIn('pushUrl', data) # Contains the URL for browser history-- def test_nonexistent_sensor_returns_404(self):- """Test that accessing nonexistent sensor returns 404."""- url = reverse('console_sensor_video_stream', kwargs={'sensor_id': 99999})- response = self.client.get(url)-- self.assertEqual(response.status_code, 404)-- @patch.object(SensorResponseManager, 'get_latest_sensor_responses')- def test_no_video_stream_returns_400(self, mock_get_responses):- """Test that no available video stream returns BadRequest."""- mock_get_responses.return_value = {}-- url = reverse('console_sensor_video_stream', kwargs={'sensor_id': self.sensor.id})- response = self.client.get(url)-- self.assertEqual(response.status_code, 400)-- @patch.object(SensorResponseManager, 'get_latest_sensor_responses')- def test_sensor_and_response_in_context(self, mock_get_responses):- """Test that sensor and response are passed to template context."""- mock_response = Mock()- mock_response.value = 'http://test-stream-url.com/stream'- mock_get_responses.return_value = {self.sensor: [mock_response]}-- url = reverse('console_sensor_video_stream', kwargs={'sensor_id': self.sensor.id})- response = self.client.get(url)-- self.assertSuccessResponse(response)- self.assertEqual(response.context['sensor'], self.sensor)- self.assertEqual(response.context['sensor_response'], mock_response)---class TestConsoleLockView(SyncViewTestCase):- """- Tests for ConsoleLockView - demonstrates POST-only view testing.- This view locks the console interface.- """-- @patch.object(ConsoleSettingsHelper, 'get_console_lock_password')- def test_lock_with_existing_password(self, mock_get_password):- """Test locking console when password is already set."""- mock_get_password.return_value = 'test_password'-- url = reverse('console_lock')- response = self.client.post(url)-- self.assertSuccessResponse(response)- # Should set session variable and redirect to unlock view- self.assertTrue(self.client.session.get(ConsoleConstants.CONSOLE_LOCKED_SESSION_VAR))-- @patch.object(ConsoleSettingsHelper, 'get_console_lock_password')- def test_lock_without_password_shows_set_password(self, mock_get_password):- """Test locking console when no password is set shows set password modal."""- mock_get_password.return_value = None-- url = reverse('console_lock')- response = self.client.post(url)-- self.assertSuccessResponse(response)- # Should render set password template- self.assertTemplateRendered(response, 'console/modals/set_lock_password.html')-- def test_get_not_allowed(self):- """Test that GET requests are not allowed."""- url = reverse('console_lock')- response = self.client.get(url)-- self.assertEqual(response.status_code, 405)---class TestSetLockPasswordView(DualModeViewTestCase):- """- Tests for SetLockPasswordView - demonstrates HiModalView with form testing.- This view allows setting a console lock password.- """-- def test_get_set_password_modal_sync(self):- """Test getting set password modal with synchronous request."""- url = reverse('console_set_lock_password')- response = self.client.get(url)-- self.assertSuccessResponse(response)- self.assertHtmlResponse(response)- self.assertTemplateRendered(response, 'console/modals/set_lock_password.html')-- def test_get_set_password_modal_async(self):- """Test getting set password modal with AJAX request."""- url = reverse('console_set_lock_password')- response = self.async_get(url)-- self.assertSuccessResponse(response)- self.assertJsonResponse(response)+ def test_view_integration_with_url_routing(self):+ """Test that the view integrates correctly with URL routing."""+ # This tests the actual URL pattern and view integration+ url = reverse('console_entity_video_stream', kwargs={'entity_id': self.video_entity.id})- # HiModalView returns JSON with modal content for AJAX requests- data = response.json()- self.assertIn('modal', data)-- @patch.object(ConsoleSettingsHelper, 'set_console_lock_password')- def test_post_valid_password(self, mock_set_password):- """Test posting valid password."""- mock_set_password.return_value = None-- url = reverse('console_set_lock_password')- response = self.client.post(url, {'password': 'new_password'})-- self.assertSuccessResponse(response)- mock_set_password.assert_called_once_with(password='new_password')+ self.assertIn('/console/entity/video-stream/', url)+ self.assertIn(str(self.video_entity.id), url)- # Should set session variable and show unlock view- self.assertTrue(self.client.session.get(ConsoleConstants.CONSOLE_LOCKED_SESSION_VAR))-- def test_post_empty_password_returns_400(self):- """Test posting empty password returns BadRequest."""- url = reverse('console_set_lock_password')- response = self.client.post(url, {'password': ''})-- self.assertEqual(response.status_code, 400)-- def test_post_no_password_returns_400(self):- """Test posting without password field returns BadRequest."""- url = reverse('console_set_lock_password')- response = self.client.post(url, {})-- self.assertEqual(response.status_code, 400)---class TestConsoleUnlockView(DualModeViewTestCase):- """- Tests for ConsoleUnlockView - demonstrates HiModalView with authentication testing.- This view allows unlocking the console interface.- """-- def test_get_unlock_modal_sync(self):- """Test getting unlock modal with synchronous request."""- url = reverse('console_unlock')- response = self.client.get(url)-- self.assertSuccessResponse(response)- self.assertHtmlResponse(response)- self.assertTemplateRendered(response, 'console/modals/console_unlock.html')-- def test_get_unlock_modal_async(self):- """Test getting unlock modal with AJAX request."""- url = reverse('console_unlock')- response = self.async_get(url)-- self.assertSuccessResponse(response)- self.assertJsonResponse(response)+ def test_view_inheritance_from_higrideview(self):+ """Test that EntityVideoStreamView correctly inherits from HiGridView."""+ view = EntityVideoStreamView()- # HiModalView returns JSON with modal content for AJAX requests- data = response.json()- self.assertIn('modal', data)-- @patch.object(ConsoleSettingsHelper, 'get_console_lock_password')- def test_post_valid_password_unlocks(self, mock_get_password):- """Test posting correct password unlocks console."""- mock_get_password.return_value = 'correct_password'+ # Should have HiGridView methods+ self.assertTrue(hasattr(view, 'get_main_template_name'))+ self.assertTrue(hasattr(view, 'get_main_template_context'))+ self.assertTrue(callable(view.get_main_template_name))+ self.assertTrue(callable(view.get_main_template_context))++ def test_view_class_exists_and_is_importable(self):+ """Test that the EntityVideoStreamView class exists and can be imported."""+ # This is a basic smoke test to ensure the view is properly defined+ from hi.apps.console.views import EntityVideoStreamView- # First lock the console- session = self.client.session- session[ConsoleConstants.CONSOLE_LOCKED_SESSION_VAR] = True- session.save()-- url = reverse('console_unlock')- response = self.client.post(url, {'password': 'correct_password'})-- self.assertSuccessResponse(response)- # Should unlock console- self.assertFalse(self.client.session.get(ConsoleConstants.CONSOLE_LOCKED_SESSION_VAR))-- @patch.object(ConsoleSettingsHelper, 'get_console_lock_password')- def test_post_invalid_password_returns_400(self, mock_get_password):- """Test posting incorrect password returns BadRequest."""- mock_get_password.return_value = 'correct_password'-- url = reverse('console_unlock')- response = self.client.post(url, {'password': 'wrong_password'})-- self.assertEqual(response.status_code, 400)-- def test_post_empty_password_returns_400(self):- """Test posting empty password returns BadRequest."""- url = reverse('console_unlock')- response = self.client.post(url, {'password': ''})-- self.assertEqual(response.status_code, 400)-- def test_post_no_password_returns_400(self):- """Test posting without password field returns BadRequest."""- url = reverse('console_unlock')- response = self.client.post(url, {})-- self.assertEqual(response.status_code, 400)-- @patch.object(ConsoleSettingsHelper, 'get_console_lock_password')- def test_unlock_without_password_set_succeeds(self, mock_get_password):- """Test unlocking when no password is set (exceptional case handling)."""- mock_get_password.return_value = None-- url = reverse('console_unlock')- response = self.client.post(url, {'password': 'any_password'})-- self.assertSuccessResponse(response)- # Should unlock console even with no password set- self.assertFalse(self.client.session.get(ConsoleConstants.CONSOLE_LOCKED_SESSION_VAR))+ self.assertTrue(EntityVideoStreamView)+ self.assertTrue(hasattr(EntityVideoStreamView, 'get_main_template_name'))+ self.assertTrue(hasattr(EntityVideoStreamView, 'get_main_template_context'))++ def test_video_entity_has_correct_attributes(self):+ """Test that test video entity has correct attributes for testing."""+ self.assertEqual(self.video_entity.name, 'Front Door Camera')+ self.assertTrue(self.video_entity.has_video_stream)+ self.assertEqual(self.video_entity.integration_id, 'test.camera.front')++ def test_non_video_entity_has_correct_attributes(self):+ """Test that test non-video entity has correct attributes for testing."""+ self.assertEqual(self.non_video_entity.name, 'Temperature Sensor')+ self.assertFalse(self.non_video_entity.has_video_stream)+ self.assertEqual(self.non_video_entity.integration_id, 'test.sensor.temp')diff --git a/src/hi/apps/console/transient_models.py b/src/hi/apps/console/transient_models.pyindex c6b0aa46..3cc4262e 100644--- a/src/hi/apps/console/transient_models.py+++ b/src/hi/apps/console/transient_models.py@@ -2,34 +2,7 @@ from dataclasses import dataclassfrom datetime import datetimefrom typing import Optional-from hi.apps.entity.enums import EntityStateTypefrom hi.apps.entity.models import Entity, EntityState-from hi.apps.sense.models import Sensor---@dataclass-class VideoStreamEntity:- entity : Entity- entity_state : EntityState- sensor : Sensor-- @property- def name(self) -> str:- name = self.entity.name- if name.lower().endswith('camera') and len(name) > len('camera'):- name = name[:-len('camera')].strip()- return name-- @property- def motion_detection_state(self) -> Optional[EntityState]:- """- Returns the motion detection (MOVEMENT) EntityState for this camera entity if it exists.- Camera entities typically have a MOVEMENT state for motion detection.- """- for entity_state in self.entity.states.all():- if entity_state.entity_state_type == EntityStateType.MOVEMENT:- return entity_state- return None@dataclass@@ -47,3 +20,13 @@ class TransientViewSuggestion:def __post_init__(self):if self.timestamp is None:self.timestamp = datetime.now()+++@dataclass+class CameraControlDisplayData:+ """+ Data container for camera control display information.+ Encapsulates entity and its primary status entity state for template rendering.+ """+ entity: Entity+ status_entity_state: Optional[EntityState] = Nonediff --git a/src/hi/apps/console/urls.py b/src/hi/apps/console/urls.pyindex 720fb1dd..a887ceea 100644--- a/src/hi/apps/console/urls.py+++ b/src/hi/apps/console/urls.py@@ -5,9 +5,10 @@ from . import viewsurlpatterns = [- re_path( r'^sensor/video-stream/(?P<sensor_id>\d+)$',- views.SensorVideoStreamView.as_view(),- name='console_sensor_video_stream'),++ re_path( r'^entity/video-stream/(?P<entity_id>\d+)$',+ views.EntityVideoStreamView.as_view(),+ name='console_entity_video_stream'),re_path( r'^lock$',views.ConsoleLockView.as_view(),diff --git a/src/hi/apps/console/view_url_utils.py b/src/hi/apps/console/view_url_utils.pyindex 7c649075..0ac8c208 100644--- a/src/hi/apps/console/view_url_utils.py+++ b/src/hi/apps/console/view_url_utils.py@@ -4,7 +4,6 @@ from typing import Optionalfrom django.urls import reversefrom hi.apps.sense.models import Sensor-from hi.apps.entity.enums import EntityStateTypelogger = logging.getLogger(__name__)@@ -33,10 +32,10 @@ class ViewUrlUtils:Returns:A Django view URL string, or None if no appropriate view can be determined"""- # Look through all source details for sensor information- for source_details in alarm.source_details_list:- if source_details.sensor_id:- view_url = ViewUrlUtils._get_view_url_for_sensor_id(source_details.sensor_id)+ # Look through all source details (SensorResponse objects) for sensor information+ for sensor_response in alarm.sensor_response_list:+ if sensor_response.sensor and sensor_response.sensor.id:+ view_url = ViewUrlUtils._get_view_url_for_sensor_id(sensor_response.sensor.id)if view_url:return view_url@@ -58,21 +57,20 @@ class ViewUrlUtils:A Django view URL string, or None if no appropriate view found"""try:- # Look up the sensor- sensor = Sensor.objects.select_related('entity_state').get(id=sensor_id)+ # Look up the sensor and its entity+ sensor = Sensor.objects.select_related('entity_state__entity').get(id=sensor_id)+ entity = sensor.entity_state.entity- # Find the video stream sensor for this entity- video_stream_sensor = ViewUrlUtils._get_video_stream_sensor(sensor)- if video_stream_sensor:- # Use the video stream sensor's ID, not the original sensor's ID- return reverse('console_sensor_video_stream', kwargs={'sensor_id': video_stream_sensor.id})+ # Check if entity has video stream capability+ if entity.has_video_stream:+ # Generate entity-based video stream URL for live video feed+ return reverse('console_entity_video_stream', kwargs={'entity_id': entity.id})# Future: Add other view types based on entity state type# elif sensor.entity_state.entity_state_type == EntityStateType.WEATHER:# return reverse('console_weather_view', kwargs={'sensor_id': sensor_id})- logger.debug(f"Sensor {sensor_id} ({sensor.entity_state.entity_state_type}) "- f"does not have an associated view")+ logger.debug(f"Entity {entity.id} for sensor {sensor_id} does not have video stream capability")return Noneexcept Sensor.DoesNotExist:@@ -82,33 +80,3 @@ class ViewUrlUtils:logger.warning(f"Could not generate view URL for sensor {sensor_id}: {e}")return None- @staticmethod- def _get_video_stream_sensor(sensor: Sensor) -> Optional[Sensor]:- """- Get the video stream sensor associated with the given sensor's entity.-- This finds the video stream sensor that belongs to the same entity- as the given sensor (e.g., finding the video stream sensor when- given a motion detection sensor from the same camera entity).-- Args:- sensor: The Sensor object to check-- Returns:- The video stream Sensor if one exists, None otherwise- """- # Get the entity this sensor belongs to- entity = sensor.entity_state.entity-- # Look for video stream entity states on the same entity- video_stream_states = entity.states.filter(- entity_state_type_str=str(EntityStateType.VIDEO_STREAM)- ).prefetch_related('sensors')-- # Return the first video stream sensor found- for state in video_stream_states:- sensors = state.sensors.all()- if sensors:- return sensors.first()-- return Nonediff --git a/src/hi/apps/console/views.py b/src/hi/apps/console/views.pyindex d48d4278..ee189218 100644--- a/src/hi/apps/console/views.py+++ b/src/hi/apps/console/views.py@@ -2,8 +2,8 @@ from django.core.exceptions import BadRequestfrom django.http import Http404from django.views.generic import View-from hi.apps.sense.models import Sensor-from hi.apps.sense.sensor_response_manager import SensorResponseMixin+from hi.apps.entity.models import Entity+from hi.integrations.integration_manager import IntegrationManagerfrom hi.enums import ViewTypefrom hi.hi_async_view import HiModalView@@ -13,29 +13,36 @@ from .constants import ConsoleConstantsfrom .console_helper import ConsoleSettingsHelper-class SensorVideoStreamView( HiGridView, SensorResponseMixin ):+class EntityVideoStreamView( HiGridView ):+ """View for displaying entity-based video streams."""def get_main_template_name( self ) -> str:- return 'console/panes/sensor_video_stream.html'+ return 'console/panes/entity_video_pane.html'def get_main_template_context( self, request, *args, **kwargs ):- sensor_id = kwargs.get('sensor_id')+ entity_id = kwargs.get('entity_id')try:- sensor = Sensor.objects.get( id = sensor_id )- except Sensor.DoesNotExist:- raise Http404('Sensor not found.')-- sensor_response_map = self.sensor_response_manager().get_latest_sensor_responses(- sensor_list = [ sensor ],- )- if not sensor_response_map or not sensor_response_map[sensor]:+ entity = Entity.objects.get( id = entity_id )+ except Entity.DoesNotExist:+ raise Http404('Entity not found.')++ # Check if entity has video stream capability+ if not entity.has_video_stream:+ raise BadRequest( 'Entity does not have video stream capability.' )++ # Get the integration gateway for this entity+ integration_gateway = IntegrationManager().get_integration_gateway( entity.integration_id )+ if not integration_gateway:+ raise BadRequest( 'Integration not available for video stream.' )++ # Get the video stream using the integration gateway+ if not entity.has_video_stream:raise BadRequest( 'Video stream is not currently available.' )request.view_parameters.view_type = ViewType.VIDEO_STREAMrequest.view_parameters.to_session( request )return {- 'sensor': sensor,- 'sensor_response': sensor_response_map[sensor][0],+ 'entity': entity,}diff --git a/src/hi/apps/entity/entity_manager.py b/src/hi/apps/entity/entity_manager.pyindex d9374be3..9ce68582 100644--- a/src/hi/apps/entity/entity_manager.py+++ b/src/hi/apps/entity/entity_manager.py@@ -15,7 +15,6 @@ from hi.apps.location.models import Location, LocationViewfrom .entity_pairing_manager import EntityPairingManagerfrom .enums import (EntityGroupType,- EntityStateType,)from .models import (Entity,@@ -495,12 +494,9 @@ class EntityManager(Singleton):return entity_view_group_listdef get_view_stream_entities(self) -> List[ Entity ]:- """ Return all entities that have a video stream state """-- entity_state_queryset = EntityState.objects.select_related( 'entity' ).filter(- entity_state_type_str = str(EntityStateType.VIDEO_STREAM),- )- return [ x.entity for x in entity_state_queryset ]+ """ Return all entities that have a video stream capability """+ # Phase 4: Use has_video_stream flag instead of VIDEO_STREAM EntityState+ return list(Entity.objects.filter(has_video_stream=True))_thread_local = local()diff --git a/src/hi/apps/entity/entity_pairing_manager.py b/src/hi/apps/entity/entity_pairing_manager.pyindex 414da699..1aba6ccf 100644--- a/src/hi/apps/entity/entity_pairing_manager.py+++ b/src/hi/apps/entity/entity_pairing_manager.py@@ -25,7 +25,6 @@ class EntityPairingManager(Singleton):enums.EntityStateType.MOVEMENT: enums.EntityType.AREA,enums.EntityStateType.PRESENCE: enums.EntityType.AREA,enums.EntityStateType.SOUND_LEVEL: enums.EntityType.AREA,- enums.EntityStateType.VIDEO_STREAM: enums.EntityType.AREA,}def __init_singleton__(self):diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.pyindex 64f9fb58..e4c1b786 100644--- a/src/hi/apps/entity/enums.py+++ b/src/hi/apps/entity/enums.py@@ -178,7 +178,6 @@ class EntityStateType(LabeledEnum):PRESENCE = ( 'Presence' , '' )SOUND_LEVEL = ( 'Sound Level' , '' )TEMPERATURE = ( 'Temperature' , '' )- VIDEO_STREAM = ( 'Video Stream' , '' )WATER_FLOW = ( 'Water Flow' , '' )WIND_SPEED = ( 'Wind Speed' , '' )@@ -200,14 +199,6 @@ class EntityStateType(LabeledEnum):"""return f'control/panes/controller_{self.name.lower()}.html'- @property- def suppress_display_name(self):- return bool( self in { EntityStateType.VIDEO_STREAM })-- @property- def suppress_history(self):- return bool( self in { EntityStateType.VIDEO_STREAM })-class EntityStateValue(LabeledEnum):@@ -266,6 +257,17 @@ class EntityPairingType(LabeledEnum):DELEGATE = ( 'Delegate', '' )+class VideoStreamType(LabeledEnum):+ """Types of video streams that can be provided by entities or sensor responses."""++ URL = ('URL', 'Direct video stream URL')+ OTHER = ('Other', 'Other video stream type for future extensibility')++ @classmethod+ def default(cls):+ return cls.OTHER++class EntityGroupType(LabeledEnum):APPLIANCES = ( 'Appliances', '', {diff --git a/src/hi/apps/entity/migrations/0006_entity_has_video_stream.py b/src/hi/apps/entity/migrations/0006_entity_has_video_stream.pynew file mode 100644index 00000000..fd7704f1--- /dev/null+++ b/src/hi/apps/entity/migrations/0006_entity_has_video_stream.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.22 on 2025-08-23 16:04++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("entity", "0005_entityattributehistory"),+ ]++ operations = [+ migrations.AddField(+ model_name="entity",+ name="has_video_stream",+ field=models.BooleanField(default=False, verbose_name="Has Video Stream"),+ ),+ ]diff --git a/src/hi/apps/entity/migrations/0007_video_stream_data_migration.py b/src/hi/apps/entity/migrations/0007_video_stream_data_migration.pynew file mode 100644index 00000000..dc79ece4--- /dev/null+++ b/src/hi/apps/entity/migrations/0007_video_stream_data_migration.py@@ -0,0 +1,84 @@+# Data migration for Issue #106 - VideoStream Infrastructure Refactor+# Migrates existing data from VIDEO_STREAM EntityStates to new VideoStream model++from django.db import migrations+++def migrate_video_stream_data(apps, schema_editor):+ """+ Migrate existing VIDEO_STREAM data to new VideoStream infrastructure:+ 1. Set has_video_stream=True for ZoneMinder camera entities+ 2. Set provides_video_stream=True for MOVEMENT sensors in ZM entities+ 3. Delete VIDEO_STREAM sensors+ 4. Delete VIDEO_STREAM EntityStates+ """+ Entity = apps.get_model('entity', 'Entity')+ EntityState = apps.get_model('entity', 'EntityState')+ Sensor = apps.get_model('sense', 'Sensor')++ # 1. Update ZoneMinder camera entities to have video capability+ zm_cameras = Entity.objects.filter(+ integration_id='zm',+ entity_type_str='camera' # Lowercase string value per LabeledEnum+ )+ updated_count = zm_cameras.update(has_video_stream=True)+ print(f"Updated {updated_count} ZoneMinder camera entities with has_video_stream=True")++ # 2. Update MOVEMENT sensors for ZM entities to provide video streams+ movement_sensors = Sensor.objects.filter(+ entity_state__entity_state_type_str='movement', # Lowercase string value+ entity_state__entity__integration_id='zm'+ )+ sensor_count = movement_sensors.update(provides_video_stream=True)+ print(f"Updated {sensor_count} MOVEMENT sensors with provides_video_stream=True")++ # 3. Delete VIDEO_STREAM sensors (CASCADE will handle SensorHistory)+ video_stream_sensors = Sensor.objects.filter(+ entity_state__entity_state_type_str='video_stream' # Lowercase string value+ )+ video_sensor_count = video_stream_sensors.count()+ if video_sensor_count > 0:+ video_stream_sensors.delete()+ print(f"Deleted {video_sensor_count} VIDEO_STREAM sensors")++ # 4. Delete VIDEO_STREAM EntityStates (CASCADE will handle delegations)+ video_stream_states = EntityState.objects.filter(+ entity_state_type_str='video_stream' # Lowercase string value+ )+ video_state_count = video_stream_states.count()+ if video_state_count > 0:+ video_stream_states.delete()+ print(f"Deleted {video_state_count} VIDEO_STREAM EntityStates")++ # Summary+ print(f"Migration complete: {updated_count} cameras updated, "+ f"{sensor_count} sensors updated, "+ f"{video_sensor_count} video sensors deleted, "+ f"{video_state_count} video states deleted")+++def reverse_migration(apps, schema_editor):+ """+ This migration cannot be reversed because:+ 1. VIDEO_STREAM enum value no longer exists in the code+ 2. Deleted data cannot be reconstructed programmatically+ """+ raise NotImplementedError(+ "This migration cannot be reversed. The VIDEO_STREAM EntityStateType "+ "no longer exists and deleted data cannot be reconstructed."+ )+++class Migration(migrations.Migration):++ dependencies = [+ ('entity', '0006_entity_has_video_stream'),+ ('sense', '0005_sensor_provides_video_stream'),+ ]++ operations = [+ migrations.RunPython(+ migrate_video_stream_data,+ reverse_migration+ ),+ ]diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.pyindex 08e7817c..c178a74a 100644--- a/src/hi/apps/entity/models.py+++ b/src/hi/apps/entity/models.py@@ -51,6 +51,10 @@ class Entity( IntegrationDetailsModel, LocationItemModelMixin ):'User Delete?',default = True,)+ has_video_stream = models.BooleanField(+ 'Has Video Stream',+ default = False,+ )created_datetime = models.DateTimeField('Created',auto_now_add = True,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.htmlindex 76da06be..8fef83b8 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@@ -10,12 +10,10 @@{% if sensor_history_list_map %}<div>{% for sensor, sensor_history_list in sensor_history_list_map.items %}- {% if not sensor.entity_state.entity_state_type.suppress_history %}<div><div class="h5">{{ sensor.name }} <small class="text-muted">[sensor]</small></div>{% include "sense/panes/sensor_history_list.html" with sensor_history_list=sensor_history_list show_all_link=True %}</div>- {% endif %}{% endfor %}</div>{% endif %}@@ -23,12 +21,10 @@{% if controller_history_list_map %}<div>{% for controller, controller_history_list in controller_history_list_map.items %}- {% if not controller.entity_state.entity_state_type.suppress_history %}<div><div class="h5">{{ controller.name }} <small class="text-muted">[controller]</small></div>{% include "control/panes/controller_history_list.html" with controller_history_list=controller_history_list show_all_link=True %}</div>- {% endif %}{% endfor %}</div>{% endif %}diff --git a/src/hi/apps/entity/templates/entity/modals/entity_status.html b/src/hi/apps/entity/templates/entity/modals/entity_status.htmlindex c352ca06..b3165cbc 100644--- a/src/hi/apps/entity/templates/entity/modals/entity_status.html+++ b/src/hi/apps/entity/templates/entity/modals/entity_status.html@@ -1,10 +1,15 @@{% extends "modals/action_3.html" %}+{% load video_tags %}{% block title_text %}{{ entity.name }}: Status{% endblock %}{% block body %}+{% if entity_for_video %}+{% include "console/panes/entity_video_stream.html" with entity=entity_for_video %}+{% endif %}+{% include "entity/panes/entity_state_status_card.html" with entity_state_status_data_list=entity_state_status_data_list %}{% endblock %}diff --git a/src/hi/apps/entity/templates/entity/panes/entity_state_status_card.html b/src/hi/apps/entity/templates/entity/panes/entity_state_status_card.htmlindex 4bb45059..52afe43a 100644--- a/src/hi/apps/entity/templates/entity/panes/entity_state_status_card.html+++ b/src/hi/apps/entity/templates/entity/panes/entity_state_status_card.html@@ -21,11 +21,9 @@{% endif %}</div>- {% if not entity_state_status_data.entity_state.entity_state_type.suppress_display_name %}<div class="align-self-center">{{ entity_state_status_data.entity_state.name }}</div>- {% endif %}</div>{% empty %}diff --git a/src/hi/apps/entity/tests/test_enums.py b/src/hi/apps/entity/tests/test_enums.pyindex 8811fa17..a838ad7a 100644--- a/src/hi/apps/entity/tests/test_enums.py+++ b/src/hi/apps/entity/tests/test_enums.py@@ -35,40 +35,9 @@ class TestEntityStateType(BaseTestCase):self.assertNotEqual(temperature_template, controller_template)# Complex state types should work correctly- video_template = EntityStateType.VIDEO_STREAM.value_template_name()- self.assertTrue(video_template.startswith('sense/panes/sensor_value_'))- self.assertIn('video_stream', video_template)-- return-- def test_suppression_rules_optimize_ui_for_different_state_types(self):- """Test suppress display/history logic - optimizes UI based on state characteristics."""- # Video streams should suppress certain UI elements for performance- video_state = EntityStateType.VIDEO_STREAM- self.assertTrue(video_state.suppress_display_name)- self.assertTrue(video_state.suppress_history)-- # Standard state types should show full UI- standard_states = [- EntityStateType.ON_OFF,- EntityStateType.TEMPERATURE,- EntityStateType.CONNECTIVITY,- EntityStateType.MOVEMENT- ]-- for state_type in standard_states:- # These states should display names and maintain history- self.assertFalse(state_type.suppress_display_name,- f"{state_type} should show display name")- self.assertFalse(state_type.suppress_history,- f"{state_type} should maintain history")-- # Test that suppression is consistent for same state type- another_video_check = EntityStateType.VIDEO_STREAM- self.assertEqual(video_state.suppress_display_name,- another_video_check.suppress_display_name)- self.assertEqual(video_state.suppress_history,- another_video_check.suppress_history)+ multivalued_template = EntityStateType.MULTVALUED.value_template_name()+ self.assertTrue(multivalued_template.startswith('sense/panes/sensor_value_'))+ self.assertIn('multvalued', multivalued_template)returndiff --git a/src/hi/apps/entity/transient_models.py b/src/hi/apps/entity/transient_models.pyindex 35f987e6..541a0fc4 100644--- a/src/hi/apps/entity/transient_models.py+++ b/src/hi/apps/entity/transient_models.py@@ -1,11 +1,11 @@from dataclasses import dataclass, field-from typing import Dict, List+from typing import Any, Dict, Listfrom hi.apps.control.models import Controller, ControllerHistoryfrom hi.apps.entity.edit.forms import EntityPositionFormfrom hi.apps.sense.models import Sensor, SensorHistory-from .enums import EntityGroupType, EntityPairingType+from .enums import EntityGroupType, EntityPairingType, VideoStreamTypefrom .forms import (EntityAttributeFormSet,EntityForm,@@ -14,6 +14,19 @@ from .forms import (from .models import Entity+@dataclass+class VideoStream:+ """Represents a video stream from any source"""+ stream_type: VideoStreamType+ source_url: str = None+ metadata: Dict[str, Any] = field(default_factory=dict)++ # Future extensibility:+ # webrtc_config: WebRTCConfig = None+ # hls_manifest_url: str = None+ # thumbnail_url: str = None++@dataclassclass EntityViewItem:diff --git a/src/hi/apps/event/tests/test_event_manager.py b/src/hi/apps/event/tests/test_event_manager.pyindex b30c8edb..9b333595 100644--- a/src/hi/apps/event/tests/test_event_manager.py+++ b/src/hi/apps/event/tests/test_event_manager.py@@ -29,7 +29,7 @@ def create_test_sensor_response(value, timestamp, detail_attrs=None):value=value,timestamp=timestamp,detail_attrs=detail_attrs or {},- image_url=None+ source_image_url=None)diff --git a/src/hi/apps/event/transient_models.py b/src/hi/apps/event/transient_models.pyindex cb82e952..988b3499 100644--- a/src/hi/apps/event/transient_models.py+++ b/src/hi/apps/event/transient_models.py@@ -3,7 +3,7 @@ from datetime import datetimefrom typing import Listfrom hi.apps.alert.enums import AlarmSource-from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+from hi.apps.alert.alarm import Alarmfrom hi.apps.entity.models import EntityStatefrom hi.apps.sense.transient_models import SensorResponse@@ -40,23 +40,13 @@ class Event:)def to_alarm( self, alarm_action : AlarmAction ) -> Alarm:-- source_details_list = list()- for sensor_response in self.sensor_response_list:- source_details = AlarmSourceDetails(- detail_attrs = sensor_response.detail_attrs,- image_url = sensor_response.image_url,- sensor_id = sensor_response.sensor.id if sensor_response.sensor else None,- )- source_details_list.append( source_details )- continuereturn Alarm(alarm_source = AlarmSource.EVENT,alarm_type = self.event_definition.event_type.label,alarm_level = alarm_action.alarm_level,title = self.event_definition.name,- source_details_list = source_details_list,+ sensor_response_list = self.sensor_response_list,security_level = alarm_action.security_level,alarm_lifetime_secs = alarm_action.alarm_lifetime_secs,timestamp = self.timestamp,diff --git a/src/hi/apps/model_helper.py b/src/hi/apps/model_helper.pyindex 5b89f7a0..3f938223 100644--- a/src/hi/apps/model_helper.py+++ b/src/hi/apps/model_helper.py@@ -26,7 +26,6 @@ class HiModelHelper:EXCLUDE_FROM_SENSOR_HISTORY = {EntityStateType.DATETIME,- EntityStateType.VIDEO_STREAM,EntityStateType.BLOB,EntityStateType.MULTVALUED,}@@ -195,9 +194,10 @@ class HiModelHelper:@classmethoddef create_movement_sensor( cls,- entity : Entity,- integration_key : IntegrationKey = None,- name : str = None ) -> Sensor:+ entity : Entity,+ integration_key : IntegrationKey = None,+ name : str = None,+ provides_video_stream : bool = False ) -> Sensor:if not name:name = f'{entity.name} Motion'return cls.create_sensor(@@ -205,20 +205,7 @@ class HiModelHelper:entity_state_type = EntityStateType.MOVEMENT,name = name,integration_key = integration_key,- )-- @classmethod- def create_video_stream_sensor( cls,- entity : Entity,- integration_key : IntegrationKey = None,- name : str = None ) -> Sensor:- if not name:- name = f'{entity.name} Stream'- return cls.create_sensor(- entity = entity,- entity_state_type = EntityStateType.VIDEO_STREAM,- name = name,- integration_key = integration_key,+ provides_video_stream = provides_video_stream,)@classmethod@@ -299,7 +286,8 @@ class HiModelHelper:sensor_type : SensorType = SensorType.DEFAULT,integration_key : IntegrationKey = None,value_range_str : str = '',- units : str = None ) -> Sensor:+ units : str = None,+ provides_video_stream : bool = False ) -> Sensor:if not name:name = f'{entity.name}'@@ -315,6 +303,7 @@ class HiModelHelper:name = name,sensor_type_str = str( sensor_type ),persist_history = bool( entity_state_type not in cls.EXCLUDE_FROM_SENSOR_HISTORY ),+ provides_video_stream = provides_video_stream,)sensor.integration_key = integration_keysensor.save()diff --git a/src/hi/apps/monitor/status_display_manager.py b/src/hi/apps/monitor/status_display_manager.pyindex 57ed907b..6a19cdba 100644--- a/src/hi/apps/monitor/status_display_manager.py+++ b/src/hi/apps/monitor/status_display_manager.py@@ -97,9 +97,16 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):# The set of entity states used to define the state includes the# principals when the entity is a delegate.#+ entity_for_video = None+ if entity.has_video_stream:+ entity_for_video = entity+entity_state_set = set( entity.states.all() )for entity_state_delegation in entity.entity_state_delegations.all():entity_state_set.add( entity_state_delegation.entity_state )+ if ( not entity_for_video+ and entity_state_delegation.entity_state.entity.has_video_stream ):+ entity_for_video = entity_state_delegation.entity_state.entitycontinueentity_state_to_status_data = self._get_entity_state_to_entity_state_status_data(@@ -108,6 +115,7 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):return EntityStatusData(entity = entity,entity_state_status_data_list = list( entity_state_to_status_data.values() ),+ entity_for_video = entity_for_video,)def get_entity_status_data_list(diff --git a/src/hi/apps/monitor/transient_models.py b/src/hi/apps/monitor/transient_models.pyindex 846f5955..9b2d57d6 100644--- a/src/hi/apps/monitor/transient_models.py+++ b/src/hi/apps/monitor/transient_models.py@@ -24,12 +24,19 @@ class EntityStateStatusData:class EntityStatusData:entity : Entityentity_state_status_data_list : List[ EntityStateStatusData ]+ entity_for_video : Entity = Nonedisplay_only_svg_icon_item : SvgIconItem = None+ def __post_init__(self):+ if not self.entity_for_video:+ self.entity_for_video = self.entity+ return+def to_template_context(self):context = {'entity': self.entity,'entity_state_status_data_list': self.entity_state_status_data_list,+ 'entity_for_video': self.entity_for_video,}return contextdiff --git a/src/hi/apps/sense/admin.py b/src/hi/apps/sense/admin.pyindex 13390644..bbc030bb 100644--- a/src/hi/apps/sense/admin.py+++ b/src/hi/apps/sense/admin.py@@ -40,7 +40,7 @@ class SensorHistoryAdmin(admin.ModelAdmin):'value','response_datetime','details',- 'image_url',+ 'source_image_url',)search_fields = ['sensor__name']diff --git a/src/hi/apps/sense/migrations/0005_sensor_provides_video_stream.py b/src/hi/apps/sense/migrations/0005_sensor_provides_video_stream.pynew file mode 100644index 00000000..b33eac76--- /dev/null+++ b/src/hi/apps/sense/migrations/0005_sensor_provides_video_stream.py@@ -0,0 +1,20 @@+# Generated by Django 4.2.22 on 2025-08-23 16:05++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("sense", "0004_alter_sensor_integration_payload"),+ ]++ operations = [+ migrations.AddField(+ model_name="sensor",+ name="provides_video_stream",+ field=models.BooleanField(+ default=False, verbose_name="Provides Video Stream"+ ),+ ),+ ]diff --git a/src/hi/apps/sense/migrations/0006_rename_image_url_to_source_image_url.py b/src/hi/apps/sense/migrations/0006_rename_image_url_to_source_image_url.pynew file mode 100644index 00000000..11a17a45--- /dev/null+++ b/src/hi/apps/sense/migrations/0006_rename_image_url_to_source_image_url.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.22 on 2025-08-23 21:52++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("sense", "0005_sensor_provides_video_stream"),+ ]++ operations = [+ migrations.RenameField(+ model_name="sensorhistory",+ old_name="image_url",+ new_name="source_image_url",+ ),+ ]diff --git a/src/hi/apps/sense/migrations/0007_add_has_video_stream_to_sensor_history.py b/src/hi/apps/sense/migrations/0007_add_has_video_stream_to_sensor_history.pynew file mode 100644index 00000000..7c39d49f--- /dev/null+++ b/src/hi/apps/sense/migrations/0007_add_has_video_stream_to_sensor_history.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.22 on 2025-08-24 16:22++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("sense", "0006_rename_image_url_to_source_image_url"),+ ]++ operations = [+ migrations.AddField(+ model_name="sensorhistory",+ name="has_video_stream",+ field=models.BooleanField(default=False, verbose_name="Has Video Stream"),+ ),+ ]diff --git a/src/hi/apps/sense/migrations/0008_backfill_zoneminder_has_video_stream.py b/src/hi/apps/sense/migrations/0008_backfill_zoneminder_has_video_stream.pynew file mode 100644index 00000000..cd280ccb--- /dev/null+++ b/src/hi/apps/sense/migrations/0008_backfill_zoneminder_has_video_stream.py@@ -0,0 +1,66 @@+# Generated by Django 4.2.22 on 2025-08-24 16:29++import json+from django.db import migrations+++def backfill_zoneminder_video_streams(apps, schema_editor):+ """+ Set has_video_stream=True for existing ZoneMinder SensorHistory records+ that have an 'Event Id' in their details JSON.+ """+ SensorHistory = apps.get_model('sense', 'SensorHistory')++ # Find all ZoneMinder sensor history records with Event Id in details+ zm_records = SensorHistory.objects.filter(+ sensor__integration_id='zm',+ details__isnull=False+ ).exclude(details='')++ updated_count = 0++ for record in zm_records:+ try:+ # Parse the details JSON+ details_dict = json.loads(record.details)++ # Check if it has an Event Id (ZoneMinder's video stream indicator)+ if 'Event Id' in details_dict:+ record.has_video_stream = True+ record.save(update_fields=['has_video_stream'])+ updated_count += 1++ except (json.JSONDecodeError, TypeError):+ # Skip records with invalid JSON+ continue++ print(f"Updated {updated_count} ZoneMinder sensor history records with has_video_stream=True")+++def reverse_backfill_zoneminder_video_streams(apps, schema_editor):+ """+ Reverse the migration by setting has_video_stream back to False+ for ZoneMinder records.+ """+ SensorHistory = apps.get_model('sense', 'SensorHistory')++ updated_count = SensorHistory.objects.filter(+ sensor__integration_id='zm',+ has_video_stream=True+ ).update(has_video_stream=False)++ print(f"Reverted {updated_count} ZoneMinder sensor history records to has_video_stream=False")+++class Migration(migrations.Migration):++ dependencies = [+ ("sense", "0007_add_has_video_stream_to_sensor_history"),+ ]++ operations = [+ migrations.RunPython(+ backfill_zoneminder_video_streams,+ reverse_backfill_zoneminder_video_streams+ ),+ ]diff --git a/src/hi/apps/sense/models.py b/src/hi/apps/sense/models.pyindex b5b24c96..ae085a7a 100644--- a/src/hi/apps/sense/models.py+++ b/src/hi/apps/sense/models.py@@ -35,6 +35,10 @@ class Sensor( IntegrationDetailsModel ):'Persist History',default = True,)+ provides_video_stream = models.BooleanField(+ 'Provides Video Stream',+ default = False,+ )class Meta:verbose_name = 'Sensor'@@ -82,10 +86,14 @@ class SensorHistory(models.Model):'Details',blank = True, null = True,)- image_url = models.TextField(+ source_image_url = models.TextField('Image URL',blank = True, null = True,)+ has_video_stream = models.BooleanField(+ 'Has Video Stream',+ default = False,+ )response_datetime = models.DateTimeField('Timestamp',db_index = True,diff --git a/src/hi/apps/sense/templates/sense/modals/sensor_history_details.html b/src/hi/apps/sense/templates/sense/modals/sensor_history_details.htmlindex f868164b..ab663607 100644--- a/src/hi/apps/sense/templates/sense/modals/sensor_history_details.html+++ b/src/hi/apps/sense/templates/sense/modals/sensor_history_details.html@@ -1,4 +1,5 @@{% extends "modals/action_ok.html" %}+{% load video_tags %}{% block title_text %}Sensor Response Details@@ -7,20 +8,23 @@ Sensor Response Details{% block body %}<div><div class="h4">{{ sensor_history.sensor.name }}</div>- {% if sensor_history.image_url %}- <div>- <img class="img-fluid" src="{{ sensor_history.image_url }}" alt="{{ alarm.title }}">- </div>+ {% if sensor_response and sensor_response.has_video_stream %}+ {% sensor_response_video_stream sensor_response as video_url %}+ {% if video_url %}+ <div>+ <img class="img-fluid" src="{{ video_url }}" alt="Sensor History">+ </div>+ {% endif %}{% endif %}<div class="table-responsive"><table class="table table-striped"><tbody>- {% for label, value in sensor_history.detail_attrs.items %}- <tr>- <th class="text-right">{{ label }}</th>- <td>{{ value }}</td>- </tr>- {% endfor %}+ {% for label, value in sensor_history.detail_attrs.items %}+ <tr>+ <th class="text-right">{{ label }}</th>+ <td>{{ value }}</td>+ </tr>+ {% endfor %}</tbody></table></div>diff --git a/src/hi/apps/sense/tests/test_sensor_history_manager.py b/src/hi/apps/sense/tests/test_sensor_history_manager.pyindex d55748c1..b570c8bb 100644--- a/src/hi/apps/sense/tests/test_sensor_history_manager.py+++ b/src/hi/apps/sense/tests/test_sensor_history_manager.py@@ -146,7 +146,7 @@ class AsyncSensorHistoryManagerTestCase(AsyncTaskTestCase):timestamp=timezone.make_aware(datetime(2023, 1, 1, 12, 0, 0)),sensor=self.sensor,detail_attrs={'key': 'value'},- image_url='http://example.com/image.jpg'+ source_image_url='http://example.com/image.jpg')history = response.to_sensor_history()@@ -154,7 +154,7 @@ class AsyncSensorHistoryManagerTestCase(AsyncTaskTestCase):self.assertEqual(history.sensor, self.sensor)self.assertEqual(len(history.value), 255) # Should be truncatedself.assertEqual(history.response_datetime, response.timestamp)- self.assertEqual(history.image_url, response.image_url)+ self.assertEqual(history.source_image_url, response.source_image_url)self.assertIn('key', history.detail_attrs)def test_get_latest_entity_sensor_history_direct_states(self):diff --git a/src/hi/apps/sense/tests/test_sensor_response.py b/src/hi/apps/sense/tests/test_sensor_response.pyindex 9b6f7b3f..3ecaf5b7 100644--- a/src/hi/apps/sense/tests/test_sensor_response.py+++ b/src/hi/apps/sense/tests/test_sensor_response.py@@ -50,7 +50,7 @@ class TestSensorResponse(BaseTestCase):self.assertEqual(response.timestamp, timestamp)self.assertIsNone(response.sensor)self.assertIsNone(response.detail_attrs)- self.assertIsNone(response.image_url)+ self.assertIsNone(response.source_image_url)def test_sensor_response_initialization_with_all_fields(self):"""Test SensorResponse initializes correctly with all optional fields."""@@ -63,7 +63,7 @@ class TestSensorResponse(BaseTestCase):timestamp=timestamp,sensor=self.sensor,detail_attrs=detail_attrs,- image_url='http://example.com/image.jpg'+ source_image_url='http://example.com/image.jpg')self.assertEqual(response.integration_key, self.integration_key)@@ -71,7 +71,7 @@ class TestSensorResponse(BaseTestCase):self.assertEqual(response.timestamp, timestamp)self.assertEqual(response.sensor, self.sensor)self.assertEqual(response.detail_attrs, detail_attrs)- self.assertEqual(response.image_url, 'http://example.com/image.jpg')+ self.assertEqual(response.source_image_url, 'http://example.com/image.jpg')def test_sensor_response_is_on_method_with_on_value(self):"""Test is_on method returns True for ON entity state value."""@@ -133,7 +133,7 @@ class TestSensorResponse(BaseTestCase):timestamp=timestamp,sensor=self.sensor,detail_attrs=detail_attrs,- image_url='http://example.com/image.jpg'+ source_image_url='http://example.com/image.jpg')result_dict = response.to_dict()@@ -143,7 +143,7 @@ class TestSensorResponse(BaseTestCase):self.assertEqual(result_dict['timestamp'], timestamp.isoformat())self.assertEqual(result_dict['sensor_id'], self.sensor.id)self.assertEqual(result_dict['detail_attrs'], detail_attrs)- self.assertEqual(result_dict['image_url'], 'http://example.com/image.jpg')+ self.assertEqual(result_dict['source_image_url'], 'http://example.com/image.jpg')def test_sensor_response_to_dict_conversion_with_none_fields(self):"""Test to_dict method handles None fields correctly."""@@ -162,7 +162,7 @@ class TestSensorResponse(BaseTestCase):self.assertEqual(result_dict['timestamp'], timestamp.isoformat())self.assertIsNone(result_dict['sensor_id'])self.assertIsNone(result_dict['detail_attrs'])- self.assertIsNone(result_dict['image_url'])+ self.assertIsNone(result_dict['source_image_url'])def test_sensor_response_str_representation_returns_json(self):"""Test __str__ method returns JSON representation."""@@ -194,7 +194,7 @@ class TestSensorResponse(BaseTestCase):timestamp=timestamp,sensor=self.sensor,detail_attrs=detail_attrs,- image_url='http://example.com/image.jpg'+ source_image_url='http://example.com/image.jpg')history = response.to_sensor_history()@@ -204,7 +204,7 @@ class TestSensorResponse(BaseTestCase):self.assertEqual(history.value, 'test_value')self.assertEqual(history.response_datetime, timestamp)self.assertEqual(history.details, json.dumps(detail_attrs))- self.assertEqual(history.image_url, 'http://example.com/image.jpg')+ self.assertEqual(history.source_image_url, 'http://example.com/image.jpg')def test_sensor_response_to_sensor_history_value_truncation(self):"""Test to_sensor_history truncates value to 255 characters."""@@ -248,7 +248,7 @@ class TestSensorResponse(BaseTestCase):value='test_value',response_datetime=timestamp,details=json.dumps(detail_attrs),- image_url='http://example.com/image.jpg'+ source_image_url='http://example.com/image.jpg')response = SensorResponse.from_sensor_history(history)@@ -258,7 +258,7 @@ class TestSensorResponse(BaseTestCase):self.assertEqual(response.timestamp, timestamp)self.assertEqual(response.sensor, self.sensor)self.assertEqual(response.detail_attrs, detail_attrs)- self.assertEqual(response.image_url, 'http://example.com/image.jpg')+ self.assertEqual(response.source_image_url, 'http://example.com/image.jpg')def test_sensor_response_from_string_deserialization(self):"""Test from_string class method correctly deserializes JSON string."""@@ -271,7 +271,7 @@ class TestSensorResponse(BaseTestCase):value='test_value',timestamp=timestamp,detail_attrs=detail_attrs,- image_url='http://example.com/image.jpg'+ source_image_url='http://example.com/image.jpg')# Serialize to string@@ -284,7 +284,7 @@ class TestSensorResponse(BaseTestCase):self.assertEqual(deserialized_response.value, 'test_value')self.assertEqual(deserialized_response.timestamp, timestamp)self.assertEqual(deserialized_response.detail_attrs, detail_attrs)- self.assertEqual(deserialized_response.image_url, 'http://example.com/image.jpg')+ self.assertEqual(deserialized_response.source_image_url, 'http://example.com/image.jpg')# Note: sensor is not included in serializationdef test_sensor_response_serialization_roundtrip_integrity(self):@@ -297,7 +297,7 @@ class TestSensorResponse(BaseTestCase):value='complex_value',timestamp=timestamp,detail_attrs=detail_attrs,- image_url='http://example.com/complex/path.jpg'+ source_image_url='http://example.com/complex/path.jpg')# Full roundtrip: to_dict -> JSON -> from_string@@ -310,14 +310,14 @@ class TestSensorResponse(BaseTestCase):value=parsed_dict['value'],timestamp=datetime.fromisoformat(parsed_dict['timestamp']),detail_attrs=parsed_dict['detail_attrs'],- image_url=parsed_dict['image_url']+ source_image_url=parsed_dict['source_image_url'])self.assertEqual(reconstructed_response.integration_key, original_response.integration_key)self.assertEqual(reconstructed_response.value, original_response.value)self.assertEqual(reconstructed_response.timestamp, original_response.timestamp)self.assertEqual(reconstructed_response.detail_attrs, original_response.detail_attrs)- self.assertEqual(reconstructed_response.image_url, original_response.image_url)+ self.assertEqual(reconstructed_response.source_image_url, original_response.source_image_url)def test_sensor_response_handles_special_characters_in_value(self):"""Test SensorResponse correctly handles special characters and unicode."""@@ -362,7 +362,7 @@ class TestSensorResponse(BaseTestCase):value=history.value,response_datetime=history.response_datetime,details=history.details,- image_url=history.image_url+ source_image_url=history.source_image_url)recreated_response = SensorResponse.from_sensor_history(saved_history)diff --git a/src/hi/apps/sense/tests/test_sensor_response_manager.py b/src/hi/apps/sense/tests/test_sensor_response_manager.pyindex d9aada08..1de2511f 100644--- a/src/hi/apps/sense/tests/test_sensor_response_manager.py+++ b/src/hi/apps/sense/tests/test_sensor_response_manager.py@@ -207,7 +207,7 @@ class AsyncSensorResponseManagerTestCase(AsyncTaskTestCase):value='test_value',timestamp=timezone.make_aware(datetime(2023, 1, 1, 12, 0, 0)),detail_attrs={'key': 'value'},- image_url='http://example.com/image.jpg'+ source_image_url='http://example.com/image.jpg')# Serialize to string@@ -221,7 +221,7 @@ class AsyncSensorResponseManagerTestCase(AsyncTaskTestCase):self.assertEqual(deserialized.value, original_response.value)self.assertEqual(deserialized.timestamp, original_response.timestamp)self.assertEqual(deserialized.detail_attrs, original_response.detail_attrs)- self.assertEqual(deserialized.image_url, original_response.image_url)+ self.assertEqual(deserialized.source_image_url, original_response.source_image_url)def test_get_latest_sensor_responses_for_specific_sensors(self):"""Test retrieval of responses for specific sensor list."""diff --git a/src/hi/apps/sense/transient_models.py b/src/hi/apps/sense/transient_models.pyindex 2697c457..081cffe3 100644--- a/src/hi/apps/sense/transient_models.py+++ b/src/hi/apps/sense/transient_models.py@@ -12,12 +12,13 @@ from .models import Sensor, SensorHistory@dataclassclass SensorResponse:- integration_key : IntegrationKey- value : str- timestamp : datetime- sensor : Sensor = None- detail_attrs : Dict[ str, str ] = None- image_url : str = None+ integration_key : IntegrationKey+ value : str+ timestamp : datetime+ sensor : Sensor = None+ detail_attrs : Dict[ str, str ] = None+ source_image_url : str = None+ has_video_stream : bool = Falsedef __str__(self):return json.dumps( self.to_dict() )@@ -38,7 +39,8 @@ class SensorResponse:'timestamp': self.timestamp.isoformat(),'sensor_id': self.sensor.id if self.sensor else None,'detail_attrs': self.detail_attrs,- 'image_url': self.image_url,+ 'source_image_url': self.source_image_url,+ 'has_video_stream': self.has_video_stream,}def to_sensor_history(self):@@ -51,7 +53,8 @@ class SensorResponse:value = self.value[0:255],response_datetime = self.timestamp,details = details,- image_url = self.image_url,+ source_image_url = self.source_image_url,+ has_video_stream = self.has_video_stream,)@classmethod@@ -62,7 +65,8 @@ class SensorResponse:timestamp = sensor_history.response_datetime,sensor = sensor_history.sensor,detail_attrs = sensor_history.detail_attrs,- image_url = sensor_history.image_url,+ source_image_url = sensor_history.source_image_url,+ has_video_stream = sensor_history.has_video_stream,)@classmethod@@ -73,5 +77,6 @@ class SensorResponse:value = sensor_response_dict.get('value'),timestamp = datetime.fromisoformat( sensor_response_dict.get('timestamp') ),detail_attrs = sensor_response_dict.get('detail_attrs'),- image_url = sensor_response_dict.get('image_url'),+ source_image_url = sensor_response_dict.get('source_image_url') or sensor_response_dict.get('image_url'),+ has_video_stream = sensor_response_dict.get('has_video_stream', False),)diff --git a/src/hi/apps/sense/views.py b/src/hi/apps/sense/views.pyindex 9fd3fc6b..ac0a10e9 100644--- a/src/hi/apps/sense/views.py+++ b/src/hi/apps/sense/views.py@@ -47,7 +47,17 @@ class SensorHistoryDetailsView( HiModalView, SenseViewMixin ):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:+ from .transient_models import SensorResponse+ 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,}return self.modal_response( request, context )diff --git a/src/hi/apps/weather/tests/test_weather_alert_alarm_mapper.py b/src/hi/apps/weather/tests/test_weather_alert_alarm_mapper.pyindex 309fb060..799a64a0 100644--- a/src/hi/apps/weather/tests/test_weather_alert_alarm_mapper.py+++ b/src/hi/apps/weather/tests/test_weather_alert_alarm_mapper.py@@ -260,8 +260,8 @@ class TestWeatherAlertAlarmMapper(BaseTestCase):self.assertEqual(alarm.security_level, SecurityLevel.OFF) # Applies to all security levels# Verify source details- self.assertEqual(len(alarm.source_details_list), 1)- details = alarm.source_details_list[0]+ self.assertEqual(len(alarm.sensor_response_list), 1)+ details = alarm.sensor_response_list[0]self.assertIn('Event Type', details.detail_attrs)self.assertIn('Severity', details.detail_attrs)self.assertIn('Affected Areas', details.detail_attrs)diff --git a/src/hi/apps/weather/tests/test_weather_alert_integration.py b/src/hi/apps/weather/tests/test_weather_alert_integration.pyindex 5c9ded66..2ed17c75 100644--- a/src/hi/apps/weather/tests/test_weather_alert_integration.py+++ b/src/hi/apps/weather/tests/test_weather_alert_integration.py@@ -85,8 +85,8 @@ class TestWeatherAlertIntegration(BaseTestCase):self.assertEqual(alarm.security_level.name, 'OFF') # Applies to all security levels# Verify alarm details contain weather info- self.assertEqual(len(alarm.source_details_list), 1)- details = alarm.source_details_list[0]+ self.assertEqual(len(alarm.sensor_response_list), 1)+ details = alarm.sensor_response_list[0]self.assertEqual(details.detail_attrs['Event Type'], WeatherEventType.TORNADO.label)self.assertEqual(details.detail_attrs['Severity'], AlertSeverity.EXTREME.label)self.assertEqual(details.detail_attrs['Affected Areas'], "Travis County")diff --git a/src/hi/apps/weather/weather_alert_alarm_mapper.py b/src/hi/apps/weather/weather_alert_alarm_mapper.pyindex a0eae2aa..d05fd3f4 100644--- a/src/hi/apps/weather/weather_alert_alarm_mapper.py+++ b/src/hi/apps/weather/weather_alert_alarm_mapper.py@@ -14,11 +14,13 @@ import loggingfrom typing import List, Optionalimport hi.apps.common.datetimeproxy as datetimeproxy-from hi.apps.alert.alarm import Alarm, AlarmSourceDetails+from hi.apps.alert.alarm import Alarmfrom hi.apps.alert.enums import AlarmLevel, AlarmSourcefrom hi.apps.security.enums import SecurityLevel+from hi.apps.sense.transient_models import SensorResponsefrom hi.apps.weather.enums import AlertSeverity, AlertStatus, AlertUrgency, WeatherEventTypefrom hi.apps.weather.transient_models import WeatherAlert+from hi.integrations.transient_models import IntegrationKeylogger = logging.getLogger(__name__)@@ -298,15 +300,15 @@ class WeatherAlertAlarmMapper:# This ensures consistent grouping across different weather sourcesreturn weather_alert.event_type.name- def create_alarm_source_details(self, weather_alert: WeatherAlert) -> List[AlarmSourceDetails]:+ def create_sensor_responses(self, weather_alert: WeatherAlert) -> List[SensorResponse]:"""- Create alarm source details from weather alert information.+ Create sensor responses from weather alert information.Args:- weather_alert: The weather alert to create details for+ weather_alert: The weather alert to create sensor responses forReturns:- List of AlarmSourceDetails for this weather alert+ List of SensorResponse for this weather alert"""detail_attrs = {'Event Type': weather_alert.event_type.label,@@ -338,7 +340,24 @@ class WeatherAlertAlarmMapper:description = description[:300] + '...'detail_attrs['Description'] = description- return [AlarmSourceDetails(detail_attrs=detail_attrs)]+ # Create a SensorResponse for weather alerts+ # Weather alerts don't have sensors, so we use a synthetic integration key+ # Use event type and timestamp to create a unique identifier+ alert_id = f'{weather_alert.event_type.name}.{weather_alert.effective.timestamp() if weather_alert.effective else "unknown"}'+ integration_key = IntegrationKey(+ integration_id='weather',+ integration_name=f'alert.{alert_id}'+ )++ return [SensorResponse(+ integration_key=integration_key,+ value='active', # Weather alerts are active when they exist+ timestamp=weather_alert.effective or datetimeproxy.now(),+ sensor=None, # No sensor for weather alerts+ detail_attrs=detail_attrs,+ source_image_url=None, # Weather alerts don't have images+ has_video_stream=False+ )]def create_alarm(self, weather_alert: WeatherAlert) -> Optional[Alarm]:"""@@ -372,7 +391,7 @@ class WeatherAlertAlarmMapper:alarm_type=self.get_alarm_type(weather_alert),alarm_level=alarm_level,title=title,- source_details_list=self.create_alarm_source_details(weather_alert),+ sensor_response_list=self.create_sensor_responses(weather_alert),security_level=SecurityLevel.OFF, # Weather alarms apply to all security levelsalarm_lifetime_secs=self.get_alarm_lifetime(weather_alert),timestamp=datetimeproxy.now(),diff --git a/src/hi/integrations/integration_gateway.py b/src/hi/integrations/integration_gateway.pyindex bd500f91..0845d4ea 100644--- a/src/hi/integrations/integration_gateway.py+++ b/src/hi/integrations/integration_gateway.py@@ -1,4 +1,9 @@+from typing import Optional++from hi.apps.entity.models import Entity+from hi.apps.entity.transient_models import VideoStreamfrom hi.apps.monitor.periodic_monitor import PeriodicMonitor+from hi.apps.sense.transient_models import SensorResponsefrom .integration_controller import IntegrationControllerfrom .integration_manage_view_pane import IntegrationManageViewPane@@ -21,3 +26,25 @@ class IntegrationGateway:def get_controller(self) -> IntegrationController:raise NotImplementedError('Subclasses must override this method')++ def get_entity_video_stream(self, entity: Entity) -> Optional[VideoStream]:+ """Get entity's primary video stream (typically live)++ Args:+ entity: Entity instance to get video stream for++ Returns:+ VideoStream object or None if entity has no video stream+ """+ return None++ def get_sensor_response_video_stream(self, sensor_response: SensorResponse) -> Optional[VideoStream]:+ """Get video stream from sensor response (recorded events)++ Args:+ sensor_response: SensorResponse instance to get video stream for++ Returns:+ VideoStream object or None if sensor response has no video stream+ """+ return Nonediff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.pyindex 469353a4..ed270bc6 100644--- a/src/hi/services/hass/hass_converter.py+++ b/src/hi/services/hass/hass_converter.py@@ -216,7 +216,7 @@ class HassConverter:(HassApi.SENSOR_DOMAIN, None, None): EntityStateType.BLOB, # Generic sensor# Other domains (read-only)- (HassApi.CAMERA_DOMAIN, None, None): EntityStateType.VIDEO_STREAM,+ # Note: CAMERA_DOMAIN entities should have has_video_stream=True but no VIDEO_STREAM EntityState(HassApi.SUN_DOMAIN, None, None): EntityStateType.MULTVALUED,(HassApi.WEATHER_DOMAIN, None, None): EntityStateType.MULTVALUED,}@@ -856,12 +856,6 @@ class HassConverter:integration_key = integration_key,name = name,)- elif entity_state_type == EntityStateType.VIDEO_STREAM:- sensor = HiModelHelper.create_video_stream_sensor(- entity = entity,- integration_key = integration_key,- name = name,- )elif entity_state_type == EntityStateType.CONNECTIVITY:sensor = HiModelHelper.create_connectivity_sensor(entity = entity,@@ -1003,12 +997,6 @@ class HassConverter:integration_key = integration_key,name = name,)- elif entity_state_type == EntityStateType.VIDEO_STREAM:- sensor = HiModelHelper.create_video_stream_sensor(- entity = entity,- integration_key = integration_key,- name = name,- )elif entity_state_type == EntityStateType.ON_OFF:sensor = HiModelHelper.create_on_off_sensor(entity = entity,diff --git a/src/hi/services/hass/tests/test_hass_converter_mapping.py b/src/hi/services/hass/tests/test_hass_converter_mapping.pyindex d9cf5f95..7efe0c24 100644--- a/src/hi/services/hass/tests/test_hass_converter_mapping.py+++ b/src/hi/services/hass/tests/test_hass_converter_mapping.py@@ -268,7 +268,6 @@ class TestHassConverterMapping(TestCase):(HassApi.BINARY_SENSOR_DOMAIN, EntityStateType.MOVEMENT),(HassApi.BINARY_SENSOR_DOMAIN, EntityStateType.CONNECTIVITY),(HassApi.BINARY_SENSOR_DOMAIN, EntityStateType.ON_OFF),- (HassApi.CAMERA_DOMAIN, EntityStateType.VIDEO_STREAM),(HassApi.SUN_DOMAIN, EntityStateType.MULTVALUED),(HassApi.WEATHER_DOMAIN, EntityStateType.MULTVALUED),]diff --git a/src/hi/services/zoneminder/constants.py b/src/hi/services/zoneminder/constants.pynew file mode 100644index 00000000..96627d91--- /dev/null+++ b/src/hi/services/zoneminder/constants.py@@ -0,0 +1,15 @@+class ZmDetailKeys:+ """+ ZoneMinder detail_attrs keys used in SensorResponse objects.++ WARNING: These keys are persisted in the database and used across+ multiple integrations. Changing them will break compatibility with+ historical data and require data migration.+ """+ EVENT_ID_ATTR_NAME = 'Event Id' # DO NOT CHANGE - stored in database+ START_TIME = 'Start Time'+ SCORE = 'Score'+ DURATION_SECS = 'Duration (secs)'+ ALARMED_FRAMES = 'Alarmed Frames'+ TOTAL_FRAMES = 'Total Frames'+ NOTES = 'Notes'diff --git a/src/hi/services/zoneminder/integration.py b/src/hi/services/zoneminder/integration.pyindex a9a202b8..6749cf3c 100644--- a/src/hi/services/zoneminder/integration.py+++ b/src/hi/services/zoneminder/integration.py@@ -1,20 +1,27 @@import logging+from typing import Optional+from hi.apps.entity.models import Entity+from hi.apps.entity.transient_models import VideoStream+from hi.apps.entity.enums import VideoStreamType+from hi.apps.sense.transient_models import SensorResponsefrom hi.integrations.integration_controller import IntegrationControllerfrom hi.integrations.integration_gateway import IntegrationGatewayfrom hi.integrations.integration_manage_view_pane import IntegrationManageViewPanefrom hi.integrations.transient_models import IntegrationMetaDatafrom hi.apps.monitor.periodic_monitor import PeriodicMonitor+from .constants import ZmDetailKeysfrom .zm_controller import ZoneMinderControllerfrom .zm_manage_view_pane import ZmManageViewPanefrom .zm_metadata import ZmMetaDatafrom .monitors import ZoneMinderMonitor+from .zm_mixins import ZoneMinderMixinlogger = logging.getLogger(__name__)-class ZoneMinderGateway( IntegrationGateway ):+class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):def get_metadata(self) -> IntegrationMetaData:return ZmMetaData@@ -27,3 +34,53 @@ class ZoneMinderGateway( IntegrationGateway ):def get_controller(self) -> IntegrationController:return ZoneMinderController()++ def get_entity_video_stream(self, entity: Entity) -> Optional[VideoStream]:+ """Get entity's primary video stream (typically live)"""+ if not entity.has_video_stream:+ return None++ # Check if this is a ZoneMinder camera entity+ if (entity.integration_id == ZmMetaData.integration_id+ and entity.integration_name+ and entity.integration_name.startswith(self.zm_manager().ZM_MONITOR_INTEGRATION_NAME_PREFIX)):++ # Extract monitor ID from integration name (format: "monitor.{id}")+ try:+ monitor_id = int(entity.integration_name.split('.')[1])+ video_url = self.zm_manager().get_video_stream_url(monitor_id)++ return VideoStream(+ stream_type=VideoStreamType.URL,+ source_url=video_url,+ metadata={'monitor_id': monitor_id, 'stream_type': 'live'}+ )+ except (IndexError, ValueError):+ logger.warning(f"Could not parse monitor ID from entity integration name: {entity.integration_name}")++ return None++ def get_sensor_response_video_stream(self, sensor_response: SensorResponse) -> Optional[VideoStream]:+ """Get video stream from sensor response (recorded events)"""+ # if not sensor_response.has_video_stream:+ # return None++ event_id_fieldname = ZmDetailKeys.EVENT_ID_ATTR_NAME++ # Check if this sensor response has an event ID in its detail_attrs+ if (sensor_response.detail_attrs+ and event_id_fieldname in sensor_response.detail_attrs):++ try:+ event_id = int(sensor_response.detail_attrs[event_id_fieldname])+ video_url = self.zm_manager().get_event_video_stream_url(event_id)++ return VideoStream(+ stream_type=VideoStreamType.URL,+ source_url=video_url,+ metadata={event_id_fieldname: event_id, 'stream_type': 'recorded'}+ )+ except (ValueError, TypeError):+ logger.warning(f"Could not parse event ID from sensor response: {sensor_response.detail_attrs}")++ return Nonediff --git a/src/hi/services/zoneminder/monitors.py b/src/hi/services/zoneminder/monitors.pyindex b89809fb..d97d93b3 100644--- a/src/hi/services/zoneminder/monitors.py+++ b/src/hi/services/zoneminder/monitors.py@@ -10,6 +10,7 @@ from hi.apps.monitor.periodic_monitor import PeriodicMonitorfrom hi.apps.sense.sensor_response_manager import SensorResponseMixinfrom hi.apps.sense.transient_models import SensorResponse+from .constants import ZmDetailKeysfrom .zm_models import ZmEvent, AggregatedMonitorStatefrom .zm_manager import ZoneMinderManagerfrom .zm_mixins import ZoneMinderMixin@@ -265,12 +266,6 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )force_load = self.CACHING_DISABLED,)for zm_monitor in zm_monitors:- video_stream_sensor_response = self._create_video_stream_sensor_response(- zm_monitor = zm_monitor,- timestamp = current_poll_datetime,- )- sensor_response_map[video_stream_sensor_response.integration_key] = video_stream_sensor_response-function_sensor_response = self._create_monitor_function_sensor_response(zm_monitor = zm_monitor,timestamp = current_poll_datetime,@@ -303,7 +298,15 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )return sensor_response_map+ def _has_video_stream_capability(self, detail_attrs: dict = None) -> bool:+ """+ Determine if a SensorResponse should have video stream capability.+ For ZoneMinder, this means the response contains an Event ID.+ """+ return detail_attrs is not None and ZmDetailKeys.EVENT_ID_ATTR_NAME in detail_attrs+def _create_movement_active_sensor_response( self, zm_event : ZmEvent ):+ detail_attrs = zm_event.to_detail_attrs()return SensorResponse(integration_key = self.zm_manager()._to_integration_key(prefix = ZoneMinderManager.MOVEMENT_SENSOR_PREFIX,@@ -311,8 +314,9 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )),value = str(EntityStateValue.ACTIVE),timestamp = zm_event.start_datetime,- detail_attrs = zm_event.to_detail_attrs(),- image_url = self.zm_manager().get_event_video_stream_url( event_id = zm_event.event_id ),+ detail_attrs = detail_attrs,+ source_image_url = zm_event.image_url( self.zm_manager() ),+ has_video_stream = self._has_video_stream_capability(detail_attrs),)def _create_movement_idle_sensor_response( self, zm_event : ZmEvent ):@@ -323,6 +327,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )),value = str(EntityStateValue.IDLE),timestamp = zm_event.end_datetime,+ has_video_stream = False,)def _create_idle_sensor_response( self, zm_monitor : ZmMonitor, timestamp : datetime ):@@ -333,16 +338,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )),value = str(EntityStateValue.IDLE),timestamp = timestamp,- )-- def _create_video_stream_sensor_response( self, zm_monitor : ZmMonitor, timestamp : datetime ):- return SensorResponse(- integration_key = self.zm_manager()._to_integration_key(- prefix = ZoneMinderManager.VIDEO_STREAM_SENSOR_PREFIX,- zm_monitor_id = zm_monitor.id(),- ),- value = self.zm_manager().get_video_stream_url( monitor_id = zm_monitor.id() ),- timestamp = timestamp,+ has_video_stream = False,)def _create_monitor_function_sensor_response( self, zm_monitor : ZmMonitor, timestamp : datetime ):@@ -354,6 +350,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )),value = str( zm_monitor.function() ),timestamp = timestamp,+ has_video_stream = False,)def _create_run_state_sensor_response( self, run_state_name : str, timestamp : datetime ):@@ -361,5 +358,6 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )integration_key = self.zm_manager()._zm_run_state_integration_key(),value = run_state_name,timestamp = timestamp,+ has_video_stream = False,)diff --git a/src/hi/services/zoneminder/tests/test_zm_sync.py b/src/hi/services/zoneminder/tests/test_zm_sync.pyindex 3cb0c2af..659b3560 100644--- a/src/hi/services/zoneminder/tests/test_zm_sync.py+++ b/src/hi/services/zoneminder/tests/test_zm_sync.py@@ -568,14 +568,13 @@ class TestZoneMinderSynchronizerEntityCreation(TestCase):mock_create_controller.assert_called_once()@patch('hi.services.zoneminder.zm_sync.transaction.atomic')- @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_video_stream_sensor')@patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_sensor')@patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_discrete_controller')@patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_event_definition')@patch.object(Entity, 'save')def test_create_monitor_entity_creates_all_components(self, mock_save, mock_create_event,mock_create_controller, mock_create_movement,- mock_create_video, mock_atomic):+ mock_atomic):"""Test _create_monitor_entity creates all required sensors and controllers"""# Mock monitormock_monitor = Mock()@@ -584,13 +583,12 @@ class TestZoneMinderSynchronizerEntityCreation(TestCase):# Mock integration key generationentity_key = IntegrationKey(integration_id='zm', integration_name='monitor.123')- video_key = IntegrationKey(integration_id='zm', integration_name='monitor.video_stream.123')movement_key = IntegrationKey(integration_id='zm', integration_name='monitor.motion.123')function_key = IntegrationKey(integration_id='zm', integration_name='monitor.function.123')event_key = IntegrationKey(integration_id='zm', integration_name='monitor.motion.123')self.mock_manager._to_integration_key.side_effect = [- entity_key, video_key, movement_key, function_key, event_key+ entity_key, movement_key, function_key, event_key]# Mock movement sensor for event creation@@ -603,7 +601,6 @@ class TestZoneMinderSynchronizerEntityCreation(TestCase):self.synchronizer._create_monitor_entity(mock_monitor, result)# Should create all components- mock_create_video.assert_called_once()mock_create_movement.assert_called_once()mock_create_controller.assert_called_once()mock_create_event.assert_called_once()@@ -613,14 +610,13 @@ class TestZoneMinderSynchronizerEntityCreation(TestCase):mock_save.assert_called_once()@patch('hi.services.zoneminder.zm_sync.transaction.atomic')- @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_video_stream_sensor')@patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_sensor')@patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_discrete_controller')@patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_event_definition')@patch.object(Entity, 'save')def test_create_monitor_entity_skips_events_when_disabled(self, mock_save, mock_create_event,mock_create_controller, mock_create_movement,- mock_create_video, mock_atomic):+ mock_atomic):"""Test _create_monitor_entity skips event creation when alarm events disabled"""self.mock_manager.should_add_alarm_events = False@@ -643,7 +639,6 @@ class TestZoneMinderSynchronizerEntityCreation(TestCase):mock_create_event.assert_not_called()# Should still create other components- mock_create_video.assert_called_once()mock_create_movement.assert_called_once()mock_create_controller.assert_called_once()@@ -977,7 +972,6 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):# Verify IsActive is boolean-like stringself.assertIn(state['IsActive'], ['0', '1'])- @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_video_stream_sensor')@patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_sensor')@patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_discrete_controller')@patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_event_definition')@@ -985,7 +979,7 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):@patch.object(Entity, 'save')def test_create_monitor_entity_with_real_monitor_variations(self, mock_save, mock_atomic,mock_create_event, mock_create_controller,- mock_create_movement, mock_create_video):+ mock_create_movement):"""Test monitor entity creation with real monitor data variations"""# Test each real monitor configurationreal_monitors = self.create_mock_monitors_from_real_data()@@ -1008,7 +1002,6 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):for monitor in real_monitors:with self.subTest(monitor_name=monitor.name.return_value):mock_save.reset_mock()- mock_create_video.reset_mock()mock_create_movement.reset_mock()mock_create_controller.reset_mock()mock_create_event.reset_mock()@@ -1017,7 +1010,6 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):self.synchronizer._create_monitor_entity(monitor, result)# Should create all components for each monitor- mock_create_video.assert_called_once()mock_create_movement.assert_called_once()mock_create_controller.assert_called_once()mock_create_event.assert_called_once()diff --git a/src/hi/services/zoneminder/zm_manager.py b/src/hi/services/zoneminder/zm_manager.pyindex f4673d39..82769bac 100644--- a/src/hi/services/zoneminder/zm_manager.py+++ b/src/hi/services/zoneminder/zm_manager.py@@ -31,7 +31,6 @@ class ZoneMinderManager( Singleton ):ZM_ENTITY_NAME = 'ZoneMinder'ZM_SYSTEM_INTEGRATION_NAME = 'system'ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'- VIDEO_STREAM_SENSOR_PREFIX = 'monitor.video_stream'MOVEMENT_SENSOR_PREFIX = 'monitor.motion'MOVEMENT_EVENT_PREFIX = 'monitor.motion'MONITOR_FUNCTION_SENSOR_PREFIX = 'monitor.function'diff --git a/src/hi/services/zoneminder/zm_models.py b/src/hi/services/zoneminder/zm_models.pyindex 8807f824..e554f9bd 100644--- a/src/hi/services/zoneminder/zm_models.py+++ b/src/hi/services/zoneminder/zm_models.py@@ -7,6 +7,7 @@ from hi.apps.entity.enums import EntityStateValuefrom pyzm.helpers.Event import Event as ZmApiEvent+from .constants import ZmDetailKeysfrom .zm_manager import ZoneMinderManager@@ -105,7 +106,7 @@ class ZmEvent:def to_detail_attrs( self ) -> Dict[ str, str ]:return {- 'Event Id': self.event_id,+ ZmDetailKeys.EVENT_ID_ATTR_NAME: self.event_id,'Start Time': self.start_datetime.isoformat(),'Score': self.score,'Duration (secs)': self.duration_secs,diff --git a/src/hi/services/zoneminder/zm_sync.py b/src/hi/services/zoneminder/zm_sync.pyindex f5141075..f67eac37 100644--- a/src/hi/services/zoneminder/zm_sync.py+++ b/src/hi/services/zoneminder/zm_sync.py@@ -200,23 +200,18 @@ class ZoneMinderSynchronizer( ZoneMinderMixin, IntegrationSyncMixin ):name = zm_monitor.name(),entity_type_str = str(EntityType.CAMERA),can_user_delete = ZmMetaData.allow_entity_deletion,+ has_video_stream = True,)entity.integration_key = entity_integration_keyentity.save()- HiModelHelper.create_video_stream_sensor(- entity = entity,- integration_key = zm_manager._to_integration_key(- prefix = zm_manager.VIDEO_STREAM_SENSOR_PREFIX,- zm_monitor_id = zm_monitor.id(),- ),- )movement_sensor = HiModelHelper.create_movement_sensor(entity = entity,integration_key = zm_manager._to_integration_key(prefix = zm_manager.MOVEMENT_SENSOR_PREFIX,zm_monitor_id = zm_monitor.id(),),+ provides_video_stream = True,)HiModelHelper.create_discrete_controller(entity = entity,