Skip to content

Home Information - Your home, your data, organized.

Python

Have basic ZoneMinder integration sync working.

Anthony Cassandra6e5290fad508
diff --git a/src/hi/apps/entity/admin.py b/src/hi/apps/entity/admin.py
index 8c38f3f3..16e142a4 100644
--- a/src/hi/apps/entity/admin.py
+++ b/src/hi/apps/entity/admin.py
@@ -1,3 +1,44 @@
from django.contrib import admin
-# Register your models here.
+from . import models
+
+
+class AttributesInLine(admin.TabularInline):
+ model = models.Attribute
+ extra = 0
+ show_change_link = True
+
+
+class StatesInLine(admin.TabularInline):
+ model = models.EntityState
+ extra = 0
+ show_change_link = True
+
+
+class PositionInLine(admin.TabularInline):
+ model = models.EntityPosition
+ extra = 0
+ show_change_link = True
+
+
+class PathInLine(admin.TabularInline):
+ model = models.EntityPath
+ extra = 0
+ show_change_link = True
+
+
[email protected](models.Entity)
+class EntityAdmin(admin.ModelAdmin):
+
+ show_full_result_count = False
+
+ list_display = (
+ 'name',
+ 'entity_type_str',
+ 'created_datetime',
+ )
+
+ search_fields = ['name']
+
+ inlines = [ AttributesInLine, StatesInLine, PositionInLine, PathInLine ]
+
diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.py
index 7809baef..3ed00d20 100644
--- a/src/hi/apps/entity/models.py
+++ b/src/hi/apps/entity/models.py
@@ -45,6 +45,12 @@ class Entity( models.Model ):
verbose_name = 'Entity'
verbose_name_plural = 'Entities'
+ def __str__(self):
+ return f'Entity[{self.id}]: {self.name} [{self.entity_type_str}]'
+
+ def __repr__(self):
+ return self.__str__()
+
@property
def entity_type(self):
return EntityType.from_name_safe( self.entity_type_str )
@@ -54,6 +60,13 @@ class Entity( models.Model ):
self.entity_type_str = str(entity_type)
return
+ def get_attribute_map(self):
+ attribute_map = dict()
+ for attribute in self.attributes.all():
+ attribute_map[attribute.name] = attribute
+ continue
+ return attribute_map
+
class EntityState(models.Model):
"""
@@ -95,6 +108,12 @@ class EntityState(models.Model):
verbose_name = 'Entity State'
verbose_name_plural = 'Entity States'
+ def __str__(self):
+ return f'State[{self.id}]: {self.name} [{self.entity_state_type_str}]'
+
+ def __repr__(self):
+ return self.__str__()
+
@property
def entity_state_type(self):
return EntityStateType.from_name_safe( self.entity_state_type_str )
@@ -257,6 +276,12 @@ class Attribute(models.Model):
models.Index( fields=[ 'name', 'value' ] ),
]
+ def __str__(self):
+ return f'Attr: {self.name}={self.value} [{self.attribute_value_type_str}] [{self.attribute_type_str}]'
+
+ def __repr__(self):
+ return self.__str__()
+
@property
def attribute_value_type(self):
return AttributeValueType.from_name_safe( self.attribute_value_type_str )
diff --git a/src/hi/apps/entity_helpers.py b/src/hi/apps/entity_helpers.py
new file mode 100644
index 00000000..ae822cfa
--- /dev/null
+++ b/src/hi/apps/entity_helpers.py
@@ -0,0 +1,73 @@
+import json
+from typing import List
+
+from hi.apps.control.enums import ControllerType
+from hi.apps.control.models import Controller
+from hi.apps.entity.enums import EntityStateType
+from hi.apps.entity.models import Entity, EntityState
+from hi.apps.sense.enums import SensorType
+from hi.apps.sense.models import Sensor
+
+
+class EntityHelpers:
+
+ @classmethod
+ def create_movement_sensor( cls, entity : Entity ):
+ name = f'{entity.name} Motion'
+ entity_state = EntityState.objects.create(
+ entity = entity,
+ entity_state_type_str = str( EntityStateType.MOVEMENT ),
+ name = name,
+ value_range = '',
+ units = None,
+ )
+ sensor = Sensor.objects.create(
+ entity_state = entity_state,
+ sensor_type_str = str( SensorType.DEFAULT ),
+ name = name,
+ )
+ return sensor
+
+ @classmethod
+ def create_video_stream_sensor( cls, entity : Entity ):
+ name = f'{entity.name} Stream'
+ entity_state = EntityState.objects.create(
+ entity = entity,
+ entity_state_type_str = str( EntityStateType.VIDEO_STREAM ),
+ name = name,
+ value_range = '',
+ units = None,
+ )
+ sensor = Sensor.objects.create(
+ entity_state = entity_state,
+ sensor_type_str = str( SensorType.DEFAULT ),
+ name = name,
+ )
+ return sensor
+
+ @classmethod
+ def create_discrete_controller( cls,
+ entity : Entity,
+ name : str,
+ value_list : List[ str ],
+ is_sensed : bool = True ):
+ entity_state = EntityState.objects.create(
+ entity = entity,
+ entity_state_type_str = str( EntityStateType.DICRETE ),
+ name = name,
+ value_range = json.dumps( value_list ),
+ units = None,
+ )
+ if is_sensed:
+ _ = Sensor.objects.create(
+ entity_state = entity_state,
+ sensor_type_str = str( SensorType.DEFAULT ),
+ name = name,
+ )
+ controller = Controller.objects.create(
+ entity_state = entity_state,
+ controller_type_str = str( ControllerType.DEFAULT ),
+ name = name,
+ )
+ return controller
+
diff --git a/src/hi/integrations/zoneminder/enums.py b/src/hi/integrations/zoneminder/enums.py
index e302139c..5d044a00 100644
--- a/src/hi/integrations/zoneminder/enums.py
+++ b/src/hi/integrations/zoneminder/enums.py
@@ -44,3 +44,18 @@ class ZmPropertyName(LabeledEnum):
True,
True,
)
+
+
+class ZmAttributeName(LabeledEnum):
+
+ ZM_MONITOR_ID = ( 'ZM Monitor Id', '' )
+
+
+class ZmMonitorState(LabeledEnum):
+
+ NONE = ( 'None', '' )
+ MONITOR = ( 'Monitor', '' )
+ MODECT = ( 'Modect', '' )
+ RECORD = ( 'Record', '' )
+ MOCORD = ( 'Mocord', '' )
+ NODECT = ( 'Nodect', '' )
diff --git a/src/hi/integrations/zoneminder/zm_manager.py b/src/hi/integrations/zoneminder/zm_manager.py
index 23bf6b87..4a71f3c1 100644
--- a/src/hi/integrations/zoneminder/zm_manager.py
+++ b/src/hi/integrations/zoneminder/zm_manager.py
@@ -1,15 +1,32 @@
import logging
import pyzm.api as pyzm_api
+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.common.singleton import Singleton
+from hi.apps.entity.enums import (
+ AttributeName,
+ EntityType,
+ AttributeValueType,
+ AttributeType,
+)
+from hi.apps.entity.models import Entity, Attribute
+
+from hi.apps.entity_helpers import EntityHelpers
from hi.integrations.core.enums import IntegrationType
from hi.integrations.core.exceptions import IntegrationPropertyError
from hi.integrations.core.models import Integration
-from .enums import ZmPropertyName
+from .enums import (
+ ZmPropertyName,
+ ZmAttributeName,
+ ZmMonitorState,
+)
logger = logging.getLogger(__name__)
@@ -26,6 +43,7 @@ class ZoneMinderManager( Singleton ):
@property
def zm_client(self):
+ # Docs: https://pyzm.readthedocs.io/en/latest/
return self._zm_client
def reload( self ):
@@ -86,25 +104,141 @@ class ZoneMinderManager( Singleton ):
logger.debug( 'ZoneMinder integration sync ended.' )
def _sync_helper( self ) -> ProcessingResult:
- processing_result = ProcessingResult( title = 'ZM Sync Result' )
-
- logger.debug( 'Getting ZM monitors.' )
+ result = ProcessingResult( title = 'ZM Sync Result' )
+
zm_client = self.zm_client
if not zm_client:
logger.debug( 'ZoneMinder client not created. ZM integration disabled?' )
- processing_result.error_list.append( 'Sync problem. ZM integration disabled?' )
- return processing_result
-
- ms = zm_client.monitors()
- for m in ms.list():
-
- logger.debug('Name:{} Enabled:{} Type:{} Dims:{}'.format( m.name(),
- m.enabled(),
- m.type(),
- m.dimensions()) )
- logger.debug( m.status() )
+ result.error_list.append( 'Sync problem. ZM integration disabled?' )
+ return result
+
+ zm_id_to_entity = self._get_zm_entities( result = result )
+ result.message_list.append( f'Found {len(zm_id_to_entity)} existing ZM entities.' )
+
+ zm_id_to_monitor = self._get_zm_monitors( result = result )
+ result.message_list.append( f'Found {len(zm_id_to_monitor)} current ZM monitors.' )
+
+ for zm_id, monitor in zm_id_to_monitor.items():
+ entity = zm_id_to_entity.get( zm_id )
+ if entity:
+ self._update_entity( entity = entity,
+ monitor = monitor,
+ result = result )
+ else:
+ self._create_entity( monitor = monitor,
+ result = result )
+ continue
+
+ for zm_id, entity in zm_id_to_entity.items():
+ if zm_id not in zm_id_to_monitor:
+ self._remove_entity( entity = entity,
+ result = result )
+ continue
+
+ return result
+
+ def _get_zm_entities( self, result : ProcessingResult ) -> Dict[ int, Entity ]:
+ logger.debug( 'Getting existing ZM entities.' )
+ zm_id_to_entity = dict()
+
+ attribute_queryset = Attribute.objects.select_related( 'entity' ). filter(
+ name = AttributeName.INTEGRATION_SOURCE,
+ value = IntegrationType.ZONEMINDER.name,
+ )
+ for attribute in attribute_queryset:
+ zm_entity = attribute.entity
+ attribute_map = zm_entity.get_attribute_map()
+ try:
+ attribute = attribute_map.get( str(ZmAttributeName.ZM_MONITOR_ID) )
+ zm_id = int( attribute.value )
+ except ( TypeError, ValueError ):
+ result.error_list.append( f'ZM entity found without valid ZM Id: {zm_entity}' )
+ zm_id = 1000000 + zm_entity.id # We need a (unique) placeholder (will remove this later)
+ zm_id_to_entity[zm_id] = zm_entity
+ continue
- # TODO: Add new cameras if needed
+ return zm_id_to_entity
+ def _get_zm_monitors( self, result : ProcessingResult ) -> Dict[ int, ZmMonitor ]:
+
+ logger.debug( 'Getting current ZM monitors.' )
+ zm_id_to_monitor = dict()
+ for zm_monitor in self.zm_client.monitors().list():
+ zm_id = zm_monitor.id()
+
+ result.message_list.append(
+ '[ZM Monitor] Id:{} Name:{} Enabled:{} Status:{} Type:{} Dims:{}'.format(
+ zm_id,
+ zm_monitor.name(),
+ zm_monitor.enabled(),
+ zm_monitor.status(),
+ zm_monitor.type(),
+ zm_monitor.dimensions(),
+ )
+ )
+ zm_id_to_monitor[zm_id] = zm_monitor
continue
- return processing_result
+
+ return zm_id_to_monitor
+
+ def _create_entity( self,
+ monitor : ZmMonitor,
+ result : ProcessingResult ):
+
+ with transaction.atomic():
+
+ entity = Entity.objects.create(
+ name = monitor.name(),
+ entity_type_str = str(EntityType.CAMERA),
+ )
+ Attribute.objects.create(
+ entity = entity,
+ name = AttributeName.INTEGRATION_SOURCE,
+ value = IntegrationType.ZONEMINDER.name,
+ attribute_value_type_str = str( AttributeValueType.STRING ),
+ attribute_type_str = str( AttributeType.PREDEFINED ),
+ is_editable = False,
+ is_required = True,
+ )
+ Attribute.objects.create(
+ entity = entity,
+ name = ZmAttributeName.ZM_MONITOR_ID,
+ value = str( monitor.id() ),
+ attribute_value_type_str = str( AttributeValueType.INTEGER ),
+ attribute_type_str = str( AttributeType.PREDEFINED ),
+ is_editable = False,
+ is_required = True,
+ )
+
+ EntityHelpers.create_video_stream_sensor(
+ entity = entity,
+ )
+ EntityHelpers.create_movement_sensor(
+ entity = entity,
+ )
+ EntityHelpers.create_discrete_controller(
+ entity = entity,
+ name = f'{entity.name} State',
+ value_list = [ str(x) for x in ZmMonitorState ],
+ )
+ result.message_list.append( f'Create new camera entity: {entity}' )
+ return
+
+ def _update_entity( self,
+ entity : Entity,
+ monitor : ZmMonitor,
+ result : ProcessingResult ):
+
+ # Currently nothing stored locally that will change (other than entity existence)
+
+ result.message_list.append( f'No updates needed for camera entity: {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
+