Home Information - Your home, your data, organized.
Python
Working on populating sensor response history and latest from ZM. WIP
Anthony Cassandra42d6bb23c1d9
diff --git a/src/hi/apps/common/datetimeproxy.py b/src/hi/apps/common/datetimeproxy.pyindex 9d0171ea..682090d1 100644--- a/src/hi/apps/common/datetimeproxy.py+++ b/src/hi/apps/common/datetimeproxy.py@@ -360,3 +360,10 @@ def day_month_name_year_to_datetime( date_str : str ):def year_to_datetime( date_str : str ):return datetime.datetime.strptime( date_str, "%Y" )++def iso_naive_to_datetime_utc( iso_str : str, tzname : str ):+ to_zone = pytz.timezone( tzname )+ naive_time = datetime.datetime.fromisoformat( iso_str )+ aware_time = to_zone.localize(naive_time)+ utc_time = aware_time.astimezone( pytz.UTC )+ return utc_timediff --git a/src/hi/apps/monitor/monitor_mixin.py b/src/hi/apps/monitor/monitor_mixin.pynew file mode 100644index 00000000..ff9f370c--- /dev/null+++ b/src/hi/apps/monitor/monitor_mixin.py@@ -0,0 +1,2 @@+class SensorMonitorMixin:+ passdiff --git a/src/hi/apps/monitor/periodic_monitor.py b/src/hi/apps/monitor/periodic_monitor.pyindex a6c96357..dccbde06 100644--- a/src/hi/apps/monitor/periodic_monitor.py+++ b/src/hi/apps/monitor/periodic_monitor.py@@ -8,7 +8,7 @@ class PeriodicMonitor:and periodically updated from some external source."""- TRACE = False+ TRACE = Truedef __init__( self, id: str, interval_secs: int ) -> None:self._id = iddiff --git a/src/hi/apps/monitor/state_monitor_mixin.py b/src/hi/apps/monitor/state_monitor_mixin.pydeleted file mode 100644index a658785b..00000000--- a/src/hi/apps/monitor/state_monitor_mixin.py+++ /dev/null@@ -1,2 +0,0 @@-class EntityStateMonitorMixin:- passdiff --git a/src/hi/apps/monitor/transient_models.py b/src/hi/apps/monitor/transient_models.pynew file mode 100644index 00000000..20748f50--- /dev/null+++ b/src/hi/apps/monitor/transient_models.py@@ -0,0 +1,31 @@+from dataclasses import dataclass+from datetime import datetime+import json++from hi.integrations.core.integration_key import IntegrationKey+++@dataclass+class SensorResponse:+ integration_key : IntegrationKey+ value : str+ timestamp : datetime++ def __str__(self):+ return json.dumps( self.to_dict() )++ def to_dict(self):+ return {+ 'key': str(self.integration_key),+ 'value': self.value,+ 'timestamp': self.timestamp.isoformat(),+ }++ @classmethod+ def from_string( self, sensor_reading_str : str ) -> 'SensorResponse':+ sensor_reading_dict = json.loads( sensor_reading_str )+ return SensorResponse(+ integration_key = IntegrationKey.from_string( sensor_reading_dict.get('key') ),+ value = sensor_reading_dict.get('value'),+ timestamp = datetime.fromisoformat( sensor_reading_dict.get('timestamp') ),+ )diff --git a/src/hi/apps/sense/enums.py b/src/hi/apps/sense/enums.pyindex 2bbc44ca..bc6fc392 100644--- a/src/hi/apps/sense/enums.py+++ b/src/hi/apps/sense/enums.py@@ -4,3 +4,9 @@ from hi.apps.common.enums import LabeledEnumclass SensorType(LabeledEnum):DEFAULT = ( 'Default', '' ) # EntityState will define behavior+++class SensorValue(LabeledEnum):++ MOVEMENT_ACTIVE = ( 'Active', '' )+ MOVEMENT_IDLE = ( 'Idle', '' )diff --git a/src/hi/integrations/hass/hass_monitor.py b/src/hi/integrations/hass/hass_monitor.pyindex 7c82deec..8645755e 100644--- a/src/hi/integrations/hass/hass_monitor.py+++ b/src/hi/integrations/hass/hass_monitor.py@@ -1,7 +1,7 @@import loggingfrom hi.apps.monitor.periodic_monitor import PeriodicMonitor-from hi.apps.monitor.state_monitor_mixin import EntityStateMonitorMixin+from hi.apps.monitor.monitor_mixin import SensorMonitorMixinfrom .hass_converter import HassConverterfrom .hass_manager import HassManager@@ -9,7 +9,7 @@ from .hass_manager import HassManagerlogger = logging.getLogger(__name__)-class HassMonitor( PeriodicMonitor, EntityStateMonitorMixin ):+class HassMonitor( PeriodicMonitor, SensorMonitorMixin ):def __init__( self ):super().__init__(@@ -20,10 +20,12 @@ class HassMonitor( PeriodicMonitor, EntityStateMonitorMixin ):returnasync def do_work(self):+ id_to_hass_state_map = self._manager.fetch_hass_states_from_api( verbose = False )+if self.TRACE:- logger.debug( 'Fetched HAss States' )+ logger.debug( f'Fetched {len(id_to_hass_state_map)} HAss States' )+- id_to_hass_state_map = self._manager.fetch_hass_states_from_api( verbose = False )for hass_state in id_to_hass_state_map.values():state_integration_key = HassConverter.hass_state_to_integration_key( hass_state = hass_state )diff --git a/src/hi/integrations/zoneminder/apps.py b/src/hi/integrations/zoneminder/apps.pyindex 4261d689..23eac38f 100644--- a/src/hi/integrations/zoneminder/apps.py+++ b/src/hi/integrations/zoneminder/apps.py@@ -1,3 +1,4 @@+import loggingimport osdiff --git a/src/hi/integrations/zoneminder/zm_manager.py b/src/hi/integrations/zoneminder/zm_manager.pyindex 5dcac41b..891536b3 100644--- a/src/hi/integrations/zoneminder/zm_manager.py+++ b/src/hi/integrations/zoneminder/zm_manager.py@@ -1,6 +1,7 @@import logging-import pyzm.api as pyzm_api+from pyzm.api import ZMApifrom pyzm.helpers.Monitor import Monitor as ZmMonitor+from pyzm.helpers.globals import logger as pyzm_loggerfrom typing import Dictfrom django.db import transaction@@ -24,10 +25,20 @@ from .enums import (from .zm_metadata import ZmMetaDatalogger = logging.getLogger(__name__)+pyzm_logger.set_level( 0 ) # pyzm does not use standard 'logging' module. ugh.class ZoneMinderManager( Singleton ):+ """+ References:+ ZM Api code: https://github.com/ZoneMinder/zoneminder/tree/master/web/api/app/Controller+ PyZM code: https://github.com/pliablepixels/pyzm/tree/357fdbd1937dab8027882598b61258ef43dc366a+ """+ VIDEO_STREAM_SENSOR_PREFIX = 'monitor.video_stream'+ MOVEMENT_SENSOR_PREFIX = 'monitor.motion'+ MONITOR_STATE_SENSOR_PREFIX = 'monitor.state'+SYNCHRONIZATION_LOCK_NAME = 'zm_integration_sync'def __init_singleton__( self ):@@ -94,9 +105,8 @@ class ZoneMinderManager( Singleton ):continuelogger.debug( f'ZoneMinder client options: {api_options}' )-- return pyzm_api.ZMApi( options = api_options )-+ return ZMApi( options = api_options )+def sync( self ) -> ProcessingResult:try:with ExclusionLockContext( name = self.SYNCHRONIZATION_LOCK_NAME ):@@ -150,7 +160,7 @@ class ZoneMinderManager( Singleton ):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 = zm_monitor )+ integration_key = self._monitor_to_integration_key( zm_monitor_id = zm_monitor.id() )result.message_list.append('[ZM Monitor] Id:{} Name:{} Enabled:{} Status:{} Type:{} Dims:{}'.format(@@ -190,27 +200,37 @@ class ZoneMinderManager( Singleton ):zm_monitor : ZmMonitor,result : ProcessingResult ):- integration_key = self._monitor_to_integration_key( zm_monitor = zm_monitor )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 = integration_key+ entity.integration_key = entity_integration_keyentity.save()+HiModelHelper.create_video_stream_sensor(entity = entity,- integration_key = integration_key,+ 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 = integration_key,+ 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 = integration_key,+ integration_key = self._sensor_to_integration_key(+ sensor_prefix = self.MONITOR_STATE_SENSOR_PREFIX,+ zm_monitor_id = zm_monitor.id(),+ ),name = f'{entity.name} State',value_list = [ str(x) for x in ZmMonitorState ],)@@ -218,9 +238,9 @@ class ZoneMinderManager( Singleton ):returndef _update_entity( self,- entity : Entity,+ entity : Entity,zm_monitor : ZmMonitor,- result : ProcessingResult ):+ result : ProcessingResult ):# Currently nothing stored locally that will change (other than entity existence)@@ -229,16 +249,22 @@ class ZoneMinderManager( Singleton ):returndef _remove_entity( self,- entity : Entity,- result : ProcessingResult ):+ 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 _monitor_to_integration_key( self, zm_monitor : ZmMonitor ) -> IntegrationKey:+ def _monitor_to_integration_key( self, zm_monitor_id : ZmMonitor ) -> IntegrationKey:return IntegrationKey(integration_id = ZmMetaData.integration_id,- integration_name = str( zm_monitor.id() ),+ integration_name = str( zm_monitor_id ),)+ def _sensor_to_integration_key( self, sensor_prefix : str, zm_monitor_id : int ) -> IntegrationKey:+ return IntegrationKey(+ integration_id = ZmMetaData.integration_id,+ integration_name = f'{sensor_prefix}.{zm_monitor_id}',+ )+diff --git a/src/hi/integrations/zoneminder/zm_monitor.py b/src/hi/integrations/zoneminder/zm_monitor.pyindex 3e0618a3..1191177e 100644--- a/src/hi/integrations/zoneminder/zm_monitor.py+++ b/src/hi/integrations/zoneminder/zm_monitor.py@@ -1,34 +1,130 @@+from datetime import datetime, timedeltaimport logging+import hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.monitor.periodic_monitor import PeriodicMonitor-from hi.apps.monitor.state_monitor_mixin import EntityStateMonitorMixin+from hi.apps.monitor.monitor_mixin import SensorMonitorMixin+from hi.apps.monitor.transient_models import SensorResponse+from hi.apps.sense.enums import SensorValuefrom .zm_manager import ZoneMinderManagerlogger = logging.getLogger(__name__)-class ZoneMinderMonitor( PeriodicMonitor, EntityStateMonitorMixin ):+class ZoneMinderMonitor( PeriodicMonitor, SensorMonitorMixin ):+ # TODO: MOve this into the integrations attributes for users to setAllCameraStatus+ ZONEMINDER_SERVER_TIMEZONE = 'America/Chicago'+def __init__( self ):super().__init__(id = 'zm-monitor',interval_secs = 10,)self._manager = ZoneMinderManager()+ self._last_event_datetime = datetimeproxy.now( self.ZONEMINDER_SERVER_TIMEZONE )returnasync def do_work(self):+ options = {+ 'from': self._last_event_datetime.isoformat(),+ 'tz': self.ZONEMINDER_SERVER_TIMEZONE,+ }+++++ print( f'FROM: {options}' )+++ response = self._manager.zm_client.events( options )+ events = response.list()if self.TRACE:- logger.debug( 'Fetched ZoneMinder States' )+ logger.debug( f"Found {len(events)} new ZM events" )+ sensor_response_list = list()+ for zm_event in events:+ if self.TRACE:+ logger.debug( f'ZM Event: {zm_event.get()}' )- # TODO: zzz Update Redis with state values+ event_id = zm_event.id()+ monitor_id = zm_event.monitor_id()+ # Currently unused values:+ #+ # event_image_url = '{}/index.php?view=image&eid={}&fid=snapshot'.format(+ # self._manager.zm_client.get_portalbase(),+ # event_id,+ # )+ # event_cause = zm_event.cause()+ # event_duration_secs = zm_event.duration()+ # total_frame_count = zm_event.total_frames()+ # alarm_frame_count = zm_event.alarmed_frames()+ # score = zm_event.score()+ # notes = zm_event.notes()+ # max_score_frame_id = zm_event.get()['MaxScoreFrameId']++ event_video_url = '{}/index.php?view=event&eid={}'.format(+ self._manager.zm_client.get_portalbase(),+ event_id,+ )+ stream_response = SensorResponse(+ integration_key = self._manager._sensor_to_integration_key(+ sensor_prefix = self._manager.VIDEO_STREAM_SENSOR_PREFIX,+ zm_monitor_id = monitor_id,+ ),+ timestamp = self._last_event_datetime,+ value = event_video_url,+ )+ sensor_response_list.append( stream_response )+ start_datetime = self.zm_response_to_datetime( zm_event.get()['StartTime'] )+ event_start_response = SensorResponse(+ integration_key = self._manager._sensor_to_integration_key(+ sensor_prefix = self._manager.MOVEMENT_SENSOR_PREFIX,+ zm_monitor_id = monitor_id,+ ),+ value = str(SensorValue.MOVEMENT_ACTIVE),+ timestamp = start_datetime,+ )+ sensor_response_list.append( event_start_response )-++ #self.add_to_sensor_response_history( event_start_response )+++++ end_datetime = self.zm_response_to_datetime( zm_event.get()['EndTime'] )+ if end_datetime:+ event_end_response = SensorResponse(+ integration_key = self._manager._sensor_to_integration_key(+ sensor_prefix = self._manager.MOVEMENT_SENSOR_PREFIX,+ zm_monitor_id = monitor_id,+ ),+ value = str(SensorValue.MOVEMENT_IDLE),+ timestamp = end_datetime,+ )+ sensor_response_list.append( event_end_response )+++ # self.add_to_sensor_response_history( event_end_response )++++ self._last_event_datetime = max( self._last_event_datetime, start_datetime )+ continue+return++ def zm_response_to_datetime( self, zm_response_time : str ):+ if not zm_response_time:+ return None+ return datetimeproxy.iso_naive_to_datetime_utc(+ zm_response_time,+ self.ZONEMINDER_SERVER_TIMEZONE,+ )diff --git a/src/hi/requirements/base.txt b/src/hi/requirements/base.txtindex 531caa9d..d9960b99 100644--- a/src/hi/requirements/base.txt+++ b/src/hi/requirements/base.txt@@ -33,6 +33,8 @@ python-utils==3.8.2pytz==2024.1pytz==2024.1pyzm==0.3.64+redis==5.2.0+redlock==1.2.0regex==2024.7.24shapely==2.0.6six==1.16.0diff --git a/src/hi/settings/base.py b/src/hi/settings/base.pyindex 18b31b12..421a8d92 100644--- a/src/hi/settings/base.py+++ b/src/hi/settings/base.py@@ -308,3 +308,17 @@ CONSTANCE_CONFIG = {'DOWN_FOR_MAINTENANCE': ( False, 'Should we force the down for maintenance page to show?' ),}+REDIS_HOST = get_env_variable('HI_REDIS_HOST')+REDIS_PORT = int(get_env_variable('HI_REDIS_PORT'))+REDIS_KEY_PREFIX = get_env_variable('HI_REDIS_KEY_PREFIX')++CACHES = {+ 'default': {+ # 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',+ 'BACKEND': 'django.core.cache.backends.redis.RedisCache',+ 'LOCATION': [+ f'redis://{REDIS_HOST}:{REDIS_PORT}',+ ],+ "KEY_PREFIX": f'main:{REDIS_KEY_PREFIX}',+ }+}