Skip to content

Home Information - Your home, your data, organized.

Python

Add video_snapshot capability with HA camera support (#334)

Tony C2ae4f5cfd71d
diff --git a/src/hi/apps/entity/migrations/0017_entity_has_video_snapshot.py b/src/hi/apps/entity/migrations/0017_entity_has_video_snapshot.py
new file mode 100644
index 00000000..dcc71fdd
--- /dev/null
+++ b/src/hi/apps/entity/migrations/0017_entity_has_video_snapshot.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.14 on 2026-05-15 21:37
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("entity", "0016_add_entity_state_role"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="entity",
+ name="has_video_snapshot",
+ field=models.BooleanField(
+ default=False,
+ help_text="Whether the source integration can provide a still image of this entity (e.g., HA camera entity_picture, ZM nph-zms mode=single). Orthogonal to has_video_stream: an entity may provide either, both, or neither capability.",
+ verbose_name="Has Video Snapshot",
+ ),
+ ),
+ ]
diff --git a/src/hi/apps/entity/migrations/0018_backfill_zoneminder_has_video_snapshot.py b/src/hi/apps/entity/migrations/0018_backfill_zoneminder_has_video_snapshot.py
new file mode 100644
index 00000000..11776716
--- /dev/null
+++ b/src/hi/apps/entity/migrations/0018_backfill_zoneminder_has_video_snapshot.py
@@ -0,0 +1,50 @@
+from django.db import migrations
+
+
+def backfill_zoneminder_camera_snapshot_flag(apps, schema_editor):
+ """Set has_video_snapshot=True for existing ZoneMinder camera
+ entities. ZM monitors natively provide a still-image URL via
+ ``nph-zms?mode=single``; the gateway's get_entity_video_snapshot
+ override exposes that capability. Existing entities (imported
+ before this field existed) need their flag flipped once via this
+ backfill; future sync runs set the flag at create-time.
+
+ Filters on ``has_video_stream=True`` rather than entity_type to
+ survive user reclassification: entity_type is user-mutable after
+ import, but ``has_video_stream`` is integration-owned and only set
+ by the ZM sync path, so it stays a reliable proxy for "this entity
+ is backed by a ZM monitor."
+ """
+ Entity = apps.get_model('entity', 'Entity')
+
+ zm_cameras = Entity.objects.filter(
+ integration_id='zm',
+ has_video_stream=True,
+ )
+ updated = zm_cameras.update(has_video_snapshot=True)
+ print(f'Backfilled has_video_snapshot=True on {updated} ZoneMinder camera entities')
+
+
+def reverse_backfill(apps, schema_editor):
+ Entity = apps.get_model('entity', 'Entity')
+
+ reverted = Entity.objects.filter(
+ integration_id='zm',
+ has_video_stream=True,
+ has_video_snapshot=True,
+ ).update(has_video_snapshot=False)
+ print(f'Reverted has_video_snapshot=False on {reverted} ZoneMinder camera entities')
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('entity', '0017_entity_has_video_snapshot'),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ backfill_zoneminder_camera_snapshot_flag,
+ reverse_backfill,
+ ),
+ ]
diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.py
index bbad086e..13349ec1 100644
--- a/src/hi/apps/entity/models.py
+++ b/src/hi/apps/entity/models.py
@@ -60,6 +60,16 @@ class Entity( IntegrationDetailsModel, LocationItemModelMixin ):
'Has Video Stream',
default = False,
)
+ has_video_snapshot = models.BooleanField(
+ 'Has Video Snapshot',
+ default = False,
+ help_text = (
+ 'Whether the source integration can provide a still image of '
+ 'this entity (e.g., HA camera entity_picture, ZM nph-zms '
+ 'mode=single). Orthogonal to has_video_stream: an entity may '
+ 'provide either, both, or neither capability.'
+ ),
+ )
is_disabled = models.BooleanField(
'Disabled?',
default = False,
diff --git a/src/hi/apps/entity/transient_models.py b/src/hi/apps/entity/transient_models.py
index 05aa5e6b..73bb0356 100644
--- a/src/hi/apps/entity/transient_models.py
+++ b/src/hi/apps/entity/transient_models.py
@@ -15,13 +15,32 @@ class VideoStream:
stream_type: VideoStreamType
source_url: str = None
metadata: Dict[str, Any] = field(default_factory=dict)
-
+
# Future extensibility:
# webrtc_config: WebRTCConfig = None
# hls_manifest_url: str = None
# thumbnail_url: str = None
+@dataclass
+class VideoSnapshot:
+ """A still image of a camera's current view, fetched on demand.
+
+ Parallel to ``VideoStream`` but distinct because the two capabilities
+ are orthogonal: an entity can provide a stream, a snapshot, both, or
+ neither. Integrations declare what they natively provide via the
+ corresponding gateway methods (``get_entity_video_stream`` /
+ ``get_entity_video_snapshot``); higher-level synthesis (e.g.,
+ presenting a snapshot-only camera as a low-rate refresh "stream"
+ for display) is a separate concern that consumes both capabilities.
+
+ Naming note: "video_snapshot" is used (rather than bare "snapshot")
+ to disambiguate from the existing ZoneMinder event-snapshot
+ terminology (a frame extracted from a past recorded event)."""
+ source_url: str = None
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
@dataclass
class EntityViewItem:
diff --git a/src/hi/integrations/integration_gateway.py b/src/hi/integrations/integration_gateway.py
index 80bacfd2..af9b5ad2 100644
--- a/src/hi/integrations/integration_gateway.py
+++ b/src/hi/integrations/integration_gateway.py
@@ -1,7 +1,7 @@
from typing import List, Optional
from hi.apps.entity.models import Entity
-from hi.apps.entity.transient_models import VideoStream
+from hi.apps.entity.transient_models import VideoSnapshot, VideoStream
from hi.apps.monitor.periodic_monitor import PeriodicMonitor
from hi.apps.sense.transient_models import SensorResponse
from hi.apps.system.health_status_provider import HealthStatusProvider
@@ -88,7 +88,10 @@ class IntegrationGateway:
def get_entity_video_stream(self, entity: Entity) -> Optional[VideoStream]:
return None
-
+
+ def get_entity_video_snapshot(self, entity: Entity) -> Optional[VideoSnapshot]:
+ return None
+
def get_sensor_response_video_stream(
self,
sensor_response: SensorResponse) -> Optional[VideoStream]:
diff --git a/src/hi/services/hass/hass_client.py b/src/hi/services/hass/hass_client.py
index 827e18f6..b1ff08b5 100644
--- a/src/hi/services/hass/hass_client.py
+++ b/src/hi/services/hass/hass_client.py
@@ -41,6 +41,10 @@ class HassClient:
self._timeout_secs = timeout_secs if timeout_secs is not None else self.DEFAULT_TIMEOUT
return
+ @property
+ def api_base_url(self) -> str:
+ return self._api_base_url
+
def states(self) -> List[ HassState ]:
url = f'{self._api_base_url}/api/states'
diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.py
index ac5bb4cf..7ccda5a5 100644
--- a/src/hi/services/hass/hass_converter.py
+++ b/src/hi/services/hass/hass_converter.py
@@ -267,7 +267,10 @@ class HassConverter:
(HassApi.SENSOR_DOMAIN, None, None): EntityStateType.BLOB, # Generic sensor
# Other domains (read-only)
- # Note: CAMERA_DOMAIN entities should have has_video_stream=True but no VIDEO_STREAM EntityState
+ # Note: CAMERA_DOMAIN entities expose video_snapshot capability
+ # via has_video_snapshot (set during _create_or_reconnect_entity),
+ # not via an EntityStateType here. They have no native video
+ # stream so has_video_stream stays False.
(HassApi.SUN_DOMAIN, None, None): EntityStateType.MULTIVALUED,
(HassApi.WEATHER_DOMAIN, None, None): EntityStateType.MULTIVALUED,
}
@@ -541,6 +544,7 @@ class HassConverter:
# reconnect so the entity reflects current upstream state.
entity.integration_key = entity_integration_key
entity.can_user_delete = HassMetaData.allow_entity_deletion
+ entity.has_video_snapshot = HassApi.CAMERA_DOMAIN in hass_device.domain_set
entity.save()
insteon_address = cls.hass_device_to_insteon_address( hass_device )
@@ -581,6 +585,16 @@ class HassConverter:
messages = list()
with transaction.atomic():
+ # Re-derive integration-owned capability flags from the
+ # current upstream device shape. Self-healing if HA's
+ # domain composition changes (e.g., a paired motion sensor
+ # added or removed), and the only point where pre-PR HA
+ # cameras pick up has_video_snapshot=True.
+ has_video_snapshot = HassApi.CAMERA_DOMAIN in hass_device.domain_set
+ if entity.has_video_snapshot != has_video_snapshot:
+ entity.has_video_snapshot = has_video_snapshot
+ entity.save( update_fields = [ 'has_video_snapshot' ] )
+
insteon_address = cls.hass_device_to_insteon_address( hass_device )
try:
attribute = entity.attributes.get( name = cls.INSTEON_ADDRESS_ATTR_NAME )
diff --git a/src/hi/services/hass/hass_manager.py b/src/hi/services/hass/hass_manager.py
index 71061853..da9f8581 100644
--- a/src/hi/services/hass/hass_manager.py
+++ b/src/hi/services/hass/hass_manager.py
@@ -1,6 +1,9 @@
import logging
+import threading
from asgiref.sync import sync_to_async
-from typing import Dict, List, Optional
+from typing import Any, Dict, List, Optional
+
+from cachetools import LRUCache
from hi.apps.common.singleton_manager import SingletonManager
from hi.apps.common.utils import str_to_bool
@@ -25,13 +28,17 @@ from .enums import HassAttributeType
from .hass_client import HassClient
from .hass_client_factory import HassClientFactory
from .hass_metadata import HassMetaData
-from .hass_models import HassState
+from .hass_models import HassApi, HassState
logger = logging.getLogger(__name__)
class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusProvider ):
+ # Generous against realistic HA installs; bounded only as memory
+ # defense against pathological long-running scale.
+ LATEST_ATTRS_CACHE_MAXSIZE = 128
+
def __init_singleton__( self ):
super().__init_singleton__()
self._hass_attr_type_to_attribute = dict()
@@ -40,6 +47,15 @@ class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusPro
self._change_listeners = set()
+ # Selective-insert LRU cache (see update_latest_attrs_cache
+ # for the policy). The lock guards both writes and reads
+ # because LRUCache.__getitem__ bumps the recency order, so
+ # readers implicitly write to the underlying OrderedDict.
+ self._latest_attrs_by_entity_id = LRUCache(
+ maxsize = self.LATEST_ATTRS_CACHE_MAXSIZE,
+ )
+ self._latest_attrs_lock = threading.Lock()
+
# Add self as the API health status provider to aggregate
self.add_api_health_status_provider(self)
@@ -118,8 +134,26 @@ class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusPro
return
def clear_caches(self):
+ with self._latest_attrs_lock:
+ self._latest_attrs_by_entity_id.clear()
return
+ def update_latest_attrs_cache( self, hass_state_map : Dict[ str, HassState ] ):
+ """Refresh per-entity attributes from a polling snapshot.
+ Selective insert: only domains downstream code needs
+ attribute access for are cached; other domains pass through
+ without consuming cache slots."""
+ with self._latest_attrs_lock:
+ for entity_id, state in hass_state_map.items():
+ if state.domain != HassApi.CAMERA_DOMAIN:
+ continue
+ self._latest_attrs_by_entity_id[ entity_id ] = dict( state.attributes )
+ return
+
+ def get_latest_attrs( self, entity_id : str ) -> Optional[ Dict[ str, Any ] ]:
+ with self._latest_attrs_lock:
+ return self._latest_attrs_by_entity_id.get( entity_id )
+
def _load_attributes(self) -> Dict[ HassAttributeType, IntegrationAttribute ]:
try:
hass_integration = Integration.objects.get( integration_id = HassMetaData.integration_id )
diff --git a/src/hi/services/hass/integration.py b/src/hi/services/hass/integration.py
index d8abdfe5..d2175e58 100644
--- a/src/hi/services/hass/integration.py
+++ b/src/hi/services/hass/integration.py
@@ -1,6 +1,8 @@
import logging
from typing import List, Optional
+from hi.apps.entity.models import Entity
+from hi.apps.entity.transient_models import VideoSnapshot
from hi.apps.system.enums import HealthStatusType
from hi.apps.system.health_status_provider import HealthStatusProvider
@@ -87,3 +89,32 @@ class HassGateway( IntegrationGateway ):
except Exception as e:
logger.exception(f'Error in HASS connection test: {e}')
return ConnectionTestResult.failure(f'Connection test error: {e}')
+
+ def get_entity_video_snapshot(self, entity: Entity) -> Optional[VideoSnapshot]:
+ if not entity.has_video_snapshot:
+ return None
+ if entity.integration_id != HassMetaData.integration_id:
+ return None
+ if not entity.integration_name:
+ return None
+
+ hass_manager = HassManager()
+ attrs = hass_manager.get_latest_attrs( entity.integration_name )
+ if not attrs:
+ return None
+
+ entity_picture = attrs.get( 'entity_picture' )
+ if not entity_picture:
+ return None
+
+ # Some HA integrations emit an absolute URL; pass those
+ # through unchanged. Relative paths get the HA base prefix.
+ if entity_picture.startswith( ('http://', 'https://') ):
+ source_url = entity_picture
+ else:
+ client = hass_manager.hass_client
+ if not client:
+ return None
+ source_url = f'{client.api_base_url}{entity_picture}'
+
+ return VideoSnapshot( source_url = source_url )
diff --git a/src/hi/services/hass/monitors.py b/src/hi/services/hass/monitors.py
index 9ea4ce77..fe20c62f 100644
--- a/src/hi/services/hass/monitors.py
+++ b/src/hi/services/hass/monitors.py
@@ -92,7 +92,9 @@ class HassMonitor( PeriodicMonitor, HassMixin, SensorResponseMixin ):
id_to_hass_state_map = await hass_manager.fetch_hass_states_from_api_async( verbose = False )
logger.debug( f'Fetched {len(id_to_hass_state_map)} HAss States' )
-
+
+ hass_manager.update_latest_attrs_cache( id_to_hass_state_map )
+
current_datetime = datetimeproxy.now()
sensor_response_latest_map = dict()
diff --git a/src/hi/services/hass/tests/test_hass_converter_create.py b/src/hi/services/hass/tests/test_hass_converter_create.py
index 0a17ed9a..a3deeddd 100644
--- a/src/hi/services/hass/tests/test_hass_converter_create.py
+++ b/src/hi/services/hass/tests/test_hass_converter_create.py
@@ -388,3 +388,121 @@ class EventDefinitionLifecycleCycleTests(TestCase):
entity=entity,
)
self.assertEqual(self._hass_event_def_count(), 1)
+
+
+class CameraDeviceVideoSnapshotFlagTests(TestCase):
+ """Camera-domain HA devices must surface as Entities with
+ ``has_video_snapshot=True``; the gateway uses that flag to gate
+ snapshot-URL resolution. Covers create, reconnect, and update
+ paths; the update path is the only one that heals pre-existing
+ entities imported before the field existed."""
+
+ def _build_camera_device(self, device_id='front_door'):
+ api_dict = {
+ 'entity_id': f'camera.{device_id}',
+ 'state': 'idle',
+ 'attributes': {
+ 'friendly_name': device_id.replace('_', ' ').title(),
+ 'entity_picture': f'/api/camera_proxy/camera.{device_id}?token=abc',
+ 'access_token': 'abc',
+ },
+ 'last_changed': '2026-01-01T00:00:00+00:00',
+ 'last_reported': '2026-01-01T00:00:00+00:00',
+ 'last_updated': '2026-01-01T00:00:00+00:00',
+ 'context': {'id': 'ctx', 'parent_id': None, 'user_id': None},
+ }
+ hass_state = HassConverter.create_hass_state(api_dict)
+ device = HassDevice(device_id=device_id)
+ device.add_state(hass_state)
+ return device
+
+ def _build_non_camera_device(self, device_id='kitchen_light'):
+ api_dict = {
+ 'entity_id': f'light.{device_id}',
+ 'state': 'on',
+ 'attributes': {
+ 'friendly_name': device_id.replace('_', ' ').title(),
+ 'supported_color_modes': ['onoff'],
+ 'color_mode': 'onoff',
+ },
+ 'last_changed': '2026-01-01T00:00:00+00:00',
+ 'last_reported': '2026-01-01T00:00:00+00:00',
+ 'last_updated': '2026-01-01T00:00:00+00:00',
+ 'context': {'id': 'ctx', 'parent_id': None, 'user_id': None},
+ }
+ hass_state = HassConverter.create_hass_state(api_dict)
+ device = HassDevice(device_id=device_id)
+ device.add_state(hass_state)
+ return device
+
+ def test_create_sets_flag_for_camera_device(self):
+ entity = HassConverter.create_models_for_hass_device(
+ hass_device=self._build_camera_device(),
+ add_alarm_events=False,
+ )
+ self.assertTrue(entity.has_video_snapshot)
+
+ def test_create_leaves_flag_off_for_non_camera_device(self):
+ entity = HassConverter.create_models_for_hass_device(
+ hass_device=self._build_non_camera_device(),
+ add_alarm_events=False,
+ )
+ self.assertFalse(entity.has_video_snapshot)
+
+ def test_reconnect_sets_flag_on_existing_entity(self):
+ existing = Entity.objects.create(
+ name='User Renamed Camera',
+ entity_type_str='CAMERA',
+ has_video_snapshot=False,
+ )
+ HassConverter.create_models_for_hass_device(
+ hass_device=self._build_camera_device(),
+ add_alarm_events=False,
+ entity=existing,
+ )
+ existing.refresh_from_db()
+ self.assertTrue(existing.has_video_snapshot)
+
+ def test_update_heals_flag_on_existing_camera_entity(self):
+ """Pre-PR cameras stay has_video_snapshot=False until the
+ next sync cycle calls update_models_for_hass_device, which
+ re-derives the flag from the current upstream device."""
+ existing = Entity.objects.create(
+ name='User Renamed Camera',
+ entity_type_str='CAMERA',
+ has_video_snapshot=False,
+ )
+ # Set integration key so the converter recognizes the
+ # entity as HASS-owned and the update path is well-formed.
+ existing.integration_id = HassMetaData.integration_id
+ existing.integration_name = 'camera.front_door'
+ existing.save()
+
+ HassConverter.update_models_for_hass_device(
+ entity=existing,
+ hass_device=self._build_camera_device(),
+ )
+
+ existing.refresh_from_db()
+ self.assertTrue(existing.has_video_snapshot)
+
+ def test_update_clears_flag_when_device_no_longer_camera(self):
+ """Self-healing in the opposite direction: if upstream
+ reshapes a device away from the camera domain, the flag
+ comes down."""
+ existing = Entity.objects.create(
+ name='Was a camera',
+ entity_type_str='LIGHT',
+ has_video_snapshot=True,
+ )
+ existing.integration_id = HassMetaData.integration_id
+ existing.integration_name = 'light.kitchen_light'
+ existing.save()
+
+ HassConverter.update_models_for_hass_device(
+ entity=existing,
+ hass_device=self._build_non_camera_device(),
+ )
+
+ existing.refresh_from_db()
+ self.assertFalse(existing.has_video_snapshot)
diff --git a/src/hi/services/hass/tests/test_hass_manager.py b/src/hi/services/hass/tests/test_hass_manager.py
index 9dc098ae..cb2f096e 100644
--- a/src/hi/services/hass/tests/test_hass_manager.py
+++ b/src/hi/services/hass/tests/test_hass_manager.py
@@ -733,11 +733,70 @@ class TestHassManagerProperties(TestCase):
"""Test clear_caches method exists and is callable"""
# Should not raise exception
self.manager.clear_caches()
-
+
# Method should be callable
self.assertTrue(callable(self.manager.clear_caches))
+class TestHassManagerLatestAttrsCache(TestCase):
+ """Selective-insert policy: only camera-domain entities populate
+ the cache. The downstream consumer is the snapshot gateway, so
+ caching states from other domains would burn slots needlessly."""
+
+ def setUp(self):
+ HassManager._instance = None
+ HassManager._lock = threading.Lock()
+ self.manager = HassManager()
+
+ def _state(self, entity_id, attributes=None):
+ s = Mock()
+ s.entity_id = entity_id
+ s.domain = entity_id.split('.')[0]
+ s.attributes = attributes or {}
+ return s
+
+ def test_only_camera_domain_states_populate_cache(self):
+ states = {
+ 'camera.front_door': self._state(
+ 'camera.front_door',
+ {'entity_picture': '/api/camera_proxy/camera.front_door?token=x'},
+ ),
+ 'light.kitchen': self._state('light.kitchen', {'brightness': 128}),
+ 'sensor.temp': self._state('sensor.temp', {'unit': 'C'}),
+ 'binary_sensor.motion': self._state('binary_sensor.motion'),
+ }
+
+ self.manager.update_latest_attrs_cache(states)
+
+ self.assertIsNotNone(self.manager.get_latest_attrs('camera.front_door'))
+ self.assertIsNone(self.manager.get_latest_attrs('light.kitchen'))
+ self.assertIsNone(self.manager.get_latest_attrs('sensor.temp'))
+ self.assertIsNone(self.manager.get_latest_attrs('binary_sensor.motion'))
+
+ def test_cache_stores_a_snapshot_not_a_reference(self):
+ """A subsequent mutation of the upstream state's attributes
+ must not leak into the cached dict; consumers rely on the
+ cached value matching the poll-time snapshot."""
+ attrs = {'entity_picture': '/api/camera_proxy/camera.front_door?token=v1'}
+ state = self._state('camera.front_door', attrs)
+
+ self.manager.update_latest_attrs_cache({'camera.front_door': state})
+ attrs['entity_picture'] = '/api/camera_proxy/camera.front_door?token=MUTATED'
+
+ cached = self.manager.get_latest_attrs('camera.front_door')
+ self.assertEqual(
+ cached['entity_picture'],
+ '/api/camera_proxy/camera.front_door?token=v1',
+ )
+
+ def test_clear_caches_drops_cached_attrs(self):
+ self.manager.update_latest_attrs_cache({
+ 'camera.front_door': self._state('camera.front_door', {'k': 'v'}),
+ })
+ self.manager.clear_caches()
+ self.assertIsNone(self.manager.get_latest_attrs('camera.front_door'))
+
+
class TestHassManagerIntegrationBoundaries(TestCase):
"""Test integration boundary behavior and error handling"""
diff --git a/src/hi/services/hass/tests/test_integration.py b/src/hi/services/hass/tests/test_integration.py
new file mode 100644
index 00000000..ce0da225
--- /dev/null
+++ b/src/hi/services/hass/tests/test_integration.py
@@ -0,0 +1,132 @@
+"""Gateway-level tests for the Home Assistant integration."""
+import logging
+import threading
+from unittest.mock import Mock
+
+from django.test import TestCase
+
+from hi.apps.entity.models import Entity
+
+from hi.services.hass.hass_manager import HassManager
+from hi.services.hass.hass_metadata import HassMetaData
+from hi.services.hass.integration import HassGateway
+
+logging.disable(logging.CRITICAL)
+
+
+class GetEntityVideoSnapshotTests(TestCase):
+ """The snapshot URL is composed from cached ``entity_picture``
+ attrs plus the HA base URL. Covers the URL-shape branches
+ (relative vs absolute) and the no-snapshot short-circuits."""
+
+ BASE_URL = 'http://ha.local:8123/'
+
+ def setUp(self):
+ HassManager._instance = None
+ HassManager._lock = threading.Lock()
+ self.manager = HassManager()
+ self.gateway = HassGateway()
+
+ mock_client = Mock()
+ # HassClient strips the trailing slash on construction, so
+ # the property returns a non-slash-terminated string.
+ mock_client.api_base_url = self.BASE_URL.rstrip('/')
+ self.manager._hass_client = mock_client
+
+ def _camera_entity(self, integration_name='camera.front_door'):
+ return Entity.objects.create(
+ name='Front Door',
+ entity_type_str='CAMERA',
+ integration_id=HassMetaData.integration_id,
+ integration_name=integration_name,
+ has_video_snapshot=True,
+ )
+
+ def _prime_cache(self, integration_name, attrs):
+ self.manager.update_latest_attrs_cache({
+ integration_name: Mock(
+ entity_id=integration_name,
+ domain=integration_name.split('.')[0],
+ attributes=attrs,
+ ),
+ })
+
+ def test_returns_none_when_flag_is_off(self):
+ entity = self._camera_entity()
+ entity.has_video_snapshot = False
+ entity.save()
+ self.assertIsNone(self.gateway.get_entity_video_snapshot(entity))
+
+ def test_returns_none_for_non_hass_entity(self):
+ other = Entity.objects.create(
+ name='Other',
+ entity_type_str='CAMERA',
+ integration_id='zm',
+ integration_name='monitor.1',
+ has_video_snapshot=True,
+ )
+ self.assertIsNone(self.gateway.get_entity_video_snapshot(other))
+
+ def test_returns_none_when_cache_cold(self):
+ entity = self._camera_entity()
+ # No prime β€” cache is empty.
+ self.assertIsNone(self.gateway.get_entity_video_snapshot(entity))
+
+ def test_returns_none_when_entity_picture_missing(self):
+ entity = self._camera_entity()
+ self._prime_cache('camera.front_door', {'access_token': 'abc'})
+ self.assertIsNone(self.gateway.get_entity_video_snapshot(entity))
+
+ def test_composes_relative_entity_picture_against_base_url(self):
+ entity = self._camera_entity()
+ self._prime_cache('camera.front_door', {
+ 'entity_picture': '/api/camera_proxy/camera.front_door?token=abc',
+ })
+
+ result = self.gateway.get_entity_video_snapshot(entity)
+
+ self.assertIsNotNone(result)
+ self.assertEqual(
+ result.source_url,
+ 'http://ha.local:8123/api/camera_proxy/camera.front_door?token=abc',
+ )
+
+ def test_passes_through_absolute_https_entity_picture(self):
+ entity = self._camera_entity()
+ self._prime_cache('camera.front_door', {
+ 'entity_picture': 'https://nabu.casa/snapshot/abc',
+ })
+
+ result = self.gateway.get_entity_video_snapshot(entity)
+
+ self.assertIsNotNone(result)
+ self.assertEqual(result.source_url, 'https://nabu.casa/snapshot/abc')
+
+ def test_passes_through_absolute_http_entity_picture(self):
+ entity = self._camera_entity()
+ self._prime_cache('camera.front_door', {
+ 'entity_picture': 'http://external.cam/snap.jpg',
+ })
+
+ result = self.gateway.get_entity_video_snapshot(entity)
+
+ self.assertIsNotNone(result)
+ self.assertEqual(result.source_url, 'http://external.cam/snap.jpg')
+
+ def test_token_rotation_reflected_after_cache_refresh(self):
+ """The snapshot URL must always reflect the latest token the
+ monitor cached. Catches a regression where the gateway holds
+ a stale value past the next poll cycle."""
+ entity = self._camera_entity()
+ self._prime_cache('camera.front_door', {
+ 'entity_picture': '/api/camera_proxy/camera.front_door?token=v1',
+ })
+ first = self.gateway.get_entity_video_snapshot(entity)
+
+ self._prime_cache('camera.front_door', {
+ 'entity_picture': '/api/camera_proxy/camera.front_door?token=v2',
+ })
+ second = self.gateway.get_entity_video_snapshot(entity)
+
+ self.assertIn('token=v1', first.source_url)
+ self.assertIn('token=v2', second.source_url)
diff --git a/src/hi/services/zoneminder/integration.py b/src/hi/services/zoneminder/integration.py
index 770c7bc1..09c058a8 100644
--- a/src/hi/services/zoneminder/integration.py
+++ b/src/hi/services/zoneminder/integration.py
@@ -2,7 +2,7 @@ import logging
from typing import List, Optional
from hi.apps.entity.models import Entity
-from hi.apps.entity.transient_models import VideoStream
+from hi.apps.entity.transient_models import VideoSnapshot, VideoStream
from hi.apps.entity.enums import VideoStreamType, VideoStreamMode
from hi.apps.entity.constants import VideoStreamMetadataKeys
from hi.apps.sense.transient_models import SensorResponse
@@ -96,6 +96,34 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):
logger.exception(f'Error in ZoneMinder connection test: {e}')
return ConnectionTestResult.failure(f'Connection test error: {e}')
+ def get_entity_video_snapshot(self, entity: Entity) -> Optional[VideoSnapshot]:
+ """Return a fresh still frame for the ZoneMinder monitor backing
+ this entity (``nph-zms?mode=single``). Returns None when the
+ entity isn't a ZM monitor or the integration_name can't be
+ parsed."""
+ if not entity.has_video_snapshot:
+ return None
+
+ if not ( entity.integration_id == ZmMetaData.integration_id
+ and entity.integration_name
+ and entity.integration_name.startswith(
+ self.zm_manager().ZM_MONITOR_INTEGRATION_NAME_PREFIX )):
+ return None
+
+ try:
+ monitor_id = int( entity.integration_name.split('.')[1] )
+ except ( IndexError, ValueError ):
+ logger.warning(
+ f'Could not parse monitor ID from entity integration name: '
+ f'{entity.integration_name}'
+ )
+ return None
+
+ return VideoSnapshot(
+ source_url = self.zm_manager().get_video_snapshot_url( monitor_id ),
+ metadata = { 'monitor_id': monitor_id },
+ )
+
def get_entity_video_stream(self, entity: Entity) -> Optional[VideoStream]:
"""Get entity's primary video stream (typically live)"""
if not entity.has_video_stream:
diff --git a/src/hi/services/zoneminder/tests/test_zm_sync.py b/src/hi/services/zoneminder/tests/test_zm_sync.py
index 6debb38e..19385317 100644
--- a/src/hi/services/zoneminder/tests/test_zm_sync.py
+++ b/src/hi/services/zoneminder/tests/test_zm_sync.py
@@ -599,6 +599,27 @@ class TestZoneMinderSynchronizerEntityUpdate(TestCase):
self.assertEqual(result.updated_list, [])
self.assertEqual(result.info_list, [])
+ def test_update_entity_heals_missing_video_snapshot_flag(self):
+ """Existing entities imported before the video_snapshot field
+ existed should self-heal on the next sync."""
+ entity = Entity.objects.create(
+ name='Pre-existing ZM Camera',
+ entity_type_str='CAMERA',
+ has_video_stream=False,
+ has_video_snapshot=False,
+ )
+ mock_monitor = Mock()
+ mock_monitor.name.return_value = 'Driveway'
+ mock_monitor.id.return_value = 42
+
+ self.synchronizer._update_entity(
+ entity, mock_monitor, IntegrationSyncResult(title='Test'),
+ )
+
+ entity.refresh_from_db()
+ self.assertTrue(entity.has_video_stream)
+ self.assertTrue(entity.has_video_snapshot)
+
class TestZoneMinderSynchronizerEntityRemoval(TestCase):
"""Test intelligent entity deletion"""
@@ -1018,6 +1039,7 @@ class CreateMonitorEntityCreateNewContractTests(TestCase):
self.assertEqual(entity.integration_id, ZmMetaData.integration_id)
self.assertEqual(entity.integration_name, 'monitor.42')
self.assertTrue(entity.has_video_stream)
+ self.assertTrue(entity.has_video_snapshot)
def test_creates_movement_sensor_and_function_controller_for_monitor(self):
result = IntegrationSyncResult(title='Test')
@@ -1111,6 +1133,7 @@ class CreateMonitorEntityReconnectContractTests(TestCase):
self.assertEqual(existing.integration_id, ZmMetaData.integration_id)
self.assertEqual(existing.integration_name, 'monitor.101')
self.assertTrue(existing.has_video_stream)
+ self.assertTrue(existing.has_video_snapshot)
class EventDefinitionLifecycleCycleTests(TestCase):
diff --git a/src/hi/services/zoneminder/zm_manager.py b/src/hi/services/zoneminder/zm_manager.py
index 7bedcf73..d40e73ab 100644
--- a/src/hi/services/zoneminder/zm_manager.py
+++ b/src/hi/services/zoneminder/zm_manager.py
@@ -372,6 +372,19 @@ class ZoneMinderManager( SingletonManager, AggregateHealthProvider, ApiHealthSta
import time
timestamp = int(time.time())
return f'{self.zm_client.portal_url}/cgi-bin/nph-zms?mode=jpeg&scale=100&rate=5&maxfps=5&replay=single&source=event&event={event_id}&_t={timestamp}'
+
+ def get_video_snapshot_url( self, monitor_id : int ):
+ """Return a URL to a single still frame for the monitor's
+ current view (ZoneMinder's ``mode=single`` variant). Cache-bust
+ with a timestamp so each call returns a fresh image rather than
+ a cached prior response."""
+ import time
+ timestamp = int(time.time())
+ return (
+ f'{self.zm_client.portal_url}/cgi-bin/nph-zms'
+ f'?mode=single&scale=100&monitor={monitor_id}'
+ f'&_t={timestamp}'
+ )
def test_client_with_attributes(
self,
diff --git a/src/hi/services/zoneminder/zm_sync.py b/src/hi/services/zoneminder/zm_sync.py
index d53de30a..5218892f 100644
--- a/src/hi/services/zoneminder/zm_sync.py
+++ b/src/hi/services/zoneminder/zm_sync.py
@@ -332,6 +332,7 @@ class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):
entity.integration_key = entity_integration_key
entity.can_user_delete = ZmMetaData.allow_entity_deletion
entity.has_video_stream = True
+ entity.has_video_snapshot = True
entity.save()
movement_sensor = HiModelHelper.create_movement_sensor(
@@ -375,11 +376,20 @@ class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):
(``can_add_custom_attributes`` defaults to True), so it's
treated as user-owned after creation: this method does not
touch it on update. ZM monitor renames upstream are not
- propagated; the operator's chosen name stays. The method is
- currently a no-op stub kept for the symmetry of the sync
- flow's create/update/remove dispatch β€” future
- integration-owned per-entity fields would land here.
+ propagated; the operator's chosen name stays.
"""
+ # Re-apply integration-owned capability flags. Every ZM
+ # monitor is a camera, so both flags are unconditionally True;
+ # the conditional save avoids spurious writes.
+ update_fields = []
+ if not entity.has_video_stream:
+ entity.has_video_stream = True
+ update_fields.append( 'has_video_stream' )
+ if not entity.has_video_snapshot:
+ entity.has_video_snapshot = True
+ update_fields.append( 'has_video_snapshot' )
+ if update_fields:
+ entity.save( update_fields = update_fields )
return
def _remove_entity( self,
diff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.py
index 8bd77188..42b396f6 100644
--- a/src/hi/simulator/management/commands/seed_sim_profiles.py
+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py
@@ -74,6 +74,8 @@ from django.db import transaction
from hi.simulator.enums import SimEntityType
from hi.simulator.models import DbSimEntity, SimProfile
from hi.simulator.services.hass.sim_models import (
+ HassCameraNoMotionSimEntityFields,
+ HassCameraSimEntityFields,
HassCarbonMonoxideDetectorFields,
HassColorSmartBulbFields,
HassFanFields,
@@ -362,6 +364,8 @@ class Command(BaseCommand):
def _build_hass_zoo(self, profile: SimProfile) -> int:
# One of every HASS sim entity definition type.
+ self._add_hass_camera( profile, 'Zoo Camera' , 'zoo_camera' )
+ self._add_hass_camera_no_motion( profile, 'Zoo Camera No Motion', 'zoo_camera_no_motion' )
self._add_hass_light_switch( profile, 'Zoo Insteon Light Switch' , '01.BB.01' )
self._add_hass_dimmer( profile, 'Zoo Insteon Dimmer' , '01.BB.02' )
self._add_hass_dual_band( profile, 'Zoo Insteon Dual Band Switch' , '01.BB.03' )
@@ -664,6 +668,30 @@ class Command(BaseCommand):
fields_kwargs = {'name': name},
)
+ def _add_hass_camera(self, profile, name, entity_id_suffix):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassCameraSimEntityFields,
+ sim_entity_type = SimEntityType.CAMERA,
+ fields_kwargs = {
+ 'name': name,
+ 'entity_id_suffix': entity_id_suffix,
+ },
+ )
+
+ def _add_hass_camera_no_motion(self, profile, name, entity_id_suffix):
+ self._create_db_entity(
+ profile = profile,
+ simulator_id = 'hass',
+ fields_class = HassCameraNoMotionSimEntityFields,
+ sim_entity_type = SimEntityType.CAMERA,
+ fields_kwargs = {
+ 'name': name,
+ 'entity_id_suffix': entity_id_suffix,
+ },
+ )
+
def _add_hass_basic_outlet(self, profile, name):
self._create_db_entity(
profile = profile,
diff --git a/src/hi/simulator/media.py b/src/hi/simulator/media.py
new file mode 100644
index 00000000..0ee5404b
--- /dev/null
+++ b/src/hi/simulator/media.py
@@ -0,0 +1,49 @@
+"""Shared synthetic-media primitives for the simulator.
+
+Renders a placeholder JPEG with operator-identifying text overlaid
+so the image viewed inside HI is obviously synthetic.
+"""
+import io
+from datetime import datetime
+from typing import List, Optional
+
+from PIL import Image, ImageDraw
+
+import hi.apps.common.datetimeproxy as datetimeproxy
+
+
+# Modest default size: recognizable text overlay, low render cost.
+FRAME_WIDTH = 320
+FRAME_HEIGHT = 240
+
+
+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/services/hass/api/urls.py b/src/hi/simulator/services/hass/api/urls.py
index 061df53e..940da63d 100644
--- a/src/hi/simulator/services/hass/api/urls.py
+++ b/src/hi/simulator/services/hass/api/urls.py
@@ -20,4 +20,8 @@ urlpatterns = [
re_path( r'^services/(?P<domain>[\w_]+)/(?P<service>[\w_]+)$',
views.ServiceCallView.as_view(),
name = 'hass_api_service_call' ),
+
+ re_path( r'^camera_proxy/(?P<entity_id>[\w\._\-]+)$',
+ views.CameraSnapshotView.as_view(),
+ name = 'hass_api_camera_snapshot' ),
]
diff --git a/src/hi/simulator/services/hass/api/views.py b/src/hi/simulator/services/hass/api/views.py
index 997bd5df..0ab258f9 100644
--- a/src/hi/simulator/services/hass/api/views.py
+++ b/src/hi/simulator/services/hass/api/views.py
@@ -2,11 +2,12 @@ import json
import logging
from django.core.exceptions import BadRequest
-from django.http import JsonResponse
+from django.http import HttpResponse, 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.media import render_jpeg_frame
from hi.simulator.services.hass.api_composers import HassApiComposer
from hi.simulator.services.hass.service_dispatchers import HassServiceDispatcher
from hi.simulator.services.hass.simulator import HassSimulator
@@ -156,3 +157,24 @@ class ServiceCallView( View ):
except Exception:
logger.exception( 'Problem processing HAss service call' )
return JsonResponse( list(), safe = False )
+
+
+class CameraSnapshotView( View ):
+ """Mirrors HA's ``/api/camera_proxy/<entity_id>`` endpoint, which
+ returns a single JPEG of the camera's current view. The simulator
+ accepts any ``token`` query param (real HA validates the rotating
+ ``access_token``); the goal here is shape parity with HA's URL
+ contract, not auth enforcement.
+
+ Returns a Pillow-rendered placeholder JPEG with the entity_id
+ overlaid so artifacts viewed inside HI are obviously coming from
+ the simulator and from a specific camera."""
+
+ def get(self, request, entity_id, *args, **kwargs):
+ jpeg_bytes = render_jpeg_frame(
+ text_lines = [
+ 'HA Camera',
+ entity_id,
+ ],
+ )
+ return HttpResponse( jpeg_bytes, content_type = 'image/jpeg' )
diff --git a/src/hi/simulator/services/hass/api_composers.py b/src/hi/simulator/services/hass/api_composers.py
index 244fe8ad..c01800ad 100644
--- a/src/hi/simulator/services/hass/api_composers.py
+++ b/src/hi/simulator/services/hass/api_composers.py
@@ -25,6 +25,11 @@ from typing import Dict, List
from hi.simulator.base_models import SimState
from .sim_models import (
+ HassCameraMotionDetectionState,
+ HassCameraMotionState,
+ HassCameraNoMotionSimEntityFields,
+ HassCameraSimEntityFields,
+ HassCameraState,
HassColorSmartBulbBrightnessState,
HassColorSmartBulbColorModeState,
HassColorSmartBulbFields,
@@ -217,10 +222,51 @@ class HassApiComposer:
return [ primary_dict ]
+ @staticmethod
+ def _camera( sim_states : List[ SimState ] ) -> List[ Dict ]:
+ """Compose camera + motion_detection + motion_sensor SimStates
+ into TWO HA entities, mirroring real HA's shape:
+
+ - ``camera.X`` from ``HassCameraState`` with the
+ ``motion_detection`` attribute folded in from
+ ``HassCameraMotionDetectionState``.
+ - ``binary_sensor.X_motion`` from ``HassCameraMotionState``
+ as its own HA entity.
+
+ The motion_detection state's placeholder ``_internal.*``
+ entity_id never reaches the response."""
+ camera_dict = None
+ motion_sensor_dict = None
+ motion_detection_attrs : Dict = {}
+
+ for state in sim_states:
+ if isinstance( state, HassCameraState ):
+ camera_dict = dict( state.to_api_dict() )
+ elif isinstance( state, HassCameraMotionState ):
+ motion_sensor_dict = state.to_api_dict()
+ elif isinstance( state, HassCameraMotionDetectionState ):
+ motion_detection_attrs.update( state.to_api_dict().get( 'attributes', {} ) )
+ continue
+
+ if camera_dict is None:
+ return HassApiComposer._default( sim_states )
+
+ merged_attrs = dict( camera_dict.get( 'attributes', {} ) )
+ merged_attrs.update( motion_detection_attrs )
+ camera_dict[ 'attributes' ] = merged_attrs
+
+ results = [ camera_dict ]
+ if motion_sensor_dict is not None:
+ results.append( motion_sensor_dict )
+ return results
+
+
# Registry built after the class is defined so the classmethod
# objects exist as references. Keyed off SimEntityFields class so
# the dispatch is per-device-type.
HassApiComposer._REGISTRY = {
+ HassCameraSimEntityFields: HassApiComposer._camera,
+ HassCameraNoMotionSimEntityFields: HassApiComposer._camera,
HassColorSmartBulbFields: HassApiComposer._color_smart_bulb,
HassMultiFeatureFanFields: HassApiComposer._multi_feature_fan,
HassThermostatFields: HassApiComposer._thermostat,
diff --git a/src/hi/simulator/services/hass/service_dispatchers.py b/src/hi/simulator/services/hass/service_dispatchers.py
index a5cc0450..f7bc125e 100644
--- a/src/hi/simulator/services/hass/service_dispatchers.py
+++ b/src/hi/simulator/services/hass/service_dispatchers.py
@@ -30,6 +30,8 @@ from hi.simulator.enums import SimStateType
from .unit_translation import UnitTranslationHelper
from .sim_models import (
+ HassCameraNoMotionSimEntityFields,
+ HassCameraSimEntityFields,
HassColorSmartBulbFields,
HassFanFields,
HassGarageCoverFields,
@@ -391,9 +393,31 @@ class HassServiceDispatcher:
return None
+ @staticmethod
+ def _camera( sim_entity,
+ domain : str,
+ service : str,
+ payload : Dict[ str, Any ],
+ ) -> List[ Tuple[ str, str ] ]:
+ """Camera motion-detection toggling. The no-motion variant
+ has no ``motion_detection`` SimState and silently no-ops, as
+ real HA does for cameras without that capability."""
+ if domain != 'camera':
+ return []
+ if isinstance( sim_entity.sim_entity_fields, HassCameraNoMotionSimEntityFields ):
+ return []
+ if service == 'enable_motion_detection':
+ return [ ( 'motion_detection', 'on' ) ]
+ if service == 'disable_motion_detection':
+ return [ ( 'motion_detection', 'off' ) ]
+ return []
+
+
# Registry built after the class is defined so the staticmethod
# objects exist as references. Keyed off SimEntityFields class.
HassServiceDispatcher._REGISTRY = {
+ HassCameraSimEntityFields: HassServiceDispatcher._camera,
+ HassCameraNoMotionSimEntityFields: HassServiceDispatcher._camera,
HassColorSmartBulbFields: HassServiceDispatcher._color_smart_bulb,
HassFanFields: HassServiceDispatcher._fan,
HassGarageCoverFields: HassServiceDispatcher._discrete_cover,
diff --git a/src/hi/simulator/services/hass/sim_models.py b/src/hi/simulator/services/hass/sim_models.py
index 487f784f..3df0db07 100644
--- a/src/hi/simulator/services/hass/sim_models.py
+++ b/src/hi/simulator/services/hass/sim_models.py
@@ -1,5 +1,6 @@
import base64
from dataclasses import dataclass, field
+import hashlib
import os
import time
from typing import ClassVar, Dict, List, Tuple
@@ -2810,7 +2811,179 @@ class HassThermostatHvacActionState( HassState ):
return { 'hvac_action': self.value }
+# ===== Generic Camera =====
+#
+# Universal-feature HA camera: snapshot via
+# ``entity_picture`` / ``access_token``, discrete camera mode, and
+# (in the full variant) a paired motion ``binary_sensor.X_motion``.
+# See ``api_composers._camera`` for the multi-state-to-HA-entity
+# collapse.
+
+
+def _camera_access_token( entity_id_suffix : str ) -> str:
+ """Per-entity stable access token in HA's 32-hex-char shape.
+ Stable across simulator restarts so HI integrations holding a
+ previously-issued URL still resolve; real HA rotates the token
+ on state change, which the simulator deliberately doesn't model
+ until the HA integration's token-rotation handling needs an
+ explicit test surface."""
+ seed = f'hi-sim-camera::{entity_id_suffix}'
+ return hashlib.sha256( seed.encode() ).hexdigest()[ :32 ]
+
+
+@dataclass( frozen = True )
+class HassCameraSimEntityFields( SimEntityFields ):
+ """Operator-configurable fields for a Generic Camera. The
+ ``entity_id_suffix`` becomes the entity's HA identifier stem
+ (e.g., ``front_door`` β†’ ``camera.front_door`` +
+ ``binary_sensor.front_door_motion``)."""
+
+ entity_id_suffix : str = 'sim_camera_1'
+ brand : str = 'Generic'
+ model_name : str = 'SimCam'
+
+
+@dataclass( frozen = True )
+class HassCameraNoMotionSimEntityFields( HassCameraSimEntityFields ):
+ """Variant of the generic camera with no paired motion
+ ``binary_sensor``. Some HA camera integrations don't expose one
+ (basic MJPEG cameras, certain doorbells); modeling both shapes
+ lets HI's integration logic be exercised against either."""
+ pass
+
+
+@dataclass
+class HassCameraState( HassState ):
+ """Camera-mode primary state. Renders as ``camera.X`` with HA's
+ canonical camera attributes (``access_token``, ``entity_picture``,
+ ``frontend_stream_type``, brand/model). The ``motion_detection``
+ attribute is contributed by the sibling
+ ``HassCameraMotionDetectionState`` via the composer; not added
+ here."""
+
+ sim_entity_fields : HassCameraSimEntityFields
+ sim_state_type : SimStateType = SimStateType.DISCRETE
+ sim_state_id : str = 'camera_mode'
+ value : str = 'idle'
+
+ CAMERA_MODE_CHOICES : ClassVar[ List[ Tuple[ str, str ] ] ] = [
+ ( 'idle' , 'Idle' ),
+ ( 'streaming' , 'Streaming' ),
+ ( 'recording' , 'Recording' ),
+ ]
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Mode'
+
+ @property
+ def entity_id(self):
+ return f'camera.{self.sim_entity_fields.entity_id_suffix}'
+
+ @property
+ def state(self):
+ return self.value
+
+ @property
+ def choices(self) -> List[ Tuple[ str, str ] ]:
+ return self.CAMERA_MODE_CHOICES
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ token = _camera_access_token( self.sim_entity_fields.entity_id_suffix )
+ return {
+ 'access_token' : token,
+ 'entity_picture' : f'/api/camera_proxy/{self.entity_id}?token={token}',
+ 'frontend_stream_type' : 'mjpeg',
+ 'brand' : self.sim_entity_fields.brand,
+ 'model_name' : self.sim_entity_fields.model_name,
+ 'friendly_name' : self.entity_name,
+ }
+
+
+@dataclass
+class HassCameraMotionDetectionState( HassState ):
+ """Toggleable motion-detection flag on the camera. Not emitted as
+ its own HA entity β€” the composer folds its value into the parent
+ camera entity's ``motion_detection`` attribute. ``entity_id`` is a
+ placeholder used only for the framework's per-state book-keeping;
+ it never reaches the ``/api/states`` response."""
+
+ sim_entity_fields : HassCameraSimEntityFields
+ sim_state_type : SimStateType = SimStateType.ON_OFF
+ sim_state_id : str = 'motion_detection'
+ value : str = 'on'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Motion Detection'
+
+ @property
+ def entity_id(self):
+ # Composer-only placeholder; never emitted.
+ return f'_internal.camera_motion_detection.{self.sim_entity_fields.entity_id_suffix}'
+
+ @property
+ def state(self):
+ return 'on' if str_to_bool( self.value ) else 'off'
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ # Camera composer reads this and merges it into the camera's
+ # attributes as ``motion_detection``.
+ return { 'motion_detection': str_to_bool( self.value ) }
+
+
+@dataclass
+class HassCameraMotionState( HassState ):
+ """Paired motion ``binary_sensor.X_motion``. Renders as its own HA
+ entity (the composer does NOT fold it into the camera), mirroring
+ HA's reality where the camera and motion sensor are paired but
+ separate entities."""
+
+ sim_entity_fields : HassCameraSimEntityFields
+ sim_state_type : SimStateType = SimStateType.MOVEMENT
+ sim_state_id : str = 'motion'
+
+ @property
+ def name(self):
+ return f'{self.entity_name} Motion'
+
+ @property
+ def entity_id(self):
+ return f'binary_sensor.{self.sim_entity_fields.entity_id_suffix}_motion'
+
+ @property
+ def state(self):
+ return 'on' if str_to_bool( self.value ) else 'off'
+
+ @property
+ def attributes(self) -> Dict[ str, str ]:
+ return {
+ 'device_class' : 'motion',
+ 'friendly_name': self.name,
+ }
+
+
HASS_SIM_ENTITY_DEFINITION_LIST = [
+ SimEntityDefinition(
+ class_label = 'Generic Camera',
+ sim_entity_type = SimEntityType.CAMERA,
+ sim_entity_fields_class = HassCameraSimEntityFields,
+ sim_state_class_list = [
+ HassCameraState,
+ HassCameraMotionDetectionState,
+ HassCameraMotionState,
+ ],
+ ),
+ SimEntityDefinition(
+ class_label = 'Generic Camera (no motion sensor)',
+ sim_entity_type = SimEntityType.CAMERA,
+ sim_entity_fields_class = HassCameraNoMotionSimEntityFields,
+ sim_state_class_list = [
+ HassCameraState,
+ ],
+ ),
SimEntityDefinition(
class_label = 'Insteon Switch',
sim_entity_type = SimEntityType.LIGHT,
diff --git a/src/hi/simulator/services/zoneminder/zm_media.py b/src/hi/simulator/services/zoneminder/zm_media.py
index e1438cda..8a0bb55f 100644
--- a/src/hi/simulator/services/zoneminder/zm_media.py
+++ b/src/hi/simulator/services/zoneminder/zm_media.py
@@ -14,27 +14,25 @@ ZoneMinder serves three byte-shapes the HI integration consumes:
``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.
+``render_jpeg_frame`` (lifted to ``hi.simulator.media`` so both
+ZM and HA snapshots share it) 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
+from hi.simulator.media import render_jpeg_frame
# Single boundary string is reused across all MJPEG responses; the
@@ -52,17 +50,13 @@ _DEFAULT_FRAME_COUNT = 8
# 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 )
+ return render_jpeg_frame( text_lines = text_lines )
def mjpeg_content_type() -> str:
@@ -103,7 +97,7 @@ def iter_bounded_mjpeg_parts(
frame_text = list( text_lines ) + [
f'frame {index + 1}/{frame_count}',
]
- jpeg_bytes = _render_jpeg_frame(
+ jpeg_bytes = render_jpeg_frame(
text_lines = frame_text,
timestamp_override = _interpolated_frame_time(
playback_start = playback_start,
@@ -164,35 +158,3 @@ def render_bounded_mjpeg_response(
)
)
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()