Home Information - Your home, your data, organized.
Python
Added ability to manage principal entities.
Anthony Cassandrad59816e17564
diff --git a/src/hi/apps/collection/collection_manager.py b/src/hi/apps/collection/collection_manager.pyindex 3105645e..5b6a0d89 100644--- a/src/hi/apps/collection/collection_manager.py+++ b/src/hi/apps/collection/collection_manager.py@@ -371,25 +371,22 @@ class CollectionManager(Singleton):continuereturn- def create_collection_view_group( self, location_view : LocationView ) -> CollectionViewGroup:-+ def create_location_collection_view_group( self, location_view : LocationView ) -> CollectionViewGroup:+ existing_collections = [ x.collection+ for x in location_view.collection_views.select_related('collection').all() ]+ return self.create_collection_view_group( existing_collections = existing_collections )++ def create_collection_view_group( self,+ existing_collections : List[ Collection ] ) -> CollectionViewGroup:+ existing_collection_set = set( existing_collections )collection_queryset = Collection.objects.all()- collection_view_group = CollectionViewGroup(- location_view = location_view,- )+ collection_view_group = CollectionViewGroup()for collection in collection_queryset:- exists_in_view = False- for collection_view in collection.collection_views.all():- if collection_view.location_view == location_view:- exists_in_view = True- break- continue-collection_view_item = CollectionViewItem(collection = collection,- exists_in_view = exists_in_view,+ exists_in_view = bool( collection in existing_collection_set ),)collection_view_group.item_list.append( collection_view_item )continuediff --git a/src/hi/apps/collection/transient_models.py b/src/hi/apps/collection/transient_models.pyindex b6b5a0a4..f9bccf96 100644--- a/src/hi/apps/collection/transient_models.py+++ b/src/hi/apps/collection/transient_models.py@@ -5,7 +5,6 @@ from hi.apps.collection.edit.forms import CollectionForm, CollectionPositionFormfrom hi.apps.entity.enums import EntityTypefrom hi.apps.entity.models import Entityfrom hi.apps.entity.transient_models import EntityInfoData-from hi.apps.location.models import LocationViewfrom .models import Collection@@ -27,7 +26,6 @@ class CollectionViewItem:@dataclassclass CollectionViewGroup:- location_view : LocationViewitem_list : List[CollectionViewItem] = field( default_factory = list )diff --git a/src/hi/apps/entity/edit/urls.py b/src/hi/apps/entity/edit/urls.pyindex 3bfb877e..b4e9f5a2 100644--- a/src/hi/apps/entity/edit/urls.py+++ b/src/hi/apps/entity/edit/urls.py@@ -26,5 +26,8 @@ urlpatterns = [async_views.EntityPositionEditView.as_view(),name='entity_position_edit' ),+ re_path( r'^entity/principal/manage/(?P<entity_id>\d+)$',+ views.PrincipalManageView.as_view(),+ name='entity_edit_principal_manage' ),]diff --git a/src/hi/apps/entity/edit/views.py b/src/hi/apps/entity/edit/views.pyindex 65b06aa6..ea5ae565 100644--- a/src/hi/apps/entity/edit/views.py+++ b/src/hi/apps/entity/edit/views.py@@ -1,4 +1,5 @@import logging+import refrom django.core.exceptions import BadRequest, PermissionDeniedfrom django.db import transaction@@ -6,6 +7,7 @@ from django.urls import reversefrom django.utils.decorators import method_decoratorfrom hi.apps.collection.collection_manager import CollectionManager+import hi.apps.common.antinode as antinodefrom hi.apps.entity.entity_manager import EntityManagerfrom hi.apps.entity.models import Entityfrom hi.apps.entity.view_mixin import EntityViewMixin@@ -110,3 +112,47 @@ class EntityDeleteView( HiModalView, EntityViewMixin ):redirect_url = reverse('home')return self.redirect_response( request, redirect_url )++@method_decorator( edit_required, name='dispatch' )+class PrincipalManageView( HiModalView, EntityViewMixin ):++ PRINCIPAL_ENTITY_ID_NAME_PREFIX = 'principal-entity-id-'++ def get_template_name( self ) -> str:+ return 'entity/edit/modals/principal_manage.html'++ def get( self, request, *args, **kwargs ):+ entity = self.get_entity( request, *args, **kwargs )++ entity_manager = EntityManager()+ entity_view_group_list = entity_manager.create_principal_entity_view_group_list(+ entity= entity,+ )+ context = {+ 'entity': entity,+ 'entity_view_group_list': entity_view_group_list,+ 'principal_entity_id_name_prefix': self.PRINCIPAL_ENTITY_ID_NAME_PREFIX,+ }+ return self.modal_response( request, context )++ def post( self, request, *args, **kwargs ):+ entity = self.get_entity( request, *args, **kwargs )++ desired_principal_entity_ids = set()+ for name, value in request.POST.items():+ m = re.match( r'(\D+)(\d+)', name )+ if not m:+ continue+ prefix = m.group(1)+ if prefix == self.PRINCIPAL_ENTITY_ID_NAME_PREFIX:+ desired_principal_entity_ids.add( int( m.group(2) ))+ continue++ EntityManager().adjust_principal_entities(+ entity = entity,+ desired_principal_entity_ids = desired_principal_entity_ids,+ )++ return antinode.refresh_response()++diff --git a/src/hi/apps/entity/entity_manager.py b/src/hi/apps/entity/entity_manager.pyindex 85f36ee9..08978198 100644--- a/src/hi/apps/entity/entity_manager.py+++ b/src/hi/apps/entity/entity_manager.py@@ -1,5 +1,5 @@from decimal import Decimal-from typing import List+from typing import List, Setfrom django.db import transaction@@ -17,6 +17,7 @@ from .models import (Entity,EntityPath,EntityPosition,+ EntityStateDelegation,EntityView,)from .transient_models import (@@ -37,22 +38,19 @@ class EntityManager(Singleton):entity : Entity,is_editing : bool ) -> EntityDetailsData:entity_edit_data = EntityEditData( entity = entity )- sensor_response_list_map = SensorResponseManager().get_entity_latest_sensor_responses( entity = entity )+ sensor_response_list_map = SensorResponseManager().get_entity_latest_sensor_responses(+ entity = entity,+ )entity_state_list = list(entity.states.all())- entity_state_delegation_list = list(- entity.entity_state_delegations.select_related('entity_state', 'entity_state__entity').all()- )- principal_state_list = [ x.entity_state for x in entity_state_delegation_list ]- principal_entity_list = list({ x.entity for x in principal_state_list }) # de-dupe+ principal_entity_list = self.get_principal_entity_list( entity = entity )return EntityInfoData(entity_edit_data = entity_edit_data,sensor_response_list_map = sensor_response_list_map,entity_state_list = entity_state_list,- principal_state_list = principal_state_list,principal_entity_list = principal_entity_list,)@@ -69,12 +67,22 @@ class EntityManager(Singleton):).first()if entity_position:entity_position_form = EntityPositionForm( instance = entity_position )++ principal_entity_list = self.get_principal_entity_list( entity = entity )entity_edit_data = EntityEditData( entity = entity )return EntityDetailsData(entity_edit_data = entity_edit_data,entity_position_form = entity_position_form,+ principal_entity_list = principal_entity_list,)++ def get_principal_entity_list( self, entity : Entity ) -> List[ Entity ]:+ entity_state_delegation_list = list(+ entity.entity_state_delegations.select_related('entity_state', 'entity_state__entity').all()+ )+ principal_state_list = [ x.entity_state for x in entity_state_delegation_list ]+ return list({ x.entity for x in principal_state_list }) # de-dupedef create_entity( self,entity_type : EntityType,@@ -258,28 +266,38 @@ class EntityManager(Singleton):)return entity_path- def create_entity_view_group_list( self, location_view : LocationView ) -> List[EntityViewGroup]:+ def create_location_entity_view_group_list( self, location_view : LocationView ) -> List[EntityViewGroup]:+ existing_entities = [ x.entity+ for x in location_view.entity_views.select_related('entity').all() ]+ return self.create_entity_view_group_list(+ existing_entities = existing_entities,+ exclude_delegates = False,+ )++ def create_principal_entity_view_group_list( self, entity : Entity ) -> List[EntityViewGroup]:+ existing_entities = self.get_principal_entity_list( entity = entity )+ return self.create_entity_view_group_list(+ existing_entities = existing_entities,+ exclude_delegates = True, # Do not allow delegates to delegate+ )+ def create_entity_view_group_list( self,+ existing_entities : List[ Entity ],+ exclude_delegates : bool ) -> List[EntityViewGroup]:+ existing_entity_set = set( existing_entities )entity_queryset = Entity.objects.all()entity_view_group_dict = dict()for entity in entity_queryset:-- exists_in_view = False- for entity_view in entity.entity_views.all():- if entity_view.location_view == location_view:- exists_in_view = True- break+ if exclude_delegates and entity.entity_state_delegations.exists():continue-entity_view_item = EntityViewItem(entity = entity,- exists_in_view = exists_in_view,+ exists_in_view = bool( entity in existing_entity_set ),)if entity.entity_type not in entity_view_group_dict:entity_view_group = EntityViewGroup(- location_view = location_view,entity_type = entity.entity_type,)entity_view_group_dict[entity.entity_type] = entity_view_group@@ -290,3 +308,33 @@ class EntityManager(Singleton):entity_view_group_list.sort( key = lambda item : item.entity_type.label )return entity_view_group_list+ def adjust_principal_entities( self, entity : Entity, desired_principal_entity_ids : Set[ int ] ):++ principal_entity_list = self.get_principal_entity_list( entity = entity )+ previous_principal_entity_map = { x.id: x for x in principal_entity_list }+ previous_principal_entity_ids = set( previous_principal_entity_map.keys() )++ to_add_entity_ids = desired_principal_entity_ids - previous_principal_entity_ids+ to_delete_entity_ids = previous_principal_entity_ids - desired_principal_entity_ids++ to_add_principal_entities = list( Entity.objects.filter( id__in = list(to_add_entity_ids) ) )++ with transaction.atomic():+ for add_principal_entity in to_add_principal_entities:+ for entity_state in add_principal_entity.states.all():+ EntityStateDelegation.objects.create(+ entity_state = entity_state,+ delegate_entity = entity,+ )+ continue+ continue++ delegation_queryset = entity.entity_state_delegations.select_related(+ 'entity_state',+ 'entity_state__entity' ).all()+ for delegation in delegation_queryset:+ if delegation.entity_state.entity.id in to_delete_entity_ids:+ delegation.delete()+ continue+ return+diff --git a/src/hi/apps/entity/templates/entity/edit/modals/principal_manage.html b/src/hi/apps/entity/templates/entity/edit/modals/principal_manage.htmlnew file mode 100644index 00000000..21f1eaad--- /dev/null+++ b/src/hi/apps/entity/templates/entity/edit/modals/principal_manage.html@@ -0,0 +1,46 @@+{% extends "modals/action_with_cancel.html" %}++{% block preamble %}+<form action="{% url 'entity_edit_principal_manage' entity_id=entity.id %}" method="post"+ class="form" data-async="true">+ {% csrf_token %}+{% endblock %}++{% block title_text %}+Principal Add+{% endblock %}++{% block body %}+<div>+ Select entities to add as principals.+</div>++{% for entity_view_group in entity_view_group_list %}+<div class="">+ <div class="h5">{{ entity_view_group.entity_type.label }}</div>+ {% for entity_view_item in entity_view_group.item_list %}+ <div>+ <input type="checkbox"+ id="principal-entity-checkbox-{{ entity_view_item.entity.id }}"+ name="{{ principal_entity_id_name_prefix }}{{ entity_view_item.entity.id }}"+ {% if entity_view_item.exists_in_view %}checked{% endif %} >+ <label for="principal-entity-checkbox-{{ entity_view_item.entity.id }}">{{ entity_view_item.entity.name }}</label>+ </div>+ {% endfor %}+</div>+{% empty %}+<div><em>No entities defined.</em></div>+{% endfor %}++{% endblock %}++{% block action_right %}+<button id="hi-principal-manage-button" type="submit" class="btn btn-lg btn-success"+ name="action" value="submit">+ SUBMIT+</button>+{% endblock %}++{% block postamble %}+</form>+{% endblock %}diff --git a/src/hi/apps/entity/templates/entity/modals/entity_info.html b/src/hi/apps/entity/templates/entity/modals/entity_info.htmlindex 65e6b3ec..234c1885 100644--- a/src/hi/apps/entity/templates/entity/modals/entity_info.html+++ b/src/hi/apps/entity/templates/entity/modals/entity_info.html@@ -32,8 +32,6 @@{% include "entity/panes/entity_state_info_list.html" with entity_state_list=entity_state_list title='States'%}-{% include "entity/panes/entity_state_info_list.html" with entity_state_list=principal_state_list title='Principle States'%}-<div>{% include "entity/edit/panes/entity_edit.html" %}</div>diff --git a/src/hi/apps/entity/templates/entity/panes/entity_details.html b/src/hi/apps/entity/templates/entity/panes/entity_details.htmlindex 38b5ae00..0ffc4f86 100644--- a/src/hi/apps/entity/templates/entity/panes/entity_details.html+++ b/src/hi/apps/entity/templates/entity/panes/entity_details.html@@ -16,6 +16,25 @@{% include "entity/edit/panes/entity_edit.html" %}</div>+<h5>Principals</h5>+<div id="hi-edit-entity-principals">+ <ul>+ {% for principal_entity in principal_entity_list %}+ <li>{{ principal_entity.name }}</li>+ {% empty %}+ <em>No principals</em>+ {% endfor %}+ </ul>++ <div class="">+ <a href="{% url 'entity_edit_principal_manage' entity_id=entity.id %}"+ class="btn btn-success btn-control" role="button" data-async="true">+ MANAGE PRINCIPALS+ </a>+ </div>++</div>+{% if entity_position_form %}<h5>Geometry</h5><div id="{{ DIVID.ENTITY_POSITION_EDIT_PANE }}">@@ -39,15 +58,10 @@</div><h5>Delegates</h5>-<div id="hi-edit-entity-controllers">+<div id="hi-edit-entity-delegates"><div>TBD - DELEGATES</div></div>-<h5>Principals</h5>-<div id="hi-edit-entity-controllers">- <div>TBD - PRINCIPALS</div>-</div>-{% if entity.can_user_delete %}<div class=""><a href="{% url 'entity_edit_entity_delete' entity_id=entity.id %}"diff --git a/src/hi/apps/entity/transient_models.py b/src/hi/apps/entity/transient_models.pyindex 1def5d64..1a729d8a 100644--- a/src/hi/apps/entity/transient_models.py+++ b/src/hi/apps/entity/transient_models.py@@ -7,7 +7,6 @@ from hi.apps.entity.edit.forms import (EntityPositionForm,EntityAttributeUploadForm,)-from hi.apps.location.models import LocationViewfrom hi.apps.sense.models import Sensorfrom hi.apps.sense.transient_models import SensorResponse@@ -26,7 +25,6 @@ class EntityViewItem:class EntityViewGroup:""" All entities of a given type and flagged as in the view or not. """- location_view : LocationViewentity_type : EntityTypeitem_list : List[EntityViewItem] = field( default_factory = list )@@ -75,7 +73,6 @@ class EntityInfoData:entity_edit_data : EntityEditDatasensor_response_list_map : Dict[ Sensor, List[ SensorResponse ] ]entity_state_list : List[ EntityState ]- principal_state_list : List[ EntityState ]principal_entity_list : List[ Entity ]@property@@ -87,7 +84,6 @@ class EntityInfoData:'entity': self.entity,'sensor_response_list_map': self.sensor_response_list_map,'entity_state_list': self.entity_state_list,- 'principal_state_list': self.principal_state_list,'principal_entity_list': self.principal_entity_list,}context.update( self.entity_edit_data.to_template_context() )@@ -100,10 +96,12 @@ class EntityDetailsData:entity_edit_data : EntityEditDataentity_position_form : EntityPositionForm = None+ principal_entity_list : List[ Entity ] = Nonedef to_template_context(self):context = {'entity_position_form': self.entity_position_form,+ 'principal_entity_list': self.principal_entity_list,}context.update( self.entity_edit_data.to_template_context() )return contextdiff --git a/src/hi/apps/location/async_views.py b/src/hi/apps/location/async_views.pyindex 5e688bd1..605ec513 100644--- a/src/hi/apps/location/async_views.py+++ b/src/hi/apps/location/async_views.py@@ -5,9 +5,6 @@ from django.http import HttpResponseRedirectfrom django.urls import reversefrom django.views.generic import View-from hi.apps.collection.async_views import CollectionDetailsView-from hi.apps.entity.async_views import EntityDetailsView-from hi.enums import ItemTypefrom hi.hi_async_view import HiSideViewdiff --git a/src/hi/apps/location/edit/async_views.py b/src/hi/apps/location/edit/async_views.pyindex bc2e949e..8ef4ac12 100644--- a/src/hi/apps/location/edit/async_views.py+++ b/src/hi/apps/location/edit/async_views.py@@ -171,13 +171,14 @@ class LocationViewManageItemsView( HiSideView ):def get_template_context( self, request, *args, **kwargs ):location_view = LocationManager().get_default_location_view( request = request )- entity_view_group_list = EntityManager().create_entity_view_group_list(+ entity_view_group_list = EntityManager().create_location_entity_view_group_list(location_view = location_view,)- collection_view_group = CollectionManager().create_collection_view_group(+ collection_view_group = CollectionManager().create_location_collection_view_group(location_view = location_view,)return {+ 'location_view': location_view,'entity_view_group_list': entity_view_group_list,'collection_view_group': collection_view_group,}diff --git a/src/hi/apps/location/templates/location/edit/panes/location_view_edit.html b/src/hi/apps/location/templates/location/edit/panes/location_view_edit.htmlindex 6a8e188d..244a9cd6 100644--- a/src/hi/apps/location/templates/location/edit/panes/location_view_edit.html+++ b/src/hi/apps/location/templates/location/edit/panes/location_view_edit.html@@ -14,8 +14,6 @@</button></form>--<div><a href="{% url 'location_edit_location_view_delete' location_view_id=location_view.id %}"id="hi-delete-location-view-link" class="btn btn-danger btn-control" role="button"diff --git a/src/hi/apps/location/templates/location/edit/panes/location_view_manage_items.html b/src/hi/apps/location/templates/location/edit/panes/location_view_manage_items.htmlindex bab236a5..a03fe1ce 100644--- a/src/hi/apps/location/templates/location/edit/panes/location_view_manage_items.html+++ b/src/hi/apps/location/templates/location/edit/panes/location_view_manage_items.html@@ -14,9 +14,9 @@{% for entity_view_group in entity_view_group_list %}<div class="">- <div class="">{{ entity_view_group.entity_type.label }}</div>+ <div class="h5">{{ entity_view_group.entity_type.label }}</div>{% for entity_view_item in entity_view_group.item_list %}- {% include "location/edit/panes/location_view_entity_toggle.html" with location_view=entity_view_group.location_view entity=entity_view_item.entity exists_in_view=entity_view_item.exists_in_view %}+ {% include "location/edit/panes/location_view_entity_toggle.html" with location_view=location_view entity=entity_view_item.entity exists_in_view=entity_view_item.exists_in_view %}{% endfor %}</div>{% empty %}@@ -24,8 +24,8 @@{% endfor %}<div class="">- <div class="">Collections</div>+ <div class="h5">Collections</div>{% for collection_view_item in collection_view_group.item_list %}- {% include "location/edit/panes/location_view_collection_toggle.html" with location_view=collection_view_group.location_view collection=collection_view_item.collection exists_in_view=collection_view_item.exists_in_view %}+ {% include "location/edit/panes/location_view_collection_toggle.html" with location_view=location_view collection=collection_view_item.collection exists_in_view=collection_view_item.exists_in_view %}{% endfor %}</div>diff --git a/src/hi/apps/sense/sensor_history_manager.py b/src/hi/apps/sense/sensor_history_manager.pyindex 837d470d..b32cb212 100644--- a/src/hi/apps/sense/sensor_history_manager.py+++ b/src/hi/apps/sense/sensor_history_manager.py@@ -27,6 +27,7 @@ class SensorHistoryManager( Singleton ):sensor = sensor_response.sensor,value = sensor_response.value[0:255],response_datetime = sensor_response.timestamp,+ details = sensor_response.details,))continuediff --git a/src/hi/apps/sense/transient_models.py b/src/hi/apps/sense/transient_models.pyindex 65a78656..72caa18e 100644--- a/src/hi/apps/sense/transient_models.py+++ b/src/hi/apps/sense/transient_models.py@@ -13,6 +13,7 @@ class SensorResponse:value : strtimestamp : datetimesensor : Sensor = None+ details : str = Nonedef __str__(self):return json.dumps( self.to_dict() )@@ -23,6 +24,7 @@ class SensorResponse:'value': self.value,'timestamp': self.timestamp.isoformat(),'sensor_id': self.sensor.id if self.sensor else None,+ 'details': self.details,}@classmethod@@ -32,4 +34,5 @@ class 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') ),+ details = sensor_reading_dict.get('details'),)diff --git a/src/hi/integrations/zoneminder/zm_models.py b/src/hi/integrations/zoneminder/zm_models.pyindex 62269db5..a2241637 100644--- a/src/hi/integrations/zoneminder/zm_models.py+++ b/src/hi/integrations/zoneminder/zm_models.py@@ -15,7 +15,7 @@ class ZmEvent:self._cause = zm_api_event.cause()self._duration_secs = zm_api_event.duration()self._total_frame_count = zm_api_event.total_frames()- self._alarm_frame_count = zm_api_event.alarmed_frames()+ self._alarmed_frame_count = zm_api_event.alarmed_frames()self._score = zm_api_event.score()self._notes = zm_api_event.notes()self._max_score_frame_id = zm_api_event.get()['MaxScoreFrameId']@@ -58,8 +58,8 @@ class ZmEvent:return self._total_frame_count@property- def alarm_frame_count(self):- return self._alarm_frame_count+ def alarmed_frame_count(self):+ return self._alarmed_frame_count@propertydef score(self):diff --git a/src/hi/integrations/zoneminder/zm_monitor.py b/src/hi/integrations/zoneminder/zm_monitor.pyindex 4a45314f..41d9e9e6 100644--- a/src/hi/integrations/zoneminder/zm_monitor.py+++ b/src/hi/integrations/zoneminder/zm_monitor.py@@ -162,14 +162,14 @@ class ZoneMinderMonitor( PeriodicMonitor ):return self._zm_monitor_listdef _create_movement_active_sensor_response( self, zm_event : ZmEvent ):-+event_details = {- 'event_id': zm_event.id(),- 'notes': zm_event.notes(),- 'duration_secs': zm_event.duration(),- 'total_frames': zm_event.total_frames(),- 'alarmed_frames': zm_event.alarmed_frames(),- 'score': zm_event.score(),+ 'event_id': zm_event.event_id,+ 'notes': zm_event.notes,+ 'duration_secs': zm_event.duration_secs,+ 'total_frames': zm_event.total_frame_count,+ 'alarmed_frames': zm_event.alarmed_frame_count,+ 'score': zm_event.score,}return SensorResponse(