Skip to content

Home Information - Your home, your data, organized.

Python

Integration Lifecycle: Configure / Remove / Pause / Resume (#278) (#284)

Tony C4074f7071ac2
diff --git a/src/hi/apps/common/templatetags/icons.py b/src/hi/apps/common/templatetags/icons.py
index c90af140..60a2a60e 100644
--- a/src/hi/apps/common/templatetags/icons.py
+++ b/src/hi/apps/common/templatetags/icons.py
@@ -52,6 +52,7 @@ AVAILABLE_ICONS = {
'minus-circle',
'move',
'path',
+ 'pause',
'play',
'plug',
'plus',
diff --git a/src/hi/apps/config/templatetags/__init__.py b/src/hi/apps/config/templatetags/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/apps/common/templatetags/units.py b/src/hi/apps/config/templatetags/units.py
similarity index 100%
rename from src/hi/apps/common/templatetags/units.py
rename to src/hi/apps/config/templatetags/units.py
diff --git a/src/hi/apps/console/console_manager.py b/src/hi/apps/console/console_manager.py
index 487e1e68..a431e962 100644
--- a/src/hi/apps/console/console_manager.py
+++ b/src/hi/apps/console/console_manager.py
@@ -89,11 +89,16 @@ class ConsoleManager( Singleton, SettingsMixin, SensorResponseMixin ):
return
def _build_camera_control_display_list(self) -> List[CameraControlDisplayData]:
- """Build camera control display data with status entity states."""
+ """Build camera control display data with status entity states.
+
+ Listing context: includes the conjunction with is_disabled to
+ suppress disabled (e.g., disconnected) cameras from the camera
+ control list. Per-entity views still respect raw has_video_stream.
+ """
# Get entities with prefetched states in one efficient query
entity_list = list(
Entity.objects
- .filter(has_video_stream=True)
+ .filter(has_video_stream=True, is_disabled=False)
.prefetch_related('states')
.order_by('name')
)
diff --git a/src/hi/apps/entity/admin.py b/src/hi/apps/entity/admin.py
index 69ad5cdb..a6c99572 100644
--- a/src/hi/apps/entity/admin.py
+++ b/src/hi/apps/entity/admin.py
@@ -75,6 +75,7 @@ class EntityAdmin(admin.ModelAdmin):
'entity_type_str',
'integration_id',
'integration_name',
+ 'is_disabled',
'created_datetime',
)
diff --git a/src/hi/apps/entity/entity_manager.py b/src/hi/apps/entity/entity_manager.py
index 4094b8b4..acd57f46 100644
--- a/src/hi/apps/entity/entity_manager.py
+++ b/src/hi/apps/entity/entity_manager.py
@@ -605,9 +605,18 @@ class EntityManager(Singleton):
return entity_view_group_list
def get_view_stream_entities(self) -> List[ Entity ]:
- """ Return all entities that have a video stream capability """
- # Phase 4: Use has_video_stream flag instead of VIDEO_STREAM EntityState
- return list(Entity.objects.filter(has_video_stream=True))
+ """
+ Return all entities that have a video-stream capability AND are
+ not currently disabled. Both conditions are required for an entity
+ to surface in capability-driven enumerations like the sidebar
+ Cameras list. Per-entity view sites should keep using the raw
+ has_video_stream flag — the disabled gate only applies at
+ listing time.
+ """
+ return list(Entity.objects.filter(
+ has_video_stream = True,
+ is_disabled = False,
+ ))
_thread_local = local()
diff --git a/src/hi/apps/entity/migrations/0014_add_entity_is_disabled.py b/src/hi/apps/entity/migrations/0014_add_entity_is_disabled.py
new file mode 100644
index 00000000..74c25f94
--- /dev/null
+++ b/src/hi/apps/entity/migrations/0014_add_entity_is_disabled.py
@@ -0,0 +1,22 @@
+# Generated by Django 4.2.24 on 2026-04-27 15:57
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("entity", "0013_add_archived_entity"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="entity",
+ name="is_disabled",
+ field=models.BooleanField(
+ default=False,
+ help_text='When True, capabilities the entity would normally provide are suppressed. Used by the integration disconnect path and any future user-initiated "disable" UX.',
+ verbose_name="Disabled?",
+ ),
+ ),
+ ]
diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.py
index 69e49ddc..6762902b 100644
--- a/src/hi/apps/entity/models.py
+++ b/src/hi/apps/entity/models.py
@@ -58,6 +58,15 @@ class Entity( IntegrationDetailsModel, LocationItemModelMixin ):
'Has Video Stream',
default = False,
)
+ is_disabled = models.BooleanField(
+ 'Disabled?',
+ default = False,
+ help_text = (
+ 'When True, capabilities the entity would normally provide are '
+ 'suppressed. Used by the integration disconnect path and any '
+ 'future user-initiated "disable" UX.'
+ ),
+ )
created_datetime = models.DateTimeField(
'Created',
auto_now_add = True,
diff --git a/src/hi/integrations/admin.py b/src/hi/integrations/admin.py
index 145809df..c223a95f 100644
--- a/src/hi/integrations/admin.py
+++ b/src/hi/integrations/admin.py
@@ -24,6 +24,7 @@ class IntegrationAdmin(admin.ModelAdmin):
list_display = (
'integration_id',
'is_enabled',
+ 'is_paused',
'created_datetime',
'updated_datetime',
)
diff --git a/src/hi/integrations/entity_operations.py b/src/hi/integrations/entity_operations.py
new file mode 100644
index 00000000..5ad0895d
--- /dev/null
+++ b/src/hi/integrations/entity_operations.py
@@ -0,0 +1,215 @@
+"""
+Operations on entities with respect to their integration attachment.
+
+This module holds mutating operations (disconnect, preserve, detach) that
+act on Entity instances relative to the integration that owns them. These
+are distinct from the read-only analytical methods on EntityUserDataDetector.
+"""
+
+import logging
+from typing import Iterable, Optional, Set
+
+from django.db import transaction
+
+from hi.apps.attribute.enums import AttributeType
+from hi.apps.common.processing_result import ProcessingResult
+from hi.apps.entity.models import Entity, EntityState, EntityStateDelegation
+from hi.apps.sense.models import Sensor
+from hi.apps.control.models import Controller
+
+from .transient_models import IntegrationRemovalSummary
+from .user_data_detector import EntityUserDataDetector
+
+logger = logging.getLogger(__name__)
+
+
+class EntityIntegrationOperations:
+ """
+ Operations on an Entity relative to its integration attachment.
+
+ Shared between sync-time preservation (when upstream drops an entity
+ that has user-created data) and integration removal (the SAFE mode of
+ IntegrationManager.disable_integration).
+ """
+
+ @staticmethod
+ def collect_removal_closure( initial_entity_ids : Iterable[int] ) -> Set[int]:
+ """
+ Expand a set of entity IDs to include delegate entities that would
+ be orphaned by the removal.
+
+ Pure graph operation over EntityStateDelegation:
+
+ - From each entity already in the closure, find delegates reached
+ via that entity's EntityStates' delegations.
+ - A delegate is added only when *every* entity that delegates to
+ it is already in the closure (otherwise the delegate is still
+ serving a non-removed entity and must remain).
+ - Iterates until no new entities are added (handles chained and
+ diamond-shaped delegations; cycles are bounded by the visited set).
+
+ This function is integration-agnostic — callers pass whatever seed
+ set defines the explicit removal scope.
+ """
+ closure : Set[int] = set(initial_entity_ids)
+ if not closure:
+ return closure
+
+ while True:
+ # Candidate delegates: any delegate_entity reached from an
+ # entity-state owned by an entity already in the closure, that
+ # isn't already in the closure itself.
+ candidate_ids = set(
+ EntityStateDelegation.objects.filter(
+ entity_state__entity_id__in = closure,
+ ).exclude(
+ delegate_entity_id__in = closure,
+ ).values_list( 'delegate_entity_id', flat = True )
+ )
+ if not candidate_ids:
+ break
+
+ added_this_pass : Set[int] = set()
+ for candidate_id in candidate_ids:
+ principal_ids = set(
+ EntityStateDelegation.objects.filter(
+ delegate_entity_id = candidate_id,
+ ).values_list( 'entity_state__entity_id', flat = True )
+ )
+ if principal_ids and principal_ids.issubset( closure ):
+ added_this_pass.add( candidate_id )
+
+ if not added_this_pass:
+ break
+ closure |= added_this_pass
+
+ return closure
+
+ @staticmethod
+ def get_removal_entity_ids( integration_id : str ) -> Set[int]:
+ """
+ Return the full set of entity IDs that a Remove of the given
+ integration should target: every entity attached to the integration,
+ plus any delegate entities that would be orphaned by their removal.
+ """
+ seed = set(
+ Entity.objects.filter( integration_id = integration_id )
+ .values_list( 'id', flat = True )
+ )
+ return EntityIntegrationOperations.collect_removal_closure( seed )
+
+ @staticmethod
+ def summarize_for_removal( integration_id : str ) -> IntegrationRemovalSummary:
+ """
+ Classify the entities targeted by a Remove of the given integration
+ (including orphan-after-removal delegates) for the Remove
+ confirmation dialog: counts total entities and those with
+ user-created data.
+ """
+ target_ids = EntityIntegrationOperations.get_removal_entity_ids(
+ integration_id = integration_id,
+ )
+ total_count = 0
+ user_data_count = 0
+ for entity in Entity.objects.filter( id__in = target_ids ):
+ total_count += 1
+ if EntityUserDataDetector.has_user_created_attributes( entity ):
+ user_data_count += 1
+ return IntegrationRemovalSummary(
+ total_count = total_count,
+ user_data_count = user_data_count,
+ )
+
+ @staticmethod
+ def preserve_with_user_data( entity : Entity,
+ integration_name : str,
+ result : Optional[ProcessingResult] = None ):
+ """
+ Preserve an entity with user-created data by disconnecting it from
+ its integration and removing only integration-related components
+ (sensors, controllers, orphaned states, integration-owned
+ attributes). Applies the '[Disconnected]' name prefix.
+
+ Args:
+ entity: The Entity to preserve.
+ integration_name: Name of the integration (used in result messages).
+ result: Optional ProcessingResult to append a status message to.
+ """
+ original_name = entity.name
+
+ # Get integration-related components to remove
+ sensor_ids_to_remove = EntityUserDataDetector.get_integration_related_sensors(entity)
+ controller_ids_to_remove = EntityUserDataDetector.get_integration_related_controllers(entity)
+
+ # Get entity states that will become orphaned
+ orphaned_state_ids = EntityUserDataDetector.get_orphaned_entity_states(
+ entity, sensor_ids_to_remove, controller_ids_to_remove
+ )
+
+ with transaction.atomic():
+ # Remove integration-related sensors
+ if sensor_ids_to_remove:
+ removed_sensor_count = Sensor.objects.filter(
+ id__in=sensor_ids_to_remove
+ ).delete()[0]
+ logger.debug(f'Removed {removed_sensor_count} integration sensors for {entity}')
+
+ # Remove integration-related controllers
+ if controller_ids_to_remove:
+ removed_controller_count = Controller.objects.filter(
+ id__in=controller_ids_to_remove
+ ).delete()[0]
+ logger.debug(f'Removed {removed_controller_count} integration controllers for {entity}')
+
+ # Remove orphaned entity states
+ if orphaned_state_ids:
+ removed_state_count = EntityState.objects.filter(
+ id__in=orphaned_state_ids
+ ).delete()[0]
+ logger.debug(f'Removed {removed_state_count} orphaned entity states for {entity}')
+
+ # Remove integration-created attributes (keep user-added ones).
+ # Provenance is determined by attribute_type_str: PREDEFINED is
+ # system/integration-created, CUSTOM is user-added. Note:
+ # queryset .delete() intentionally bypasses the model-level
+ # SoftDeleteAttributeModel.delete() override, performing a hard
+ # delete. Integration attributes should not accumulate as
+ # soft-deleted records.
+ removed_attr_count = entity.attributes.exclude(
+ attribute_type_str=str(AttributeType.CUSTOM),
+ ).delete()[0]
+ if removed_attr_count:
+ logger.debug(f'Removed {removed_attr_count} integration attributes for {entity}')
+
+ # Disconnect entity from integration
+ entity.integration_id = None
+ entity.integration_name = None
+
+ # Restore user-management flags. These are commonly set to False
+ # by integration converters to prevent the user from deleting or
+ # extending an integration-managed entity. After disconnect the
+ # entity is no longer integration-managed, so user-management
+ # rights are restored.
+ entity.can_user_delete = True
+ entity.can_add_custom_attributes = True
+
+ # Suppress integration-backed capabilities. The intrinsic
+ # video-stream capability is genuinely lost (the backing sensor
+ # was deleted above). The is_disabled flag is the general
+ # capability gate — listing/enumeration sites use it to keep
+ # a disconnected entity out of capability-driven UX (e.g., the
+ # sidebar Cameras list).
+ entity.has_video_stream = False
+ entity.is_disabled = True
+
+ # Update name to indicate disconnected status
+ if not entity.name.startswith('[Disconnected]'):
+ entity.name = f'[Disconnected] {entity.name}'
+
+ entity.save()
+
+ if result is not None:
+ result.message_list.append(
+ f'Preserved {integration_name} entity "{original_name}" with user data, '
+ f'disconnected from integration and renamed to "{entity.name}"'
+ )
diff --git a/src/hi/integrations/enums.py b/src/hi/integrations/enums.py
index 2e9c071e..4314f3ad 100644
--- a/src/hi/integrations/enums.py
+++ b/src/hi/integrations/enums.py
@@ -4,6 +4,30 @@ from hi.apps.attribute.enums import AttributeValueType
from hi.apps.common.enums import LabeledEnum
+class IntegrationDisableMode( LabeledEnum ):
+ """
+ Mode used when removing (disabling) an integration. Controls how the
+ integration's attached entities are handled.
+
+ SAFE — delete entities without user-created data; preserve entities with
+ user-created data by disconnecting them (strips integration association,
+ removes integration-only components, applies '[Disconnected]' name
+ prefix). This mirrors the sync-time preservation behavior.
+
+ ALL — hard-delete all entities attached to the integration regardless of
+ user-created data.
+ """
+
+ SAFE = ( 'Delete Safe',
+ 'Delete entities without user data; preserve those with user data' )
+ ALL = ( 'Delete All',
+ 'Hard-delete all entities regardless of user data' )
+
+ @classmethod
+ def default(cls):
+ return cls.SAFE
+
+
class IntegrationAttributeType( LabeledEnum ):
""" Abstract base class for integrations ot define the required attributes they need. """
diff --git a/src/hi/integrations/integration_data.py b/src/hi/integrations/integration_data.py
index 69834f62..15430bc6 100644
--- a/src/hi/integrations/integration_data.py
+++ b/src/hi/integrations/integration_data.py
@@ -32,4 +32,8 @@ class IntegrationData:
@property
def is_enabled(self):
return self.integration.is_enabled
-
+
+ @property
+ def is_paused(self):
+ return self.integration.is_paused
+
diff --git a/src/hi/integrations/integration_manager.py b/src/hi/integrations/integration_manager.py
index dfc3ee3f..9bdf5978 100644
--- a/src/hi/integrations/integration_manager.py
+++ b/src/hi/integrations/integration_manager.py
@@ -15,14 +15,17 @@ from hi.apps.attribute.enums import AttributeType
from hi.apps.common.delayed_signal_processor import DelayedSignalProcessor
from hi.apps.common.singleton import Singleton
from hi.apps.common.module_utils import import_module_safe
+from hi.apps.entity.models import Entity
from hi.apps.system.health_status_provider import HealthStatusProvider
-from .enums import IntegrationAttributeType
+from .entity_operations import EntityIntegrationOperations
+from .enums import IntegrationAttributeType, IntegrationDisableMode
from .integration_data import IntegrationData
from .integration_gateway import IntegrationGateway
from .transient_models import IntegrationKey
from .models import Integration, IntegrationAttribute
from .transient_models import IntegrationMetaData
+from .user_data_detector import EntityUserDataDetector
logger = logging.getLogger(__name__)
@@ -42,6 +45,16 @@ class IntegrationManager( Singleton ):
self._monitor_event_loop = None
return
+ def reset_for_testing(self):
+ """
+ Reset the manager's in-memory state. Intended for use in tests only,
+ to provide isolation from singleton state that persists across test
+ methods (integration data map, monitor map).
+ """
+ self._integration_data_map.clear()
+ self._monitor_map.clear()
+ return
+
def get_integration_data_list( self, enabled_only = False ) -> List[ IntegrationData ]:
if enabled_only:
integration_data_list = [ x for x in self._integration_data_map.values() if x.is_enabled ]
@@ -340,20 +353,109 @@ class IntegrationManager( Singleton ):
with self._data_lock:
with transaction.atomic():
integration_data.integration.is_enabled = True
+ integration_data.integration.is_paused = False
integration_data.integration.save()
self.refresh_integrations_from_db()
self._launch_integration_monitor_task(
integration_data = integration_data,
)
return
-
- def disable_integration( self, integration_data : IntegrationData ):
+
+ def disable_integration( self,
+ integration_data : IntegrationData,
+ mode : IntegrationDisableMode = None ):
+ """
+ Remove an integration: stop monitors, handle attached entities per
+ mode, flip state flags. Configuration attributes (IntegrationAttribute
+ rows) are retained so a subsequent Configure can reuse them.
+
+ Mode semantics:
+ SAFE (default): delete entities without user-created data; preserve
+ entities with user-created data by detaching them from the
+ integration (via EntityIntegrationOperations.preserve_with_user_data).
+ Preserved entities get the '[Disconnected]' name prefix.
+
+ ALL: hard-delete all entities attached to this integration
+ regardless of user data.
+
+ Monitors are stopped first to avoid races with in-flight sync work.
+ """
+ if mode is None:
+ mode = IntegrationDisableMode.default()
+
with self._data_lock:
+ # Stop monitors before any entity changes to avoid races with
+ # in-flight sync work.
+ self._stop_integration_monitor( integration_data = integration_data )
+
+ integration_id = integration_data.integration_id
+
with transaction.atomic():
+ # Targeted entity set includes the integration's own entities
+ # plus any delegate entities that would be orphaned by their
+ # removal (e.g., the Area entity auto-created when a motion
+ # sensor was added to a view).
+ target_ids = EntityIntegrationOperations.get_removal_entity_ids(
+ integration_id = integration_id,
+ )
+ entities = list( Entity.objects.filter( id__in = target_ids ) )
+ if mode == IntegrationDisableMode.ALL:
+ for entity in entities:
+ entity.delete()
+ else: # SAFE
+ for entity in entities:
+ if EntityUserDataDetector.has_user_created_attributes( entity ):
+ EntityIntegrationOperations.preserve_with_user_data(
+ entity = entity,
+ integration_name = integration_id,
+ )
+ else:
+ entity.delete()
+
integration_data.integration.is_enabled = False
+ integration_data.integration.is_paused = False
+ integration_data.integration.save()
+ return
+
+ def pause_integration( self, integration_data : IntegrationData ):
+ """
+ Stop the integration's monitors while leaving is_enabled, entities,
+ and configuration intact. No-op if the integration is not enabled or
+ is already paused. The DB flag represents user intent: once set, a
+ failed monitor stop does not re-trigger on a subsequent pause call.
+ """
+ if not integration_data.integration.is_enabled:
+ return
+ if integration_data.integration.is_paused:
+ return
+ with self._data_lock:
+ with transaction.atomic():
+ integration_data.integration.is_paused = True
integration_data.integration.save()
+ self.refresh_integrations_from_db()
self._stop_integration_monitor( integration_data = integration_data )
return
+
+ def resume_integration( self, integration_data : IntegrationData ):
+ """
+ Relaunch the integration's monitors after a pause. No-op if the
+ integration is not enabled. Unlike pause, resume always attempts the
+ monitor launch regardless of the is_paused flag, so that a prior
+ failed launch can be retried by invoking resume again.
+ _launch_integration_monitor_task is idempotent when the monitor is
+ already running.
+ """
+ if not integration_data.integration.is_enabled:
+ return
+ with self._data_lock:
+ with transaction.atomic():
+ integration_data.integration.is_paused = False
+ integration_data.integration.save()
+ self.refresh_integrations_from_db()
+ self._launch_integration_monitor_task(
+ integration_data = integration_data,
+ )
+ return
def notify_integration_settings_changed(self):
"""
diff --git a/src/hi/integrations/migrations/0006_add_integration_is_paused.py b/src/hi/integrations/migrations/0006_add_integration_is_paused.py
new file mode 100644
index 00000000..dd62ae39
--- /dev/null
+++ b/src/hi/integrations/migrations/0006_add_integration_is_paused.py
@@ -0,0 +1,18 @@
+# Generated by Django 4.2.24 on 2026-04-23 15:10
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("integrations", "0005_add_integration_attribute_description"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="integration",
+ name="is_paused",
+ field=models.BooleanField(default=False, verbose_name="Paused?"),
+ ),
+ ]
diff --git a/src/hi/integrations/models.py b/src/hi/integrations/models.py
index 30ccaf50..8e756ceb 100644
--- a/src/hi/integrations/models.py
+++ b/src/hi/integrations/models.py
@@ -20,6 +20,10 @@ class Integration( models.Model ):
'Enabled?',
default = False,
)
+ is_paused = models.BooleanField(
+ 'Paused?',
+ default = False,
+ )
created_datetime = models.DateTimeField(
'Created',
auto_now_add = True,
diff --git a/src/hi/integrations/sync_mixins.py b/src/hi/integrations/sync_mixins.py
index e9d6ff5f..2d7050b2 100644
--- a/src/hi/integrations/sync_mixins.py
+++ b/src/hi/integrations/sync_mixins.py
@@ -7,13 +7,10 @@ particularly around intelligent entity deletion that preserves user data.
import logging
-from django.db import transaction
-
from hi.apps.common.processing_result import ProcessingResult
-from hi.apps.entity.models import Entity, EntityState
-from hi.apps.sense.models import Sensor
-from hi.apps.control.models import Controller
+from hi.apps.entity.models import Entity
+from .entity_operations import EntityIntegrationOperations
from .user_data_detector import EntityUserDataDetector
logger = logging.getLogger(__name__)
@@ -22,101 +19,29 @@ logger = logging.getLogger(__name__)
class IntegrationSyncMixin:
"""
Mixin providing common functionality for integration synchronization operations.
-
- This mixin provides intelligent entity deletion that preserves user-created
- data while removing integration-specific components.
+
+ Provides intelligent entity deletion that preserves user-created data
+ while removing integration-specific components.
"""
- def _remove_entity_intelligently(self,
- entity: Entity,
+ def _remove_entity_intelligently(self,
+ entity: Entity,
result: ProcessingResult,
integration_name: str):
"""
Remove an entity that no longer exists in the integration.
-
- If the entity has user-created attributes, preserve the entity but disconnect
- it from the integration and remove only integration-related components.
- Otherwise, perform complete deletion.
-
- Args:
- entity: The Entity to remove or preserve
- result: ProcessingResult to update with messages
- integration_name: Name of the integration (for logging)
+
+ If the entity has user-created attributes, preserve the entity but
+ disconnect it from the integration and remove only integration-related
+ components. Otherwise, perform complete deletion.
"""
if EntityUserDataDetector.has_user_created_attributes(entity):
- self._preserve_entity_with_user_data(entity, result, integration_name)
+ EntityIntegrationOperations.preserve_with_user_data(
+ entity = entity,
+ integration_name = integration_name,
+ result = result,
+ )
else:
# No user data, safe to delete completely
entity.delete() # Deletion cascades to all related data
result.message_list.append(f'Removed stale {integration_name} entity: {entity}')
-
- def _preserve_entity_with_user_data(self,
- entity: Entity,
- result: ProcessingResult,
- integration_name: str):
- """
- Preserve an entity with user-created data by disconnecting it from integration
- and removing only integration-related components.
-
- Args:
- entity: The Entity to preserve
- result: ProcessingResult to update with messages
- integration_name: Name of the integration (for logging)
- """
- original_name = entity.name
-
- # Get integration-related components to remove
- sensor_ids_to_remove = EntityUserDataDetector.get_integration_related_sensors(entity)
- controller_ids_to_remove = EntityUserDataDetector.get_integration_related_controllers(entity)
-
- # Get entity states that will become orphaned
- orphaned_state_ids = EntityUserDataDetector.get_orphaned_entity_states(
- entity, sensor_ids_to_remove, controller_ids_to_remove
- )
-
- with transaction.atomic():
- # Remove integration-related sensors
- if sensor_ids_to_remove:
- removed_sensor_count = Sensor.objects.filter(
- id__in=sensor_ids_to_remove
- ).delete()[0]
- logger.debug(f'Removed {removed_sensor_count} integration sensors for {entity}')
-
- # Remove integration-related controllers
- if controller_ids_to_remove:
- removed_controller_count = Controller.objects.filter(
- id__in=controller_ids_to_remove
- ).delete()[0]
- logger.debug(f'Removed {removed_controller_count} integration controllers for {entity}')
-
- # Remove orphaned entity states
- if orphaned_state_ids:
- removed_state_count = EntityState.objects.filter(
- id__in=orphaned_state_ids
- ).delete()[0]
- logger.debug(f'Removed {removed_state_count} orphaned entity states for {entity}')
-
- # Remove integration-related attributes (keep user-created ones).
- # Note: queryset .delete() intentionally bypasses the model-level
- # SoftDeleteAttributeModel.delete() override, performing a hard delete.
- # Integration attributes should not accumulate as soft-deleted records.
- removed_attr_count = entity.attributes.filter(
- integration_key_str__isnull=False
- ).delete()[0]
- if removed_attr_count:
- logger.debug(f'Removed {removed_attr_count} integration attributes for {entity}')
-
- # Disconnect entity from integration
- entity.integration_id = None
- entity.integration_name = None
-
- # Update name to indicate disconnected status
- if not entity.name.startswith('[Disconnected]'):
- entity.name = f'[Disconnected] {entity.name}'
-
- entity.save()
-
- result.message_list.append(
- f'Preserved {integration_name} entity "{original_name}" with user data, '
- f'disconnected from integration and renamed to "{entity.name}"'
- )
diff --git a/src/hi/integrations/templates/integrations/modals/integration_disable.html b/src/hi/integrations/templates/integrations/modals/integration_disable.html
index 8f1caf87..4f743034 100644
--- a/src/hi/integrations/templates/integrations/modals/integration_disable.html
+++ b/src/hi/integrations/templates/integrations/modals/integration_disable.html
@@ -1,30 +1,84 @@
-{% extends "modals/action_with_cancel.html" %}
+{% extends "modals/action_2_with_cancel.html" %}
+{% load icons %}
{% block header_class %}bg-secondary{% endblock %}
{% block preamble %}
<form action="{% url 'integrations_disable' integration_id=integration_data.integration_id %}"
- method="post" enctype="multipart/form-data"
+ method="post"
class="form" data-async="modal">
{% csrf_token %}
- {% endblock %}
-
- {% block title_text %}
- {{ integration_data.label }}
- {% endblock %}
-
- {% block body %}
- <h4>Disable {{ integration_data.label }} Integration?</h4>
-
- {% endblock %}
-
- {% block action_right %}
- <button id="hi-integration-disable" type="submit" class="btn btn-warning"
- name="action" value="enable">
- DISABLE
- </button>
- {% endblock %}
-
- {% block postamble %}
+{% endblock %}
+
+{% block title_text %}
+{{ integration_data.label }}
+{% endblock %}
+
+{% block body %}
+<h4>Remove {{ integration_data.label }} Integration?</h4>
+
+{% if removal_summary.total_count == 0 %}
+<p>This integration has no attached entities.</p>
+{% elif removal_summary.has_mixed_state %}
+<p>
+ This integration has <strong>{{ removal_summary.total_count }}</strong>
+ {% if removal_summary.total_count == 1 %}entity{% else %}entities{% endif %}.
+ <strong>{{ removal_summary.user_data_count }}</strong> of
+ {% if removal_summary.user_data_count == 1 %}them has{% else %}them have{% endif %}
+ custom data you've added.
+</p>
+<ul>
+ <li>
+ <strong>DELETE SAFE</strong> — delete the {{ removal_summary.deletable_count }}
+ {% if removal_summary.deletable_count == 1 %}entity{% else %}entities{% endif %}
+ without custom data, and preserve the {{ removal_summary.user_data_count }} with custom
+ data (disconnected from this integration, prefixed with
+ <code>[Disconnected]</code>, custom attributes and layout retained).
+ </li>
+ <li>
+ <strong>DELETE ALL</strong> — delete all {{ removal_summary.total_count }}
+ {% if removal_summary.total_count == 1 %}entity{% else %}entities{% endif %}
+ and all the custom data associated with these items.
+ You will not be able to recover the deleted custom data.
+ </li>
+</ul>
+{% else %}
+<p>
+ This integration has <strong>{{ removal_summary.total_count }}</strong>
+ {% if removal_summary.total_count == 1 %}entity{% else %}entities{% endif %}.
+ None have custom data you've added, so all will be deleted.
+</p>
+{% endif %}
+
+<p class="text-muted small">
+ Configuration values are retained. If you re-configure this integration
+ later, it will start fresh without reconnecting to any preserved entities.
+</p>
+{% endblock %}
+
+{% block action_center %}
+{% if removal_summary.has_mixed_state %}
+<button type="submit" class="btn btn-outline-danger ml-2"
+ name="mode" value="{{ disable_mode_all }}">
+ {% icon "warning" size="sm" css_class="hi-icon-left" %}DELETE ALL
+</button>
+{% endif %}
+{% endblock %}
+
+{% block action_right %}
+{% if removal_summary.has_mixed_state %}
+<button type="submit" class="btn btn-secondary"
+ name="mode" value="{{ disable_mode_safe }}">
+ {% icon "shield" size="sm" css_class="hi-icon-left" %}DELETE SAFE
+</button>
+{% else %}
+<button type="submit" class="btn btn-danger"
+ name="mode" value="{{ disable_mode_safe }}">
+ {% icon "delete" size="sm" css_class="hi-icon-left" %}DELETE
+</button>
+{% endif %}
+{% endblock %}
+
+{% block postamble %}
</form>
{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/modals/integrations_select.html b/src/hi/integrations/templates/integrations/modals/integrations_select.html
index f580b5fe..c8924826 100644
--- a/src/hi/integrations/templates/integrations/modals/integrations_select.html
+++ b/src/hi/integrations/templates/integrations/modals/integrations_select.html
@@ -19,13 +19,17 @@ Select Integrations
{{ integration_data.integration_metadata.label }}
</div>
<div class="col-3">
- {% if integration_data.integration.is_enabled %}
- <span class="text-weight-bold text-primary">
- {% icon "save" size="sm" css_class="hi-icon-left" %}ENABLED
+ {% if not integration_data.integration.is_enabled %}
+ <span class="text-muted">
+ {% icon "disabled" size="sm" css_class="hi-icon-left" %}Not configured
+ </span>
+ {% elif integration_data.integration.is_paused %}
+ <span class="text-weight-bold text-warning">
+ {% icon "pause" size="sm" css_class="hi-icon-left" %}Paused
</span>
{% else %}
- <span class="text-secondary">
- {% icon "eye-off" size="sm" css_class="hi-icon-left" %}DISABLED
+ <span class="text-weight-bold text-primary">
+ {% icon "check-circle" size="sm" css_class="hi-icon-left" %}Running
</span>
{% endif %}
</div>
@@ -33,14 +37,13 @@ Select Integrations
<div class="col-3">
{% if integration_data.integration.is_enabled %}
<a href="{% url 'integrations_disable' integration_id=integration_data.integration.integration_id %}"
- role="button" class="btn btn-secondary btn-control" data-async="modal">
- {% icon "eye-off" size="sm" css_class="hi-icon-left" %}DISABLE
+ role="button" class="btn btn-danger btn-control" data-async="modal">
+ {% icon "delete" size="sm" css_class="hi-icon-left" %}REMOVE
</a>
-
{% else %}
<a href="{% url 'integrations_enable' integration_id=integration_data.integration.integration_id %}"
class="btn btn-primary btn-control" role="button" data-async="modal">
- {% icon "eye" size="sm" css_class="hi-icon-left" %}ENABLE
+ {% icon "plug" size="sm" css_class="hi-icon-left" %}CONFIGURE
</a>
{% endif %}
</div>
diff --git a/src/hi/integrations/templates/integrations/pages/no_integrations.html b/src/hi/integrations/templates/integrations/pages/no_integrations.html
index b032fd9f..eaced5c3 100644
--- a/src/hi/integrations/templates/integrations/pages/no_integrations.html
+++ b/src/hi/integrations/templates/integrations/pages/no_integrations.html
@@ -1,13 +1,13 @@
{% extends "config/pages/config_base.html" %}
{% block config_content %}
<div class="alert alert-info text-center m-4">
- There are no integrations currently enabled.
+ There are no integrations currently configured.
</div>
<div class="text-center m-4 p-4">
<a class="btn btn-primary btn-lg" role="button"
href="{% url 'integrations_select' %}"
data-async="modal">
- ENABLE INTEGRATIONS
+ MANAGE INTEGRATIONS
</a>
-</div>
+</div>
{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/panes/lifecycle_actions.html b/src/hi/integrations/templates/integrations/panes/lifecycle_actions.html
new file mode 100644
index 00000000..4680f6ea
--- /dev/null
+++ b/src/hi/integrations/templates/integrations/panes/lifecycle_actions.html
@@ -0,0 +1,27 @@
+{% load icons %}
+{% comment %}
+ Shared Pause/Resume lifecycle actions fragment.
+
+ Integrations that have monitors and want to expose Pause/Resume controls
+ should include this fragment from their per-integration manage template
+ alongside any other integration-specific controls (e.g., SYNC). Rendering
+ is conditional on is_enabled so the control is hidden for not-yet-
+ configured integrations.
+{% endcomment %}
+{% if core.integration_data.is_enabled %}
+<form class="mr-2"
+ method="post"
+ action="{% if core.integration_data.is_paused %}{% url 'integrations_resume' integration_id=core.integration_data.integration_id %}{% else %}{% url 'integrations_pause' integration_id=core.integration_data.integration_id %}{% endif %}"
+ data-async="true">
+ {% csrf_token %}
+ {% if core.integration_data.is_paused %}
+ <button type="submit" class="btn btn-outline-primary">
+ {% icon "play" size="sm" css_class="hi-icon-left" %}RESUME
+ </button>
+ {% else %}
+ <button type="submit" class="btn btn-outline-secondary">
+ {% icon "pause" size="sm" css_class="hi-icon-left" %}PAUSE
+ </button>
+ {% endif %}
+</form>
+{% endif %}
diff --git a/src/hi/integrations/tests/test_entity_operations.py b/src/hi/integrations/tests/test_entity_operations.py
new file mode 100644
index 00000000..285d64ff
--- /dev/null
+++ b/src/hi/integrations/tests/test_entity_operations.py
@@ -0,0 +1,293 @@
+"""
+Unit tests for EntityIntegrationOperations.
+
+Only covers behavior that encodes real classification / transformation /
+graph-traversal logic. The preserve_with_user_data path is already tested
+indirectly via test_sync_mixins (which exercises _remove_entity_intelligently).
+"""
+
+import logging
+
+from django.test import TestCase
+
+from hi.apps.attribute.enums import AttributeType, AttributeValueType
+from hi.apps.entity.models import Entity, EntityAttribute, EntityState, EntityStateDelegation
+from hi.integrations.entity_operations import EntityIntegrationOperations
+
+logging.disable(logging.CRITICAL)
+
+
+class SummarizeForRemovalTests(TestCase):
+ """
+ summarize_for_removal classifies entities by whether they have
+ user-created attributes (attribute_type_str = CUSTOM). This test
+ exercises a mixed case — all other cases are subsumed.
+ """
+
+ INTEGRATION_ID = 'summary_test'
+
+ def _make_entity(self, name, user_attribute=False, integration_attribute=False):
+ entity = Entity.objects.create(
+ name=name,
+ entity_type_str='LIGHT',
+ integration_id=self.INTEGRATION_ID,
+ integration_name=f'device_{name}',
+ )
+ if user_attribute:
+ EntityAttribute.objects.create(
+ entity=entity,
+ name='User Note',
+ value='user-supplied',
+ value_type_str=str(AttributeValueType.TEXT),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ # integration_key_str left NULL → classified as user data
+ )
+ if integration_attribute:
+ EntityAttribute.objects.create(
+ entity=entity,
+ name='Integration Data',
+ value='from-integration',
+ value_type_str=str(AttributeValueType.TEXT),
+ attribute_type_str=str(AttributeType.PREDEFINED),
+ integration_key_str=f'{self.INTEGRATION_ID}:device_{name}',
+ )
+ return entity
+
+ def test_summary_counts_and_mixed_state(self):
+ # One integration-only, one user-data, one both, one bare (no attributes)
+ self._make_entity('only_integration', integration_attribute=True)
+ self._make_entity('only_user', user_attribute=True)
+ self._make_entity('both', user_attribute=True, integration_attribute=True)
+ self._make_entity('bare')
+
+ # Also create an entity in a DIFFERENT integration to verify filtering.
+ Entity.objects.create(
+ name='Other Integration',
+ entity_type_str='LIGHT',
+ integration_id='different_integration',
+ )
+
+ summary = EntityIntegrationOperations.summarize_for_removal(
+ integration_id=self.INTEGRATION_ID,
+ )
+
+ # Total includes only this integration's entities (4, not 5).
+ self.assertEqual(summary.total_count, 4)
+ # User-data entities are those with at least one CUSTOM-typed attribute.
+ # "bare" has no attributes at all → not user-data.
+ # "only_integration" has only PREDEFINED attributes → not user-data.
+ # "only_user" and "both" have at least one CUSTOM attribute → user-data.
+ self.assertEqual(summary.user_data_count, 2)
+ self.assertEqual(summary.deletable_count, 2)
+ self.assertTrue(summary.has_mixed_state)
+
+
+class CollectRemovalClosureTests(TestCase):
+ """
+ Pure graph-traversal tests for collect_removal_closure.
+
+ Each test constructs a small entity / state / delegation fixture and
+ asserts which entities end up in the closure given a seed set. The
+ function is integration-agnostic, so these tests work on raw IDs
+ rather than going through summarize_for_removal.
+ """
+
+ def _make_entity(self, label):
+ return Entity.objects.create(
+ name=label,
+ entity_type_str='LIGHT',
+ )
+
+ def _make_state(self, entity):
+ return EntityState.objects.create(
+ entity=entity,
+ entity_state_type_str='DISCRETE',
+ name=f'{entity.name} State',
+ )
+
+ def _delegate(self, principal_state, delegate_entity):
+ return EntityStateDelegation.objects.create(
+ entity_state=principal_state,
+ delegate_entity=delegate_entity,
+ )
+
+ def test_empty_seed_returns_empty_closure(self):
+ result = EntityIntegrationOperations.collect_removal_closure(set())
+ self.assertEqual(result, set())
+
+ def test_seed_with_no_delegations_is_unchanged(self):
+ a = self._make_entity('A')
+ b = self._make_entity('B')
+ result = EntityIntegrationOperations.collect_removal_closure({a.id, b.id})
+ self.assertEqual(result, {a.id, b.id})
+
+ def test_orphanable_delegate_is_added(self):
+ """Single principal whose state delegates to a delegate not pointed at by anyone else."""
+ principal = self._make_entity('Principal')
+ principal_state = self._make_state(principal)
+ delegate = self._make_entity('Delegate')
+ self._delegate(principal_state, delegate)
+
+ result = EntityIntegrationOperations.collect_removal_closure({principal.id})
+ self.assertEqual(result, {principal.id, delegate.id})
+
+ def test_shared_delegate_not_added_when_other_principal_remains(self):
+ """Delegate has two principals; only one is in the seed; delegate must remain."""
+ seeded_principal = self._make_entity('Seeded')
+ seeded_state = self._make_state(seeded_principal)
+ other_principal = self._make_entity('Other')
+ other_state = self._make_state(other_principal)
+ delegate = self._make_entity('SharedDelegate')
+ self._delegate(seeded_state, delegate)
+ self._delegate(other_state, delegate)
+
+ result = EntityIntegrationOperations.collect_removal_closure({seeded_principal.id})
+ self.assertEqual(result, {seeded_principal.id})
+ self.assertNotIn(delegate.id, result)
+
+ def test_shared_delegate_added_when_all_principals_in_seed(self):
+ """Delegate has two principals; both are in the seed; delegate is included."""
+ principal_a = self._make_entity('A')
+ state_a = self._make_state(principal_a)
+ principal_b = self._make_entity('B')
+ state_b = self._make_state(principal_b)
+ delegate = self._make_entity('Delegate')
+ self._delegate(state_a, delegate)
+ self._delegate(state_b, delegate)
+
+ result = EntityIntegrationOperations.collect_removal_closure({principal_a.id, principal_b.id})
+ self.assertEqual(result, {principal_a.id, principal_b.id, delegate.id})
+
+ def test_chained_delegations_are_walked(self):
+ """A's state delegates to B; B's state delegates to C — closure includes all three."""
+ a = self._make_entity('A')
+ a_state = self._make_state(a)
+ b = self._make_entity('B')
+ b_state = self._make_state(b)
+ c = self._make_entity('C')
+ self._delegate(a_state, b)
+ self._delegate(b_state, c)
+
+ result = EntityIntegrationOperations.collect_removal_closure({a.id})
+ self.assertEqual(result, {a.id, b.id, c.id})
+
+ def test_diamond_shape_is_walked(self):
+ """A delegates to B and C; both B and C delegate to D; closure is all four."""
+ a = self._make_entity('A')
+ a_state_left = self._make_state(a)
+ a_state_right = EntityState.objects.create(
+ entity=a, entity_state_type_str='DISCRETE', name='A Right State'
+ )
+ b = self._make_entity('B')
+ b_state = self._make_state(b)
+ c = self._make_entity('C')
+ c_state = self._make_state(c)
+ d = self._make_entity('D')
+ self._delegate(a_state_left, b)
+ self._delegate(a_state_right, c)
+ self._delegate(b_state, d)
+ self._delegate(c_state, d)
+
+ result = EntityIntegrationOperations.collect_removal_closure({a.id})
+ self.assertEqual(result, {a.id, b.id, c.id, d.id})
+
+ def test_chained_delegate_blocked_by_external_principal(self):
+ """A → B → C, but X also delegates to C — C must remain because X is outside the seed."""
+ a = self._make_entity('A')
+ a_state = self._make_state(a)
+ b = self._make_entity('B')
+ b_state = self._make_state(b)
+ c = self._make_entity('C')
+ x = self._make_entity('X')
+ x_state = self._make_state(x)
+ self._delegate(a_state, b)
+ self._delegate(b_state, c)
+ self._delegate(x_state, c)
+
+ result = EntityIntegrationOperations.collect_removal_closure({a.id})
+ # B has only A as principal → orphan-able. C has B and X as principals;
+ # X is not in seed → C must remain.
+ self.assertEqual(result, {a.id, b.id})
+
+ def test_cycle_is_handled(self):
+ """A's state delegates to B; B's state delegates to A. Seed {A} → closure {A, B}."""
+ a = self._make_entity('A')
+ a_state = self._make_state(a)
+ b = self._make_entity('B')
+ b_state = self._make_state(b)
+ self._delegate(a_state, b)
+ self._delegate(b_state, a)
+
+ result = EntityIntegrationOperations.collect_removal_closure({a.id})
+ self.assertEqual(result, {a.id, b.id})
+
+
+class PreserveWithUserDataFlagTests(TestCase):
+ """
+ Behavior the disconnected entity must satisfy after preservation:
+ user-management flags are restored so the entity behaves like any
+ other user-defined entity (deletable, can add custom attributes).
+ Integration converters initialize these flags to False to lock down
+ integration-managed entities; once disconnected, that lockdown no
+ longer applies.
+ """
+
+ def test_disconnected_entity_is_user_manageable(self):
+ entity = Entity.objects.create(
+ name='Locked Down',
+ entity_type_str='LIGHT',
+ integration_id='test_integration',
+ integration_name='locked_device',
+ can_user_delete=False,
+ can_add_custom_attributes=False,
+ )
+ # Has user data so it qualifies for preservation.
+ EntityAttribute.objects.create(
+ entity=entity,
+ name='User Note',
+ value='keep me',
+ value_type_str=str(AttributeValueType.TEXT),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ )
+
+ EntityIntegrationOperations.preserve_with_user_data(
+ entity=entity,
+ integration_name='test_integration',
+ )
+
+ entity.refresh_from_db()
+ self.assertIsNone(entity.integration_id)
+ self.assertTrue(entity.can_user_delete)
+ self.assertTrue(entity.can_add_custom_attributes)
+
+ def test_disconnected_entity_capabilities_are_suppressed(self):
+ """
+ After preservation, integration-backed capability flags are turned
+ off and the general is_disabled gate is set. This keeps the entity
+ out of capability-driven enumerations (e.g., the Cameras sidebar)
+ while the per-entity views still respect the raw flags.
+ """
+ entity = Entity.objects.create(
+ name='Camera With Notes',
+ entity_type_str='CAMERA',
+ integration_id='test_integration',
+ integration_name='camera_device',
+ has_video_stream=True,
+ is_disabled=False,
+ )
+ EntityAttribute.objects.create(
+ entity=entity,
+ name='User Note',
+ value='lens type X',
+ value_type_str=str(AttributeValueType.TEXT),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ )
+
+ EntityIntegrationOperations.preserve_with_user_data(
+ entity=entity,
+ integration_name='test_integration',
+ )
+
+ entity.refresh_from_db()
+ self.assertFalse(entity.has_video_stream)
+ self.assertTrue(entity.is_disabled)
diff --git a/src/hi/integrations/tests/test_integration_manager.py b/src/hi/integrations/tests/test_integration_manager.py
index c7ca2a68..808ff618 100644
--- a/src/hi/integrations/tests/test_integration_manager.py
+++ b/src/hi/integrations/tests/test_integration_manager.py
@@ -10,12 +10,13 @@ from unittest.mock import Mock, AsyncMock, patch
from django.test import TestCase
from hi.apps.attribute.enums import AttributeType, AttributeValueType
+from hi.apps.entity.models import Entity, EntityAttribute
from hi.integrations.integration_manager import IntegrationManager
from hi.integrations.integration_data import IntegrationData
from hi.integrations.integration_gateway import IntegrationGateway
from hi.integrations.models import Integration, IntegrationAttribute
from hi.integrations.transient_models import IntegrationMetaData, IntegrationKey
-from hi.integrations.enums import IntegrationAttributeType
+from hi.integrations.enums import IntegrationAttributeType, IntegrationDisableMode
logging.disable(logging.CRITICAL)
@@ -406,7 +407,7 @@ class IntegrationManagerTestCase(TestCase):
manager = IntegrationManager()
# Clear any existing data to start clean
- manager._integration_data_map.clear()
+ manager.reset_for_testing()
results = []
errors = []
@@ -566,29 +567,249 @@ class IntegrationManagerTestCase(TestCase):
def test_disable_integration_database_transaction(self):
"""Test disable integration with database transaction and monitor stop."""
manager = IntegrationManager()
-
+
integration = Integration.objects.create(
integration_id='test_integration',
- is_enabled=True
+ is_enabled=True,
+ is_paused=True,
)
-
+
gateway = MockIntegrationGateway('test_integration')
data = IntegrationData(
integration_gateway=gateway,
integration=integration
)
-
+
with patch.object(manager, '_stop_integration_monitor') as mock_stop:
# Call disable
manager.disable_integration(data)
-
+
# Verify database changes
integration.refresh_from_db()
self.assertFalse(integration.is_enabled)
-
+ # Disable also clears is_paused so a subsequent Configure starts clean.
+ self.assertFalse(integration.is_paused)
+
# Verify monitor was stopped
mock_stop.assert_called_once_with(integration_data=data)
+ def _make_integration_with_entities(self, integration_id, include_user_data_entity):
+ """
+ Fixture helper: create an integration with two attached entities —
+ one integration-only (no user data) and optionally one with
+ user-created attributes. Also creates retained IntegrationAttribute
+ rows to verify config retention on disable.
+ """
+ integration = Integration.objects.create(
+ integration_id=integration_id,
+ is_enabled=True,
+ is_paused=False,
+ )
+ # Retained configuration attributes (should survive disable).
+ IntegrationAttribute.objects.create(
+ integration=integration,
+ name='API URL',
+ value='http://example.com',
+ value_type_str=str(AttributeValueType.TEXT),
+ attribute_type_str=str(AttributeType.PREDEFINED),
+ )
+
+ integration_only_entity = Entity.objects.create(
+ name='Integration Only Entity',
+ entity_type_str='LIGHT',
+ integration_id=integration_id,
+ integration_name='device_no_user_data',
+ )
+ EntityAttribute.objects.create(
+ entity=integration_only_entity,
+ name='Integration Config',
+ value='from integration',
+ value_type_str=str(AttributeValueType.TEXT),
+ attribute_type_str=str(AttributeType.PREDEFINED),
+ integration_key_str=f'{integration_id}:device_no_user_data',
+ )
+
+ user_data_entity = None
+ if include_user_data_entity:
+ user_data_entity = Entity.objects.create(
+ name='User Data Entity',
+ entity_type_str='LIGHT',
+ integration_id=integration_id,
+ integration_name='device_with_user_data',
+ )
+ EntityAttribute.objects.create(
+ entity=user_data_entity,
+ name='User Note',
+ value='user-supplied note',
+ value_type_str=str(AttributeValueType.TEXT),
+ attribute_type_str=str(AttributeType.CUSTOM),
+ )
+
+ gateway = MockIntegrationGateway(integration_id)
+ data = IntegrationData(integration_gateway=gateway, integration=integration)
+ return integration, data, integration_only_entity, user_data_entity
+
+ def test_disable_integration_safe_mode_splits_entities_by_user_data(self):
+ """SAFE mode deletes no-user-data entities and preserves user-data entities."""
+ manager = IntegrationManager()
+ manager.reset_for_testing()
+
+ integration, data, integration_only_entity, user_data_entity = (
+ self._make_integration_with_entities('disable_safe_test', include_user_data_entity=True)
+ )
+ no_user_id = integration_only_entity.id
+ user_data_id = user_data_entity.id
+
+ with patch.object(manager, '_stop_integration_monitor'):
+ manager.disable_integration(data, mode=IntegrationDisableMode.SAFE)
+
+ # Integration-only entity is gone.
+ self.assertFalse(Entity.objects.filter(id=no_user_id).exists())
+ # User-data entity survives and is disconnected (integration_id cleared).
+ preserved = Entity.objects.get(id=user_data_id)
+ self.assertIsNone(preserved.integration_id)
+ self.assertTrue(preserved.name.startswith('[Disconnected]'))
+
+ # Configuration attributes retained for re-Configure.
+ self.assertEqual(integration.attributes.count(), 1)
+
+ def test_disable_integration_all_mode_deletes_everything(self):
+ """ALL mode hard-deletes every attached entity regardless of user data."""
+ manager = IntegrationManager()
+ manager.reset_for_testing()
+
+ integration, data, integration_only_entity, user_data_entity = (
+ self._make_integration_with_entities('disable_all_test', include_user_data_entity=True)
+ )
+ no_user_id = integration_only_entity.id
+ user_data_id = user_data_entity.id
+
+ with patch.object(manager, '_stop_integration_monitor'):
+ manager.disable_integration(data, mode=IntegrationDisableMode.ALL)
+
+ self.assertFalse(Entity.objects.filter(id=no_user_id).exists())
+ self.assertFalse(Entity.objects.filter(id=user_data_id).exists())
+
+ # Configuration attributes retained even when entities all deleted.
+ self.assertEqual(integration.attributes.count(), 1)
+
+ def test_disable_integration_stops_monitor_before_entity_changes(self):
+ """Monitors must stop before any entity mutation to avoid races with sync."""
+ manager = IntegrationManager()
+ manager.reset_for_testing()
+
+ _integration, data, integration_only_entity, _ = (
+ self._make_integration_with_entities('disable_order_test', include_user_data_entity=False)
+ )
+ entity_id = integration_only_entity.id
+
+ call_order = []
+
+ def record_stop(**_kwargs):
+ # At the moment the monitor is stopped, the entity must still exist.
+ call_order.append(('stop', Entity.objects.filter(id=entity_id).exists()))
+
+ def record_entity_delete_observer(sender, instance, **_kwargs):
+ if instance.id == entity_id:
+ call_order.append(('entity_delete', instance.id))
+
+ from django.db.models.signals import pre_delete
+ pre_delete.connect(record_entity_delete_observer, sender=Entity)
+ try:
+ with patch.object(manager, '_stop_integration_monitor', side_effect=record_stop):
+ manager.disable_integration(data, mode=IntegrationDisableMode.SAFE)
+ finally:
+ pre_delete.disconnect(record_entity_delete_observer, sender=Entity)
+
+ self.assertEqual(call_order[0][0], 'stop')
+ self.assertTrue(call_order[0][1], 'Entity should still exist when stop is called')
+ self.assertTrue(any(event[0] == 'entity_delete' for event in call_order))
+
+ def test_pause_integration_noop_when_not_enabled(self):
+ """Pause on a not-enabled integration is a no-op (no DB write, no stop)."""
+ manager = IntegrationManager()
+ manager.reset_for_testing()
+
+ integration = Integration.objects.create(
+ integration_id='pause_noop_test',
+ is_enabled=False,
+ is_paused=False,
+ )
+ gateway = MockIntegrationGateway('pause_noop_test')
+ data = IntegrationData(integration_gateway=gateway, integration=integration)
+
+ with patch.object(manager, '_stop_integration_monitor') as mock_stop:
+ manager.pause_integration(data)
+
+ integration.refresh_from_db()
+ self.assertFalse(integration.is_enabled)
+ self.assertFalse(integration.is_paused)
+ mock_stop.assert_not_called()
+
+ def test_pause_integration_noop_when_already_paused(self):
+ """Pause on an already-paused integration is a no-op."""
+ manager = IntegrationManager()
+ manager.reset_for_testing()
+
+ integration = Integration.objects.create(
+ integration_id='pause_already_test',
+ is_enabled=True,
+ is_paused=True,
+ )
+ gateway = MockIntegrationGateway('pause_already_test')
+ data = IntegrationData(integration_gateway=gateway, integration=integration)
+
+ with patch.object(manager, '_stop_integration_monitor') as mock_stop:
+ manager.pause_integration(data)
+
+ integration.refresh_from_db()
+ self.assertTrue(integration.is_paused)
+ mock_stop.assert_not_called()
+
+ def test_resume_integration_noop_when_not_enabled(self):
+ """Resume on a not-enabled integration is a no-op."""
+ manager = IntegrationManager()
+ manager.reset_for_testing()
+
+ integration = Integration.objects.create(
+ integration_id='resume_noop_test',
+ is_enabled=False,
+ is_paused=False,
+ )
+ gateway = MockIntegrationGateway('resume_noop_test')
+ data = IntegrationData(integration_gateway=gateway, integration=integration)
+
+ with patch.object(manager, '_launch_integration_monitor_task') as mock_launch:
+ manager.resume_integration(data)
+
+ integration.refresh_from_db()
+ self.assertFalse(integration.is_enabled)
+ mock_launch.assert_not_called()
+
+ def test_resume_integration_retries_launch_when_not_paused(self):
+ """Resume always attempts the launch even when is_paused is already False.
+
+ This allows the user to recover from a prior failed launch by invoking
+ resume again. _launch_integration_monitor_task is idempotent when the
+ monitor is already running.
+ """
+ manager = IntegrationManager()
+ manager.reset_for_testing()
+
+ integration = Integration.objects.create(
+ integration_id='resume_retry_test',
+ is_enabled=True,
+ is_paused=False,
+ )
+ gateway = MockIntegrationGateway('resume_retry_test')
+ data = IntegrationData(integration_gateway=gateway, integration=integration)
+
+ with patch.object(manager, '_launch_integration_monitor_task') as mock_launch:
+ manager.resume_integration(data)
+
+ mock_launch.assert_called_once_with(integration_data=data)
+
+
def test_data_lock_thread_safety_during_attribute_creation(self):
"""Test thread safety of attribute creation operations."""
# Note: This test verifies the presence of thread safety mechanisms
diff --git a/src/hi/integrations/tests/test_models.py b/src/hi/integrations/tests/test_models.py
index 6ae33346..2d976fef 100644
--- a/src/hi/integrations/tests/test_models.py
+++ b/src/hi/integrations/tests/test_models.py
@@ -78,7 +78,7 @@ class IntegrationModelTestCase(TestCase):
integration = Integration.objects.create(
integration_id='default_test'
)
-
+
# Should default to False
self.assertFalse(integration.is_enabled)
diff --git a/src/hi/integrations/tests/test_sync_mixins.py b/src/hi/integrations/tests/test_sync_mixins.py
index b2124a83..8804c639 100644
--- a/src/hi/integrations/tests/test_sync_mixins.py
+++ b/src/hi/integrations/tests/test_sync_mixins.py
@@ -6,6 +6,7 @@ import logging
from django.test import TestCase, TransactionTestCase
+from hi.apps.attribute.enums import AttributeType
from hi.apps.entity.models import Entity, EntityAttribute, EntityState
from hi.apps.sense.models import Sensor
from hi.apps.control.models import Controller
@@ -51,7 +52,7 @@ class IntegrationSyncMixinTestCase(TestCase):
name='Integration Data',
value='Integration-specific data',
value_type_str='TEXT',
- attribute_type_str='CONFIGURATION',
+ attribute_type_str=str(AttributeType.PREDEFINED),
integration_key_str='test_integration:test_device_1'
)
@@ -92,7 +93,7 @@ class IntegrationSyncMixinTestCase(TestCase):
name='User Note',
value='This is a user note',
value_type_str='TEXT',
- attribute_type_str='DOCUMENTATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
# integration_key_str is None (user-created)
)
@@ -102,7 +103,7 @@ class IntegrationSyncMixinTestCase(TestCase):
name='Integration Data',
value='Integration data',
value_type_str='TEXT',
- attribute_type_str='CONFIGURATION',
+ attribute_type_str=str(AttributeType.PREDEFINED),
integration_key_str='test_integration:test_device_1'
)
@@ -191,7 +192,7 @@ class IntegrationSyncMixinTestCase(TestCase):
name='User Note',
value='User note',
value_type_str='TEXT',
- attribute_type_str='DOCUMENTATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
)
# Create integration sensor
@@ -239,7 +240,7 @@ class IntegrationSyncMixinTestCase(TestCase):
name='User Note',
value='User note',
value_type_str='TEXT',
- attribute_type_str='DOCUMENTATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
)
# Call the method
@@ -262,7 +263,7 @@ class IntegrationSyncMixinTestCase(TestCase):
name='User Note',
value='User note',
value_type_str='TEXT',
- attribute_type_str='DOCUMENTATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
)
# Create second entity state
@@ -328,7 +329,7 @@ class IntegrationSyncMixinTestCase(TestCase):
name='Integration Data',
value='Some data',
value_type_str='TEXT',
- attribute_type_str='CONFIGURATION',
+ attribute_type_str=str(AttributeType.PREDEFINED),
integration_key_str='test_integration:test_device_1'
)
@@ -363,7 +364,7 @@ class IntegrationSyncMixinTestCase(TestCase):
name='User Note',
value='Important note',
value_type_str='TEXT',
- attribute_type_str='DOCUMENTATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
)
# Call the method
@@ -388,7 +389,7 @@ class IntegrationSyncMixinTestCase(TestCase):
name=f'Integration Config {i}',
value=f'Config value {i}',
value_type_str='TEXT',
- attribute_type_str='CONFIGURATION',
+ attribute_type_str=str(AttributeType.PREDEFINED),
integration_key_str=f'test_integration:config_{i}'
)
integration_attrs.append(attr)
@@ -399,7 +400,7 @@ class IntegrationSyncMixinTestCase(TestCase):
name='User Documentation',
value='User-created note',
value_type_str='TEXT',
- attribute_type_str='DOCUMENTATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
)
# Call the method
@@ -480,7 +481,7 @@ class IntegrationSyncMixinTestCase(TestCase):
name='User Note',
value='User note',
value_type_str='TEXT',
- attribute_type_str='DOCUMENTATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
)
# Call the method
@@ -552,7 +553,7 @@ class IntegrationSyncMixinTestCase(TestCase):
name='Config 1',
value='Value 1',
value_type_str='TEXT',
- attribute_type_str='CONFIGURATION',
+ attribute_type_str=str(AttributeType.PREDEFINED),
integration_key_str='test_integration:config_1'
)
@@ -561,7 +562,7 @@ class IntegrationSyncMixinTestCase(TestCase):
name='Config 2',
value='Value 2',
value_type_str='TEXT',
- attribute_type_str='CONFIGURATION',
+ attribute_type_str=str(AttributeType.PREDEFINED),
integration_key_str='test_integration:config_2'
)
@@ -602,7 +603,7 @@ class IntegrationSyncMixinTestCase(TestCase):
name='User Note',
value='User note',
value_type_str='TEXT',
- attribute_type_str='DOCUMENTATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
)
# Call the method
@@ -657,7 +658,7 @@ class IntegrationSyncMixinTransactionTestCase(TransactionTestCase):
name='User Note',
value='Critical user note',
value_type_str='TEXT',
- attribute_type_str='DOCUMENTATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
)
# Create complex state structure
@@ -696,7 +697,7 @@ class IntegrationSyncMixinTransactionTestCase(TransactionTestCase):
name='Integration Config',
value='Config data',
value_type_str='TEXT',
- attribute_type_str='CONFIGURATION',
+ attribute_type_str=str(AttributeType.PREDEFINED),
integration_key_str='test_integration:config_1'
)
@@ -755,7 +756,7 @@ class IntegrationSyncMixinTransactionTestCase(TransactionTestCase):
name='User Note',
value='User note',
value_type_str='TEXT',
- attribute_type_str='DOCUMENTATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
)
# Create integration sensor that will be orphaned (state will be deleted)
@@ -849,7 +850,7 @@ class IntegrationSyncMixinTransactionTestCase(TransactionTestCase):
name='Integration Config',
value='Config value',
value_type_str='TEXT',
- attribute_type_str='CONFIGURATION',
+ attribute_type_str=str(AttributeType.PREDEFINED),
integration_key_str='test_integration:device_2'
)
@@ -876,7 +877,7 @@ class IntegrationSyncMixinTransactionTestCase(TransactionTestCase):
name='Integration Config',
value='Config value',
value_type_str='TEXT',
- attribute_type_str='CONFIGURATION',
+ attribute_type_str=str(AttributeType.PREDEFINED),
integration_key_str='test_integration:device_3'
)
@@ -886,7 +887,7 @@ class IntegrationSyncMixinTransactionTestCase(TransactionTestCase):
name='User Comment',
value='User added this',
value_type_str='TEXT',
- attribute_type_str='DOCUMENTATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
# No integration_key_str - user created
)
@@ -954,7 +955,7 @@ class IntegrationSyncMixinTransactionTestCase(TransactionTestCase):
name='User Note',
value='Important user data',
value_type_str='TEXT',
- attribute_type_str='DOCUMENTATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
)
# Store IDs for verification
@@ -1036,7 +1037,7 @@ class IntegrationSyncMixinTransactionTestCase(TransactionTestCase):
name='User Data',
value='User value',
value_type_str='TEXT',
- attribute_type_str='DOCUMENTATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
)
# Create fresh result for each test
diff --git a/src/hi/integrations/tests/test_user_data_detector.py b/src/hi/integrations/tests/test_user_data_detector.py
index b170e17c..1a9d5ac6 100644
--- a/src/hi/integrations/tests/test_user_data_detector.py
+++ b/src/hi/integrations/tests/test_user_data_detector.py
@@ -7,6 +7,7 @@ import logging
from django.test import TestCase
from django.db import IntegrityError
+from hi.apps.attribute.enums import AttributeType
from hi.apps.entity.models import Entity, EntityAttribute, EntityState
from hi.apps.sense.models import Sensor
from hi.apps.control.models import Controller
@@ -47,7 +48,7 @@ class EntityUserDataDetectorTestCase(TestCase):
name='User Note',
value='This is a user note',
value_type_str='TEXT',
- attribute_type_str='DOCUMENTATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
# integration_key_str is None (user-created)
)
@@ -73,7 +74,7 @@ class EntityUserDataDetectorTestCase(TestCase):
name='Integration Data',
value='Integration-specific data',
value_type_str='TEXT',
- attribute_type_str='CONFIGURATION',
+ attribute_type_str=str(AttributeType.PREDEFINED),
integration_key_str='test_integration:test_device_1'
)
@@ -109,7 +110,7 @@ class EntityUserDataDetectorTestCase(TestCase):
name='User Note',
value='User data',
value_type_str='TEXT',
- attribute_type_str='DOCUMENTATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
# integration_key_str is None (user-created)
)
integration_attr = EntityAttribute.objects.create(
@@ -117,7 +118,7 @@ class EntityUserDataDetectorTestCase(TestCase):
name='Integration Data',
value='Integration data',
value_type_str='TEXT',
- attribute_type_str='CONFIGURATION',
+ attribute_type_str=str(AttributeType.PREDEFINED),
integration_key_str='test_integration:test_device_1'
)
@@ -375,14 +376,14 @@ class EntityUserDataDetectorTestCase(TestCase):
name='User Note 1',
value='First note',
value_type_str='TEXT',
- attribute_type_str='DOCUMENTATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
)
attr2 = EntityAttribute.objects.create(
entity=self.entity,
name='User Note 2',
value='Second note',
value_type_str='TEXT',
- attribute_type_str='CONFIGURATION'
+ attribute_type_str=str(AttributeType.CUSTOM)
)
result = EntityUserDataDetector.has_user_created_attributes(self.entity)
@@ -509,7 +510,7 @@ class EntityUserDataDetectorTestCase(TestCase):
name=f'Test Attr {key}',
value='test value',
value_type_str='TEXT',
- attribute_type_str='CONFIGURATION',
+ attribute_type_str=str(AttributeType.PREDEFINED),
integration_key_str=key
)
diff --git a/src/hi/integrations/tests/test_views.py b/src/hi/integrations/tests/test_views.py
new file mode 100644
index 00000000..4ff9cf5e
--- /dev/null
+++ b/src/hi/integrations/tests/test_views.py
@@ -0,0 +1,186 @@
+"""
+View tests for Integration lifecycle actions.
+"""
+
+import logging
+from unittest.mock import Mock, patch
+
+from django.urls import reverse
+
+from hi.apps.attribute.enums import AttributeValueType
+from hi.integrations.enums import IntegrationAttributeType, IntegrationDisableMode
+from hi.integrations.integration_data import IntegrationData
+from hi.integrations.integration_gateway import IntegrationGateway
+from hi.integrations.integration_manager import IntegrationManager
+from hi.integrations.models import Integration
+from hi.integrations.transient_models import IntegrationMetaData
+from hi.testing.view_test_base import SyncViewTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class _PauseResumeTestAttributeType(IntegrationAttributeType):
+ TEST_ATTR = ('Test Attribute', 'Test description', AttributeValueType.TEXT, {}, True, True, 'default')
+
+
+class _PauseResumeTestGateway(IntegrationGateway):
+
+ def __init__(self, integration_id='pause_resume_view_test'):
+ self.integration_id = integration_id
+
+ def get_metadata(self):
+ return IntegrationMetaData(
+ integration_id=self.integration_id,
+ label='Pause/Resume Test Integration',
+ attribute_type=_PauseResumeTestAttributeType,
+ allow_entity_deletion=True,
+ )
+
+ def get_manage_view_pane(self):
+ return Mock()
+
+ def get_monitor(self):
+ return Mock()
+
+ def get_controller(self):
+ return Mock()
+
+
+class PauseResumeViewTests(SyncViewTestCase):
+ """
+ View tests for the Pause and Resume lifecycle actions.
+
+ Only covers behavior that encodes app-critical decisions:
+ - The view delegates to the correct manager method.
+ - The is_enabled guard prevents pause/resume on a not-enabled integration.
+ """
+
+ def setUp(self):
+ super().setUp()
+ IntegrationManager().reset_for_testing()
+
+ self.integration = Integration.objects.create(
+ integration_id='pause_resume_view_test',
+ is_enabled=True,
+ is_paused=False,
+ )
+ self.integration_data = IntegrationData(
+ integration_gateway=_PauseResumeTestGateway('pause_resume_view_test'),
+ integration=self.integration,
+ )
+ IntegrationManager()._integration_data_map['pause_resume_view_test'] = self.integration_data
+
+ def test_pause_view_delegates_to_manager(self):
+ url = reverse('integrations_pause', kwargs={'integration_id': 'pause_resume_view_test'})
+ with patch.object(IntegrationManager, 'pause_integration') as mock_pause:
+ response = self.client.post(url)
+
+ self.assertSuccessResponse(response)
+ mock_pause.assert_called_once()
+ call_kwargs = mock_pause.call_args.kwargs
+ self.assertEqual(call_kwargs['integration_data'].integration_id, 'pause_resume_view_test')
+
+ def test_resume_view_delegates_to_manager(self):
+ url = reverse('integrations_resume', kwargs={'integration_id': 'pause_resume_view_test'})
+ with patch.object(IntegrationManager, 'resume_integration') as mock_resume:
+ response = self.client.post(url)
+
+ self.assertSuccessResponse(response)
+ mock_resume.assert_called_once()
+ call_kwargs = mock_resume.call_args.kwargs
+ self.assertEqual(call_kwargs['integration_data'].integration_id, 'pause_resume_view_test')
+
+ def test_pause_view_rejects_not_enabled_integration(self):
+ self.integration.is_enabled = False
+ self.integration.save()
+
+ url = reverse('integrations_pause', kwargs={'integration_id': 'pause_resume_view_test'})
+ with patch.object(IntegrationManager, 'pause_integration') as mock_pause:
+ response = self.client.post(url)
+
+ self.assertErrorResponse(response)
+ mock_pause.assert_not_called()
+
+ def test_resume_view_rejects_not_enabled_integration(self):
+ self.integration.is_enabled = False
+ self.integration.save()
+
+ url = reverse('integrations_resume', kwargs={'integration_id': 'pause_resume_view_test'})
+ with patch.object(IntegrationManager, 'resume_integration') as mock_resume:
+ response = self.client.post(url)
+
+ self.assertErrorResponse(response)
+ mock_resume.assert_not_called()
+
+
+class RemoveViewTests(SyncViewTestCase):
+ """
+ View tests for the Remove confirmation dialog.
+
+ Covers behavior that encodes real decisions:
+ - POST dispatches the correct IntegrationDisableMode to the manager.
+ - Missing/invalid mode falls back to SAFE (form-facing safety default).
+ - Not-enabled integrations are rejected.
+ """
+
+ INTEGRATION_ID = 'remove_view_test'
+
+ def setUp(self):
+ super().setUp()
+ IntegrationManager().reset_for_testing()
+
+ self.integration = Integration.objects.create(
+ integration_id=self.INTEGRATION_ID,
+ is_enabled=True,
+ is_paused=False,
+ )
+ integration_data = IntegrationData(
+ integration_gateway=_PauseResumeTestGateway(self.INTEGRATION_ID),
+ integration=self.integration,
+ )
+ IntegrationManager()._integration_data_map[self.INTEGRATION_ID] = integration_data
+
+ def _url(self):
+ return reverse('integrations_disable', kwargs={'integration_id': self.INTEGRATION_ID})
+
+ def test_post_with_mode_safe_dispatches_safe(self):
+ with patch.object(IntegrationManager, 'disable_integration') as mock_disable:
+ response = self.client.post(self._url(), {'mode': IntegrationDisableMode.SAFE.name})
+
+ self.assertSuccessResponse(response)
+ mock_disable.assert_called_once()
+ self.assertEqual(mock_disable.call_args.kwargs['mode'], IntegrationDisableMode.SAFE)
+
+ def test_post_with_mode_all_dispatches_all(self):
+ with patch.object(IntegrationManager, 'disable_integration') as mock_disable:
+ response = self.client.post(self._url(), {'mode': IntegrationDisableMode.ALL.name})
+
+ self.assertSuccessResponse(response)
+ mock_disable.assert_called_once()
+ self.assertEqual(mock_disable.call_args.kwargs['mode'], IntegrationDisableMode.ALL)
+
+ def test_post_with_missing_mode_defaults_to_safe(self):
+ """Tampered / missing mode must not escalate to ALL."""
+ with patch.object(IntegrationManager, 'disable_integration') as mock_disable:
+ response = self.client.post(self._url(), {})
+
+ self.assertSuccessResponse(response)
+ self.assertEqual(mock_disable.call_args.kwargs['mode'], IntegrationDisableMode.SAFE)
+
+ def test_post_with_unknown_mode_defaults_to_safe(self):
+ """Tampered / unknown mode must not escalate to ALL."""
+ with patch.object(IntegrationManager, 'disable_integration') as mock_disable:
+ response = self.client.post(self._url(), {'mode': 'NUKE'})
+
+ self.assertSuccessResponse(response)
+ self.assertEqual(mock_disable.call_args.kwargs['mode'], IntegrationDisableMode.SAFE)
+
+ def test_post_rejects_not_enabled_integration(self):
+ self.integration.is_enabled = False
+ self.integration.save()
+
+ with patch.object(IntegrationManager, 'disable_integration') as mock_disable:
+ response = self.client.post(self._url(), {'mode': IntegrationDisableMode.SAFE.name})
+
+ self.assertErrorResponse(response)
+ mock_disable.assert_not_called()
diff --git a/src/hi/integrations/transient_models.py b/src/hi/integrations/transient_models.py
index 38319194..eb371d9e 100644
--- a/src/hi/integrations/transient_models.py
+++ b/src/hi/integrations/transient_models.py
@@ -78,6 +78,31 @@ class IntegrationDetails:
payload : Optional[Dict] = None
+@dataclass
+class IntegrationRemovalSummary:
+ """
+ Classification of an integration's attached entities for the Remove
+ confirmation dialog. Raw counts only; derived values are properties so
+ the object stays consistent.
+ """
+
+ total_count: int
+ user_data_count: int
+
+ @property
+ def deletable_count(self) -> int:
+ return self.total_count - self.user_data_count
+
+ @property
+ def has_mixed_state(self) -> bool:
+ """
+ True when at least one entity has user data. Drives the dialog
+ decision between a single DELETE action and the DELETE SAFE /
+ DELETE ALL variants.
+ """
+ return self.user_data_count > 0
+
+
@dataclass
class IntegrationValidationResult:
"""Result from integration configuration validation."""
diff --git a/src/hi/integrations/urls.py b/src/hi/integrations/urls.py
index 8a98188e..534b533c 100644
--- a/src/hi/integrations/urls.py
+++ b/src/hi/integrations/urls.py
@@ -19,11 +19,19 @@ urlpatterns = [
views.IntegrationEnableView.as_view(),
name='integrations_enable' ),
- re_path( r'^disable/(?P<integration_id>[\w\-]+)$',
- views.IntegrationDisableView.as_view(),
+ re_path( r'^disable/(?P<integration_id>[\w\-]+)$',
+ views.IntegrationDisableView.as_view(),
name='integrations_disable' ),
- re_path( r'^health/(?P<integration_id>[\w\-]+)$',
+ re_path( r'^pause/(?P<integration_id>[\w\-]+)$',
+ views.IntegrationPauseView.as_view(),
+ name='integrations_pause' ),
+
+ re_path( r'^resume/(?P<integration_id>[\w\-]+)$',
+ views.IntegrationResumeView.as_view(),
+ name='integrations_resume' ),
+
+ re_path( r'^health/(?P<integration_id>[\w\-]+)$',
views.IntegrationHealthStatusView.as_view(),
name='integrations_health_status' ),
diff --git a/src/hi/integrations/user_data_detector.py b/src/hi/integrations/user_data_detector.py
index 00168761..587447e4 100644
--- a/src/hi/integrations/user_data_detector.py
+++ b/src/hi/integrations/user_data_detector.py
@@ -9,6 +9,7 @@ All methods are purely analytical and perform no database operations.
import logging
from typing import Set
+from hi.apps.attribute.enums import AttributeType
from hi.apps.entity.models import Entity
logger = logging.getLogger(__name__)
@@ -28,26 +29,32 @@ class EntityUserDataDetector:
def has_user_created_attributes(entity: Entity) -> bool:
"""
Check if an entity has user-created attributes that justify preservation.
-
- This is the primary decision criteria for whether to preserve an entity
- during integration sync deletion. Only user-created attributes (those
- without integration_key_str) are considered significant enough to preserve
- the entire entity.
-
+
+ Provenance is determined by ``attribute_type_str``:
+ - ``AttributeType.CUSTOM`` → user-added via the UI.
+ - ``AttributeType.PREDEFINED`` → defined by the system or by an
+ integration's converter.
+
+ ``integration_key_str`` is *not* a provenance signal — it is an
+ optional per-attribute upstream backreference some integrations
+ (e.g., HomeBox) use for fine-grained sync, and is absent for
+ integration-created attributes that have no per-field upstream id
+ (e.g., HA's synthesized Insteon-address attribute).
+
Args:
entity: The Entity to check for user-created attributes
-
+
Returns:
True if the entity has user-created attributes, False otherwise
"""
user_attributes = entity.attributes.filter(
- integration_key_str__isnull=True
+ attribute_type_str=str(AttributeType.CUSTOM),
).exists()
-
+
if user_attributes:
logger.debug(f'Entity {entity} has user-created attributes - should be preserved')
return True
-
+
logger.debug(f'Entity {entity} has no user-created attributes - can be deleted')
return False
diff --git a/src/hi/integrations/views.py b/src/hi/integrations/views.py
index c3a86e8e..d1b65b1c 100644
--- a/src/hi/integrations/views.py
+++ b/src/hi/integrations/views.py
@@ -4,6 +4,7 @@ from django.core.exceptions import BadRequest
from django.urls import reverse
from django.views.generic import View
+from hi.apps.common import antinode
from hi.exceptions import ForceRedirectException
from hi.hi_async_view import HiModalView
from hi.views import page_not_found_response
@@ -13,6 +14,8 @@ from hi.apps.attribute.view_mixins import AttributeEditViewMixin
from hi.apps.config.enums import ConfigPageType
from hi.apps.config.views import ConfigPageView
+from .entity_operations import EntityIntegrationOperations
+from .enums import IntegrationDisableMode
from .integration_attribute_edit_context import IntegrationAttributeItemEditContext
from .integration_manager import IntegrationManager
from .models import IntegrationAttribute
@@ -83,7 +86,7 @@ class IntegrationEnableView( HiModalView, IntegrationViewMixin, AttributeEditVie
)
if integration_data.integration.is_enabled:
- raise BadRequest( f'{integration_data.label} is already enabled' )
+ raise BadRequest( f'{integration_data.label} is already configured' )
integration_manager.ensure_all_attributes_exist(
integration_metadata = integration_data.integration_metadata,
@@ -91,10 +94,10 @@ class IntegrationEnableView( HiModalView, IntegrationViewMixin, AttributeEditVie
)
attr_item_context = IntegrationAttributeItemEditContext(
integration_data = integration_data,
- update_button_label = 'ENABLE',
+ update_button_label = 'CONFIGURE',
suppress_history = True,
show_secrets = True,
-
+
)
template_context = self.create_initial_template_context(
attr_item_context= attr_item_context,
@@ -108,11 +111,11 @@ class IntegrationEnableView( HiModalView, IntegrationViewMixin, AttributeEditVie
integration_id = integration_id,
)
if integration_data.integration.is_enabled:
- raise BadRequest( f'{integration_data.label} is already enabled' )
+ raise BadRequest( f'{integration_data.label} is already configured' )
attr_item_context = IntegrationAttributeItemEditContext(
integration_data = integration_data,
- update_button_label = 'ENABLE',
+ update_button_label = 'CONFIGURE',
suppress_history = True,
show_secrets = True,
)
@@ -140,44 +143,89 @@ class IntegrationEnableView( HiModalView, IntegrationViewMixin, AttributeEditVie
self.validate_attributes_extra_helper(
attr_item_context,
regular_attributes_formset,
- error_title = 'Cannot enable integration.' )
+ error_title = 'Cannot configure integration.' )
return
class IntegrationDisableView( HiModalView, IntegrationViewMixin ):
+ """
+ Remove confirmation dialog. Classifies attached entities on GET to
+ decide between a single DELETE action (no user-data entities exist) or
+ DELETE SAFE / DELETE ALL variants (some entities have user-added data).
+ POST dispatches to disable_integration with the chosen mode.
+ """
def get_template_name( self ) -> str:
return 'integrations/modals/integration_disable.html'
def get(self, request, *args, **kwargs):
- integration_id = kwargs.get('integration_id')
- integration_data = self.get_integration_data(
- integration_id = integration_id,
+ integration_data = self._get_validated_integration_data( kwargs )
+ context = self._build_remove_context( integration_data )
+ return self.modal_response( request, context )
+
+ def post(self, request, *args, **kwargs):
+ integration_data = self._get_validated_integration_data( kwargs )
+ mode = IntegrationDisableMode.from_name_safe( request.POST.get('mode', '') )
+ IntegrationManager().disable_integration(
+ integration_data = integration_data,
+ mode = mode,
)
+ redirect_url = reverse( 'integrations_home' )
+ return self.redirect_response( request, redirect_url )
+
+ def _get_validated_integration_data(self, kwargs):
+ integration_id = kwargs.get('integration_id')
+ integration_data = self.get_integration_data( integration_id = integration_id )
if not integration_data.integration.is_enabled:
- raise BadRequest( f'{integration_data.label} is already disabled' )
+ raise BadRequest( f'{integration_data.label} is not configured' )
+ return integration_data
- context = {
+ def _build_remove_context(self, integration_data):
+ summary = EntityIntegrationOperations.summarize_for_removal(
+ integration_id = integration_data.integration_id,
+ )
+ return {
'integration_data': integration_data,
+ 'removal_summary': summary,
+ 'disable_mode_safe': IntegrationDisableMode.SAFE.name,
+ 'disable_mode_all': IntegrationDisableMode.ALL.name,
}
- return self.modal_response( request, context )
+
+class IntegrationPauseView( View, IntegrationViewMixin ):
+
def post(self, request, *args, **kwargs):
- integration_manager = IntegrationManager()
integration_id = kwargs.get('integration_id')
integration_data = self.get_integration_data(
integration_id = integration_id,
)
if not integration_data.integration.is_enabled:
- raise BadRequest( f'{integration_data.label} is already disabled' )
+ raise BadRequest( f'{integration_data.label} integration is not configured' )
- integration_manager.disable_integration(
- integration_data = integration_data,
+ IntegrationManager().pause_integration( integration_data = integration_data )
+
+ redirect_url = reverse( 'integrations_manage',
+ kwargs = { 'integration_id': integration_id } )
+ return antinode.redirect_response( redirect_url )
+
+
+class IntegrationResumeView( View, IntegrationViewMixin ):
+
+ def post(self, request, *args, **kwargs):
+ integration_id = kwargs.get('integration_id')
+ integration_data = self.get_integration_data(
+ integration_id = integration_id,
)
- redirect_url = reverse( 'integrations_home' )
- return self.redirect_response( request, redirect_url )
+ if not integration_data.integration.is_enabled:
+ raise BadRequest( f'{integration_data.label} integration is not configured' )
+
+ IntegrationManager().resume_integration( integration_data = integration_data )
+
+ redirect_url = reverse( 'integrations_manage',
+ kwargs = { 'integration_id': integration_id } )
+ return antinode.redirect_response( redirect_url )
+
-
class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEditViewMixin ):
def config_page_type(self) -> ConfigPageType:
@@ -198,7 +246,7 @@ class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEdit
integration_data = integration_manager.get_default_integration_data()
if not integration_data.integration.is_enabled:
- raise BadRequest( f'{integration_data.label} integration is not enabled' )
+ raise BadRequest( f'{integration_data.label} integration is not configured' )
# Get health status from the integration gateway
health_status_provider = integration_data.integration_gateway.get_health_status_provider()
@@ -245,7 +293,7 @@ class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEdit
integration_data = integration_manager.get_default_integration_data()
if not integration_data.integration.is_enabled:
- raise BadRequest( f'{integration_data.label} integration is not enabled' )
+ raise BadRequest( f'{integration_data.label} integration is not configured' )
# Get health status from the integration gateway
health_status_provider = integration_data.integration_gateway.get_health_status_provider()
diff --git a/src/hi/services/hass/templates/hass/panes/hass_manage.html b/src/hi/services/hass/templates/hass/panes/hass_manage.html
index bb137c77..f12658ed 100644
--- a/src/hi/services/hass/templates/hass/panes/hass_manage.html
+++ b/src/hi/services/hass/templates/hass/panes/hass_manage.html
@@ -7,7 +7,8 @@
alt="{{ core.integration_data.integration_metadata.label }} Logo">
{{ core.integration_data.integration_metadata.label }}
</div>
- <div class="">
+ <div class="d-flex">
+ {% include "integrations/panes/lifecycle_actions.html" %}
<form action="{% url 'hass_sync' %}"
method="POST" role="form" data-async="true">
{% csrf_token %}
diff --git a/src/hi/services/homebox/hb_client.py b/src/hi/services/homebox/hb_client.py
index 1f59224a..f6b03add 100644
--- a/src/hi/services/homebox/hb_client.py
+++ b/src/hi/services/homebox/hb_client.py
@@ -78,15 +78,23 @@ class HbClient:
return response.json()
return response
+ def get_items_summary(self) -> List[Dict[str, Any]]:
+ """
+ Fetches just the items summary list (one API call). Does not fetch
+ per-item details. Suitable for lightweight reachability /
+ health-check probes where only the count or IDs are needed.
+ """
+ url_list = f"{self._api_url}/{self.API_VERSION}/items"
+ data = self._make_request('GET', url_list)
+ return data.get('items', []) if isinstance(data, dict) else data
+
def get_items(self) -> List[HbItem]:
"""
Fetches the list of items and, for each one, fetches the full details.
Returns a list of fully populated HbItem objects.
"""
- url_list = f"{self._api_url}/{self.API_VERSION}/items"
- data = self._make_request('GET', url_list)
- items_summary = data.get('items', []) if isinstance(data, dict) else data
-
+ items_summary = self.get_items_summary()
+
full_items = []
for summary in items_summary:
item_id = summary.get('id')
@@ -97,7 +105,7 @@ class HbClient:
full_items.append(HbItem(api_dict=item_detail, client=self))
except Exception as e:
logger.error(f"Error fetching details for item {item_id}: {e}")
-
+
return full_items
def download_attachment(self, item_id: str, attachment_id: str) -> Optional[Dict[str, Any]]:
diff --git a/src/hi/services/homebox/hb_manager.py b/src/hi/services/homebox/hb_manager.py
index a066791a..3477887f 100644
--- a/src/hi/services/homebox/hb_manager.py
+++ b/src/hi/services/homebox/hb_manager.py
@@ -157,6 +157,25 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatus
self.fetch_hb_items_from_api,
thread_sensitive = True,
)(verbose=verbose)
+
+ def fetch_hb_items_summary_from_api( self ) -> list:
+ """
+ Lightweight one-call probe used by the monitor's reachability
+ heartbeat. Returns the items summary list (no per-item detail
+ fetches) or an empty list if the client is unavailable.
+ """
+ if not self.hb_client:
+ logger.warning('HomeBox client not available - cannot fetch items summary')
+ return []
+
+ with self.api_call_context( 'hb_items_summary' ):
+ return self.hb_client.get_items_summary()
+
+ async def fetch_hb_items_summary_from_api_async( self ) -> list:
+ return await sync_to_async(
+ self.fetch_hb_items_summary_from_api,
+ thread_sensitive = True,
+ )()
def test_connection(self) -> bool:
try:
diff --git a/src/hi/services/homebox/monitors.py b/src/hi/services/homebox/monitors.py
index 76455fd9..5f7dc095 100644
--- a/src/hi/services/homebox/monitors.py
+++ b/src/hi/services/homebox/monitors.py
@@ -9,9 +9,15 @@ logger = logging.getLogger(__name__)
class HomeBoxMonitor( PeriodicMonitor, HomeBoxMixin ):
+ """
+ HomeBox does not have real-time per-item state to poll. The monitor's
+ only job is a periodic reachability/health probe so the integration's
+ health status reflects whether the API is currently reachable. Entity
+ creation/update/removal happens only via user-initiated SYNC.
+ """
MONITOR_ID = 'hi.services.homebox.monitor'
- HOMEBOX_POLLING_INTERVAL_SECS = 30
+ HOMEBOX_POLLING_INTERVAL_SECS = 300
HOMEBOX_API_TIMEOUT_SECS = 20.0
def __init__( self ):
@@ -61,15 +67,19 @@ class HomeBoxMonitor( PeriodicMonitor, HomeBoxMixin ):
self.record_error( 'No manager found.' )
return
- item_list = await self._process_items( hb_manager )
+ item_count = await self._check_api_reachable( hb_manager )
- message = (
- f'Processed HomeBox resources. '
- f'items={len(item_list)}'
- )
+ message = f'HomeBox API reachable. items={item_count}'
self.record_healthy( message )
hb_manager.record_healthy( message )
return
- async def _process_items(self, hb_manager):
- return await hb_manager.fetch_hb_items_from_api_async( verbose = False )
+ async def _check_api_reachable(self, hb_manager) -> int:
+ """
+ Lightweight reachability probe: hits the items summary endpoint
+ (one API call, no per-item detail fetches) and returns the count.
+ The count is informational; the probe's purpose is to confirm
+ the API is up and authentication is still valid.
+ """
+ item_list = await hb_manager.fetch_hb_items_summary_from_api_async()
+ return len(item_list)
diff --git a/src/hi/services/homebox/templates/homebox/panes/hb_manage.html b/src/hi/services/homebox/templates/homebox/panes/hb_manage.html
index 149cd29c..fbaad1c4 100644
--- a/src/hi/services/homebox/templates/homebox/panes/hb_manage.html
+++ b/src/hi/services/homebox/templates/homebox/panes/hb_manage.html
@@ -8,7 +8,8 @@
alt="{{ core.integration_data.integration_metadata.label }} Logo">
{{ core.integration_data.integration_metadata.label }}
</div>
- <div class="">
+ <div class="d-flex">
+ {% include "integrations/panes/lifecycle_actions.html" %}
<form action="{% url 'hb_sync' %}"
method="POST" role="form" data-async="true">
{% csrf_token %}
diff --git a/src/hi/services/zoneminder/templates/zoneminder/panes/zm_manage.html b/src/hi/services/zoneminder/templates/zoneminder/panes/zm_manage.html
index 44377224..7d5b36b3 100644
--- a/src/hi/services/zoneminder/templates/zoneminder/panes/zm_manage.html
+++ b/src/hi/services/zoneminder/templates/zoneminder/panes/zm_manage.html
@@ -8,7 +8,8 @@
alt="{{ core.integration_data.integration_metadata.label }} Logo">
{{ core.integration_data.integration_metadata.label }}
</div>
- <div class="">
+ <div class="d-flex">
+ {% include "integrations/panes/lifecycle_actions.html" %}
<form action="{% url 'zm_sync' %}"
method="POST" role="form" data-async="">
{% csrf_token %}
diff --git a/src/hi/settings/simulator.py b/src/hi/settings/simulator.py
index b8364130..0b684c88 100644
--- a/src/hi/settings/simulator.py
+++ b/src/hi/settings/simulator.py
@@ -15,6 +15,7 @@ INSTALLED_APPS = [
'hi.apps.common',
'hi.simulator',
'hi.simulator.services.hass',
+ 'hi.simulator.services.homebox',
'hi.simulator.services.zoneminder',
]
diff --git a/src/hi/simulator/services/hass/api/urls.py b/src/hi/simulator/services/hass/api/urls.py
index 702ebeed..4ac557ee 100644
--- a/src/hi/simulator/services/hass/api/urls.py
+++ b/src/hi/simulator/services/hass/api/urls.py
@@ -3,7 +3,7 @@ from django.urls import re_path
from . import views
urlpatterns = [
-
+
re_path( r'^states$',
views.AllStatesView.as_view(),
name = 'hass_api_states' ),
@@ -11,4 +11,8 @@ urlpatterns = [
re_path( r'^states/(?P<entity_id>[\w\._\-]+)$',
views.StateView.as_view(),
name = 'hass_api_states_set' ),
+
+ re_path( r'^services/(?P<domain>[\w_]+)/(?P<service>[\w_]+)$',
+ views.ServiceCallView.as_view(),
+ name = 'hass_api_service_call' ),
]
diff --git a/src/hi/simulator/services/hass/api/views.py b/src/hi/simulator/services/hass/api/views.py
index 49218357..833f5c1f 100644
--- a/src/hi/simulator/services/hass/api/views.py
+++ b/src/hi/simulator/services/hass/api/views.py
@@ -12,6 +12,20 @@ from hi.simulator.services.hass.simulator import HassSimulator
logger = logging.getLogger(__name__)
+# Service-call mapping for the limited set of entity types the simulator
+# supports (switches, outlets, dimmer light switches). Keys are
+# (domain, service) tuples; values are the target state value the
+# simulator should set on the addressed entity.
+#
+# Sensors (motion, open/close) are read-only and accept no service calls.
+_SUPPORTED_SERVICES = {
+ ( 'switch', 'turn_on' ): 'on',
+ ( 'switch', 'turn_off' ): 'off',
+ ( 'light', 'turn_on' ): 'on',
+ ( 'light', 'turn_off' ): 'off',
+}
+
+
class AllStatesView( View ):
def get(self, request, *args, **kwargs):
@@ -24,7 +38,7 @@ class AllStatesView( View ):
logger.exception( 'Problem processing HAss states API request', e )
return JsonResponse( list(), safe = False )
-
+
@method_decorator(csrf_exempt, name='dispatch')
class StateView( View ):
@@ -43,10 +57,81 @@ class StateView( View ):
value_str = value_str,
)
return JsonResponse( sim_state.to_api_dict(), safe = False )
-
+
except json.JSONDecodeError as jde:
raise BadRequest( f'Request body is not JSON: {jde}' )
except KeyError as ke:
raise BadRequest( f'Unknown HAss state: {ke}' )
-
+
+
+@method_decorator(csrf_exempt, name='dispatch')
+class ServiceCallView( View ):
+ """
+ Handles HAss service calls:
+ POST /api/services/<domain>/<service>
+
+ Mirrors the real Home Assistant REST API (see
+ https://developers.home-assistant.io/docs/api/rest/#post-apiservicesdomainservice).
+ The response is a JSON list of state objects for the entities that
+ were changed.
+
+ Only the services emitted by Home Information's HAss controller for
+ the hard-coded simulator entity types (switch/light turn_on/turn_off)
+ are supported. Brightness data on light.turn_on is accepted but not
+ modeled — the simulator's dimmer states are ON_OFF only.
+ """
+
+ def post(self, request, *args, **kwargs):
+ try:
+ domain = kwargs.get('domain')
+ service = kwargs.get('service')
+
+ try:
+ data = json.loads( request.body ) if request.body else dict()
+ except json.JSONDecodeError as jde:
+ raise BadRequest( f'Request body is not JSON: {jde}' )
+
+ target_state = _SUPPORTED_SERVICES.get( (domain, service) )
+ if target_state is None:
+ logger.warning( f'Unsupported HAss service: {domain}.{service}' )
+ return JsonResponse(
+ { 'message': f'Service {domain}.{service} not supported by simulator' },
+ status = 400,
+ )
+
+ entity_id_field = data.get('entity_id')
+ if not entity_id_field:
+ raise BadRequest( '"entity_id" is required in service call body.' )
+ if isinstance( entity_id_field, list ):
+ entity_id_list = entity_id_field
+ else:
+ entity_id_list = [ entity_id_field ]
+
+ hass_simulator = HassSimulator()
+ changed_states = list()
+ for hass_entity_id in entity_id_list:
+ try:
+ sim_state = hass_simulator.set_sim_state_by_hass_entity_id(
+ hass_entity_id = hass_entity_id,
+ value_str = target_state,
+ )
+ changed_states.append( sim_state.to_api_dict() )
+ except KeyError:
+ # Real HA silently no-ops on unknown entity_ids in
+ # service calls; mirror that behavior.
+ logger.warning( f'HAss entity not found: {hass_entity_id}' )
+ continue
+
+ logger.debug(
+ f'HAss service call: {domain}.{service} on {entity_id_list} '
+ f'-> {target_state} ({len(changed_states)} changed)'
+ )
+ return JsonResponse( changed_states, safe = False )
+
+ except BadRequest:
+ raise
+
+ except Exception as e:
+ logger.exception( 'Problem processing HAss service call', e )
+ return JsonResponse( list(), safe = False )
diff --git a/src/hi/simulator/services/homebox/__init__.py b/src/hi/simulator/services/homebox/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/simulator/services/homebox/api/__init__.py b/src/hi/simulator/services/homebox/api/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/simulator/services/homebox/api/urls.py b/src/hi/simulator/services/homebox/api/urls.py
new file mode 100644
index 00000000..45d3ac96
--- /dev/null
+++ b/src/hi/simulator/services/homebox/api/urls.py
@@ -0,0 +1,18 @@
+from django.urls import re_path
+
+from . import views
+
+urlpatterns = [
+
+ re_path( r'^v1/users/login$',
+ views.LoginView.as_view(),
+ name = 'homebox_api_login' ),
+
+ re_path( r'^v1/items$',
+ views.AllItemsView.as_view(),
+ name = 'homebox_api_items' ),
+
+ re_path( r'^v1/items/(?P<item_id>[\w\-]+)$',
+ views.ItemDetailView.as_view(),
+ name = 'homebox_api_item_detail' ),
+]
diff --git a/src/hi/simulator/services/homebox/api/views.py b/src/hi/simulator/services/homebox/api/views.py
new file mode 100644
index 00000000..5ce75a10
--- /dev/null
+++ b/src/hi/simulator/services/homebox/api/views.py
@@ -0,0 +1,75 @@
+"""
+Emulated HomeBox REST API endpoints.
+
+Mirrors the subset of the real HomeBox API consumed by the main app's
+HomeBox integration:
+ - POST /v1/users/login
+ - GET /v1/items
+ - GET /v1/items/<id>
+
+The login endpoint accepts any credentials and returns a fixed token. The
+token is not validated on subsequent requests. Both the request body
+shapes and the response shapes match the real HomeBox API closely enough
+for the integration's HbItem parser to consume them unchanged.
+"""
+
+import logging
+
+from django.http import JsonResponse
+from django.utils.decorators import method_decorator
+from django.views.decorators.csrf import csrf_exempt
+from django.views.generic import View
+
+from hi.simulator.services.homebox.sim_models import build_item_api_dict
+from hi.simulator.services.homebox.simulator import HomeBoxSimulator
+
+logger = logging.getLogger(__name__)
+
+
+# Static token returned by the simulator's login endpoint. Not validated
+# on subsequent requests; the simulator simply ignores the Authorization
+# header.
+_STATIC_SIM_TOKEN = 'simulator-token'
+
+
+@method_decorator(csrf_exempt, name='dispatch')
+class LoginView( View ):
+
+ def post(self, request, *args, **kwargs):
+ return JsonResponse( { 'token': _STATIC_SIM_TOKEN } )
+
+
+class AllItemsView( View ):
+
+ def get(self, request, *args, **kwargs):
+ try:
+ simulator = HomeBoxSimulator()
+ items = [
+ build_item_api_dict(
+ sim_entity_id = sim_entity_id,
+ fields = fields,
+ archived_state = archived_state,
+ )
+ for ( sim_entity_id, fields, archived_state )
+ in simulator.get_sim_entity_pairs()
+ ]
+ return JsonResponse( { 'items': items } )
+
+ except Exception as e:
+ logger.exception( 'Problem processing HomeBox items list', e )
+ return JsonResponse( { 'items': [] } )
+
+
+class ItemDetailView( View ):
+
+ def get(self, request, *args, **kwargs):
+ item_id = kwargs.get('item_id')
+ simulator = HomeBoxSimulator()
+ for ( sim_entity_id, fields, archived_state ) in simulator.get_sim_entity_pairs():
+ if str(sim_entity_id) == item_id:
+ return JsonResponse( build_item_api_dict(
+ sim_entity_id = sim_entity_id,
+ fields = fields,
+ archived_state = archived_state,
+ ))
+ return JsonResponse( { 'message': f'Item {item_id} not found' }, status = 404 )
diff --git a/src/hi/simulator/services/homebox/apps.py b/src/hi/simulator/services/homebox/apps.py
new file mode 100644
index 00000000..9c2327d4
--- /dev/null
+++ b/src/hi/simulator/services/homebox/apps.py
@@ -0,0 +1,6 @@
+from django.apps import AppConfig
+
+
+class HomeBoxConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "hi.simulator.services.homebox"
diff --git a/src/hi/simulator/services/homebox/migrations/__init__.py b/src/hi/simulator/services/homebox/migrations/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/simulator/services/homebox/sim_models.py b/src/hi/simulator/services/homebox/sim_models.py
new file mode 100644
index 00000000..28228e10
--- /dev/null
+++ b/src/hi/simulator/services/homebox/sim_models.py
@@ -0,0 +1,100 @@
+"""
+HomeBox simulator entity and state definitions.
+
+The simulator's "HomeBox Inventory Item" entity represents a single inventory
+item as exposed by the real HomeBox REST API. Item metadata is stored in
+HomeBoxInventoryItemFields (persisted via DbSimEntity); the only mutable
+runtime state is the ``archived`` flag.
+
+The to_api_dict helper builds the JSON shape the integration's HbItem parser
+(src/hi/services/homebox/hb_models.py) consumes.
+"""
+
+from dataclasses import dataclass
+from typing import Any, Dict, List
+
+import hi.apps.common.datetimeproxy as datetimeproxy
+from hi.apps.common.utils import str_to_bool
+
+from hi.simulator.base_models import SimEntityFields, SimState, SimEntityDefinition
+from hi.simulator.enums import SimEntityType, SimStateType
+
+
+@dataclass( frozen = True )
+class HomeBoxInventoryItemFields( SimEntityFields ):
+ """ User-editable metadata for a simulated HomeBox inventory item. """
+
+ description : str = ''
+ serial_number : str = ''
+ model_number : str = ''
+ manufacturer : str = ''
+ notes : str = ''
+ quantity : int = 1
+
+
+@dataclass
+class HomeBoxItemArchivedState( SimState ):
+ """
+ Single mutable state per item: the archived flag (boolean).
+
+ Stored as a string ('on'/'off') consistent with how SimStateType.ON_OFF
+ is rendered in the simulator UI; converted to a real boolean in the API
+ response.
+ """
+
+ sim_entity_fields : HomeBoxInventoryItemFields
+ sim_state_type : SimStateType = SimStateType.ON_OFF
+ sim_state_id : str = 'archived'
+ value : str = 'off'
+
+ @property
+ def name(self):
+ return f'{self.sim_entity_fields.name} Is Archived?'
+
+ @property
+ def is_archived(self) -> bool:
+ return str_to_bool( self.value )
+
+
+HOMEBOX_SIM_ENTITY_DEFINITION_LIST: List[SimEntityDefinition] = [
+ SimEntityDefinition(
+ class_label = 'HomeBox Inventory Item',
+ sim_entity_type = SimEntityType.OTHER,
+ sim_entity_fields_class = HomeBoxInventoryItemFields,
+ sim_state_class_list = [
+ HomeBoxItemArchivedState,
+ ],
+ ),
+]
+
+
+def build_item_api_dict( sim_entity_id : int,
+ fields : HomeBoxInventoryItemFields,
+ archived_state : HomeBoxItemArchivedState ) -> Dict[ str, Any ]:
+ """
+ Build the HomeBox item JSON shape returned by the simulator's API,
+ matching the fields the integration's HbItem parser consumes.
+
+ Fields not in the simulator's scope (custom fields, attachments,
+ location, labels) are emitted as empty/null. Timestamps are emitted
+ as the current time on every call; the integration uses them only
+ for change detection.
+ """
+ now_iso = datetimeproxy.now().isoformat()
+ return {
+ 'id' : str(sim_entity_id),
+ 'name' : fields.name,
+ 'description' : fields.description,
+ 'serialNumber' : fields.serial_number,
+ 'modelNumber' : fields.model_number,
+ 'manufacturer' : fields.manufacturer,
+ 'notes' : fields.notes,
+ 'quantity' : fields.quantity,
+ 'archived' : archived_state.is_archived,
+ 'fields' : [],
+ 'attachments' : [],
+ 'location' : None,
+ 'labels' : [],
+ 'createdAt' : now_iso,
+ 'updatedAt' : now_iso,
+ }
diff --git a/src/hi/simulator/services/homebox/simulator.py b/src/hi/simulator/services/homebox/simulator.py
new file mode 100644
index 00000000..3f8ada86
--- /dev/null
+++ b/src/hi/simulator/services/homebox/simulator.py
@@ -0,0 +1,40 @@
+from typing import List
+
+from hi.simulator.base_models import SimEntityDefinition
+from hi.simulator.simulator import Simulator
+
+from .sim_models import (
+ HOMEBOX_SIM_ENTITY_DEFINITION_LIST,
+ HomeBoxInventoryItemFields,
+ HomeBoxItemArchivedState,
+)
+
+
+class HomeBoxSimulator( Simulator ):
+
+ @property
+ def id(self):
+ return 'hb'
+
+ @property
+ def label(self):
+ return 'HomeBox'
+
+ @property
+ def sim_entity_definition_list(self) -> List[ SimEntityDefinition ]:
+ return HOMEBOX_SIM_ENTITY_DEFINITION_LIST
+
+ def get_sim_entity_pairs(self):
+ """
+ Iterate (sim_entity_id, fields, archived_state) tuples for every
+ configured HomeBox inventory item in the active profile. Used by
+ the API views to build item responses.
+ """
+ for sim_entity in self._sim_entity_map.values():
+ fields = sim_entity.sim_entity_fields
+ if not isinstance( fields, HomeBoxInventoryItemFields ):
+ continue
+ archived_state = sim_entity._sim_state_map.get( 'archived' )
+ if not isinstance( archived_state, HomeBoxItemArchivedState ):
+ continue
+ yield ( sim_entity.id, fields, archived_state )
diff --git a/src/hi/simulator/services/homebox/urls.py b/src/hi/simulator/services/homebox/urls.py
new file mode 100644
index 00000000..54c7f1ca
--- /dev/null
+++ b/src/hi/simulator/services/homebox/urls.py
@@ -0,0 +1,12 @@
+from django.urls import include, re_path
+
+from . import views
+
+urlpatterns = [
+
+ re_path( r'^$',
+ views.HomeView.as_view(),
+ name = 'homebox_home' ),
+
+ re_path( r'^api/', include('hi.simulator.services.homebox.api.urls' )),
+]
diff --git a/src/hi/simulator/services/homebox/views.py b/src/hi/simulator/services/homebox/views.py
new file mode 100644
index 00000000..0327d135
--- /dev/null
+++ b/src/hi/simulator/services/homebox/views.py
@@ -0,0 +1,7 @@
+from django.views.generic import View
+
+
+class HomeView( View ):
+
+ def get(self, request, *args, **kwargs):
+ pass
diff --git a/src/hi/templates/icons/pause.html b/src/hi/templates/icons/pause.html
new file mode 100644
index 00000000..dc5f4803
--- /dev/null
+++ b/src/hi/templates/icons/pause.html
@@ -0,0 +1,4 @@
+<svg class="{{ class_attr }}" viewBox="0 0 24 24" fill="currentColor" {{ accessibility_attrs }}>
+ <rect x="6" y="5" width="4" height="14" rx="1"/>
+ <rect x="14" y="5" width="4" height="14" rx="1"/>
+</svg>