Skip to content

Home Information - Your home, your data, organized.

Python

Refactoring of ZoneMinder integration module. Prep for controllers.

Anthony Cassandra72cf82804ea5
diff --git a/src/hi/apps/control/views.py b/src/hi/apps/control/views.py
index 1bd13dc2..70ef7f09 100644
--- a/src/hi/apps/control/views.py
+++ b/src/hi/apps/control/views.py
@@ -26,18 +26,18 @@ class ControllerView( View, ControlViewMixin ):
# zzz Check against latest state value????
-
-
+ integration_factory = IntegrationFactory()
+ integration_gateway = IntegrationFactory().get_integration_gateway(
+ integration_id = controller.integration_id,
+ )
+ integration_controller = integration_gateway.get_controller()
error_messages = list()
- integration_gateway = IntegrationFactory().get_integration_gateway(
- integration_id = controller.integration_id,
- )
- control_result = integration_gateway.do_control(
- controller_integration_key = controller.integration_key,
+ control_result = integration_controller.do_control(
+ integration_key = controller.integration_key,
control_value = control_value,
)
diff --git a/src/hi/integrations/core/integration_controller.py b/src/hi/integrations/core/integration_controller.py
new file mode 100644
index 00000000..fa3ff3a8
--- /dev/null
+++ b/src/hi/integrations/core/integration_controller.py
@@ -0,0 +1,10 @@
+from .integration_key import IntegrationKey
+from .transient_models import IntegrationControlResult
+
+
+class IntegrationController:
+
+ def do_control( self,
+ integration_key : IntegrationKey,
+ control_value : str ) -> IntegrationControlResult:
+ raise NotImplementedError('Subclasses must override this method')
diff --git a/src/hi/integrations/core/integration_factory.py b/src/hi/integrations/core/integration_factory.py
index e6e9eb90..02cc82ec 100644
--- a/src/hi/integrations/core/integration_factory.py
+++ b/src/hi/integrations/core/integration_factory.py
@@ -72,7 +72,7 @@ class IntegrationFactory( Singleton ):
try:
integration = Integration.objects.get( integration_id = integration_id )
if integration.is_enabled:
- periodic_monitor = integration_gateway.get_monitor()
+ periodic_monitor = integration_gateway.get_sensor_monitor()
self._integration_monitor_map[integration_id] = periodic_monitor
MonitorManager().register( periodic_monitor )
except Integration.DoesNotExist:
diff --git a/src/hi/integrations/core/integration_gateway.py b/src/hi/integrations/core/integration_gateway.py
index 1111437d..de2229c4 100644
--- a/src/hi/integrations/core/integration_gateway.py
+++ b/src/hi/integrations/core/integration_gateway.py
@@ -2,8 +2,8 @@ from django.http import HttpRequest, HttpResponse
from hi.apps.monitor.periodic_monitor import PeriodicMonitor
-from .integration_key import IntegrationKey
-from .transient_models import IntegrationControlResult, IntegrationMetaData
+from .integration_controller import IntegrationController
+from .transient_models import IntegrationMetaData
class IntegrationGateway:
@@ -14,7 +14,10 @@ class IntegrationGateway:
def get_meta_data(self) -> IntegrationMetaData:
raise NotImplementedError('Subclasses must override this method')
- def get_monitor(self) -> PeriodicMonitor:
+ def get_sensor_monitor(self) -> PeriodicMonitor:
+ raise NotImplementedError('Subclasses must override this method')
+
+ def get_controller(self) -> IntegrationController:
raise NotImplementedError('Subclasses must override this method')
def enable_modal_view( self, request : HttpRequest, *args, **kwargs ) -> HttpResponse:
@@ -30,9 +33,3 @@ class IntegrationGateway:
details_str : str ) -> HttpResponse:
# Should return a modal via antinode.modal_from_template() (called async)
raise NotImplementedError('Subclasses must override this method')
-
- def do_control( self,
- controller_integration_key : IntegrationKey,
- control_value : str ) -> IntegrationControlResult:
- # 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/transient_models.py b/src/hi/integrations/core/transient_models.py
index 245c29ef..d68397e9 100644
--- a/src/hi/integrations/core/transient_models.py
+++ b/src/hi/integrations/core/transient_models.py
@@ -1,5 +1,7 @@
from dataclasses import dataclass
+from hi.apps.common.processing_result import ProcessingResult
+
from .enums import IntegrationAttributeType
from .models import Integration
@@ -23,4 +25,5 @@ class IntegrationData:
@dataclass
class IntegrationControlResult:
- pass
+ new_value : str
+ processing_result : ProcessingResult
diff --git a/src/hi/integrations/hass/hass_controller.py b/src/hi/integrations/hass/hass_controller.py
new file mode 100644
index 00000000..59c0ae45
--- /dev/null
+++ b/src/hi/integrations/hass/hass_controller.py
@@ -0,0 +1,15 @@
+from hi.integrations.core.integration_controller import IntegrationController
+from hi.integrations.core.integration_key import IntegrationKey
+from hi.integrations.core.transient_models import IntegrationControlResult
+
+
+class HassController( IntegrationController ):
+
+ def do_control( self,
+ integration_key : IntegrationKey,
+ control_value : str ) -> IntegrationControlResult:
+
+ # zzz Needs implementation
+
+ return IntegrationControlResult()
+
diff --git a/src/hi/integrations/hass/hass_gateway.py b/src/hi/integrations/hass/hass_gateway.py
index 9743828d..b627c1ac 100644
--- a/src/hi/integrations/hass/hass_gateway.py
+++ b/src/hi/integrations/hass/hass_gateway.py
@@ -2,11 +2,12 @@ import logging
from django.http import HttpRequest, HttpResponse
+from hi.integrations.core.integration_controller import IntegrationController
from hi.integrations.core.integration_gateway import IntegrationGateway
-from hi.integrations.core.integration_key import IntegrationKey
-from hi.integrations.core.transient_models import IntegrationControlResult, IntegrationMetaData
+from hi.integrations.core.transient_models import IntegrationMetaData
from hi.apps.monitor.periodic_monitor import PeriodicMonitor
+from .hass_controller import HassController
from .hass_metadata import HassMetaData
from .hass_monitor import HassMonitor
from . import views
@@ -19,9 +20,12 @@ class HassGateway( IntegrationGateway ):
def get_meta_data(self) -> IntegrationMetaData:
return HassMetaData
- def get_monitor(self) -> PeriodicMonitor:
+ def get_sensor_monitor(self) -> PeriodicMonitor:
return HassMonitor()
+ def get_controller(self) -> IntegrationController:
+ return HassController()
+
def enable_modal_view( self, request : HttpRequest, *args, **kwargs ) -> HttpResponse:
return views.HassEnableView().get( request )
@@ -35,12 +39,3 @@ class HassGateway( IntegrationGateway ):
request,
details_str = details_str,
)
-
- def do_control( self,
- controller_integration_key : IntegrationKey,
- control_value : str ) -> IntegrationControlResult:
-
- # zzz Needs implementation
-
-
- return IntegrationControlResult()
diff --git a/src/hi/integrations/hass/hass_manager.py b/src/hi/integrations/hass/hass_manager.py
index cae0c727..07a8a5ff 100644
--- a/src/hi/integrations/hass/hass_manager.py
+++ b/src/hi/integrations/hass/hass_manager.py
@@ -206,4 +206,3 @@ class HassManager( Singleton ):
entity.delete() # Deletion cascades to attributes, positions, sensors, controllers, etc.
result.message_list.append( f'Removed stale HAss entity: {entity}' )
return
-
diff --git a/src/hi/integrations/zoneminder/views.py b/src/hi/integrations/zoneminder/views.py
index 60bf6077..c265ad9d 100644
--- a/src/hi/integrations/zoneminder/views.py
+++ b/src/hi/integrations/zoneminder/views.py
@@ -17,6 +17,7 @@ from .sensor_response_helper import SensorResponseHelper
from .zm_manager import ZoneMinderManager
from .zm_models import ZmEventDetails
from .zm_metadata import ZmMetaData
+from .zm_sync import ZoneMinderSynchronizer
class ZmEnableView( HiModalView, IntegrationHelperMixin ):
@@ -154,7 +155,7 @@ class ZmSyncView( HiModalView ):
def post(self, request, *args, **kwargs):
- processing_result = ZoneMinderManager().sync()
+ processing_result = ZoneMinderSynchronizer().sync()
context = {
'processing_result': processing_result,
}
diff --git a/src/hi/integrations/zoneminder/zm_controller.py b/src/hi/integrations/zoneminder/zm_controller.py
new file mode 100644
index 00000000..64e9fb62
--- /dev/null
+++ b/src/hi/integrations/zoneminder/zm_controller.py
@@ -0,0 +1,97 @@
+import logging
+import re
+
+from hi.apps.common.processing_result import ProcessingResult
+
+from hi.integrations.core.integration_controller import IntegrationController
+from hi.integrations.core.integration_key import IntegrationKey
+from hi.integrations.core.transient_models import IntegrationControlResult
+
+from .zm_manager import ZoneMinderManager
+
+logger = logging.getLogger(__name__)
+
+
+class ZoneMinderController( IntegrationController ):
+
+ def __init__(self):
+ self._zm_manager = ZoneMinderManager()
+ return
+
+ def do_control( self,
+ integration_key : IntegrationKey,
+ control_value : str ) -> IntegrationControlResult:
+
+ if integration_key.integration_name == self._zm_manager.ZM_RUN_STATE_SENSOR_INTEGRATION_NAME:
+ return self.set_run_state( run_state_value = control_value )
+
+ if integration_key.integration_name.startswith( self._zm_manager.MONITOR_FUNCTION_SENSOR_PREFIX ):
+ m = re.match( r'.+\D(\d+)', integration_key.integration_name )
+ if m:
+ return self.set_monitor_function(
+ monitor_id = m.group(1),
+ function_value = control_value,
+ )
+
+ logger.warning( f'Unknown ZM control action. key={integration_key}, value={control_value}' )
+ return IntegrationControlResult(
+ new_value = None,
+ error_messages = [ 'Unknown ZM control action.' ]
+ )
+
+ def set_run_state( self, run_state_value : str ):
+ result = ProcessingResult( title = 'ZM Set Monitors' )
+ try:
+ response = self._zm_manager._zm_client.set_state( run_state_value )
+ logger.debug( f'ZM Set run state to "{run_state_value}" = {response}' )
+ return IntegrationControlResult(
+ new_value = run_state_value,
+ processing_result = result,
+ )
+ except Exception as e:
+ logger.error( f'Exception setting ZM run state: {e}' )
+ result.error_list.append( str(e) )
+ return IntegrationControlResult(
+ new_value = None,
+ processing_result = result,
+ )
+ finally:
+ self._zm_manager.clear_caches()
+
+ def set_monitor_function( self,
+ monitor_id : str,
+ function_value : str ):
+ result = ProcessingResult( title = 'ZM Set Monitor Function' )
+ try:
+ zm_monitor_list = self._zm_manager.get_zm_monitors()
+ for zm_monitor in zm_monitor_list:
+ if str(zm_monitor.id()) == str(monitor_id):
+ response = zm_monitor.set_parameter({
+ 'function': function_value,
+ })
+ logger.debug( f'ZM Set monitor: {monitor_id}={function_value}, response={response}' )
+ response_message = response.get('message')
+ if response_message and ( 'error' in response_message.lower() ):
+ result.error_list.append( 'Problen setting ZM monitor function.')
+ return IntegrationControlResult(
+ new_value = function_value,
+ processing_result = result,
+ )
+ else:
+ logger.debug( f'Skipping ZM monitor: {zm_monitor.id()} != {monitor_id}' )
+ continue
+
+ result.error_list.append( 'Unknown ZM monitor.')
+ return IntegrationControlResult(
+ new_value = None,
+ processing_result = result,
+ )
+ except Exception as e:
+ logger.error( f'Exception setting ZM monitor function: {e}' )
+ result.error_list.append( str(e) )
+ return IntegrationControlResult(
+ new_value = None,
+ processing_result = result,
+ )
+ finally:
+ self._zm_manager.clear_caches()
diff --git a/src/hi/integrations/zoneminder/zm_gateway.py b/src/hi/integrations/zoneminder/zm_gateway.py
index 85e9ddd3..9662e8ab 100644
--- a/src/hi/integrations/zoneminder/zm_gateway.py
+++ b/src/hi/integrations/zoneminder/zm_gateway.py
@@ -2,11 +2,12 @@ import logging
from django.http import HttpRequest, HttpResponse
+from hi.integrations.core.integration_controller import IntegrationController
from hi.integrations.core.integration_gateway import IntegrationGateway
-from hi.integrations.core.integration_key import IntegrationKey
-from hi.integrations.core.transient_models import IntegrationControlResult, IntegrationMetaData
+from hi.integrations.core.transient_models import IntegrationMetaData
from hi.apps.monitor.periodic_monitor import PeriodicMonitor
+from .zm_controller import ZoneMinderController
from .zm_metadata import ZmMetaData
from .zm_monitor import ZoneMinderMonitor
from . import views
@@ -19,9 +20,12 @@ class ZoneMinderGateway( IntegrationGateway ):
def get_meta_data(self) -> IntegrationMetaData:
return ZmMetaData
- def get_monitor(self) -> PeriodicMonitor:
+ def get_sensor_monitor(self) -> PeriodicMonitor:
return ZoneMinderMonitor()
+ def get_controller(self) -> IntegrationController:
+ return ZoneMinderController()
+
def enable_modal_view( self, request : HttpRequest, *args, **kwargs ) -> HttpResponse:
return views.ZmEnableView().get( request )
@@ -35,12 +39,3 @@ class ZoneMinderGateway( IntegrationGateway ):
request,
details_str = details_str,
)
-
- def do_control( self,
- controller_integration_key : IntegrationKey,
- control_value : str ) -> IntegrationControlResult:
-
- # zzz Needs implementation
-
-
- return IntegrationControlResult()
diff --git a/src/hi/integrations/zoneminder/zm_manager.py b/src/hi/integrations/zoneminder/zm_manager.py
index c1bec7c3..56bfc81b 100644
--- a/src/hi/integrations/zoneminder/zm_manager.py
+++ b/src/hi/integrations/zoneminder/zm_manager.py
@@ -1,30 +1,19 @@
-import json
import logging
from pyzm.api import ZMApi
+from pyzm.helpers.Event import Event as ZmEvent
from pyzm.helpers.Monitor import Monitor as ZmMonitor
from pyzm.helpers.State import State as ZmState
from pyzm.helpers.globals import logger as pyzm_logger
from typing import Dict, List
-from django.db import transaction
-
-from hi.apps.common.database_lock import ExclusionLockContext
-from hi.apps.common.processing_result import ProcessingResult
+import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.common.singleton import Singleton
-from hi.apps.entity.enums import EntityType
-from hi.apps.entity.models import Entity
-from hi.apps.sense.models import Sensor
-
-from hi.apps.model_helper import HiModelHelper
from hi.integrations.core.exceptions import IntegrationAttributeError
from hi.integrations.core.integration_key import IntegrationKey
from hi.integrations.core.models import Integration, IntegrationAttribute
-from .enums import (
- ZmAttributeType,
- ZmMonitorFunction,
-)
+from .enums import ZmAttributeType
from .zm_metadata import ZmMetaData
logger = logging.getLogger(__name__)
@@ -45,12 +34,23 @@ class ZoneMinderManager( Singleton ):
MOVEMENT_SENSOR_PREFIX = 'monitor.motion'
MONITOR_FUNCTION_SENSOR_PREFIX = 'monitor.function'
ZM_RUN_STATE_SENSOR_INTEGRATION_NAME = 'run.state'
-
- SYNCHRONIZATION_LOCK_NAME = 'zm_integration_sync'
+ # ZM monitors and states will not change frequently, so we do not need
+ # to query for them at a high frequency.
+ #
+ STATE_REFRESH_INTERVAL_SECS = 300
+ MONITOR_REFRESH_INTERVAL_SECS = 300
+
def __init_singleton__( self ):
self._is_loading = False
self._zm_client = None
+
+ self._zm_state_list = list()
+ self._zm_state_timestamp = datetimeproxy.min()
+
+ self._zm_monitor_list = list()
+ self._zm_monitor_timestamp = datetimeproxy.min()
+
self.reload()
return
@@ -67,12 +67,18 @@ class ZoneMinderManager( Singleton ):
try:
self._is_loading = True
self._zm_client = self.create_zm_client()
-
+ self.clear_caches()
+
finally:
self._is_loading = False
logger.debug( 'ZoneMinder manager loading completed.' )
return
+ def clear_caches(self):
+ self._zm_state_list = list()
+ self._zm_monitor_list = list()
+ return
+
def create_zm_client(self):
try:
zm_integration = Integration.objects.get( integration_id = ZmMetaData.integration_id )
@@ -114,233 +120,29 @@ class ZoneMinderManager( Singleton ):
logger.debug( f'ZoneMinder client options: {api_options}' )
return ZMApi( options = api_options )
-
- def sync( self ) -> ProcessingResult:
- try:
- with ExclusionLockContext( name = self.SYNCHRONIZATION_LOCK_NAME ):
- logger.debug( 'ZoneMinder integration sync started.' )
- return self._sync_helper()
- except RuntimeError as e:
- return ProcessingResult(
- title = 'ZM Sync Result',
- error_list = [ str(e) ],
- )
- finally:
- logger.debug( 'ZoneMinder integration sync ended.' )
-
- def _sync_helper( self ) -> ProcessingResult:
- result = ProcessingResult( title = 'ZM Sync Result' )
-
- if not self.zm_client:
- logger.debug( 'ZoneMinder client not created. ZM integration disabled?' )
- result.error_list.append( 'Sync problem. ZM integration disabled?' )
- return result
-
- self._sync_states( result = result )
- self._sync_monitors( result = result )
-
- return result
-
- def _sync_states( self, result : ProcessingResult ) -> ProcessingResult:
-
- zm_run_state_list = self._fetch_zm_run_states()
- new_state_values_dict = { x.name(): x.name() for x in zm_run_state_list }
-
- zm_entity = Entity.objects.filter_by_integration_key(
- integration_key = self._zm_integration_key(),
- ).first()
-
- if not zm_entity:
- _ = self._create_zm_entity(
- run_state_name_label_dict = new_state_values_dict,
- result = result,
- )
-
- zm_run_state_sensor = Sensor.objects.filter_by_integration_key(
- integration_key = self._zm_run_state_integration_key()
- ).select_related('entity_state').first()
-
- if not zm_run_state_sensor:
- result.error_list.append( 'Missing ZoneMinder sensor for ZM state.' )
- return
-
- entity_state = zm_run_state_sensor.entity_state
- new_state_values = new_state_values_dict.keys()
- existing_state_values_dict = entity_state.value_range_dict
- existing_state_values = existing_state_values_dict.keys()
-
- if existing_state_values != new_state_values:
- entity_state.value_range_dict = new_state_values_dict
- entity_state.save()
- result.message_list.append( f'Updated ZM state values to: {new_state_values_dict}' )
-
- return
-
- def _sync_monitors( self, result : ProcessingResult ) -> ProcessingResult:
-
- integration_key_to_monitor = self._fetch_zm_monitors( result = result )
- result.message_list.append( f'Found {len(integration_key_to_monitor)} current ZM monitors.' )
- integration_key_to_entity = self._get_existing_zm_monitor_entities( result = result )
- result.message_list.append( f'Found {len(integration_key_to_entity)} existing ZM entities.' )
-
- for integration_key, zm_monitor in integration_key_to_monitor.items():
- entity = integration_key_to_entity.get( integration_key )
- if entity:
- self._update_entity( entity = entity,
- zm_monitor = zm_monitor,
- result = result )
- else:
- self._create_monitor_entity( zm_monitor = zm_monitor,
- result = result )
- continue
-
- for integration_key, entity in integration_key_to_entity.items():
- if integration_key not in integration_key_to_monitor:
- self._remove_entity( entity = entity,
- result = result )
- continue
-
- return
-
- def _fetch_zm_monitors( self, result : ProcessingResult ) -> Dict[ IntegrationKey, ZmMonitor ]:
-
- logger.debug( 'Getting current ZM monitors.' )
- integration_key_to_monitor = dict()
- for zm_monitor in self.zm_client.monitors().list():
- integration_key = self._monitor_to_integration_key( zm_monitor_id = zm_monitor.id() )
- integration_key_to_monitor[integration_key] = zm_monitor
-
- logger.debug(
- '[ZM Monitor] Id:{} Name:{} Enabled:{} Status:{} Type:{} Dims:{}'.format(
- zm_monitor.id(),
- zm_monitor.name(),
- zm_monitor.enabled(),
- zm_monitor.status(),
- zm_monitor.type(),
- zm_monitor.dimensions(),
- )
- )
- continue
-
- return integration_key_to_monitor
+ def get_zm_states( self, force_load : bool = False ) -> List[ ZmState ]:
+ state_list_age = datetimeproxy.now() - self._zm_state_timestamp
+ if ( force_load
+ or ( not self._zm_state_list )
+ or ( state_list_age.seconds > self.STATE_REFRESH_INTERVAL_SECS )):
+ self._zm_state_list = self.zm_client.states().list()
+ self._zm_state_timestamp = datetimeproxy.now()
+ logger.debug( f'Fetched ZM states: {self._zm_state_list}' )
+ return self._zm_state_list
- def _fetch_zm_run_states( self ) -> List[ ZmState ]:
+ def get_zm_monitors( self, force_load : bool = False ) -> List[ ZmMonitor ]:
+ monitor_list_age = datetimeproxy.now() - self._zm_monitor_timestamp
+ if ( force_load
+ or ( not self._zm_monitor_list )
+ or ( monitor_list_age.seconds > self.MONITOR_REFRESH_INTERVAL_SECS )):
+ self._zm_monitor_list = self.zm_client.monitors().list()
+ self._zm_monitor_timestamp = datetimeproxy.now()
+ logger.debug( f'Fetched ZM monitors: {self._zm_monitor_list}' )
+ return self._zm_monitor_list
- logger.debug( 'Getting current ZM states.' )
- zm_run_state_list = list()
- for zm_run_state in self._zm_client.states().list():
- logger.debug(
- '[ZM State] {}'.format(
- zm_run_state.get(),
- )
- )
- zm_run_state_list.append( zm_run_state )
- continue
-
- return zm_run_state_list
-
- def _get_existing_zm_monitor_entities( self, result : ProcessingResult ) -> Dict[IntegrationKey, Entity]:
- logger.debug( 'Getting existing ZM entities.' )
- integration_key_to_entity = dict()
-
- entity_queryset = Entity.objects.filter( integration_id = ZmMetaData.integration_id )
- for entity in entity_queryset:
- integration_key = entity.integration_key
- if not integration_key:
- result.error_list.append( f'ZM entity found without integration name: {entity}' )
- mock_monitor_id = 1000000 + entity.id # We need a (unique) placeholder (will remove later)
- integration_key = IntegrationKey(
- integration_id = ZmMetaData.integration_id,
- integration_name = str( mock_monitor_id ),
- )
- if integration_key.integration_name.startswith( self.ZM_MONITOR_INTEGRATION_NAME_PREFIX ):
- integration_key_to_entity[integration_key] = entity
- continue
-
- return integration_key_to_entity
-
- def _create_zm_entity( self,
- run_state_name_label_dict : Dict[ str, str ],
- result : ProcessingResult ):
- with transaction.atomic():
- zm_entity = Entity(
- name = self.ZM_ENTITY_NAME,
- entity_type_str = str(EntityType.SERVICE),
- can_user_delete = ZmMetaData.allow_entity_deletion,
- )
- zm_entity.integration_key = self._zm_integration_key()
- zm_entity.save()
-
- HiModelHelper.create_discrete_controller(
- entity = zm_entity,
- integration_key = self._zm_run_state_integration_key(),
- name = f'{zm_entity.name} Run State',
- name_label_dict = run_state_name_label_dict,
- )
-
- result.message_list.append( f'Created ZM entity: {zm_entity}' )
- return zm_entity
-
- def _create_monitor_entity( self,
- zm_monitor : ZmMonitor,
- result : ProcessingResult ):
-
- with transaction.atomic():
- entity_integration_key = self._monitor_to_integration_key( zm_monitor_id = zm_monitor.id() )
- entity = Entity(
- name = zm_monitor.name(),
- entity_type_str = str(EntityType.CAMERA),
- can_user_delete = ZmMetaData.allow_entity_deletion,
- )
- entity.integration_key = entity_integration_key
- entity.save()
-
- HiModelHelper.create_video_stream_sensor(
- entity = entity,
- integration_key = self._sensor_to_integration_key(
- sensor_prefix = self.VIDEO_STREAM_SENSOR_PREFIX,
- zm_monitor_id = zm_monitor.id(),
- ),
- )
- HiModelHelper.create_movement_sensor(
- entity = entity,
- integration_key = self._sensor_to_integration_key(
- sensor_prefix = self.MOVEMENT_SENSOR_PREFIX,
- zm_monitor_id = zm_monitor.id(),
- ),
- )
- HiModelHelper.create_discrete_controller(
- entity = entity,
- integration_key = self._sensor_to_integration_key(
- sensor_prefix = self.MONITOR_FUNCTION_SENSOR_PREFIX,
- zm_monitor_id = zm_monitor.id(),
- ),
- name = f'{entity.name} Function',
- name_label_dict = { str(x): x.label for x in ZmMonitorFunction },
- )
- result.message_list.append( f'Create new camera entity: {entity}' )
- return
-
- def _update_entity( self,
- entity : Entity,
- zm_monitor : ZmMonitor,
- result : ProcessingResult ):
-
- if entity.name != zm_monitor.name():
- result.message_list.append(f'Name changed for {entity}. Setting to "{zm_monitor.name()}"')
- entity.name = zm_monitor.name()
- entity.save()
- else:
- result.message_list.append( f'No changes found for {entity}.' )
- return
-
- def _remove_entity( self,
- entity : Entity,
- result : ProcessingResult ):
- entity.delete() # Deletion cascades to attributes, positions, sensors, controllers, etc.
- result.message_list.append( f'Removed stale ZM entity: {entity}' )
- return
+ def get_zm_events( self, options : Dict[ str, str ] ) -> List[ ZmEvent ]:
+ return self.zm_client.events( options ).list()
def _zm_integration_key( self ) -> IntegrationKey:
return IntegrationKey(
@@ -360,7 +162,6 @@ class ZoneMinderManager( Singleton ):
return IntegrationKey(
integration_id = ZmMetaData.integration_id,
integration_name = f'{self.ZM_MONITOR_INTEGRATION_NAME_PREFIX}.{zm_monitor_id}',
-
)
def _sensor_to_integration_key( self, sensor_prefix : str, zm_monitor_id : int ) -> IntegrationKey:
@@ -394,4 +195,3 @@ class ZoneMinderManager( Singleton ):
def get_event_video_stream_url( self, event_id : int ):
return f'{self.zm_client.portal_url}/cgi-bin/nph-zms?mode=jpeg&scale=100&rate=5&maxfps=5&replay=single&source=event&event={event_id}'
-
diff --git a/src/hi/integrations/zoneminder/zm_monitor.py b/src/hi/integrations/zoneminder/zm_monitor.py
index 794d1860..845316e8 100644
--- a/src/hi/integrations/zoneminder/zm_monitor.py
+++ b/src/hi/integrations/zoneminder/zm_monitor.py
@@ -2,8 +2,6 @@ from cachetools import TTLCache
from datetime import datetime
import logging
from pyzm.helpers.Monitor import Monitor as ZmMonitor
-from pyzm.helpers.State import State as ZmState
-from typing import List
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.monitor.periodic_monitor import PeriodicMonitor
@@ -24,9 +22,6 @@ class ZoneMinderMonitor( PeriodicMonitor ):
# TODO: Move this into the integrations attributes for users to set
ZONEMINDER_SERVER_TIMEZONE = 'America/Chicago'
- MONITOR_REFRESH_INTERVAL_SECS = 600
- STATE_REFRESH_INTERVAL_SECS = 300
-
def __init__( self ):
super().__init__(
id = 'zm-monitor',
@@ -35,12 +30,6 @@ class ZoneMinderMonitor( PeriodicMonitor ):
self._zm_manager = ZoneMinderManager()
self._sensor_history_manager = SensorHistoryManager()
self._sensor_response_manager = SensorResponseManager()
-
- self._zm_monitor_list = list()
- self._zm_monitor_timestamp = datetimeproxy.min()
-
- self._zm_state_list = list()
- self._zm_state_timestamp = datetimeproxy.min()
self._fully_processed_event_ids = TTLCache( maxsize = 1000, ttl = 100000 )
self._start_processed_event_ids = TTLCache( maxsize = 1000, ttl = 100000 )
@@ -70,13 +59,23 @@ class ZoneMinderMonitor( PeriodicMonitor ):
return
async def do_work(self):
+ sensor_response_map = dict()
+ sensor_response_map.update( self._process_events( ) )
+ sensor_response_map.update( self._process_monitors() )
+ sensor_response_map.update( self._process_states() )
+
+ await self._sensor_response_manager.update_with_latest_sensor_responses(
+ sensor_response_map = sensor_response_map,
+ )
+ return
+
+ def _process_events(self):
current_poll_datetime = datetimeproxy.now()
options = {
'from': self._poll_from_datetime.isoformat(), # This "from" only looks at event start time
'tz': self._zm_tzname,
}
- response = self._zm_manager.zm_client.events( options )
- events = response.list()
+ events = self._zm_manager.get_zm_events( options = options )
if self.TRACE:
logger.debug( f"Found {len(events)} new ZM events" )
@@ -132,24 +131,11 @@ class ZoneMinderMonitor( PeriodicMonitor ):
sensor_response_map[idle_sensor_response.integration_key] = idle_sensor_response
self._fully_processed_event_ids[zm_event.event_id] = True
continue
-
+
# If there are no events for monitors/states, 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
-
+ for zm_monitor in self._zm_manager.get_zm_monitors():
if zm_monitor.id() not in zm_monitor_ids_seen:
idle_sensor_response = self._create_idle_sensor_response(
zm_monitor = zm_monitor,
@@ -157,25 +143,7 @@ class ZoneMinderMonitor( PeriodicMonitor ):
)
sensor_response_map[idle_sensor_response.integration_key] = idle_sensor_response
continue
-
- active_run_state_name = None
- for zm_state in self._get_zm_states():
- if zm_state.active():
- active_run_state_name = zm_state.name()
- break
- continue
-
- if active_run_state_name:
- run_state_sensor_response = self._create_run_state_sensor_response(
- run_state_name = active_run_state_name,
- timestamp = current_poll_datetime,
- )
- sensor_response_map[run_state_sensor_response.integration_key] = run_state_sensor_response
-
- await self._sensor_response_manager.update_with_latest_sensor_responses(
- sensor_response_map = sensor_response_map,
- )
-
+
if open_zm_event_list:
# Ensure that we will continue to poll for all the open events we
# currently see.
@@ -200,24 +168,49 @@ class ZoneMinderMonitor( PeriodicMonitor ):
#
pass
- return
+ return sensor_response_map
+
+ def _process_monitors(self):
+ current_poll_datetime = datetimeproxy.now()
+ sensor_response_map = dict()
+
+ for zm_monitor in self._zm_manager.get_zm_monitors():
- def _get_zm_monitors(self) -> List[ ZmMonitor ]:
- monitor_list_age = datetimeproxy.now() - self._zm_monitor_timestamp
- 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
+ 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
+ continue
- def _get_zm_states(self) -> List[ ZmState ]:
- state_list_age = datetimeproxy.now() - self._zm_state_timestamp
- if (( not self._zm_state_list )
- or ( state_list_age.seconds > self.STATE_REFRESH_INTERVAL_SECS )):
- self._zm_state_list = self._zm_manager.zm_client.states().list()
- self._zm_state_timestamp = datetimeproxy.now()
- return self._zm_state_list
+ return sensor_response_map
+
+ def _process_states(self):
+ current_poll_datetime = datetimeproxy.now()
+ sensor_response_map = dict()
+
+ active_run_state_name = None
+ for zm_state in self._zm_manager.get_zm_states():
+ if zm_state.active():
+ active_run_state_name = zm_state.name()
+ break
+ continue
+
+ if active_run_state_name:
+ run_state_sensor_response = self._create_run_state_sensor_response(
+ run_state_name = active_run_state_name,
+ timestamp = current_poll_datetime,
+ )
+ sensor_response_map[run_state_sensor_response.integration_key] = run_state_sensor_response
+ return sensor_response_map
+
def _create_movement_active_sensor_response( self, zm_event : ZmEvent ):
return SensorResponse(
integration_key = self._zm_manager._sensor_to_integration_key(
diff --git a/src/hi/integrations/zoneminder/zm_sync.py b/src/hi/integrations/zoneminder/zm_sync.py
new file mode 100644
index 00000000..373f08ca
--- /dev/null
+++ b/src/hi/integrations/zoneminder/zm_sync.py
@@ -0,0 +1,238 @@
+import logging
+from pyzm.helpers.Monitor import Monitor as ZmMonitor
+from typing import Dict
+
+from django.db import transaction
+
+from hi.apps.common.database_lock import ExclusionLockContext
+from hi.apps.common.processing_result import ProcessingResult
+from hi.apps.entity.enums import EntityType
+from hi.apps.entity.models import Entity
+from hi.apps.sense.models import Sensor
+
+from hi.apps.model_helper import HiModelHelper
+
+from hi.integrations.core.integration_key import IntegrationKey
+
+from .enums import ZmMonitorFunction
+from .zm_manager import ZoneMinderManager
+from .zm_metadata import ZmMetaData
+
+logger = logging.getLogger(__name__)
+
+
+class ZoneMinderSynchronizer:
+
+ SYNCHRONIZATION_LOCK_NAME = 'zm_integration_sync'
+
+ def __init__(self):
+ self._zm_manager = ZoneMinderManager()
+ return
+
+ def sync( self ) -> ProcessingResult:
+ try:
+ with ExclusionLockContext( name = self.SYNCHRONIZATION_LOCK_NAME ):
+ logger.debug( 'ZoneMinder integration sync started.' )
+ return self._sync_helper()
+ except RuntimeError as e:
+ return ProcessingResult(
+ title = 'ZM Sync Result',
+ error_list = [ str(e) ],
+ )
+ finally:
+ logger.debug( 'ZoneMinder integration sync ended.' )
+
+ def _sync_helper( self ) -> ProcessingResult:
+ result = ProcessingResult( title = 'ZM Sync Result' )
+
+ if not self._zm_manager.zm_client:
+ logger.debug( 'ZoneMinder client not created. ZM integration disabled?' )
+ result.error_list.append( 'Sync problem. ZM integration disabled?' )
+ return result
+
+ self._sync_states( result = result )
+ self._sync_monitors( result = result )
+
+ return result
+
+ def _sync_states( self, result : ProcessingResult ) -> ProcessingResult:
+
+ zm_run_state_list = self._zm_manager.get_zm_states( force_load = True )
+ new_state_values_dict = { x.name(): x.name() for x in zm_run_state_list }
+
+ zm_entity = Entity.objects.filter_by_integration_key(
+ integration_key = self._zm_manager._zm_integration_key(),
+ ).first()
+
+ if not zm_entity:
+ _ = self._create_zm_entity(
+ run_state_name_label_dict = new_state_values_dict,
+ result = result,
+ )
+
+ zm_run_state_sensor = Sensor.objects.filter_by_integration_key(
+ integration_key = self._zm_manager._zm_run_state_integration_key()
+ ).select_related('entity_state').first()
+
+ if not zm_run_state_sensor:
+ result.error_list.append( 'Missing ZoneMinder sensor for ZM state.' )
+ return
+
+ entity_state = zm_run_state_sensor.entity_state
+ new_state_values = new_state_values_dict.keys()
+ existing_state_values_dict = entity_state.value_range_dict
+ existing_state_values = existing_state_values_dict.keys()
+
+ if existing_state_values != new_state_values:
+ entity_state.value_range_dict = new_state_values_dict
+ entity_state.save()
+ result.message_list.append( f'Updated ZM state values to: {new_state_values_dict}' )
+
+ return
+
+ def _sync_monitors( self, result : ProcessingResult ) -> ProcessingResult:
+
+ integration_key_to_monitor = self._fetch_zm_monitors( result = result )
+ result.message_list.append( f'Found {len(integration_key_to_monitor)} current ZM monitors.' )
+
+ integration_key_to_entity = self._get_existing_zm_monitor_entities( result = result )
+ result.message_list.append( f'Found {len(integration_key_to_entity)} existing ZM entities.' )
+
+ for integration_key, zm_monitor in integration_key_to_monitor.items():
+ entity = integration_key_to_entity.get( integration_key )
+ if entity:
+ self._update_entity( entity = entity,
+ zm_monitor = zm_monitor,
+ result = result )
+ else:
+ self._create_monitor_entity( zm_monitor = zm_monitor,
+ result = result )
+ continue
+
+ for integration_key, entity in integration_key_to_entity.items():
+ if integration_key not in integration_key_to_monitor:
+ self._remove_entity( entity = entity,
+ result = result )
+ continue
+
+ return
+
+ def _fetch_zm_monitors( self, result : ProcessingResult ) -> Dict[ IntegrationKey, ZmMonitor ]:
+
+ logger.debug( 'Getting current ZM monitors.' )
+ integration_key_to_monitor = dict()
+ for zm_monitor in self._zm_manager.get_zm_monitors( force_load = True ):
+ integration_key = self._zm_manager._monitor_to_integration_key( zm_monitor_id = zm_monitor.id() )
+ integration_key_to_monitor[integration_key] = zm_monitor
+ continue
+
+ return integration_key_to_monitor
+
+ def _get_existing_zm_monitor_entities( self, result : ProcessingResult ) -> Dict[IntegrationKey, Entity]:
+ logger.debug( 'Getting existing ZM entities.' )
+ integration_key_to_entity = dict()
+
+ entity_queryset = Entity.objects.filter( integration_id = ZmMetaData.integration_id )
+ for entity in entity_queryset:
+ integration_key = entity.integration_key
+ if not integration_key:
+ result.error_list.append( f'ZM entity found without integration name: {entity}' )
+ mock_monitor_id = 1000000 + entity.id # We need a (unique) placeholder (will remove later)
+ integration_key = IntegrationKey(
+ integration_id = ZmMetaData.integration_id,
+ integration_name = str( mock_monitor_id ),
+ )
+ if integration_key.integration_name.startswith(
+ self._zm_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX ):
+ integration_key_to_entity[integration_key] = entity
+ continue
+
+ return integration_key_to_entity
+
+ def _create_zm_entity( self,
+ run_state_name_label_dict : Dict[ str, str ],
+ result : ProcessingResult ):
+ with transaction.atomic():
+ zm_entity = Entity(
+ name = self._zm_manager.ZM_ENTITY_NAME,
+ entity_type_str = str(EntityType.SERVICE),
+ can_user_delete = ZmMetaData.allow_entity_deletion,
+ )
+ zm_entity.integration_key = self._zm_manager._zm_integration_key()
+ zm_entity.save()
+
+ HiModelHelper.create_discrete_controller(
+ entity = zm_entity,
+ integration_key = self._zm_manager._zm_run_state_integration_key(),
+ name = f'{zm_entity.name} Run State',
+ name_label_dict = run_state_name_label_dict,
+ )
+
+ result.message_list.append( f'Created ZM entity: {zm_entity}' )
+ return zm_entity
+
+ def _create_monitor_entity( self,
+ zm_monitor : ZmMonitor,
+ result : ProcessingResult ):
+
+ with transaction.atomic():
+ entity_integration_key = self._zm_manager._monitor_to_integration_key(
+ zm_monitor_id = zm_monitor.id() )
+ entity = Entity(
+ name = zm_monitor.name(),
+ entity_type_str = str(EntityType.CAMERA),
+ can_user_delete = ZmMetaData.allow_entity_deletion,
+ )
+ entity.integration_key = entity_integration_key
+ entity.save()
+
+ HiModelHelper.create_video_stream_sensor(
+ entity = entity,
+ integration_key = self._zm_manager._sensor_to_integration_key(
+ sensor_prefix = self._zm_manager.VIDEO_STREAM_SENSOR_PREFIX,
+ zm_monitor_id = zm_monitor.id(),
+ ),
+ )
+ HiModelHelper.create_movement_sensor(
+ entity = entity,
+ integration_key = self._zm_manager._sensor_to_integration_key(
+ sensor_prefix = self._zm_manager.MOVEMENT_SENSOR_PREFIX,
+ zm_monitor_id = zm_monitor.id(),
+ ),
+ )
+ HiModelHelper.create_discrete_controller(
+ entity = entity,
+ integration_key = self._zm_manager._sensor_to_integration_key(
+ sensor_prefix = self._zm_manager.MONITOR_FUNCTION_SENSOR_PREFIX,
+ zm_monitor_id = zm_monitor.id(),
+ ),
+ name = f'{entity.name} Function',
+ name_label_dict = { str(x): x.label for x in ZmMonitorFunction },
+ )
+ result.message_list.append( f'Create new camera entity: {entity}' )
+ return
+
+ def _update_entity( self,
+ entity : Entity,
+ zm_monitor : ZmMonitor,
+ result : ProcessingResult ):
+
+ if entity.name != zm_monitor.name():
+ result.message_list.append(f'Name changed for {entity}. Setting to "{zm_monitor.name()}"')
+ entity.name = zm_monitor.name()
+ entity.save()
+ else:
+ result.message_list.append( f'No changes found for {entity}.' )
+ return
+
+ def _remove_entity( self,
+ entity : Entity,
+ result : ProcessingResult ):
+ entity.delete() # Deletion cascades to attributes, positions, sensors, controllers, etc.
+ result.message_list.append( f'Removed stale ZM entity: {entity}' )
+ return
+
+
+
+
+