Home Information - Your home, your data, organized.
Python
Fixed some ZoneMinder monitor bugs. Added sensor value template scheme.
Anthony Cassandra7efadc5c8855
diff --git a/src/hi/apps/common/templatetags/common_template_helpers.py b/src/hi/apps/common/templatetags/common_template_helpers.pyindex 258d96fd..840c94f0 100644--- a/src/hi/apps/common/templatetags/common_template_helpers.py+++ b/src/hi/apps/common/templatetags/common_template_helpers.py@@ -4,6 +4,7 @@ import urllibfrom django import templatefrom django.conf import settingsfrom django.template import engines+from django.template.loader import get_templatefrom django.urls import reverseregister = template.Library()@@ -86,7 +87,22 @@ def include_media_template( context, file_path ):file_content = file.read()template_engine = engines['django']- template_obj = template_engine.from_string(file_content)+ template_obj = template_engine.from_string( file_content )context_dict = context.flatten()- return template_obj.render(context_dict)+ return template_obj.render( context_dict )++[email protected]_tag( takes_context = True )+def include_with_fallback( context, template_name : str, fallback_name : str ):+ """+ Use the specified template_name and falls back to fallback_name if the+ first template does not exist.+ """+ try:+ template_obj = get_template( template_name )+ except Exception:+ template_obj = get_template( fallback_name )++ context_dict = context.flatten()+ return template_obj.render( context_dict )diff --git a/src/hi/apps/entity/entity_manager.py b/src/hi/apps/entity/entity_manager.pyindex f626dd9c..28316c32 100644--- a/src/hi/apps/entity/entity_manager.py+++ b/src/hi/apps/entity/entity_manager.py@@ -8,6 +8,7 @@ from hi.apps.entity.edit.forms import EntityPositionFormfrom hi.apps.location.models import Location, LocationViewfrom hi.apps.location.svg_item_factory import SvgItemFactoryfrom hi.apps.sense.sensor_history_manager import SensorHistoryManager+from hi.apps.sense.transient_models import SensorResponsefrom .delegation_manager import DelegationManagerfrom .enums import (@@ -44,16 +45,21 @@ class EntityManager(Singleton):entity = entity,max_items = self.ENTITY_INFO_SENSOR_HISTORY_ITEM_MAX,)-- entity_state_list = list(- entity.states.all()- )+ latest_sensor_response_map = dict()+ for sensor, sensor_history_list in sensor_history_list_map.items():+ if sensor_history_list:+ sensor_response = SensorResponse.from_sensor_history( sensor_history = sensor_history_list[0] )+ else:+ sensor_response = None+ latest_sensor_response_map[sensor] = sensor_response+ continue+principal_entity_list = self.get_principal_entity_list( entity = entity )return EntityInfoData(entity_edit_data = entity_edit_data,sensor_history_list_map = sensor_history_list_map,- entity_state_list = entity_state_list,+ latest_sensor_response_map = latest_sensor_response_map,principal_entity_list = principal_entity_list,)diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.pyindex 05fec088..658e24e7 100644--- a/src/hi/apps/entity/enums.py+++ b/src/hi/apps/entity/enums.py@@ -102,7 +102,16 @@ class EntityStateType(LabeledEnum):VIDEO_STREAM = ( 'Video Stream' , '' )WATER_FLOW = ( 'Water Flow' , '' )WIND_SPEED = ( 'Wind Speed' , '' )-++ def value_template_name(self):+ """+ Template used to render a sensor's value for this state. Create the+ template at the given location to define a state-specific rendering, else+ it will fallback to the default template of+ "entity/panes/sensor_value_default.html"+ """+ return f'entity/panes/sensor_value_{self.name.lower()}.html'+class AttributeName(LabeledEnum):# Common attribute namesdiff --git a/src/hi/apps/entity/templates/entity/modals/entity_info.html b/src/hi/apps/entity/templates/entity/modals/entity_info.htmlindex d3c452c8..ba6817cb 100644--- a/src/hi/apps/entity/templates/entity/modals/entity_info.html+++ b/src/hi/apps/entity/templates/entity/modals/entity_info.html@@ -1,4 +1,5 @@{% extends "modals/action_done.html" %}+{% load common_template_helpers %}{% block title_text %}{{ entity.name }}@@ -6,7 +7,18 @@{% block body %}-<h5>Sensor Responses</h5>+<h5>Latest Sensor Responses</h5>+<ul>+ {% for sensor, sensor_response in latest_sensor_response_map.items %}+ <li>Sensor: {{ sensor.name }}+ {% include_with_fallback sensor_response.sensor.entity_state.entity_state_type.value_template_name "entity/panes/sensor_value_default.html" %}+ </li>+ {% empty %}+ <div><em>No sensors</em></div>+ {% endfor %}+</ul>++<h5>Sensor History</h5><ul>{% for sensor, sensor_history_list in sensor_history_list_map.items %}<li>Sensor: {{ sensor.name }}@@ -26,8 +38,6 @@{% endfor %}</ul>-{% include "entity/panes/entity_state_info_list.html" with entity_state_list=entity_state_list title='States'%}-<div>{% include "entity/edit/panes/entity_edit.html" %}</div>diff --git a/src/hi/apps/entity/templates/entity/panes/entity_state_info_list.html b/src/hi/apps/entity/templates/entity/panes/entity_state_info_list.htmldeleted file mode 100644index 9efffbe9..00000000--- a/src/hi/apps/entity/templates/entity/panes/entity_state_info_list.html+++ /dev/null@@ -1,34 +0,0 @@-<div>- <h4>{{ title }}</h4>- <ul>- {% for entity_state in entity_state_list %}- <li>- {{ entity_state.name }} [{{ entity_state.entity_state_type }}]- <ul>- <li>- Sensors- <ul>- {% for sensor in entity_state.sensors.all %}- <li>{{ sensor.name }}</li>- {% empty %}- <em>No sensors</em>- {% endfor %}- </ul>- </li>- <li>- Controllers- <ul>- {% for controller in entity_state.controllers.all %}- <li>{{ controller.name }}</li>- {% empty %}- <em>No controllers</em>- {% endfor %}- </ul>- </li>- </ul>- </li>- {% empty %}- <em>No states</em>- {% endfor %}- </ul>-</div>diff --git a/src/hi/apps/entity/templates/entity/panes/sensor_value_default.html b/src/hi/apps/entity/templates/entity/panes/sensor_value_default.htmlnew file mode 100644index 00000000..96422509--- /dev/null+++ b/src/hi/apps/entity/templates/entity/panes/sensor_value_default.html@@ -0,0 +1 @@+{{ sensor_response.value }}diff --git a/src/hi/apps/entity/templates/entity/panes/sensor_value_video_stream.html b/src/hi/apps/entity/templates/entity/panes/sensor_value_video_stream.htmlnew file mode 100644index 00000000..f30659cc--- /dev/null+++ b/src/hi/apps/entity/templates/entity/panes/sensor_value_video_stream.html@@ -0,0 +1,3 @@+<img class="img-fluid"+ src="{{ sensor_response.value }}"+ alt="Latest sensor response for {{ sensor_response.sensor.name }}">diff --git a/src/hi/apps/entity/transient_models.py b/src/hi/apps/entity/transient_models.pyindex 271651af..2df60a1e 100644--- a/src/hi/apps/entity/transient_models.py+++ b/src/hi/apps/entity/transient_models.py@@ -8,6 +8,7 @@ from hi.apps.entity.edit.forms import (EntityAttributeUploadForm,)from hi.apps.sense.models import Sensor, SensorHistory+from hi.apps.sense.transient_models import SensorResponsefrom .enums import EntityTypefrom .models import Entity, EntityState@@ -69,10 +70,10 @@ class EntityEditData:class EntityInfoData:""" All the data needed to render the Entity info modal. """- entity_edit_data : EntityEditData- sensor_history_list_map : Dict[ Sensor, List[ SensorHistory ] ]- entity_state_list : List[ EntityState ]- principal_entity_list : List[ Entity ]+ entity_edit_data : EntityEditData+ sensor_history_list_map : Dict[ Sensor, List[ SensorHistory ] ]+ latest_sensor_response_map : Dict[ Sensor, SensorResponse ]+ principal_entity_list : List[ Entity ]@propertydef entity(self):@@ -82,7 +83,7 @@ class EntityInfoData:context = {'entity': self.entity,'sensor_history_list_map': self.sensor_history_list_map,- 'entity_state_list': self.entity_state_list,+ 'latest_sensor_response_map': self.latest_sensor_response_map,'principal_entity_list': self.principal_entity_list,}context.update( self.entity_edit_data.to_template_context() )diff --git a/src/hi/apps/sense/transient_models.py b/src/hi/apps/sense/transient_models.pyindex 2476a748..c292291b 100644--- a/src/hi/apps/sense/transient_models.py+++ b/src/hi/apps/sense/transient_models.py@@ -35,6 +35,16 @@ class SensorResponse:details = self.details,)+ @classmethod+ def from_sensor_history( self, sensor_history : SensorHistory ) -> 'SensorResponse':+ return SensorResponse(+ integration_key = sensor_history.sensor.integration_key,+ value = sensor_history.value,+ timestamp = sensor_history.response_datetime,+ sensor = sensor_history.sensor,+ details = sensor_history.details,+ )+@classmethoddef from_string( self, sensor_reading_str : str ) -> 'SensorResponse':sensor_reading_dict = json.loads( sensor_reading_str )diff --git a/src/hi/integrations/zoneminder/enums.py b/src/hi/integrations/zoneminder/enums.pyindex 7f13042b..e21525b8 100644--- a/src/hi/integrations/zoneminder/enums.py+++ b/src/hi/integrations/zoneminder/enums.py@@ -44,7 +44,7 @@ class ZmAttributeType( IntegrationAttributeType ):)-class ZmMonitorState(LabeledEnum):+class ZmMonitorFunction(LabeledEnum):NONE = ( 'None', '' )MONITOR = ( 'Monitor', '' )diff --git a/src/hi/integrations/zoneminder/zm_manager.py b/src/hi/integrations/zoneminder/zm_manager.pyindex 95f25626..d2d22e42 100644--- a/src/hi/integrations/zoneminder/zm_manager.py+++ b/src/hi/integrations/zoneminder/zm_manager.py@@ -3,7 +3,6 @@ from pyzm.api import ZMApifrom pyzm.helpers.Monitor import Monitor as ZmMonitorfrom pyzm.helpers.globals import logger as pyzm_loggerfrom typing import Dict-from urllib.parse import urlparsefrom django.db import transaction@@ -21,7 +20,7 @@ from hi.integrations.core.models import Integration, IntegrationAttributefrom .enums import (ZmAttributeType,- ZmMonitorState,+ ZmMonitorFunction,)from .zm_metadata import ZmMetaData@@ -38,7 +37,7 @@ class ZoneMinderManager( Singleton ):VIDEO_STREAM_SENSOR_PREFIX = 'monitor.video_stream'MOVEMENT_SENSOR_PREFIX = 'monitor.motion'- MONITOR_STATE_SENSOR_PREFIX = 'monitor.state'+ MONITOR_FUNCTION_SENSOR_PREFIX = 'monitor.function'SYNCHRONIZATION_LOCK_NAME = 'zm_integration_sync'@@ -230,11 +229,11 @@ class ZoneMinderManager( Singleton ):HiModelHelper.create_discrete_controller(entity = entity,integration_key = self._sensor_to_integration_key(- sensor_prefix = self.MONITOR_STATE_SENSOR_PREFIX,+ sensor_prefix = self.MONITOR_FUNCTION_SENSOR_PREFIX,zm_monitor_id = zm_monitor.id(),),- name = f'{entity.name} State',- value_list = [ str(x) for x in ZmMonitorState ],+ name = f'{entity.name} Function',+ value_list = [ str(x) for x in ZmMonitorFunction ],)result.message_list.append( f'Create new camera entity: {entity}' )returndiff --git a/src/hi/integrations/zoneminder/zm_monitor.py b/src/hi/integrations/zoneminder/zm_monitor.pyindex 0f96617f..25e32022 100644--- a/src/hi/integrations/zoneminder/zm_monitor.py+++ b/src/hi/integrations/zoneminder/zm_monitor.py@@ -66,7 +66,6 @@ class ZoneMinderMonitor( PeriodicMonitor ):async def do_work(self):current_poll_datetime = datetimeproxy.min()-options = {'from': self._poll_from_datetime.isoformat(), # This "from" only looks at event start time'tz': self._zm_tzname,@@ -128,11 +127,24 @@ class ZoneMinderMonitor( PeriodicMonitor ):sensor_response_map[idle_sensor_response.integration_key] = idle_sensor_responseself._fully_processed_event_ids[zm_event.event_id] = Truecontinue-+# If there are no events for a monitor, we still want to emit the# sensor response of it being idle.#for zm_monitor in self._get_zm_monitors():++ video_stream_sensor_response = self._create_video_stream_sensor_response(+ zm_monitor = zm_monitor,+ timestamp = current_poll_datetime,+ )+ sensor_response_map[video_stream_sensor_response.integration_key] = video_stream_sensor_response++ function_sensor_response = self._create_monitor_function_sensor_response(+ zm_monitor = zm_monitor,+ timestamp = current_poll_datetime,+ )+ sensor_response_map[function_sensor_response.integration_key] = function_sensor_response+if zm_monitor.id() not in zm_monitor_ids_seen:idle_sensor_response = self._create_idle_sensor_response(zm_monitor = zm_monitor,@@ -140,7 +152,7 @@ class ZoneMinderMonitor( PeriodicMonitor ):)sensor_response_map[idle_sensor_response.integration_key] = idle_sensor_responsecontinue-+await self._sensor_response_manager.update_with_latest_sensor_responses(sensor_response_map = sensor_response_map,)@@ -173,7 +185,8 @@ class ZoneMinderMonitor( PeriodicMonitor ):def _get_zm_monitors(self) -> List[ ZmMonitor ]:monitor_list_age = datetimeproxy.now() - self._zm_monitor_timestamp- if monitor_list_age.seconds > self.MONITOR_REFRESH_INTERVAL_SECS:+ if (( not self._zm_monitor_list )+ or ( monitor_list_age.seconds > self.MONITOR_REFRESH_INTERVAL_SECS )):self._zm_monitor_list = self._zm_manager.zm_client.monitors().list()self._zm_monitor_timestamp = datetimeproxy.now()return self._zm_monitor_list@@ -208,4 +221,24 @@ class ZoneMinderMonitor( PeriodicMonitor ):value = str(SensorValue.MOVEMENT_IDLE),timestamp = timestamp,)++ def _create_video_stream_sensor_response( self, zm_monitor : ZmMonitor, timestamp : datetime ):+ return SensorResponse(+ integration_key = self._zm_manager._sensor_to_integration_key(+ sensor_prefix = self._zm_manager.VIDEO_STREAM_SENSOR_PREFIX,+ zm_monitor_id = zm_monitor.id(),+ ),+ value = self._zm_manager.get_video_stream_url( monitor_id = zm_monitor.id() ),+ timestamp = timestamp,+ )++ def _create_monitor_function_sensor_response( self, zm_monitor : ZmMonitor, timestamp : datetime ):+ return SensorResponse(+ integration_key = self._zm_manager._sensor_to_integration_key(+ sensor_prefix = self._zm_manager.MONITOR_FUNCTION_SENSOR_PREFIX,+ zm_monitor_id = zm_monitor.id(),+ ),+ value = str( zm_monitor.function() ),+ timestamp = timestamp,+ )