Home Information - Your home, your data, organized.
Python
Generalized Entity Attribute model and added to Location.
Anthony Cassandra5ba7200c71bf
diff --git a/src/hi/apps/attribute/__init__.py b/src/hi/apps/attribute/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/attribute/apps.py b/src/hi/apps/attribute/apps.pynew file mode 100644index 00000000..7ed28283--- /dev/null+++ b/src/hi/apps/attribute/apps.py@@ -0,0 +1,6 @@+from django.apps import AppConfig+++class AttributeConfig(AppConfig):+ default_auto_field = "django.db.models.BigAutoField"+ name = "hi.apps.attribute"diff --git a/src/hi/apps/attribute/enums.py b/src/hi/apps/attribute/enums.pynew file mode 100644index 00000000..bb5beaa9--- /dev/null+++ b/src/hi/apps/attribute/enums.py@@ -0,0 +1,20 @@+from hi.apps.common.enums import LabeledEnum+++class AttributeType(LabeledEnum):++ PREDEFINED = ('Predefined', '' )+ CUSTOM = ('Custom', '' )+++class AttributeValueType(LabeledEnum):++ STRING = ('String', '' )+ INTEGER = ('Integer', '' )+ FLOAT = ('Float', '' )+ TEXT = ('Text', '' ) # relative filename in MEDIA_ROOT+ PDF = ('PDF', '' ) # relative filename in MEDIA_ROOT+ IMAGE = ('Image', '' ) # relative filename in MEDIA_ROOT+ VIDEO = ('Video', '' ) # relative filename in MEDIA_ROOT+ AUDIO = ('Audio', '' ) # relative filename in MEDIA_ROOT+ LINK = ('Link', '' )diff --git a/src/hi/apps/attribute/migrations/__init__.py b/src/hi/apps/attribute/migrations/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/apps/attribute/models.py b/src/hi/apps/attribute/models.pynew file mode 100644index 00000000..3ac6c08c--- /dev/null+++ b/src/hi/apps/attribute/models.py@@ -0,0 +1,72 @@+from django.db import models++from .enums import (+ AttributeValueType,+ AttributeType,+)+++class AttributeModel(models.Model):++ class Meta:+ abstract = True++ attribute_value_type_str = models.CharField(+ 'Attribute Value Type',+ max_length = 32,+ null = False, blank = False,+ )+ name = models.CharField(+ 'Name',+ max_length = 64,+ )+ value = models.TextField(+ 'Value',+ )+ attribute_type_str = models.CharField(+ 'Attribute Type',+ max_length = 32,+ null = False, blank = False,+ )+ is_editable = models.BooleanField(+ 'Editable?',+ default = True,+ )+ is_required = models.BooleanField(+ 'Required?',+ default = False,+ )+ created_datetime = models.DateTimeField(+ 'Created',+ auto_now_add = True,+ )+ updated_datetime = models.DateTimeField(+ 'Updated',+ auto_now=True,+ blank = True,+ )++ def __str__(self):+ return f'Attr[{self}] {self.name}={self.value} [{self.attribute_value_type_str}] [{self.attribute_type_str}]'++ def __repr__(self):+ return self.__str__()++ @property+ def attribute_value_type(self):+ return AttributeValueType.from_name_safe( self.attribute_value_type_str )++ @attribute_value_type.setter+ def attribute_value_type( self, attribute_value_type : AttributeValueType ):+ self.attribute_value_type_str = str(attribute_value_type)+ return++ @property+ def attribute_type(self):+ return AttributeType.from_name_safe( self.attribute_type_str )++ @attribute_type.setter+ def attribute_type( self, attribute_type : AttributeType ):+ self.attribute_type_str = str(attribute_type)+ return+diff --git a/src/hi/apps/entity/admin.py b/src/hi/apps/entity/admin.pyindex 6fdd617d..54093222 100644--- a/src/hi/apps/entity/admin.py+++ b/src/hi/apps/entity/admin.py@@ -3,13 +3,13 @@ from django.contrib import adminfrom . import models-class AttributesInLine(admin.TabularInline):- model = models.Attribute+class EntityAttributeInLine(admin.TabularInline):+ model = models.EntityAttributeextra = 0show_change_link = True-class StatesInLine(admin.TabularInline):+class StateInLine(admin.TabularInline):model = models.EntityStateextra = 0show_change_link = True@@ -55,8 +55,8 @@ class EntityAdmin(admin.ModelAdmin):search_fields = ['name']inlines = [- AttributesInLine,- StatesInLine,+ EntityAttributeInLine,+ StateInLine,EntityViewInLine,PositionInLine,PathInLine,diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.pyindex 6bd70269..8ad64b8a 100644--- a/src/hi/apps/entity/enums.py+++ b/src/hi/apps/entity/enums.py@@ -109,25 +109,6 @@ class EntityStateType(LabeledEnum):WIND_SPEED = ( 'Wind Speed' , '' )-class AttributeType(LabeledEnum):-- PREDEFINED = ('Predefined', '' )- CUSTOM = ('Custom', '' )---class AttributeValueType(LabeledEnum):-- STRING = ('String', '' )- INTEGER = ('Integer', '' )- FLOAT = ('Float', '' )- TEXT = ('Text', '' ) # relative filename in MEDIA_ROOT- PDF = ('PDF', '' ) # relative filename in MEDIA_ROOT- IMAGE = ('Image', '' ) # relative filename in MEDIA_ROOT- VIDEO = ('Video', '' ) # relative filename in MEDIA_ROOT- AUDIO = ('Audio', '' ) # relative filename in MEDIA_ROOT- LINK = ('Link', '' )--class AttributeName(LabeledEnum):# Common attribute namesdiff --git a/src/hi/apps/entity/migrations/0012_rename_attribute_entityattribute_and_more.py b/src/hi/apps/entity/migrations/0012_rename_attribute_entityattribute_and_more.pynew file mode 100644index 00000000..ec47d45e--- /dev/null+++ b/src/hi/apps/entity/migrations/0012_rename_attribute_entityattribute_and_more.py@@ -0,0 +1,22 @@+# Generated by Django 4.2.15 on 2024-10-11 19:54++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("entity", "0011_alter_entitystatedelegation_options_and_more"),+ ]++ operations = [+ migrations.RenameModel(+ old_name="Attribute",+ new_name="EntityAttribute",+ ),+ migrations.RenameIndex(+ model_name="entityattribute",+ new_name="entity_enti_name_ca029b_idx",+ old_name="entity_attr_name_820790_idx",+ ),+ ]diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.pyindex b0fd631b..8e0ab058 100644--- a/src/hi/apps/entity/models.py+++ b/src/hi/apps/entity/models.py@@ -7,14 +7,13 @@ from hi.apps.location.models import (LocationItemPathModel,LocationView,)+from hi.apps.attribute.models import AttributeModelfrom hi.integrations.core.models import IntegrationIdModelfrom hi.enums import ItemTypefrom .enums import (EntityType,EntityStateType,- AttributeValueType,- AttributeType,)@@ -84,7 +83,7 @@ class Entity( IntegrationIdModel, LocationItemModelMixin ):return attribute_map-class Attribute(models.Model):+class EntityAttribute( AttributeModel ):"""- Information related to an entity, e.g., specs, docs, notes, configs- The 'attribute type' is used to help define what information the user might need to provide.@@ -96,40 +95,6 @@ class Attribute(models.Model):verbose_name = 'Entity',on_delete = models.CASCADE,)- attribute_value_type_str = models.CharField(- 'Attribute Value Type',- max_length = 32,- null = False, blank = False,- )- name = models.CharField(- 'Name',- max_length = 64,- )- value = models.TextField(- 'Value',- )- attribute_type_str = models.CharField(- 'Attribute Type',- max_length = 32,- null = False, blank = False,- )- is_editable = models.BooleanField(- 'Editable?',- default = True,- )- is_required = models.BooleanField(- 'Required?',- default = False,- )- created_datetime = models.DateTimeField(- 'Created',- auto_now_add = True,- )- updated_datetime = models.DateTimeField(- 'Updated',- auto_now=True,- blank = True,- )class Meta:verbose_name = 'Attribute'@@ -137,33 +102,9 @@ class Attribute(models.Model):indexes = [models.Index( fields=[ 'name', 'value' ] ),]-- def __str__(self):- return f'Attr: {self.name}={self.value} [{self.attribute_value_type_str}] [{self.attribute_type_str}]'-- def __repr__(self):- return self.__str__()-- @property- def attribute_value_type(self):- return AttributeValueType.from_name_safe( self.attribute_value_type_str )-- @attribute_value_type.setter- def attribute_value_type( self, attribute_value_type : AttributeValueType ):- self.attribute_value_type_str = str(attribute_value_type)- return-- @property- def attribute_type(self):- return AttributeType.from_name_safe( self.attribute_type_str )-- @attribute_type.setter- def attribute_type( self, attribute_type : AttributeType ):- self.attribute_type_str = str(attribute_type)- return-class EntityState(models.Model):+class EntityState( models.Model ):"""- The (hidden) state of an entity that can be controlled and/or sensed.- The EntityType will help define the (default) name and value ranges (if not a general type)diff --git a/src/hi/apps/location/edit/forms.py b/src/hi/apps/location/edit/forms.pyindex d832a74c..0df59648 100644--- a/src/hi/apps/location/edit/forms.py+++ b/src/hi/apps/location/edit/forms.py@@ -18,6 +18,7 @@ ET.register_namespace('', 'http://www.w3.org/2000/svg')class LocationForm(forms.Form):LOCATION_DEFAULT_FILENAME = 'location-default.svg'+ MEDIA_DIRECTORY = 'location/svg'MAX_SVG_FILE_SIZE_MEGABYTES = 5MAX_SVG_FILE_SIZE_BYTES = MAX_SVG_FILE_SIZE_MEGABYTES * 1024 * 1024@@ -95,7 +96,12 @@ class LocationForm(forms.Form):inner_content = ''.join( ET.tostring( element, encoding = 'unicode' ) for element in root )cleaned_data['svg_fragment_content'] = inner_content- cleaned_data['svg_fragment_filename'] = self.generate_unique_filename( svg_filename )++ svg_fragment_filename = os.path.join(+ self.MEDIA_DIRECTORY,+ self.generate_unique_filename( svg_filename ),+ )+ cleaned_data['svg_fragment_filename'] = svg_fragment_filenameexcept ET.ParseError:raise ValidationError( 'The uploaded file is not a valid XML (SVG) file.' )@@ -107,7 +113,7 @@ class LocationForm(forms.Form):def generate_unique_filename( self, filename : str ):original_name, extension = os.path.splitext( filename )timestamp = int( time.time() )- unique_name = f'{original_name}_{timestamp}{extension}'+ unique_name = f'{original_name}-{timestamp}{extension}'return unique_namediff --git a/src/hi/apps/location/location_manager.py b/src/hi/apps/location/location_manager.pyindex 43c62338..93357492 100644--- a/src/hi/apps/location/location_manager.py+++ b/src/hi/apps/location/location_manager.py@@ -1,4 +1,6 @@-from django.core.files.storage import default_storage+import os++from django.core.files.storage import default_storage, FileSystemStoragefrom django.db import transactionfrom hi.apps.common.singleton import Singleton@@ -30,6 +32,7 @@ class LocationManager(Singleton):else:order_id = 0+ self._ensure_directory_exists( svg_fragment_filename )with default_storage.open( svg_fragment_filename, 'w') as destination:destination.write( svg_fragment_content )@@ -47,3 +50,11 @@ class LocationManager(Singleton):)return location++ def _ensure_directory_exists( self, filepath ):+ if isinstance( default_storage, FileSystemStorage ):+ directory = os.path.dirname( default_storage.path( filepath ))++ if not os.path.exists( directory ):+ os.makedirs( directory, exist_ok = True )+ returndiff --git a/src/hi/apps/location/migrations/0013_locationattribute.py b/src/hi/apps/location/migrations/0013_locationattribute.pynew file mode 100644index 00000000..42d3be86--- /dev/null+++ b/src/hi/apps/location/migrations/0013_locationattribute.py@@ -0,0 +1,74 @@+# Generated by Django 4.2.15 on 2024-10-11 19:54++from django.db import migrations, models+import django.db.models.deletion+++class Migration(migrations.Migration):++ dependencies = [+ ("location", "0012_remove_location_svg_filename"),+ ]++ operations = [+ migrations.CreateModel(+ name="LocationAttribute",+ fields=[+ (+ "id",+ models.BigAutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ (+ "attribute_value_type_str",+ models.CharField(+ max_length=32, verbose_name="Attribute Value Type"+ ),+ ),+ ("name", models.CharField(max_length=64, verbose_name="Name")),+ ("value", models.TextField(verbose_name="Value")),+ (+ "attribute_type_str",+ models.CharField(max_length=32, verbose_name="Attribute Type"),+ ),+ (+ "is_editable",+ models.BooleanField(default=True, verbose_name="Editable?"),+ ),+ (+ "is_required",+ models.BooleanField(default=False, verbose_name="Required?"),+ ),+ (+ "created_datetime",+ models.DateTimeField(auto_now_add=True, verbose_name="Created"),+ ),+ (+ "updated_datetime",+ models.DateTimeField(auto_now=True, verbose_name="Updated"),+ ),+ (+ "location",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="attributes",+ to="location.location",+ verbose_name="Location",+ ),+ ),+ ],+ options={+ "verbose_name": "Attribute",+ "verbose_name_plural": "Attributes",+ "indexes": [+ models.Index(+ fields=["name", "value"], name="location_lo_name_0c26e1_idx"+ )+ ],+ },+ ),+ ]diff --git a/src/hi/apps/location/models.py b/src/hi/apps/location/models.pyindex b2d2091e..bed549eb 100644--- a/src/hi/apps/location/models.py+++ b/src/hi/apps/location/models.py@@ -4,6 +4,7 @@ from django.core.files.storage import default_storagefrom django.db import modelsfrom hi.apps.common.svg_models import SvgViewBox+from hi.apps.attribute.models import AttributeModelfrom hi.enums import ItemTypefrom hi.models import ItemTypeModelMixin@@ -88,6 +89,27 @@ class Location( models.Model, ItemTypeModelMixin ):return+class LocationAttribute( AttributeModel ):+ """+ - Information related to an location, e.g., specs, docs, notes, configs+ - The 'attribute type' is used to help define what information the user might need to provide.+ """++ location = models.ForeignKey(+ Location,+ related_name = 'attributes',+ verbose_name = 'Location',+ on_delete = models.CASCADE,+ )++ class Meta:+ verbose_name = 'Attribute'+ verbose_name_plural = 'Attributes'+ indexes = [+ models.Index( fields=[ 'name', 'value' ] ),+ ]++class LocationView( models.Model, ItemTypeModelMixin ):location = models.ForeignKey(diff --git a/src/hi/integrations/hass/hass_converter.py b/src/hi/integrations/hass/hass_converter.pyindex 70200529..992f181c 100644--- a/src/hi/integrations/hass/hass_converter.py+++ b/src/hi/integrations/hass/hass_converter.py@@ -4,15 +4,17 @@ from typing import Dictfrom django.db import transaction-from hi.apps.entity.enums import (- AttributeName,+from hi.apps.attribute.enums import (AttributeType,AttributeValueType,+)+from hi.apps.entity.enums import (+ AttributeName,EntityType,HumidityUnit,TemperatureUnit,)-from hi.apps.entity.models import Entity, Attribute+from hi.apps.entity.models import Entity, EntityAttributefrom hi.apps.model_helper import HiModelHelperfrom hi.integrations.core.enums import IntegrationType@@ -235,7 +237,7 @@ class HassConverter:insteon_address = cls.hass_device_to_insteon_address( hass_device )if insteon_address:- Attribute.objects.create(+ EntityAttribute.objects.create(entity = entity,name = AttributeName.INSTEON_ADDRESS,value = insteon_address,diff --git a/src/hi/settings/base.py b/src/hi/settings/base.pyindex c4139932..8a4643ff 100644--- a/src/hi/settings/base.py+++ b/src/hi/settings/base.py@@ -137,6 +137,7 @@ INSTALLED_APPS = ['constance','hi.apps.common','hi.apps.config',+ 'hi.apps.attribute','hi.apps.location','hi.apps.entity','hi.apps.collection',