Skip to content

Home Information - Your home, your data, organized.

Python

Added boolean attribute. Integration refactor of attribute loading.

Anthony Cassandra888bc84d297a
diff --git a/src/hi/apps/attribute/enums.py b/src/hi/apps/attribute/enums.py
index 8159abb2..dd0ab200 100644
--- a/src/hi/apps/attribute/enums.py
+++ b/src/hi/apps/attribute/enums.py
@@ -17,7 +17,8 @@ class AttributeValueType(LabeledEnum):
FILE = ('File' , '' ) # relative filename of MEDIA_ROOT
SECRET = ('Secret' , '' )
ENUM = ('Enum' , '' )
-
+ BOOLEAN = ('Boolean' , '' )
+
@classmethod
def default(cls):
return cls.TEXT
@@ -37,3 +38,7 @@ class AttributeValueType(LabeledEnum):
@property
def is_enum(self):
return bool( self == AttributeValueType.ENUM )
+
+ @property
+ def is_boolean(self):
+ return bool( self == AttributeValueType.BOOLEAN )
diff --git a/src/hi/apps/attribute/forms.py b/src/hi/apps/attribute/forms.py
index 00329aa1..db66b346 100644
--- a/src/hi/apps/attribute/forms.py
+++ b/src/hi/apps/attribute/forms.py
@@ -3,7 +3,7 @@ import mimetypes
from django.core.exceptions import ValidationError
from django import forms
-from hi.apps.common.utils import is_blank
+from hi.apps.common.utils import is_blank, str_to_bool
from .enums import AttributeType, AttributeValueType
@@ -41,6 +41,9 @@ class AttributeForm( forms.ModelForm ):
# Access the instance's value_type field
instance = kwargs.get('instance')
+ if instance and instance.value_type.is_boolean:
+ self.initial['value'] = str_to_bool( instance.value )
+
for field in self.fields.values():
if self._show_as_editable or ( instance and instance.is_editable ):
continue
@@ -64,7 +67,9 @@ class AttributeForm( forms.ModelForm ):
value = cleaned_data.get('value')
if self.instance.is_required and is_blank( value ):
self.add_error( 'value', 'A value is required.')
-
+ if self.instance.value_type.is_boolean:
+ cleaned_data['value'] = str(str_to_bool( value ))
+
if self.cleaned_data.get('secret'):
stripped_value = value.strip()
value_lines = stripped_value.splitlines()
diff --git a/src/hi/apps/attribute/templates/attribute/panes/attribute_form.html b/src/hi/apps/attribute/templates/attribute/panes/attribute_form.html
index 1e93b5df..63ac6308 100644
--- a/src/hi/apps/attribute/templates/attribute/panes/attribute_form.html
+++ b/src/hi/apps/attribute/templates/attribute/panes/attribute_form.html
@@ -19,6 +19,8 @@
{% include "attribute/panes/attribute_form_file.html" %}
{% elif attribute_form.instance.value_type.is_enum %}
{% include "attribute/panes/attribute_form_enum.html" %}
+ {% elif attribute_form.instance.value_type.is_boolean %}
+ {% include "attribute/panes/attribute_form_boolean.html" %}
{% else %}
{% include "attribute/panes/attribute_form_text.html" %}
{% endif %}
diff --git a/src/hi/apps/attribute/templates/attribute/panes/attribute_form_boolean.html b/src/hi/apps/attribute/templates/attribute/panes/attribute_form_boolean.html
new file mode 100644
index 00000000..897d4c2b
--- /dev/null
+++ b/src/hi/apps/attribute/templates/attribute/panes/attribute_form_boolean.html
@@ -0,0 +1,16 @@
+{% load common_template_helpers %}
+<input type="hidden" id="{{ attribute_form.name.id_for_label }}"
+ name="{{ attribute_form.name.html_name }}"
+ value="{{ attribute_form.instance.name }}" />
+<div class="input-group" >
+ <input type="checkbox" name="{{ attribute_form.value.html_name }}"
+ id="{{ attribute_form.value.id_for_label }}"
+ {% if attribute_form.value.value %}checked="on"{% endif %} >
+ <label for="{{ attribute_form.value.id_for_label }}">Add Alarm Events</label>
+</div>
+
+{% if attribute_form.show_as_editable and attribute_form.instance.is_editable and attribute_form.instance.attribute_type.can_delete %}
+<div class="">
+ {{ attribute_form.DELETE }} Delete
+</div>
+{% endif %}
diff --git a/src/hi/apps/common/utils.py b/src/hi/apps/common/utils.py
index 34ef3870..71cfa1c1 100644
--- a/src/hi/apps/common/utils.py
+++ b/src/hi/apps/common/utils.py
@@ -21,12 +21,19 @@ def is_blank( obj ):
return False
return bool( obj.strip() == '' )
-
+
+def str_to_bool( value: str ) -> bool:
+ truthy_values = {'true', '1', 'on', 'yes', 'y', 't', 'enabled'}
+ if isinstance( value, str ):
+ return value.strip().lower() in truthy_values
+ return False
+
+
def get_long_display_name( user_obj ):
if not user_obj:
return settings.USER_DISPLAY_NAME_DEFAULT
if user_obj.last_name and user_obj.first_name:
- return "%s, %s" % ( user_obj.last_name, user_obj.first_name )
+ return '%s, %s' % ( user_obj.last_name, user_obj.first_name )
if user_obj.last_name:
return user_obj.last_name
if user_obj.first_name:
diff --git a/src/hi/apps/event/admin.py b/src/hi/apps/event/admin.py
index 8c38f3f3..e728bc7a 100644
--- a/src/hi/apps/event/admin.py
+++ b/src/hi/apps/event/admin.py
@@ -1,3 +1,56 @@
from django.contrib import admin
-# Register your models here.
+from . import models
+
+
+class EventClauseInLine(admin.TabularInline):
+ model = models.EventClause
+ extra = 0
+ show_change_link = True
+
+
+class AlarmActionInLine(admin.TabularInline):
+ model = models.AlarmAction
+ extra = 0
+ show_change_link = True
+
+
+class ControlActionInLine(admin.TabularInline):
+ model = models.ControlAction
+ extra = 0
+ show_change_link = True
+
+
[email protected](models.EventDefinition)
+class EventDefinitionAdmin(admin.ModelAdmin):
+
+ show_full_result_count = False
+
+ list_display = (
+ 'name',
+ 'event_window_secs',
+ 'enabled',
+ )
+
+ search_fields = ['zzz']
+ readonly_fields = ( 'created_datetime', 'updated_datetime', )
+ inlines = [
+ EventClauseInLine,
+ AlarmActionInLine,
+ ControlActionInLine,
+ ]
+
+
[email protected](models.EventHistory)
+class EventHistoryAdmin(admin.ModelAdmin):
+
+ show_full_result_count = False
+
+ list_display = (
+ 'event_definition',
+ 'event_datetime',
+ )
+
+ search_fields = ['event_definition__name']
+ readonly_fields = ( 'event_datetime', )
+
diff --git a/src/hi/apps/event/event_manager.py b/src/hi/apps/event/event_manager.py
index 465d42a6..c97f7408 100644
--- a/src/hi/apps/event/event_manager.py
+++ b/src/hi/apps/event/event_manager.py
@@ -1,6 +1,7 @@
from asgiref.sync import sync_to_async
from cachetools import TTLCache
from collections import deque
+from datetime import timedelta
import logging
from typing import List
@@ -28,20 +29,28 @@ class EventManager(Singleton):
def reload(self):
self._event_definitions = EventDefinition.objects.prefetch_related(
'clauses',
+ 'clauses__entity_state',
'alarm_actions',
'control_actions',
).filter( enabled = True )
- self._max_event_window_secs = max([ x.event_window_secs for x in self._event_definitions ])
+ 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 = 10
return
async def add_entity_state_transitions( self,
entity_state_transition_list : List[ EntityStateTransition ] ):
if not entity_state_transition_list:
return
+ logger.debug( f'Adding state transitions: {entity_state_transition_list}' )
+
self._recent_transitions.extend( entity_state_transition_list )
self._purge_old_transitions()
new_event_list = self._get_new_events()
+ logger.debug( f'New events found: {new_event_list}' )
+
await self._do_new_event_action( event_list = new_event_list )
await self._add_to_event_history( event_list = new_event_list )
return
@@ -65,7 +74,7 @@ class EventManager(Singleton):
if not recent_event:
return False
recent_event_timedelta = datetimeproxy.now() - recent_event.timestamp
- return bool( recent_event_timedelta <= event_definition.event_window_secs )
+ return bool( recent_event_timedelta.seconds <= event_definition.event_window_secs )
def _create_event_if_detected( self, event_definition : EventDefinition ) -> bool:
if not event_definition.clauses.exists():
@@ -100,7 +109,7 @@ class EventManager(Singleton):
current_timestamp = datetimeproxy.now()
while ( self._recent_transitions
and (( current_timestamp - self._recent_transitions[0].timestamp )
- > self._max_event_window_secs )):
+ > timedelta( seconds = self._max_event_window_secs ))):
self._recent_transitions.popleft()
continue
return
diff --git a/src/hi/apps/event/migrations/0001_initial.py b/src/hi/apps/event/migrations/0001_initial.py
new file mode 100644
index 00000000..642866b1
--- /dev/null
+++ b/src/hi/apps/event/migrations/0001_initial.py
@@ -0,0 +1,202 @@
+# Generated by Django 4.2.15 on 2024-12-05 18:14
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ ("control", "0003_controller_persist_history"),
+ ("entity", "0006_rename_value_range_entityattribute_value_range_str_and_more"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="EventDefinition",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("name", models.CharField(max_length=64, verbose_name="Name")),
+ (
+ "event_window_secs",
+ models.PositiveIntegerField(verbose_name="Event Window Secs"),
+ ),
+ ("enabled", models.BooleanField(default=True)),
+ (
+ "created_datetime",
+ models.DateTimeField(auto_now_add=True, verbose_name="Created"),
+ ),
+ (
+ "updated_datetime",
+ models.DateTimeField(auto_now=True, verbose_name="Updated"),
+ ),
+ ],
+ options={
+ "verbose_name": "Event Definition",
+ "verbose_name_plural": "Event Definitions",
+ },
+ ),
+ migrations.CreateModel(
+ name="EventHistory",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("event_datetime", models.DateTimeField(verbose_name="Timestamp")),
+ (
+ "event_definition",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="history",
+ to="event.eventdefinition",
+ verbose_name="Event Definition",
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "Event History",
+ "verbose_name_plural": "Event History",
+ },
+ ),
+ migrations.CreateModel(
+ name="EventClause",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("value", models.CharField(max_length=255, verbose_name="Value")),
+ (
+ "created_datetime",
+ models.DateTimeField(auto_now_add=True, verbose_name="Created"),
+ ),
+ (
+ "updated_datetime",
+ models.DateTimeField(auto_now=True, verbose_name="Updated"),
+ ),
+ (
+ "entity_state",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="entity.entitystate",
+ verbose_name="Entity State",
+ ),
+ ),
+ (
+ "event_definition",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="clauses",
+ to="event.eventdefinition",
+ verbose_name="Event Definition",
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "Event Clause",
+ "verbose_name_plural": "Event Clauses",
+ },
+ ),
+ migrations.CreateModel(
+ name="ControlAction",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("value", models.CharField(max_length=255, verbose_name="Value")),
+ (
+ "created_datetime",
+ models.DateTimeField(auto_now_add=True, verbose_name="Created"),
+ ),
+ (
+ "controller",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="control_actions",
+ to="control.controller",
+ verbose_name="Controller",
+ ),
+ ),
+ (
+ "event_definition",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="control_actions",
+ to="event.eventdefinition",
+ verbose_name="Event Definition",
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "Control Action",
+ "verbose_name_plural": "Control Actions",
+ },
+ ),
+ migrations.CreateModel(
+ name="AlarmAction",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "security_posture_str",
+ models.CharField(max_length=32, verbose_name="Security Posture"),
+ ),
+ (
+ "alarm_level_str",
+ models.CharField(max_length=32, verbose_name="Alarm Level"),
+ ),
+ (
+ "lifetime_secs",
+ models.PositiveIntegerField(verbose_name="Lifetime Secs"),
+ ),
+ (
+ "event_definition",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="alarm_actions",
+ to="event.eventdefinition",
+ verbose_name="Event Definition",
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "Alarm Actions",
+ "verbose_name_plural": "Alarm Actions",
+ },
+ ),
+ ]
diff --git a/src/hi/apps/event/transient_models.py b/src/hi/apps/event/transient_models.py
index 4d76f2d9..9d2c5293 100644
--- a/src/hi/apps/event/transient_models.py
+++ b/src/hi/apps/event/transient_models.py
@@ -1,4 +1,5 @@
from dataclasses import dataclass
+from datetime import datetime
from typing import List
from hi.apps.alert.transient_models import Alarm
@@ -26,21 +27,19 @@ class Event:
sensor_response_list : List[ SensorResponse ]
@property
- def timestamp(self):
+ def timestamp(self) -> datetime:
return max([ x.timestamp for x in self.sensor_response_list ])
- @property
- def to_event_history(self):
+ def to_event_history(self) -> EventHistory:
return EventHistory(
event_definition = self.event_definition,
event_datetime = self.timestamp,
)
- @property
- def to_alarm( self, alarm_action : AlarmAction ):
+ def to_alarm( self, alarm_action : AlarmAction ) -> Alarm:
return Alarm(
title = self.event_definition.name,
- details = ', '.join([ x.name for x in self.sensor_response_list ]),
+ 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,
diff --git a/src/hi/apps/sense/sensor_response_manager.py b/src/hi/apps/sense/sensor_response_manager.py
index 8066f8de..59dc5094 100644
--- a/src/hi/apps/sense/sensor_response_manager.py
+++ b/src/hi/apps/sense/sensor_response_manager.py
@@ -89,9 +89,9 @@ class SensorResponseManager( Singleton ):
changed_sensor_response_list.append( latest_sensor_response )
continue
+ logger.debug( f'Sensors changed: {len(changed_sensor_response_list)} of {len(sensor_response_map)}' )
await self._add_latest_sensor_responses( changed_sensor_response_list )
await self._event_manager.add_entity_state_transitions( entity_state_transition_list )
- logger.debug( f'Sensor changed: {len(changed_sensor_response_list)} of {len(sensor_response_map)}' )
return
def get_all_latest_sensor_responses( self ) -> Dict[ Sensor, List[ SensorResponse ] ]:
diff --git a/src/hi/integrations/core/exceptions.py b/src/hi/integrations/core/exceptions.py
index f10424e6..2b383161 100644
--- a/src/hi/integrations/core/exceptions.py
+++ b/src/hi/integrations/core/exceptions.py
@@ -1,3 +1,7 @@
+class IntegrationError(Exception):
+ pass
+
+
class IntegrationAttributeError(Exception):
pass
diff --git a/src/hi/integrations/hass/enums.py b/src/hi/integrations/hass/enums.py
index 85c0ab0f..872aa3f7 100644
--- a/src/hi/integrations/hass/enums.py
+++ b/src/hi/integrations/hass/enums.py
@@ -20,6 +20,15 @@ class HassAttributeType( IntegrationAttributeType ):
True,
True,
)
+ ADD_ALARM_EVENTS = (
+ 'Add Alarm Events',
+ '',
+ AttributeValueType.BOOLEAN,
+ None,
+ True,
+ False,
+ True,
+ )
class HassStateValue:
diff --git a/src/hi/integrations/hass/hass_manager.py b/src/hi/integrations/hass/hass_manager.py
index 2b918122..11724f27 100644
--- a/src/hi/integrations/hass/hass_manager.py
+++ b/src/hi/integrations/hass/hass_manager.py
@@ -3,9 +3,9 @@ from typing import Dict
from hi.apps.common.singleton import Singleton
-from hi.integrations.core.exceptions import IntegrationAttributeError
+from hi.integrations.core.exceptions import IntegrationAttributeError, IntegrationError
from hi.integrations.core.integration_key import IntegrationKey
-from hi.integrations.core.models import Integration
+from hi.integrations.core.models import Integration, IntegrationAttribute
from .enums import HassAttributeType
from .hass_client import HassClient
@@ -19,6 +19,7 @@ class HassManager( Singleton ):
def __init_singleton__( self ):
self._is_loading = False
+ self._hass_attributes = dict()
self._hass_client = None
self.reload()
return
@@ -34,23 +35,47 @@ class HassManager( Singleton ):
return
try:
self._is_loading = True
- self._hass_client = self.create_hass_client()
-
+ self._hass_attributes = self._load_attributes()
+ self._hass_client = self.create_hass_client( self._hass_attributes )
+ self.clear_caches()
+
finally:
self._is_loading = False
logger.debug( 'HAss loading completed.' )
return
- def create_hass_client(self):
+ def clear_caches(self):
+ return
+
+ def _load_attributes(self) -> Dict[ str, IntegrationAttribute ]:
try:
hass_integration = Integration.objects.get( integration_id = HassMetaData.integration_id )
except Integration.DoesNotExist:
- logger.debug( 'HAss integration is not implemented.' )
-
+ raise IntegrationError( 'Home Assistant integration is not implemented.' )
+
if not hass_integration.is_enabled:
- logger.debug( 'HAss integration is not enabled.' )
- return None
+ raise IntegrationError( 'Home Assistant integration is not enabled.' )
+
+ attribute_dict = hass_integration.attributes_by_integration_key
+ for 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 )
+ if not hass_attr:
+ if hass_attr_type.is_required:
+ raise IntegrationAttributeError( f'Missing HAss attribute {hass_attr_type}' )
+ else:
+ continue
+ if hass_attr.is_required and not hass_attr.value.strip():
+ raise IntegrationAttributeError( f'Missing HAss attribute value for {hass_attr_type}' )
+
+ continue
+ return { x.name: x for x in attribute_dict.values() }
+
+ def create_hass_client( self, hass_attributes : Dict[ str, IntegrationAttribute ] ) -> HassClient:
# Verify integration and build API data payload
api_options = {
# 'disable_ssl_cert_check': True
@@ -60,27 +85,28 @@ class HassManager( Singleton ):
HassAttributeType.API_TOKEN: HassClient.API_TOKEN,
}
- attribute_dict = hass_integration.attributes_by_integration_key
- for hass_attr_type in HassAttributeType:
+ attribute_dict = { x.integration_key: x for x in hass_attributes.values() }
+ for hass_attr_type in attr_to_api_option_key.keys():
integration_key = IntegrationKey(
- integration_id = hass_integration.integration_id,
+ integration_id = HassMetaData.integration_id,
integration_name = str(hass_attr_type),
)
hass_attr = attribute_dict.get( integration_key )
if not hass_attr:
- raise IntegrationAttributeError( f'Missing HAss attribute {hass_attr_type}' )
- if hass_attr.is_required and not hass_attr.value.strip():
- raise IntegrationAttributeError( f'Missing HAss attribute value for {hass_attr_type}' )
+ raise IntegrationAttributeError( f'Missing HAss API attribute {hass_attr_type}' )
+ if not hass_attr.value.strip():
+ raise IntegrationAttributeError( f'Missing HAss API attribute value for {hass_attr_type}' )
- if hass_attr_type in attr_to_api_option_key:
- options_key = attr_to_api_option_key[hass_attr_type]
- api_options[options_key] = hass_attr.value
-
+ options_key = attr_to_api_option_key[hass_attr_type]
+ api_options[options_key] = hass_attr.value
continue
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 )
+
def fetch_hass_states_from_api( self, verbose : bool = True ) -> Dict[ str, HassState ]:
if verbose:
logger.debug( 'Getting current HAss states.' )
diff --git a/src/hi/integrations/zoneminder/enums.py b/src/hi/integrations/zoneminder/enums.py
index 13c95ebb..00896ec1 100644
--- a/src/hi/integrations/zoneminder/enums.py
+++ b/src/hi/integrations/zoneminder/enums.py
@@ -49,6 +49,15 @@ class ZmAttributeType( IntegrationAttributeType ):
True,
'America/Chicago',
)
+ ADD_ALARM_EVENTS = (
+ 'Add Alarm Events',
+ '',
+ AttributeValueType.BOOLEAN,
+ None,
+ True,
+ False,
+ True,
+ )
class ZmMonitorFunction(LabeledEnum):
diff --git a/src/hi/integrations/zoneminder/zm_manager.py b/src/hi/integrations/zoneminder/zm_manager.py
index 4d0fa0d6..58e51f6a 100644
--- a/src/hi/integrations/zoneminder/zm_manager.py
+++ b/src/hi/integrations/zoneminder/zm_manager.py
@@ -9,7 +9,7 @@ from typing import Dict, List
import hi.apps.common.datetimeproxy as datetimeproxy
from hi.apps.common.singleton import Singleton
-from hi.integrations.core.exceptions import IntegrationAttributeError
+from hi.integrations.core.exceptions import IntegrationAttributeError, IntegrationError
from hi.integrations.core.integration_key import IntegrationKey
from hi.integrations.core.models import Integration, IntegrationAttribute
@@ -44,6 +44,7 @@ class ZoneMinderManager( Singleton ):
def __init_singleton__( self ):
self._is_loading = False
+ self._zm_attributes = dict()
self._zm_client = None
self._zm_state_list = list()
@@ -67,7 +68,8 @@ class ZoneMinderManager( Singleton ):
return
try:
self._is_loading = True
- self._zm_client = self.create_zm_client()
+ self._zm_attributes = self._load_attributes()
+ self._zm_client = self.create_zm_client( self._zm_attributes )
self.clear_caches()
finally:
@@ -80,15 +82,35 @@ class ZoneMinderManager( Singleton ):
self._zm_monitor_list = list()
return
- def create_zm_client(self):
+ def _load_attributes(self) -> Dict[ str, IntegrationAttribute ]:
try:
zm_integration = Integration.objects.get( integration_id = ZmMetaData.integration_id )
except Integration.DoesNotExist:
- logger.debug( 'ZoneMinder integration is not implemented.' )
-
+ raise IntegrationError( 'ZoneMinder integration is not implemented.' )
+
if not zm_integration.is_enabled:
- logger.debug( 'ZoneMinder integration is not enabled.' )
- return None
+ raise IntegrationError( 'ZoneMinder integration is not enabled.' )
+
+ attribute_dict = zm_integration.attributes_by_integration_key
+ for 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 )
+ if not zm_attr:
+ if zm_attr_type.is_required:
+ raise IntegrationAttributeError( f'Missing ZM attribute {zm_attr_type}' )
+ else:
+ continue
+ if zm_attr.is_required and not zm_attr.value.strip():
+ raise IntegrationAttributeError( f'Missing ZM attribute value for {zm_attr_type}' )
+
+ continue
+
+ return { x.name: x for x in attribute_dict.values() }
+
+ def create_zm_client( self, zm_attributes : Dict[ str, IntegrationAttribute ] ) -> ZMApi:
# Verify integration and build API data payload
api_options = {
@@ -101,26 +123,27 @@ class ZoneMinderManager( Singleton ):
ZmAttributeType.API_PASSWORD: 'password',
}
- attribute_dict = zm_integration.attributes_by_integration_key
+ attribute_dict = { x.integration_key: x for x in zm_attributes.values() }
for zm_attr_type in attr_to_api_option_key.keys():
integration_key = IntegrationKey(
- integration_id = zm_integration.integration_id,
+ integration_id = ZmMetaData.integration_id,
integration_name = str(zm_attr_type),
)
zm_attr = attribute_dict.get( integration_key )
if not zm_attr:
- raise IntegrationAttributeError( f'Missing ZM attribute {zm_attr_type}' )
- if zm_attr.is_required and not zm_attr.value.strip():
- raise IntegrationAttributeError( f'Missing ZM attribute value for {zm_attr_type}' )
+ raise IntegrationAttributeError( f'Missing ZM API attribute {zm_attr_type}' )
+ if not zm_attr.value.strip():
+ raise IntegrationAttributeError( f'Missing ZM API attribute value for {zm_attr_type}' )
- if zm_attr_type in attr_to_api_option_key:
- options_key = attr_to_api_option_key[zm_attr_type]
- api_options[options_key] = zm_attr.value
-
+ options_key = attr_to_api_option_key[zm_attr_type]
+ api_options[options_key] = zm_attr.value
continue
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 )
def get_zm_states( self, force_load : bool = False ) -> List[ ZmState ]:
state_list_age = datetimeproxy.now() - self._zm_state_timestamp