Skip to content

Home Information - Your home, your data, organized.

Python

Added duration to video browse timline [#165] (#187)

Tony C436821a4155e
diff --git a/docs/dev/integrations/integration-guidelines.md b/docs/dev/integrations/integration-guidelines.md
index fe0c420b..f27083ff 100644
--- a/docs/dev/integrations/integration-guidelines.md
+++ b/docs/dev/integrations/integration-guidelines.md
@@ -4,6 +4,11 @@
Each integration is a Django app in the `hi/services` directory. The `hi.integration` app handles integration management and required interfaces.
+### Responsibility Boundaries
+
+
+he detail_attrs should be an opaque blob of data to main application. Only the integration populates or utiizes the data in here. It is the integration that created the SensorResponse object and it is only that level of objects that the application can access. For example, these SensorResponses get turned into Event objects with start and end times, so the Event object duration is the only place to get duration information. Though the Event duration is connected to the ZoneMinder durations, the Event object does not know or need to know this.
+
## Nomenclature
- **integration_id** - Unique identifier for each integration type
@@ -378,4 +383,4 @@ class ResilientIntegrationClient:
- Gateway implementation: [Gateway Implementation](gateway-implementation.md)
- External API standards: [External API Standards](external-api-standards.md)
- Weather integration: [Weather Integration](weather-integration.md)
-- Backend integration: [Backend Guidelines](../backend/backend-guidelines.md)
\ No newline at end of file
+- Backend integration: [Backend Guidelines](../backend/backend-guidelines.md)
diff --git a/src/hi/apps/alert/templates/alert/modals/alert_details.html b/src/hi/apps/alert/templates/alert/modals/alert_details.html
index 72465058..c0222465 100644
--- a/src/hi/apps/alert/templates/alert/modals/alert_details.html
+++ b/src/hi/apps/alert/templates/alert/modals/alert_details.html
@@ -46,18 +46,37 @@
<!-- 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 %}
+{% sensor_response_video_stream alert_visual_content.sensor_response as video_stream %}
+{% if video_stream and video_stream.source_url %}
<div class="row mb-3">
<div class="col-12">
<div class="card">
<div class="card-header bg-primary text-white">
<h6 class="mb-0">
- {% icon "camera" size="sm" css_class="hi-icon-left" %}Visual Content
+ {% icon "camera" size="sm" css_class="hi-icon-left" %}Video
</h6>
</div>
<div class="card-body p-2">
- <img class="img-fluid" src="{{ video_url }}" alt="{{ alert_visual_content.alarm.title }}">
+ <img class="img-fluid" src="{{ video_stream.source_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>
+ {% endif %}
+ </div>
+ </div>
+ </div>
+</div>
+{% elif alert_visual_content.source_image_url %}
+<!-- Fallback to snapshot image when video stream is not available -->
+<div class="row mb-3">
+ <div class="col-12">
+ <div class="card">
+ <div class="card-header bg-primary text-white">
+ <h6 class="mb-0">
+ {% icon "camera" size="sm" css_class="hi-icon-left" %}Image
+ </h6>
+ </div>
+ <div class="card-body p-2">
+ <img class="img-fluid" src="{{ alert_visual_content.source_image_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>
{% endif %}
@@ -75,7 +94,7 @@
<h6 class="mb-0">
<a class="text-white text-decoration-none" data-toggle="collapse" href="#videoSources"
role="button" aria-expanded="false" aria-controls="videoSources">
- {% icon "camera" size="sm" css_class="hi-icon-left" %}Visual Content ({{ video_source_count }} sources)
+ {% icon "camera" size="sm" css_class="hi-icon-left" %}Video Sources ({{ video_source_count }})
{% icon "play" size="sm" css_class="hi-icon-right" %}
</a>
</h6>
@@ -85,14 +104,14 @@
<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 %}
+ {% sensor_response_video_stream video_source.sensor_response as video_stream %}
+ {% if video_stream and video_stream.source_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 }}">
+ <img class="img-fluid" src="{{ video_stream.source_url }}" alt="Source {{ video_source.index }}">
</div>
</div>
{% endif %}
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.html
index 705fd656..c4c80791 100644
--- a/src/hi/apps/alert/templates/alert/panes/alarm_sensor_response.html
+++ b/src/hi/apps/alert/templates/alert/panes/alarm_sensor_response.html
@@ -2,10 +2,15 @@
{% load icons %}
<div>
{% if show_video_inline %}
- {% sensor_response_video_stream sensor_response as video_url %}
- {% if video_url %}
+ {% sensor_response_video_stream sensor_response as video_stream %}
+ {% if video_stream and video_stream.source_url %}
<div class="mb-2">
- <img class="img-fluid" src="{{ video_url }}" alt="{{ alarm.title }}">
+ <img class="img-fluid" src="{{ video_stream.source_url }}" alt="{{ alarm.title }}">
+ </div>
+ {% elif sensor_response.source_image_url %}
+ <!-- Fallback to image when video stream is not available -->
+ <div class="mb-2">
+ <img class="img-fluid" src="{{ sensor_response.source_image_url }}" alt="{{ alarm.title }}">
</div>
{% endif %}
{% endif %}
diff --git a/src/hi/apps/api/views.py b/src/hi/apps/api/views.py
index 5f7ab581..24f28799 100644
--- a/src/hi/apps/api/views.py
+++ b/src/hi/apps/api/views.py
@@ -11,6 +11,7 @@ from django.views.generic import View
from hi.apps.alert.alert_mixins import AlertMixin
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.config.settings_mixins import SettingsMixin
+from hi.apps.console.console_mixins import ConsoleMixin
from hi.apps.console.transient_view_manager import TransientViewManager
from hi.apps.monitor.status_display_manager import StatusDisplayManager
from hi.apps.security.security_mixins import SecurityMixin
@@ -20,7 +21,12 @@ from hi.testing.dev_injection import DevInjectionManager
logger = logging.getLogger(__name__)
-class StatusView( View, AlertMixin, SecurityMixin, SettingsMixin, WeatherMixin ):
+class StatusView( View,
+ ConsoleMixin,
+ AlertMixin,
+ SecurityMixin,
+ SettingsMixin,
+ WeatherMixin ):
ServerStartTimestampAttr = 'startTimestamp'
ServerTimestampAttr = 'timestamp'
@@ -57,6 +63,7 @@ class StatusView( View, AlertMixin, SecurityMixin, SettingsMixin, WeatherMixin )
)
id_replace_map = dict()
+ id_replace_map.update( self.console_manager().get_status_id_replace_map( request = request ) )
id_replace_map.update( self.security_manager().get_status_id_replace_map( request = request ) )
id_replace_map.update( self.weather_manager().get_status_id_replace_map( request = request ) )
diff --git a/src/hi/apps/console/console_manager.py b/src/hi/apps/console/console_manager.py
index 3a99e2b0..487e1e68 100644
--- a/src/hi/apps/console/console_manager.py
+++ b/src/hi/apps/console/console_manager.py
@@ -1,14 +1,20 @@
import logging
-from typing import List, Optional
+from typing import Dict, List, Optional
from cachetools import TTLCache
+from django.http import HttpRequest
+from django.template.loader import get_template
+
+from hi.constants import DIVID
+
from hi.apps.common.singleton import Singleton
from hi.apps.config.settings_mixins import SettingsMixin
from hi.apps.entity.entity_manager import EntityManager
from hi.apps.entity.models import Entity, EntityState
from hi.apps.entity.enums import EntityStateType
-
from hi.apps.sense.sensor_response_manager import SensorResponseMixin
+
+from .constants import ConsoleConstants
from .transient_models import CameraControlDisplayData
logger = logging.getLogger(__name__)
@@ -47,6 +53,15 @@ class ConsoleManager( Singleton, SettingsMixin, SensorResponseMixin ):
self._was_initialized = True
return
+ def get_status_id_replace_map( self, request : HttpRequest ) -> Dict[ str, str ]:
+
+ context = dict()
+ template = get_template( ConsoleConstants.DATETIME_HEADER_TEMPLATE_NAME )
+ datetime_header_html_str = template.render( context, request = request )
+ return {
+ DIVID['DATETIME_HEADER']: datetime_header_html_str,
+ }
+
def get_camera_control_display_list(self) -> List[CameraControlDisplayData]:
"""Get camera control display data with TTL caching."""
self.ensure_initialized()
diff --git a/src/hi/apps/console/constants.py b/src/hi/apps/console/constants.py
index 77f6b6d0..b3e883d1 100644
--- a/src/hi/apps/console/constants.py
+++ b/src/hi/apps/console/constants.py
@@ -1,4 +1,4 @@
class ConsoleConstants:
CONSOLE_LOCKED_SESSION_VAR = 'console_locked'
-
+ DATETIME_HEADER_TEMPLATE_NAME = 'console/panes/datetime_header.html'
diff --git a/src/hi/apps/console/templates/console/panes/datetime_header.html b/src/hi/apps/console/templates/console/panes/datetime_header.html
index c5079488..43005d2b 100644
--- a/src/hi/apps/console/templates/console/panes/datetime_header.html
+++ b/src/hi/apps/console/templates/console/panes/datetime_header.html
@@ -1,6 +1,6 @@
{% load tz %}
{% timezone USER_TIMEZONE %}
-<div class="datetime-header text-center my-2 border-bottom">
+<div id="{{ DIVID.DATETIME_HEADER }}" class="datetime-header text-center my-2 border-bottom">
<a class="plain text-black" href="{% url 'config_settings' %}">
<div class="">
{% now "l, F jS" %}
diff --git a/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html b/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html
index 792aade8..429f0457 100644
--- a/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html
+++ b/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html
@@ -65,8 +65,14 @@
aria-label="View event from {{ response.timestamp|localtime|date:'g:i A' }}{% if response.sensor_history_id == sensor_history_data.current_sensor_response.sensor_history_id %} - Currently viewing{% endif %}">
<div>
<span class="time">{{ response.timestamp|localtime|date:"g:i A" }}</span>
+ {% if response.has_video_stream %}
+ {% sensor_response_video_stream response as video_stream %}
+ {% if video_stream and video_stream.metadata.duration_secs %}
+ <small class="text-muted d-block duration">{{ video_stream.metadata.duration_secs|format_duration }}</small>
+ {% endif %}
+ {% endif %}
{% if response.sensor_history_id == sensor_history_data.current_sensor_response.sensor_history_id %}
- <small class="text-muted d-block" aria-current="page">→ Currently viewing</small>
+ <small class="text-muted d-block" aria-current="page">→ Showing</small>
{% endif %}
</div>
</a>
@@ -106,11 +112,17 @@
<!-- Video display area -->
<div class="video-container mb-3" role="img" aria-label="Event video playback">
- {% sensor_response_video_stream sensor_history_data.current_sensor_response as video_url %}
- {% if video_url %}
- <img class="img-fluid" src="{{ video_url }}" alt="Video recording from {{ sensor_history_data.current_sensor_response.timestamp|localtime|date:'F j, Y g:i A' }}" data-event-id="{{ sensor_history_data.current_sensor_response.sensor_history_id }}" onerror="this.style.display='none'; this.outerHTML='<div class=\'alert alert-warning text-center d-flex align-items-center justify-content-center\' style=\'min-height: 240px;\'><div><div class=\'mb-2\'>[VIDEO]</div><h6>Video No Longer Available</h6></div></div>'">
+ {% sensor_response_video_stream sensor_history_data.current_sensor_response as video_stream %}
+ {% if video_stream and video_stream.source_url %}
+ <img class="img-fluid" src="{{ video_stream.source_url }}" alt="Video recording from {{ sensor_history_data.current_sensor_response.timestamp|localtime|date:'F j, Y g:i A' }}" data-event-id="{{ sensor_history_data.current_sensor_response.sensor_history_id }}" onerror="this.style.display='none'; this.outerHTML='<div class=\'alert alert-warning text-center d-flex align-items-center justify-content-center\' style=\'min-height: 240px;\'><div><div class=\'mb-2\'>[VIDEO]</div><h6>Video No Longer Available</h6></div></div>'">
+ {% elif sensor_history_data.current_sensor_response.source_image_url %}
+ <!-- Fallback to image when video stream is not available -->
+ <img class="img-fluid" src="{{ sensor_history_data.current_sensor_response.source_image_url }}" alt="Image from {{ sensor_history_data.current_sensor_response.timestamp|localtime|date:'F j, Y g:i A' }}" data-event-id="{{ sensor_history_data.current_sensor_response.sensor_history_id }}">
+ <div class="text-center mt-2">
+ <small class="text-muted">Image - video may be processing</small>
+ </div>
{% else %}
- <!-- Fallback when no video stream is available -->
+ <!-- Fallback when no video stream or snapshot is available -->
<div class="video-placeholder d-flex align-items-center justify-content-center">
<div class="text-center">
<div class="video-placeholder-icon mb-3">
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.html
index 1afa2e30..f5f28675 100644
--- a/src/hi/apps/console/templates/console/panes/entity_video_stream.html
+++ b/src/hi/apps/console/templates/console/panes/entity_video_stream.html
@@ -1,7 +1,7 @@
{% load video_tags %}
-{% entity_video_stream entity as video_url %}
-{% if video_url %}
+{% entity_video_stream entity as video_stream %}
+{% if video_stream and video_stream.source_url %}
<div class="video-container">
- <img class="img-fluid" src="{{ video_url }}" alt="{{ entity.name }} Live Video">
+ <img class="img-fluid" src="{{ video_stream.source_url }}" alt="{{ entity.name }} Live Video">
</div>
{% endif %}
diff --git a/src/hi/apps/console/templatetags/video_tags.py b/src/hi/apps/console/templatetags/video_tags.py
index ccc8b013..ae0a83f0 100644
--- a/src/hi/apps/console/templatetags/video_tags.py
+++ b/src/hi/apps/console/templatetags/video_tags.py
@@ -1,6 +1,8 @@
import logging
from django import template
+from hi.apps.common.utils import get_humanized_secs
+
logger = logging.getLogger(__name__)
register = template.Library()
@@ -9,86 +11,108 @@ register = template.Library()
@register.simple_tag
def sensor_response_video_stream(sensor_response):
"""
- Get recorded video stream URL for a SensorResponse.
-
+ Get recorded video stream for a SensorResponse.
+
Args:
sensor_response: SensorResponse object
-
+
Returns:
- Video stream URL string or empty string if no video available
+ VideoStream object or None if no video available
"""
if not sensor_response or not sensor_response.has_video_stream:
- return ""
-
+ return None
+
try:
# Get the entity from the sensor response
if not sensor_response.sensor:
logger.debug("SensorResponse has no associated sensor")
- return ""
-
+ return None
+
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 ""
-
+ return None
+
# 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
-
+
+ if video_stream:
+ return video_stream
+
logger.debug("No video stream available for sensor response")
- return ""
-
+ return None
+
except Exception as e:
- logger.error(f"Error getting video URL for sensor response: {e}")
- return ""
+ logger.error(f"Error getting video stream for sensor response: {e}")
+ return None
@register.simple_tag
def entity_video_stream(entity):
"""
- Get entity live video stream URL for a entity object.
-
+ Get entity live video stream for an entity object.
+
Args:
entity: Entity object
-
+
Returns:
- Video stream URL string or empty string if no video available
+ VideoStream object or None if no video available
"""
if not entity:
- return ""
-
+ return None
+
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 ""
-
+ return None
+
# 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 ""
+ return None
# 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
-
+
+ if video_stream:
+ return video_stream
+
logger.debug(f"No video stream available for entity {entity.id}")
- return ""
+ return None
except Exception as e:
- logger.error(f"Error getting video URL for entity {entity.id}: {e}")
+ logger.error(f"Error getting video stream for entity {entity.id}: {e}")
+ return None
+
+
+def format_duration(duration_secs):
+ """
+ Format duration in seconds to a human-readable format using existing utility.
+
+ Args:
+ duration_secs: Duration in seconds (int or float)
+
+ Returns:
+ Formatted duration string using get_humanized_secs
+ """
+ if duration_secs is None:
+ return ""
+
+ try:
+ return get_humanized_secs(duration_secs)
+ except (ValueError, TypeError):
return ""
+
+
diff --git a/src/hi/apps/console/tests/test_integration_error_handling.py b/src/hi/apps/console/tests/test_integration_error_handling.py
index c12e2f98..aea459f0 100644
--- a/src/hi/apps/console/tests/test_integration_error_handling.py
+++ b/src/hi/apps/console/tests/test_integration_error_handling.py
@@ -8,6 +8,7 @@ from hi.apps.console.video_stream_browsing_helper import VideoStreamBrowsingHelp
from hi.apps.console.views import EntityVideoSensorHistoryView
from hi.apps.entity.models import Entity, EntityState
from hi.apps.sense.models import Sensor, SensorHistory
+from hi.apps.sense.tests.synthetic_data import SensorHistorySyntheticData
logging.disable(logging.CRITICAL)
@@ -152,18 +153,13 @@ class TestIntegrationErrorHandling(TransactionTestCase):
base_time = timezone.now()
batch_size = 1000 # Large enough to test memory handling
- # Create records in batches for efficiency
- records_to_create = []
- for i in range(batch_size):
- records_to_create.append(SensorHistory(
- sensor=self.video_sensor,
- value=f'memory_test_{i}',
- response_datetime=base_time - timezone.timedelta(minutes=i),
- has_video_stream=True,
- details=f'{{"memory_test": {i}}}'
- ))
-
- SensorHistory.objects.bulk_create(records_to_create)
+ # Create records efficiently using synthetic data helper
+ SensorHistorySyntheticData.create_bulk_sensor_history(
+ sensor=self.video_sensor,
+ count=batch_size,
+ base_time=base_time,
+ value_prefix='memory_test'
+ )
# Test that helper methods handle large datasets efficiently
result = VideoStreamBrowsingHelper.build_sensor_history_data_default(self.video_sensor)
@@ -203,11 +199,10 @@ class TestIntegrationErrorHandling(TransactionTestCase):
]
for i, test_time in enumerate(challenging_times):
- SensorHistory.objects.create(
+ SensorHistorySyntheticData.create_simple_sensor_history(
sensor=self.video_sensor,
value=f'timezone_edge_{i}',
response_datetime=test_time,
- has_video_stream=True,
details=f'{{"timezone_test": {i}}}'
)
@@ -228,15 +223,12 @@ class TestIntegrationErrorHandling(TransactionTestCase):
base_time = timezone.now()
# Create exactly 50 records (common pagination boundary)
- boundary_records = []
- for i in range(50):
- record = SensorHistory.objects.create(
- sensor=self.video_sensor,
- value=f'boundary_record_{i}',
- response_datetime=base_time - timezone.timedelta(minutes=i),
- has_video_stream=True
- )
- boundary_records.append(record)
+ boundary_records = SensorHistorySyntheticData.create_bulk_sensor_history(
+ sensor=self.video_sensor,
+ count=50,
+ base_time=base_time,
+ value_prefix='boundary_record'
+ )
# Test pagination at the exact boundary
result = VideoStreamBrowsingHelper.build_sensor_history_data_default(self.video_sensor)
diff --git a/src/hi/apps/console/tests/test_timeline_preservation.py b/src/hi/apps/console/tests/test_timeline_preservation.py
index f2787338..3b9ed488 100644
--- a/src/hi/apps/console/tests/test_timeline_preservation.py
+++ b/src/hi/apps/console/tests/test_timeline_preservation.py
@@ -6,6 +6,7 @@ from hi.apps.console.video_stream_browsing_helper import VideoStreamBrowsingHelp
from hi.apps.console.transient_models import EntitySensorHistoryData
from hi.apps.entity.models import Entity, EntityState
from hi.apps.sense.models import Sensor, SensorHistory
+from hi.apps.sense.enums import CorrelationRole
from hi.apps.sense.tests.synthetic_data import SensorHistorySyntheticData
logging.disable(logging.CRITICAL)
@@ -168,6 +169,8 @@ class TestTimelinePreservationLogic(TransactionTestCase):
value='active',
response_datetime=base_time.replace(hour=hour),
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
details='{"day": "today"}'
)
today_records.append(record)
@@ -179,9 +182,11 @@ class TestTimelinePreservationLogic(TransactionTestCase):
value='active',
response_datetime=yesterday,
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
details='{"day": "yesterday"}'
)
-
+
# Older records
old_time = base_time - timezone.timedelta(days=3)
old_record = SensorHistory.objects.create(
@@ -189,6 +194,8 @@ class TestTimelinePreservationLogic(TransactionTestCase):
value='active',
response_datetime=old_time,
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
details='{"day": "old"}'
)
@@ -236,6 +243,8 @@ class TestTimelinePreservationLogic(TransactionTestCase):
value=f'nav_test_{i}',
response_datetime=base_time - timezone.timedelta(hours=i),
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
details=f'{{"nav_order": "{i}"}}'
)
records.append(record)
@@ -274,6 +283,8 @@ class TestTimelinePreservationLogic(TransactionTestCase):
value=response.value,
response_datetime=response.timestamp,
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
details='{"timezone": "aware"}'
)
records.append(record)
diff --git a/src/hi/apps/console/tests/test_video_stream_browsing_helper.py b/src/hi/apps/console/tests/test_video_stream_browsing_helper.py
index 0f088c70..284186ea 100644
--- a/src/hi/apps/console/tests/test_video_stream_browsing_helper.py
+++ b/src/hi/apps/console/tests/test_video_stream_browsing_helper.py
@@ -11,6 +11,7 @@ from hi.apps.console.enums import VideoDispatchType
from hi.apps.entity.models import Entity, EntityState
from hi.apps.sense.models import Sensor, SensorHistory
from hi.apps.sense.transient_models import SensorResponse
+from hi.apps.sense.enums import CorrelationRole
from hi.integrations.transient_models import IntegrationKey
from django.core.exceptions import BadRequest
@@ -78,6 +79,8 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):
sensor=self.video_sensor,
value='active',
response_datetime=timezone.now(),
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
has_video_stream=True,
details='{"original": "data"}'
)
@@ -96,6 +99,8 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):
sensor=self.video_sensor,
value='active',
response_datetime=timezone.now(),
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
has_video_stream=True,
details='{"existing": "value", "duration": "120"}'
)
@@ -119,7 +124,9 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):
sensor=self.video_sensor,
value=f'value_{i}',
response_datetime=base_time - timezone.timedelta(hours=i),
- has_video_stream=True
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id=str(i),
+ has_video_stream=True,
)
records.append(record)
@@ -146,7 +153,9 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):
sensor=self.video_sensor,
value=f'value_{i}',
response_datetime=base_time - timezone.timedelta(hours=i),
- has_video_stream=True
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id=str(i),
+ has_video_stream=True,
)
records.append(record)
@@ -181,7 +190,9 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):
sensor=self.video_sensor,
value=f'value_{i}',
response_datetime=base_time - timezone.timedelta(hours=i),
- has_video_stream=True
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id=str(i),
+ has_video_stream=True,
)
records.append(record)
@@ -296,7 +307,9 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):
sensor=self.video_sensor,
value=f'value_{i}',
response_datetime=base_time - timezone.timedelta(hours=i),
- has_video_stream=True
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id=str(i),
+ has_video_stream=True,
)
records.append(record)
@@ -324,7 +337,9 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):
sensor=self.video_sensor,
value=f'value_{i}',
response_datetime=base_time - timezone.timedelta(hours=i),
- has_video_stream=True
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id=str(i),
+ has_video_stream=True,
)
records.append(record)
@@ -357,7 +372,9 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):
sensor=self.video_sensor,
value=f'value_{i}',
response_datetime=base_time - timezone.timedelta(hours=i),
- has_video_stream=True
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id=str(i),
+ has_video_stream=True,
)
result = VideoStreamBrowsingHelper.build_sensor_history_data(self.video_sensor)
@@ -386,7 +403,9 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):
sensor=self.video_sensor,
value=f'value_{i}',
response_datetime=base_time - timezone.timedelta(hours=i),
- has_video_stream=True
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id=str(i),
+ has_video_stream=True,
)
records.append(record)
@@ -426,7 +445,9 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):
sensor=self.video_sensor,
value=f'value_{i}',
response_datetime=base_time - timezone.timedelta(hours=i),
- has_video_stream=True
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id=str(i),
+ has_video_stream=True,
)
records.append(record)
@@ -464,7 +485,9 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):
sensor=self.video_sensor,
value=f'value_{i}',
response_datetime=base_time - timezone.timedelta(hours=i),
- has_video_stream=True
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id=str(i),
+ has_video_stream=True,
)
result = VideoStreamBrowsingHelper.build_sensor_history_data(
@@ -485,7 +508,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):
# Create entity with corrupted state (no sensors)
corrupted_entity = Entity.objects.create(
integration_id='test.corrupted',
- integration_name='test_integration',
+ integration_name='test_integration',
name='Corrupted Entity',
has_video_stream=True # Claims to have video but has no sensors
)
@@ -502,6 +525,8 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):
sensor=self.video_sensor,
value='test_value',
response_datetime=base_time,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='base_time',
has_video_stream=True
)
@@ -538,7 +563,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):
timestamp=same_timestamp, # Same timestamp for all
sensor=self.video_sensor,
detail_attrs={'sensor_history_id': str(1000 + i)},
- has_video_stream=True
+ has_video_stream=True,
)
sensor_responses.append(response)
@@ -568,6 +593,8 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):
sensor=self.video_sensor,
value='recent',
response_datetime=base_time,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='base_time',
has_video_stream=True
)
@@ -681,6 +708,8 @@ class TestVideoDispatchResult(TransactionTestCase):
sensor=self.video_sensor,
value='earlier_event',
response_datetime=earlier_time,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='earlier',
has_video_stream=True
)
@@ -688,6 +717,8 @@ class TestVideoDispatchResult(TransactionTestCase):
sensor=self.video_sensor,
value='later_event',
response_datetime=later_time,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='later',
has_video_stream=True
)
@@ -801,7 +832,9 @@ class TestVideoDispatchResult(TransactionTestCase):
sensor=self.video_sensor,
value='test_event',
response_datetime=base_time - timezone.timedelta(hours=1),
- has_video_stream=True
+ has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='integration_test'
)
# Test that helper methods work correctly
@@ -867,6 +900,8 @@ class TestTimezoneHandling(TransactionTestCase):
sensor=self.video_sensor,
value='event_july_14_cdt',
response_datetime=utc_time_1,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='utc1',
has_video_stream=True
)
@@ -874,6 +909,8 @@ class TestTimezoneHandling(TransactionTestCase):
sensor=self.video_sensor,
value='event_july_15_cdt',
response_datetime=utc_time_2,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='utc2',
has_video_stream=True
)
@@ -914,6 +951,8 @@ class TestTimezoneHandling(TransactionTestCase):
sensor=self.video_sensor,
value='before_dst',
response_datetime=utc_before,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='utc_before',
has_video_stream=True
)
@@ -921,6 +960,8 @@ class TestTimezoneHandling(TransactionTestCase):
sensor=self.video_sensor,
value='after_dst',
response_datetime=utc_after,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='utc_after',
has_video_stream=True
)
diff --git a/src/hi/apps/console/tests/test_view_url_utils.py b/src/hi/apps/console/tests/test_view_url_utils.py
index 4e385824..30101194 100644
--- a/src/hi/apps/console/tests/test_view_url_utils.py
+++ b/src/hi/apps/console/tests/test_view_url_utils.py
@@ -18,7 +18,7 @@ class TestViewUrlUtils(BaseTestCase):
# Create entity with video stream capability
self.video_entity = Entity.objects.create(
integration_id='test.camera.video',
- integration_name='test_integration',
+ integration_name='test_integration',
name='Video Camera',
entity_type_str='camera',
has_video_stream=True
diff --git a/src/hi/apps/console/tests/test_views.py b/src/hi/apps/console/tests/test_views.py
index 534f95b6..0a013cd8 100644
--- a/src/hi/apps/console/tests/test_views.py
+++ b/src/hi/apps/console/tests/test_views.py
@@ -12,6 +12,7 @@ from hi.apps.console.views import (
from hi.apps.console.transient_models import EntitySensorHistoryData
from hi.apps.entity.models import Entity, EntityState
from hi.apps.sense.models import Sensor, SensorHistory
+from hi.apps.sense.enums import CorrelationRole
from hi.testing.base_test_case import BaseTestCase
logging.disable(logging.CRITICAL)
@@ -129,6 +130,8 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):
value='active' if i % 2 == 0 else 'idle',
response_datetime=base_time - timezone.timedelta(hours=i),
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
details='{"test": "data"}'
)
self.sensor_history_records.append(record)
@@ -172,6 +175,8 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):
value=f'motion_detected_{i}',
response_datetime=base_time - timezone.timedelta(hours=i),
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
details=f'{{"event": "test_{i}", "confidence": 0.9}}'
)
test_records.append(record)
@@ -229,6 +234,8 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):
value=f'older_motion_{i}',
response_datetime=base_time - timezone.timedelta(hours=3 + i),
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
details=f'{{"event": "older_{i}", "confidence": 0.8}}'
)
older_records.append(record)
@@ -240,6 +247,8 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):
value=f'newer_motion_{i}',
response_datetime=base_time - timezone.timedelta(minutes=30 * i),
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
details=f'{{"event": "newer_{i}", "confidence": 0.9}}'
)
newer_records.append(record)
@@ -294,6 +303,8 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):
value=f'older_motion_{i}',
response_datetime=base_time - timezone.timedelta(hours=5 + i),
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
details=f'{{"event": "older_{i}", "confidence": 0.7}}'
)
older_records.append(record)
@@ -305,6 +316,8 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):
value=f'newer_motion_{i}',
response_datetime=base_time - timezone.timedelta(hours=2.5) + timezone.timedelta(minutes=15 * i),
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
details=f'{{"event": "newer_{i}", "confidence": 0.95}}'
)
newer_records.append(record)
@@ -377,6 +390,8 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):
value=f'inside_window_{i}',
response_datetime=base_time - timezone.timedelta(hours=2) + timezone.timedelta(minutes=20 * i),
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
details=f'{{"window_test": "record_{i}"}}'
)
window_records.append(record)
@@ -473,6 +488,8 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):
value='active',
response_datetime=timezone.now(),
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
details='invalid-json-format{not valid}'
)
@@ -567,6 +584,8 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):
value=f'large_dataset_record_{i}',
response_datetime=base_time - timezone.timedelta(minutes=i * 10),
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
details=f'{{"large_test": true, "index": {i}}}'
)
large_dataset.append(record)
@@ -612,6 +631,8 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):
value=f'same_time_{i}',
response_datetime=same_timestamp,
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id='test',
details=f'{{"same_timestamp_test": {i}}}'
)
diff --git a/src/hi/apps/console/video_stream_browsing_helper.py b/src/hi/apps/console/video_stream_browsing_helper.py
index 2b449f5f..8e6ccb73 100644
--- a/src/hi/apps/console/video_stream_browsing_helper.py
+++ b/src/hi/apps/console/video_stream_browsing_helper.py
@@ -105,9 +105,8 @@ class VideoStreamBrowsingHelper:
if preserve_window_bounds:
# Preserve existing timeline window - query records within bounds
start_time, end_time = preserve_window_bounds
- history_records = list(SensorHistory.objects.filter(
+ history_records = list(SensorHistory.objects.filter_video_browse().filter(
sensor=sensor,
- has_video_stream=True,
response_datetime__gte=start_time,
response_datetime__lte=end_time
).order_by('-response_datetime'))
@@ -124,9 +123,8 @@ class VideoStreamBrowsingHelper:
window_center_timestamp = start_time if history_records else None
elif center_record is None:
# No center record - get most recent records (default behavior)
- history_records = SensorHistory.objects.filter(
- sensor=sensor,
- has_video_stream=True
+ history_records = SensorHistory.objects.filter_video_browse().filter(
+ sensor=sensor
).order_by('-response_datetime')[:window_size]
has_older_records = len(history_records) == window_size
@@ -137,16 +135,14 @@ class VideoStreamBrowsingHelper:
half_window = window_size // 2
# Get records before center (older timestamps)
- before_records = list(SensorHistory.objects.filter(
+ before_records = list(SensorHistory.objects.filter_video_browse().filter(
sensor=sensor,
- has_video_stream=True,
response_datetime__lt=center_record.response_datetime
).order_by('-response_datetime')[:half_window])
- # Get records after center (newer timestamps)
- after_records = list(SensorHistory.objects.filter(
+ # Get records after center (newer timestamps)
+ after_records = list(SensorHistory.objects.filter_video_browse().filter(
sensor=sensor,
- has_video_stream=True,
response_datetime__gt=center_record.response_datetime
).order_by('response_datetime')[:half_window])
@@ -352,9 +348,8 @@ class VideoStreamBrowsingHelper:
return (None, None)
# Find previous record (older timestamp)
- prev_record = SensorHistory.objects.filter(
+ prev_record = SensorHistory.objects.filter_video_browse().filter(
sensor=sensor,
- has_video_stream=True,
response_datetime__lt=current_record.response_datetime
).order_by('-response_datetime').first()
@@ -363,9 +358,8 @@ class VideoStreamBrowsingHelper:
prev_sensor_response = cls.create_sensor_response_with_history_id(prev_record)
# Find next record (newer timestamp)
- next_record = SensorHistory.objects.filter(
+ next_record = SensorHistory.objects.filter_video_browse().filter(
sensor=sensor,
- has_video_stream=True,
response_datetime__gt=current_record.response_datetime
).order_by('response_datetime').first()
@@ -409,9 +403,8 @@ class VideoStreamBrowsingHelper:
pivot_time = timezone.make_aware(datetime.fromtimestamp(pivot_timestamp))
# Get events before the pivot time
- history_records = list(SensorHistory.objects.filter(
+ history_records = list(SensorHistory.objects.filter_video_browse().filter(
sensor = sensor,
- has_video_stream = True,
response_datetime__lt = pivot_time
).order_by('-response_datetime')[:50])
@@ -494,9 +487,8 @@ class VideoStreamBrowsingHelper:
pivot_time = timezone.make_aware(datetime.fromtimestamp(pivot_timestamp))
# Get 50 events after the pivot time (ordered chronologically, oldest first)
- history_records = list( SensorHistory.objects.filter(
+ history_records = list( SensorHistory.objects.filter_video_browse().filter(
sensor=sensor,
- has_video_stream=True,
response_datetime__gt=pivot_time
).order_by('response_datetime')[:50])
@@ -695,9 +687,8 @@ class VideoStreamBrowsingHelper:
pivot_datetime = timestamp
else:
pivot_datetime = timezone.make_aware(datetime.fromtimestamp(timestamp))
- return SensorHistory.objects.filter(
+ return SensorHistory.objects.filter_video_browse().filter(
sensor = sensor,
- has_video_stream = True,
response_datetime__lt = pivot_datetime
).exists()
@@ -708,9 +699,8 @@ class VideoStreamBrowsingHelper:
pivot_datetime = timestamp
else:
pivot_datetime = timezone.make_aware(datetime.fromtimestamp(timestamp))
- return SensorHistory.objects.filter(
+ return SensorHistory.objects.filter_video_browse().filter(
sensor = sensor,
- has_video_stream = True,
response_datetime__gt = pivot_datetime
).exists()
diff --git a/src/hi/apps/entity/constants.py b/src/hi/apps/entity/constants.py
new file mode 100644
index 00000000..c9059994
--- /dev/null
+++ b/src/hi/apps/entity/constants.py
@@ -0,0 +1,16 @@
+"""
+Constants for the entity app.
+"""
+
+
+class VideoStreamMetadataKeys:
+ """Standard metadata keys for VideoStream objects."""
+
+ # Core metadata fields
+ STREAM_MODE = 'stream_mode' # VideoStreamMode enum value (LIVE or RECORDED)
+ DURATION_SECS = 'duration_secs' # Duration in seconds for recorded content
+
+ # Future extensibility
+ # RESOLUTION = 'resolution' # e.g., "1920x1080"
+ # FPS = 'fps' # Frames per second
+ # BITRATE = 'bitrate' # Stream bitrate
diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.py
index ef66c73f..4bb837d3 100644
--- a/src/hi/apps/entity/enums.py
+++ b/src/hi/apps/entity/enums.py
@@ -299,12 +299,23 @@ class EntityPairingType(LabeledEnum):
DELEGATE = ( 'Delegate', '' )
+class VideoStreamMode(LabeledEnum):
+ """Mode of video stream - whether live or recorded."""
+
+ LIVE = ('Live', 'Live real-time video stream')
+ RECORDED = ('Recorded', 'Recorded video playback')
+
+ @classmethod
+ def default(cls):
+ return cls.LIVE
+
+
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
diff --git a/src/hi/apps/event/transient_models.py b/src/hi/apps/event/transient_models.py
index 988b3499..2daabf84 100644
--- a/src/hi/apps/event/transient_models.py
+++ b/src/hi/apps/event/transient_models.py
@@ -24,7 +24,7 @@ class EntityStateTransition:
@dataclass
class Event:
- """ This would be more preceisly described as an "Entity State Change Event" """
+ """ This would be more precisely described as an "Entity State Change Event" """
event_definition : EventDefinition
sensor_response_list : List[ SensorResponse ]
diff --git a/src/hi/apps/sense/admin.py b/src/hi/apps/sense/admin.py
index bbc030bb..c2b1f92d 100644
--- a/src/hi/apps/sense/admin.py
+++ b/src/hi/apps/sense/admin.py
@@ -40,6 +40,9 @@ class SensorHistoryAdmin(admin.ModelAdmin):
'value',
'response_datetime',
'details',
+ 'has_video_stream',
+ 'correlation_role_str',
+ 'correlation_id',
'source_image_url',
)
diff --git a/src/hi/apps/sense/enums.py b/src/hi/apps/sense/enums.py
index 93d479eb..8f1ec2b8 100644
--- a/src/hi/apps/sense/enums.py
+++ b/src/hi/apps/sense/enums.py
@@ -5,4 +5,14 @@ class SensorType(LabeledEnum):
DEFAULT = ( 'Default', '' ) # EntityState will define behavior
-
+
+class CorrelationRole(LabeledEnum):
+ """
+ Role of a sensor response in a correlated event sequence.
+ Used to identify start and end events that belong to the same logical event.
+ """
+
+ START = ( 'Start', 'Event start/beginning' )
+ END = ( 'End', 'Event end/completion' )
+
+
diff --git a/src/hi/apps/sense/migrations/0009_add_video_stream_duration_ms.py b/src/hi/apps/sense/migrations/0009_add_video_stream_duration_ms.py
new file mode 100644
index 00000000..7338aa8d
--- /dev/null
+++ b/src/hi/apps/sense/migrations/0009_add_video_stream_duration_ms.py
@@ -0,0 +1,20 @@
+# Generated by Django 4.2.24 on 2025-09-15 04:02
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("sense", "0008_backfill_zoneminder_has_video_stream"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="sensorhistory",
+ name="video_stream_duration_ms",
+ field=models.IntegerField(
+ blank=True, null=True, verbose_name="Video Stream Duration (ms)"
+ ),
+ ),
+ ]
diff --git a/src/hi/apps/sense/migrations/0010_replace_duration_with_correlation_fields.py b/src/hi/apps/sense/migrations/0010_replace_duration_with_correlation_fields.py
new file mode 100644
index 00000000..787d0145
--- /dev/null
+++ b/src/hi/apps/sense/migrations/0010_replace_duration_with_correlation_fields.py
@@ -0,0 +1,31 @@
+# Generated by Django 4.2.24 on 2025-09-15 15:22
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("sense", "0009_add_video_stream_duration_ms"),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ model_name="sensorhistory",
+ name="video_stream_duration_ms",
+ ),
+ migrations.AddField(
+ model_name="sensorhistory",
+ name="correlation_id",
+ field=models.CharField(
+ blank=True, max_length=32, null=True, verbose_name="Correlation ID"
+ ),
+ ),
+ migrations.AddField(
+ model_name="sensorhistory",
+ name="correlation_role_str",
+ field=models.CharField(
+ blank=True, max_length=32, null=True, verbose_name="Correlation Role"
+ ),
+ ),
+ ]
diff --git a/src/hi/apps/sense/models.py b/src/hi/apps/sense/models.py
index ae085a7a..dfc63447 100644
--- a/src/hi/apps/sense/models.py
+++ b/src/hi/apps/sense/models.py
@@ -6,7 +6,21 @@ from hi.apps.entity.models import EntityState
from hi.integrations.models import IntegrationDetailsModel
-from .enums import SensorType
+from .enums import SensorType, CorrelationRole
+
+
+class SensorHistoryManager(models.Manager):
+ def filter_video_browse(self):
+ """Return queryset filtered for video browsing - records with END
+ correlation role. We do this mostly because of the ZoneMinder
+ integration behavior where the video duration time is only known on
+ the end event.
+
+ If we did not filter at all, we would be getting the start and end
+ events for the same video stream and thus have duplicates
+ everywhere.
+ """
+ return self.filter(correlation_role_str=str(CorrelationRole.END))
class Sensor( IntegrationDetailsModel ):
@@ -72,6 +86,8 @@ class Sensor( IntegrationDetailsModel ):
class SensorHistory(models.Model):
+ objects = SensorHistoryManager()
+
sensor = models.ForeignKey(
Sensor,
related_name = 'history',
@@ -94,6 +110,16 @@ class SensorHistory(models.Model):
'Has Video Stream',
default = False,
)
+ correlation_role_str = models.CharField(
+ 'Correlation Role',
+ max_length = 32,
+ null = True, blank = True,
+ )
+ correlation_id = models.CharField(
+ 'Correlation ID',
+ max_length = 32,
+ null = True, blank = True,
+ )
response_datetime = models.DateTimeField(
'Timestamp',
db_index = True,
@@ -112,4 +138,14 @@ class SensorHistory(models.Model):
if self.details:
return json.loads( self.details )
return dict()
+
+ @property
+ def correlation_role(self) -> CorrelationRole:
+ if self.correlation_role_str:
+ return CorrelationRole.from_name_safe(self.correlation_role_str)
+ return None
+
+ @correlation_role.setter
+ def correlation_role(self, correlation_role: CorrelationRole):
+ self.correlation_role_str = str(correlation_role) if correlation_role else None
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.html
index ab663607..bf7d8f07 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
@@ -8,11 +8,23 @@ Sensor Response Details
{% block body %}
<div>
<div class="h4">{{ sensor_history.sensor.name }}</div>
- {% if sensor_response and sensor_response.has_video_stream %}
- {% sensor_response_video_stream sensor_response as video_url %}
- {% if video_url %}
+ {% if sensor_response %}
+ {% if sensor_response.has_video_stream %}
+ {% sensor_response_video_stream sensor_response as video_stream %}
+ {% if video_stream and video_stream.source_url %}
+ <div>
+ <img class="img-fluid" src="{{ video_stream.source_url }}" alt="Sensor History">
+ </div>
+ {% elif sensor_response.source_image_url %}
+ <!-- Fallback to image when video stream is not available -->
+ <div>
+ <img class="img-fluid" src="{{ sensor_response.source_image_url }}" alt="Sensor History">
+ </div>
+ {% endif %}
+ {% elif sensor_response.source_image_url %}
+ <!-- Show image when no video stream capability -->
<div>
- <img class="img-fluid" src="{{ video_url }}" alt="Sensor History">
+ <img class="img-fluid" src="{{ sensor_response.source_image_url }}" alt="Sensor History">
</div>
{% endif %}
{% endif %}
diff --git a/src/hi/apps/sense/tests/synthetic_data.py b/src/hi/apps/sense/tests/synthetic_data.py
index ef21f780..6567aa0b 100644
--- a/src/hi/apps/sense/tests/synthetic_data.py
+++ b/src/hi/apps/sense/tests/synthetic_data.py
@@ -11,6 +11,7 @@ from django.utils import timezone
from hi.apps.sense.models import Sensor, SensorHistory
from hi.apps.sense.transient_models import SensorResponse
+from hi.apps.sense.enums import CorrelationRole
from hi.integrations.transient_models import IntegrationKey
@@ -225,6 +226,8 @@ class SensorHistorySyntheticData:
value='active' if hours_ago % 3 == 0 else 'idle',
response_datetime=timestamp,
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id=str(hours_ago),
details=f'{{"event_id": "{hours_ago}", "duration_seconds": "{60 + hours_ago * 15}"}}'
)
records.append(record)
@@ -247,6 +250,8 @@ class SensorHistorySyntheticData:
value=f'event_{hours_ago}',
response_datetime=timestamp,
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id=str(hours_ago),
details=f'{{"hours_ago": "{hours_ago}"}}'
)
all_records.append(record)
@@ -274,6 +279,8 @@ class SensorHistorySyntheticData:
value=f'record_{i}',
response_datetime=timestamp,
has_video_stream=True,
+ correlation_role_str=str(CorrelationRole.END),
+ correlation_id=str(i),
details=f'{{"record_index": "{i}", "window_size": "{window}"}}'
)
records.append(record)
@@ -334,6 +341,67 @@ class SensorHistorySyntheticData:
return responses
+ @staticmethod
+ def create_simple_sensor_history(
+ sensor: Sensor,
+ value: str = 'active',
+ response_datetime: Optional[datetime] = None,
+ has_video_stream: bool = True,
+ correlation_role: CorrelationRole = CorrelationRole.END,
+ correlation_id: Optional[str] = None,
+ details: Optional[str] = None
+ ) -> SensorHistory:
+ """
+ Create a single SensorHistory record with correlation fields.
+ Simple helper to replace manual SensorHistory.objects.create() calls in tests.
+ """
+ if response_datetime is None:
+ response_datetime = timezone.now()
+
+ if correlation_id is None:
+ correlation_id = str(int(response_datetime.timestamp()))
+
+ return SensorHistory.objects.create(
+ sensor=sensor,
+ value=value,
+ response_datetime=response_datetime,
+ has_video_stream=has_video_stream,
+ correlation_role_str=str(correlation_role),
+ correlation_id=correlation_id,
+ details=details
+ )
+
+ @staticmethod
+ def create_bulk_sensor_history(
+ sensor: Sensor,
+ count: int,
+ base_time: Optional[datetime] = None,
+ time_interval_minutes: int = 1,
+ value_prefix: str = 'test_record',
+ has_video_stream: bool = True,
+ correlation_role: CorrelationRole = CorrelationRole.END
+ ) -> List[SensorHistory]:
+ """
+ Create multiple SensorHistory records efficiently for testing.
+ """
+ if base_time is None:
+ base_time = timezone.now()
+
+ records_to_create = []
+ for i in range(count):
+ timestamp = base_time - timezone.timedelta(minutes=i * time_interval_minutes)
+ records_to_create.append(SensorHistory(
+ sensor=sensor,
+ value=f'{value_prefix}_{i}',
+ response_datetime=timestamp,
+ has_video_stream=has_video_stream,
+ correlation_role_str=str(correlation_role),
+ correlation_id=str(i),
+ details=f'{{"{value_prefix}": {i}}}'
+ ))
+
+ return SensorHistory.objects.bulk_create(records_to_create)
+
# Legacy methods for backward compatibility - use create_timeline_test_scenario instead
@staticmethod
def create_timeline_preservation_test_data(sensor: Sensor) -> Tuple[List[SensorHistory], datetime, datetime]:
diff --git a/src/hi/apps/sense/transient_models.py b/src/hi/apps/sense/transient_models.py
index 17ebdd5b..ed097d2d 100644
--- a/src/hi/apps/sense/transient_models.py
+++ b/src/hi/apps/sense/transient_models.py
@@ -1,25 +1,28 @@
from dataclasses import dataclass
from datetime import datetime
import json
-from typing import Dict
+from typing import Dict, Optional
from hi.apps.entity.enums import EntityStateValue
from hi.integrations.transient_models import IntegrationKey
from .models import Sensor, SensorHistory
+from .enums import CorrelationRole
@dataclass
class SensorResponse:
- 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 = False
- sensor_history_id : int = None # Core Django SensorHistory primary key
+ 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 = False
+ correlation_role : Optional[CorrelationRole] = None
+ correlation_id : Optional[str] = None
+ sensor_history_id : int = None # Core Django SensorHistory primary key
def __str__(self):
return json.dumps( self.to_dict() )
@@ -42,6 +45,8 @@ class SensorResponse:
'detail_attrs': self.detail_attrs,
'source_image_url': self.source_image_url,
'has_video_stream': self.has_video_stream,
+ 'correlation_role': str(self.correlation_role) if self.correlation_role else None,
+ 'correlation_id': self.correlation_id,
'sensor_history_id': self.sensor_history_id,
}
@@ -57,6 +62,8 @@ class SensorResponse:
details = details,
source_image_url = self.source_image_url,
has_video_stream = self.has_video_stream,
+ correlation_role_str = str(self.correlation_role) if self.correlation_role else None,
+ correlation_id = self.correlation_id,
)
@classmethod
@@ -69,16 +76,32 @@ class SensorResponse:
detail_attrs = sensor_history.detail_attrs,
source_image_url = sensor_history.source_image_url,
has_video_stream = sensor_history.has_video_stream,
+ correlation_role = sensor_history.correlation_role,
+ correlation_id = sensor_history.correlation_id,
+ sensor_history_id = sensor_history.id,
)
@classmethod
def from_string( cls, sensor_response_str : str ) -> 'SensorResponse':
sensor_response_dict = json.loads( sensor_response_str )
+
+ # Parse correlation_role if present
+ correlation_role = None
+ correlation_role_str = sensor_response_dict.get('correlation_role')
+ if correlation_role_str:
+ correlation_role = CorrelationRole.from_name_safe(correlation_role_str)
+
return SensorResponse(
integration_key = IntegrationKey.from_string( sensor_response_dict.get('key') ),
value = sensor_response_dict.get('value'),
timestamp = datetime.fromisoformat( sensor_response_dict.get('timestamp') ),
detail_attrs = sensor_response_dict.get('detail_attrs'),
- source_image_url = sensor_response_dict.get('source_image_url') or 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),
+ correlation_role = correlation_role,
+ correlation_id = sensor_response_dict.get('correlation_id'),
+ sensor_history_id = sensor_response_dict.get('sensor_history_id'),
)
diff --git a/src/hi/apps/weather/tests/test_daily_weather_tracker.py b/src/hi/apps/weather/tests/test_daily_weather_tracker.py
index 8a345b6d..e54aafb5 100644
--- a/src/hi/apps/weather/tests/test_daily_weather_tracker.py
+++ b/src/hi/apps/weather/tests/test_daily_weather_tracker.py
@@ -4,6 +4,7 @@ Unit tests for DailyWeatherTracker - daily weather statistics tracking.
import json
import logging
import unittest
+import uuid
from datetime import datetime, timedelta
from unittest.mock import patch
@@ -30,15 +31,18 @@ class TestDailyWeatherTracker(unittest.TestCase):
"""Set up test environment."""
# Clear cache before each test
cache.clear()
-
+
+ # Create unique test identifier for cache isolation
+ self.test_id = uuid.uuid4().hex[:8]
+
# Use UTC timezone for consistent testing
self.test_timezone = pytz.UTC
-
+
# Mock ConsoleSettingsHelper to return UTC for consistent testing
self.console_helper_patcher = patch('hi.apps.weather.daily_weather_tracker.ConsoleSettingsHelper')
mock_console_helper = self.console_helper_patcher.start()
mock_console_helper.return_value.get_tz_name.return_value = 'UTC'
-
+
self.tracker = DailyWeatherTracker()
# Create test data point source and station
@@ -60,6 +64,8 @@ class TestDailyWeatherTracker(unittest.TestCase):
def tearDown(self):
"""Clean up test environment."""
+ # Clear cache to prevent test interference in parallel execution
+ cache.clear()
self.console_helper_patcher.stop()
def create_test_temperature_datapoint(self, temp_celsius, timestamp=None):
@@ -86,10 +92,11 @@ class TestDailyWeatherTracker(unittest.TestCase):
with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):
# Record a temperature observation
conditions = self.create_test_weather_conditions(25.0)
- self.tracker.record_weather_conditions(conditions, location_key="test_location")
+ location_key = f"test_location_{self.test_id}"
+ self.tracker.record_weather_conditions(conditions, location_key=location_key)
# Check that data was stored
- summary = self.tracker.get_daily_summary(location_key="test_location")
+ summary = self.tracker.get_daily_summary(location_key=location_key)
self.assertIsNotNone(summary)
self.assertEqual(summary['date'], '2024-03-15')
self.assertIn('temperature', summary['fields'])
@@ -101,7 +108,7 @@ class TestDailyWeatherTracker(unittest.TestCase):
def test_temperature_min_max_tracking(self):
"""Test that min/max temperatures are tracked correctly."""
with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):
- location_key = "test_location"
+ location_key = f"test_location_{self.test_id}"
# Record multiple temperatures throughout the day
temps_and_times = [
@@ -131,7 +138,7 @@ class TestDailyWeatherTracker(unittest.TestCase):
def test_multiple_days_tracking(self):
"""Test that data is tracked separately for different days."""
- location_key = "test_location"
+ location_key = f"test_location_{self.test_id}"
# Day 1: Record temperatures
day1 = self.base_time
@@ -167,7 +174,7 @@ class TestDailyWeatherTracker(unittest.TestCase):
central_time = central_tz.localize(datetime(2024, 3, 15, 23, 30, 0))
utc_time = central_time.astimezone(pytz.UTC)
- location_key = "test_location"
+ location_key = f"test_location_{self.test_id}"
# Mock ConsoleSettingsHelper to return Central timezone for this test
with patch('hi.apps.weather.daily_weather_tracker.ConsoleSettingsHelper') as mock_console, \
@@ -192,7 +199,7 @@ class TestDailyWeatherTracker(unittest.TestCase):
def test_no_data_scenarios(self):
"""Test behavior when no temperature data is available."""
- location_key = "empty_location"
+ location_key = f"empty_location_{self.test_id}"
# Should return None for both min and max when no data
min_temp, max_temp = self.tracker.get_temperature_min_max_today(location_key=location_key)
@@ -205,7 +212,7 @@ class TestDailyWeatherTracker(unittest.TestCase):
def test_invalid_temperature_data(self):
"""Test handling of invalid temperature data."""
- location_key = "test_location"
+ location_key = f"test_location_{self.test_id}"
# Test with None temperature
conditions_none = WeatherConditionsData()
@@ -224,7 +231,7 @@ class TestDailyWeatherTracker(unittest.TestCase):
def test_fallback_source_properties(self):
"""Test that fallback data points have correct source properties."""
- location_key = "test_location"
+ location_key = f"test_location_{self.test_id}"
with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):
conditions = self.create_test_weather_conditions(20.0)
@@ -240,7 +247,7 @@ class TestDailyWeatherTracker(unittest.TestCase):
def test_cache_storage_and_retrieval(self):
"""Test that data is properly stored and retrieved from cache."""
- location_key = "test_location"
+ location_key = f"test_location_{self.test_id}"
with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):
# Record temperature
@@ -260,7 +267,7 @@ class TestDailyWeatherTracker(unittest.TestCase):
def test_clear_today_functionality(self):
"""Test clearing today's temperature data."""
- location_key = "test_location"
+ location_key = f"test_location_{self.test_id}"
with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):
# Record temperature
@@ -303,7 +310,7 @@ class TestDailyWeatherTracker(unittest.TestCase):
def test_temperature_unit_conversion(self):
"""Test that temperatures are consistently stored in Celsius."""
- location_key = "test_location"
+ location_key = f"test_location_{self.test_id}"
with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):
# Record temperature in Fahrenheit
@@ -330,7 +337,7 @@ class TestDailyWeatherTracker(unittest.TestCase):
def test_record_weather_conditions_tracks_temperature_statistics(self):
"""Test that recording weather conditions properly tracks temperature min/max."""
- location_key = "test_location"
+ location_key = f"test_location_{self.test_id}"
with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):
# Record multiple temperature readings throughout the day
@@ -356,7 +363,7 @@ class TestDailyWeatherTracker(unittest.TestCase):
def test_get_daily_summary_provides_debug_information(self):
"""Test that get_daily_summary provides useful debugging information."""
- location_key = "test_location"
+ location_key = f"test_location_{self.test_id}"
with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):
# Record some temperature data
@@ -413,7 +420,7 @@ class TestDailyWeatherTracker(unittest.TestCase):
def test_clear_today_resets_tracking_data(self):
"""Test that clear_today properly resets tracking for a location."""
- location_key = "test_location"
+ location_key = f"test_location_{self.test_id}"
with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):
# Record some temperature data
@@ -441,7 +448,7 @@ class TestDailyWeatherTracker(unittest.TestCase):
def test_bug_reproduction_first_bad_reading_sets_both_min_max(self):
"""Test case reproducing Issue #166 - first bad reading sets both min and max to same wrong value."""
- location_key = "test_location"
+ location_key = f"test_location_{self.test_id}"
with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):
# Scenario: First reading of the day is a bad 88°F (31.1°C) value
@@ -482,7 +489,7 @@ class TestDailyWeatherTracker(unittest.TestCase):
def test_current_temperature_outside_cached_range_scenario(self):
"""Test the specific scenario from Issue #166 - current temp outside min/max range should not occur."""
- location_key = "test_location"
+ location_key = f"test_location_{self.test_id}"
with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):
# Simulate the problematic scenario: a high temperature gets recorded first
@@ -530,7 +537,7 @@ class TestDailyWeatherTracker(unittest.TestCase):
def test_extensibility_for_future_fields(self):
"""Test that the architecture supports future weather field additions."""
# This test verifies the general field recording mechanism
- location_key = "test_location"
+ location_key = f"test_location_{self.test_id}"
with patch('hi.apps.common.datetimeproxy.now', return_value=self.base_time):
# Test the internal _record_field_value method for extensibility
diff --git a/src/hi/apps/weather/tests/test_weather_alert_integration.py b/src/hi/apps/weather/tests/test_weather_alert_integration.py
index ac04035e..460d8ee7 100644
--- a/src/hi/apps/weather/tests/test_weather_alert_integration.py
+++ b/src/hi/apps/weather/tests/test_weather_alert_integration.py
@@ -2,7 +2,6 @@
Integration tests for weather alert to system alarm conversion.
Tests the complete flow from NWS data parsing to alarm creation.
"""
-import asyncio
import logging
from unittest.mock import Mock, AsyncMock
@@ -11,12 +10,12 @@ from hi.apps.weather.weather_sources.nws import NationalWeatherService
from hi.apps.weather.weather_manager import WeatherManager
from hi.transient_models import GeographicLocation
from hi.units import UnitQuantity
-from hi.testing.base_test_case import BaseTestCase
+from hi.testing.async_task_utils import AsyncTaskTestCase
logging.disable(logging.CRITICAL)
-class TestWeatherAlertIntegration(BaseTestCase):
+class TestWeatherAlertIntegration(AsyncTaskTestCase):
"""Test end-to-end weather alert to alarm integration."""
def test_nws_tornado_warning_creates_critical_alarm(self):
@@ -194,8 +193,8 @@ class TestWeatherAlertIntegration(BaseTestCase):
data_point_source=mock_data_source.data_point_source,
weather_alerts=test_alerts
)
-
- asyncio.run(test_update())
+
+ self.run_async(test_update())
# Verify alert manager was called to add alarms
self.assertEqual(mock_alert_manager.add_alarm.call_count, 2) # Only 2 should create alarms
diff --git a/src/hi/apps/weather/tests/test_weather_manager.py b/src/hi/apps/weather/tests/test_weather_manager.py
index 2d44ce3f..f9a2b575 100644
--- a/src/hi/apps/weather/tests/test_weather_manager.py
+++ b/src/hi/apps/weather/tests/test_weather_manager.py
@@ -1,7 +1,6 @@
from datetime import timedelta, datetime
import logging
from unittest.mock import patch, AsyncMock
-import asyncio
import pytz
import hi.apps.common.datetimeproxy as datetimeproxy
@@ -28,13 +27,13 @@ from hi.apps.weather.enums import (
)
from hi.units import UnitQuantity
-from hi.testing.base_test_case import BaseTestCase
+from hi.testing.async_task_utils import AsyncTaskTestCase
from hi.apps.weather.tests.synthetic_data import WeatherSyntheticData
logging.disable(logging.CRITICAL)
-class TestWeatherManager( BaseTestCase ):
+class TestWeatherManager( AsyncTaskTestCase ):
def _create_test_weather_data(self, priority, time_offset_secs, temperature_value, is_null=False):
"""Helper to create test weather data with specified parameters."""
@@ -125,7 +124,7 @@ class TestWeatherManager( BaseTestCase ):
self.assertEqual(current_conditions.temperature.source, high_priority_source)
# Run the async test
- asyncio.run(run_test())
+ self.run_async(run_test())
def test_update_current_conditions_preserves_newer_data(self):
"""Test that newer data is preserved even from lower priority sources within staleness window."""
@@ -177,7 +176,7 @@ class TestWeatherManager( BaseTestCase ):
# This test documents the actual behavior rather than testing implementation
# Run the async test
- asyncio.run(run_test())
+ self.run_async(run_test())
def test_update_hourly_forecast_aggregates_multiple_sources(self):
"""Test that hourly forecast properly aggregates data from multiple sources."""
@@ -220,7 +219,7 @@ class TestWeatherManager( BaseTestCase ):
self.assertGreater(len(hourly_forecast.data_list), 0)
# Run the async test
- asyncio.run(run_test())
+ self.run_async(run_test())
def test_get_current_conditions_returns_latest_data(self):
"""Test that get_current_conditions returns the most recent weather data."""
@@ -261,7 +260,7 @@ class TestWeatherManager( BaseTestCase ):
)
# Run the async test
- asyncio.run(run_test())
+ self.run_async(run_test())
def test_update_weather_alerts_stores_alerts_when_enabled(self):
"""Test that weather alerts are stored when alerts feature is enabled."""
@@ -298,7 +297,7 @@ class TestWeatherManager( BaseTestCase ):
# Mock settings to enable alerts
with patch('hi.apps.weather.weather_manager.WeatherSettingsHelper') as mock_helper_class:
mock_helper = mock_helper_class.return_value
- mock_helper.is_weather_alerts_enabled.return_value = True
+ mock_helper.is_weather_alerts_enabled_async = AsyncMock(return_value=True)
# Mock alert manager
with patch.object(weather_manager, 'alert_manager_async', return_value=AsyncMock()):
@@ -314,7 +313,7 @@ class TestWeatherManager( BaseTestCase ):
self.assertEqual(stored_alerts[0].event, "Severe Thunderstorm Warning")
# Run the async test
- asyncio.run(run_test())
+ self.run_async(run_test())
# ============= ORIGINAL TESTS (TO BE DEPRECATED) =============
@@ -540,8 +539,8 @@ class TestWeatherManager( BaseTestCase ):
def test_weather_alerts_enabled_disabled_integration(self):
"""Integration test running both enabled and disabled scenarios."""
- asyncio.run(self.test_weather_alerts_enabled_stores_alerts())
- asyncio.run(self.test_weather_alerts_disabled_blocks_processing())
+ self.run_async(self.test_weather_alerts_enabled_stores_alerts())
+ self.run_async(self.test_weather_alerts_disabled_blocks_processing())
def test_daily_history_data_flow(self):
"""Test that daily history data flows correctly from weather manager to template context."""
@@ -604,7 +603,7 @@ class TestWeatherManager( BaseTestCase ):
)
# Run the async test
- asyncio.run(test_update())
+ self.run_async(test_update())
# Verify daily history is populated
daily_history = weather_manager.get_daily_history()
@@ -705,7 +704,7 @@ class TestWeatherManager( BaseTestCase ):
# Mock WeatherSettingsHelper to return disabled state
with patch('hi.apps.weather.weather_manager.WeatherSettingsHelper') as mock_helper_class:
mock_helper = mock_helper_class.return_value
- mock_helper.is_weather_alerts_enabled.return_value = False
+ mock_helper.is_weather_alerts_enabled_async = AsyncMock(return_value=False)
# Test actual behavior when disabled
await weather_manager.update_weather_alerts(
diff --git a/src/hi/apps/weather/tests/test_weather_manager_daily_tracker_integration.py b/src/hi/apps/weather/tests/test_weather_manager_daily_tracker_integration.py
index c22f4cae..5804279f 100644
--- a/src/hi/apps/weather/tests/test_weather_manager_daily_tracker_integration.py
+++ b/src/hi/apps/weather/tests/test_weather_manager_daily_tracker_integration.py
@@ -2,9 +2,7 @@
Integration tests for WeatherManager and DailyWeatherTracker.
Tests the complete flow of temperature tracking and fallback value population.
"""
-import asyncio
import logging
-import unittest
from unittest.mock import patch
from datetime import datetime, timedelta
@@ -17,6 +15,7 @@ from hi.apps.weather.transient_models import WeatherConditionsData, NumericDataP
from hi.apps.weather.weather_data_source import WeatherDataSource
from hi.transient_models import GeographicLocation
from hi.units import UnitQuantity
+from hi.testing.async_task_utils import AsyncTaskTestCase
logging.disable(logging.CRITICAL)
@@ -44,7 +43,7 @@ class MockWeatherDataSource(WeatherDataSource):
pass # Not used in these tests
-class TestWeatherManagerDailyTrackerIntegration(unittest.TestCase):
+class TestWeatherManagerDailyTrackerIntegration(AsyncTaskTestCase):
"""Test integration between WeatherManager and DailyWeatherTracker."""
def setUp(self):
@@ -68,7 +67,13 @@ class TestWeatherManagerDailyTrackerIntegration(unittest.TestCase):
# Base test time
self.base_time = timezone.make_aware(datetime(2024, 3, 15, 12, 0, 0), pytz.UTC)
-
+
+ def tearDown(self):
+ """Clean up test environment."""
+ # Clear cache to prevent test interference in parallel execution
+ cache.clear()
+ super().tearDown()
+
def create_test_conditions(self, temp_celsius, timestamp=None, include_today_fields=True):
"""Helper to create test weather conditions."""
if timestamp is None:
@@ -105,7 +110,7 @@ class TestWeatherManagerDailyTrackerIntegration(unittest.TestCase):
conditions = self.create_test_conditions(25.0, include_today_fields=False)
# Update current conditions (should record temperature)
- asyncio.run(self.weather_manager.update_current_conditions(
+ self.run_async(self.weather_manager.update_current_conditions(
data_point_source=self.mock_source.data_point_source,
weather_conditions_data=conditions
))
@@ -235,7 +240,7 @@ class TestWeatherManagerDailyTrackerIntegration(unittest.TestCase):
# Use incrementing timestamps so each update actually overwrites the previous
timestamp = self.base_time + timedelta(minutes=i * 10)
conditions = self.create_test_conditions(temp, timestamp=timestamp, include_today_fields=False)
- asyncio.run(self.weather_manager.update_current_conditions(
+ self.run_async(self.weather_manager.update_current_conditions(
data_point_source=self.mock_source.data_point_source,
weather_conditions_data=conditions
))
@@ -296,7 +301,7 @@ class TestWeatherManagerDailyTrackerIntegration(unittest.TestCase):
# Record temperature
conditions = self.create_test_conditions(25.0, utc_late, include_today_fields=False)
- asyncio.run(self.weather_manager.update_current_conditions(
+ self.run_async(self.weather_manager.update_current_conditions(
data_point_source=self.mock_source.data_point_source,
weather_conditions_data=conditions
))
diff --git a/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py b/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py
index 129464dd..589c4203 100644
--- a/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py
+++ b/src/hi/apps/weather/tests/test_weather_manager_defensive_handling.py
@@ -2,7 +2,6 @@
Test that WeatherManager gracefully handles errors in daily weather tracking
without breaking core weather API functionality.
"""
-import asyncio
import logging
from unittest.mock import patch
from datetime import datetime
@@ -16,7 +15,7 @@ from hi.apps.weather.transient_models import WeatherConditionsData, NumericDataP
from hi.apps.weather.weather_data_source import WeatherDataSource
from hi.transient_models import GeographicLocation
from hi.units import UnitQuantity
-from hi.testing.base_test_case import BaseTestCase
+from hi.testing.async_task_utils import AsyncTaskTestCase
logging.disable(logging.CRITICAL)
@@ -48,7 +47,7 @@ class MockWeatherDataSource(WeatherDataSource):
pass
-class TestWeatherManagerDefensiveHandling(BaseTestCase):
+class TestWeatherManagerDefensiveHandling(AsyncTaskTestCase):
"""Test defensive error handling for daily weather tracking."""
def setUp(self):
@@ -70,7 +69,13 @@ class TestWeatherManagerDefensiveHandling(BaseTestCase):
)
self.base_time = timezone.make_aware(datetime(2024, 3, 15, 12, 0, 0), pytz.UTC)
-
+
+ def tearDown(self):
+ """Clean up test environment."""
+ # Clear cache to prevent test interference in parallel execution
+ cache.clear()
+ super().tearDown()
+
def create_test_conditions(self, temp_celsius):
"""Helper to create test weather conditions."""
temperature_datapoint = NumericDataPoint(
@@ -95,7 +100,7 @@ class TestWeatherManagerDefensiveHandling(BaseTestCase):
conditions = self.create_test_conditions(25.0)
# The update should complete successfully
- asyncio.run(self.weather_manager.update_current_conditions(
+ self.run_async(self.weather_manager.update_current_conditions(
data_point_source=self.mock_source.data_point_source,
weather_conditions_data=conditions
))
@@ -118,7 +123,7 @@ class TestWeatherManagerDefensiveHandling(BaseTestCase):
# This should NOT raise an exception
conditions = self.create_test_conditions(20.0)
- asyncio.run(self.weather_manager.update_current_conditions(
+ self.run_async(self.weather_manager.update_current_conditions(
data_point_source=self.mock_source.data_point_source,
weather_conditions_data=conditions
))
@@ -165,7 +170,7 @@ class TestWeatherManagerDefensiveHandling(BaseTestCase):
# Update conditions
conditions = self.create_test_conditions(30.0)
- asyncio.run(self.weather_manager.update_current_conditions(
+ self.run_async(self.weather_manager.update_current_conditions(
data_point_source=self.mock_source.data_point_source,
weather_conditions_data=conditions
))
diff --git a/src/hi/apps/weather/weather_manager.py b/src/hi/apps/weather/weather_manager.py
index 85519109..2b5361f2 100644
--- a/src/hi/apps/weather/weather_manager.py
+++ b/src/hi/apps/weather/weather_manager.py
@@ -249,7 +249,7 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
"""Update weather alerts from data sources and create system alarms for qualifying alerts."""
# Check if weather alerts processing is enabled
weather_settings_helper = WeatherSettingsHelper()
- if not weather_settings_helper.is_weather_alerts_enabled():
+ if not await weather_settings_helper.is_weather_alerts_enabled_async():
logger.debug(f'Weather alerts processing disabled, ignoring'
f' {len(weather_alerts)} alerts from {data_point_source.id}')
return
diff --git a/src/hi/apps/weather/weather_settings_helper.py b/src/hi/apps/weather/weather_settings_helper.py
index d6f76d6b..c453c5d1 100644
--- a/src/hi/apps/weather/weather_settings_helper.py
+++ b/src/hi/apps/weather/weather_settings_helper.py
@@ -7,7 +7,7 @@ from .settings import WeatherSetting
logger = logging.getLogger(__name__)
-class WeatherSettingsHelper(SettingsMixin):
+class WeatherSettingsHelper( SettingsMixin ):
"""Helper class to access weather-related settings."""
def _get_weather_source_enabled_value(self, source_id: str, settings_manager):
@@ -87,15 +87,26 @@ class WeatherSettingsHelper(SettingsMixin):
return value.lower() in ('true', '1', 'yes', 'on')
return bool(value)
- def is_weather_alerts_enabled(self) -> bool:
- """Check if weather alerts processing is enabled."""
- value = self.settings_manager().get_setting_value(WeatherSetting.WEATHER_ALERTS_ENABLED)
+ def _get_weather_alerts_enabled_value(self, settings_manager):
+ """Private helper to get weather alerts enabled value with any settings manager."""
+ value = settings_manager.get_setting_value(WeatherSetting.WEATHER_ALERTS_ENABLED)
if value is None:
return True
# Handle string boolean values from database
if isinstance(value, str):
return value.lower() in ('true', '1', 'yes', 'on')
return bool(value)
+
+ def is_weather_alerts_enabled(self) -> bool:
+ """Check if weather alerts processing is enabled."""
+ return self._get_weather_alerts_enabled_value(self.settings_manager())
+
+ async def is_weather_alerts_enabled_async(self) -> bool:
+ """Check if weather alerts processing is enabled (async version)."""
+ settings_manager = await self.settings_manager_async()
+ if not settings_manager:
+ return True
+ return self._get_weather_alerts_enabled_value(settings_manager)
def get_weather_source_config(self, source_id: str) -> Dict[str, any]:
"""Get complete configuration for a weather source."""
diff --git a/src/hi/constants.py b/src/hi/constants.py
index caa694ec..8207ffd3 100644
--- a/src/hi/constants.py
+++ b/src/hi/constants.py
@@ -53,6 +53,7 @@ DIVID = {
'ATTRIBUTE_CONTAINER_CLASS': 'hi-attribute',
+ 'DATETIME_HEADER': 'hi-datetime-header',
'ALERT_BANNER_CONTAINER': 'hi-alert-banner-container',
'ALERT_BANNER_CONTENT': 'hi-alert-banner-content',
'SECURITY_STATE_CONTROL': 'hi-security-state-control',
diff --git a/src/hi/services/zoneminder/integration.py b/src/hi/services/zoneminder/integration.py
index 6749cf3c..79f4fc63 100644
--- a/src/hi/services/zoneminder/integration.py
+++ b/src/hi/services/zoneminder/integration.py
@@ -3,7 +3,8 @@ 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.entity.enums import VideoStreamType, VideoStreamMode
+from hi.apps.entity.constants import VideoStreamMetadataKeys
from hi.apps.sense.transient_models import SensorResponse
from hi.integrations.integration_controller import IntegrationController
from hi.integrations.integration_gateway import IntegrationGateway
@@ -53,7 +54,10 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):
return VideoStream(
stream_type=VideoStreamType.URL,
source_url=video_url,
- metadata={'monitor_id': monitor_id, 'stream_type': 'live'}
+ metadata={
+ 'monitor_id': monitor_id,
+ VideoStreamMetadataKeys.STREAM_MODE: str(VideoStreamMode.LIVE)
+ }
)
except (IndexError, ValueError):
logger.warning(f"Could not parse monitor ID from entity integration name: {entity.integration_name}")
@@ -74,11 +78,25 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):
try:
event_id = int(sensor_response.detail_attrs[event_id_fieldname])
video_url = self.zm_manager().get_event_video_stream_url(event_id)
-
+
+ # Extract duration from detail_attrs if available
+ metadata = {
+ event_id_fieldname: event_id,
+ VideoStreamMetadataKeys.STREAM_MODE: str(VideoStreamMode.RECORDED)
+ }
+
+ # Look for duration in detail_attrs using the ZoneMinder constant
+ if ZmDetailKeys.DURATION_SECS in sensor_response.detail_attrs:
+ try:
+ duration_secs = float(sensor_response.detail_attrs[ZmDetailKeys.DURATION_SECS])
+ metadata[VideoStreamMetadataKeys.DURATION_SECS] = int(duration_secs)
+ except (ValueError, TypeError):
+ logger.debug(f"Could not parse duration from sensor response: {sensor_response.detail_attrs.get(ZmDetailKeys.DURATION_SECS)}")
+
return VideoStream(
stream_type=VideoStreamType.URL,
source_url=video_url,
- metadata={event_id_fieldname: event_id, 'stream_type': 'recorded'}
+ metadata=metadata
)
except (ValueError, TypeError):
logger.warning(f"Could not parse event ID from sensor response: {sensor_response.detail_attrs}")
diff --git a/src/hi/services/zoneminder/monitors.py b/src/hi/services/zoneminder/monitors.py
index 2ae98ffe..9b7ddbe5 100644
--- a/src/hi/services/zoneminder/monitors.py
+++ b/src/hi/services/zoneminder/monitors.py
@@ -9,6 +9,7 @@ from hi.apps.entity.enums import EntityStateValue
from hi.apps.monitor.periodic_monitor import PeriodicMonitor
from hi.apps.sense.sensor_response_manager import SensorResponseMixin
from hi.apps.sense.transient_models import SensorResponse
+from hi.apps.sense.enums import CorrelationRole
from .constants import ZmDetailKeys
from .zm_models import ZmEvent, AggregatedMonitorState
@@ -306,7 +307,13 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )
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()
+ all_detail_attrs = zm_event.to_detail_attrs()
+ # For active (start) events, only include basic event info
+ detail_attrs = {
+ ZmDetailKeys.EVENT_ID_ATTR_NAME: all_detail_attrs.get(ZmDetailKeys.EVENT_ID_ATTR_NAME),
+ ZmDetailKeys.START_TIME: all_detail_attrs.get(ZmDetailKeys.START_TIME),
+ ZmDetailKeys.NOTES: all_detail_attrs.get(ZmDetailKeys.NOTES),
+ }
return SensorResponse(
integration_key = self.zm_manager()._to_integration_key(
prefix = ZoneMinderManager.MOVEMENT_SENSOR_PREFIX,
@@ -317,9 +324,15 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )
detail_attrs = detail_attrs,
source_image_url = zm_event.image_url( self.zm_manager() ),
has_video_stream = self._has_video_stream_capability(detail_attrs),
+ correlation_role = CorrelationRole.START,
+ correlation_id = all_detail_attrs.get(ZmDetailKeys.EVENT_ID_ATTR_NAME),
)
def _create_movement_idle_sensor_response( self, zm_event : ZmEvent ):
+ all_detail_attrs = zm_event.to_detail_attrs()
+ # For idle (end) events, include all detail attributes
+ detail_attrs = all_detail_attrs
+
return SensorResponse(
integration_key = self.zm_manager()._to_integration_key(
prefix = ZoneMinderManager.MOVEMENT_SENSOR_PREFIX,
@@ -327,7 +340,10 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )
),
value = str(EntityStateValue.IDLE),
timestamp = zm_event.end_datetime,
- has_video_stream = False,
+ detail_attrs = detail_attrs,
+ has_video_stream = self._has_video_stream_capability(detail_attrs),
+ correlation_role = CorrelationRole.END,
+ correlation_id = all_detail_attrs.get(ZmDetailKeys.EVENT_ID_ATTR_NAME),
)
def _create_idle_sensor_response( self, zm_monitor : ZmMonitor, timestamp : datetime ):
diff --git a/src/hi/services/zoneminder/zm_models.py b/src/hi/services/zoneminder/zm_models.py
index ffec95a2..88266e95 100644
--- a/src/hi/services/zoneminder/zm_models.py
+++ b/src/hi/services/zoneminder/zm_models.py
@@ -107,12 +107,12 @@ class ZmEvent:
def to_detail_attrs( self ) -> Dict[ str, str ]:
return {
ZmDetailKeys.EVENT_ID_ATTR_NAME: self.event_id,
- 'Start Time': self.start_datetime.isoformat(),
- 'Score': self.score,
- 'Duration (secs)': self.duration_secs,
- 'Alarmed Frames': self.alarmed_frame_count,
- 'Total Frames': self.total_frame_count,
- 'Notes': self.notes,
+ ZmDetailKeys.START_TIME: self.start_datetime.isoformat(),
+ ZmDetailKeys.SCORE: self.score,
+ ZmDetailKeys.DURATION_SECS: self.duration_secs,
+ ZmDetailKeys.ALARMED_FRAMES: self.alarmed_frame_count,
+ ZmDetailKeys.TOTAL_FRAMES: self.total_frame_count,
+ ZmDetailKeys.NOTES: self.notes,
}