Home Information - Your home, your data, organized.
Python
Refinements of Event Definition model and creation via integrations.
Anthony Cassandra0b034cd8be0f
diff --git a/src/hi/apps/alert/transient_models.py b/src/hi/apps/alert/transient_models.pyindex 630f63e6..1f13b37a 100644--- a/src/hi/apps/alert/transient_models.py+++ b/src/hi/apps/alert/transient_models.py@@ -6,9 +6,9 @@ from .enums import AlarmLevel, SecurityPosture@dataclassclass Alarm:- title : str- details : str- security_posture : SecurityPosture- alarm_level : AlarmLevel # zzz make this AlarmLevel and move here???- lifetime_secs : int- timestamp : datetime+ title : str+ details : str+ security_posture : SecurityPosture+ alarm_level : AlarmLevel+ alarm_lifetime_secs : int+ timestamp : datetimediff --git a/src/hi/apps/event/admin.py b/src/hi/apps/event/admin.pyindex e728bc7a..c3e471b5 100644--- a/src/hi/apps/event/admin.py+++ b/src/hi/apps/event/admin.py@@ -29,6 +29,7 @@ class EventDefinitionAdmin(admin.ModelAdmin):list_display = ('name','event_window_secs',+ 'dedupe_window_secs','enabled',)diff --git a/src/hi/apps/event/event_manager.py b/src/hi/apps/event/event_manager.pyindex c97f7408..9d64c143 100644--- a/src/hi/apps/event/event_manager.py+++ b/src/hi/apps/event/event_manager.py@@ -18,9 +18,21 @@ logger = logging.getLogger(__name__)class EventManager(Singleton):+ RECENT_EVENT_CACHE_SIZE = 1000+ RECENT_EVENT_CACHE_TTL_SECS = 3600+ RECENT_TRANSITION_QUEUE_MAX_WINDOW_SECS = 300++ # We need to put some bounds to keep memory/cpu requirements for+ # managing events managable, but this will put impose bounds on how the+ # EventDefinitions parameters.+ #+ MAX_EVENT_WINDOW_SECS = RECENT_EVENT_CACHE_TTL_SECS+ MAX_DEDUPE_WINDOW_SECS = RECENT_TRANSITION_QUEUE_MAX_WINDOW_SECS+def __init_singleton__(self):self._recent_transitions = deque()- self._recent_events = TTLCache( maxsize = 1000, ttl = 300 )+ self._recent_events = TTLCache( maxsize = self.RECENT_EVENT_CACHE_SIZE,+ ttl = self.RECENT_EVENT_CACHE_TTL_SECS )self._alert_manager = AlertManager()self._controller_manager = ControllerManager()self.reload()@@ -33,10 +45,6 @@ class EventManager(Singleton):'alarm_actions','control_actions',).filter( enabled = True )- if self._event_definitions:- self._max_event_window_secs = max([ x.event_window_secs for x in self._event_definitions ])- else:- self._max_event_window_secs = 10returnasync def add_entity_state_transitions( self,@@ -74,7 +82,7 @@ class EventManager(Singleton):if not recent_event:return Falserecent_event_timedelta = datetimeproxy.now() - recent_event.timestamp- return bool( recent_event_timedelta.seconds <= event_definition.event_window_secs )+ return bool( recent_event_timedelta.seconds <= event_definition.dedupe_window_secs )def _create_event_if_detected( self, event_definition : EventDefinition ) -> bool:if not event_definition.clauses.exists():@@ -107,9 +115,14 @@ class EventManager(Singleton):def _purge_old_transitions( self ):current_timestamp = datetimeproxy.now()- while ( self._recent_transitions- and (( current_timestamp - self._recent_transitions[0].timestamp )- > timedelta( seconds = self._max_event_window_secs ))):++ # Pop from front those that are too old until encounter one that is not too old.+ while True:+ if not self._recent_transitions:+ return+ transition_age = current_timestamp - self._recent_transitions[0].timestamp+ if transition_age.seconds < self.RECENT_TRANSITION_QUEUE_MAX_WINDOW_SECS:+ returnself._recent_transitions.popleft()continuereturndiff --git a/src/hi/apps/event/migrations/0002_eventdefinition_integration_id_and_more.py b/src/hi/apps/event/migrations/0002_eventdefinition_integration_id_and_more.pynew file mode 100644index 00000000..feddb6ae--- /dev/null+++ b/src/hi/apps/event/migrations/0002_eventdefinition_integration_id_and_more.py@@ -0,0 +1,27 @@+# Generated by Django 4.2.15 on 2024-12-05 22:11++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("event", "0001_initial"),+ ]++ operations = [+ migrations.AddField(+ model_name="eventdefinition",+ name="integration_id",+ field=models.CharField(+ blank=True, max_length=32, null=True, verbose_name="Integration Id"+ ),+ ),+ migrations.AddField(+ model_name="eventdefinition",+ name="integration_name",+ field=models.CharField(+ blank=True, max_length=128, null=True, verbose_name="Integration Name"+ ),+ ),+ ]diff --git a/src/hi/apps/event/migrations/0003_rename_lifetime_secs_alarmaction_alarm_lifetime_secs.py b/src/hi/apps/event/migrations/0003_rename_lifetime_secs_alarmaction_alarm_lifetime_secs.pynew file mode 100644index 00000000..bb855467--- /dev/null+++ b/src/hi/apps/event/migrations/0003_rename_lifetime_secs_alarmaction_alarm_lifetime_secs.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-12-05 23:13++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("event", "0002_eventdefinition_integration_id_and_more"),+ ]++ operations = [+ migrations.RenameField(+ model_name="alarmaction",+ old_name="lifetime_secs",+ new_name="alarm_lifetime_secs",+ ),+ ]diff --git a/src/hi/apps/event/migrations/0004_eventdefinition_dedupe_window_secs.py b/src/hi/apps/event/migrations/0004_eventdefinition_dedupe_window_secs.pynew file mode 100644index 00000000..ed0addf5--- /dev/null+++ b/src/hi/apps/event/migrations/0004_eventdefinition_dedupe_window_secs.py@@ -0,0 +1,21 @@+# Generated by Django 4.2.15 on 2024-12-06 01:19++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("event", "0003_rename_lifetime_secs_alarmaction_alarm_lifetime_secs"),+ ]++ operations = [+ migrations.AddField(+ model_name="eventdefinition",+ name="dedupe_window_secs",+ field=models.PositiveIntegerField(+ default=300, verbose_name="Desupe Window Secs"+ ),+ preserve_default=False,+ ),+ ]diff --git a/src/hi/apps/event/models.py b/src/hi/apps/event/models.pyindex 98cca1f2..4a3678e9 100644--- a/src/hi/apps/event/models.py+++ b/src/hi/apps/event/models.py@@ -4,16 +4,31 @@ from hi.apps.alert.enums import AlarmLevel, SecurityPosturefrom hi.apps.control.models import Controllerfrom hi.apps.entity.models import EntityState+from hi.integrations.core.models import IntegrationKeyModel-class EventDefinition( models.Model ):++class EventDefinition( IntegrationKeyModel ):name = models.CharField('Name',max_length = 64,)++ # For multi-clause event definitions, the span in which all clauses+ # need to satisfied.+ #event_window_secs = models.PositiveIntegerField('Event Window Secs',)++ # Rate limits how many events will be generated for this+ # EventDefinition by ensuring at least this time elapsed before a new+ # event would be generated.+ #+ dedupe_window_secs = models.PositiveIntegerField(+ 'Desupe Window Secs',+ )+enabled = models.BooleanField(default = True,)@@ -85,7 +100,12 @@ class AlarmAction( models.Model ):max_length = 32,null = False, blank = False,)- lifetime_secs = models.PositiveIntegerField(++ # How long will this alarm be relevant to the user. Alarms exist until+ # they expire or are acknowledged. Set this to zero for ann alarm that+ # will only be dismissed by a user acknowledgement.+ #+ alarm_lifetime_secs = models.PositiveIntegerField('Lifetime Secs',)diff --git a/src/hi/apps/event/transient_models.py b/src/hi/apps/event/transient_models.pyindex 9d2c5293..35dbfcbe 100644--- a/src/hi/apps/event/transient_models.py+++ b/src/hi/apps/event/transient_models.py@@ -42,6 +42,6 @@ class Event:details = ', '.join([ x.sensor.name for x in self.sensor_response_list ]),security_posture = alarm_action.security_posture,alarm_level = alarm_action.alarm_level,- lifetime_secs = alarm_action.lifetime_secs,+ alarm_lifetime_secs = alarm_action.alarm_lifetime_secs,timestamp = self.timestamp,)diff --git a/src/hi/apps/model_helper.py b/src/hi/apps/model_helper.pyindex 8ada69c9..5de923f9 100644--- a/src/hi/apps/model_helper.py+++ b/src/hi/apps/model_helper.py@@ -1,14 +1,17 @@import json-from typing import Dict, List+from typing import Dict+from hi.apps.alert.enums import SecurityPosture, AlarmLevelfrom hi.apps.control.enums import ControllerTypefrom hi.apps.control.models import Controllerfrom hi.apps.entity.enums import (EntityStateType,+ EntityStateValue,HumidityUnit,TemperatureUnit,)from hi.apps.entity.models import Entity, EntityState+from hi.apps.event.models import AlarmAction, EventClause, EventDefinitionfrom hi.apps.sense.enums import SensorTypefrom hi.apps.sense.models import Sensor@@ -24,12 +27,24 @@ class HiModelHelper:EntityStateType.BLOB,EntityStateType.MULTVALUED,}++ DEFAULT_CONNECTIVITY_EVENT_WINDOW_SECS = 60+ DEFAULT_CONNECTIVITY_ALARM_LIFETIME_SECS = 0++ DEFAULT_OPEN_CLOSE_EVENT_WINDOW_SECS = 60+ DEFAULT_OPEN_CLOSE_ALARM_LIFETIME_SECS = 180++ DEFAULT_MOVEMENT_EVENT_WINDOW_SECS = 60+ DEFAULT_MOVEMENT_ALARM_LIFETIME_SECS = 180++ DEFAULT_BATTERY_EVENT_WINDOW_SECS = 60+ DEFAULT_BATTERY_ALARM_LIFETIME_SECS = 0@classmethoddef create_blob_sensor( cls,entity : Entity,integration_key : IntegrationKey = None,- name : str = None ):+ name : str = None ) -> Sensor:if not name:name = f'{entity.name} Blob'return cls.create_sensor(@@ -43,7 +58,7 @@ class HiModelHelper:def create_multivalued_sensor( cls,entity : Entity,integration_key : IntegrationKey = None,- name : str = None ):+ name : str = None ) -> Sensor:if not name:name = f'{entity.name} Values'return cls.create_sensor(@@ -57,7 +72,7 @@ class HiModelHelper:def create_connectivity_sensor( cls,entity : Entity,integration_key : IntegrationKey = None,- name : str = None ):+ name : str = None ) -> Sensor:if not name:name = f'{entity.name} Connection'return cls.create_sensor(@@ -71,7 +86,7 @@ class HiModelHelper:def create_datetime_sensor( cls,entity : Entity,integration_key : IntegrationKey = None,- name : str = None ):+ name : str = None ) -> Sensor:if not name:name = f'{entity.name} Date/Time'return cls.create_sensor(@@ -86,7 +101,7 @@ class HiModelHelper:entity : Entity,name_label_dict : Dict[ str, str ],integration_key : IntegrationKey = None,- name : str = None ):+ name : str = None ) -> Sensor:if not name:name = f'{entity.name} Value'return cls.create_sensor(@@ -101,7 +116,7 @@ class HiModelHelper:def create_high_low_sensor( cls,entity : Entity,integration_key : IntegrationKey = None,- name : str = None ):+ name : str = None ) -> Sensor:if not name:name = f'{entity.name} Level'return cls.create_sensor(@@ -116,7 +131,7 @@ class HiModelHelper:entity : Entity,temperature_unit : TemperatureUnit,integration_key : IntegrationKey = None,- name : str = None ):+ name : str = None ) -> Sensor:if not name:name = f'{entity.name} Temperature'return cls.create_sensor(@@ -132,7 +147,7 @@ class HiModelHelper:entity : Entity,humidity_unit : HumidityUnit,integration_key : IntegrationKey = None,- name : str = None ):+ name : str = None ) -> Sensor:if not name:name = f'{entity.name} Humidity'return cls.create_sensor(@@ -147,7 +162,7 @@ class HiModelHelper:def create_on_off_sensor( cls,entity : Entity,integration_key : IntegrationKey = None,- name : str = None ):+ name : str = None ) -> Sensor:if not name:name = f'{entity.name} On/Off'return cls.create_sensor(@@ -161,7 +176,7 @@ class HiModelHelper:def create_open_close_sensor( cls,entity : Entity,integration_key : IntegrationKey = None,- name : str = None ):+ name : str = None ) -> Sensor:if not name:name = f'{entity.name} Open/Close'return cls.create_sensor(@@ -175,7 +190,7 @@ class HiModelHelper:def create_movement_sensor( cls,entity : Entity,integration_key : IntegrationKey = None,- name : str = None ):+ name : str = None ) -> Sensor:if not name:name = f'{entity.name} Motion'return cls.create_sensor(@@ -189,7 +204,7 @@ class HiModelHelper:def create_video_stream_sensor( cls,entity : Entity,integration_key : IntegrationKey = None,- name : str = None ):+ name : str = None ) -> Sensor:if not name:name = f'{entity.name} Stream'return cls.create_sensor(@@ -204,7 +219,7 @@ class HiModelHelper:entity : Entity,integration_key : IntegrationKey = None,name : str = None,- is_sensed : bool = True ):+ is_sensed : bool = True ) -> Controller:if not name:name = f'{entity.name} Controller'return cls.create_controller(@@ -221,7 +236,7 @@ class HiModelHelper:entity_state : EntityState,integration_key : IntegrationKey = None,name : str = None,- is_sensed : bool = True ):+ is_sensed : bool = True ) -> Controller:if not name:name = f'{entity.name} Controller'return cls.add_controller(@@ -238,7 +253,7 @@ class HiModelHelper:name_label_dict : Dict[ str, str ],integration_key : IntegrationKey = None,name : str = None,- is_sensed : bool = True ):+ is_sensed : bool = True ) -> Controller:if not name:name = f'{entity.name} Controller'return cls.create_controller(@@ -258,7 +273,7 @@ class HiModelHelper:sensor_type : SensorType = SensorType.DEFAULT,integration_key : IntegrationKey = None,value_range_str : str = '',- units : str = None ):+ units : str = None ) -> Sensor:if not name:name = f'{entity.name}'@@ -288,7 +303,7 @@ class HiModelHelper:is_sensed : bool = True,integration_key : IntegrationKey = None,value_range_str : str = '',- units : str = None ):+ units : str = None ) -> Controller:if not name:name = f'{entity.name}'@@ -315,7 +330,7 @@ class HiModelHelper:name : str = None,controller_type : ControllerType = ControllerType.DEFAULT,is_sensed : bool = True,- integration_key : IntegrationKey = None ):+ integration_key : IntegrationKey = None ) -> Controller:if not name:name = f'{entity.name}'@@ -338,3 +353,127 @@ class HiModelHelper:controller.integration_key = integration_keycontroller.save()return controller++ @classmethod+ def create_connectivity_event_definition(+ cls,+ name : str,+ entity_state : EntityState,+ integration_key : IntegrationKey = None ) -> EventDefinition:++ return cls.create_simple_alarm_event_definition(+ name = name,+ entity_state = entity_state,+ value = EntityStateValue.DISCONNECTED,+ posture_to_level = {+ SecurityPosture.AWAY: AlarmLevel.WARNING,+ SecurityPosture.NIGHT: AlarmLevel.WARNING,+ SecurityPosture.HOME: AlarmLevel.WARNING,+ },+ event_window_secs = cls.DEFAULT_CONNECTIVITY_EVENT_WINDOW_SECS,+ dedupe_window_secs = cls.DEFAULT_CONNECTIVITY_DEDUPE_WINDOW_SECS,+ alarm_lifetime_secs = cls.DEFAULT_CONNECTIVITY_ALARM_LIFETIME_SECS,+ integration_key = integration_key,+ )++ @classmethod+ def create_open_close_event_definition(+ cls,+ name : str,+ entity_state : EntityState,+ integration_key : IntegrationKey = None ) -> EventDefinition:++ return cls.create_simple_alarm_event_definition(+ name = name,+ entity_state = entity_state,+ value = EntityStateValue.OPEN,+ posture_to_level = {+ SecurityPosture.AWAY: AlarmLevel.CRITICAL,+ SecurityPosture.NIGHT: AlarmLevel.CRITICAL,+ SecurityPosture.HOME: AlarmLevel.INFO,+ },+ event_window_secs = cls.DEFAULT_OPEN_CLOSE_EVENT_WINDOW_SECS,+ dedupe_window_secs = cls.DEFAULT_OPEN_CLOSE_DEDUPE_WINDOW_SECS,+ alarm_lifetime_secs = cls.DEFAULT_OPEN_CLOSE_ALARM_LIFETIME_SECS,+ integration_key = integration_key,+ )++ @classmethod+ def create_movement_event_definition(+ cls,+ name : str,+ entity_state : EntityState,+ integration_key : IntegrationKey = None ) -> EventDefinition:++ return cls.create_simple_alarm_event_definition(+ name = name,+ entity_state = entity_state,+ value = EntityStateValue.ACTIVE,+ posture_to_level = {+ SecurityPosture.AWAY: AlarmLevel.CRITICAL,+ SecurityPosture.NIGHT: AlarmLevel.CRITICAL,+ SecurityPosture.HOME: AlarmLevel.INFO,+ },+ event_window_secs = cls.DEFAULT_MOVEMENT_EVENT_WINDOW_SECS,+ dedupe_window_secs = cls.DEFAULT_MOVEMENT_DEDUPE_WINDOW_SECS,+ alarm_lifetime_secs = cls.DEFAULT_MOVEMENT_ALARM_LIFETIME_SECS,+ integration_key = integration_key,+ )++ @classmethod+ def create_battery_event_definition(+ cls,+ name : str,+ entity_state : EntityState,+ integration_key : IntegrationKey = None ) -> EventDefinition:++ return cls.create_simple_alarm_event_definition(+ name = name,+ entity_state = entity_state,+ value = EntityStateValue.LOW,+ posture_to_level = {+ SecurityPosture.AWAY: AlarmLevel.INFO,+ SecurityPosture.NIGHT: AlarmLevel.INFO,+ SecurityPosture.HOME: AlarmLevel.INFO,+ },+ event_window_secs = cls.DEFAULT_BATTERY_EVENT_WINDOW_SECS,+ dedupe_window_secs = cls.DEFAULT_BATTERY_DEDUPE_WINDOW_SECS,+ alarm_lifetime_secs = cls.DEFAULT_BATTERY_ALARM_LIFETIME_SECS,+ integration_key = integration_key,+ )++ @classmethod+ def create_simple_alarm_event_definition(+ cls,+ name : str,+ entity_state : EntityState,+ value : str,+ posture_to_level : Dict[ SecurityPosture, AlarmLevel ],+ event_window_secs : int,+ dedupe_window_secs : int,+ alarm_lifetime_secs : int,+ integration_key : IntegrationKey = None ) -> EventDefinition:++ event_definition = EventDefinition(+ name = name,+ event_window_secs = event_window_secs,+ dedupe_window_secs = dedupe_window_secs,+ enabled = True,+ )+ event_definition.integration_key = integration_key+ event_definition.save()++ _ = EventClause.objects.create(+ event_definition = event_definition,+ entity_state = entity_state,+ value = value,+ )+ for security_posture, alarm_level in posture_to_level.items():+ _ = AlarmAction.objects.create(+ event_definition = event_definition,+ security_posture_str = str(security_posture),+ alarm_level_str = str(alarm_level),+ alarm_lifetime_secs = alarm_lifetime_secs,+ )+ continue+ return event_definitiondiff --git a/src/hi/apps/sense/models.py b/src/hi/apps/sense/models.pyindex 549eb560..a50f1383 100644--- a/src/hi/apps/sense/models.py+++ b/src/hi/apps/sense/models.py@@ -1,6 +1,7 @@from django.db import modelsfrom hi.apps.entity.models import EntityState+from hi.integrations.core.models import IntegrationKeyModelfrom .enums import SensorTypediff --git a/src/hi/integrations/hass/hass_converter.py b/src/hi/integrations/hass/hass_converter.pyindex f10b903c..98478347 100644--- a/src/hi/integrations/hass/hass_converter.py+++ b/src/hi/integrations/hass/hass_converter.py@@ -4,6 +4,7 @@ from typing import Dict, Listfrom django.db import transaction+from hi.apps.alert.enums import SecurityPosture, AlarmLevelfrom hi.apps.attribute.enums import (AttributeType,AttributeValueType,@@ -227,7 +228,9 @@ class HassConverter:return hass_device_id_to_device@classmethod- def create_models_for_hass_device( cls, hass_device : HassDevice ) -> Entity:+ def create_models_for_hass_device( cls,+ hass_device : HassDevice,+ add_alarm_events : bool ) -> Entity:with transaction.atomic():@@ -259,6 +262,7 @@ class HassConverter:entity = entity,hass_device = hass_device,hass_state_list = hass_device.hass_state_list,+ add_alarm_events = add_alarm_events,)return entity@@ -345,6 +349,7 @@ class HassConverter:entity = entity,hass_device = hass_device,hass_state_list = new_hass_state_list,+ add_alarm_events = False,)for integration_key, sensor in entiity_sensors.items():@@ -365,9 +370,10 @@ class HassConverter:@classmethoddef _create_hass_sensors_and_controllers( cls,- entity : Entity,- hass_device : HassDevice,- hass_state_list : List[ HassState ] ):+ entity : Entity,+ hass_device : HassDevice,+ hass_state_list : List[ HassState ],+ add_alarm_events : bool ):"""Each HAss state of the device becomes a HI state with a Sensor.Some may have also require a Controller.@@ -419,6 +425,7 @@ class HassConverter:hass_state = hass_state,entity = entity,integration_key = state_integration_key,+ add_alarm_events = add_alarm_events,)prefix_to_entity_state[hass_state.entity_id_prefix] = entity_state@@ -427,10 +434,11 @@ class HassConverter:@classmethoddef _create_hass_state_sensor_or_controller( cls,- hass_device : HassDevice,- hass_state : HassState,- entity : Entity,- integration_key : IntegrationKey ) -> EntityState:+ hass_device : HassDevice,+ hass_state : HassState,+ entity : Entity,+ integration_key : IntegrationKey,+ add_alarm_events : bool ) -> EntityState:name = hass_state.friendly_namedevice_class = hass_state.device_classif not name:@@ -473,6 +481,7 @@ class HassConverter:hass_state = hass_state,entity = entity,integration_key = integration_key,+ add_alarm_events = add_alarm_events,)return@@ -532,35 +541,54 @@ class HassConverter:@classmethoddef _create_hass_state_binary_sensor( cls,- hass_device : HassDevice,- hass_state : HassState,- entity : Entity,- integration_key : IntegrationKey ):+ hass_device : HassDevice,+ hass_state : HassState,+ entity : Entity,+ integration_key : IntegrationKey,+ add_alarm_events : bool ):name = hass_state.friendly_namedevice_class = hass_state.device_classif not name and device_class:name = f'{entity.name} ({device_class})'elif not name:name = f'{entity.name} ({hass_state.entity_id_prefix})'-+if hass_state.device_class == HassApi.CONNECTIVITY_DEVICE_CLASS:- HiModelHelper.create_connectivity_sensor(+ sensor = HiModelHelper.create_connectivity_sensor(entity = entity,integration_key = integration_key,name = name,)+ if add_alarm_events:+ HiModelHelper.create_connectivity_event_definition(+ name = f'{sensor.name} Alarm',+ entity_state = sensor.entity_state,+ integration_key = integration_key,+ )elif hass_state.device_class in HassApi.OPEN_CLOSE_DEVICE_CLASS_SET:- HiModelHelper.create_open_close_sensor(+ sensor = HiModelHelper.create_open_close_sensor(entity = entity,integration_key = integration_key,name = name,)+ if add_alarm_events:+ HiModelHelper.create_open_close_event_definition(+ name = f'{sensor.name} Alarm',+ entity_state = sensor.entity_state,+ integration_key = integration_key,+ )elif hass_state.device_class == HassApi.MOTION_DEVICE_CLASS:- HiModelHelper.create_movement_sensor(+ sensor = HiModelHelper.create_movement_sensor(entity = entity,integration_key = integration_key,name = name,)+ if add_alarm_events:+ HiModelHelper.create_movement_event_definition(+ name = f'{sensor.name} Alarm',+ entity_state = sensor.entity_state,+ integration_key = integration_key,+ )elif hass_state.device_class == HassApi.LIGHT_DEVICE_CLASS:HiModelHelper.create_on_off_sensor(entity = entity,@@ -568,11 +596,17 @@ class HassConverter:name = name,)elif hass_state.device_class == HassApi.BATTERY_DEVICE_CLASS:- HiModelHelper.create_high_low_sensor(+ sensor = HiModelHelper.create_high_low_sensor(entity = entity,integration_key = integration_key,name = name,)+ if add_alarm_events:+ HiModelHelper.create_battery_event_definition(+ name = f'{sensor.name} Alarm',+ entity_state = sensor.entity_state,+ integration_key = integration_key,+ )else:HiModelHelper.create_on_off_sensor(entity = entity,diff --git a/src/hi/integrations/hass/hass_manager.py b/src/hi/integrations/hass/hass_manager.pyindex 11724f27..2b8403bd 100644--- a/src/hi/integrations/hass/hass_manager.py+++ b/src/hi/integrations/hass/hass_manager.py@@ -2,6 +2,7 @@ import loggingfrom typing import Dictfrom hi.apps.common.singleton import Singleton+from hi.apps.common.utils import str_to_boolfrom hi.integrations.core.exceptions import IntegrationAttributeError, IntegrationErrorfrom hi.integrations.core.integration_key import IntegrationKey@@ -19,7 +20,7 @@ class HassManager( Singleton ):def __init_singleton__( self ):self._is_loading = False- self._hass_attributes = dict()+ self._hass_attr_type_to_attribute = dict()self._hass_client = Noneself.reload()return@@ -35,8 +36,8 @@ class HassManager( Singleton ):returntry:self._is_loading = True- self._hass_attributes = self._load_attributes()- self._hass_client = self.create_hass_client( self._hass_attributes )+ self._hass_attr_type_to_attribute = self._load_attributes()+ self._hass_client = self.create_hass_client( self._hass_attr_type_to_attribute )self.clear_caches()finally:@@ -47,7 +48,7 @@ class HassManager( Singleton ):def clear_caches(self):return- def _load_attributes(self) -> Dict[ str, IntegrationAttribute ]:+ def _load_attributes(self) -> Dict[ HassAttributeType, IntegrationAttribute ]:try:hass_integration = Integration.objects.get( integration_id = HassMetaData.integration_id )except Integration.DoesNotExist:@@ -56,13 +57,14 @@ class HassManager( Singleton ):if not hass_integration.is_enabled:raise IntegrationError( 'Home Assistant integration is not enabled.' )- attribute_dict = hass_integration.attributes_by_integration_key+ hass_attr_type_to_attribute = dict()+ integration_key_to_attribute = hass_integration.attributes_by_integration_keyfor hass_attr_type in HassAttributeType:integration_key = IntegrationKey(integration_id = hass_integration.integration_id,integration_name = str(hass_attr_type),)- hass_attr = attribute_dict.get( integration_key )+ hass_attr = integration_key_to_attribute.get( integration_key )if not hass_attr:if hass_attr_type.is_required:raise IntegrationAttributeError( f'Missing HAss attribute {hass_attr_type}' )@@ -71,11 +73,14 @@ class HassManager( Singleton ):if hass_attr.is_required and not hass_attr.value.strip():raise IntegrationAttributeError( f'Missing HAss attribute value for {hass_attr_type}' )+ hass_attr_type_to_attribute[hass_attr_type] = hass_attrcontinue- return { x.name: x for x in attribute_dict.values() }+ return hass_attr_type_to_attribute- def create_hass_client( self, hass_attributes : Dict[ str, IntegrationAttribute ] ) -> HassClient:+ def create_hass_client(+ self,+ hass_attr_type_to_attribute : Dict[ HassAttributeType, IntegrationAttribute ] ) -> HassClient:# Verify integration and build API data payloadapi_options = {# 'disable_ssl_cert_check': True@@ -85,13 +90,13 @@ class HassManager( Singleton ):HassAttributeType.API_TOKEN: HassClient.API_TOKEN,}- attribute_dict = { x.integration_key: x for x in hass_attributes.values() }+ integration_key_to_attribute = { x.integration_key: x for x in hass_attr_type_to_attribute.values() }for hass_attr_type in attr_to_api_option_key.keys():integration_key = IntegrationKey(integration_id = HassMetaData.integration_id,integration_name = str(hass_attr_type),)- hass_attr = attribute_dict.get( integration_key )+ hass_attr = integration_key_to_attribute.get( integration_key )if not hass_attr:raise IntegrationAttributeError( f'Missing HAss API attribute {hass_attr_type}' )if not hass_attr.value.strip():@@ -104,8 +109,12 @@ class HassManager( Singleton ):logger.debug( f'Home Assistant client options: {api_options}' )return HassClient( api_options = api_options )- def get_hass_attribute( self, attr_name : str ) -> str:- return self._hass_attributes.get( attr_name )+ @property+ def should_add_alarm_events( self ) -> bool:+ attribute = self._hass_attr_type_to_attribute.get( HassAttributeType.ADD_ALARM_EVENTS )+ if attribute:+ return str_to_bool( attribute.value )+ return Falsedef fetch_hass_states_from_api( self, verbose : bool = True ) -> Dict[ str, HassState ]:if verbose:diff --git a/src/hi/integrations/hass/hass_sync.py b/src/hi/integrations/hass/hass_sync.pyindex c89e76f2..fbe8eee1 100644--- a/src/hi/integrations/hass/hass_sync.py+++ b/src/hi/integrations/hass/hass_sync.py@@ -47,7 +47,7 @@ class HassSynchronizer:logger.debug( 'HAss client not created. HAss integration disabled?' )result.error_list.append( 'Sync problem. HAss integration disabled?' )return result-+hass_entity_id_to_state = self._hass_manager.fetch_hass_states_from_api()result.message_list.append( f'Found {len(hass_entity_id_to_state)} current HAss states.' )@@ -63,7 +63,7 @@ class HassSynchronizer:HassConverter.hass_device_to_integration_key( hass_device ): hass_devicefor hass_device in hass_device_id_to_device.values()}-+with transaction.atomic():for integration_key, hass_device in integration_key_to_hass_device.items():entity = integration_key_to_entity.get( integration_key )@@ -106,7 +106,10 @@ class HassSynchronizer:def _create_entity( self,hass_device : HassDevice,result : ProcessingResult ):- entity = HassConverter.create_models_for_hass_device( hass_device = hass_device )+ entity = HassConverter.create_models_for_hass_device(+ hass_device = hass_device,+ add_alarm_events = self._hass_manager.should_add_alarm_events,+ )result.message_list.append( f'Created HAss entity: {entity}' )returndiff --git a/src/hi/integrations/zoneminder/zm_manager.py b/src/hi/integrations/zoneminder/zm_manager.pyindex 58e51f6a..c6f7db5e 100644--- a/src/hi/integrations/zoneminder/zm_manager.py+++ b/src/hi/integrations/zoneminder/zm_manager.py@@ -8,6 +8,7 @@ from typing import Dict, Listimport hi.apps.common.datetimeproxy as datetimeproxyfrom hi.apps.common.singleton import Singleton+from hi.apps.common.utils import str_to_boolfrom hi.integrations.core.exceptions import IntegrationAttributeError, IntegrationErrorfrom hi.integrations.core.integration_key import IntegrationKey@@ -33,6 +34,7 @@ class ZoneMinderManager( Singleton ):ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'VIDEO_STREAM_SENSOR_PREFIX = 'monitor.video_stream'MOVEMENT_SENSOR_PREFIX = 'monitor.motion'+ MOVEMENT_EVENT_PREFIX = 'monitor.motion'MONITOR_FUNCTION_SENSOR_PREFIX = 'monitor.function'ZM_RUN_STATE_SENSOR_INTEGRATION_NAME = 'run.state'@@ -44,7 +46,7 @@ class ZoneMinderManager( Singleton ):def __init_singleton__( self ):self._is_loading = False- self._zm_attributes = dict()+ self._zm_attr_type_to_attribute = dict()self._zm_client = Noneself._zm_state_list = list()@@ -68,8 +70,8 @@ class ZoneMinderManager( Singleton ):returntry:self._is_loading = True- self._zm_attributes = self._load_attributes()- self._zm_client = self.create_zm_client( self._zm_attributes )+ self._zm_attr_type_to_attribute = self._load_attributes()+ self._zm_client = self.create_zm_client( self._zm_attr_type_to_attribute )self.clear_caches()finally:@@ -82,7 +84,7 @@ class ZoneMinderManager( Singleton ):self._zm_monitor_list = list()return- def _load_attributes(self) -> Dict[ str, IntegrationAttribute ]:+ def _load_attributes(self) -> Dict[ ZmAttributeType, IntegrationAttribute ]:try:zm_integration = Integration.objects.get( integration_id = ZmMetaData.integration_id )except Integration.DoesNotExist:@@ -90,14 +92,15 @@ class ZoneMinderManager( Singleton ):if not zm_integration.is_enabled:raise IntegrationError( 'ZoneMinder integration is not enabled.' )-- attribute_dict = zm_integration.attributes_by_integration_key++ zm_attr_type_to_attribute = dict()+ integration_key_to_attribute = zm_integration.attributes_by_integration_keyfor zm_attr_type in ZmAttributeType:integration_key = IntegrationKey(integration_id = zm_integration.integration_id,integration_name = str(zm_attr_type),)- zm_attr = attribute_dict.get( integration_key )+ zm_attr = integration_key_to_attribute.get( integration_key )if not zm_attr:if zm_attr_type.is_required:raise IntegrationAttributeError( f'Missing ZM attribute {zm_attr_type}' )@@ -105,12 +108,15 @@ class ZoneMinderManager( Singleton ):continueif zm_attr.is_required and not zm_attr.value.strip():raise IntegrationAttributeError( f'Missing ZM attribute value for {zm_attr_type}' )-++ zm_attr_type_to_attribute[zm_attr_type] = zm_attrcontinue- return { x.name: x for x in attribute_dict.values() }+ return zm_attr_type_to_attribute- def create_zm_client( self, zm_attributes : Dict[ str, IntegrationAttribute ] ) -> ZMApi:+ def create_zm_client(+ self,+ zm_attr_type_to_attribute : Dict[ ZmAttributeType, IntegrationAttribute ] ) -> ZMApi:# Verify integration and build API data payloadapi_options = {@@ -123,13 +129,13 @@ class ZoneMinderManager( Singleton ):ZmAttributeType.API_PASSWORD: 'password',}- attribute_dict = { x.integration_key: x for x in zm_attributes.values() }+ integration_key_to_attribute = { x.integration_key: x for x in zm_attr_type_to_attribute.values() }for zm_attr_type in attr_to_api_option_key.keys():integration_key = IntegrationKey(integration_id = ZmMetaData.integration_id,integration_name = str(zm_attr_type),)- zm_attr = attribute_dict.get( integration_key )+ zm_attr = integration_key_to_attribute.get( integration_key )if not zm_attr:raise IntegrationAttributeError( f'Missing ZM API attribute {zm_attr_type}' )if not zm_attr.value.strip():@@ -142,8 +148,12 @@ class ZoneMinderManager( Singleton ):logger.debug( f'ZoneMinder client options: {api_options}' )return ZMApi( options = api_options )- def get_zm_attribute( self, attr_name : str ) -> str:- return self._zm_attributes.get( attr_name )+ @property+ def should_add_alarm_events( self ) -> bool:+ attribute = self._zm_attr_type_to_attribute.get( ZmAttributeType.ADD_ALARM_EVENTS )+ if attribute:+ return str_to_bool( attribute.value )+ return Falsedef get_zm_states( self, force_load : bool = False ) -> List[ ZmState ]:state_list_age = datetimeproxy.now() - self._zm_state_timestamp@@ -188,16 +198,10 @@ class ZoneMinderManager( Singleton ):)- def _monitor_to_integration_key( self, zm_monitor_id : ZmMonitor ) -> IntegrationKey:- 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:+ def _to_integration_key( self, prefix : str, zm_monitor_id : ZmMonitor ) -> IntegrationKey:return IntegrationKey(integration_id = ZmMetaData.integration_id,- integration_name = f'{sensor_prefix}.{zm_monitor_id}',+ integration_name = f'{prefix}.{zm_monitor_id}',)def get_zm_tzname(self) -> str:diff --git a/src/hi/integrations/zoneminder/zm_monitor.py b/src/hi/integrations/zoneminder/zm_monitor.pyindex 464d0669..b3145f05 100644--- a/src/hi/integrations/zoneminder/zm_monitor.py+++ b/src/hi/integrations/zoneminder/zm_monitor.py@@ -214,8 +214,8 @@ class ZoneMinderMonitor( PeriodicMonitor ):def _create_movement_active_sensor_response( self, zm_event : ZmEvent ):return SensorResponse(- integration_key = self._zm_manager._sensor_to_integration_key(- sensor_prefix = self._zm_manager.MOVEMENT_SENSOR_PREFIX,+ integration_key = self._zm_manager._to_integration_key(+ prefix = self._zm_manager.MOVEMENT_SENSOR_PREFIX,zm_monitor_id = zm_event.monitor_id,),value = str(EntityStateValue.ACTIVE),@@ -225,8 +225,8 @@ class ZoneMinderMonitor( PeriodicMonitor ):def _create_movement_idle_sensor_response( self, zm_event : ZmEvent ):return SensorResponse(- integration_key = self._zm_manager._sensor_to_integration_key(- sensor_prefix = self._zm_manager.MOVEMENT_SENSOR_PREFIX,+ integration_key = self._zm_manager._to_integration_key(+ prefix = self._zm_manager.MOVEMENT_SENSOR_PREFIX,zm_monitor_id = zm_event.monitor_id,),value = str(EntityStateValue.IDLE),@@ -235,8 +235,8 @@ class ZoneMinderMonitor( PeriodicMonitor ):def _create_idle_sensor_response( self, zm_monitor : ZmMonitor, timestamp : datetime ):return SensorResponse(- integration_key = self._zm_manager._sensor_to_integration_key(- sensor_prefix = self._zm_manager.MOVEMENT_SENSOR_PREFIX,+ integration_key = self._zm_manager._to_integration_key(+ prefix = self._zm_manager.MOVEMENT_SENSOR_PREFIX,zm_monitor_id = zm_monitor.id(),),value = str(EntityStateValue.IDLE),@@ -245,8 +245,8 @@ class ZoneMinderMonitor( PeriodicMonitor ):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,+ integration_key = self._zm_manager._to_integration_key(+ 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() ),@@ -255,8 +255,8 @@ class ZoneMinderMonitor( PeriodicMonitor ):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,+ integration_key = self._zm_manager._to_integration_key(+ prefix = self._zm_manager.MONITOR_FUNCTION_SENSOR_PREFIX,zm_monitor_id = zm_monitor.id(),),value = str( zm_monitor.function() ),diff --git a/src/hi/integrations/zoneminder/zm_sync.py b/src/hi/integrations/zoneminder/zm_sync.pyindex 373f08ca..9bee9c24 100644--- a/src/hi/integrations/zoneminder/zm_sync.py+++ b/src/hi/integrations/zoneminder/zm_sync.py@@ -91,7 +91,7 @@ class ZoneMinderSynchronizer:returndef _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.' )@@ -122,7 +122,10 @@ class ZoneMinderSynchronizer: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 = self._zm_manager._to_integration_key(+ prefix = self._zm_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX,+ zm_monitor_id = zm_monitor.id(),+ )integration_key_to_monitor[integration_key] = zm_monitorcontinue@@ -176,8 +179,10 @@ class ZoneMinderSynchronizer:result : ProcessingResult ):with transaction.atomic():- entity_integration_key = self._zm_manager._monitor_to_integration_key(- zm_monitor_id = zm_monitor.id() )+ entity_integration_key = self._zm_manager._to_integration_key(+ prefix = self._zm_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX,+ zm_monitor_id = zm_monitor.id(),+ )entity = Entity(name = zm_monitor.name(),entity_type_str = str(EntityType.CAMERA),@@ -188,27 +193,38 @@ class ZoneMinderSynchronizer: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,+ integration_key = self._zm_manager._to_integration_key(+ prefix = self._zm_manager.VIDEO_STREAM_SENSOR_PREFIX,zm_monitor_id = zm_monitor.id(),),)- HiModelHelper.create_movement_sensor(+ movement_sensor = HiModelHelper.create_movement_sensor(entity = entity,- integration_key = self._zm_manager._sensor_to_integration_key(- sensor_prefix = self._zm_manager.MOVEMENT_SENSOR_PREFIX,+ integration_key = self._zm_manager._to_integration_key(+ 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,+ integration_key = self._zm_manager._to_integration_key(+ 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 },)++ if self._zm_manager.should_add_alarm_events:+ HiModelHelper.create_movement_event_definition(+ name = f'{movement_sensor.name} Alarm',+ entity_state = movement_sensor.entity_state,+ integration_key = self._zm_manager._to_integration_key(+ prefix = self._zm_manager.MOVEMENT_EVENT_PREFIX,+ zm_monitor_id = zm_monitor.id(),+ ),+ )+result.message_list.append( f'Create new camera entity: {entity}' )return@@ -228,11 +244,9 @@ class ZoneMinderSynchronizer:def _remove_entity( self,entity : Entity,result : ProcessingResult ):++ # TODO: Should we remove the EventDefinitions that were auto-created (with integration key)?+entity.delete() # Deletion cascades to attributes, positions, sensors, controllers, etc.result.message_list.append( f'Removed stale ZM entity: {entity}' )return-----