Home Information - Your home, your data, organized.
Python
Improved handling for ENUM Attributes.
Anthony Cassandra5a2f514dd384
diff --git a/src/hi/apps/attribute/attribute_enums.py b/src/hi/apps/attribute/attribute_enums.pyindex 3843ea3d..f094d60d 100644--- a/src/hi/apps/attribute/attribute_enums.py+++ b/src/hi/apps/attribute/attribute_enums.py@@ -1,55 +1,31 @@from typing import List, Tuple-from hi.apps.common.singleton import Singletonfrom hi.apps.config.enums import Theme+from hi.constants import TIMEZONE_NAME_LIST-class AttributeEnums( Singleton ):++class AttributeEnums:"""For attributes of type AttributeValueType.ENUM. There are some- predefined common defaults, or can add others when modules are- added.. This is needed so that the general attribute rendering- templates can have access to them.+ predefined common defaults that can be used. Instead of putting all+ the possible choices in the 'value_range_str' field of an Attribute,+ you can include a well-known identifier and the values will come from+ this module.- TODO: Add some form of dynamic registration process to decouple- this module from all the individual modules that need an enum type.+ This is also needed for enumerations that might change in future+ releases where we do not want to have to update the user database."""- TIMEZONE_NAME_LIST = [- 'UTC',- 'America/New_York',- 'America/Chicago',- 'America/Denver',- 'America/Los_Angeles',- 'America/Toronto',- 'America/Mexico_City',- 'America/Sao_Paulo',- 'Europe/London',- 'Europe/Berlin',- 'Europe/Paris',- 'Europe/Moscow',- 'Asia/Dubai',- 'Asia/Tokyo',- 'Asia/Seoul',- 'Asia/Shanghai',- 'Asia/Hong_Kong',- 'Asia/Singapore',- 'Asia/Kolkata',- 'Asia/Jakarta',- 'Australia/Sydney',- 'Australia/Melbourne',- 'Africa/Johannesburg',- 'Africa/Lagos',- 'Africa/Cairo',- 'America/Argentina/Buenos_Aires',- ]+ TIMEZONE_CHOICES_ID = 'hi.timezone'+ THEME_CHOICES_ID = 'hi.theme'++ ID_TO_CHOICES = {+ TIMEZONE_CHOICES_ID: [ ( x, x ) for x in TIMEZONE_NAME_LIST ],+ THEME_CHOICES_ID: Theme.choices(),+ }++ @classmethod+ def get_choices( cls, choices_id : str ) -> List[ Tuple[ str, str ] ]:+ return cls.ID_TO_CHOICES.get( choices_id )- def __init_singleton__( self ):- self._enum_name_to_choices = dict()- self._enum_name_to_choices['Timezone'] = [ ( x, x ) for x in self.TIMEZONE_NAME_LIST ]- self._enum_name_to_choices['Theme'] = Theme.choices()- return-- @property- def attribute_enums_map(self) -> List[ Tuple[ str, str ] ]:- return self._enum_name_to_choicesdiff --git a/src/hi/apps/attribute/models.py b/src/hi/apps/attribute/models.pyindex fb66e632..f118c5eb 100644--- a/src/hi/apps/attribute/models.py+++ b/src/hi/apps/attribute/models.py@@ -1,8 +1,10 @@+import jsonimport loggingfrom django.core.files.storage import default_storagefrom django.db import models+from hi.apps.attribute.attribute_enums import AttributeEnumsfrom hi.apps.common.file_utils import generate_unique_filenamefrom hi.integrations.core.integration_key import IntegrationKey@@ -42,6 +44,10 @@ class AttributeModel(models.Model):max_length = 32,null = False, blank = False,)+ value_range_str = models.TextField(+ 'Value Range',+ null = True, blank = True,+ )integration_key_str = models.CharField('Integration Key',max_length = 128,@@ -70,6 +76,9 @@ class AttributeModel(models.Model):blank = True,)+ def get_upload_to(self):+ raise NotImplementedError('Subclasses should override this method.' )+def __str__(self):return f'Attr: {self.name}={self.value} [{self.value_type_str}] [{self.attribute_type_str}]'@@ -107,9 +116,23 @@ class AttributeModel(models.Model):def attribute_type( self, attribute_type : AttributeType ):self.attribute_type_str = str(attribute_type)return-- def get_upload_to(self):- raise NotImplementedError('Subclasses should override this method.' )++ def choices(self):+ # First check predefined ids+ choice_list = AttributeEnums.get_choices( self.value_range_str )+ if choice_list:+ return choice_list+ if not self.value_range_str:+ return list()+ try:+ value_range = json.loads( self.value_range_str )+ if isinstance( value_range, dict ):+ return [ ( k, v ) for k, v in value_range.items() ]+ if isinstance( value_range, list ):+ return [ ( x, x ) for x in value_range ]+ except json.JSONDecodeError:+ pass+ return dict()def save(self, *args, **kwargs):if self.file_value and self.file_value.name:diff --git a/src/hi/apps/attribute/templates/attribute/panes/attribute_form_enum.html b/src/hi/apps/attribute/templates/attribute/panes/attribute_form_enum.htmlindex 7d877ac5..27eb65d9 100644--- a/src/hi/apps/attribute/templates/attribute/panes/attribute_form_enum.html+++ b/src/hi/apps/attribute/templates/attribute/panes/attribute_form_enum.html@@ -6,7 +6,7 @@<div class="input-group-prepend" ><span class="input-group-text" >{{ attribute_form.instance.name }}</span></div>- {% with ATTRIBUTE_ENUMS|get_item:attribute_form.instance.name as choices_list %}+ {% with attribute_form.instance.choices as choices_list %}<selectid="{{ attribute_form.value.id_for_label }}"{% if attribute_form.instance and not attribute_form.instance.is_editable %}disabled="true"{% endif %}diff --git a/src/hi/apps/config/enums.py b/src/hi/apps/config/enums.pyindex 7daaef16..c363e16a 100644--- a/src/hi/apps/config/enums.py+++ b/src/hi/apps/config/enums.py@@ -1,6 +1,10 @@+from typing import Dict+from hi.apps.attribute.enums import AttributeValueTypefrom hi.apps.common.enums import LabeledEnum+from hi.constants import TIMEZONE_NAME_LIST+class ConfigPageType(LabeledEnum):"""@@ -42,6 +46,7 @@ class SubsystemAttributeType(LabeledEnum):'Timezone to use for display',SubsystemType.LOCALE,AttributeValueType.ENUM,+ 'hi.timezone',True,True,'America/Chicago',@@ -51,22 +56,25 @@ class SubsystemAttributeType(LabeledEnum):'Overall look and feel of interfaces',SubsystemType.DISPLAY,AttributeValueType.ENUM,+ 'hi.theme',True,True,str( Theme.default() ),)def __init__( self,- label : str,- description : str,- subsystem_type : SubsystemType,- value_type : AttributeValueType,- is_editable : bool,- is_required : bool,- initial_value : str ):+ label : str,+ description : str,+ subsystem_type : SubsystemType,+ value_type : AttributeValueType,+ value_range_str : str,+ is_editable : bool,+ is_required : bool,+ initial_value : str ):super().__init__( label, description )self.subsystem_type = subsystem_typeself.value_type = value_type+ self.value_range_str = value_range_strself.is_editable = is_editableself.is_required = is_requiredself.initial_value = initial_valuediff --git a/src/hi/apps/config/migrations/0003_subsystemattribute_value_range.py b/src/hi/apps/config/migrations/0003_subsystemattribute_value_range.pynew file mode 100644index 00000000..26c8402a--- /dev/null+++ b/src/hi/apps/config/migrations/0003_subsystemattribute_value_range.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-12-04 22:13++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("config", "0002_alter_subsystem_options"),+ ]++ operations = [+ migrations.AddField(+ model_name="subsystemattribute",+ name="value_range",+ field=models.TextField(blank=True, null=True, verbose_name="Value Range"),+ ),+ ]diff --git a/src/hi/apps/config/migrations/0004_rename_value_range_subsystemattribute_value_range_str.py b/src/hi/apps/config/migrations/0004_rename_value_range_subsystemattribute_value_range_str.pynew file mode 100644index 00000000..394a90e7--- /dev/null+++ b/src/hi/apps/config/migrations/0004_rename_value_range_subsystemattribute_value_range_str.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-12-04 22:56++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("config", "0003_subsystemattribute_value_range"),+ ]++ operations = [+ migrations.RenameField(+ model_name="subsystemattribute",+ old_name="value_range",+ new_name="value_range_str",+ ),+ ]diff --git a/src/hi/apps/config/system_settings.py b/src/hi/apps/config/system_settings.pyindex 30250588..ac8eb931 100644--- a/src/hi/apps/config/system_settings.py+++ b/src/hi/apps/config/system_settings.py@@ -1,3 +1,4 @@+import jsonfrom typing import Listfrom django.db import transaction@@ -43,6 +44,7 @@ class SystemSettings( Singleton ):name = subsystem_attribute_type.label,value = subsystem_attribute_type.initial_value,value_type_str = str(subsystem_attribute_type.value_type),+ value_range_str = subsystem_attribute_type.value_range_str,attribute_type_str = AttributeType.PREDEFINED,is_editable = subsystem_attribute_type.is_editable,is_required = subsystem_attribute_type.is_required,diff --git a/src/hi/apps/control/models.py b/src/hi/apps/control/models.pyindex 17024d9f..611e1551 100644--- a/src/hi/apps/control/models.py+++ b/src/hi/apps/control/models.py@@ -57,7 +57,7 @@ class Controller( IntegrationKeyModel ):@propertydef choices(self):- return [ ( k, v ) for k, v in self.entity_state.value_range_dict.items() ]+ return self.entity_state.choices()class ControllerHistory(models.Model):diff --git a/src/hi/apps/entity/admin.py b/src/hi/apps/entity/admin.pyindex f6380baf..fbed48e1 100644--- a/src/hi/apps/entity/admin.py+++ b/src/hi/apps/entity/admin.py@@ -88,7 +88,7 @@ class EntityStateAdmin(admin.ModelAdmin):'entity','name','entity_state_type_str',- 'value_range',+ 'value_range_str','units','created_datetime',)diff --git a/src/hi/apps/entity/migrations/0005_entityattribute_value_range.py b/src/hi/apps/entity/migrations/0005_entityattribute_value_range.pynew file mode 100644index 00000000..dc5da57a--- /dev/null+++ b/src/hi/apps/entity/migrations/0005_entityattribute_value_range.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-12-04 22:13++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("entity", "0004_entity_entity_integration_key"),+ ]++ operations = [+ migrations.AddField(+ model_name="entityattribute",+ name="value_range",+ field=models.TextField(blank=True, null=True, verbose_name="Value Range"),+ ),+ ]diff --git a/src/hi/apps/entity/migrations/0006_rename_value_range_entityattribute_value_range_str_and_more.py b/src/hi/apps/entity/migrations/0006_rename_value_range_entityattribute_value_range_str_and_more.pynew file mode 100644index 00000000..de3d8263--- /dev/null+++ b/src/hi/apps/entity/migrations/0006_rename_value_range_entityattribute_value_range_str_and_more.py@@ -0,0 +1,23 @@+# Generated by Django 4.2.15 on 2024-12-04 22:56++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("entity", "0005_entityattribute_value_range"),+ ]++ operations = [+ migrations.RenameField(+ model_name="entityattribute",+ old_name="value_range",+ new_name="value_range_str",+ ),+ migrations.RenameField(+ model_name="entitystate",+ old_name="value_range",+ new_name="value_range_str",+ ),+ ]diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.pyindex cec4af25..971b2a16 100644--- a/src/hi/apps/entity/models.py+++ b/src/hi/apps/entity/models.py@@ -138,7 +138,7 @@ class EntityState( models.Model ):max_length = 64,null = False, blank = False,)- value_range = models.TextField(+ value_range_str = models.TextField('Value Range',null = True, blank = True,)@@ -178,7 +178,7 @@ class EntityState( models.Model ):@propertydef value_range_dict(self):try:- value_range = json.loads( self.value_range )+ value_range = json.loads( self.value_range_str )if isinstance( value_range, dict ):return value_rangeif isinstance( value_range, list ):@@ -189,9 +189,22 @@ class EntityState( models.Model ):@value_range_dict.setterdef value_range_dict( self, value_dict : Dict[ str, str ] ):- self.value_range = json.dumps( value_dict )+ self.value_range_str = json.dumps( value_dict )return-++ def choices(self):+ if not self.value_range_str:+ return list()+ try:+ value_range = json.loads( self.value_range_str )+ if isinstance( value_range, dict ):+ return [ ( k, v ) for k, v in value_range.items() ]+ if isinstance( value_range, list ):+ return [ ( x, x ) for x in value_range ]+ except json.JSONDecodeError:+ pass+ return dict()+class EntityStateDelegation(models.Model):"""An EntityState associated with a Sensor or Controller is often servingdiff --git a/src/hi/apps/location/migrations/0007_locationattribute_value_range.py b/src/hi/apps/location/migrations/0007_locationattribute_value_range.pynew file mode 100644index 00000000..789bd92d--- /dev/null+++ b/src/hi/apps/location/migrations/0007_locationattribute_value_range.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-12-04 22:13++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("location", "0006_remove_locationview_status_display_type_str"),+ ]++ operations = [+ migrations.AddField(+ model_name="locationattribute",+ name="value_range",+ field=models.TextField(blank=True, null=True, verbose_name="Value Range"),+ ),+ ]diff --git a/src/hi/apps/location/migrations/0008_rename_value_range_locationattribute_value_range_str.py b/src/hi/apps/location/migrations/0008_rename_value_range_locationattribute_value_range_str.pynew file mode 100644index 00000000..6b71cb4d--- /dev/null+++ b/src/hi/apps/location/migrations/0008_rename_value_range_locationattribute_value_range_str.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-12-04 22:56++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("location", "0007_locationattribute_value_range"),+ ]++ operations = [+ migrations.RenameField(+ model_name="locationattribute",+ old_name="value_range",+ new_name="value_range_str",+ ),+ ]diff --git a/src/hi/apps/model_helper.py b/src/hi/apps/model_helper.pyindex 3f29fcdd..8ada69c9 100644--- a/src/hi/apps/model_helper.py+++ b/src/hi/apps/model_helper.py@@ -94,7 +94,7 @@ class HiModelHelper:entity_state_type = EntityStateType.DISCRETE,name = name,integration_key = integration_key,- value_range = json.dumps( name_label_dict ),+ value_range_str = json.dumps( name_label_dict ),)@classmethod@@ -247,7 +247,7 @@ class HiModelHelper:name = name,is_sensed = is_sensed,integration_key = integration_key,- value_range = json.dumps( name_label_dict ),+ value_range_str = json.dumps( name_label_dict ),)@classmethod@@ -257,7 +257,7 @@ class HiModelHelper:name : str = None,sensor_type : SensorType = SensorType.DEFAULT,integration_key : IntegrationKey = None,- value_range : str = '',+ value_range_str : str = '',units : str = None ):if not name:name = f'{entity.name}'@@ -266,7 +266,7 @@ class HiModelHelper:entity = entity,entity_state_type_str = str( entity_state_type ),name = name,- value_range = value_range,+ value_range_str = value_range_str,units = units,)sensor = Sensor(@@ -287,7 +287,7 @@ class HiModelHelper:controller_type : ControllerType = ControllerType.DEFAULT,is_sensed : bool = True,integration_key : IntegrationKey = None,- value_range : str = '',+ value_range_str : str = '',units : str = None ):if not name:name = f'{entity.name}'@@ -296,7 +296,7 @@ class HiModelHelper:entity = entity,entity_state_type_str = str( entity_state_type ),name = name,- value_range = value_range,+ value_range_str = value_range_str,units = units,)diff --git a/src/hi/constants.py b/src/hi/constants.pyindex 96861bfb..2afe8b28 100644--- a/src/hi/constants.py+++ b/src/hi/constants.py@@ -1,4 +1,33 @@+TIMEZONE_NAME_LIST = [+ 'UTC',+ 'America/New_York',+ 'America/Chicago',+ 'America/Denver',+ 'America/Los_Angeles',+ 'America/Toronto',+ 'America/Mexico_City',+ 'America/Sao_Paulo',+ 'Europe/London',+ 'Europe/Berlin',+ 'Europe/Paris',+ 'Europe/Moscow',+ 'Asia/Dubai',+ 'Asia/Tokyo',+ 'Asia/Seoul',+ 'Asia/Shanghai',+ 'Asia/Hong_Kong',+ 'Asia/Singapore',+ 'Asia/Kolkata',+ 'Asia/Jakarta',+ 'Australia/Sydney',+ 'Australia/Melbourne',+ 'Africa/Johannesburg',+ 'Africa/Lagos',+ 'Africa/Cairo',+ 'America/Argentina/Buenos_Aires',+]+# HTML div ids (classes and attributes) that app logic depends on.DIVID = {diff --git a/src/hi/context_processors.py b/src/hi/context_processors.pyindex df17526e..6b505191 100644--- a/src/hi/context_processors.py+++ b/src/hi/context_processors.py@@ -1,10 +1,7 @@-from hi.apps.attribute.attribute_enums import AttributeEnums-from .constants import DIVIDdef constants_context(request):return {'DIVID': DIVID,- 'ATTRIBUTE_ENUMS': AttributeEnums().attribute_enums_map,}diff --git a/src/hi/integrations/core/enums.py b/src/hi/integrations/core/enums.pyindex f58eb204..7bda6834 100644--- a/src/hi/integrations/core/enums.py+++ b/src/hi/integrations/core/enums.py@@ -1,3 +1,5 @@+from typing import Dict+from hi.apps.attribute.enums import AttributeValueTypefrom hi.apps.common.enums import LabeledEnum@@ -6,14 +8,16 @@ class IntegrationAttributeType(LabeledEnum):""" Abstract base class for integrations ot define the required attributes they need. """def __init__( self,- label : str,- description : str,- value_type : AttributeValueType,- is_editable : bool,- is_required : bool,- initial_value : str = '' ):+ label : str,+ description : str,+ value_type : AttributeValueType,+ value_range_dict : Dict[ str, str ],+ is_editable : bool,+ is_required : bool,+ initial_value : str = '' ):super().__init__( label, description )self.value_type = value_type+ self.value_range_dict = value_range_dictself.is_editable = is_editableself.is_required = is_requiredself.initial_value = initial_valuediff --git a/src/hi/integrations/core/helpers.py b/src/hi/integrations/core/helpers.pyindex 79a593fb..8064be84 100644--- a/src/hi/integrations/core/helpers.py+++ b/src/hi/integrations/core/helpers.py@@ -1,3 +1,5 @@+import json+from django.db import transactionfrom hi.apps.attribute.enums import AttributeType@@ -82,6 +84,7 @@ class IntegrationHelperMixin:name = attribute_type.label,value = attribute_type.initial_value,value_type_str = str(attribute_type.value_type),+ value_range_str = json.dumps( attribute_type.value_range_dict ),integration_key_str = str(integration_key),attribute_type_str = AttributeType.PREDEFINED,is_editable = attribute_type.is_editable,diff --git a/src/hi/integrations/core/migrations/0004_integrationattribute_value_range.py b/src/hi/integrations/core/migrations/0004_integrationattribute_value_range.pynew file mode 100644index 00000000..c27c2e12--- /dev/null+++ b/src/hi/integrations/core/migrations/0004_integrationattribute_value_range.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-12-04 22:13++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("core", "0003_integrationattribute_file_mime_type_and_more"),+ ]++ operations = [+ migrations.AddField(+ model_name="integrationattribute",+ name="value_range",+ field=models.TextField(blank=True, null=True, verbose_name="Value Range"),+ ),+ ]diff --git a/src/hi/integrations/core/migrations/0005_rename_value_range_integrationattribute_value_range_str.py b/src/hi/integrations/core/migrations/0005_rename_value_range_integrationattribute_value_range_str.pynew file mode 100644index 00000000..32485af0--- /dev/null+++ b/src/hi/integrations/core/migrations/0005_rename_value_range_integrationattribute_value_range_str.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-12-04 22:56++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("core", "0004_integrationattribute_value_range"),+ ]++ operations = [+ migrations.RenameField(+ model_name="integrationattribute",+ old_name="value_range",+ new_name="value_range_str",+ ),+ ]diff --git a/src/hi/integrations/hass/enums.py b/src/hi/integrations/hass/enums.pyindex e7086067..85c0ab0f 100644--- a/src/hi/integrations/hass/enums.py+++ b/src/hi/integrations/hass/enums.py@@ -8,6 +8,7 @@ class HassAttributeType( IntegrationAttributeType ):'Server URL','e.g., https://myhassserver:8123',AttributeValueType.TEXT,+ None,True,True,)@@ -15,6 +16,7 @@ class HassAttributeType( IntegrationAttributeType ):'API Token','',AttributeValueType.TEXT,+ None,True,True,)diff --git a/src/hi/integrations/zoneminder/enums.py b/src/hi/integrations/zoneminder/enums.pyindex e21525b8..13c95ebb 100644--- a/src/hi/integrations/zoneminder/enums.py+++ b/src/hi/integrations/zoneminder/enums.py@@ -1,8 +1,10 @@+from hi.apps.attribute.enums import AttributeValueTypefrom hi.apps.common.enums import LabeledEnum-from hi.apps.attribute.enums import AttributeValueTypefrom hi.integrations.core.enums import IntegrationAttributeType+from hi.constants import TIMEZONE_NAME_LIST+class ZmAttributeType( IntegrationAttributeType ):@@ -10,6 +12,7 @@ class ZmAttributeType( IntegrationAttributeType ):'API URL','e.g., https://myserver:8443/zm/api',AttributeValueType.TEXT,+ None,True,True,)@@ -17,6 +20,7 @@ class ZmAttributeType( IntegrationAttributeType ):'Portal URL','e.g., https://myserver:8443/zm',AttributeValueType.TEXT,+ None,True,True,)@@ -24,6 +28,7 @@ class ZmAttributeType( IntegrationAttributeType ):'Username','',AttributeValueType.TEXT,+ None,True,True,)@@ -31,6 +36,7 @@ class ZmAttributeType( IntegrationAttributeType ):'Password','',AttributeValueType.SECRET,+ None,True,True,)@@ -38,6 +44,7 @@ class ZmAttributeType( IntegrationAttributeType ):'Timezone','',AttributeValueType.ENUM,+ { x: x for x in TIMEZONE_NAME_LIST },True,True,'America/Chicago',