Skip to content

Home Information - Your home, your data, organized.

Python

Allow Selecting Which Home Assistant Entities to Import (Issue #242) (#264)

Tony C3883a99f5068
diff --git a/src/hi/apps/common/processing_result.py b/src/hi/apps/common/processing_result.py
index 5974ca8e..93daa46c 100644
--- a/src/hi/apps/common/processing_result.py
+++ b/src/hi/apps/common/processing_result.py
@@ -13,6 +13,7 @@ class ProcessingResult:
Provide this as 'processing_result' in the template context.
"""
- title : str
- message_list : List[ str ] = field( default_factory = list )
- error_list : List[ str ] = field( default_factory = list )
+ title : str
+ message_list : List[ str ] = field( default_factory = list )
+ error_list : List[ str ] = field( default_factory = list )
+ footer_message : str = ''
diff --git a/src/hi/apps/common/templates/common/panes/processing_result.html b/src/hi/apps/common/templates/common/panes/processing_result.html
index df787e59..1de50592 100644
--- a/src/hi/apps/common/templates/common/panes/processing_result.html
+++ b/src/hi/apps/common/templates/common/panes/processing_result.html
@@ -24,3 +24,7 @@
{% if not processing_result.error_list %}
<div><em>No errors.</em></div>
{% endif %}
+
+{% if processing_result.footer_message %}
+<div class="text-muted small mt-3 border-top pt-2">{{ processing_result.footer_message }}</div>
+{% endif %}
diff --git a/src/hi/integrations/integration_manager.py b/src/hi/integrations/integration_manager.py
index e337f077..dfc3ee3f 100644
--- a/src/hi/integrations/integration_manager.py
+++ b/src/hi/integrations/integration_manager.py
@@ -282,8 +282,8 @@ class IntegrationManager( Singleton ):
"""
with self._data_lock:
new_attribute_types = list()
- existing_attribute_integration_keys = set([ x.integration_key
- for x in integration.attributes.all() ])
+ existing_attributes = { x.integration_key: x
+ for x in integration.attributes.all() }
AttributeType = integration_metadata.attribute_type
for attribute_type in AttributeType:
@@ -291,8 +291,17 @@ class IntegrationManager( Singleton ):
integration_id = integration.integration_id,
integration_name = str(attribute_type),
)
- if integration_key not in existing_attribute_integration_keys:
+ if integration_key not in existing_attributes:
new_attribute_types.append( attribute_type )
+ else:
+ existing_attr = existing_attributes[integration_key]
+ description = attribute_type.description or ''
+ if existing_attr.description != description:
+ existing_attr.description = description
+ existing_attr.save(
+ update_fields = ['description'],
+ track_history = False,
+ )
continue
if new_attribute_types:
@@ -316,6 +325,7 @@ class IntegrationManager( Singleton ):
integration = integration,
name = attribute_type.label,
value = attribute_type.initial_value,
+ description = attribute_type.description or '',
value_type_str = str(attribute_type.value_type),
value_range_str = json.dumps( attribute_type.value_range_dict ),
integration_key_str = str(integration_key),
diff --git a/src/hi/integrations/migrations/0005_add_integration_attribute_description.py b/src/hi/integrations/migrations/0005_add_integration_attribute_description.py
new file mode 100644
index 00000000..6169ba3c
--- /dev/null
+++ b/src/hi/integrations/migrations/0005_add_integration_attribute_description.py
@@ -0,0 +1,18 @@
+# Generated by Django 4.2.29 on 2026-03-29 20:22
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("integrations", "0004_alter_integrationattribute_options"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="integrationattribute",
+ name="description",
+ field=models.TextField(blank=True, default="", verbose_name="Description"),
+ ),
+ ]
diff --git a/src/hi/integrations/models.py b/src/hi/integrations/models.py
index d445c5fb..30ccaf50 100644
--- a/src/hi/integrations/models.py
+++ b/src/hi/integrations/models.py
@@ -48,22 +48,31 @@ class Integration( models.Model ):
class IntegrationAttribute( AttributeModel ):
-
+
integration = models.ForeignKey(
Integration,
related_name = 'attributes',
verbose_name = 'Integration',
on_delete = models.CASCADE,
)
+ description = models.TextField(
+ 'Description',
+ blank = True,
+ default = '',
+ )
class Meta:
verbose_name = 'Attribute'
verbose_name_plural = 'Attributes'
ordering = ['order_id', 'id']
+ @property
+ def display_description( self ):
+ return self.description or ''
+
def get_upload_to(self):
return 'integration/attributes/'
-
+
def _get_history_model_class(self):
"""Return the history model class for IntegrationAttribute."""
return IntegrationAttributeHistory
diff --git a/src/hi/services/hass/enums.py b/src/hi/services/hass/enums.py
index 9a916a94..f01ec2ae 100644
--- a/src/hi/services/hass/enums.py
+++ b/src/hi/services/hass/enums.py
@@ -29,8 +29,27 @@ class HassAttributeType( IntegrationAttributeType ):
False,
True,
)
+ IMPORT_ALLOWLIST = (
+ 'Import Allowlist',
+ 'HA domains and device classes to import (one per line). '
+ 'Use "domain" for all classes, or "domain:class" for specific ones.',
+ AttributeValueType.TEXT,
+ None,
+ True,
+ False,
+ 'binary_sensor\n'
+ 'camera\n'
+ 'climate\n'
+ 'cover\n'
+ 'fan\n'
+ 'light\n'
+ 'lock\n'
+ 'media_player\n'
+ 'sensor\n'
+ 'switch',
+ )
+
-
class HassStateValue:
ON = 'on'
diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.py
index eee4ffb5..001d06cf 100644
--- a/src/hi/services/hass/hass_converter.py
+++ b/src/hi/services/hass/hass_converter.py
@@ -1,6 +1,6 @@
import logging
import re
-from typing import Dict, List
+from typing import Dict, List, Optional, Set, Tuple
from django.db import transaction
@@ -81,6 +81,41 @@ class HassConverter:
Controller/Sensor Creation → Payload Storage → Runtime Service Calls
"""
+ @staticmethod
+ def parse_import_allowlist( allowlist_text : str ) -> Tuple[ Set[str], Set[Tuple[str, str]] ]:
+ """Parse allowlist text into domain-only and domain:class rule sets.
+ Returns:
+ (allowed_domains, allowed_domain_classes) where:
+ - allowed_domains: set of domains where all classes are allowed
+ - allowed_domain_classes: set of (domain, device_class) tuples
+ """
+ allowed_domains = set()
+ allowed_domain_classes = set()
+ for line in allowlist_text.strip().splitlines():
+ rule = line.strip()
+ if not rule:
+ continue
+ if ':' in rule:
+ domain, device_class = rule.split( ':', 1 )
+ allowed_domain_classes.add( ( domain.strip(), device_class.strip() ) )
+ else:
+ allowed_domains.add( rule )
+ return ( allowed_domains, allowed_domain_classes )
+
+ @staticmethod
+ def is_state_allowed( hass_state,
+ allowed_domains : Set[str],
+ allowed_domain_classes : Set[Tuple[str, str]] ) -> bool:
+ """Check if a state matches the allowlist. The allowlist is the sole
+ authority when configured — IGNORE_DOMAINS is not consulted."""
+ domain = hass_state.domain
+ if domain in allowed_domains:
+ return True
+ device_class = hass_state.device_class or ''
+ if ( domain, device_class ) in allowed_domain_classes:
+ return True
+ return False
+
# Ignore all states from these domains - typically non-physical entities
# that don't represent controllable devices or useful sensors
#
@@ -330,7 +365,8 @@ class HassConverter:
@classmethod
def hass_states_to_hass_devices( cls,
- hass_entity_id_to_state : Dict[ str, HassState ]
+ hass_entity_id_to_state : Dict[ str, HassState ],
+ import_allowlist : Optional[str] = None,
) -> Dict[ str, HassDevice ]:
"""
The Home Assistant (HAss) model we see by fetching the HAss states does
@@ -341,9 +377,19 @@ class HassConverter:
HAss devices to help map from the HAss model to this app's model.
"""
+ # When an allowlist is configured, it is the sole authority on what
+ # gets imported. When not configured, fall back to IGNORE_DOMAINS.
+ if import_allowlist:
+ allowed_domains, allowed_domain_classes = cls.parse_import_allowlist( import_allowlist )
+ use_allowlist = True
+ else:
+ allowed_domains = set()
+ allowed_domain_classes = set()
+ use_allowlist = False
+
##########
# First pass to gather candidate device names.
-
+
# All names (ignoring domain) seen with a known suffix. Values are set of domains seen.
names_seen_with_suffixes = dict()
@@ -354,13 +400,16 @@ class HassConverter:
# uniquely identify a device.
#
group_ids = dict()
-
+
for hass_state in hass_entity_id_to_state.values():
domain = hass_state.domain
full_name = hass_state.entity_name_sans_prefix
short_name = hass_state.entity_name_sans_suffix
- if domain in cls.IGNORE_DOMAINS:
+ if use_allowlist:
+ if not cls.is_state_allowed( hass_state, allowed_domains, allowed_domain_classes ):
+ continue
+ elif domain in cls.IGNORE_DOMAINS:
continue
# All states with same insteon address are from same device
@@ -393,7 +442,10 @@ class HassConverter:
full_name = hass_state.entity_name_sans_prefix
short_name = hass_state.entity_name_sans_suffix
- if domain in cls.IGNORE_DOMAINS:
+ if use_allowlist:
+ if not cls.is_state_allowed( hass_state, allowed_domains, allowed_domain_classes ):
+ continue
+ elif domain in cls.IGNORE_DOMAINS:
continue
# Simplest case of having explicit group id
diff --git a/src/hi/services/hass/hass_manager.py b/src/hi/services/hass/hass_manager.py
index 016670c6..0e1c244a 100644
--- a/src/hi/services/hass/hass_manager.py
+++ b/src/hi/services/hass/hass_manager.py
@@ -149,6 +149,13 @@ class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusPro
if attribute:
return str_to_bool( attribute.value )
return False
+
+ @property
+ def import_allowlist( self ) -> str:
+ attribute = self._hass_attr_type_to_attribute.get( HassAttributeType.IMPORT_ALLOWLIST )
+ if attribute and attribute.value:
+ return attribute.value
+ return HassAttributeType.IMPORT_ALLOWLIST.initial_value
def fetch_hass_states_from_api( self, verbose : bool = True ) -> Dict[ str, HassState ]:
if verbose:
diff --git a/src/hi/services/hass/hass_sync.py b/src/hi/services/hass/hass_sync.py
index 15211815..f65a75f0 100644
--- a/src/hi/services/hass/hass_sync.py
+++ b/src/hi/services/hass/hass_sync.py
@@ -55,11 +55,30 @@ class HassSynchronizer( HassMixin, IntegrationSyncMixin ):
integration_key_to_entity = self._get_existing_hass_entities( result = result )
result.message_list.append( f'Found {len(integration_key_to_entity)} existing Home Assistant entities.' )
+ import_allowlist = hass_manager.import_allowlist
hass_device_id_to_device = HassConverter.hass_states_to_hass_devices(
hass_entity_id_to_state = hass_entity_id_to_state,
+ import_allowlist = import_allowlist,
)
result.message_list.append( f'Found {len(hass_device_id_to_device)} current Home Assistant devices.' )
+ if import_allowlist:
+ total_states = len( hass_entity_id_to_state )
+ imported_states = sum(
+ len( device.hass_state_list )
+ for device in hass_device_id_to_device.values()
+ )
+ skipped_count = total_states - imported_states
+ if skipped_count > 0:
+ result.message_list.append(
+ f'Filtered {skipped_count} states not matching the Import Allowlist.'
+ )
+ result.footer_message = (
+ 'Not seeing all your Home Assistant items? '
+ 'Check the "Import Allowlist" in the Home Assistant '
+ 'integration settings to add more domains or device classes.'
+ )
+
integration_key_to_hass_device = {
HassConverter.hass_device_to_integration_key( hass_device ): hass_device
for hass_device in hass_device_id_to_device.values()
diff --git a/src/hi/services/hass/tests/test_hass_sync.py b/src/hi/services/hass/tests/test_hass_sync.py
index 5f3d3890..bb102ba0 100644
--- a/src/hi/services/hass/tests/test_hass_sync.py
+++ b/src/hi/services/hass/tests/test_hass_sync.py
@@ -92,6 +92,7 @@ class TestHassSynchronizerSyncHelper(TestCase):
self.mock_manager = Mock()
self.mock_client = Mock()
self.mock_manager.hass_client = self.mock_client
+ self.mock_manager.import_allowlist = None
class TestHassSynchronizerStateConversion(TestCase):
@@ -151,8 +152,9 @@ class TestHassSynchronizerTransactionBehavior(TestCase):
# Setup manager
mock_manager = Mock()
mock_manager.hass_client = Mock()
+ mock_manager.import_allowlist = None
mock_hass_manager.return_value = mock_manager
-
+
# Setup scenario: one new device, one entity to remove
api_states = {'light.new': self._create_mock_hass_state('light.new', 'light', 'on')}
mock_manager.fetch_hass_states_from_api.return_value = api_states
@@ -183,11 +185,12 @@ class TestHassSynchronizerTransactionBehavior(TestCase):
with patch.object(self.synchronizer, 'hass_manager') as mock_hass_manager, \
patch.object(self.synchronizer, '_get_existing_hass_entities') as mock_get_entities:
- # Setup manager
+ # Setup manager
mock_manager = Mock()
mock_manager.hass_client = Mock()
+ mock_manager.import_allowlist = None
mock_hass_manager.return_value = mock_manager
-
+
# Setup API data
api_states = {'light.test': self._create_mock_hass_state('light.test', 'light', 'on')}
mock_manager.fetch_hass_states_from_api.return_value = api_states
@@ -230,6 +233,7 @@ class TestHassSynchronizerErrorScenarios(TestCase):
# Mock manager with client that fails API fetch
mock_manager = Mock()
mock_manager.hass_client = Mock()
+ mock_manager.import_allowlist = None
mock_manager.fetch_hass_states_from_api.side_effect = Exception("API connection failed")
mock_hass_manager.return_value = mock_manager
@@ -248,6 +252,7 @@ class TestHassSynchronizerErrorScenarios(TestCase):
# Setup mocks
mock_manager = Mock()
mock_manager.hass_client = Mock()
+ mock_manager.import_allowlist = None
mock_manager.fetch_hass_states_from_api.return_value = {'test': Mock()}
mock_hass_manager.return_value = mock_manager
diff --git a/src/hi/services/hass/tests/test_import_allowlist.py b/src/hi/services/hass/tests/test_import_allowlist.py
new file mode 100644
index 00000000..ee5e3d7e
--- /dev/null
+++ b/src/hi/services/hass/tests/test_import_allowlist.py
@@ -0,0 +1,107 @@
+import logging
+from unittest.mock import Mock
+
+from django.test import SimpleTestCase
+
+from hi.services.hass.hass_converter import HassConverter
+
+logging.disable( logging.CRITICAL )
+
+
+class TestParseImportAllowlist( SimpleTestCase ):
+
+ def test_parse_domain_only_rules( self ):
+ allowlist = 'light\nswitch\nsensor'
+ domains, domain_classes = HassConverter.parse_import_allowlist( allowlist )
+
+ self.assertEqual( domains, { 'light', 'switch', 'sensor' } )
+ self.assertEqual( domain_classes, set() )
+ return
+
+ def test_parse_domain_class_rules( self ):
+ allowlist = 'sensor:temperature\nbinary_sensor:motion'
+ domains, domain_classes = HassConverter.parse_import_allowlist( allowlist )
+
+ self.assertEqual( domains, set() )
+ self.assertEqual( domain_classes, {
+ ( 'sensor', 'temperature' ),
+ ( 'binary_sensor', 'motion' ),
+ } )
+ return
+
+ def test_parse_mixed_rules( self ):
+ allowlist = 'light\nsensor:temperature\nswitch\nbinary_sensor:door'
+ domains, domain_classes = HassConverter.parse_import_allowlist( allowlist )
+
+ self.assertEqual( domains, { 'light', 'switch' } )
+ self.assertEqual( domain_classes, {
+ ( 'sensor', 'temperature' ),
+ ( 'binary_sensor', 'door' ),
+ } )
+ return
+
+ def test_parse_ignores_blank_lines( self ):
+ allowlist = 'light\n\n\nswitch\n \n'
+ domains, domain_classes = HassConverter.parse_import_allowlist( allowlist )
+
+ self.assertEqual( domains, { 'light', 'switch' } )
+ return
+
+ def test_parse_strips_whitespace( self ):
+ allowlist = ' light \n sensor:temperature '
+ domains, domain_classes = HassConverter.parse_import_allowlist( allowlist )
+
+ self.assertEqual( domains, { 'light' } )
+ self.assertEqual( domain_classes, { ( 'sensor', 'temperature' ) } )
+ return
+
+
+class TestIsStateAllowed( SimpleTestCase ):
+
+ def _mock_state( self, domain, device_class = None ):
+ state = Mock()
+ state.domain = domain
+ state.device_class = device_class
+ return state
+
+ def test_domain_match_allows_state( self ):
+ state = self._mock_state( 'light' )
+ self.assertTrue( HassConverter.is_state_allowed(
+ state, { 'light', 'switch' }, set(),
+ ) )
+ return
+
+ def test_domain_not_in_allowlist_rejects_state( self ):
+ state = self._mock_state( 'automation' )
+ self.assertFalse( HassConverter.is_state_allowed(
+ state, { 'light', 'switch' }, set(),
+ ) )
+ return
+
+ def test_domain_class_match_allows_state( self ):
+ state = self._mock_state( 'sensor', device_class = 'temperature' )
+ self.assertTrue( HassConverter.is_state_allowed(
+ state, set(), { ( 'sensor', 'temperature' ) },
+ ) )
+ return
+
+ def test_domain_class_mismatch_rejects_state( self ):
+ state = self._mock_state( 'sensor', device_class = 'diagnostic' )
+ self.assertFalse( HassConverter.is_state_allowed(
+ state, set(), { ( 'sensor', 'temperature' ) },
+ ) )
+ return
+
+ def test_full_domain_allows_any_class( self ):
+ state = self._mock_state( 'sensor', device_class = 'anything' )
+ self.assertTrue( HassConverter.is_state_allowed(
+ state, { 'sensor' }, set(),
+ ) )
+ return
+
+ def test_no_device_class_with_domain_class_rule_rejects( self ):
+ state = self._mock_state( 'sensor', device_class = None )
+ self.assertFalse( HassConverter.is_state_allowed(
+ state, set(), { ( 'sensor', 'temperature' ) },
+ ) )
+ return