Skip to content

Home Information - Your home, your data, organized.

Python

Basic SVG icon positioning calcs in place. WIP

Anthony Cassandra988e3007726a
diff --git a/src/hi/apps/api/api_models.py b/src/hi/apps/api/api_models.py
index 323d9059..9a722526 100644
--- a/src/hi/apps/api/api_models.py
+++ b/src/hi/apps/api/api_models.py
@@ -6,74 +6,12 @@ little as possible about the server's internal models.
"""
from dataclasses import dataclass, field
+import json
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,
- }
+from hi.apps.common.svg_models import SvgPathStyle
-@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:
"""
@@ -129,17 +67,16 @@ class SvgOverlayData:
"""
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,
+ 'base_html_id': self.base_html_id,
'icon_items': [ x.to_dict() for x in self.icon_items ],
'path_items': [ x.to_dict() for x in self.path_items ],
}
+
+ def to_json(self):
+ return json.dumps( self.to_dict() )
diff --git a/src/hi/apps/api/api_translator.py b/src/hi/apps/api/api_translator.py
new file mode 100644
index 00000000..51e3b3c1
--- /dev/null
+++ b/src/hi/apps/api/api_translator.py
@@ -0,0 +1,51 @@
+from hi.apps.location.location_view_data import LocationViewData
+
+from . import api_models
+
+
+class ApiTranslator:
+
+ @classmethod
+ def toSvgOverlayData( cls, location_view_data : LocationViewData ) -> api_models.SvgOverlayData:
+
+ icon_items = list()
+ path_items = list()
+
+ for entity_position in location_view_data.entity_positions:
+ icon_item = api_models.SvgIconItem(
+ html_id = entity_position.entity.html_id,
+ icon_filename = entity_position.entity.entity_type.svg_icon_template_name,
+ svg_x = float( entity_position.svg_x ),
+ svg_y = float( entity_position.svg_y ),
+ scale = float( entity_position.svg_scale ),
+ rotation = float( entity_position.svg_rotation ),
+ )
+ icon_items.append( icon_item )
+ continue
+
+ for entity_path in location_view_data.entity_paths:
+ path_item = api_models.SvgPathItem(
+ html_id = entity_path.entity.html_id,
+ svg_path = entity_path.svg_path,
+ svg_path_style = entity_path.entity.entity_type.svg_path_style,
+ )
+ icon_items.append( path_item )
+ continue
+
+ for collection_position in location_view_data.collection_positions:
+ icon_item = api_models.SvgIconItem(
+ html_id = collection_position.collection.html_id,
+ icon_filename = collection_position.collection.collection_type.svg_icon_template_name,
+ svg_x = float( collection_position.svg_x ),
+ svg_y = float( collection_position.svg_y ),
+ scale = float( collection_position.svg_scale ),
+ rotation = float( collection_position.svg_rotation ),
+ )
+ continue
+
+ return api_models.SvgOverlayData(
+ base_html_id = location_view_data.location_view.html_id,
+ icon_items = icon_items,
+ path_items = path_items,
+ )
+
diff --git a/src/hi/apps/collection/enums.py b/src/hi/apps/collection/enums.py
index bebe0750..9b6a9e3c 100644
--- a/src/hi/apps/collection/enums.py
+++ b/src/hi/apps/collection/enums.py
@@ -1,7 +1,28 @@
from hi.apps.common.enums import LabeledEnum
+from hi.apps.common.svg_models import SvgViewBox
class CollectionType(LabeledEnum):
DEFAULT = ( 'Default', '' )
ZONE = ( 'Zone', '' )
+
+ @classmethod
+ def default(cls):
+ return cls.DEFAULT
+
+ @property
+ def svg_bounding_box(self):
+ """
+ This defines the bounding box of the SVG, which we need to properly
+ position, rotate and scale the icon.
+ """
+ # TODO: Change this after creating initial icons
+ return SvgViewBox( x = 0, y = 0, width = 32, height = 32 )
+
+ @property
+ def svg_icon_template_name(self):
+ # TODO: Change this after creating initial icons
+ #
+ # return f'templates/entity/svg/type.{self.name.lower()}.svg'
+ return 'entity/svg/type.other.svg'
diff --git a/src/hi/apps/collection/models.py b/src/hi/apps/collection/models.py
index 4cde4ec4..3d9291fe 100644
--- a/src/hi/apps/collection/models.py
+++ b/src/hi/apps/collection/models.py
@@ -1,7 +1,12 @@
from django.db import models
+from hi.apps.common.svg_models import SvgItem
from hi.apps.entity.models import Entity
-from hi.apps.location.models import Location, LocationView, SvgPositionModel
+from hi.apps.location.models import (
+ Location,
+ LocationView,
+ SvgPositionModel,
+)
from .enums import CollectionType
@@ -26,6 +31,10 @@ class Collection( models.Model ):
verbose_name = 'Collection'
verbose_name_plural = 'Collections'
+ @property
+ def html_id(self):
+ return f'hi-collection-{self.id}'
+
@property
def collection_type(self):
return CollectionType.from_name_safe( self.collection_type_str )
@@ -60,6 +69,8 @@ class CollectionEntity(models.Model):
)
class Meta:
+ verbose_name = 'Collection Entity'
+ verbose_name_plural = 'Collection Entities'
ordering = [ 'order_id' ]
indexes = [
models.Index( fields=[ 'collection', 'entity' ] ),
@@ -90,18 +101,34 @@ class CollectionPosition( SvgPositionModel ):
blank = True,
)
+ class Meta:
+ verbose_name = 'Collection Position'
+ verbose_name_plural = 'Collection Positions'
+
+ @property
+ def svg_item(self):
+ return SvgItem(
+ html_id = f'hi-collection-{self.collection.id}',
+ template_name = self.collection.collection_type.svg_icon_template_name,
+ position_x = float( self.svg_x ),
+ position_y = float( self.svg_y ),
+ bounding_box = self.collection.collection_type.svg_bounding_box,
+ rotate = float( self.svg_rotation ),
+ scale = float( self.svg_scale ),
+ )
+
class CollectionView(models.Model):
collection = models.ForeignKey(
Collection,
- related_name = 'location_views',
+ related_name = 'collection_views',
verbose_name = 'Collection',
on_delete = models.CASCADE,
)
location_view = models.ForeignKey(
LocationView,
- related_name = 'collections',
+ related_name = 'collection_views',
verbose_name = 'Location',
on_delete = models.CASCADE,
)
diff --git a/src/hi/apps/common/svg_models.py b/src/hi/apps/common/svg_models.py
new file mode 100644
index 00000000..53d7ff85
--- /dev/null
+++ b/src/hi/apps/common/svg_models.py
@@ -0,0 +1,113 @@
+from dataclasses import dataclass
+
+
+@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 SvgItem:
+ html_id : str
+ template_name : str
+ bounding_box : SvgViewBox
+ position_x : float
+ position_y : float
+ rotate : float = 0.0
+ scale : float = 1.0
+
+ @property
+ def bounds_center_x(self):
+ return self.bounding_box.x + ( self.bounding_box.width / 2.0 )
+
+ @property
+ def bounds_center_y(self):
+ return self.bounding_box.y + ( self.bounding_box.height / 2.0 )
+
+ @property
+ def translate_x(self):
+ """ Translation needed to put the item's center at the SVG position x. """
+ if self.scale < 0.000001:
+ return 0
+ return ( self.position_x / self.scale ) - self.bounds_center_x
+
+ @property
+ def translate_y(self):
+ """ Translation needed to put the item's center at the SVG posiiton y. """
+ if self.scale < 0.000001:
+ return 0
+ return ( self.position_y / self.scale ) - self.bounds_center_y
+
+ @property
+ def rotation_x(self):
+ if self.scale < 0.000001:
+ return 0
+ return ( self.position_x / self.scale )
+
+ @property
+ def rotation_y(self):
+ if self.scale < 0.000001:
+ return 0
+ return ( self.position_y / self.scale )
+
diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.py
index 20961fa9..91ec74ee 100644
--- a/src/hi/apps/entity/enums.py
+++ b/src/hi/apps/entity/enums.py
@@ -1,4 +1,5 @@
from hi.apps.common.enums import LabeledEnum
+from hi.apps.common.svg_models import SvgPathStyle, SvgViewBox
class EntityType(LabeledEnum):
@@ -64,18 +65,32 @@ class EntityType(LabeledEnum):
@classmethod
def default(cls):
return cls.OTHER
+
+ @property
+ def svg_bounding_box(self):
+ """
+ This defines the bounding box of the SVG, which we need to properly
+ position, rotate and scale the icon.
+ """
+ # TODO: Change this after creating initial icons
+ return SvgViewBox( x = 0, y = 0, width = 32, height = 32 )
@property
- def svg_icon_name(self):
+ def svg_icon_template_name(self):
# TODO: Change this after creating initial icons
#
# return f'templates/entity/svg/type.{self.name.lower()}.svg'
- return 'templates/entity/svg/type.other.svg'
+ return 'entity/svg/type.other.svg'
@property
def svg_path_style(self):
- raise NotImplementedError()
-
+ # TODO: Change this to be based on type
+ return SvgPathStyle(
+ stroke_color = '888888',
+ stroke_width = 1.0,
+ fill_color = 'none',
+ )
+
class EntityStateType(LabeledEnum):
diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.py
index 88a1b258..a234fb7d 100644
--- a/src/hi/apps/entity/models.py
+++ b/src/hi/apps/entity/models.py
@@ -1,6 +1,12 @@
from django.db import models
-from hi.apps.location.models import Location, LocationView, SvgPositionModel, SvgPathModel
+from hi.apps.common.svg_models import SvgItem
+from hi.apps.location.models import (
+ Location,
+ LocationView,
+ SvgPositionModel,
+ SvgPathModel,
+)
from hi.integrations.core.models import IntegrationIdModel
from .enums import (
@@ -52,6 +58,10 @@ class Entity( IntegrationIdModel ):
def __repr__(self):
return self.__str__()
+ @property
+ def html_id(self):
+ return f'hi-entity-{self.id}'
+
@property
def entity_type(self):
return EntityType.from_name_safe( self.entity_type_str )
@@ -172,7 +182,7 @@ class EntityState(models.Model):
)
value_range = models.TextField(
'Value Range',
- null = False, blank = False,
+ null = True, blank = True,
)
units = models.CharField(
'Units',
@@ -296,7 +306,21 @@ class EntityPosition( SvgPositionModel ):
indexes = [
models.Index( fields=[ 'location', 'entity' ] ),
]
-
+
+ @property
+ def svg_item(self):
+ return SvgItem(
+ html_id = f'hi-entity-{self.entity.id}',
+ template_name = self.entity.entity_type.svg_icon_template_name,
+ position_x = float( self.svg_x ),
+ position_y = float( self.svg_y ),
+ bounding_box = self.entity.entity_type.svg_bounding_box,
+ # rotate = float( self.svg_rotation ),
+ # scale = float( self.svg_scale ),
+ rotate = 5,
+ scale = 4.0,
+ )
+
class EntityPath( SvgPathModel ):
"""
@@ -339,13 +363,13 @@ class EntityView(models.Model):
entity = models.ForeignKey(
Entity,
- related_name = 'location_views',
+ related_name = 'entity_views',
verbose_name = 'Entity',
on_delete = models.CASCADE,
)
location_view = models.ForeignKey(
LocationView,
- related_name = 'entities',
+ related_name = 'entity_views',
verbose_name = 'Location',
on_delete = models.CASCADE,
)
diff --git a/src/hi/apps/entity/templates/entity/svg/type.other.svg b/src/hi/apps/entity/templates/entity/svg/type.other.svg
index 5c158a8e..2d33bf80 100644
--- a/src/hi/apps/entity/templates/entity/svg/type.other.svg
+++ b/src/hi/apps/entity/templates/entity/svg/type.other.svg
@@ -1,3 +1,5 @@
-<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>
+<rect id="{{ svg_item.html_id }}"
+ hi-state="default"
+ fill="blue"
+ x="0" y="0" width="32" height="32"
+ transform="scale( {{ svg_item.scale }} ) translate( {{ svg_item.translate_x }} {{ svg_item.translate_y }} ) rotate( {{ svg_item.rotate }} {{ svg_item.bounds_center_x }} {{ svg_item.bounds_center_y }} )"/>
diff --git a/src/hi/apps/location/location_view_data.py b/src/hi/apps/location/location_view_data.py
index 810ef9c4..2fb39480 100644
--- a/src/hi/apps/location/location_view_data.py
+++ b/src/hi/apps/location/location_view_data.py
@@ -1,5 +1,5 @@
from dataclasses import dataclass
-from typing import List
+from typing import List, Set
from hi.apps.collection.models import Collection, CollectionPosition
from hi.apps.entity.models import Entity, EntityPosition, EntityPath
@@ -18,4 +18,4 @@ class LocationViewData:
entity_paths : List[ EntityPath ]
collection_positions : List[ CollectionPosition ]
unpositioned_collections : List[ Collection ]
- orphan_entities : List[ Entity ]
+ orphan_entities : Set[ Entity ]
diff --git a/src/hi/apps/location/location_view_manager.py b/src/hi/apps/location/location_view_manager.py
index 3f385672..0f3c2010 100644
--- a/src/hi/apps/location/location_view_manager.py
+++ b/src/hi/apps/location/location_view_manager.py
@@ -12,33 +12,33 @@ class LocationViewManager(Singleton):
def get_location_view_data( self, location_view : LocationView ):
location = location_view.location
- entity_positions = set()
- entity_paths = set()
+ entity_positions = list()
+ entity_paths = list()
non_displayed_entities = set()
- for entity in location_view.entities.all():
+ for entity_view in location_view.entity_views.all():
+ entity = entity_view.entity
is_visible = False
entity_position = entity.positions.filter( location = location ).first()
if entity_position:
is_visible = True
- entity_positions.add( entity_position )
+ entity_positions.append( entity_position )
entity_path = entity.paths.filter( location = location ).first()
if entity_path:
is_visible = True
- entity_paths.add( entity_path )
+ entity_paths.append( 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_positions = list()
+ unpositioned_collections = list()
+ for collection_view in location_view.collection_views.all():
+ collection = collection_view.collection
collection_position = collection.positions.filter( location = location ).first()
if collection_position:
- collection_positions.add( collection )
+ collection_positions.append( collection )
else:
- unpositioned_collections.add( collection )
- all_collections.add( collection )
+ unpositioned_collections.append( collection )
continue
# These are used for reporting entities that might otherwise be
@@ -52,8 +52,7 @@ class LocationViewManager(Singleton):
continue
# These become bottom buttons, which can be ordered
- collection_list = list( unpositioned_collections )
- collection_list.sort( key = lambda item : item.order_id )
+ unpositioned_collections.sort( key = lambda item : item.order_id )
return LocationViewData(
location_view = location_view,
diff --git a/src/hi/apps/location/models.py b/src/hi/apps/location/models.py
index f2a501a1..34169130 100644
--- a/src/hi/apps/location/models.py
+++ b/src/hi/apps/location/models.py
@@ -1,6 +1,6 @@
from django.db import models
-from hi.apps.api.api_models import SvgViewBox
+from hi.apps.common.svg_models import SvgViewBox
from .enums import ViewType
diff --git a/src/hi/apps/location/templates/location/location_view.html b/src/hi/apps/location/templates/location/location_view.html
index 3d783782..b27581d8 100644
--- a/src/hi/apps/location/templates/location/location_view.html
+++ b/src/hi/apps/location/templates/location/location_view.html
@@ -1,10 +1,19 @@
{% load common_template_helpers %}
<div class="hi-location-view">
- {% 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 %}
+ <svg id="{{ location_view_data.location_view.html_id }}" xmlns="http://www.w3.org/2000/svg"
+ viewBox="{{ location_view_data.location_view.svg_view_box }}"
+ transform="rotate({{ location_view_data.location_view.svg_rotation }} 0 0)">
+ {% include_media_template location_view_data.location_view.location.svg_filename %}
+
+ {% for entity_path in location_view_data.entity_paths %}
+ {% endfor %}
+
+ {% for entity_position in location_view_data.entity_positions %}
+ {% include entity_position.svg_item.template_name with svg_item=entity_position.svg_item %}
+ {% endfor %}
+
+ {% for collection_position in location_view_data.collection_positions %}
+ {% endfor %}
+
+ </svg>
</div>
diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.py
index f469bcd3..b8919430 100644
--- a/src/hi/apps/location/views.py
+++ b/src/hi/apps/location/views.py
@@ -4,6 +4,8 @@ from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views.generic import View
+from hi.apps.api.api_translator import ApiTranslator
+from hi.apps.common.utils import is_ajax
from hi.hi_grid_view import HiGridView
from .location_view_manager import LocationViewManager
@@ -59,8 +61,13 @@ class LocationViewView( HiGridView ):
location_view_data = LocationViewManager().get_location_view_data(
location_view = location_view,
)
+ svgOverlayData = ApiTranslator.toSvgOverlayData(
+ location_view_data = location_view_data,
+ )
context = {
+ 'is_async_request': is_ajax( request ),
'location_view_data': location_view_data,
+ 'svgOverlayData': svgOverlayData,
}
return self.hi_grid_response(
request = request,
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index 229d275c..a0c8164c 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -277,6 +277,8 @@ PIPELINE = {
},
'js_after_content_custom': {
'source_filenames': (
+ 'js/svg-utils.js',
+ 'js/polling.js',
'js/main.js',
),
'output_filename': 'js/js_after_content_custom.js',
diff --git a/src/hi/static/js/main.js b/src/hi/static/js/main.js
index e69de29b..cb7e5e8c 100644
--- a/src/hi/static/js/main.js
+++ b/src/hi/static/js/main.js
@@ -0,0 +1,4 @@
+(function() {
+ window.Hi = window.Hi || {};
+
+})();
diff --git a/src/hi/static/js/polling.js b/src/hi/static/js/polling.js
new file mode 100644
index 00000000..1166df1e
--- /dev/null
+++ b/src/hi/static/js/polling.js
@@ -0,0 +1,11 @@
+(function() {
+ window.Hi = window.Hi || {};
+
+ const HiPolling = {
+ pollStates: function() {
+ return true;
+ }
+ };
+
+ window.Hi.polling = HiPolling;
+})();
diff --git a/src/hi/static/js/svg-utils.js b/src/hi/static/js/svg-utils.js
new file mode 100644
index 00000000..654c67e7
--- /dev/null
+++ b/src/hi/static/js/svg-utils.js
@@ -0,0 +1,35 @@
+(function() {
+ window.Hi = window.Hi || {};
+
+ const HiSvgUtils = {
+ overlayData: function( svgOverlayData ) {
+
+ const baseSvgData = getBaseSvgData( svgOverlayData.base_html_id );
+
+ }
+ };
+
+ window.Hi.svgUtils = HiSvgUtils;
+
+ function getBaseSvgData( htmlId ) {
+
+ const $baseSvg = $('#' + htmlId + ' svg' );
+
+ const bbox = $baseSvg[0].getBoundingClientRect();
+
+ const viewBox = $baseSvg.attr('viewBox').split(' ').map(Number);
+ const viewBoxWidth = viewBox[2];
+ const viewBoxHeight = viewBox[3];
+
+ const scaleX = bbox.width / viewBoxWidth;
+ const scaleY = bbox.height / viewBoxHeight;
+
+ return {
+ htmlBoundingBox : bbox,
+ svgViewBox : { x: viewBox[0], y: viewBox[1], width: viewBox[2], height: viewBox[3] },
+ scaleX : scaleX,
+ scaleY : scaleY
+ };
+ }
+
+})();