Home Information - Your home, your data, organized.
Python
Added handling sensor response details and ZM event video.
Anthony Cassandra6387f6d3b09c
diff --git a/src/hi/apps/sense/sensor_history_manager.py b/src/hi/apps/sense/sensor_history_manager.pyindex ea7e898d..ecc703be 100644--- a/src/hi/apps/sense/sensor_history_manager.py+++ b/src/hi/apps/sense/sensor_history_manager.py@@ -23,7 +23,7 @@ class SensorHistoryManager( Singleton ):sensor_history_list = list()for sensor_response in sensor_response_list:if sensor_response.sensor and sensor_response.sensor.persist_history:- sensor_history_list.append( sensor_response.to_sensor_history )+ sensor_history_list.append( sensor_response.to_sensor_history() )continueawait self._bulk_create_sensor_history_async( sensor_history_list )diff --git a/src/hi/apps/sense/templates/sense/panes/sensor_history_list.html b/src/hi/apps/sense/templates/sense/panes/sensor_history_list.htmlindex 928152c8..f409a20f 100644--- a/src/hi/apps/sense/templates/sense/panes/sensor_history_list.html+++ b/src/hi/apps/sense/templates/sense/panes/sensor_history_list.html@@ -3,7 +3,7 @@<li>Response: {{ sensor_history.value }} [{{ sensor_history.response_datetime }}]{% if sensor_history.details %}- <a href="{% url 'sense_sensor_history_details' id=sensor_history.id %}"+ <a href="{% url 'integration_sensor_response_details' sensor_history_id=sensor_history.id %}"data-async="true">Details</a>{% endif %}</li>diff --git a/src/hi/apps/sense/transient_models.py b/src/hi/apps/sense/transient_models.pyindex 04b83939..2476a748 100644--- a/src/hi/apps/sense/transient_models.py+++ b/src/hi/apps/sense/transient_models.py@@ -35,7 +35,6 @@ class SensorResponse:details = self.details,)-@classmethoddef from_string( self, sensor_reading_str : str ) -> 'SensorResponse':sensor_reading_dict = json.loads( sensor_reading_str )diff --git a/src/hi/apps/sense/urls.py b/src/hi/apps/sense/urls.pyindex 29463f33..8985d92b 100644--- a/src/hi/apps/sense/urls.py+++ b/src/hi/apps/sense/urls.py@@ -8,9 +8,4 @@ urlpatterns = [re_path( r'^sensor/history/(?P<sensor_id>\d+)$',views.SensorHistoryView.as_view(),name='sense_sensor_history'),-- re_path( r'^sensor/history/details/(?P<id>\d+)$',- views.SensorHistoryDetailsView.as_view(),- name='sense_sensor_history_details'),-]diff --git a/src/hi/apps/sense/view_mixin.py b/src/hi/apps/sense/view_mixin.pyindex 0018275b..508151b4 100644--- a/src/hi/apps/sense/view_mixin.py+++ b/src/hi/apps/sense/view_mixin.py@@ -1,7 +1,7 @@from django.core.exceptions import BadRequestfrom django.http import Http404-from hi.apps.sense.models import Sensor+from hi.apps.sense.models import Sensor, SensorHistoryclass SenseViewMixin:diff --git a/src/hi/apps/sense/views.py b/src/hi/apps/sense/views.pyindex f163116c..d966c3fa 100644--- a/src/hi/apps/sense/views.py+++ b/src/hi/apps/sense/views.py@@ -1,7 +1,6 @@import loggingfrom django.urls import reverse-from django.views.generic import Viewfrom hi.hi_async_view import HiModalViewfrom hi.apps.common.pagination import compute_pagination_from_queryset@@ -38,9 +37,3 @@ class SensorHistoryView( HiModalView, SenseViewMixin ):'pagination': pagination,}return self.modal_response( request, context )---class SensorHistoryDetailsView( View, SenseViewMixin ):-- def get(self, request, *args, **kwargs):- passdiff --git a/src/hi/integrations/core/integration_gateway.py b/src/hi/integrations/core/integration_gateway.pyindex eaf9fe6c..76093905 100644--- a/src/hi/integrations/core/integration_gateway.py+++ b/src/hi/integrations/core/integration_gateway.py@@ -24,3 +24,8 @@ class IntegrationGateway:# Should return a modal via antinode.modal_from_template() (called async)raise NotImplementedError('Subclasses must override this method')+ def sensor_response_details_view( self,+ request : HttpRequest,+ details_str : str ) -> HttpResponse:+ # Should return a modal via antinode.modal_from_template() (called async)+ raise NotImplementedError('Subclasses must override this method')diff --git a/src/hi/integrations/core/urls.py b/src/hi/integrations/core/urls.pyindex b6fd3fa4..7f4d4226 100644--- a/src/hi/integrations/core/urls.py+++ b/src/hi/integrations/core/urls.py@@ -22,5 +22,10 @@ urlpatterns = [re_path( r'^hass/', include('hi.integrations.hass.urls' )),++ re_path( r'^sensor/response/details/(?P<sensor_history_id>\d+)$',+ views.SensorResponseDetailsView.as_view(),+ name='integration_sensor_response_details'),+]diff --git a/src/hi/integrations/core/views.py b/src/hi/integrations/core/views.pyindex 27b2ca67..aec43a5d 100644--- a/src/hi/integrations/core/views.py+++ b/src/hi/integrations/core/views.py@@ -1,11 +1,13 @@import loggingfrom django.core.exceptions import BadRequest+from django.http import Http404from django.urls import reversefrom django.views.generic import Viewfrom hi.apps.config.enums import ConfigPageTypefrom hi.apps.config.views import ConfigPageView+from hi.apps.sense.models import SensorHistoryfrom hi.exceptions import ForceRedirectExceptionfrom hi.hi_async_view import HiModalView@@ -107,3 +109,28 @@ class IntegrationActionView( View ):error_message = str(e)raise BadRequest( error_message )+++class SensorResponseDetailsView( View ):++ def get(self, request, *args, **kwargs):+ sensor_history = self.get_sensor_history( request, *args, **kwargs )+ integration_gateway = IntegrationFactory().get_integration_gateway(+ integration_id = sensor_history.sensor.integration_id,+ )+ return integration_gateway.sensor_response_details_view(+ request = request,+ details_str = sensor_history.details,+ )++ def get_sensor_history( self, request, *args, **kwargs ) -> SensorHistory:+ """ Assumes there is a required id in kwargs """+ try:+ sensor_history_id = int( kwargs.get( 'sensor_history_id' ))+ except (TypeError, ValueError):+ raise BadRequest( 'Invalid sensor history id.' )+ try:+ return SensorHistory.objects.select_related('sensor').get( id = sensor_history_id )+ except SensorHistory.DoesNotExist:+ raise Http404( request )+diff --git a/src/hi/integrations/hass/hass_gateway.py b/src/hi/integrations/hass/hass_gateway.pyindex 0c836d7a..9c89646f 100644--- a/src/hi/integrations/hass/hass_gateway.py+++ b/src/hi/integrations/hass/hass_gateway.py@@ -2,7 +2,6 @@ import loggingfrom django.http import HttpRequest, HttpResponse-from hi.integrations.core.integration_factory import IntegrationFactoryfrom hi.integrations.core.integration_gateway import IntegrationGatewayfrom hi.integrations.core.transient_models import IntegrationMetaDatafrom hi.apps.monitor.periodic_monitor import PeriodicMonitor@@ -28,5 +27,10 @@ class HassGateway( IntegrationGateway ):def disable_modal_view( self, request : HttpRequest, *args, **kwargs ) -> HttpResponse:return views.HassDisableView().get( request )--IntegrationFactory().register( HassGateway() )+ def sensor_response_details_view( self,+ request : HttpRequest,+ details_str : str ) -> HttpResponse:+ return views.SensorResponseDetailsView().get(+ request,+ details_str = details_str,+ )diff --git a/src/hi/integrations/hass/templates/hass/modals/sensor_response_details.html b/src/hi/integrations/hass/templates/hass/modals/sensor_response_details.htmlnew file mode 100644index 00000000..40f5720f--- /dev/null+++ b/src/hi/integrations/hass/templates/hass/modals/sensor_response_details.html@@ -0,0 +1,11 @@+{% extends "modals/action_ok.html" %}++{% block title_text %}+Home Assistent Status Details+{% endblock %}++{% block body %}+<div class="alert alert-warning">+ State status details are not yet implemented for the Home Assistant integration.+</div>+{% endblock %}diff --git a/src/hi/integrations/hass/views.py b/src/hi/integrations/hass/views.pyindex af4eaa51..1a82ae04 100644--- a/src/hi/integrations/hass/views.py+++ b/src/hi/integrations/hass/views.py@@ -1,3 +1,5 @@+import json+from django.core.exceptions import BadRequestfrom django.db import transaction@@ -148,3 +150,17 @@ class HassSyncView( HiModalView ):'processing_result': processing_result,}return self.modal_response( request, context )+++class SensorResponseDetailsView( HiModalView ):++ def get_template_name( self ) -> str:+ return 'hass/modals/sensor_response_details.html'++ def get(self, request, *args, **kwargs):+ details_str = kwargs.get( 'details_str' )++ # TODO: No current HAss SensorResponse instances add any viewable details.+ details_dict = json.loads( details_str )+ context = details_dict+ return self.modal_response( request, context )diff --git a/src/hi/integrations/zoneminder/sensor_response_helper.py b/src/hi/integrations/zoneminder/sensor_response_helper.pynew file mode 100644index 00000000..5c75809b--- /dev/null+++ b/src/hi/integrations/zoneminder/sensor_response_helper.py@@ -0,0 +1,33 @@+import json++from .zm_models import ZmEvent, ZmDetails, ZmEventDetails+++class SensorResponseHelper:++ @classmethod+ def event_to_details( cls, zm_event : ZmEvent ) -> str:+ event_details = {+ 'event_id': zm_event.event_id,+ 'notes': zm_event.notes,+ 'duration_secs': zm_event.duration_secs,+ 'total_frames': zm_event.total_frame_count,+ 'alarmed_frames': zm_event.alarmed_frame_count,+ 'score': zm_event.score,+ }+ return json.dumps( event_details )++ @classmethod+ def from_details( cls, details : str ) -> ZmDetails:+ details_dict = json.loads( details )+ if 'event_id' in details_dict:+ return ZmEventDetails(+ event_id = details_dict.get('event_id'),+ notes = details_dict.get('notes'),+ duration_secs = details_dict.get('duration_secs'),+ total_frames = details_dict.get('total_frames'),+ alarmed_frames = details_dict.get('alarmed_frames'),+ score = details_dict.get('score'),+ )+ return None+diff --git a/src/hi/integrations/zoneminder/templates/zoneminder/modals/zm_event_details.html b/src/hi/integrations/zoneminder/templates/zoneminder/modals/zm_event_details.htmlnew file mode 100644index 00000000..31efbaef--- /dev/null+++ b/src/hi/integrations/zoneminder/templates/zoneminder/modals/zm_event_details.html@@ -0,0 +1,35 @@+{% extends "modals/action_ok.html" %}++{% block title_text %}+ZoneMinder Event Details+{% endblock %}++{% block body %}+<div class="" >+ RECORDED+</div>++<div>+ <img class="img-fluid" src="https://bordeaux:8443/zm/cgi-bin/nph-zms?mode=jpeg&scale=100&rate=100&maxfps=30&replay=single&source=event&event={{ zm_event_details.event_id }}" alt="ZoneMinder Camera Event {{ zm_event_details.event_id }}">+</div>++<div>+ Id: {{ zm_event_details.event_id }}+</div>+<div>+ Notes: {{ zm_event_details.notes }}+</div>+<div>+ Duration_Secs: {{ zm_event_details.duration_secs }}+</div>+<div>+ Total_Frames: {{ zm_event_details.total_frames }}+</div>+<div>+ Alarmed_Frames: {{ zm_event_details.alarmed_frames }}+</div>+<div>+ Scores: {{ zm_event_details.score.total }} / {{ zm_event_details.score.average }} / {{ zm_event_details.score.max }}+</div>++{% endblock %}diff --git a/src/hi/integrations/zoneminder/views.py b/src/hi/integrations/zoneminder/views.pyindex 3b9a1e60..1c847bfe 100644--- a/src/hi/integrations/zoneminder/views.py+++ b/src/hi/integrations/zoneminder/views.py@@ -4,13 +4,17 @@ from django.shortcuts import renderfrom django.urls import reversefrom django.views.generic import View+import hi.apps.common.antinode as antinode+from hi.integrations.core.forms import IntegrationAttributeFormSetfrom hi.integrations.core.helpers import IntegrationHelperMixinfrom hi.integrations.core.views import IntegrationPageViewfrom hi.hi_async_view import HiModalView+from .sensor_response_helper import SensorResponseHelperfrom .zm_manager import ZoneMinderManager+from .zm_models import ZmEventDetailsfrom .zm_metadata import ZmMetaData@@ -147,4 +151,24 @@ class ZmSyncView( HiModalView ):'processing_result': processing_result,}return self.modal_response( request, context )++class SensorResponseDetailsView( View ):++ def get(self, request, *args, **kwargs):+ details_str = kwargs.get( 'details_str' )+ zm_details = SensorResponseHelper.from_details( details = details_str )++ if isinstance( zm_details, ZmEventDetails ):+ context = {+ 'zm_event_details': zm_details,+ }+ template_name = 'zoneminder/modals/zm_event_details.html'+ else:+ raise BadRequest( f'Unknown ZmDetails: {details_str}' )++ return antinode.modal_from_template(+ request = request,+ template_name = template_name,+ context = context,+ )diff --git a/src/hi/integrations/zoneminder/zm_gateway.py b/src/hi/integrations/zoneminder/zm_gateway.pyindex f50ba5d6..65e589e3 100644--- a/src/hi/integrations/zoneminder/zm_gateway.py+++ b/src/hi/integrations/zoneminder/zm_gateway.py@@ -26,3 +26,11 @@ class ZoneMinderGateway( IntegrationGateway ):def disable_modal_view( self, request : HttpRequest, *args, **kwargs ) -> HttpResponse:return views.ZmDisableView().get( request )++ def sensor_response_details_view( self,+ request : HttpRequest,+ details_str : str ) -> HttpResponse:+ return views.SensorResponseDetailsView().get(+ request,+ details_str = details_str,+ )diff --git a/src/hi/integrations/zoneminder/zm_models.py b/src/hi/integrations/zoneminder/zm_models.pyindex a2241637..0255f09d 100644--- a/src/hi/integrations/zoneminder/zm_models.py+++ b/src/hi/integrations/zoneminder/zm_models.py@@ -1,3 +1,5 @@+from dataclasses import dataclass+import hi.apps.common.datetimeproxy as datetimeproxyfrom pyzm.helpers.Event import Event as ZmApiEvent@@ -90,5 +92,19 @@ class ZmEvent:if not zm_response_time:return Nonereturn datetimeproxy.iso_naive_to_datetime_utc( zm_response_time, tzname )-++@dataclass+class ZmDetails:+ """ Base class for all SensorResponse detail objects """+ pass+++@dataclass+class ZmEventDetails( ZmDetails ):+ event_id : int+ notes : str+ duration_secs : int+ total_frames : int+ alarmed_frames : int+ score : intdiff --git a/src/hi/integrations/zoneminder/zm_monitor.py b/src/hi/integrations/zoneminder/zm_monitor.pyindex 41d9e9e6..6365f1ee 100644--- a/src/hi/integrations/zoneminder/zm_monitor.py+++ b/src/hi/integrations/zoneminder/zm_monitor.py@@ -1,6 +1,5 @@from cachetools import TTLCachefrom datetime import datetime-import jsonimport loggingfrom pyzm.helpers.Monitor import Monitor as ZmMonitorfrom typing import List@@ -12,6 +11,7 @@ from hi.apps.sense.sensor_history_manager import SensorHistoryManagerfrom hi.apps.sense.sensor_response_manager import SensorResponseManagerfrom hi.apps.sense.transient_models import SensorResponse+from .sensor_response_helper import SensorResponseHelperfrom .zm_models import ZmEventfrom .zm_manager import ZoneMinderManager@@ -162,16 +162,6 @@ class ZoneMinderMonitor( PeriodicMonitor ):return self._zm_monitor_listdef _create_movement_active_sensor_response( self, zm_event : ZmEvent ):-- event_details = {- 'event_id': zm_event.event_id,- 'notes': zm_event.notes,- 'duration_secs': zm_event.duration_secs,- 'total_frames': zm_event.total_frame_count,- 'alarmed_frames': zm_event.alarmed_frame_count,- 'score': zm_event.score,- }-return SensorResponse(integration_key = self._zm_manager._sensor_to_integration_key(sensor_prefix = self._zm_manager.MOVEMENT_SENSOR_PREFIX,@@ -179,7 +169,7 @@ class ZoneMinderMonitor( PeriodicMonitor ):),value = str(SensorValue.MOVEMENT_ACTIVE),timestamp = zm_event.start_datetime,- details = json.dumps( event_details ),+ details = SensorResponseHelper.event_to_details( zm_event = zm_event ),)def _create_movement_idle_sensor_response( self, zm_event : ZmEvent ):diff --git a/src/hi/settings/development.py b/src/hi/settings/development.pyindex 5d6455e8..b7144c86 100644--- a/src/hi/settings/development.py+++ b/src/hi/settings/development.py@@ -4,6 +4,86 @@ from .base import *# SECURITY WARNING: don't run with debug turned on in production!DEBUG = True+ALLOWED_HOSTS = [+ '127.0.0.1',+ '192.168.100.6',+ '192.168.100.112',+ 'localhost',+]++# Content Security Policy Settings for CSPMiddleware+#+CORS_ALLOWED_ORIGINS = [+ 'http://127.0.0.1:8000',+ 'http://localhost:8000',+ 'http://192.168.100.6:8008',+]+CSP_DEFAULT_SRC = (+ "'self'",+ 'data:',+ 'http://127.0.0.1:8000',+ 'http://localhost:8000',+ 'http://192.168.100.6:8008',+)+CSP_CONNECT_SRC = (+ "'self'",+ 'http://127.0.0.1:8000',+ 'http://localhost:8000',+ 'http://192.168.100.6:8008',+ "ws://127.0.0.1:8000",+ "ws://localhost:8000",+ 'ws://192.168.100.6:8008',+ 'ws://192.168.100.80:8000',+)+CSP_FRAME_SRC = [+ "'self'",+ 'http://127.0.0.1:8000',+ 'http://localhost:8000',+ 'http://192.168.100.6:8008',+ 'https://player.vimeo.com',+]++CSP_SCRIPT_SRC = (+ "'self'",+ "'unsafe-inline'",+ "'unsafe-eval'",+ 'http://127.0.0.1:8000',+ 'http://localhost:8000',+ 'http://192.168.100.6:8008',+ 'https://bordeaux:8443',+)+CSP_STYLE_SRC = (+ "'self'",+ "'unsafe-inline'",+ "'unsafe-eval'",+)++CSP_MEDIA_SRC = [+ "'self'",+ "'unsafe-inline'",+ "'unsafe-eval'",+ 'data:',+ 'http://127.0.0.1:8000',+ 'http://localhost:8000',+ 'http://192.168.100.6:8008',+ 'https://bordeaux:8443',+]++CSP_IMG_SRC = [+ "'self'",+ 'data:',+ 'https://bordeaux:8443',+]++CSP_CHILD_SRC = [+ "'self'",+]++CSP_FONT_SRC = [+ "'self'",+ 'data:',+]+STATIC_ROOT = '/tmp/hi/static'LOGGING = {