Skip to content

Home Information - Your home, your data, organized.

Python

Added delegate and principal models and in default views.

Anthony Cassandra6478b2149f17
diff --git a/src/hi/apps/edit/templates/edit/panes/side.html b/src/hi/apps/edit/templates/edit/panes/side.html
index 3b8f39f0..04263842 100644
--- a/src/hi/apps/edit/templates/edit/panes/side.html
+++ b/src/hi/apps/edit/templates/edit/panes/side.html
@@ -24,7 +24,7 @@
<div id="hi-edit-item">
{% if entity %}
- {% include "edit/panes/details_entity.html" %}
+ {% include "edit/panes/entity_details.html" %}
{% elif collection %}
{% include "edit/panes/details_collection.html" %}
{% else %}
diff --git a/src/hi/apps/edit/views.py b/src/hi/apps/edit/views.py
index 339141f1..ae9f06f9 100644
--- a/src/hi/apps/edit/views.py
+++ b/src/hi/apps/edit/views.py
@@ -14,8 +14,7 @@ import hi.apps.common.antinode as antinode
import hi.apps.collection.edit.views as collection_edit_views
from hi.apps.collection.helpers import CollectionHelpers
import hi.apps.entity.edit.views as entity_edit_views
-from hi.apps.entity.edit.helpers import EntityEditHelpers
-from hi.apps.entity.helpers import EntityHelpers
+from hi.apps.entity.entity_manager import EntityManager
import hi.apps.location.edit.views as location_edit_views
from hi.apps.location.forms import SvgPositionForm
from hi.decorators import edit_required
@@ -152,7 +151,7 @@ class EditSvgPositionView( View, EditViewMixin ):
location_view = request.view_parameters.location_view
if item_type == 'entity':
- svg_position_model = EntityHelpers.get_entity_position(
+ svg_position_model = EntityManager().get_entity_position(
entity_id = item_id,
location = location_view.location,
)
@@ -205,7 +204,7 @@ class EditSvgPathView( View, EditViewMixin ):
location_view = request.view_parameters.location_view
if item_type == 'entity':
- EntityEditHelpers.set_entity_path(
+ EntityManager().set_entity_path(
entity_id = item_id,
location = location_view.location,
svg_path_str = svg_path_str,
diff --git a/src/hi/apps/entity/admin.py b/src/hi/apps/entity/admin.py
index 03d27499..6fdd617d 100644
--- a/src/hi/apps/entity/admin.py
+++ b/src/hi/apps/entity/admin.py
@@ -27,8 +27,8 @@ class PathInLine(admin.TabularInline):
show_change_link = True
-class ProxyStateInLine(admin.TabularInline):
- model = models.ProxyState
+class EntityStateDelegationInLine(admin.TabularInline):
+ model = models.EntityStateDelegation
extra = 0
show_change_link = True
@@ -60,21 +60,21 @@ class EntityAdmin(admin.ModelAdmin):
EntityViewInLine,
PositionInLine,
PathInLine,
- ProxyStateInLine,
+ EntityStateDelegationInLine,
]
[email protected](models.ProxyState)
-class ProxyStateAdmin(admin.ModelAdmin):
[email protected](models.EntityStateDelegation)
+class EntityStateDelegationAdmin(admin.ModelAdmin):
show_full_result_count = False
list_display = (
'entity_state',
- 'entity',
+ 'delegate_entity',
'created_datetime',
)
search_fields = ['entity__name']
- readonly_fields = ( 'entity_state', 'entity', )
+ readonly_fields = ( 'entity_state', 'delegate_entity', )
diff --git a/src/hi/apps/entity/delegation_manager.py b/src/hi/apps/entity/delegation_manager.py
new file mode 100644
index 00000000..d8b1b947
--- /dev/null
+++ b/src/hi/apps/entity/delegation_manager.py
@@ -0,0 +1,136 @@
+from typing import List
+
+from hi.apps.common.singleton import Singleton
+from hi.integrations.core.enums import IntegrationType
+from hi.apps.location.models import LocationView
+
+from . import enums
+from . import models
+
+
+class DelegationManager(Singleton):
+
+ CREATE_BY_DEFAULT_MAP = {
+ # Defines which EntityStateType should have a delegate entity by
+ # default and the type of entity to create. Delegations are mainly for
+ # visual/view use, so usually only get created when an entity is
+ # added to a location view for the first time.
+
+ enums.EntityStateType.MOVEMENT: enums.EntityType.AREA,
+ enums.EntityStateType.PRESENCE: enums.EntityType.AREA,
+ enums.EntityStateType.SOUND_LEVEL: enums.EntityType.AREA,
+ enums.EntityStateType.VIDEO_STREAM: enums.EntityType.AREA,
+ }
+
+ def __init_singleton__(self):
+ return
+
+ def get_delegate_entities( self, entity : models.Entity ) -> List[ models.Entity ]:
+ delegate_entity_list = list()
+ for entity_state in entity.states.all():
+ for entity_state_delegation in entity_state.entity_state_delegations.all():
+ delegate_entity_list.append( entity_state_delegation.delegate_entity )
+ continue
+ continue
+ return delegate_entity_list
+
+ def get_principal_entities( self, entity : models.Entity ) -> List[ models.Entity ]:
+ principal_entity_list = list()
+ for entity_state_delegation in entity.entity_state_delegations.all():
+ principal_entity_list.append( entity_state_delegation.entity_state.entity )
+ continue
+ return principal_entity_list
+
+ def get_delegate_entities_with_defaults( self, entity : models.Entity ) -> List[ models.Entity ]:
+
+ # We only want to create one entity of each entity type. Multiple
+ # states of the entity may need delegates, so we collate the states
+ # by entity types.
+ #
+ entity_type_to_state_list_map = dict()
+
+ # If the entity already has delegates of a given entity type,
+ # then we will want to use those instead of creating new ones of
+ # the same entity type.
+ #
+ entity_type_to_delegate_entity_list_map = dict()
+
+ # Used to make sure we do not create a delegation if it already exists.
+ entity_state_to_delegate_entity_map = dict()
+
+ for entity_state in entity.states.all():
+
+ for entity_state_delegation in entity_state.entity_state_delegations.all():
+ entity_state_to_delegate_entity_map[entity_state] = entity_state_delegation.delegate_entity
+
+ delegate_entity = entity_state_delegation.delegate_entity
+ entity_type = delegate_entity.entity_type
+ if entity_type not in entity_type_to_delegate_entity_list_map:
+ entity_type_to_delegate_entity_list_map[entity_type] = list()
+ entity_type_to_delegate_entity_list_map[entity_type].append( delegate_entity )
+ continue
+
+ if entity_state.entity_state_type not in self.CREATE_BY_DEFAULT_MAP:
+ continue
+ entity_type = self.CREATE_BY_DEFAULT_MAP[entity_state.entity_state_type]
+ if entity_type not in entity_type_to_state_list_map:
+ entity_type_to_state_list_map[entity_type] = list()
+ entity_type_to_state_list_map[entity_type].append( entity_state )
+ continue
+
+ delegate_entity_list = list( entity_state_to_delegate_entity_map.values() )
+
+ for entity_type, entity_state_list in entity_type_to_state_list_map.items():
+
+ entity_states_needing_delegates = set()
+ for entity_state in entity_state_list:
+ if entity_state in entity_state_to_delegate_entity_map:
+ continue
+ entity_states_needing_delegates.add( entity_state )
+ continue
+
+ if not entity_states_needing_delegates:
+ continue
+
+ if entity_type in entity_type_to_delegate_entity_list_map:
+ delegate_entity = entity_type_to_delegate_entity_list_map[entity_type][0] # Choose first
+ else:
+ delegate_entity = models.Entity.objects.create(
+ name = f'{entity.name} - {entity_type.label}',
+ entity_type = entity_type,
+ integration_type_str = str(IntegrationType.NONE),
+ integration_key = None,
+ )
+ delegate_entity_list.append( delegate_entity )
+
+ for entity_state in entity_states_needing_delegates:
+ _ = models.EntityStateDelegation.objects.create(
+ entity_state = entity_state,
+ delegate_entity = delegate_entity,
+ )
+ continue
+ continue
+
+ return delegate_entity_list
+
+ def remove_delegate_entities_from_view_if_needed( self,
+ entity : models.Entity,
+ location_view : LocationView ):
+ # We only remove the entity's delegates if the entity is its only principal.
+
+ delegate_entities = set( self.get_delegate_entities( entity ))
+ for delegate_entity in delegate_entities:
+ principal_entities = set( self.get_principal_entities( entity = delegate_entity ))
+ if (( len(principal_entities) == 1 )
+ and ( next(iter(principal_entities)) == entity )):
+ try:
+ entity_view = models.EntityView.objects.get(
+ entity = delegate_entity,
+ location_view = location_view,
+ )
+ entity_view.delete()
+ except models.EntityView.DoesNotExist:
+ pass
+ continue
+
+ return
diff --git a/src/hi/apps/entity/edit/helpers.py b/src/hi/apps/entity/edit/helpers.py
deleted file mode 100644
index ec678338..00000000
--- a/src/hi/apps/entity/edit/helpers.py
+++ /dev/null
@@ -1,47 +0,0 @@
-from django.http import HttpRequest
-
-from hi.apps.entity.enums import EntityType
-from hi.apps.entity.models import Entity, EntityPath
-from hi.integrations.core.enums import IntegrationType
-from hi.apps.location.models import Location
-
-
-class EntityEditHelpers:
-
- @classmethod
- def create_entity( cls,
- request : HttpRequest,
- entity_type : EntityType,
- name : str ) -> Entity:
- return Entity.objects.create(
- name = name,
- entity_type_str = str(entity_type),
- integration_type_str = str(IntegrationType.NONE),
- integration_key = None,
- )
-
- @classmethod
- def set_entity_path( cls,
- entity_id : int,
- location : Location,
- svg_path_str : str ) -> EntityPath:
-
- try:
- entity_path = EntityPath.objects.get(
- location = location,
- entity_id = entity_id,
- )
- entity_path.svg_path = svg_path_str
- entity_path.save()
- return entity_path
-
- except EntityPath.DoesNotExist:
- pass
-
- entity = Entity.objects.get( id = entity_id )
- return EntityPath.objects.create(
- entity = entity,
- location = location,
- svg_path = svg_path_str,
- )
-
diff --git a/src/hi/apps/entity/edit/views.py b/src/hi/apps/entity/edit/views.py
index 5580fb60..e338b6e4 100644
--- a/src/hi/apps/entity/edit/views.py
+++ b/src/hi/apps/entity/edit/views.py
@@ -7,6 +7,7 @@ from django.utils.decorators import method_decorator
from django.views.generic import View
import hi.apps.common.antinode as antinode
+from hi.apps.entity.entity_manager import EntityManager
from hi.apps.entity.enums import EntityType
from hi.apps.entity.models import Entity, EntityPosition
from hi.apps.location.forms import SvgPositionForm
@@ -16,7 +17,6 @@ from hi.decorators import edit_required
from hi.views import bad_request_response, page_not_found_response
from . import forms
-from .helpers import EntityEditHelpers
logger = logging.getLogger(__name__)
@@ -87,8 +87,7 @@ class EntityAddView( View ):
name = cleaned_data.get('name')
try:
- _ = EntityEditHelpers.create_entity(
- request = request,
+ _ = EntityManager().create_entity(
entity_type = entity_type,
name = name,
)
diff --git a/src/hi/apps/entity/entity_manager.py b/src/hi/apps/entity/entity_manager.py
new file mode 100644
index 00000000..f34b4f34
--- /dev/null
+++ b/src/hi/apps/entity/entity_manager.py
@@ -0,0 +1,196 @@
+from decimal import Decimal
+
+from django.db import transaction
+
+from hi.apps.common.singleton import Singleton
+from hi.integrations.core.enums import IntegrationType
+from hi.apps.location.models import Location, LocationView
+
+from .enums import (
+ EntityType,
+)
+from .models import (
+ Entity,
+ EntityPath,
+ EntityPosition,
+ EntityView,
+)
+
+
+class EntityManager(Singleton):
+
+ PATH_EDIT_NEW_PATH_RADIUS_PERCENT = 5.0 # Preferrable if this matches Javascript new path sizing.
+
+ def __init_singleton__(self):
+ return
+
+ def create_entity( self,
+ entity_type : EntityType,
+ name : str,
+ integration_type : IntegrationType = IntegrationType.NONE,
+ integration_key : str = None) -> Entity:
+ return Entity.objects.create(
+ name = name,
+ entity_type_str = str(entity_type),
+ integration_type_str = str(integration_type),
+ integration_key = integration_key,
+ )
+
+ def set_entity_path( self,
+ entity_id : int,
+ location : Location,
+ svg_path_str : str ) -> EntityPath:
+
+ try:
+ entity_path = EntityPath.objects.get(
+ location = location,
+ entity_id = entity_id,
+ )
+ entity_path.svg_path = svg_path_str
+ entity_path.save()
+ return entity_path
+
+ except EntityPath.DoesNotExist:
+ pass
+
+ entity = Entity.objects.get( id = entity_id )
+ return EntityPath.objects.create(
+ entity = entity,
+ location = location,
+ svg_path = svg_path_str,
+ )
+
+ def get_entity_position( self,
+ entity_id : int,
+ location : Location ) -> EntityPosition:
+ try:
+ entity = Entity.objects.get( id = entity_id )
+ except Entity.DoesNotExist:
+ return None
+
+ entity_position = EntityPosition.objects.filter(
+ entity = entity,
+ location = location,
+ ).first()
+ if entity_position:
+ return entity_position
+ return EntityPosition(
+ entity = entity,
+ location = location,
+ )
+
+ def create_entity_view( self, entity : Entity, location_view : LocationView ):
+
+ with transaction.atomic():
+
+ # Need to make sure it has some visible representation in the view if none exists.
+ if entity.entity_type.is_path:
+ self.add_entity_path_if_needed(
+ entity = entity,
+ location_view = location_view,
+ )
+ else:
+ self.add_entity_position_if_needed(
+ entity = entity,
+ location_view = location_view,
+ )
+
+ try:
+ entity_view = EntityView.objects.get(
+ entity = entity,
+ location_view = location_view,
+ )
+ except EntityView.DoesNotExist:
+ entity_view = EntityView.objects.create(
+ entity = entity,
+ location_view = location_view,
+ )
+
+ return entity_view
+
+ def remove_entity_view( self, entity : Entity, location_view : LocationView ):
+
+ with transaction.atomic():
+ entity_view = EntityView.objects.get(
+ entity = entity,
+ location_view = location_view,
+ )
+ entity_view.delete()
+
+ return
+
+ def add_entity_position_if_needed( self, entity : Entity, location_view : LocationView ) -> EntityPosition:
+ assert not entity.entity_type.is_path
+
+ try:
+ _ = EntityPosition.objects.get(
+ location = location_view.location,
+ entity = entity,
+ )
+ return
+ except EntityPosition.DoesNotExist:
+ pass
+
+ # Default display in middle of current view
+ svg_x = location_view.svg_view_box.x + ( location_view.svg_view_box.width / 2.0 )
+ svg_y = location_view.svg_view_box.y + ( location_view.svg_view_box.height / 2.0 )
+
+ entity_position = EntityPosition.objects.create(
+ entity = entity,
+ location = location_view.location,
+ svg_x = Decimal( svg_x ),
+ svg_y = Decimal( svg_y ),
+ svg_scale = Decimal( 1.0 ),
+ svg_rotate = Decimal( 0.0 ),
+ )
+ return entity_position
+
+ def add_entity_path_if_needed( self, entity : Entity, location_view : LocationView ) -> EntityPath:
+ assert entity.entity_type.is_path
+
+ try:
+ _ = EntityPath.objects.get(
+ location = location_view.location,
+ entity = entity,
+ )
+ return
+ except EntityPath.DoesNotExist:
+ pass
+
+ # Note that this server-side creation of a new path is just one
+ # place new paths can be created. During client-side path editing,
+ # the Javascript code also uses logic to add new path segments.
+ # These do not have to behave identical, but it is preferrable for
+ # there to be some consistency.
+
+ # Default display a line or rectangle in middle of current view with radius X% of viewbox
+ center_x = location_view.svg_view_box.x + ( location_view.svg_view_box.width / 2.0 )
+ center_y = location_view.svg_view_box.y + ( location_view.svg_view_box.height / 2.0 )
+ radius_x = location_view.svg_view_box.width * ( self.PATH_EDIT_NEW_PATH_RADIUS_PERCENT / 100.0 )
+ radius_y = location_view.svg_view_box.height * ( self.PATH_EDIT_NEW_PATH_RADIUS_PERCENT / 100.0 )
+
+ if entity.entity_type.is_path_closed:
+ top_left_x = center_x - radius_x
+ top_left_y = center_y - radius_y
+ top_right_x = center_x + radius_x
+ top_right_y = center_y - radius_y
+ bottom_right_x = center_x + radius_x
+ bottom_right_y = center_y + radius_y
+ bottom_left_x = center_x - radius_x
+ bottom_left_y = center_y + radius_y
+ svg_path = f'M {top_left_x},{top_left_y} L {top_right_x},{top_right_y} L {bottom_right_x},{bottom_right_y} L {bottom_left_x},{bottom_left_y} Z'
+ else:
+ start_x = center_x - radius_x
+ start_y = center_y
+ end_x = start_x + radius_x
+ end_y = start_y
+ svg_path = f'M {start_x},{start_y} L {end_x},{end_y}'
+
+ entity_path = EntityPath.objects.create(
+ entity = entity,
+ location = location_view.location,
+ svg_path = svg_path,
+ )
+ return entity_path
+
+
diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.py
index 727c36ca..1e1fe890 100644
--- a/src/hi/apps/entity/enums.py
+++ b/src/hi/apps/entity/enums.py
@@ -18,10 +18,14 @@ class EntityType(LabeledEnum):
self.is_path = is_path
self.is_path_closed = is_path_closed
return
+
+ @property
+ def is_icon(self):
+ return bool( not self.is_path )
AIR_CONDITIONER = ( 'Air Conditioner', '' ) # Controls area
APPLIANCE = ( 'Appliance', '' )
- AREA = ( 'Area', '' )
+ AREA = ( 'Area', '', True, True )
AUDIO_AMPLIFIER = ( 'Audio Amplifier', '' ) # Controls Speaker
AUDIO_PLAYER = ( 'Audio Player', '' )
BAROMETER = ( 'Barometer', '' )
@@ -72,7 +76,6 @@ class EntityType(LabeledEnum):
WATER_SHUTOFF_VALVE = ( 'Water Shutoff Valve', '' )
WEATHER_STATION = ( 'Weather Station', '' )
WINDOW = ( 'Window', '' )
- ZONE = ( 'Zone', '', True, True )
@classmethod
def default(cls):
@@ -121,10 +124,8 @@ class EntityStateType(LabeledEnum):
def __init__( self,
label : str,
- description : str,
- use_default_zone : bool = False ):
+ description : str ):
super().__init__( label, description )
- self.use_default_zone = use_default_zone
return
# General types
@@ -146,15 +147,15 @@ class EntityStateType(LabeledEnum):
ELECTRIC_USAGE = ( 'Electric Usage' , '' )
HIGH_LOW = ( 'High/Low' , '' )
HUMIDITY = ( 'Humidity' , '' )
- LIGHT_LEVEL = ( 'Light Level' , '', True )
+ LIGHT_LEVEL = ( 'Light Level' , '' )
MOISTURE = ( 'Moisture' , '' )
- MOVEMENT = ( 'Movement' , '', True )
+ MOVEMENT = ( 'Movement' , '' )
ON_OFF = ( 'On/Off' , '' )
OPEN_CLOSE = ( 'Open/Close' , '' )
- PRESENCE = ( 'Presence' , '', True )
- SOUND_LEVEL = ( 'Sound Level' , '', True )
- TEMPERATURE = ( 'Temperature' , '', True )
- VIDEO_STREAM = ( 'Video Stream' , '', True )
+ PRESENCE = ( 'Presence' , '' )
+ SOUND_LEVEL = ( 'Sound Level' , '' )
+ TEMPERATURE = ( 'Temperature' , '' )
+ VIDEO_STREAM = ( 'Video Stream' , '' )
WATER_FLOW = ( 'Water Flow' , '' )
WIND_SPEED = ( 'Wind Speed' , '' )
diff --git a/src/hi/apps/entity/helpers.py b/src/hi/apps/entity/helpers.py
deleted file mode 100644
index 531a133b..00000000
--- a/src/hi/apps/entity/helpers.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from hi.apps.location.models import Location
-
-from .models import Entity, EntityPosition
-
-
-class EntityHelpers:
-
- @classmethod
- def get_entity_position( cls,
- entity_id : int,
- location : Location ) -> EntityPosition:
- try:
- entity = Entity.objects.get( id = entity_id )
- except Entity.DoesNotExist:
- return None
-
- entity_position = EntityPosition.objects.filter(
- entity = entity,
- location = location,
- ).first()
- if entity_position:
- return entity_position
- return EntityPosition(
- entity = entity,
- location = location,
- )
diff --git a/src/hi/apps/entity/migrations/0009_entitystateproxy_delete_proxystate.py b/src/hi/apps/entity/migrations/0009_entitystateproxy_delete_proxystate.py
new file mode 100644
index 00000000..ea20a168
--- /dev/null
+++ b/src/hi/apps/entity/migrations/0009_entitystateproxy_delete_proxystate.py
@@ -0,0 +1,53 @@
+# Generated by Django 4.2.15 on 2024-10-07 15:38
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("entity", "0008_entityview_entity_view_entity_location_view"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="EntityStateProxy",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "created_datetime",
+ models.DateTimeField(auto_now_add=True, verbose_name="Created"),
+ ),
+ (
+ "entity",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="entity_state_proxies",
+ to="entity.entity",
+ verbose_name="Entity",
+ ),
+ ),
+ (
+ "entity_state",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="entity_state_proxies",
+ to="entity.entitystate",
+ verbose_name="Entity State",
+ ),
+ ),
+ ],
+ ),
+ migrations.DeleteModel(
+ name="ProxyState",
+ ),
+ ]
diff --git a/src/hi/apps/entity/migrations/0010_entitystatedelegation_delete_entitystateproxy.py b/src/hi/apps/entity/migrations/0010_entitystatedelegation_delete_entitystateproxy.py
new file mode 100644
index 00000000..02a55a17
--- /dev/null
+++ b/src/hi/apps/entity/migrations/0010_entitystatedelegation_delete_entitystateproxy.py
@@ -0,0 +1,53 @@
+# Generated by Django 4.2.15 on 2024-10-07 18:32
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("entity", "0009_entitystateproxy_delete_proxystate"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="EntityStateDelegation",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "created_datetime",
+ models.DateTimeField(auto_now_add=True, verbose_name="Created"),
+ ),
+ (
+ "delegate_entity",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="entity_state_delegations",
+ to="entity.entity",
+ verbose_name="Deleage Entity",
+ ),
+ ),
+ (
+ "entity_state",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="entity_state_delegations",
+ to="entity.entitystate",
+ verbose_name="Entity State",
+ ),
+ ),
+ ],
+ ),
+ migrations.DeleteModel(
+ name="EntityStateProxy",
+ ),
+ ]
diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.py
index 6e81612d..1b6ceaba 100644
--- a/src/hi/apps/entity/models.py
+++ b/src/hi/apps/entity/models.py
@@ -214,54 +214,62 @@ class EntityState(models.Model):
return
-class ProxyState(models.Model):
- """An EntityState associated with a Sensors or Controller is
- implicitly a "sensing" or "controlling" the internals of the
- entity/device. However, this may really just be a proxy for another entity's
- (hidden) state.
-
- e.g., An open/close sensor is directly sensing the proximity sensor in
- the device, but it is indirectly trying to sense the state of a door or window.
+class EntityStateDelegation(models.Model):
+ """An EntityState associated with a Sensor or Controller is often serving
+ representing the state of some other entity. In those cases, the entity
+ containing the sensors/controllers is really just a proxy for some
+ other entity's (hidden) state. If we want to explicitly represent that
+ relationship between two entities, we can define a delegation where some
+ other entity becomes the "delegate" and the original entity containing the
+ sensor/controller being the "principal".
+
+ e.g., An open/close switch entity with an open/close sensor is
+ directly sensing the state of the switch in the device, but it is
+ indirectly trying to sense the state of a door or window. Thus, the
+ door open/close "state" is being proxied by the open/close sensor's
+ swith. The open/close swith device is the principal entity while
+ the door/window is the delegate entity.
e.g., A sprinkler controller valve is directly sensing and controlling
whether it is on or off, but also serves as a proxy for all the
sprinkler heads connected to it.
e.g., A temperature sensor's internal temperature states is really just
- a proxy for an area (and area is also an Entity).
+ a proxy for a area (and a Area is also an Entity).
e.g., A motion detectors's internal "movement" state about reflected
- infrared signals is just a proxy for movement associated with an area.
+ infrared signals is just a proxy for movement associated with a Area.
- This relationship between an EntityState and proxy for another Entity
- can either be one-to-many or many-to-one.
+ This delegation relationship between an Entities can either be
+ one-to-many or many-to-one.
e.g., A thermostat may be aggregating the readings from multiple
remote sensors so that the internal temperature state of the
thermostat is a proxy for all the remote sensor states.
- The purpose of representing the proxy relationships is to allow
+ The purpose of representing the delegation relationships is to allow
visually changing the display of an Entity based on the sensors
- that are serving as a proxy for it. It also allows clicks/taps on the
+ that are serving as a proxy for it. It also allows clicks/taps on the delegate
entity to be associated with the sensors or controllers that are proxying
for it.
- e.g., A common case is for defining "AREA" entities and visually
+ e.g., A common case is for defining "Area" entities and visually
displaying them so that they can change colors based on movement
sensors that proxy for the area and showing the video stream for
the camera entity proxying for the area.
+
"""
entity_state = models.ForeignKey(
EntityState,
- related_name = 'proxy_for_entities',
+ related_name = 'entity_state_delegations',
verbose_name = 'Entity State',
on_delete=models.CASCADE,
)
- entity = models.ForeignKey(
+ delegate_entity = models.ForeignKey(
Entity,
- related_name = 'proxy_by_states',
- verbose_name = 'Entity',
+ related_name = 'entity_state_delegations',
+ verbose_name = 'Deleage Entity',
on_delete = models.CASCADE,
)
created_datetime = models.DateTimeField(
@@ -269,6 +277,16 @@ class ProxyState(models.Model):
auto_now_add = True,
)
+ class Meta:
+ verbose_name = 'Entity State Delegation'
+ verbose_name_plural = 'Entity State Delegations'
+ constraints = [
+ models.UniqueConstraint(
+ fields = [ 'delegate_entity', 'entity_state' ],
+ name = 'entity_state_delegation_uniqueness',
+ ),
+ ]
+
class EntityPosition( SvgPositionModel ):
"""
diff --git a/src/hi/apps/entity/templates/entity/edit/panes/entity_details.html b/src/hi/apps/entity/templates/entity/edit/panes/entity_details.html
index 2d996c21..2bfe38a0 100644
--- a/src/hi/apps/entity/templates/entity/edit/panes/entity_details.html
+++ b/src/hi/apps/entity/templates/entity/edit/panes/entity_details.html
@@ -28,3 +28,13 @@
<div id="hi-edit-entity-controllers">
{% include "edit/panes/entity_controllers.html" %}
</div>
+
+<h5>Delegates</h5>
+<div id="hi-edit-entity-controllers">
+ <div>TBD - DELEGATES</div>
+</div>
+
+<h5>Principals</h5>
+<div id="hi-edit-entity-controllers">
+ <div>TBD - PRINCIPALS</div>
+</div>
diff --git a/src/hi/apps/location/edit/helpers.py b/src/hi/apps/location/edit/helpers.py
index 43018ef6..7671fb1e 100644
--- a/src/hi/apps/location/edit/helpers.py
+++ b/src/hi/apps/location/edit/helpers.py
@@ -9,11 +9,11 @@ from hi.apps.collection.models import (
CollectionView,
CollectionPosition,
)
+from hi.apps.entity.delegation_manager import DelegationManager
+from hi.apps.entity.entity_manager import EntityManager
from hi.apps.entity.models import (
Entity,
EntityView,
- EntityPosition,
- EntityPath,
)
from hi.apps.location.enums import LocationViewType
from hi.apps.location.models import Location, LocationView
@@ -28,8 +28,6 @@ from .transient_models import (
class LocationEditHelpers:
- PATH_EDIT_NEW_PATH_RADIUS_PERCENT = 5.0 # Preferrable if this matches Javascript new path sizing.
-
@classmethod
def create_location_view( cls,
request : HttpRequest,
@@ -121,107 +119,55 @@ class LocationEditHelpers:
def toggle_entity_in_view( cls, entity : Entity, location_view : LocationView ) -> bool:
try:
- entity_view = EntityView.objects.get(
- entity = entity,
- location_view = location_view,
- )
- entity_view.delete()
+ cls.remove_entity_from_view( entity = entity, location_view = location_view )
return False
-
except EntityView.DoesNotExist:
cls.add_entity_to_view( entity = entity, location_view = location_view )
return True
@classmethod
- def add_entity_to_view( cls, entity : Entity, location_view : LocationView ):
-
- with transaction.atomic():
- # Need to make sure it has some visible representation in the view if none exists.
- if entity.entity_type.is_path:
- cls.add_entity_path_if_needed(
- entity = entity,
- location_view = location_view,
- )
- else:
- cls.add_entity_position_if_needed(
- entity = entity,
- location_view = location_view,
- )
+ def remove_entity_from_view( cls, entity : Entity, location_view : LocationView ):
- _ = EntityView.objects.create(
+ with transaction.atomic():
+ EntityManager().remove_entity_view(
entity = entity,
location_view = location_view,
)
- return
-
- @classmethod
- def add_entity_position_if_needed( cls, entity : Entity, location_view : LocationView ) -> EntityPosition:
- assert not entity.entity_type.is_path
- try:
- _ = EntityPosition.objects.get(
- location = location_view.location,
+ DelegationManager().remove_delegate_entities_from_view_if_needed(
entity = entity,
+ location_view = location_view,
)
- return
- except EntityPosition.DoesNotExist:
- pass
-
- # Default display in middle of current view
- svg_x = location_view.svg_view_box.x + ( location_view.svg_view_box.width / 2.0 )
- svg_y = location_view.svg_view_box.y + ( location_view.svg_view_box.height / 2.0 )
-
- entity_position = EntityPosition.objects.create(
- entity = entity,
- location = location_view.location,
- svg_x = Decimal( svg_x ),
- svg_y = Decimal( svg_y ),
- svg_scale = Decimal( 1.0 ),
- svg_rotate = Decimal( 0.0 ),
- )
- return entity_position
+
+ return
@classmethod
- def add_entity_path_if_needed( cls, entity : Entity, location_view : LocationView ) -> EntityPath:
- assert entity.entity_type.is_path
+ def add_entity_to_view( cls, entity : Entity, location_view : LocationView ):
- try:
- _ = EntityPath.objects.get(
- location = location_view.location,
+ with transaction.atomic():
+ # Only create delegate entities the first time an entity is added to a view.
+ if not entity.entity_views.all().exists():
+ delegate_entity_list = DelegationManager().get_delegate_entities_with_defaults(
+ entity = entity,
+ )
+ else:
+ delegate_entity_list = DelegationManager().get_delegate_entities(
+ entity = entity,
+ )
+
+ _ = EntityManager().create_entity_view(
entity = entity,
+ location_view = location_view,
)
- return
- except EntityPath.DoesNotExist:
- pass
-
- # Default display a line in middle of current view with radius 10% of viewbox width
- center_x = location_view.svg_view_box.x + ( location_view.svg_view_box.width / 2.0 )
- center_y = location_view.svg_view_box.y + ( location_view.svg_view_box.height / 2.0 )
- radius = location_view.svg_view_box.width * ( cls.PATH_EDIT_NEW_PATH_RADIUS_PERCENT / 100.0 )
-
- if entity.entity_type.is_path_closed:
- top_left_x = center_x - radius
- top_left_y = center_y - radius
- top_right_x = center_x + radius
- top_right_y = center_y - radius
- bottom_right_x = center_x + radius
- bottom_right_y = center_y + radius
- bottom_left_x = center_x - radius
- bottom_left_y = center_y + radius
- svg_path = f'M {top_left_x},{top_left_y} L {top_right_x},{top_right_y} L {bottom_right_x},{bottom_right_y} L {bottom_left_x},{bottom_left_y} Z'
- else:
- start_x = center_x - radius
- start_y = center_y
- end_x = start_x + radius
- end_y = start_y
- svg_path = f'M {start_x},{start_y} L {end_x},{end_y}'
-
- entity_path = EntityPath.objects.create(
- entity = entity,
- location = location_view.location,
- svg_path = svg_path,
- )
- return entity_path
+
+ for delegate_entity in delegate_entity_list:
+ _ = EntityManager().create_entity_view(
+ entity = delegate_entity,
+ location_view = location_view,
+ )
+ continue
+
+ return
@classmethod
def toggle_collection_in_view( cls,
diff --git a/src/hi/static/js/edit-svg-icon.js b/src/hi/static/js/edit-svg-icon.js
index b78b5bb0..91cfaba6 100644
--- a/src/hi/static/js/edit-svg-icon.js
+++ b/src/hi/static/js/edit-svg-icon.js
@@ -19,6 +19,14 @@
window.Hi.edit.icon = HiEditSvgIcon;
HiEditSvgIcon.init();
+
+ /*
+ SVG ICON EDITING
+
+ - Icons can be selected to show the entity details in the side edit panel.
+ - Icons can be dragged to chnage their location.
+ - Selected icons can be rotated and scaled to change their appearance.
+ */
const SELECTABLE_CLASS = 'selectable';
const SELECTABLE_SELECTOR = '.' + SELECTABLE_CLASS;
diff --git a/src/hi/static/js/edit-svg-path.js b/src/hi/static/js/edit-svg-path.js
index 1c9d581d..d12a3698 100644
--- a/src/hi/static/js/edit-svg-path.js
+++ b/src/hi/static/js/edit-svg-path.js
@@ -23,15 +23,21 @@
/*
SVG PATH EDITING
+ - When a path is selected, the original SVG element/group is hidden and proxy elements created.
+ - Proxy elements are points and lines with points being way to move path endpoint location.
+ - During editing, control proxy popionts can be moved, added and deleted.
- Two types of paths: closed (with ending 'Z') and open.
- - The type is determined by the initial path and not editable.
+ - The type is determined by the initial path and not changeable during editing.
- An open path must have at least two proxy points (control points for manipulation).
- A closed path must have at least 3 proxy points.
- The behavior of adding to the path depends on its type.
- - An open path gets extended when adding.
- - A closed path has its lines subdivided when adding.
- Adding is relative to the last selected item.
- - You can select a line or a proxy point.
+ - You can select a line or a proxy point during editing.
+ - An open path gets extended when adding (can also subdivide a line if it is selected).
+ - A closed path has its lines subdivided when adding.
+ - A entity's path can consist of multiple, disconnected segments.
+ - Add a new proxy path adds a line or a rectangle for open and closed paths respectively.
+ - A selected path aso shows the entity details in the side edit panel.
*/
const PROXY_PATH_CONTAINER_ID = 'hi-proxy-path-container';