Home Information - Your home, your data, organized.
Python
Integration platform tweaks (2026-05-06) (#293)
Tony C4536980dd7eb
diff --git a/src/hi/apps/attribute/edit_context.py b/src/hi/apps/attribute/edit_context.pyindex 6a139b41..785df364 100644--- a/src/hi/apps/attribute/edit_context.py+++ b/src/hi/apps/attribute/edit_context.py@@ -262,6 +262,18 @@ class AttributeItemEditContext( AttributePageEditContext ):@propertydef add_attribute_disabled_message(self) -> str:return ''++ @property+ def externally_managed_message(self) -> str:+ """Operator-facing notice rendered in the action bar's+ UPDATE-button slot when the surface has no UPDATE action+ (i.e., ``can_add_custom_attributes`` is False on the owner).+ Returns an empty string by default; owner contexts override+ to enable the notice. The template only renders the notice+ when UPDATE is hidden, so an owner can return a non-empty+ value here without worrying about duplication on the normal+ editable surface."""+ return ''def to_template_context(self) -> Dict[str, Any]:template_context = super().to_template_context()diff --git a/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html b/src/hi/apps/attribute/templates/attribute/components/edit_content_body.htmlindex da27365f..47836ab9 100644--- a/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html+++ b/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html@@ -45,16 +45,31 @@ by using the AttributeItemEditContext pattern.<div class="{{ DIVID.ATTR_V2_ACTION_BAR_CONTENT_CLASS }}"><!-- Left Side: UPDATE button and vertically stacked message areas --><div class="attr-v2-action-bar-left">- <button id="{{ attr_page_context.update_button_html_id }}"- type="submit"+ {% if attr_item_context.can_add_custom_attributes %}+ <button id="{{ attr_page_context.update_button_html_id }}"+ type="submit"class="btn btn-outline-primary d-inline-flex align-items-center {{ DIVID.ATTR_V2_UPDATE_BTN_CLASS }}"- name="action"+ name="action"value="update">{% icon "save" size="sm" css_class="hi-icon-left" %}{{ attr_page_context.update_button_label }}</button>+ {% elif attr_item_context.externally_managed_message %}+ <div class="attr-v2-externally-managed text-muted small d-inline-flex align-items-center">+ {% icon "info-circle" size="sm" css_class="hi-icon-left" %}+ {{ attr_item_context.externally_managed_message }}+ </div>+ {% endif %}{% block additional_buttons %}{% endblock %}+ {% comment %}+ Dirty + status messages are tied to the UPDATE submission+ flow; they have no role on a surface where UPDATE is hidden,+ so the whole stack is omitted there to keep the action bar+ free of empty placeholders that the script layer would+ otherwise target.+ {% endcomment %}+ {% if attr_item_context.can_add_custom_attributes %}<!-- Vertically stacked message areas --><div class="attr-v2-message-stack"><div id="{{ attr_page_context.dirty_msg_html_id }}"@@ -69,28 +84,29 @@ by using the AttributeItemEditContext pattern.{% endif %}</div></div>+ {% endif %}</div><!-- Right Side: Action buttons --><div class="{{ DIVID.ATTR_V2_ACTION_BUTTONS_CLASS }}">{% block additional_actions %}{% endblock %}+ {% if attr_item_context.can_add_custom_attributes %}{% block file_upload_button %}<button type="button"class="btn btn-sm btn-outline-primary mb-0"- {% if not attr_item_context.can_add_custom_attributes %}disabled aria-disabled="true" title="{{ attr_item_context.add_attribute_disabled_message }}"{% endif %}onclick="document.getElementById('{{ attr_item_context.file_input_html_id }}').click();">{% icon "upload" size="sm" css_class="hi-icon-left" %}Add File</button>{% endblock %}{% block add_attribute_button %}- <button id="{{ attr_item_context.add_attribute_button_html_id }}"- type="button"+ <button id="{{ attr_item_context.add_attribute_button_html_id }}"+ type="button"class="btn btn-sm btn-outline-primary"- {% if not attr_item_context.can_add_custom_attributes %}disabled aria-disabled="true" title="{{ attr_item_context.add_attribute_disabled_message }}"{% endif %}onclick="window.Hi.attr.showAddAttribute('#{{ attr_page_context.container_html_id }}');">{% icon "plus" size="sm" css_class="hi-icon-left" %}Add Info</button>{% endblock %}+ {% endif %}</div></div></div>diff --git a/src/hi/apps/attribute/templates/attribute/components/file_card.html b/src/hi/apps/attribute/templates/attribute/components/file_card.htmlindex 56931836..26522088 100644--- a/src/hi/apps/attribute/templates/attribute/components/file_card.html+++ b/src/hi/apps/attribute/templates/attribute/components/file_card.html@@ -64,13 +64,14 @@ Individual file attribute card with preview, actions, and metadata<!-- File Info --><div class="{{ DIVID.ATTR_V2_FILE_INFO_CLASS }}">- <input type="text"+ <input type="text"id="{{ attr_item_context|file_title_field_name:attribute.id }}"- name="{{ attr_item_context|file_title_field_name:attribute.id }}"- value="{{ attribute.value }}"+ name="{{ attr_item_context|file_title_field_name:attribute.id }}"+ value="{{ attribute.value }}"class="{{ DIVID.ATTR_V2_FILE_TITLE_INPUT_CLASS }}"placeholder="Enter file title"- maxlength="255">+ maxlength="255"+ {% if not attribute.is_editable %}readonly aria-readonly="true"{% endif %}><div class="{{ DIVID.ATTR_V2_FILE_NAME_CLASS }}">{{ attribute.name }}</div><!-- File Actions -->diff --git a/src/hi/apps/console/video_stream_browsing_helper.py b/src/hi/apps/console/video_stream_browsing_helper.pyindex 8e6ccb73..e592d44a 100644--- a/src/hi/apps/console/video_stream_browsing_helper.py+++ b/src/hi/apps/console/video_stream_browsing_helper.py@@ -423,7 +423,12 @@ class VideoStreamBrowsingHelper:prev_sensor_response = None,next_sensor_response = None,window_start_timestamp = None,- window_end_timestamp = pivot_timestamp if has_newer_records else None,+ # ``window_end_timestamp`` is declared Optional[datetime]+ # and the templates run it through |date:"U"; the int+ # ``pivot_timestamp`` would crash the formatter. Reuse the+ # already-computed datetime so the no-records branch+ # honors the field's contract.+ window_end_timestamp = pivot_time if has_newer_records else None,)# Convert to SensorResponse objects@@ -506,7 +511,11 @@ class VideoStreamBrowsingHelper:pagination_metadata={'has_older_records': has_older_records, 'has_newer_records': False},prev_sensor_response=None,next_sensor_response=None,- window_start_timestamp = pivot_timestamp if has_older_records else None,+ # ``window_start_timestamp`` is declared Optional[datetime]+ # and the templates run it through |date:"U"; the int+ # ``pivot_timestamp`` would crash the formatter. Reuse+ # the already-computed datetime instead.+ window_start_timestamp = pivot_time if has_older_records else None,window_end_timestamp = None,)diff --git a/src/hi/apps/entity/entity_attribute_edit_context.py b/src/hi/apps/entity/entity_attribute_edit_context.pyindex 3a14f5b2..cd098316 100644--- a/src/hi/apps/entity/entity_attribute_edit_context.py+++ b/src/hi/apps/entity/entity_attribute_edit_context.py@@ -88,3 +88,9 @@ class EntityAttributeItemEditContext(AttributeItemEditContext):if self.can_add_custom_attributes:return ''return 'New attributes are disabled for externally managed entities.'++ @property+ def externally_managed_message(self) -> str:+ if self.can_add_custom_attributes:+ return ''+ return 'Attributes are managed externally and cannot be edited here.'diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.pyindex 68147f31..97597340 100644--- a/src/hi/apps/entity/tests/test_views.py+++ b/src/hi/apps/entity/tests/test_views.py@@ -331,7 +331,13 @@ class TestEntityEditView(DualModeViewTestCase):self.assertIsNotNone(new_attr)self.assertEqual(new_attr.value, 'new value')- def test_get_disables_add_info_when_entity_disallows_custom_attributes(self):+ def test_get_hides_add_and_update_buttons_when_entity_disallows_custom_attributes(self):+ """When the entity is integration-managed (cannot add custom+ attributes), the Add File / Add Info / Update buttons are+ omitted entirely rather than rendered disabled — disabled-but-+ visible affordances were confusing on a fully read-only+ surface, and Update was a no-op there.+ """self.entity.can_add_custom_attributes = Falseself.entity.save(update_fields=['can_add_custom_attributes'])@@ -341,9 +347,9 @@ class TestEntityEditView(DualModeViewTestCase):self.assertSuccessResponse(response)content = response.content.decode('utf-8')- self.assertIn(f'attr-v2-add-attribute-btn-entity-{self.entity.id}', content)- self.assertIn('disabled aria-disabled="true"', content)- self.assertIn('New attributes are disabled for externally managed entities.', content)+ self.assertNotIn(f'attr-v2-add-attribute-btn-entity-{self.entity.id}', content)+ self.assertNotIn('>Add File<', content)+ self.assertNotIn('>Add Info<', content)def test_post_rejects_new_attribute_when_entity_disallows_custom_attributes(self):self.entity.can_add_custom_attributes = Falsediff --git a/src/hi/integrations/entity_operations.py b/src/hi/integrations/entity_operations.pyindex e0c582b6..dae8502a 100644--- a/src/hi/integrations/entity_operations.py+++ b/src/hi/integrations/entity_operations.py@@ -178,10 +178,20 @@ class EntityIntegrationOperations:@staticmethoddef 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.+ Classify the entities attached to the integration for the+ confirmation dialogs that gate a Disable or a Refresh: counts+ total entities (plus orphan-after-removal delegates) and how+ many carry user-created data.++ Both the Disable modal and the pre-Refresh modal use the same+ classification: each is asking the operator a *policy*+ question ("if items with custom data are about to be let go,+ retain them or delete them?") and surfaces the SAFE / ALL+ choice only when ``has_mixed_state``. Refresh's actual dropped+ set is decided at sync execution against fresh upstream — the+ operator's choice expresses the policy that applies if drops+ include user-data items, regardless of which specific items+ end up dropping."""target_ids = EntityIntegrationOperations.get_removal_entity_ids(integration_id = integration_id,diff --git a/src/hi/integrations/integration_synchronizer.py b/src/hi/integrations/integration_synchronizer.pyindex 2a46750b..52686b9f 100644--- a/src/hi/integrations/integration_synchronizer.py+++ b/src/hi/integrations/integration_synchronizer.py@@ -82,7 +82,10 @@ class IntegrationSynchronizer:return 'Import Result'return 'Refresh Result'- def sync(self, is_initial_import: bool) -> IntegrationSyncResult:+ def sync(self,+ is_initial_import : bool,+ preserve_user_data : bool = True,+ ) -> IntegrationSyncResult:"""Public entry point used by the framework. Wraps `_sync_impl`with the sync lock and standard error handling. Subclasses@@ -92,7 +95,19 @@ class IntegrationSynchronizer:sync flow (Import for first-time, Refresh otherwise);threaded down so each subclass can title its resultconsistently.++ ``preserve_user_data`` controls how user-data entities are+ handled when the sync drops them as no-longer-present+ upstream — symmetric to the integration-disable flow's SAFE+ / ALL choice. True (default, "Refresh and Retain") detaches+ them; False ("Refresh and Remove") hard-deletes them. Stored+ on the instance for the duration so+ ``_remove_entity_intelligently`` can read it without+ threading the flag through every subclass's ``_sync_impl``;+ the process-wide ``SYNCHRONIZATION_LOCK_NAME`` precludes+ concurrent syncs."""+ self._preserve_user_data = preserve_user_datatry:with ExclusionLockContext(name=self.SYNCHRONIZATION_LOCK_NAME):logger.debug(f'{self.__class__.__name__} sync started.')@@ -362,16 +377,18 @@ class IntegrationSynchronizer:Remove an entity that no longer exists in the integration.Delegates to ``EntityIntegrationOperations.remove_entities_with_closure``- — the same path the integration-disable SAFE flow uses. The+ — the same path the integration-disable flow uses. Theclosure walk picks up delegate entities (e.g., the Areaauto-created when a camera was placed in a view) when their- only remaining principal is being removed. Operator-added- attributes on any closure entity trigger the detach-and-preserve- path; otherwise the entity is hard-deleted.+ only remaining principal is being removed. Whether+ operator-added attributes trigger the detach-and-preserve+ branch is controlled by ``self._preserve_user_data`` (set on+ ``sync()`` entry from the operator's pre-sync choice;+ defaults to True / preserve when not explicitly set)."""EntityIntegrationOperations.remove_entities_with_closure(seed_entity_ids = { entity.id },integration_name = self.get_integration_metadata().label,- preserve_user_data = True,+ preserve_user_data = getattr( self, '_preserve_user_data', True ),result = result,)diff --git a/src/hi/integrations/templates/integrations/modals/pre_sync_confirm.html b/src/hi/integrations/templates/integrations/modals/pre_sync_confirm.htmlindex 0e050743..3a2a402f 100644--- a/src/hi/integrations/templates/integrations/modals/pre_sync_confirm.html+++ b/src/hi/integrations/templates/integrations/modals/pre_sync_confirm.html@@ -26,6 +26,20 @@ saving from there returns to this modal. On the manage-page entrypath, the user came from the manage page and the inherited CANCELalready takes them "back" to it.+When `removal_summary.has_mixed_state` (Refresh path with at least+one user-data entity present), the modal symmetrically mirrors the+disable modal's policy choice: REFRESH AND RETAIN preserves dropped+user-data items by detaching, REFRESH AND REMOVE hard-deletes them.+The summary is the integration's full footprint (not a per-sync+prediction); the operator's choice expresses policy that applies at+sync execution if any drops carry user data.++The form is opened in `preamble` and closed in `postamble` so each+action button is a plain `<button name="preserve_user_data" value=…>`+on the same form (mirrors the integration_disable.html pattern).+The REVIEW CONFIG anchor on the first-time path sits inside the+form harmlessly — it navigates rather than submitting.+Context:integration_data : IntegrationData (required) — for label, id.is_initial_import : bool (required) — True when no entities for@@ -34,20 +48,22 @@ Context:REFRESH operations.sync_description : Optional[str] — per-integration text fromIntegrationSynchronizer.get_description.- sync_url : str (required) — URL the action posts to.+ sync_url : str (required) — URL the form posts to.review_config_url : str (required) — URL the REVIEW CONFIGaction opens (the integrations_enablemodal).+ removal_summary : Optional[IntegrationRemovalSummary] —+ integration's user-data classification.+ None on the first-time import path; a+ zero-count summary when no entities are+ attached. Drives the Retain / Remove+ choice on the Refresh path.{% endcomment %}-{% comment %}-First-time path only: override the inherited dismiss-only CANCEL with-one that triggers a full page reload. Reason: the operator's-underlying page (typically integrations home) was rendered before the-integration was enabled and is therefore stale; a plain dismiss would-leave them on a pre-enable view. On the refresh path the underlying-page is already current, so we keep the inherited dismiss behavior.-{% endcomment %}+{% block preamble %}+<form action="{{ sync_url }}" method="post" class="form" data-async="modal">+ {% csrf_token %}+{% endblock %}{% block title_text %}{% if is_initial_import %}@@ -69,6 +85,26 @@ Refresh from {{ integration_data.label }}?Refresh adds new items from <strong>{{ integration_data.label }}</strong>,updates ones that have changed, and removes ones no longer present.</p>+{% if removal_summary.has_mixed_state %}+<p>+ This integration has <strong>{{ removal_summary.user_data_count }}</strong>+ {% if removal_summary.user_data_count == 1 %}item{% else %}items{% endif %}+ with custom data you've added. If a Refresh would drop+ {% if removal_summary.user_data_count == 1 %}that item{% else %}any of them{% endif %}:+</p>+<ul>+ <li>+ <strong>RETAIN MISSING</strong> — preserve any missing items with custom data+ (detached from this integration; they will show as+ <em>Detached from {{ integration_data.label }}</em> in the entity-detail UI,+ with custom attributes and layout retained).+ </li>+ <li>+ <strong>REMOVE MISSING</strong> — delete any missing items along with their+ custom data. You will not be able to recover the deleted custom data.+ </li>+</ul>+{% endif %}{% endif %}{% if sync_description %}@@ -76,19 +112,6 @@ Refresh from {{ integration_data.label }}?{% endif %}{% endblock %}-{% block action_left %}-{% if is_initial_import %}-<a id="hi-modal-cancel" role="button"- class="btn btn-outline-tertiary"- href="#"- onclick="location.reload(); return false;">- {% icon "close" size="lg" css_class="hi-icon-left" %}SKIP-</a>-{% else %}-{{ block.super }}-{% endif %}-{% endblock %}-{% block action_center %}{% if is_initial_import %}<a href="{{ review_config_url }}"@@ -97,18 +120,31 @@ Refresh from {{ integration_data.label }}?data-async="modal">{% icon "settings" size="lg" css_class="hi-icon-left" %}REVIEW CONFIG</a>+{% elif removal_summary.has_mixed_state %}+<button type="submit" class="btn btn-outline-danger ml-2"+ name="preserve_user_data" value="false">+ {% icon "warning" size="sm" css_class="hi-icon-left" %}REMOVE MISSING+</button>{% endif %}{% endblock %}{% block action_right %}-<form action="{{ sync_url }}" method="post" class="form" data-async="modal">- {% csrf_token %}- <button type="submit" class="btn btn-primary">- {% if is_initial_import %}- {% icon "upload" size="lg" css_class="hi-icon-left" %}IMPORT- {% else %}- {% icon "sync" size="lg" css_class="hi-icon-left" %}REFRESH- {% endif %}- </button>+{% if is_initial_import %}+<button type="submit" class="btn btn-primary">+ {% icon "upload" size="lg" css_class="hi-icon-left" %}IMPORT+</button>+{% elif removal_summary.has_mixed_state %}+<button type="submit" class="btn btn-primary"+ name="preserve_user_data" value="true">+ {% icon "shield" size="sm" css_class="hi-icon-left" %}RETAIN MISSING+</button>+{% else %}+<button type="submit" class="btn btn-primary">+ {% icon "sync" size="lg" css_class="hi-icon-left" %}REFRESH+</button>+{% endif %}+{% endblock %}++{% block postamble %}</form>{% endblock %}diff --git a/src/hi/integrations/tests/test_views.py b/src/hi/integrations/tests/test_views.pyindex c3d30e3e..e0fd5939 100644--- a/src/hi/integrations/tests/test_views.py+++ b/src/hi/integrations/tests/test_views.py@@ -210,9 +210,10 @@ class _SyncTestSynchronizer:def get_result_title(self, is_initial_import):return 'Test Sync Result'- def sync(self, is_initial_import=False):+ def sync(self, is_initial_import=False, preserve_user_data=True):from hi.integrations.sync_result import IntegrationSyncResultself.sync_called = True+ self.last_preserve_user_data = preserve_user_datareturn IntegrationSyncResult(title='Test Sync Result',info_list=['Synced.'],@@ -368,6 +369,55 @@ class PreSyncViewTests(SyncViewTestCase):self.assertSuccessResponse(response)self.assertNotIn('REVIEW CONFIG', response.content.decode())+ def test_refresh_modal_shows_single_button_when_no_user_data(self):+ """No entities carry user data → has_mixed_state is False, so+ the Refresh path renders the single REFRESH button (not the+ Retain / Remove choice). Mirrors the integration_disable+ modal's collapsed mode for the no-mixed-state case.+ """+ from hi.apps.entity.enums import EntityType+ from hi.apps.entity.models import Entity+ Entity.objects.create(+ integration_id=self.INTEGRATION_ID,+ integration_name='ent_no_user_data',+ name='No User Data',+ entity_type_str=EntityType.default_value(),+ )+ response = self.client.get(self._url())+ self.assertSuccessResponse(response)+ body = response.content.decode()+ self.assertIn('>REFRESH<', body.replace('\n', ''))+ self.assertNotIn('RETAIN MISSING', body)+ self.assertNotIn('REMOVE MISSING', body)++ def test_refresh_modal_shows_retain_remove_choice_with_user_data(self):+ """When at least one attached entity has operator-added+ attributes, the Refresh modal exposes the policy choice+ (RETAIN MISSING / REMOVE MISSING) symmetric to the+ disable modal's DELETE SAFE / DELETE ALL.+ """+ from hi.apps.attribute.enums import AttributeType, AttributeValueType+ from hi.apps.entity.enums import EntityType+ from hi.apps.entity.models import Entity, EntityAttribute+ entity = Entity.objects.create(+ integration_id=self.INTEGRATION_ID,+ integration_name='ent_with_user_data',+ name='Has User Data',+ entity_type_str=EntityType.default_value(),+ )+ EntityAttribute.objects.create(+ entity=entity,+ name='Operator Note',+ value='Hand-edited.',+ attribute_type_str=str(AttributeType.CUSTOM),+ value_type_str=str(AttributeValueType.TEXT),+ )+ response = self.client.get(self._url())+ self.assertSuccessResponse(response)+ body = response.content.decode()+ self.assertIn('RETAIN MISSING', body)+ self.assertIn('REMOVE MISSING', body)+class SyncViewTests(SyncViewTestCase):"""@@ -408,6 +458,25 @@ class SyncViewTests(SyncViewTestCase):self.assertSuccessResponse(response)self.assertTrue(self.synchronizer.sync_called)+ def test_post_defaults_to_preserve_user_data(self):+ """POST with no preserve_user_data field (e.g., the+ single-button form rendered when has_mixed_state is False)+ falls back to the safe default — preserve user data on+ drops."""+ self.client.post(self._url())+ self.assertTrue(self.synchronizer.last_preserve_user_data)++ def test_post_with_preserve_user_data_false_disables_preservation(self):+ """The REMOVE MISSING button posts preserve_user_data=false;+ the view must thread that through to synchronizer.sync."""+ self.client.post(self._url(), {'preserve_user_data': 'false'})+ self.assertFalse(self.synchronizer.last_preserve_user_data)++ def test_post_with_preserve_user_data_true_keeps_preservation(self):+ """The RETAIN MISSING button posts preserve_user_data=true."""+ self.client.post(self._url(), {'preserve_user_data': 'true'})+ self.assertTrue(self.synchronizer.last_preserve_user_data)+def test_post_404s_when_integration_has_no_synchronizer(self):IntegrationManager()._integration_data_map[self.INTEGRATION_ID] = IntegrationData(integration_gateway=_SyncIncapableGateway(self.INTEGRATION_ID),@@ -519,8 +588,9 @@ class _PlacementTestSynchronizer:def get_result_title(self, is_initial_import):return 'Placement Test'- def sync(self, is_initial_import=False):+ def sync(self, is_initial_import=False, preserve_user_data=True):self.sync_called = True+ self.last_preserve_user_data = preserve_user_datareturn self._sync_resultdiff --git a/src/hi/integrations/views.py b/src/hi/integrations/views.pyindex d8832086..a973d9cc 100644--- a/src/hi/integrations/views.py+++ b/src/hi/integrations/views.py@@ -6,6 +6,7 @@ from django.urls import reversefrom django.views.generic import Viewfrom hi.apps.common import antinode+from hi.apps.common.utils import str_to_boolfrom hi.enums import ViewMode, ViewTypefrom hi.exceptions import ForceRedirectExceptionfrom hi.hi_async_view import HiModalView@@ -124,6 +125,20 @@ class IntegrationPreSyncView( HiModalView, IntegrationViewMixin ):kwargs = { 'integration_id': integration_data.integration_id },)+ # Refresh path: surface the same SAFE / ALL policy choice the+ # disable modal does when the integration has any user-data+ # entities. The summary is the integration's full footprint+ # (not a per-sync prediction): the operator's choice+ # expresses the policy applied at sync execution if any+ # drops carry user data, which is the same question the+ # disable modal asks. Skipped on the first-time import path+ # since no entities exist yet.+ removal_summary = None+ if not is_initial_import:+ removal_summary = EntityIntegrationOperations.summarize_for_removal(+ integration_id = integration_data.integration_id,+ )+context = {'integration_data': integration_data,'is_initial_import': is_initial_import,@@ -132,6 +147,7 @@ class IntegrationPreSyncView( HiModalView, IntegrationViewMixin ):),'sync_url': sync_url,'review_config_url': review_config_url,+ 'removal_summary': removal_summary,}return self.modal_response( request, context )@@ -176,7 +192,20 @@ class IntegrationSyncView( HiModalView, IntegrationViewMixin ):integration_id = integration_data.integration_id,).exists()- sync_result = synchronizer.sync( is_initial_import = is_initial_import )+ # Operator's per-Refresh policy for items that would be+ # dropped. True ("Refresh and Retain") preserves user-data+ # entities by detaching them; False ("Refresh and Remove")+ # hard-deletes everything dropped. Defaults to True — the+ # safe value when the choice was not surfaced (no user-data+ # entities) or the field was absent for any reason.+ preserve_user_data = str_to_bool(+ request.POST.get( 'preserve_user_data', 'true' ),+ )++ sync_result = synchronizer.sync(+ is_initial_import = is_initial_import,+ preserve_user_data = preserve_user_data,+ )# Scope the placement to just the entities this sync created.# Without scoping, the placement's GET endpoint queries everydiff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.pyindex 6dbcc959..d79827ff 100644--- a/src/hi/services/hass/hass_converter.py+++ b/src/hi/services/hass/hass_converter.py@@ -567,7 +567,12 @@ class HassConverter:elif attribute and not insteon_address:messages.append( f'Insteon address removed for {entity}. Removing {insteon_address}' )- attribute.delete()+ # Hard-delete: integration-owned attribute (not+ # user-editable). Soft-delete would surface this+ # in the "Deleted Attributes" section with a+ # restore button, creating an inconsistency+ # against upstream's source of truth.+ attribute.delete( hard_delete = True )elif not attribute and insteon_address:messages.append( f'No insteon address for {entity}. Adding {insteon_address}' )diff --git a/src/hi/services/homebox/hb_sync.py b/src/hi/services/homebox/hb_sync.pyindex 12bd327d..49cdca31 100644--- a/src/hi/services/homebox/hb_sync.py+++ b/src/hi/services/homebox/hb_sync.py@@ -49,6 +49,11 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):# try again. Returning None opts this cycle out cleanly.return Nonesummary_list = await hb_manager.fetch_hb_items_summary_from_api_async()+ # ``archived: true`` upstream is HomeBox's "no longer in+ # active use" marker. Treat archived items as if they were+ # absent so the sync-check correctly reports them as removed+ # — see ``_sync_helper_entities`` for the matching filter on+ # the full-detail fetch.upstream_keys = {IntegrationKey(integration_id = HbMetaData.integration_id,@@ -56,6 +61,7 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):)for item in summary_listif item.get('id') is not None+ and item.get('archived') is not True}current_keys = await sync_to_async( self._get_current_integration_keys )()return IntegrationSyncCheck.compute_delta(@@ -124,13 +130,28 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):Existing-entity updates do not contribute — they don't needre-placement."""integration_key_to_item = dict()+ skipped_archived = 0for item in item_list:+ # ``archived: true`` upstream means the item is no+ # longer in active use. Skip it so the sync's removal+ # branch picks up its HI counterpart on the same pass:+ # SAFE removal handles user-data preservation if the+ # operator added attributes; hard-delete otherwise.+ # Mirrored in ``check_needs_sync`` so the sync-check+ # delta agrees with what the full sync will do.+ if item.archived is True:+ skipped_archived += 1+ continuetry:integration_key = HbConverter.hb_item_to_integration_key( hb_item = item )integration_key_to_item[integration_key] = itemexcept Exception as e:result.error_list.append( f'Ignoring HomeBox item due to missing/invalid id: {e}' )continue+ if skipped_archived:+ result.info_list.append(+ f'Skipped {skipped_archived} archived HomeBox item(s).'+ )integration_key_to_entity = self._get_existing_hb_entities( result = result )result.info_list.append( f'Found {len(integration_key_to_entity)} existing HomeBox items.' )@@ -396,8 +417,15 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):def _remove_attribute( self,attribute: EntityAttribute,message_list: List[str] ):+ # Hard-delete: these are integration-owned attributes (not+ # editable by the user), so the SoftDeleteAttributeModel's+ # default soft-delete + restore affordance doesn't apply.+ # Soft-deleting would surface the row under "Deleted+ # Attributes" with a restore button, and a restore creates+ # an inconsistency between HI and the integration's source+ # of truth.old_name = attribute.name- attribute.delete()+ attribute.delete( hard_delete = True )message_list.append( f'Field attribute removed: {old_name}' )returndiff --git a/src/hi/services/zoneminder/monitors.py b/src/hi/services/zoneminder/monitors.pyindex 3d8a2c4c..2d897d16 100644--- a/src/hi/services/zoneminder/monitors.py+++ b/src/hi/services/zoneminder/monitors.py@@ -31,7 +31,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )ZONEMINDER_POLLING_INTERVAL_SECS = ZmTimeouts.POLLING_INTERVAL_SECSZONEMINDER_API_TIMEOUT_SECS = ZmTimeouts.API_TIMEOUT_SECS- CACHING_DISABLED = True+ DEBUG_STATES_AND_MONITORS = Falsedef __init__( self ):super().__init__(@@ -313,7 +313,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )current_poll_datetime = datetimeproxy.now()sensor_response_map = dict()- zm_monitors = await self.zm_manager().get_zm_monitors_async( force_load = self.CACHING_DISABLED )+ zm_monitors = await self.zm_manager().get_zm_monitors_async( force_load = self.DEBUG_STATES_AND_MONITORS )for zm_monitor in zm_monitors:function_sensor_response = self._create_monitor_function_sensor_response(zm_monitor = zm_monitor,@@ -329,7 +329,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )sensor_response_map = dict()active_run_state_name = None- zm_states = await self.zm_manager().get_zm_states_async( force_load = self.CACHING_DISABLED )+ zm_states = await self.zm_manager().get_zm_states_async( force_load = self.DEBUG_STATES_AND_MONITORS )for zm_state in zm_states:if zm_state.active():active_run_state_name = zm_state.name()diff --git a/src/hi/services/zoneminder/zm_manager.py b/src/hi/services/zoneminder/zm_manager.pyindex 7f8ead01..7bedcf73 100644--- a/src/hi/services/zoneminder/zm_manager.py+++ b/src/hi/services/zoneminder/zm_manager.py@@ -354,7 +354,18 @@ class ZoneMinderManager( SingletonManager, AggregateHealthProvider, ApiHealthSta)()def get_video_stream_url( self, monitor_id : int ):- return f'{self.zm_client.portal_url}/cgi-bin/nph-zms?mode=jpeg&scale=100&rate=5&maxfps=5&monitor={monitor_id}'+ # Cache-bust the URL so a re-rendered <img> on the same+ # monitor (e.g., reopening an entity-status modal) gets a+ # unique src value and the browser refetches the stream+ # rather than reusing the previously-completed response.+ # Symmetric to get_event_video_stream_url below.+ import time+ timestamp = int(time.time())+ return (+ f'{self.zm_client.portal_url}/cgi-bin/nph-zms'+ f'?mode=jpeg&scale=100&rate=5&maxfps=5&monitor={monitor_id}'+ f'&_t={timestamp}'+ )def get_event_video_stream_url( self, event_id : int ):# Add timestamp for cache busting to help with connection managementdiff --git a/src/hi/simulator/base_models.py b/src/hi/simulator/base_models.pyindex 51aebb3c..378ff275 100644--- a/src/hi/simulator/base_models.py+++ b/src/hi/simulator/base_models.py@@ -2,6 +2,8 @@ from dataclasses import dataclass, fields, MISSINGfrom datetime import datetimefrom typing import Any, Dict, List, Tuple, Type+from hi.apps.common.utils import str_to_bool+from .enums import SimEntityType, SimStateType@@ -100,6 +102,18 @@ class SimState:def name(self):return self.sim_entity_fields.name+ @property+ def is_on(self) -> bool:+ """Boolean coercion of ``value`` for templates that render+ a checkbox ``checked``-state. Default ``value``s like+ ``'off'`` are non-empty strings and would be truthy under+ Django's ``{% if value %}`` test, leaving the initial+ render out of sync with the logical state. Routing through+ ``str_to_bool`` keeps the visible toggle aligned with the+ actual ON/OFF interpretation across all string-stored+ boolean states (ON_OFF, MOVEMENT, OPEN_CLOSE, etc.)."""+ return str_to_bool( self.value )+def set_value_from_string( self, value_str : str ):""" Subclasses should override this is the value is not a string and needs conversion. """if self.value == value_str:diff --git a/src/hi/simulator/forms.py b/src/hi/simulator/forms.pyindex dedf65d0..9d55928e 100644--- a/src/hi/simulator/forms.py+++ b/src/hi/simulator/forms.py@@ -9,7 +9,7 @@ from .models import SimProfileclass SimProfileForm( forms.ModelForm ):-+class Meta:model = SimProfilefields = (@@ -20,6 +20,19 @@ class SimProfileForm( forms.ModelForm ):class SimEntityFieldsForm( forms.Form ):"""Dynamically build a Django form from a subclass of SimEntityFields.++ Per-field metadata is read from the dataclass's+ ``field.metadata`` mapping:++ * ``csv_choices`` — callable or iterable of ``(value, label)``+ tuples. Switches the form field from a plain ``CharField`` to+ a ``MultipleChoiceField`` rendered as checkboxes; the form+ round-trips between the dataclass's CSV string and the+ widget's list of values, so the underlying dataclass+ ``str`` field shape is preserved.++ * ``help_text`` — string passed straight to the Django form+ field (rendered by the standard form template)."""DATA_TYPE_TO_FORM_FIELD = {@@ -29,16 +42,34 @@ class SimEntityFieldsForm( forms.Form ):datetime: forms.DateTimeField,bool: forms.BooleanField,}-+def __init__(self, sim_entity_fields_class: Type[ SimEntityFields ], *args, initial = None, **kwargs):super().__init__(*args, **kwargs)+ # Track which fields use the CSV-choices round-trip so+ # ``clean()`` can rejoin the multi-select list back into a+ # CSV string for the dataclass consumer.+ self._csv_choice_field_names = set()+for field in fields( sim_entity_fields_class ):+ metadata = field.metadata or {}+ help_text = metadata.get( 'help_text', '' )+ csv_choices = metadata.get( 'csv_choices' )++ if csv_choices is not None:+ self._add_csv_choice_field(+ field = field,+ choices_source = csv_choices,+ help_text = help_text,+ initial = initial,+ )+ continue+field_type = field.typeform_field_class = self.DATA_TYPE_TO_FORM_FIELD.get( field_type, None )if not form_field_class:raise ValueError( f'Unsupported field type: {field_type}' )-+default_value = None if field.default is MISSING else field.defaultfield_initial = initial.get( field.name, default_value ) if initial else default_value@@ -46,6 +77,47 @@ class SimEntityFieldsForm( forms.Form ):initial = field_initial,required = field.default is MISSING,label = field.name.replace("_", " ").capitalize(),+ help_text = help_text,)continuereturn++ def _add_csv_choice_field(self, field, choices_source, help_text, initial):+ """Render a CSV-string dataclass field as a multi-checkbox+ picker. The dataclass keeps its plain ``str`` shape; the+ form converts initial CSV → list at render time and+ ``clean()`` converts list → CSV at submit time."""+ choices = choices_source() if callable( choices_source ) else list( choices_source )++ default_value = '' if field.default is MISSING else ( field.default or '' )+ raw_initial = initial.get( field.name, default_value ) if initial else default_value+ if isinstance( raw_initial, str ):+ field_initial = [+ token.strip() for token in raw_initial.split(',') if token.strip()+ ]+ elif isinstance( raw_initial, (list, tuple) ):+ field_initial = list( raw_initial )+ else:+ field_initial = []++ self.fields[field.name] = forms.MultipleChoiceField(+ choices = choices,+ initial = field_initial,+ required = False,+ label = field.name.replace("_", " ").capitalize(),+ widget = forms.CheckboxSelectMultiple,+ help_text = help_text,+ )+ self._csv_choice_field_names.add( field.name )+ return++ def clean(self):+ cleaned = super().clean()+ # Rejoin multi-select lists back into CSV so consumers+ # (the dataclass build path) see the same shape regardless+ # of widget choice.+ for name in self._csv_choice_field_names:+ value = cleaned.get( name )+ if isinstance( value, (list, tuple) ):+ cleaned[name] = ','.join( value )+ return cleaneddiff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.pyindex 4fb00c13..68759a96 100644--- a/src/hi/simulator/management/commands/seed_sim_profiles.py+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py@@ -32,25 +32,30 @@ before recreating.Operator workflow for full-category coverage (sync result modalmanual validation):- 1. Switch simulator to ``baseline``. Sync HI. Three entities+ 1. Switch simulator to ``baseline``. Sync HI. Two entitieswhose names start with ``★ Custom Attr Needed ★`` will be- imported alongside the others (one per integration). Open- each in entity-edit and add ANY custom attribute (e.g., a- "Note" attribute with any value). The custom attribute is- what flips them onto the preserve-with-user-data path when- they later disappear upstream.+ imported (HASS and ZM only — HomeBox sets+ ``can_add_custom_attributes = False`` by design, so HB+ entities cannot participate in the detach/reconnect cycle+ and have no anchor item). Open each in entity-edit and add+ ANY custom attribute (e.g., a "Note" attribute with any+ value). The custom attribute is what flips them onto the+ preserve-with-user-data path when they later disappear+ upstream.2. Switch simulator to ``baseline-changed``. Refresh sync.The result modal shows:- Created: three new items present only in baseline-changed- Updated: three items renamed / metadata-changed- Removed: three items absent here, no user attribute- - Detached: three ★-prefixed items absent here, with the- user attribute the operator added in step 1 retained+ - Detached: two ★-prefixed items (HASS, ZM) absent here,+ with the user attribute the operator added in step 1+ retained- (Reconnected is empty on this direction)3. Switch simulator back to ``baseline``. Refresh sync.The result modal shows:- - Reconnected: the three ★-prefixed items rejoin via the- secondary-match path; their custom attributes are intact+ - Reconnected: the two ★-prefixed items (HASS, ZM) rejoin+ via the secondary-match path; their custom attributes+ are intact- Created: the three previously-Removed items return asfresh entities (no previous_integration_id, so noreconnect — they come back as duplicates would, but@@ -76,6 +81,7 @@ from hi.simulator.services.hass.sim_models import (HassInsteonOpenCloseSensorFields,HassInsteonOutletFields,)+from hi.simulator.services.homebox.attachment_catalog import AttachmentTemplatefrom hi.simulator.services.homebox.sim_models import (HomeBoxInventoryItemFields,)@@ -180,13 +186,15 @@ class Command(BaseCommand):profile, '★ Custom Attr Needed ★ Office Light', '01.AA.10',)- # HomeBox: 4 items with mixed metadata richness, plus a- # ★-prefixed item that the operator anchors with a custom- # attribute (HomeBox-side detach/reconnect anchor).- # ``item_id`` is the per-item stable id used by the- # integration's change-detection — kept identical across- # baseline / baseline-changed for items that should be 'the- # same item'.+ # HomeBox: 4 items with mixed metadata richness. No+ # ★-prefixed anchor here: HomeBox sets+ # ``can_add_custom_attributes = False`` (the converter is+ # the source of truth for HB item attributes), so the+ # operator cannot add a custom attribute on the HI side and+ # the detach/reconnect cycle does not apply to HB. ``item_id``+ # is the per-item stable id used by the integration's+ # change-detection — kept identical across baseline /+ # baseline-changed for items that should be 'the same item'.self._add_homebox_item(profile, 'Cordless Drill',item_id = 'cordless-drill',@@ -195,12 +203,17 @@ class Command(BaseCommand):model_number = 'DCD777',serial_number = 'DW-100231',quantity = 1,+ attachment_keys = ','.join([+ AttachmentTemplate.MANUAL.key,+ AttachmentTemplate.RECEIPT.key,+ ]),)self._add_homebox_item(profile, 'Stud Finder',item_id = 'stud-finder',manufacturer = 'Franklin Sensors',quantity = 1,+ attachment_keys = AttachmentTemplate.PHOTO.key,)self._add_homebox_item(profile, 'Soldering Iron Kit',@@ -213,13 +226,6 @@ class Command(BaseCommand):item_id = 'spare-light-bulbs',quantity = 12,)- self._add_homebox_item(- profile, '★ Custom Attr Needed ★ Multimeter',- item_id = 'multimeter',- manufacturer = 'Fluke',- model_number = '117',- quantity = 1,- )# ZoneMinder: 1 server (singleton) + 2 monitors + a# ★-prefixed monitor anchor for the ZM detach/reconnect@@ -269,9 +275,8 @@ class Command(BaseCommand):# (attribute update path)# Soldering Iron — REMOVED (item_id absent, no user attr)# Spare Bulbs — kept (same item_id, same content)- # ★ Multimeter — ABSENT (item_id absent) → Detached on- # the HI side via user-attribute anchor# <new> Caulk Gun — ADDED (new item_id)+ # No HB detach/reconnect anchor — see baseline's HB section.# Identity carries via ``item_id`` (the simulator's stable# API id), not row order — so the order here doesn't matter# for change-detection.@@ -283,12 +288,20 @@ class Command(BaseCommand):model_number = 'DCD777',serial_number = 'DW-100231',quantity = 1,+ # Attachment churn vs baseline: receipt removed, warranty+ # added; manual kept. Exercises attachment add+remove+ # paths in the refresh sync.+ attachment_keys = ','.join([+ AttachmentTemplate.MANUAL.key,+ AttachmentTemplate.WARRANTY.key,+ ]),)self._add_homebox_item(profile, 'Stud Finder',item_id = 'stud-finder',manufacturer = 'Bosch', # changed from 'Franklin Sensors'quantity = 1,+ attachment_keys = AttachmentTemplate.PHOTO.key, # unchanged across baseline pair)self._add_homebox_item(profile, 'Spare Light Bulbs',@@ -301,8 +314,6 @@ class Command(BaseCommand):description = '10-oz cartridge gun, dripless',quantity = 1,)- # 'multimeter' (item_id) intentionally absent — Detached- # via user-attribute anchor on the HI side.# ZoneMinder deltas:# ZM Server — keptdiff --git a/src/hi/simulator/services/hass/sim_models.py b/src/hi/simulator/services/hass/sim_models.pyindex a4096807..690f3c39 100644--- a/src/hi/simulator/services/hass/sim_models.py+++ b/src/hi/simulator/services/hass/sim_models.py@@ -233,7 +233,7 @@ class HassInsteonMotionDetectorBatteryState( HassInsteonState ):sim_state_type : SimStateType = SimStateType.DISCRETEsim_state_id : str = 'battery'value : str = 'High'-+@propertydef name(self):return f'{self.entity_name} Battery'@@ -244,11 +244,11 @@ class HassInsteonMotionDetectorBatteryState( HassInsteonState ):( 'Low' , 'Low' ),( 'High' , 'High' ),]-+@propertydef entity_id(self):return 'binary_sensor.motion_sensor_%s_battery' % self.insteon_address_id_suffix-+@propertydef attributes(self) -> Dict[ str, str ]:return {@@ -258,6 +258,16 @@ class HassInsteonMotionDetectorBatteryState( HassInsteonState ):"insteon_group": 1,}+ @property+ def state(self):+ # HA convention for binary_sensor with device_class=battery:+ # "on" means the battery is low (problem signal), "off"+ # means it's healthy. Override the inherited str_to_bool+ # path so the DISCRETE Low/High UI choice maps to the+ # right API output instead of resolving both labels to+ # "off" via str_to_bool.+ return 'on' if self.value == 'Low' else 'off'+@dataclass( frozen = True )class HassInsteonOpenCloseSensorFields( HassInsteonSimEntityFields ):diff --git a/src/hi/simulator/services/homebox/api/urls.py b/src/hi/simulator/services/homebox/api/urls.pyindex 45d3ac96..953174e5 100644--- a/src/hi/simulator/services/homebox/api/urls.py+++ b/src/hi/simulator/services/homebox/api/urls.py@@ -15,4 +15,8 @@ urlpatterns = [re_path( r'^v1/items/(?P<item_id>[\w\-]+)$',views.ItemDetailView.as_view(),name = 'homebox_api_item_detail' ),++ re_path( r'^v1/items/(?P<item_id>[\w\-]+)/attachments/(?P<attachment_id>[\w\-]+)$',+ views.AttachmentDownloadView.as_view(),+ name = 'homebox_api_attachment_download' ),]diff --git a/src/hi/simulator/services/homebox/api/views.py b/src/hi/simulator/services/homebox/api/views.pyindex 4819851f..7e750d5a 100644--- a/src/hi/simulator/services/homebox/api/views.py+++ b/src/hi/simulator/services/homebox/api/views.py@@ -6,18 +6,26 @@ HomeBox integration:- POST /v1/users/login- GET /v1/items- GET /v1/items/<id>+ - GET /v1/items/<id>/attachments/<key>The login endpoint accepts any credentials and returns a fixed token. Thetoken is not validated on subsequent requests. Both the request bodyshapes and the response shapes match the real HomeBox API closely enough-for the integration's HbItem parser to consume them unchanged.+for the integration's HbItem parser to consume them unchanged. The+attachment download endpoint serves bytes generated on the fly from+the per-item ``attachment_keys`` configuration plus the catalog in+``attachment_catalog`` — no files on disk."""-from django.http import JsonResponse+from django.http import HttpResponse, JsonResponsefrom django.utils.decorators import method_decoratorfrom django.views.decorators.csrf import csrf_exemptfrom django.views.generic import View+from hi.simulator.services.homebox.attachment_catalog import (+ parse_attachment_keys,+ render_attachment_content,+)from hi.simulator.services.homebox.sim_models import build_item_api_dictfrom hi.simulator.services.homebox.simulator import HomeBoxSimulator@@ -85,3 +93,50 @@ class ItemDetailView( View ):updated_at = updated_at,))return JsonResponse( { 'message': f'Item {item_id} not found' }, status = 404 )+++class AttachmentDownloadView( View ):+ """Serves the binary content for an attachment listed on an item.++ The real HomeBox API exposes ``GET /v1/items/<id>/attachments/<id>``+ returning the raw file with a Content-Type header; the+ integration's ``HbClient.download_attachment`` reads the body+ bytes and the header. Here, the bytes are rendered on demand from+ the catalog so the simulator stays file-management-free; the+ item's name is baked into the rendered content so the operator+ can identify which item an attachment came from when inspecting+ it inside HI.+ """++ def get(self, request, *args, **kwargs):+ item_id = kwargs.get('item_id')+ attachment_id = kwargs.get('attachment_id')++ simulator = HomeBoxSimulator()+ for ( sim_entity_id, fields, _archived_state,+ _created_at, _updated_at ) in simulator.get_sim_entity_pairs():+ if _api_id_for(fields, sim_entity_id) != item_id:+ continue+ templates_by_key = {+ template.key: template+ for template in parse_attachment_keys( fields.attachment_keys )+ }+ template = templates_by_key.get( attachment_id )+ if template is None:+ return JsonResponse(+ { 'message': f'Attachment {attachment_id} not found' },+ status = 404,+ )+ rendered = render_attachment_content(+ template = template, item_name = fields.name,+ )+ if not rendered:+ return JsonResponse(+ { 'message': f'Attachment {attachment_id} not found' },+ status = 404,+ )+ return HttpResponse(+ rendered['content'],+ content_type = rendered['mime_type'],+ )+ return JsonResponse( { 'message': f'Item {item_id} not found' }, status = 404 )diff --git a/src/hi/simulator/services/homebox/attachment_catalog.py b/src/hi/simulator/services/homebox/attachment_catalog.pynew file mode 100644index 00000000..d540f3f7--- /dev/null+++ b/src/hi/simulator/services/homebox/attachment_catalog.py@@ -0,0 +1,193 @@+"""+Pre-canned HomeBox attachment templates for the simulator.++The real HomeBox API delivers attachments as binary payloads (images,+PDFs) tied to inventory items. To exercise the HI app's attachment+download / parse / store paths without introducing actual file+management on the simulator side, this module defines a small fixed+catalog of templates as a ``LabeledEnum``; each item's+``attachment_keys`` field is a CSV of those members' wire keys.++The bytes are rendered on demand by the download endpoint (no files+on disk, no upload UI). Each rendered artifact carries the item name+in its content so the operator can recognize which item an+attachment came from when inspecting it inside HI.++Wire convention follows ``LabeledEnum``: a member's wire key is+``member.name.lower()`` (e.g., ``AttachmentTemplate.MANUAL`` →+``"manual"``). That is the string used in URLs, in the per-item+``attachment_keys`` CSV, and as the ``id`` field on the API+attachment dict.+"""+import io+import logging+from typing import Dict, List, Optional, Tuple++from PIL import Image, ImageDraw++from hi.apps.common.enums import LabeledEnum++logger = logging.getLogger(__name__)+++class AttachmentTemplate( LabeledEnum ):+ """Catalog of pre-canned attachment templates.++ Each member carries the user-facing label, MIME type, and+ rendering kind. The wire key (used in URLs, CSV fields, and the+ API ``attachment.id`` value) is ``member.name.lower()`` per the+ ``LabeledEnum`` convention. ``description`` is left empty —+ operator-facing label is sufficient for the picker UI.+ """++ RECEIPT = ( 'Receipt' , '' , 'image/png' , 'image' )+ MANUAL = ( 'Manual' , '' , 'application/pdf' , 'pdf' )+ PHOTO = ( 'Photo' , '' , 'image/jpeg' , 'image' )+ WARRANTY = ( 'Warranty' , '' , 'application/pdf' , 'pdf' )++ def __init__( self,+ label : str,+ description : str,+ mime_type : str,+ kind : str ):+ super().__init__( label, description )+ self.mime_type = mime_type+ self.kind = kind+ return++ @property+ def key( self ) -> str:+ """Wire string used in URLs, CSV fields, and the API+ ``attachment.id`` value. Stable across renames as long as+ the enum member name is preserved."""+ return self.name.lower()+++def attachment_choices() -> List[ Tuple[ str, str ] ]:+ """Choice tuples (value, label) for any UI that needs to render a+ selector over the catalog. Single source of truth — the+ ``SimEntityFieldsForm`` builder reads this via the+ ``csv_choices`` field-metadata hook so renaming a member here+ updates the picker without separate coordination."""+ return [+ ( template.key, f'{template.label} ({template.mime_type})' )+ for template in AttachmentTemplate+ ]+++def parse_attachment_keys( csv_value: str ) -> List[ AttachmentTemplate ]:+ """Split the CSV ``attachment_keys`` field into validated+ templates. Unknown keys are dropped silently (with a debug log)+ — the field is operator-edited free text and a typo should not+ 500 the simulator's item endpoint."""+ if not csv_value:+ return []+ templates = []+ for raw in csv_value.split( ',' ):+ key = raw.strip().lower()+ if not key:+ continue+ try:+ template = AttachmentTemplate.from_name( key )+ except ValueError:+ logger.debug( f'Ignoring unknown attachment key "{key}"' )+ continue+ templates.append( template )+ return templates+++def build_attachment_metadata( template: AttachmentTemplate ) -> Dict[ str, str ]:+ """The dict shape the real HomeBox API emits inside an item's+ ``attachments`` array. Returned shape is intentionally small —+ the HI integration's HbItem parser reads ``id`` (used as the+ download key here), ``title``, and ``mimeType``."""+ return {+ 'id' : template.key,+ 'title' : template.label,+ 'mimeType' : template.mime_type,+ }+++def render_attachment_content( template : AttachmentTemplate,+ item_name : str,+ ) -> Optional[ Dict[ str, object ] ]:+ """Generate the binary payload for the given catalog template,+ with ``item_name`` baked into the content so the operator can+ distinguish artifacts in the HI UI. Returns a dict with+ ``content`` (bytes) and ``mime_type`` (str), or None if the+ template's ``kind`` is unrecognized (should not happen with+ the current catalog)."""+ if template.kind == 'image':+ content = _render_image(+ title = template.label,+ item_name = item_name,+ image_format = 'PNG' if template.mime_type == 'image/png' else 'JPEG',+ )+ elif template.kind == 'pdf':+ content = _render_pdf( title = template.label, item_name = item_name )+ else:+ return None+ return {+ 'content' : content,+ 'mime_type' : template.mime_type,+ }+++def _render_image( title : str, item_name : str, image_format : str ) -> bytes:+ """Pillow-rendered placeholder image: a colored canvas with the+ attachment title and item name drawn on it. Default bitmap font+ keeps the simulator independent of system font availability."""+ image = Image.new( mode = 'RGB', size = ( 320, 160 ), color = ( 230, 240, 250 ) )+ draw = ImageDraw.Draw( image )+ draw.text( ( 20, 30 ), title, fill = ( 30, 40, 80 ) )+ draw.text( ( 20, 70 ), item_name, fill = ( 30, 40, 80 ) )+ draw.text( ( 20, 110 ), '(simulator)', fill = ( 90, 90, 90 ) )+ buffer = io.BytesIO()+ image.save( buffer, format = image_format )+ return buffer.getvalue()+++def _render_pdf( title : str, item_name : str ) -> bytes:+ """Hand-rolled minimal single-page PDF. The PDF format is a mix+ of structured text and a binary xref table; we build the body+ first, then compute byte offsets for the xref. This avoids+ pulling in an external PDF library for what amounts to four+ objects of placeholder content. The output is a valid PDF that+ most viewers will render with the title and item-name text."""+ text = f'{title}: {item_name} (simulator)'+ # Escape parens that would otherwise terminate a PDF string literal.+ text_safe = text.replace( '\\', '\\\\' ).replace( '(', '\\(' ).replace( ')', '\\)' )+ content_stream = (+ f'BT /F1 18 Tf 60 740 Td ({text_safe}) Tj ET'+ ).encode( 'latin-1' )++ objects = [+ b'<< /Type /Catalog /Pages 2 0 R >>',+ b'<< /Type /Pages /Kids [3 0 R] /Count 1 >>',+ (+ b'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] '+ b'/Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>'+ ),+ b'<< /Length ' + str( len( content_stream ) ).encode( 'latin-1' )+ + b' >>\nstream\n' + content_stream + b'\nendstream',+ b'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',+ ]++ output = bytearray( b'%PDF-1.4\n%\xe2\xe3\xcf\xd3\n' )+ offsets = []+ for index, body in enumerate( objects, start = 1 ):+ offsets.append( len( output ) )+ output += f'{index} 0 obj\n'.encode( 'latin-1' )+ output += body+ output += b'\nendobj\n'++ xref_offset = len( output )+ output += f'xref\n0 {len(objects) + 1}\n'.encode( 'latin-1' )+ output += b'0000000000 65535 f \n'+ for offset in offsets:+ output += f'{offset:010d} 00000 n \n'.encode( 'latin-1' )+ output += (+ f'trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\n'+ f'startxref\n{xref_offset}\n%%EOF\n'+ ).encode( 'latin-1' )+ return bytes( output )diff --git a/src/hi/simulator/services/homebox/sim_models.py b/src/hi/simulator/services/homebox/sim_models.pyindex d730b4f2..6b6d7a55 100644--- a/src/hi/simulator/services/homebox/sim_models.py+++ b/src/hi/simulator/services/homebox/sim_models.py@@ -10,7 +10,7 @@ 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 dataclasses import dataclass, field as dc_fieldfrom typing import Any, Dict, Listfrom hi.apps.common.utils import str_to_bool@@ -18,6 +18,12 @@ from hi.apps.common.utils import str_to_boolfrom hi.simulator.base_models import SimEntityFields, SimState, SimEntityDefinitionfrom hi.simulator.enums import SimEntityType, SimStateType+from .attachment_catalog import (+ attachment_choices,+ build_attachment_metadata,+ parse_attachment_keys,+)+@dataclass( frozen = True )class HomeBoxInventoryItemFields( SimEntityFields ):@@ -32,13 +38,33 @@ class HomeBoxInventoryItemFields( SimEntityFields ):item in two different profiles ends up with different ids."""- item_id : str = ''- description : str = ''- serial_number : str = ''- model_number : str = ''- manufacturer : str = ''- notes : str = ''- quantity : int = 1+ item_id : str = ''+ description : str = ''+ serial_number : str = ''+ model_number : str = ''+ manufacturer : str = ''+ notes : str = ''+ quantity : int = 1+ # Comma-separated wire keys of ``AttachmentTemplate`` members+ # (``hi.simulator.services.homebox.attachment_catalog``);+ # unknown keys are dropped silently. The simulator's API+ # download endpoint renders each referenced attachment's+ # bytes on demand, so this is the only place attachments+ # are configured per-item. The ``csv_choices`` metadata hook+ # tells ``SimEntityFieldsForm`` to render this as a+ # multi-checkbox picker over the catalog instead of a free-+ # text input.+ attachment_keys : str = dc_field(+ default = '',+ metadata = {+ 'csv_choices': attachment_choices,+ 'help_text': (+ 'Pre-canned simulator attachments to attach to '+ 'this item. Each selection is rendered on demand '+ 'when the integration fetches it.'+ ),+ },+ )@dataclass@@ -86,16 +112,23 @@ def build_item_api_dict( sim_entity_id : int,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 come- from the persisted ``DbSimEntity`` so they're stable across- reads — change only when the operator actually edits the row,- matching real HomeBox behavior.+ Fields not in the simulator's scope (custom fields, location,+ labels) are emitted as empty/null. Attachments are populated+ from the per-item ``attachment_keys`` CSV via the catalog in+ ``attachment_catalog``; the actual bytes are rendered on demand+ by the download endpoint when the integration fetches each+ attachment. Timestamps come from the persisted ``DbSimEntity``+ so they're stable across reads — change only when the operator+ actually edits the row, matching real HomeBox behavior."""# Prefer the operator-supplied stable id; fall back to the# auto-assigned PK for items that don't set one (legacy and# UI-created profiles).item_id = fields.item_id or str(sim_entity_id)+ attachments = [+ build_attachment_metadata( template )+ for template in parse_attachment_keys( fields.attachment_keys )+ ]return {'id' : item_id,'name' : fields.name,@@ -107,7 +140,7 @@ def build_item_api_dict( sim_entity_id : int,'quantity' : fields.quantity,'archived' : archived_state.is_archived,'fields' : [],- 'attachments' : [],+ 'attachments' : attachments,'location' : None,'labels' : [],'createdAt' : created_at.isoformat(),diff --git a/src/hi/simulator/services/zoneminder/sim_models.py b/src/hi/simulator/services/zoneminder/sim_models.pyindex cc2fe306..53a08aa2 100644--- a/src/hi/simulator/services/zoneminder/sim_models.py+++ b/src/hi/simulator/services/zoneminder/sim_models.py@@ -112,6 +112,10 @@ class ZmSimMonitor:def monitor_id(self) -> int:return int( self.sim_entity.sim_entity_fields.monitor_id )+ @property+ def name(self) -> str:+ return self.sim_entity.sim_entity_fields.name+@propertydef width(self):return self.sim_entity.sim_entity_fields.widthdiff --git a/src/hi/simulator/services/zoneminder/simulator.py b/src/hi/simulator/services/zoneminder/simulator.pyindex e47a8d0a..fc0e49f8 100644--- a/src/hi/simulator/services/zoneminder/simulator.py+++ b/src/hi/simulator/services/zoneminder/simulator.py@@ -35,6 +35,19 @@ class ZoneMinderSimulator( Simulator ):return [ ZmSimMonitor( sim_entity = x ) for x in self.sim_entitiesif x.sim_entity_definition.sim_entity_fields_class == ZmMonitorSimEntityFields ]+ def find_zm_monitor_by_id( self, monitor_id : int ) -> ZmSimMonitor:+ """Locate a monitor by its API id, or return None if no+ monitor in the active profile carries that id. Used by the+ media endpoints (thumbnail / MJPEG) to render frames with+ the correct monitor name; missing ids fall back to a+ generic placeholder rather than 404, to keep the simulator+ forgiving across profile switches that drop monitors."""+ for zm_sim_monitor in self.get_zm_monitor_sim_entity_list():+ if zm_sim_monitor.monitor_id == monitor_id:+ return zm_sim_monitor+ continue+ return None+def get_zm_server_sim_entity( self ) -> ZmSimServer:for sim_entity in self.sim_entities:if sim_entity.sim_entity_definition.sim_entity_fields_class == ZmServerSimEntityFields:diff --git a/src/hi/simulator/services/zoneminder/urls.py b/src/hi/simulator/services/zoneminder/urls.pyindex aa30db0f..e01e5c52 100644--- a/src/hi/simulator/services/zoneminder/urls.py+++ b/src/hi/simulator/services/zoneminder/urls.py@@ -8,5 +8,16 @@ urlpatterns = [views.HomeView.as_view(),name = 'zoneminder_home' ),+ # Portal-level paths the HI integration requests for media:+ # event thumbnails go through index.php?view=image, and live /+ # event playback streams go through cgi-bin/nph-zms.+ re_path( r'^index\.php$',+ views.IndexPhpView.as_view(),+ name = 'zoneminder_index_php' ),++ re_path( r'^cgi-bin/nph-zms$',+ views.NphZmsView.as_view(),+ name = 'zoneminder_nph_zms' ),+re_path( r'^api/', include('hi.simulator.services.zoneminder.api.urls' )),]diff --git a/src/hi/simulator/services/zoneminder/views.py b/src/hi/simulator/services/zoneminder/views.pyindex b54dd518..95dc76cc 100644--- a/src/hi/simulator/services/zoneminder/views.py+++ b/src/hi/simulator/services/zoneminder/views.py@@ -1,8 +1,193 @@+"""+Top-level (non-API) ZoneMinder simulator views.++ZoneMinder serves more than the JSON ``api/`` endpoints; the HI+integration also points at portal-level URLs for media:++ * ``index.php?view=image&eid=<id>&fid=snapshot`` — single-JPEG+ event thumbnail.+ * ``cgi-bin/nph-zms?...&monitor=<id>`` — live MJPEG.+ * ``cgi-bin/nph-zms?...&source=event&event=<id>`` — event playback+ MJPEG.++These endpoints respond with synthetic Pillow-rendered placeholder+frames (see ``zm_media``). The MJPEG flavors are bounded — the+response body contains a small fixed number of frames and a closing+boundary, so the client cycles once and stops on the last frame.+That's enough to exercise the HI player wiring without holding+long-lived streams open against Django's dev server.+"""+from django.http import HttpResponse, StreamingHttpResponsefrom django.views.generic import View+from .simulator import ZoneMinderSimulator+from .zm_event_manager import ZmSimEventManager+from .zm_media import (+ iter_bounded_mjpeg_parts,+ mjpeg_content_type,+ render_thumbnail_jpeg,+)+class HomeView( View ):def get(self, request, *args, **kwargs):pass-+++class IndexPhpView( View ):+ """Dispatch on the ``view`` query parameter. Real ZoneMinder's+ ``index.php`` is a multi-purpose entry point; we only honor+ ``view=image`` (used by the integration to fetch event+ thumbnails) and 404 anything else so unsupported portal paths+ don't silently render an empty body."""++ def get(self, request, *args, **kwargs):+ view_param = request.GET.get( 'view' )+ if view_param == 'image':+ return _event_image_response( request )+ return HttpResponse(+ f'Unsupported view "{view_param}".',+ status = 404,+ content_type = 'text/plain',+ )+++class NphZmsView( View ):+ """``cgi-bin/nph-zms`` MJPEG endpoint. The HI integration emits+ two URL flavors against this path:++ * ``source=event&event=<id>`` — event playback. Frames+ identify the monitor + event id.++ * ``monitor=<id>`` (no event params) — live feed. Frames+ identify the monitor.++ Both flavors return a bounded ``multipart/x-mixed-replace``+ response (single body containing N JPEG parts followed by a+ closing boundary). See ``zm_media`` for rationale on the+ bounded shape.+ """++ def get(self, request, *args, **kwargs):+ event_id_str = request.GET.get( 'event' )+ if event_id_str is not None:+ return self._event_playback_response( event_id_str = event_id_str )++ monitor_id_str = request.GET.get( 'monitor' )+ if monitor_id_str is not None:+ return self._live_stream_response( monitor_id_str = monitor_id_str )++ return HttpResponse(+ 'nph-zms requires monitor or event query parameter.',+ status = 400,+ content_type = 'text/plain',+ )++ def _event_playback_response( self, event_id_str : str ) -> StreamingHttpResponse:+ text_lines = [ 'Event Playback (simulator)' ]+ playback_start = None+ playback_duration = None+ try:+ event_id = int( event_id_str )+ except ValueError:+ text_lines.append( f'unknown event "{event_id_str}"' )+ else:+ zm_sim_event = ZmSimEventManager().find_event_by_id( event_id = event_id )+ if zm_sim_event is None:+ text_lines.append( f'event {event_id} (no record)' )+ else:+ text_lines.append(+ f'monitor: {zm_sim_event.zm_sim_monitor.name}',+ )+ text_lines.append( f'event id: {event_id}' )+ playback_start = zm_sim_event.start_datetime+ # ``length_secs`` is an event-driven value the+ # simulator updates as the event is closed; it can+ # legitimately be 0 for an event that opened and+ # closed in the same poll. Fall back to a small+ # nonzero window so the interpolated frame times+ # still show motion.+ playback_duration = (+ zm_sim_event.length_secs if zm_sim_event.length_secs else 1.0+ )+ return _streaming_mjpeg_response(+ text_lines = text_lines,+ playback_start = playback_start,+ playback_duration = playback_duration,+ )++ def _live_stream_response( self, monitor_id_str : str ) -> StreamingHttpResponse:+ text_lines = [ 'Live Stream (simulator)' ]+ try:+ monitor_id = int( monitor_id_str )+ except ValueError:+ text_lines.append( f'unknown monitor "{monitor_id_str}"' )+ else:+ zm_sim_monitor = ZoneMinderSimulator().find_zm_monitor_by_id(+ monitor_id = monitor_id,+ )+ if zm_sim_monitor is None:+ text_lines.append( f'monitor {monitor_id} (no record)' )+ else:+ text_lines.append( f'monitor: {zm_sim_monitor.name}' )+ text_lines.append( f'id: {monitor_id}' )+ return _streaming_mjpeg_response( text_lines = text_lines )+++def _streaming_mjpeg_response(+ text_lines,+ playback_start = None,+ playback_duration = None,+) -> StreamingHttpResponse:+ """Build the StreamingHttpResponse for an MJPEG endpoint with+ cache-busting headers. Without ``no-store`` the browser caches+ the multipart response and replays it instantly on the next+ fetch, which collapses the rendered animation to the last frame+ (the renderer sees all parts arrive in one tick). Real+ ZoneMinder also emits no-cache headers for the same reason.++ ``playback_start`` + ``playback_duration``, when provided, make+ the rendered frame timestamps span the event's actual time+ window instead of wall-clock now (event-replay flavor)."""+ response = StreamingHttpResponse(+ iter_bounded_mjpeg_parts(+ text_lines = text_lines,+ playback_start = playback_start,+ playback_duration = playback_duration,+ ),+ content_type = mjpeg_content_type(),+ )+ _apply_no_cache_headers( response )+ return response+++def _apply_no_cache_headers( response ) -> None:+ response['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0'+ response['Pragma'] = 'no-cache'+ response['Expires'] = '0'+ return+++def _event_image_response( request ) -> HttpResponse:+ event_id_str = request.GET.get( 'eid' )+ text_lines = [ 'Event Snapshot (simulator)' ]+ try:+ event_id = int( event_id_str ) if event_id_str else None+ except ValueError:+ event_id = None+ if event_id is None:+ text_lines.append( f'unknown event "{event_id_str}"' )+ else:+ zm_sim_event = ZmSimEventManager().find_event_by_id( event_id = event_id )+ if zm_sim_event is None:+ text_lines.append( f'event {event_id} (no record)' )+ else:+ text_lines.append( f'monitor: {zm_sim_event.zm_sim_monitor.name}' )+ text_lines.append( f'event id: {event_id}' )+ response = HttpResponse(+ render_thumbnail_jpeg( text_lines = text_lines ),+ content_type = 'image/jpeg',+ )+ _apply_no_cache_headers( response )+ return responsediff --git a/src/hi/simulator/services/zoneminder/zm_event_manager.py b/src/hi/simulator/services/zoneminder/zm_event_manager.pyindex ceb6c269..94ca49d9 100644--- a/src/hi/simulator/services/zoneminder/zm_event_manager.py+++ b/src/hi/simulator/services/zoneminder/zm_event_manager.py@@ -36,6 +36,22 @@ class ZmSimEventManager( Singleton ):self._update_zm_sim_events( zm_sim_event_list = zm_sim_event_list )return zm_sim_event_list+ def find_event_by_id( self, event_id : int ) -> ZmSimEvent:+ """Walk every monitor's history and return the first event+ with the given id, or None if no match. Used by the media+ endpoints (thumbnail / MJPEG playback) to render frames+ with the right monitor + event metadata baked in. Returns+ None for unknown ids so the views can fall back to a+ generic placeholder rather than 404."""+ with self._data_lock:+ for zm_event_history in self._zm_sim_events_map.values():+ for zm_sim_event in zm_event_history._zm_sim_events:+ if zm_sim_event.event_id == event_id:+ return zm_sim_event+ continue+ continue+ return None+def _update_zm_sim_events( self, zm_sim_event_list : List[ ZmSimEvent ] ):for zm_sim_event in zm_sim_event_list:if zm_sim_event.is_active:diff --git a/src/hi/simulator/services/zoneminder/zm_media.py b/src/hi/simulator/services/zoneminder/zm_media.pynew file mode 100644index 00000000..e1438cda--- /dev/null+++ b/src/hi/simulator/services/zoneminder/zm_media.py@@ -0,0 +1,198 @@+"""+Synthetic ZoneMinder media generation for the simulator.++ZoneMinder serves three byte-shapes the HI integration consumes:++ 1. Event snapshot thumbnails — single JPEG via+ ``index.php?view=image&eid=<id>&fid=snapshot``.++ 2. Event playback — a *bounded* MJPEG stream+ (``multipart/x-mixed-replace`` response containing N JPEG+ parts) via ``cgi-bin/nph-zms?...&source=event&event=<id>``.++ 3. Live camera feed — same MJPEG shape via+ ``cgi-bin/nph-zms?...&monitor=<id>``.++The simulator collapses all three into the same primitives:+``render_jpeg_frame`` (Pillow-rendered placeholder) and+``iter_bounded_mjpeg_parts`` (yields each multipart chunk with a+delay between frames so the browser's MJPEG renderer animates+through them rather than collapsing to the last frame). The "live"+stream is bounded too — it cycles through a fixed frame count and+ends — which is enough to exercise the HI player's wiring without+holding a long-running connection open against Django's dev server.++Frame content carries operator-visible identifiers (monitor name,+event id, frame number, current time) so that artifacts viewed+inside HI are obviously coming from the simulator and from which+specific monitor/event.+"""+import io+import time+from datetime import datetime, timedelta+from typing import Iterator, List, Optional, Tuple++from PIL import Image, ImageDraw++import hi.apps.common.datetimeproxy as datetimeproxy+++# Single boundary string is reused across all MJPEG responses; the+# bytes are arbitrary as long as they don't appear in the JPEG+# payload (JPEGs start with ``\xff\xd8`` and end with ``\xff\xd9``,+# and never contain the literal "ZmSimulatorMjpegBoundary" string).+_MJPEG_BOUNDARY = b'ZmSimulatorMjpegBoundary'++# Fixed frame count for bounded MJPEG. Small enough to keep each+# stream short, large enough that the operator sees the player+# animate before the response ends.+_DEFAULT_FRAME_COUNT = 8++# Inter-frame delay. Real ZoneMinder MJPEG runs around 5 fps; we+# slow it slightly so the "(simulator)" frame counter is readable.+_DEFAULT_FRAME_INTERVAL_SECS = 0.5++# Modest default size — recognizable text, low render cost.+_FRAME_WIDTH = 320+_FRAME_HEIGHT = 240+++def render_thumbnail_jpeg( text_lines : List[str] ) -> bytes:+ """Single placeholder JPEG used as an event snapshot thumbnail.+ ``text_lines`` is rendered in stacked rows; callers typically+ pass the monitor name, event id, and timestamp so the+ artifact is identifiable inside HI."""+ return _render_jpeg_frame( text_lines = text_lines )+++def mjpeg_content_type() -> str:+ """``Content-Type`` header value pairing the streamed body with+ its multipart boundary."""+ return (+ f'multipart/x-mixed-replace; boundary={_MJPEG_BOUNDARY.decode("latin-1")}'+ )+++def iter_bounded_mjpeg_parts(+ text_lines : List[str],+ frame_count : int = _DEFAULT_FRAME_COUNT,+ frame_interval : float = _DEFAULT_FRAME_INTERVAL_SECS,+ playback_start : Optional[datetime] = None,+ playback_duration : Optional[float] = None,+) -> Iterator[ bytes ]:+ """Yield multipart chunks for a bounded MJPEG stream — one+ boundary+headers+JPEG body per frame, with a sleep between+ frames so the browser's MJPEG renderer actually animates.+ Without the sleep the parts arrive in a single TCP burst and+ the renderer collapses to the last frame.++ ``playback_start`` + ``playback_duration`` (when both provided)+ interpolate a frame timestamp across the playback window so an+ event replay shows the event's actual time progression rather+ than wall-clock now. When omitted, frames stamp the current+ time — the right behavior for a live feed.++ Used with ``StreamingHttpResponse``; pair the iterator with+ ``mjpeg_content_type()`` for the response header. Total stream+ duration is ``frame_count * frame_interval``; the connection+ closes naturally after the last frame so we don't hold an+ open-ended live feed against the Django dev server.+ """+ boundary = _MJPEG_BOUNDARY+ for index in range( frame_count ):+ frame_text = list( text_lines ) + [+ f'frame {index + 1}/{frame_count}',+ ]+ jpeg_bytes = _render_jpeg_frame(+ text_lines = frame_text,+ timestamp_override = _interpolated_frame_time(+ playback_start = playback_start,+ playback_duration = playback_duration,+ index = index,+ frame_count = frame_count,+ ),+ )+ part = (+ b'--' + boundary + b'\r\n'+ + b'Content-Type: image/jpeg\r\n'+ + f'Content-Length: {len(jpeg_bytes)}\r\n\r\n'.encode( 'latin-1' )+ + jpeg_bytes+ + b'\r\n'+ )+ yield part+ # Sleep AFTER yielding the frame so the browser sees a+ # cadence between frames; the final frame still gets+ # displayed for ``frame_interval`` before the closing+ # boundary tells the browser the stream has ended.+ time.sleep( frame_interval )+ yield b'--' + boundary + b'--\r\n'+++def _interpolated_frame_time(+ playback_start : Optional[datetime],+ playback_duration : Optional[float],+ index : int,+ frame_count : int,+) -> Optional[datetime]:+ """Linearly interpolate a frame's timestamp across the playback+ window. Frame 0 lands at ``playback_start``; the last frame+ lands at ``playback_start + playback_duration``. Returns None+ when either bound is missing — the renderer then falls back to+ wall-clock time."""+ if playback_start is None or playback_duration is None:+ return None+ if frame_count <= 1:+ return playback_start+ progress = index / ( frame_count - 1 )+ return playback_start + timedelta( seconds = playback_duration * progress )+++# Backward-compatible non-streaming variant kept for callers that+# want a single bytes blob (e.g., tests). Note that delivering this+# in one HttpResponse causes browsers to render only the last frame+# — use ``iter_bounded_mjpeg_parts`` + ``StreamingHttpResponse`` for+# anything the operator will actually view.+def render_bounded_mjpeg_response(+ text_lines : List[str],+ frame_count : int = _DEFAULT_FRAME_COUNT,+) -> Tuple[ bytes, str ]:+ body = b''.join(+ iter_bounded_mjpeg_parts(+ text_lines = text_lines,+ frame_count = frame_count,+ frame_interval = 0.0,+ )+ )+ return body, mjpeg_content_type()+++def _render_jpeg_frame(+ text_lines : List[str],+ timestamp_override : Optional[datetime] = None,+) -> bytes:+ """Pillow-rendered single JPEG frame. Default bitmap font so the+ simulator stays independent of system font availability. The+ timestamp line is appended automatically so multiple frames+ rendered in quick succession still differ visibly. When+ ``timestamp_override`` is provided (event playback), that value+ is rendered instead of wall-clock now."""+ raw_timestamp = (+ timestamp_override if timestamp_override is not None else datetimeproxy.now()+ )+ timestamp = raw_timestamp.strftime( '%Y-%m-%d %H:%M:%S' )+ image = Image.new(+ mode = 'RGB',+ size = ( _FRAME_WIDTH, _FRAME_HEIGHT ),+ color = ( 25, 30, 50 ),+ )+ draw = ImageDraw.Draw( image )+ y = 30+ for line in text_lines:+ draw.text( ( 20, y ), line, fill = ( 230, 240, 250 ) )+ y += 24+ draw.text( ( 20, _FRAME_HEIGHT - 30 ), timestamp, fill = ( 150, 170, 200 ) )+ draw.text( ( _FRAME_WIDTH - 110, _FRAME_HEIGHT - 30 ),+ '(simulator)', fill = ( 120, 130, 150 ) )+ buffer = io.BytesIO()+ image.save( buffer, format = 'JPEG', quality = 70 )+ return buffer.getvalue()diff --git a/src/hi/simulator/templates/simulator/panes/sim_control_movement.html b/src/hi/simulator/templates/simulator/panes/sim_control_movement.htmlindex 3975a1fa..d658820e 100644--- a/src/hi/simulator/templates/simulator/panes/sim_control_movement.html+++ b/src/hi/simulator/templates/simulator/panes/sim_control_movement.html@@ -1,7 +1,7 @@IDLE<label class="switch"><input type="checkbox" name="value"- {% if sim_state.value %}checked="true"{% endif %}+ {% if sim_state.is_on %}checked="true"{% endif %}onchange-async="true" ><span class="slider"></span></label>diff --git a/src/hi/simulator/templates/simulator/panes/sim_control_on_off.html b/src/hi/simulator/templates/simulator/panes/sim_control_on_off.htmlindex 56222801..4aa5744c 100644--- a/src/hi/simulator/templates/simulator/panes/sim_control_on_off.html+++ b/src/hi/simulator/templates/simulator/panes/sim_control_on_off.html@@ -1,7 +1,7 @@OFF<label class="switch"><input type="checkbox" name="value"- {% if sim_state.value %}checked="true"{% endif %}+ {% if sim_state.is_on %}checked="true"{% endif %}onchange-async="true" ><span class="slider"></span></label>diff --git a/src/hi/simulator/templates/simulator/panes/sim_control_open_close.html b/src/hi/simulator/templates/simulator/panes/sim_control_open_close.htmlindex 2256388e..78c5448c 100644--- a/src/hi/simulator/templates/simulator/panes/sim_control_open_close.html+++ b/src/hi/simulator/templates/simulator/panes/sim_control_open_close.html@@ -1,7 +1,7 @@CLOSED<label class="switch"><input type="checkbox" name="value"- {% if sim_state.value %}checked="true"{% endif %}+ {% if sim_state.is_on %}checked="true"{% endif %}onchange-async="true" ><span class="slider"></span></label>