Skip to content

Home Information - Your home, your data, organized.

Python

Added first API models. Prep for beginning first SVG overlay logic.

Anthony Cassandrab02cd07e0a3d
diff --git a/src/hi/apps/api/__init__.py b/src/hi/apps/api/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/api/api_models.py b/src/hi/apps/api/api_models.py
new file mode 100644
index 00000000..323d9059
--- /dev/null
+++ b/src/hi/apps/api/api_models.py
@@ -0,0 +1,145 @@
+"""
+The models that define the interface and model translations between the
+client and server. This is meant to decouple the client and server data
+model spaces. We want the client to be a simple as possible and know as
+little as possible about the server's internal models.
+"""
+
+from dataclasses import dataclass, field
+from typing import List
+
+
+@dataclass
+class SvgViewBox:
+ x : float
+ y : float
+ width : float
+ height : float
+
+ def __post_init__(self):
+ self._max_x = self.x + self.width
+ self._max_y = self.y + self.height
+ return
+
+ def __str__(self):
+ return f'{self.x} {self.y} {self.width} {self.height}'
+
+ @property
+ def min_x(self):
+ return self.x
+
+ @property
+ def min_y(self):
+ return self.y
+
+ @property
+ def max_x(self):
+ return self._max_x
+
+ @property
+ def max_y(self):
+ return self._max_y
+
+ @staticmethod
+ def from_attribute_value( value : str ):
+ components = value.split(' ')
+ if len(components) != 4:
+ raise ValueError( f'Invalid viewBox value "{value}".' )
+ return SvgViewBox(
+ x = float(components[0]),
+ y = float(components[1]),
+ width = float(components[2]),
+ height = float(components[3]),
+ )
+
+ def to_dict(self):
+ return {
+ 'x': self.x,
+ 'y': self.y,
+ 'width': self.width,
+ 'height': self.height,
+ }
+
+
+@dataclass
+class SvgPathStyle:
+ stroke_color : str
+ stroke_width : float
+ fill_color : str
+
+ def to_dict(self):
+ return {
+ 'stroke_color': self.stroke_color,
+ 'stroke_width': self.stroke_width,
+ 'fill_color': self.fill_color,
+ }
+
+@dataclass
+class SvgIconItem:
+ """
+ A item that is positoned over a base SVG relative to the base SVG
+ viewBox. Styling is defined by CSS classes in the
+ icon_filename. Each itemm will have a "state" HTML attribute that can
+ be used to change the appearance of the icon based on state changes and
+ sensoir values. However, those are changes dynamically by the client
+ polling for status, so the svg file itself will contain the default
+ state value (how it appears when the state is unknown). This structure
+ is only used for the initial population of the SVG display when the
+ server is first providing the view..
+ """
+ html_id : str
+ icon_filename : str
+ svg_x : float
+ svg_y : float
+ scale : float
+ rotation : float
+
+ def to_dict(self):
+ return {
+ 'html_id': self.html_id,
+ 'icon_filename': self.icon_filename,
+ 'svg_x': self.svg_x,
+ 'svg_y': self.svg_y,
+ 'scale': self.scale,
+ 'rotation': self.rotation,
+ }
+
+
+@dataclass
+class SvgPathItem:
+ html_id : str
+ svg_path : str # The value/content of the 'd' attribute
+ svg_path_style : SvgPathStyle
+
+ def to_dict(self):
+ return {
+ 'html_id': self.html_id,
+ 'svg_path': self.svg_path,
+ 'svg_path_style': self.svg_path_style.to_dict(),
+ }
+
+
+@dataclass
+class SvgOverlayData:
+ """
+ All the data the client (Javascript) needs to display items over a a
+ base SVG. The positioning is relative to the current view box and
+ display area which only the Javascript can know since the dislpay area
+ is defined dynamically to be responsive.
+ """
+
+ base_html_id : str
+ view_box : SvgViewBox
+ rotation : float
+ icon_items : List[ SvgIconItem ] = field( default_factory = list )
+ path_items : List[ SvgPathItem ] = field( default_factory = list )
+
+ def to_dict(self):
+ return {
+ 'html_id': self.html_id,
+ 'view_box': self.view_box.to_dict(),
+ 'rotation': self.rotation,
+ 'icon_items': [ x.to_dict() for x in self.icon_items ],
+ 'path_items': [ x.to_dict() for x in self.path_items ],
+ }
+
diff --git a/src/hi/apps/api/apps.py b/src/hi/apps/api/apps.py
new file mode 100644
index 00000000..1e654d6a
--- /dev/null
+++ b/src/hi/apps/api/apps.py
@@ -0,0 +1,6 @@
+from django.apps import AppConfig
+
+
+class ApiConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "hi.apps.api"
diff --git a/src/hi/apps/api/migrations/__init__.py b/src/hi/apps/api/migrations/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/api/urls.py b/src/hi/apps/api/urls.py
new file mode 100644
index 00000000..0156c5f1
--- /dev/null
+++ b/src/hi/apps/api/urls.py
@@ -0,0 +1,9 @@
+from django.urls import re_path
+
+from . import views
+
+
+urlpatterns = [
+
+
+]
diff --git a/src/hi/apps/api/views.py b/src/hi/apps/api/views.py
new file mode 100644
index 00000000..c7a3481c
--- /dev/null
+++ b/src/hi/apps/api/views.py
@@ -0,0 +1,6 @@
+import logging
+
+from django.views.generic import View
+
+logger = logging.getLogger(__name__)
+
diff --git a/src/hi/apps/collection/migrations/0003_collectionview_order_id_and_more.py b/src/hi/apps/collection/migrations/0003_collectionview_order_id_and_more.py
new file mode 100644
index 00000000..5d8d2ac9
--- /dev/null
+++ b/src/hi/apps/collection/migrations/0003_collectionview_order_id_and_more.py
@@ -0,0 +1,40 @@
+# Generated by Django 4.2.15 on 2024-08-28 14:02
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("entity", "0005_entitypath_updated_datetime_and_more"),
+ ("collection", "0002_remove_collection_svg_path_collectionview_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="collectionview",
+ name="order_id",
+ field=models.PositiveIntegerField(default=0, verbose_name="Order Id"),
+ ),
+ migrations.AlterField(
+ model_name="collectionentity",
+ name="collection",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="entities",
+ to="collection.collection",
+ verbose_name="Collection",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="collectionentity",
+ name="entity",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="collections",
+ to="entity.entity",
+ verbose_name="Entity",
+ ),
+ ),
+ ]
diff --git a/src/hi/apps/collection/models.py b/src/hi/apps/collection/models.py
index 025da175..4cde4ec4 100644
--- a/src/hi/apps/collection/models.py
+++ b/src/hi/apps/collection/models.py
@@ -40,11 +40,13 @@ class CollectionEntity(models.Model):
collection = models.ForeignKey(
Collection,
+ related_name = 'entities',
verbose_name = 'Collection',
on_delete=models.CASCADE,
)
entity = models.ForeignKey(
Entity,
+ related_name = 'collections',
verbose_name = 'Entity',
on_delete=models.CASCADE,
)
@@ -103,6 +105,10 @@ class CollectionView(models.Model):
verbose_name = 'Location',
on_delete = models.CASCADE,
)
+ order_id = models.PositiveIntegerField(
+ 'Order Id',
+ default = 0,
+ )
created_datetime = models.DateTimeField(
'Created',
auto_now_add = True,
diff --git a/src/hi/apps/common/templatetags/common_template_helpers.py b/src/hi/apps/common/templatetags/common_template_helpers.py
index 53e4dd09..eb6ea8b4 100644
--- a/src/hi/apps/common/templatetags/common_template_helpers.py
+++ b/src/hi/apps/common/templatetags/common_template_helpers.py
@@ -69,8 +69,11 @@ def include_media_template( context, file_path ):
Load a file from MEDIA_ROOT, treat it as a Django template,
and render it with the current context.
"""
- full_path = os.path.join( settings.MEDIA_ROOT, file_path )
+ if not file_path:
+ return 'Template file path not defined.'
+ full_path = os.path.join( settings.MEDIA_ROOT, file_path )
+
if not os.path.exists(full_path):
return f'Template file not found: {full_path}'
diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.py
index 9f440c6b..20961fa9 100644
--- a/src/hi/apps/entity/enums.py
+++ b/src/hi/apps/entity/enums.py
@@ -6,7 +6,7 @@ class EntityType(LabeledEnum):
- This helps define the default visual appearance.
- No assumptions are made about what sensors or controllers are associated with a given EntityType.
- SVG file is needed for each of these, else will use a default.
- - SVG filename is by convention: templates/entity/svg/type.{name.lower()}.svg
+ - SVG filename is by convention:
"""
AIR_CONDITIONER = ( 'Air Conditioner', '' ) # Controls area
@@ -60,10 +60,17 @@ class EntityType(LabeledEnum):
WATER_METER = ( 'Water Meter', '' )
WATER_SHUTOFF_VALVE = ( 'Water Shutoff Valve', '' )
WEATHER_STATION = ( 'Weather Station', '' )
+
+ @classmethod
+ def default(cls):
+ return cls.OTHER
@property
def svg_icon_name(self):
- raise NotImplementedError()
+ # TODO: Change this after creating initial icons
+ #
+ # return f'templates/entity/svg/type.{self.name.lower()}.svg'
+ return 'templates/entity/svg/type.other.svg'
@property
def svg_path_style(self):
diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.py
index cf4b0243..88a1b258 100644
--- a/src/hi/apps/entity/models.py
+++ b/src/hi/apps/entity/models.py
@@ -1,6 +1,6 @@
from django.db import models
-from hi.apps.location.models import Location, LocationView
+from hi.apps.location.models import Location, LocationView, SvgPositionModel, SvgPathModel
from hi.integrations.core.models import IntegrationIdModel
from .enums import (
@@ -260,7 +260,7 @@ class ProxyState(models.Model):
)
-class EntityPosition(models.Model):
+class EntityPosition( SvgPositionModel ):
"""
- For entities represented by an SVG icon.
- This is the most common case.
@@ -280,28 +280,6 @@ class EntityPosition(models.Model):
verbose_name = 'Entity',
on_delete = models.CASCADE,
)
- svg_x = models.DecimalField(
- 'X',
- max_digits = 12,
- decimal_places = 6,
- )
- svg_y = models.DecimalField(
- 'Y',
- max_digits = 12,
- decimal_places = 6,
- )
- svg_scale = models.DecimalField(
- 'Scale',
- max_digits = 12,
- decimal_places = 6,
- default = 1.0,
- )
- svg_rotation = models.DecimalField(
- 'Rotation',
- max_digits = 12,
- decimal_places = 6,
- default = 0.0,
- )
created_datetime = models.DateTimeField(
'Created',
auto_now_add = True,
@@ -320,7 +298,7 @@ class EntityPosition(models.Model):
]
-class EntityPath(models.Model):
+class EntityPath( SvgPathModel ):
"""
- For entities represented by an arbitary SVG path. e.g., The path of a utility line,
- The styling of the path is determined by the EntityType.
@@ -339,10 +317,6 @@ class EntityPath(models.Model):
verbose_name = 'Entity',
on_delete = models.CASCADE,
)
- svg_path = models.TextField(
- 'Path',
- null = False, blank = False,
- )
created_datetime = models.DateTimeField(
'Created',
auto_now_add = True,
diff --git a/src/hi/apps/entity/templates/entity/svg/type.other.svg b/src/hi/apps/entity/templates/entity/svg/type.other.svg
new file mode 100644
index 00000000..5c158a8e
--- /dev/null
+++ b/src/hi/apps/entity/templates/entity/svg/type.other.svg
@@ -0,0 +1,3 @@
+<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">
+ <rect x="0" y="0" width="32" height="32" fill="blue" />
+</svg>
diff --git a/src/hi/apps/location/admin.py b/src/hi/apps/location/admin.py
index 8705fda1..03cada63 100644
--- a/src/hi/apps/location/admin.py
+++ b/src/hi/apps/location/admin.py
@@ -16,7 +16,7 @@ class LocationAdmin(admin.ModelAdmin):
list_display = (
'name',
'svg_filename',
- 'svg_viewbox',
+ 'svg_view_box_str',
'latitude',
'longitude',
'elevation_feet',
@@ -38,7 +38,7 @@ class LocationViewAdmin(admin.ModelAdmin):
list_display = (
'name',
'location',
- 'svg_viewbox',
+ 'svg_view_box_str',
'svg_rotation',
'order_id',
'created_datetime',
diff --git a/src/hi/apps/location/location_view_data.py b/src/hi/apps/location/location_view_data.py
new file mode 100644
index 00000000..810ef9c4
--- /dev/null
+++ b/src/hi/apps/location/location_view_data.py
@@ -0,0 +1,21 @@
+from dataclasses import dataclass
+from typing import List
+
+from hi.apps.collection.models import Collection, CollectionPosition
+from hi.apps.entity.models import Entity, EntityPosition, EntityPath
+
+from .models import LocationView
+
+
+@dataclass
+class LocationViewData:
+ """
+ Encapsulates all the data needed to render overlaying a Location's SVG
+ for a given LocationView.
+ """
+ location_view : LocationView
+ entity_positions : List[ EntityPosition ]
+ entity_paths : List[ EntityPath ]
+ collection_positions : List[ CollectionPosition ]
+ unpositioned_collections : List[ Collection ]
+ orphan_entities : List[ Entity ]
diff --git a/src/hi/apps/location/location_view_manager.py b/src/hi/apps/location/location_view_manager.py
new file mode 100644
index 00000000..3f385672
--- /dev/null
+++ b/src/hi/apps/location/location_view_manager.py
@@ -0,0 +1,65 @@
+from hi.apps.common.singleton import Singleton
+
+from .location_view_data import LocationViewData
+from .models import LocationView
+
+
+class LocationViewManager(Singleton):
+
+ def __init_singleton__(self):
+ return
+
+ def get_location_view_data( self, location_view : LocationView ):
+
+ location = location_view.location
+ entity_positions = set()
+ entity_paths = set()
+ non_displayed_entities = set()
+ for entity in location_view.entities.all():
+ is_visible = False
+ entity_position = entity.positions.filter( location = location ).first()
+ if entity_position:
+ is_visible = True
+ entity_positions.add( entity_position )
+ entity_path = entity.paths.filter( location = location ).first()
+ if entity_path:
+ is_visible = True
+ entity_paths.add( entity_path )
+ if not is_visible:
+ non_displayed_entities.add( entity )
+ continue
+
+ all_collections = set()
+ collection_positions = set()
+ unpositioned_collections = set()
+ for collection in location_view.collections.all():
+ collection_position = collection.positions.filter( location = location ).first()
+ if collection_position:
+ collection_positions.add( collection )
+ else:
+ unpositioned_collections.add( collection )
+ all_collections.add( collection )
+ continue
+
+ # These are used for reporting entities that might otherwise be
+ # invisible to the user. (not displayed on SVG and nor part of any
+ # viewable collection).
+ #
+ orphan_entities = set()
+ for entity in non_displayed_entities:
+ if not entity.collections.exists():
+ orphan_entities.add( entity )
+ continue
+
+ # These become bottom buttons, which can be ordered
+ collection_list = list( unpositioned_collections )
+ collection_list.sort( key = lambda item : item.order_id )
+
+ return LocationViewData(
+ location_view = location_view,
+ entity_positions = entity_positions,
+ entity_paths = entity_paths,
+ collection_positions = collection_positions,
+ unpositioned_collections = unpositioned_collections,
+ orphan_entities = orphan_entities,
+ )
diff --git a/src/hi/apps/location/migrations/0004_rename_svg_viewbox_location_svg_view_box_str_and_more.py b/src/hi/apps/location/migrations/0004_rename_svg_viewbox_location_svg_view_box_str_and_more.py
new file mode 100644
index 00000000..7804bc0b
--- /dev/null
+++ b/src/hi/apps/location/migrations/0004_rename_svg_viewbox_location_svg_view_box_str_and_more.py
@@ -0,0 +1,26 @@
+# Generated by Django 4.2.15 on 2024-08-29 01:21
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ (
+ "location",
+ "0003_locationview_view_type_str_alter_location_order_id_and_more",
+ ),
+ ]
+
+ operations = [
+ migrations.RenameField(
+ model_name="location",
+ old_name="svg_viewbox",
+ new_name="svg_view_box_str",
+ ),
+ migrations.RenameField(
+ model_name="locationview",
+ old_name="svg_viewbox",
+ new_name="svg_view_box_str",
+ ),
+ ]
diff --git a/src/hi/apps/location/models.py b/src/hi/apps/location/models.py
index 651f852e..f2a501a1 100644
--- a/src/hi/apps/location/models.py
+++ b/src/hi/apps/location/models.py
@@ -1,5 +1,7 @@
from django.db import models
+from hi.apps.api.api_models import SvgViewBox
+
from .enums import ViewType
@@ -15,12 +17,11 @@ class Location(models.Model):
max_length = 256,
null = False, blank = False,
)
- svg_viewbox = models.CharField(
+ svg_view_box_str = models.CharField(
'Viewbox',
max_length = 64,
null = False, blank = False,
)
-
latitude = models.DecimalField(
'Latitude',
max_digits = 11,
@@ -59,6 +60,15 @@ class Location(models.Model):
def __repr__(self):
return self.__str__()
+
+ @property
+ def svg_view_box(self):
+ return SvgViewBox.from_attribute_value( self.svg_view_box_str )
+
+ @svg_view_box.setter
+ def svg_view_box( self, svg_view_box : SvgViewBox ):
+ self.svg_view_box_str = str(svg_view_box)
+ return
class LocationView(models.Model):
@@ -80,12 +90,11 @@ class LocationView(models.Model):
max_length = 64,
null = False, blank = False,
)
- svg_viewbox = models.CharField(
+ svg_view_box_str = models.CharField(
'Viewbox',
max_length = 64,
null = False, blank = False,
)
-
svg_rotation = models.DecimalField(
'Rotation',
max_digits = 9,
@@ -114,6 +123,10 @@ class LocationView(models.Model):
def __repr__(self):
return self.__str__()
+
+ @property
+ def html_id(self):
+ return f'hi-location-view-{self.id}'
@property
def view_type(self):
@@ -123,6 +136,15 @@ class LocationView(models.Model):
def view_type( self, view_type : ViewType ):
self.view_type_str = str(view_type)
return
+
+ @property
+ def svg_view_box(self):
+ return SvgViewBox.from_attribute_value( self.svg_view_box_str )
+
+ @svg_view_box.setter
+ def svg_view_box( self, svg_view_box : SvgViewBox ):
+ self.svg_view_box_str = str(svg_view_box)
+ return
class SvgPositionModel(models.Model):
diff --git a/src/hi/apps/location/templates/location/location_view.html b/src/hi/apps/location/templates/location/location_view.html
index 53fad3d5..3d783782 100644
--- a/src/hi/apps/location/templates/location/location_view.html
+++ b/src/hi/apps/location/templates/location/location_view.html
@@ -1,8 +1,10 @@
{% load common_template_helpers %}
<div class="hi-location-view">
- {% with current_location_view.svg_viewbox as svg_viewbox %}
- {% with current_location_view.svg_rotation as svg_rotation %}
- {% include_media_template current_location_view.location.svg_filename %}
+ {% with location_view_data.location_view.svg_view_box as svg_view_box %}
+ {% with location_view_data.location_view.svg_rotation as svg_rotation %}
+ {% with location_view_data.location_view.html_id as html_id %}
+ {% include_media_template location_view_data.location_view.location.svg_filename %}
+ {% endwith %}
{% endwith %}
{% endwith %}
</div>
diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.py
index 88ec8c31..f469bcd3 100644
--- a/src/hi/apps/location/views.py
+++ b/src/hi/apps/location/views.py
@@ -6,6 +6,7 @@ from django.views.generic import View
from hi.hi_grid_view import HiGridView
+from .location_view_manager import LocationViewManager
from .models import Location, LocationView
logger = logging.getLogger(__name__)
@@ -45,18 +46,21 @@ class LocationViewView( HiGridView ):
location_view_id = kwargs.get('id')
try:
- current_location_view = LocationView.objects.select_related(
+ location_view = LocationView.objects.select_related(
'location' ).get( id = location_view_id )
except LocationView.DoesNotExist:
logger.warning( f'Location view "{location_view_id}" does not exist.' )
raise NotImplementedError('Handling bad location view not yet implemengted')
# Remember last view chosen
- request.view_parameters.location_view_id = current_location_view.id
+ request.view_parameters.location_view_id = location_view.id
request.view_parameters.to_session( request )
-
+
+ location_view_data = LocationViewManager().get_location_view_data(
+ location_view = location_view,
+ )
context = {
- 'current_location_view': current_location_view,
+ 'location_view_data': location_view_data,
}
return self.hi_grid_response(
request = request,
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index ab0b1ffd..229d275c 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -143,6 +143,7 @@ INSTALLED_APPS = [
'hi.apps.sense',
'hi.apps.control',
'hi.apps.edit',
+ 'hi.apps.api',
'hi.integrations.core',
'hi.integrations.zoneminder',
'hi.integrations.hass',
diff --git a/src/hi/urls.py b/src/hi/urls.py
index 6b58eb2f..a797803c 100644
--- a/src/hi/urls.py
+++ b/src/hi/urls.py
@@ -26,6 +26,7 @@ urlpatterns = [
re_path( r'^$', views.HomeView.as_view(), name='home' ),
re_path( r'^index.html$', views.HomeView.as_view(), name='home_index' ),
+ re_path( r'^api/', include('hi.apps.api.urls' )),
re_path( r'^config/', include('hi.apps.config.urls' )),
re_path( r'^edit/', include('hi.apps.edit.urls' )),
re_path( r'^integration/', include('hi.integrations.core.urls' )),