Home Information - Your home, your data, organized.
Python
Frigate NVR integration (v1) (#347)
Tony C0eee15864cdd
diff --git a/docs/Integrations.md b/docs/Integrations.mdindex 1ca6a16f..057600bd 100644--- a/docs/Integrations.md+++ b/docs/Integrations.md@@ -33,6 +33,9 @@ enter it.- **[ZoneMinder](integrations/zoneminder.md)** — open-source videosurveillance. Imports ZM monitors as cameras with motion sensors andfunction controllers; provides live stream playback in HI.+- **[Frigate](integrations/frigate.md)** — open-source NVR with+ object detection. Imports Frigate cameras with an object-presence+ sensor that drives event playback in HI.- **[HomeBox](integrations/homebox.md)** — home inventory tracking.Imports HomeBox items as read-only HI items with custom fields andattached files (manuals, receipts, photos).diff --git a/docs/dev/integrations/frigate.md b/docs/dev/integrations/frigate.mdnew file mode 100644index 00000000..ccf0bbe6--- /dev/null+++ b/docs/dev/integrations/frigate.md@@ -0,0 +1,142 @@+# Frigate++## Overview++The Frigate integration follows the standard pattern in+`integration-guidelines.md`: a `FrigateGateway` exposes the+framework surface; a singleton `FrigateManager` owns shared client+state and the active `FrigateClient` instance; the synchronizer+imports each Frigate camera as a HI camera entity with a single+object-presence sensor; `FrigateMonitor` polls in the background for+event changes.++Frigate communicates over plain HTTP only — there is no MQTT path+(HI doesn't have MQTT plumbing); the API surface is small enough+that HTTP polling delivers a usable experience without sub-second+latency.++User-facing setup lives in+[`docs/integrations/frigate.md`](../../integrations/frigate.md).++## Key modules++- `src/hi/services/frigate/integration.py` — `FrigateGateway`.+ Framework entry point.+- `src/hi/services/frigate/frigate_manager.py` — `FrigateManager`.+ Singleton holding the active `FrigateClient`, integration+ attributes, and change-listener fan-out.+- `src/hi/services/frigate/frigate_client.py` — `FrigateClient`.+ Encapsulated HTTP client wrapping the Frigate REST API.+- `src/hi/services/frigate/frigate_sync.py` —+ `FrigateSynchronizer`. Drives Import / Refresh; per-camera entity+ creation in `_create_camera_entity`.+- `src/hi/services/frigate/frigate_converter.py` —+ `FrigateConverter`. Wire-format ↔ HI model translation. Owns the+ canonical OBJECT_PRESENCE mapping (Frigate's raw object class →+ one of `person` / `car` / `animal` / `package` / `other` / `none`).+- `src/hi/services/frigate/monitors.py` — `FrigateMonitor`.+ Periodic poll for camera events; emits `SensorResponse` updates+ for the object-presence sensor.+- `src/hi/services/frigate/frigate_controller.py` —+ `FrigateController`. v1 stub: returns "no control mapping" for+ every input. Frigate's only HTTP-reachable operator-toggle+ (`PUT /api/config/set` on `cameras.<name>.detect.enabled`) is a+ config edit rather than transient state, so no control surface is+ exposed in v1.++## API patterns++Frigate's REST API is the only command/query protocol; live snapshots+are JPEG bytes from `/api/<camera>/latest.jpg`. The integration was+validated only against installs with Frigate's authentication+disabled. An optional verbatim `Authorization` header field is+plumbed through but untested. No login flow, token refresh, or JWT+handling exists.++Per-request timeouts and the polling cadence are defined in+`constants.py` (`FrigateTimeouts`).++## Event polling model++The polling pipeline is the load-bearing complexity of this+integration. Frigate's `/api/events?after=T` filters strictly on+`start_time > T`, which means **once the polling cursor advances+past an event's `start_time`, that event is invisible to cursor+scans forever — even after it closes**. A ZM-style cursor-hold+approach (hold the cursor back at the open event's `start_time`)+is incompatible: with strict `>` semantics, the held cursor+excludes the very event being held for.++The monitor instead runs three phases per cycle:++1. **Cursor scan** (`?after=cursor`): for each event whose+ `start_time` is past the cursor, emit a START transition. If the+ event was already closed when first seen (lifetime shorter than+ the poll interval), also emit an END. Otherwise add the event to+ `_tracked_events`, keyed by id. Advance cursor to the latest+ `start_time` observed.+2. **Per-id refresh** (`GET /api/events/<id>`): for each id in+ `_tracked_events`, fetch its canonical state.+ - Closed → emit END, drop from tracking.+ - 404 (Frigate cleared the event) → force-close, drop.+ - Aged past `MAX_OPEN_EVENT_AGE_SECS` → force-close, drop.+ - Still open → refresh snapshot, keep tracking.+3. **Heartbeat**: emit OBJECT_NONE for cameras with no activity+ this cycle and no event currently in `_tracked_events`. Without+ this, a quiet camera's state goes stale.++The cursor never moves backward; the tracked-event set is the only+state that can grow during a cycle. API budget per cycle is `1 + N`+calls where `N` is the count of currently-open events (typically 0+or 1 in normal home use).++`FrigateMonitor._initialize` seeds the cursor at `datetimeproxy.now()`+on startup. Events open at the moment HI starts are not seeded —+the v1 posture is "HI's detection window begins when HI starts."++## Implementation notes++- **Object detection mapping.** Frigate's raw object class set is+ model-dependent (default YOLO has ~80 classes; custom models can+ have arbitrary classes). HI maps these onto a canonical 6-value+ `OBJECT_PRESENCE` range — see `FrigateConverter`. Classes that+ don't map to a named bucket land in `other`. The integration is+ the only place this mapping lives; do not duplicate it elsewhere.+- **Single sensor per camera.** Frigate couples motion to object+ detection — there is no motion-without-class signal on the events+ API — so OBJECT_PRESENCE subsumes the "is motion happening"+ signal and a separate MOVEMENT sensor would always mirror it.+- **MQTT is intentionally not supported.** HI doesn't have an MQTT+ client and Frigate's HTTP API is sufficient for the use cases+ HI's spatial-display model requires.+- **Zones and sub-labels travel as event metadata.** Frigate emits+ zone-enter / zone-leave events and rich sub-label data+ (face recognition, LPR); HI surfaces both as `detail_attrs` on the+ event without promoting them to typed states. Revisit if/when a+ use case needs rule-based branching on zones.+- **Force-close timeout.** `MAX_OPEN_EVENT_AGE_SECS` (1 hour) caps+ how long an event may stay in `_tracked_events` before HI synthesizes+ an END row. Intended for orphaned events (Frigate restart,+ dropped detection). No equivalent to ZM's auto-close-on-no-update+ behavior — Frigate is consulted by id on every cycle, so a stuck+ event surfaces directly rather than via timeout heuristics.++## Testing approach++Tests live in `src/hi/services/frigate/tests/`. The monitor's+phase-by-phase invariants and the open→closed transition that+motivated the rewrite are covered in `test_frigate_monitor.py`.++Manual end-to-end testing uses the simulator; Frigate simulator+support lives at `src/hi/simulator/services/frigate/`. The+simulator's `get_events_after` mirrors Frigate's strict `>`+semantics so monitor behavior validated against the simulator+matches real Frigate. For the operator workflow and profile+descriptions, see+[`docs/dev/testing/test-simulator.md`](../testing/test-simulator.md).++## References++- [Frigate HTTP API documentation](https://docs.frigate.video/integrations/api/frigate-http-api/)+- User-facing setup: [`docs/integrations/frigate.md`](../../integrations/frigate.md)+- Tracking issue: <https://github.com/cassandra/home-information/issues/233>diff --git a/docs/integrations/frigate.md b/docs/integrations/frigate.mdnew file mode 100644index 00000000..20bf4151--- /dev/null+++ b/docs/integrations/frigate.md@@ -0,0 +1,141 @@+<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">++# Frigate++## Overview++[Frigate](https://frigate.video/) is an open-source NVR with built-in+object detection. The Frigate integration imports each Frigate camera+into **Home Information (HI)** as a camera item with an+object-presence sensor. **HI** consumes Frigate's HTTP API only (no+MQTT). It best serves users who want their security-camera events to+participate in HI's spatial display and rule-based alarms alongside+other integrations.++Frigate couples motion to object detection — there is no+motion-without-class signal on the events API — so each camera's+state is a single canonical object class (`person` / `car` /+`animal` / `package` / `other` / `none`) rather than a separate+motion bit and label.++## Prerequisites++- Frigate version ≥ 0.14 (tested against 0.17). Earlier versions+ may work but are not validated.+- The Frigate host must be reachable from the **HI** server and, for+ video playback, from the user's browser.+- A camera that produces a **browser-playable codec** (H.264 or+ H.265) on the stream Frigate uses for recording. Older cameras+ that only output MPEG-4 produce clips browsers cannot decode. See+ [Event clip will not play](#event-clip-will-not-play) below.++## Obtaining credentials++The integration was validated against Frigate with authentication+disabled. No credentials are required in that mode. For installs+that gate Frigate behind authentication, see+[Authentication caveat](#authentication-caveat) at the end of this+page.++## Configuration values++| Field | What to enter | Notes |+|-------|---------------|-------|+| Base URL | Frigate's API root, e.g. `http://frigate.local:5000` | No trailing slash. |+| Authorization Header | Optional verbatim `Authorization` header value. | See [Authentication caveat](#authentication-caveat). |++## Setup walkthrough++1. Open **HI**'s integration picker (see+ [Enabling an integration](../Integrations.md#enabling-an-integration))+ and choose **Frigate**.+2. Fill in the fields above and save.+3. **HI** walks you through a series of modals to confirm the+ **Import** action, pull each Frigate camera as an **HI** camera+ item, and place the imported cameras into a location view or+ collection.++To pick up upstream changes later (new cameras, renames, removals),+click **Refresh** on the integration's manage page.++## Troubleshooting++### Camera streams or event clips will not play (CSP)++Browsers refuse to load video frames from a different origin unless+the server's Content Security Policy (CSP) explicitly allows it. If+your Frigate host is at a different origin than **HI**, add the+Frigate origin to **HI**'s allowed CSP URLs:++```shell+export HI_EXTRA_CSP_URLS="${SCHEME}://${HOST}:${PORT}"+```++Set this in the environment of the running **HI** process (e.g.,+your service unit file or shell profile) and restart **HI**.++### Event clip will not play++Symptom: the event-detail panel shows "*No video with supported+format and MIME type found*" or a similar decode error, even though+the camera and recording are working in Frigate's own UI.++Frigate records and serves event clips in whatever codec the camera+streams. If the camera outputs a codec the browser cannot decode —+most commonly MPEG-4 (the older DivX/Xvid family, not the H.264+that newer cameras default to) — the resulting clip will fail to+play.++Fixes:++- In the camera's admin UI, change the recording stream's codec to+ H.264 if it is not already.+- If the camera cannot produce H.264, configure Frigate to+ transcode the recording — see Frigate's+ [ffmpeg presets documentation](https://docs.frigate.video/configuration/ffmpeg_presets/).++### Connection refused / cannot reach Frigate++The **Base URL** is wrong, or Frigate is not reachable from the **HI**+host. Verify by opening the URL in a browser from the **HI** host+and confirming Frigate's web UI loads.++### Refresh imports zero cameras++Frigate's `/api/config` returned an empty `cameras` map. Confirm+your `config.yml` defines at least one camera and that Frigate is+serving that config (the web UI lists the cameras Frigate knows+about).++## Known limitations++- No MQTT support. Frigate's MQTT topics are not consumed; all+ detection events are pulled via the HTTP API.+- The per-camera state is the canonical six-value `OBJECT_PRESENCE`+ set. Raw Frigate labels (`dog`, `truck`, …) are bucketed; the+ original label is preserved on each event's detail record but is+ not directly addressable as a sensor state.+- No zone-as-state mapping. Zone names travel as event metadata but+ do not project into per-zone sensors.+- No PTZ control.+- No continuous-recording playback. Only event clips are played.+- **HI** does not run any image analysis itself — all detection+ originates from Frigate. Configure detection sensitivity, zones,+ and recording in Frigate's own config.++## Authentication caveat++The integration was validated only against Frigate installs with+authentication disabled. It exposes an optional+**Authorization Header** field that, when set, is sent verbatim on+every request — intended for installs that either use Frigate's+internal auth with a static token, or place Frigate behind a+reverse proxy that enforces auth. **This path has not been tested.**+No other authentication flow is supported: no login, no token+refresh, no JWT handling.++## References++- [Frigate documentation](https://docs.frigate.video/)+- [Frigate HTTP API reference](https://docs.frigate.video/integrations/api/frigate-http-api/)+- [Frigate ffmpeg presets](https://docs.frigate.video/configuration/ffmpeg_presets/)diff --git a/src/hi/apps/alert/alert.py b/src/hi/apps/alert/alert.pyindex b0952edd..462814f7 100644--- a/src/hi/apps/alert/alert.py+++ b/src/hi/apps/alert/alert.py@@ -141,23 +141,18 @@ class Alert:def get_first_visual_content(self):"""Find the first image/video content from any alarm in the alert.- Returns dict with image info and sensor response or None if no visual content found.+ Returns dict with sensor response and alarm context, or None+ if no visual content found. The snapshot / clip URLs are no+ longer carried on the dict — templates resolve them via the+ gateway tags using ``sensor_response`` so they always reflect+ the integration's current configuration."""for alarm in self.alarm_list:for sensor_response in alarm.sensor_response_list:- # Check for video stream capability first (preferred over static source_image_url)- if sensor_response.has_video_stream:+ has_clip = sensor_response.has_event_video_clip+ has_snapshot = sensor_response.has_event_video_snapshot+ if has_clip or has_snapshot:return {- 'source_image_url': sensor_response.source_image_url,- 'alarm': alarm,- 'source_details': sensor_response, # Keep for backward compatibility- 'sensor_response': sensor_response,- 'is_from_latest': alarm == self.alarm_list[0] if self.alarm_list else False,- }- # Fallback to static source_image_url if no video stream- elif sensor_response.source_image_url:- return {- 'source_image_url': sensor_response.source_image_url,'alarm': alarm,'source_details': sensor_response, # Keep for backward compatibility'sensor_response': sensor_response,@@ -173,7 +168,7 @@ class Alert:video_sources = []for alarm in self.alarm_list:for sensor_response in alarm.sensor_response_list:- if sensor_response.has_video_stream:+ if sensor_response.has_event_video_clip:video_sources.append({'sensor_response': sensor_response,'alarm': alarm,diff --git a/src/hi/apps/alert/templates/alert/modals/alert_details.html b/src/hi/apps/alert/templates/alert/modals/alert_details.htmlindex de796a51..a9bf433e 100644--- a/src/hi/apps/alert/templates/alert/modals/alert_details.html+++ b/src/hi/apps/alert/templates/alert/modals/alert_details.html@@ -49,6 +49,7 @@{% if video_source_count == 1 and alert_visual_content and alert_visual_content.sensor_response %}<!-- Show single video at alert level to avoid duplication -->{% sensor_response_video_stream alert_visual_content.sensor_response as video_stream %}+{% sensor_response_event_snapshot_url alert_visual_content.sensor_response as event_snapshot_url %}{% if video_stream and video_stream.source_url %}<div class="row mb-3"><div class="col-12">@@ -59,9 +60,14 @@</h6></div><div class="card-body p-2">- <div class="hi-video-recording">- <img class="img-fluid" data-video-recording src="{{ video_stream.source_url }}" alt="{{ alert_visual_content.alarm.title }}">- {% include "console/panes/video_recording_replay_button.html" %}+ <div class="hi-video-clip">+ {% if video_stream.stream_type|stringformat:"s" == "mp4" %}+ <video class="img-fluid" data-video-clip controls autoplay muted playsinline+ src="{{ video_stream.source_url }}" aria-label="{{ alert_visual_content.alarm.title }}"></video>+ {% else %}+ <img class="img-fluid" data-video-clip src="{{ video_stream.source_url }}" alt="{{ alert_visual_content.alarm.title }}">+ {% endif %}+ {% include "console/panes/video_clip_replay_button.html" %}</div>{% if not alert_visual_content.is_from_latest %}<small class="text-muted d-block mt-1">From: {{ alert_visual_content.alarm.timestamp|localtime|date:"M j, Y H:i" }}</small>@@ -70,7 +76,7 @@</div></div></div>-{% elif alert_visual_content.source_image_url %}+{% elif event_snapshot_url %}<!-- Fallback to snapshot image when video stream is not available --><div class="row mb-3"><div class="col-12">@@ -81,7 +87,7 @@</h6></div><div class="card-body p-2">- <img class="img-fluid" src="{{ alert_visual_content.source_image_url }}" alt="{{ alert_visual_content.alarm.title }}">+ <img class="img-fluid" src="{{ event_snapshot_url }}" alt="{{ alert_visual_content.alarm.title }}">{% if not alert_visual_content.is_from_latest %}<small class="text-muted d-block mt-1">From: {{ alert_visual_content.alarm.timestamp|localtime|date:"M j, Y H:i" }}</small>{% endif %}@@ -116,9 +122,14 @@<small class="text-muted">Source {{ video_source.index }} - {{ video_source.alarm.timestamp|localtime|date:"M j H:i" }}</small></div><div class="card-body p-2">- <div class="hi-video-recording">- <img class="img-fluid" data-video-recording src="{{ video_stream.source_url }}" alt="Source {{ video_source.index }}">- {% include "console/panes/video_recording_replay_button.html" %}+ <div class="hi-video-clip">+ {% if video_stream.stream_type|stringformat:"s" == "mp4" %}+ <video class="img-fluid" data-video-clip controls muted playsinline+ src="{{ video_stream.source_url }}" aria-label="Source {{ video_source.index }}"></video>+ {% else %}+ <img class="img-fluid" data-video-clip src="{{ video_stream.source_url }}" alt="Source {{ video_source.index }}">+ {% endif %}+ {% include "console/panes/video_clip_replay_button.html" %}</div></div></div>diff --git a/src/hi/apps/alert/templates/alert/panes/alarm_sensor_response.html b/src/hi/apps/alert/templates/alert/panes/alarm_sensor_response.htmlindex 770d4009..6e502319 100644--- a/src/hi/apps/alert/templates/alert/panes/alarm_sensor_response.html+++ b/src/hi/apps/alert/templates/alert/panes/alarm_sensor_response.html@@ -3,17 +3,23 @@<div>{% if show_video_inline %}{% sensor_response_video_stream sensor_response as video_stream %}+ {% sensor_response_event_snapshot_url sensor_response as event_snapshot_url %}{% if video_stream and video_stream.source_url %}<div class="mb-2">- <div class="hi-video-recording">- <img class="img-fluid" data-video-recording src="{{ video_stream.source_url }}" alt="{{ alarm.title }}">- {% include "console/panes/video_recording_replay_button.html" %}+ <div class="hi-video-clip">+ {% if video_stream.stream_type|stringformat:"s" == "mp4" %}+ <video class="img-fluid" data-video-clip controls autoplay muted playsinline+ src="{{ video_stream.source_url }}" aria-label="{{ alarm.title }}"></video>+ {% else %}+ <img class="img-fluid" data-video-clip src="{{ video_stream.source_url }}" alt="{{ alarm.title }}">+ {% endif %}+ {% include "console/panes/video_clip_replay_button.html" %}</div></div>- {% elif sensor_response.source_image_url %}+ {% elif event_snapshot_url %}<!-- Fallback to image when video stream is not available --><div class="mb-2">- <img class="img-fluid" src="{{ sensor_response.source_image_url }}" alt="{{ alarm.title }}">+ <img class="img-fluid" src="{{ event_snapshot_url }}" alt="{{ alarm.title }}"></div>{% endif %}{% endif %}@@ -24,7 +30,7 @@<div class="col-9">{{ value }}</div></div>{% endfor %}- {% if sensor_response.has_video_stream %}+ {% if sensor_response.has_event_video_clip %}<div class="row mt-2"><div class="col-12"><small>diff --git a/src/hi/apps/alert/tests/synthetic_data.py b/src/hi/apps/alert/tests/synthetic_data.pyindex 6065ed66..483096c8 100644--- a/src/hi/apps/alert/tests/synthetic_data.py+++ b/src/hi/apps/alert/tests/synthetic_data.py@@ -34,7 +34,6 @@ class AlertSyntheticData:if not detail_attrs:detail_attrs = {'Location': 'Kitchen', 'Sensor': 'Motion-01'}- source_image_url = '/static/img/hi-icon-196x196.png' if has_image else Nonealarm = Alarm(alarm_source = alarm_source,@@ -48,8 +47,8 @@ class AlertSyntheticData:timestamp=timestamp,sensor=None,detail_attrs=detail_attrs,- source_image_url=source_image_url,- has_video_stream=False+ has_event_video_snapshot=has_image,+ has_event_video_clip=False)],security_level = security_level,@@ -80,7 +79,6 @@ class AlertSyntheticData:base_detail_attrs = {'Location': 'Living Room', 'Sensor': 'Motion-02'}# Create first alarm- source_image_url = '/static/img/hi-icon-196x196.png' if has_image else Nonedetail_attrs = dict(base_detail_attrs)detail_attrs.update({'Count': f'1 of {alarm_count}'})@@ -96,8 +94,8 @@ class AlertSyntheticData:timestamp=reference_datetime,sensor=None,detail_attrs=detail_attrs,- source_image_url=source_image_url,- has_video_stream=False+ has_event_video_snapshot=has_image,+ has_event_video_clip=False)],security_level = security_level,@@ -124,8 +122,8 @@ class AlertSyntheticData:timestamp=reference_datetime,sensor=None,detail_attrs=detail_attrs,- source_image_url=source_image_url if i == 2 else None, # Only second alarm has image- has_video_stream=False+ has_event_video_snapshot=(has_image and i == 2), # Only second alarm has image+ has_event_video_clip=False),],security_level = security_level,@@ -147,7 +145,6 @@ class AlertSyntheticData:alarm_level : AlarmLevel = AlarmLevel.INFO ) -> Alert:"""Create an event-based alert for testing."""- source_image_url = '/static/img/hi-icon-196x196.png' if has_image else Nonedetail_attrs = {'Event': event_name,'Location': location,@@ -168,8 +165,8 @@ class AlertSyntheticData:timestamp=datetimeproxy.now(),sensor=None,detail_attrs=detail_attrs,- source_image_url=source_image_url,- has_video_stream=False+ has_event_video_snapshot=has_image,+ has_event_video_clip=False)],security_level = SecurityLevel.LOW,@@ -189,7 +186,6 @@ class AlertSyntheticData:has_image : bool = False ) -> Alert:"""Create a weather-based alert for testing."""- source_image_url = '/static/img/hi-icon-196x196.png' if has_image else Nonedetail_attrs = {'Alert Type': alert_type,'Location': location,@@ -212,8 +208,8 @@ class AlertSyntheticData:timestamp=datetimeproxy.now(),sensor=None,detail_attrs=detail_attrs,- source_image_url=source_image_url,- has_video_stream=False+ has_event_video_snapshot=has_image,+ has_event_video_clip=False)],security_level = SecurityLevel.HIGH,@@ -284,8 +280,8 @@ class AlertSyntheticData:sensor_response_list = [SensorResponse(integration_key=IntegrationKey("test", "synthetic"), value="active", timestamp=alarm_timestamp, sensor=None,detail_attrs={'Notes': f'Details for {alarm_title}. Seed = {seed} '},- source_image_url='/static/img/hi-icon-196x196.png',- has_video_stream=False+ has_event_video_snapshot=True,+ has_event_video_clip=False),],security_level = security_level,@@ -307,8 +303,8 @@ class AlertSyntheticData:sensor_response_list = [SensorResponse(integration_key=IntegrationKey("test", "synthetic"), value="active", timestamp=alarm_timestamp, sensor=None,detail_attrs={'Notes': f'Details for {alarm_title}. Seed = {seed} '},- source_image_url='/static/img/hi-icon-196x196.png',- has_video_stream=False+ has_event_video_snapshot=True,+ has_event_video_clip=False),],security_level = security_level,diff --git a/src/hi/apps/alert/tests/test_alarm.py b/src/hi/apps/alert/tests/test_alarm.pyindex e530531a..3cdc9965 100644--- a/src/hi/apps/alert/tests/test_alarm.py+++ b/src/hi/apps/alert/tests/test_alarm.py@@ -117,8 +117,8 @@ class TestAlarmWithSensorResponse(BaseTestCase):timestamp=datetimeproxy.now(),sensor=None,detail_attrs=detail_attrs,- source_image_url='https://example.com/sensor.jpg',- has_video_stream=False+ has_event_video_snapshot=True,+ has_event_video_clip=False)alarm = Alarm(@@ -134,7 +134,7 @@ class TestAlarmWithSensorResponse(BaseTestCase):self.assertEqual(len(alarm.sensor_response_list), 1)self.assertEqual(alarm.sensor_response_list[0].detail_attrs, detail_attrs)- self.assertEqual(alarm.sensor_response_list[0].source_image_url, 'https://example.com/sensor.jpg')+ self.assertTrue(alarm.sensor_response_list[0].has_event_video_snapshot)returndef test_alarm_with_weather_sensor_response(self):@@ -151,8 +151,7 @@ class TestAlarmWithSensorResponse(BaseTestCase):timestamp=datetimeproxy.now(),sensor=None,detail_attrs=detail_attrs,- source_image_url=None,- has_video_stream=False+ has_event_video_clip=False)alarm = Alarm(@@ -167,6 +166,6 @@ class TestAlarmWithSensorResponse(BaseTestCase):)self.assertEqual(alarm.sensor_response_list[0].detail_attrs, detail_attrs)- self.assertIsNone(alarm.sensor_response_list[0].source_image_url)+ self.assertFalse(alarm.sensor_response_list[0].has_event_video_snapshot)self.assertIsNone(alarm.sensor_response_list[0].sensor)returndiff --git a/src/hi/apps/alert/tests/test_alert.py b/src/hi/apps/alert/tests/test_alert.pyindex 77a53c89..3562b354 100644--- a/src/hi/apps/alert/tests/test_alert.py+++ b/src/hi/apps/alert/tests/test_alert.py@@ -341,8 +341,8 @@ class TestAlert(BaseTestCase):timestamp=datetimeproxy.now(),sensor=None,detail_attrs={'Location': 'Kitchen'},- source_image_url='/static/img/test-image.png',- has_video_stream=False+ has_event_video_snapshot=True,+ has_event_video_clip=False)],security_level=SecurityLevel.LOW,@@ -354,7 +354,6 @@ class TestAlert(BaseTestCase):visual_content = alert.get_first_visual_content()self.assertIsNotNone(visual_content)- self.assertEqual(visual_content['source_image_url'], '/static/img/test-image.png')self.assertEqual(visual_content['alarm'], alarm_with_image)self.assertTrue(visual_content['is_from_latest'])return@@ -373,8 +372,7 @@ class TestAlert(BaseTestCase):timestamp=datetimeproxy.now(),sensor=None,detail_attrs={'Location': 'Front Door'},- source_image_url=None,- has_video_stream=False+ has_event_video_clip=False)],security_level=SecurityLevel.LOW,@@ -402,8 +400,8 @@ class TestAlert(BaseTestCase):timestamp=datetimeproxy.now(),sensor=None,detail_attrs={'Location': 'Kitchen'},- source_image_url='/static/img/first-image.png',- has_video_stream=False+ has_event_video_snapshot=True,+ has_event_video_clip=False)],security_level=SecurityLevel.LOW,@@ -423,8 +421,7 @@ class TestAlert(BaseTestCase):timestamp=datetimeproxy.now(),sensor=None,detail_attrs={'Location': 'Kitchen'},- source_image_url=None,- has_video_stream=False+ has_event_video_clip=False)],security_level=SecurityLevel.LOW,@@ -437,7 +434,6 @@ class TestAlert(BaseTestCase):visual_content = alert.get_first_visual_content()self.assertIsNotNone(visual_content)- self.assertEqual(visual_content['source_image_url'], '/static/img/first-image.png')self.assertEqual(visual_content['alarm'], first_alarm_with_image)self.assertFalse(visual_content['is_from_latest']) # first_alarm_with_image is not at index 0 after adding second alarmreturn@@ -456,8 +452,7 @@ class TestAlert(BaseTestCase):timestamp=datetimeproxy.now(),sensor=None,detail_attrs={'Location': 'Kitchen'},- source_image_url=None,- has_video_stream=False+ has_event_video_clip=False)],security_level=SecurityLevel.LOW,@@ -477,8 +472,8 @@ class TestAlert(BaseTestCase):timestamp=datetimeproxy.now(),sensor=None,detail_attrs={'Location': 'Kitchen'},- source_image_url='/static/img/second-image.png',- has_video_stream=False+ has_event_video_snapshot=True,+ has_event_video_clip=False)],security_level=SecurityLevel.LOW,@@ -491,7 +486,6 @@ class TestAlert(BaseTestCase):visual_content = alert.get_first_visual_content()self.assertIsNotNone(visual_content)- self.assertEqual(visual_content['source_image_url'], '/static/img/second-image.png')self.assertEqual(visual_content['alarm'], second_alarm_with_image)self.assertTrue(visual_content['is_from_latest']) # second_alarm_with_image is at index 0 after being addedreturndiff --git a/src/hi/apps/alert/tests/test_alert_manager_delegation.py b/src/hi/apps/alert/tests/test_alert_manager_delegation.pyindex 129a27da..30810583 100644--- a/src/hi/apps/alert/tests/test_alert_manager_delegation.py+++ b/src/hi/apps/alert/tests/test_alert_manager_delegation.py@@ -74,7 +74,7 @@ class TestAlertManagerDelegation(BaseTestCase):name='Motion Sensor')- # Phase 3: VIDEO_STREAM EntityState removed - video capability now indicated by has_video_stream=True+ # Phase 3: VIDEO_STREAM EntityState removed - video capability now indicated by has_event_video_clip=Trueentity.has_video_stream = Trueentity.save()@@ -85,8 +85,7 @@ class TestAlertManagerDelegation(BaseTestCase):timestamp=timezone.now(),sensor=motion_sensor, # Motion sensor that triggered the alarmdetail_attrs={'location': 'Front Door'},- source_image_url=None,- has_video_stream=False+ has_event_video_clip=False)motion_alarm = Alarm(@@ -213,8 +212,7 @@ class TestAlertManagerDelegation(BaseTestCase):timestamp=timezone.now(),sensor=motion_sensor1, # First motion sensordetail_attrs={},- source_image_url=None,- has_video_stream=False+ has_event_video_clip=False)source_details_2 = SensorResponse(@@ -223,8 +221,7 @@ class TestAlertManagerDelegation(BaseTestCase):timestamp=timezone.now(),sensor=motion_sensor2, # Second motion sensordetail_attrs={},- source_image_url=None,- has_video_stream=False+ has_event_video_clip=False)# Create alarms with different types to ensure separate alertsdiff --git a/src/hi/apps/audio/tests/test_integration.py b/src/hi/apps/audio/tests/test_integration.pyindex 77935ce2..403bc5f1 100644--- a/src/hi/apps/audio/tests/test_integration.py+++ b/src/hi/apps/audio/tests/test_integration.py@@ -24,7 +24,7 @@ class TestAudioIntegration(BaseTestCase):alarm_type='SEVERE_THUNDERSTORM',alarm_level=AlarmLevel.CRITICAL,title='Severe Thunderstorm Warning',- sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'location': 'Austin, TX'}, source_image_url=None, has_video_stream=False)],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'location': 'Austin, TX'}, has_event_video_clip=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=1800,timestamp=datetimeproxy.now(),@@ -44,7 +44,7 @@ class TestAudioIntegration(BaseTestCase):alarm_type='TORNADO',alarm_level=AlarmLevel.CRITICAL,title='Tornado Warning',- sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'location': 'Austin, TX'}, source_image_url=None, has_video_stream=False)],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'location': 'Austin, TX'}, has_event_video_clip=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=1800,timestamp=datetimeproxy.now(),@@ -64,7 +64,7 @@ class TestAudioIntegration(BaseTestCase):alarm_type='DEVICE_FAILURE',alarm_level=AlarmLevel.CRITICAL,title='Device Failure',- sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'device': 'Sensor-01'}, source_image_url=None, has_video_stream=False)],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'device': 'Sensor-01'}, has_event_video_clip=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=3600,timestamp=datetimeproxy.now(),@@ -84,7 +84,7 @@ class TestAudioIntegration(BaseTestCase):alarm_type='SEVERE_THUNDERSTORM',alarm_level=AlarmLevel.WARNING,title='Severe Thunderstorm Warning',- sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'location': 'Austin, TX'}, source_image_url=None, has_video_stream=False)],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'location': 'Austin, TX'}, has_event_video_clip=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=1800,timestamp=datetimeproxy.now(),@@ -95,7 +95,7 @@ class TestAudioIntegration(BaseTestCase):alarm_type='HIGH_TEMP',alarm_level=AlarmLevel.WARNING,title='High Temperature Alert',- sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'sensor': 'Temp-01'}, source_image_url=None, has_video_stream=False)],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'sensor': 'Temp-01'}, has_event_video_clip=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=3600,timestamp=datetimeproxy.now(),@@ -129,7 +129,7 @@ class TestAudioIntegration(BaseTestCase):alarm_type='TEST',alarm_level=alarm_level,title='Test Alarm',- sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'test': 'data'}, source_image_url=None, has_video_stream=False)],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'test': 'data'}, has_event_video_clip=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=3600,timestamp=datetimeproxy.now(),diff --git a/src/hi/apps/audio/tests/test_tornado_audio.py b/src/hi/apps/audio/tests/test_tornado_audio.pyindex 5b5f8b7a..f7012aa0 100644--- a/src/hi/apps/audio/tests/test_tornado_audio.py+++ b/src/hi/apps/audio/tests/test_tornado_audio.py@@ -29,7 +29,7 @@ class TestTornadoAudio(BaseTestCase):alarm_type=WeatherEventType.TORNADO.name, # This is how weather alerts set alarm_typealarm_level=alarm_level,title=f'Tornado {alarm_level.label} Alert',- sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'location': 'Austin, TX'}, source_image_url=None, has_video_stream=False)],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'location': 'Austin, TX'}, has_event_video_clip=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=1800,timestamp=datetimeproxy.now(),@@ -49,7 +49,7 @@ class TestTornadoAudio(BaseTestCase):alarm_type=WeatherEventType.SEVERE_THUNDERSTORM.name,alarm_level=AlarmLevel.WARNING,title='Severe Thunderstorm Warning',- sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'location': 'Austin, TX'}, source_image_url=None, has_video_stream=False)],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'location': 'Austin, TX'}, has_event_video_clip=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=1800,timestamp=datetimeproxy.now(),@@ -108,7 +108,7 @@ class TestTornadoAudio(BaseTestCase):alarm_type='DEVICE_FAILURE',alarm_level=AlarmLevel.CRITICAL,title='Device Failure',- sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'device': 'Sensor-01'}, source_image_url=None, has_video_stream=False)],+ sensor_response_list=[SensorResponse(integration_key=IntegrationKey("test", "audio_test"), value="active", timestamp=datetimeproxy.now(), sensor=None, detail_attrs={'device': 'Sensor-01'}, has_event_video_clip=False)],security_level=SecurityLevel.OFF,alarm_lifetime_secs=3600,timestamp=datetimeproxy.now(),diff --git a/src/hi/apps/console/console_manager.py b/src/hi/apps/console/console_manager.pyindex f4595ae2..a80f180a 100644--- a/src/hi/apps/console/console_manager.py+++ b/src/hi/apps/console/console_manager.py@@ -29,8 +29,9 @@ class ConsoleManager( Singleton, SettingsMixin, SensorResponseMixin, WeatherMixi# Priority order for status entity state selectionSTATUS_ENTITY_STATE_PRIORITY = [+ EntityStateType.OBJECT_PRESENCE,EntityStateType.MOVEMENT,- EntityStateType.PRESENCE,+ EntityStateType.PRESENCE,EntityStateType.OPEN_CLOSE,EntityStateType.ON_OFF,EntityStateType.HIGH_LOW,diff --git a/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html b/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.htmlindex 4345b1cf..0fe098d8 100644--- a/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html+++ b/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html@@ -66,7 +66,7 @@aria-label="View event from {{ response.timestamp|localtime|date:'g:i A' }}{% if response.sensor_history_id == sensor_history_data.current_sensor_response.sensor_history_id %} - Currently viewing{% endif %}"><div><span class="time">{{ response.timestamp|localtime|date:"g:i A" }}</span>- {% if response.has_video_stream %}+ {% if response.has_event_video_clip %}{% sensor_response_video_stream response as video_stream %}{% if video_stream and video_stream.metadata.duration_secs %}<small class="text-muted d-block duration">{{ video_stream.metadata.duration_secs|format_duration }}</small>@@ -114,22 +114,31 @@<!-- Video display area --><div class="video-container mb-3" role="img" aria-label="Event video playback">{% sensor_response_video_stream sensor_history_data.current_sensor_response as video_stream %}+ {% sensor_response_event_snapshot_url sensor_history_data.current_sensor_response as event_snapshot_url %}{% if video_stream and video_stream.source_url %}- <div class="hi-video-recording">- <img class="img-fluid" data-video-recording+ {% if video_stream.stream_type|stringformat:"s" == "mp4" %}+ <div class="hi-video-clip hi-video-clip--mp4">+ <video class="img-fluid" data-video-clip controls autoplay muted playsinline+ src="{{ video_stream.source_url }}"+ aria-label="Video clip from {{ sensor_history_data.current_sensor_response.timestamp|localtime|date:'F j, Y g:i A' }}"+ data-event-id="{{ sensor_history_data.current_sensor_response.sensor_history_id }}">+ </video>+ {% include "console/panes/video_clip_replay_button.html" %}+ </div>+ {% else %}+ <div class="hi-video-clip">+ <img class="img-fluid" data-video-clipsrc="{{ video_stream.source_url }}"- alt="Video recording from {{ sensor_history_data.current_sensor_response.timestamp|localtime|date:'F j, Y g:i A' }}"+ alt="Video clip from {{ sensor_history_data.current_sensor_response.timestamp|localtime|date:'F j, Y g:i A' }}"data-event-id="{{ sensor_history_data.current_sensor_response.sensor_history_id }}">- {% include "console/panes/video_recording_replay_button.html" %}- </div>- {% elif sensor_history_data.current_sensor_response.source_image_url %}- <!-- Fallback to image when video stream is not available -->- <img class="img-fluid" src="{{ sensor_history_data.current_sensor_response.source_image_url }}" alt="Image from {{ sensor_history_data.current_sensor_response.timestamp|localtime|date:'F j, Y g:i A' }}" data-event-id="{{ sensor_history_data.current_sensor_response.sensor_history_id }}">- <div class="text-center mt-2">- <small class="text-muted">Image - video may be processing</small>+ {% include "console/panes/video_clip_replay_button.html" %}</div>+ {% endif %}+ {% elif event_snapshot_url %}+ <!-- Snapshot-only: event carries a captured frame but no playable clip -->+ <img class="img-fluid" src="{{ event_snapshot_url }}" alt="Image from {{ sensor_history_data.current_sensor_response.timestamp|localtime|date:'F j, Y g:i A' }}" data-event-id="{{ sensor_history_data.current_sensor_response.sensor_history_id }}">{% else %}- {% include "console/panes/video_unavailable_placeholder.html" with heading="Video Stream Unavailable" subtitle="Video recording may not be available for this event" %}+ {% include "console/panes/video_unavailable_placeholder.html" with heading="Video Stream Unavailable" subtitle="Video clip may not be available for this event" %}{% endif %}</div>diff --git a/src/hi/apps/console/templates/console/panes/video_recording_replay_button.html b/src/hi/apps/console/templates/console/panes/video_clip_replay_button.htmlsimilarity index 55%rename from src/hi/apps/console/templates/console/panes/video_recording_replay_button.htmlrename to src/hi/apps/console/templates/console/panes/video_clip_replay_button.htmlindex 0103c35c..9225073e 100644--- a/src/hi/apps/console/templates/console/panes/video_recording_replay_button.html+++ b/src/hi/apps/console/templates/console/panes/video_clip_replay_button.html@@ -1,11 +1,11 @@{% load icons %}-{# Replay-from-start affordance for a ``<img data-video-recording>`` #}-{# element. Expected to sit inside a ``.hi-video-recording`` wrapper #}+{# Replay-from-start affordance for a ``<img data-video-clip>`` #}+{# element. Expected to sit inside a ``.hi-video-clip`` wrapper #}{# alongside the img; the wrapper provides ``position: relative`` so #}{# this button anchors to the top-right of the video frame. The #}{# click handler (delegated in video-timeline.js) re-fetches the #}-{# img's URL to play the recording from the start. #}-<button type="button" class="hi-video-recording-replay"+{# img's URL to play the clip from the start. #}+<button type="button" class="hi-video-clip-replay"title="Replay from start" aria-label="Replay from start">{% icon "rotate" size="sm" %}</button>diff --git a/src/hi/apps/console/templatetags/video_tags.py b/src/hi/apps/console/templatetags/video_tags.pyindex e171d6c3..5d6c09fa 100644--- a/src/hi/apps/console/templatetags/video_tags.py+++ b/src/hi/apps/console/templatetags/video_tags.py@@ -21,7 +21,7 @@ def sensor_response_video_stream(sensor_response):Returns:VideoStream object or None if no video available"""- if not sensor_response or not sensor_response.has_video_stream:+ if not sensor_response or not sensor_response.has_event_video_clip:return Nonetry:@@ -52,6 +52,32 @@ def sensor_response_video_stream(sensor_response):return None+def sensor_response_event_snapshot_url(sensor_response):+ """Per-event captured-frame URL for a SensorResponse, generated+ fresh by the owning gateway each render. Returns ``None`` when+ the response carries no snapshot (``has_event_video_snapshot``+ False), the integration can't produce one, or any error+ occurs."""+ if not sensor_response or not sensor_response.has_event_video_snapshot:+ return None++ try:+ if not sensor_response.sensor:+ logger.debug("SensorResponse has no associated sensor")+ return None++ entity = sensor_response.sensor.entity_state.entity+ gateway = IntegrationManager().get_integration_gateway(entity.integration_id)+ if not gateway:+ logger.warning(f"No integration gateway found for {entity.integration_id}")+ return None+ return gateway.get_sensor_response_event_snapshot_url(sensor_response)+ except Exception as e:+ logger.error(f"Error getting event snapshot URL for sensor response: {e}")+ return None++@register.simple_tagdef entity_video_stream(entity):"""diff --git a/src/hi/apps/console/tests/test_dataclass_functionality.py b/src/hi/apps/console/tests/test_dataclass_functionality.pyindex 3f8fa486..bc8f56b0 100644--- a/src/hi/apps/console/tests/test_dataclass_functionality.py+++ b/src/hi/apps/console/tests/test_dataclass_functionality.py@@ -38,7 +38,7 @@ class TestEntitySensorHistoryData(TestCase):detail_attrs={'duration_seconds': str(60 + i * 30)},- has_video_stream=True,+ has_event_video_clip=True,sensor_history_id=1000 + i # Set as direct property)self.sensor_responses.append(response)diff --git a/src/hi/apps/console/tests/test_integration_error_handling.py b/src/hi/apps/console/tests/test_integration_error_handling.pyindex aea459f0..ca2b2fdd 100644--- a/src/hi/apps/console/tests/test_integration_error_handling.py+++ b/src/hi/apps/console/tests/test_integration_error_handling.py@@ -41,7 +41,7 @@ class TestIntegrationErrorHandling(TransactionTestCase):name='Error Test Sensor',entity_state=self.entity_state,sensor_type_str='binary',- provides_video_stream=True+ provides_event_video_clip=True)def test_helper_method_database_constraint_violations(self):@@ -51,7 +51,7 @@ class TestIntegrationErrorHandling(TransactionTestCase):sensor=self.video_sensor,value='active',response_datetime=timezone.now(),- has_video_stream=True+ has_event_video_clip=True)# Test constraint violation scenarios@@ -63,7 +63,7 @@ class TestIntegrationErrorHandling(TransactionTestCase):sensor=self.video_sensor,value='duplicate',response_datetime=timezone.now(),- has_video_stream=True+ has_event_video_clip=True)def test_helper_method_failure_recovery(self):@@ -73,7 +73,7 @@ class TestIntegrationErrorHandling(TransactionTestCase):sensor=self.video_sensor,value='valid_record',response_datetime=timezone.now(),- has_video_stream=True+ has_event_video_clip=True)# Test that view handles helper method exceptions gracefully@@ -104,7 +104,7 @@ class TestIntegrationErrorHandling(TransactionTestCase):sensor=self.video_sensor,value='connection_test',response_datetime=timezone.now(),- has_video_stream=True+ has_event_video_clip=True)# Test database query failure simulation@@ -126,7 +126,7 @@ class TestIntegrationErrorHandling(TransactionTestCase):sensor=self.video_sensor,value='concurrent_test',response_datetime=base_time,- has_video_stream=True+ has_event_video_clip=True)# Test concurrent modification by modifying record between queriesdiff --git a/src/hi/apps/console/tests/test_timeline_preservation.py b/src/hi/apps/console/tests/test_timeline_preservation.pyindex 3b9ed488..08529f57 100644--- a/src/hi/apps/console/tests/test_timeline_preservation.py+++ b/src/hi/apps/console/tests/test_timeline_preservation.py@@ -37,7 +37,7 @@ class TestTimelinePreservationLogic(TransactionTestCase):name='Timeline Test Sensor',entity_state=self.entity_state,sensor_type_str='binary',- provides_video_stream=True+ provides_event_video_clip=True)def test_timeline_preserved_when_target_record_within_window(self):@@ -168,7 +168,7 @@ class TestTimelinePreservationLogic(TransactionTestCase):sensor=self.video_sensor,value='active',response_datetime=base_time.replace(hour=hour),- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id='test',details='{"day": "today"}'@@ -181,7 +181,7 @@ class TestTimelinePreservationLogic(TransactionTestCase):sensor=self.video_sensor,value='active',response_datetime=yesterday,- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id='test',details='{"day": "yesterday"}'@@ -193,7 +193,7 @@ class TestTimelinePreservationLogic(TransactionTestCase):sensor=self.video_sensor,value='active',response_datetime=old_time,- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id='test',details='{"day": "old"}'@@ -242,7 +242,7 @@ class TestTimelinePreservationLogic(TransactionTestCase):sensor=self.video_sensor,value=f'nav_test_{i}',response_datetime=base_time - timezone.timedelta(hours=i),- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id='test',details=f'{{"nav_order": "{i}"}}'@@ -282,7 +282,7 @@ class TestTimelinePreservationLogic(TransactionTestCase):sensor=self.video_sensor,value=response.value,response_datetime=response.timestamp,- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id='test',details='{"timezone": "aware"}'diff --git a/src/hi/apps/console/tests/test_transient_models.py b/src/hi/apps/console/tests/test_transient_models.pyindex 2b8b541c..254c13df 100644--- a/src/hi/apps/console/tests/test_transient_models.py+++ b/src/hi/apps/console/tests/test_transient_models.py@@ -91,10 +91,10 @@ class TestVideoStream(BaseTestCase):def test_video_stream_creation_with_minimal_fields(self):"""Test creating a VideoStream with minimal required fields."""video_stream = VideoStream(- stream_type=VideoStreamType.URL+ stream_type=VideoStreamType.MJPEG)- self.assertEqual(video_stream.stream_type, VideoStreamType.URL)+ self.assertEqual(video_stream.stream_type, VideoStreamType.MJPEG)self.assertIsNone(video_stream.source_url)self.assertEqual(video_stream.metadata, {})@@ -108,12 +108,12 @@ class TestVideoStream(BaseTestCase):}video_stream = VideoStream(- stream_type=VideoStreamType.URL,+ stream_type=VideoStreamType.MJPEG,source_url='https://example.com/stream.m3u8',metadata=metadata)- self.assertEqual(video_stream.stream_type, VideoStreamType.URL)+ self.assertEqual(video_stream.stream_type, VideoStreamType.MJPEG)self.assertEqual(video_stream.source_url, 'https://example.com/stream.m3u8')self.assertEqual(video_stream.metadata, metadata)self.assertEqual(video_stream.metadata['width'], 1920)@@ -123,10 +123,10 @@ class TestVideoStream(BaseTestCase):"""Test VideoStream creation with different stream types."""# Test URL streamurl_stream = VideoStream(- stream_type=VideoStreamType.URL,+ stream_type=VideoStreamType.MJPEG,source_url='http://camera.local/mjpeg')- self.assertEqual(url_stream.stream_type, VideoStreamType.URL)+ self.assertEqual(url_stream.stream_type, VideoStreamType.MJPEG)# Test OTHER streamother_stream = VideoStream(@@ -138,7 +138,7 @@ class TestVideoStream(BaseTestCase):def test_video_stream_metadata_defaults_to_empty_dict(self):"""Test that VideoStream metadata defaults to empty dictionary."""video_stream = VideoStream(- stream_type=VideoStreamType.URL,+ stream_type=VideoStreamType.MJPEG,source_url='http://test.local/stream')@@ -160,7 +160,7 @@ class TestVideoStream(BaseTestCase):}video_stream = VideoStream(- stream_type=VideoStreamType.URL,+ stream_type=VideoStreamType.MJPEG,source_url='https://test.local/stream.m3u8',metadata=metadata)@@ -175,7 +175,7 @@ class TestVideoStream(BaseTestCase):def test_video_stream_is_dataclass(self):"""Test that VideoStream behaves as a proper dataclass."""video_stream = VideoStream(- stream_type=VideoStreamType.URL,+ stream_type=VideoStreamType.MJPEG,source_url='http://test.local/mjpeg',metadata={'test': 'value'})@@ -192,9 +192,9 @@ class TestVideoStream(BaseTestCase):def test_video_stream_with_none_source_url(self):"""Test VideoStream with None source_url (valid use case)."""video_stream = VideoStream(- stream_type=VideoStreamType.URL,+ stream_type=VideoStreamType.MJPEG,source_url=None)- self.assertEqual(video_stream.stream_type, VideoStreamType.URL)+ self.assertEqual(video_stream.stream_type, VideoStreamType.MJPEG)self.assertIsNone(video_stream.source_url)diff --git a/src/hi/apps/console/tests/test_transient_view_manager.py b/src/hi/apps/console/tests/test_transient_view_manager.pyindex 9ce59616..52f96d9a 100644--- a/src/hi/apps/console/tests/test_transient_view_manager.py+++ b/src/hi/apps/console/tests/test_transient_view_manager.py@@ -167,8 +167,7 @@ class TestTransientViewManager(BaseTestCase):timestamp=timezone.now(),sensor=motion_sensor, # Motion sensor that triggered the alarmdetail_attrs={'location': 'Front Door'},- source_image_url=None,- has_video_stream=False+ has_event_video_clip=False)motion_alarm = Alarm(@@ -230,8 +229,7 @@ class TestTransientViewManager(BaseTestCase):timestamp=timezone.now(),sensor=None, # TODO: fix sensor referencedetail_attrs={},- source_image_url=None,- has_video_stream=False+ has_event_video_clip=False)motion_alarm = Alarm(@@ -276,8 +274,7 @@ class TestTransientViewManager(BaseTestCase):timestamp=timezone.now(),sensor=None, # TODO: fix sensor referencedetail_attrs={},- source_image_url=None,- has_video_stream=False+ has_event_video_clip=False)status_alarm = Alarm(@@ -322,8 +319,7 @@ class TestTransientViewManager(BaseTestCase):timestamp=timezone.now(),sensor=None,detail_attrs={'location': 'Front Door'},- source_image_url=None,- has_video_stream=False+ has_event_video_clip=False)motion_alarm = Alarm(diff --git a/src/hi/apps/console/tests/test_video_stream_browsing_helper.py b/src/hi/apps/console/tests/test_video_stream_browsing_helper.pyindex f1e7d6f4..ab816f02 100644--- a/src/hi/apps/console/tests/test_video_stream_browsing_helper.py+++ b/src/hi/apps/console/tests/test_video_stream_browsing_helper.py@@ -45,7 +45,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):name='Motion Sensor',entity_state=self.entity_state,sensor_type_str='binary',- provides_video_stream=True+ provides_event_video_clip=True)# Create another entity without video capability for find_video_sensor tests@@ -80,7 +80,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):response_datetime=timezone.now(),correlation_role_str=str(CorrelationRole.END),correlation_id='test',- has_video_stream=True,+ has_event_video_clip=True,details='{"original": "data"}')@@ -100,7 +100,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):response_datetime=timezone.now(),correlation_role_str=str(CorrelationRole.END),correlation_id='test',- has_video_stream=True,+ has_event_video_clip=True,details='{"existing": "value", "duration": "120"}')@@ -125,7 +125,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):response_datetime=base_time - timezone.timedelta(hours=i),correlation_role_str=str(CorrelationRole.END),correlation_id=str(i),- has_video_stream=True,+ has_event_video_clip=True,)records.append(record)@@ -154,7 +154,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):response_datetime=base_time - timezone.timedelta(hours=i),correlation_role_str=str(CorrelationRole.END),correlation_id=str(i),- has_video_stream=True,+ has_event_video_clip=True,)records.append(record)@@ -191,7 +191,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):response_datetime=base_time - timezone.timedelta(hours=i),correlation_role_str=str(CorrelationRole.END),correlation_id=str(i),- has_video_stream=True,+ has_event_video_clip=True,)records.append(record)@@ -240,7 +240,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):timestamp=timestamp,sensor=self.video_sensor,detail_attrs={'duration_seconds': '120', 'details': f'Motion event {days_ago}_{hour_offset}'},- has_video_stream=True,+ has_event_video_clip=True,sensor_history_id=int(f'{days_ago}{hour_offset}') # Use unique ID for test)sensor_responses.append(response)@@ -282,7 +282,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):timestamp=timestamp,sensor=self.video_sensor,detail_attrs={'duration_seconds': '90', 'details': f'Motion event hour {hour}'},- has_video_stream=True,+ has_event_video_clip=True,sensor_history_id=hour)sensor_responses.append(response)@@ -308,7 +308,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):response_datetime=base_time - timezone.timedelta(hours=i),correlation_role_str=str(CorrelationRole.END),correlation_id=str(i),- has_video_stream=True,+ has_event_video_clip=True,)records.append(record)@@ -338,7 +338,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):response_datetime=base_time - timezone.timedelta(hours=i),correlation_role_str=str(CorrelationRole.END),correlation_id=str(i),- has_video_stream=True,+ has_event_video_clip=True,)records.append(record)@@ -373,7 +373,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):response_datetime=base_time - timezone.timedelta(hours=i),correlation_role_str=str(CorrelationRole.END),correlation_id=str(i),- has_video_stream=True,+ has_event_video_clip=True,)result = VideoStreamBrowsingHelper.build_sensor_history_data(self.video_sensor)@@ -404,7 +404,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):response_datetime=base_time - timezone.timedelta(hours=i),correlation_role_str=str(CorrelationRole.END),correlation_id=str(i),- has_video_stream=True,+ has_event_video_clip=True,)records.append(record)@@ -446,7 +446,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):response_datetime=base_time - timezone.timedelta(hours=i),correlation_role_str=str(CorrelationRole.END),correlation_id=str(i),- has_video_stream=True,+ has_event_video_clip=True,)records.append(record)@@ -486,7 +486,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):response_datetime=base_time - timezone.timedelta(hours=i),correlation_role_str=str(CorrelationRole.END),correlation_id=str(i),- has_video_stream=True,+ has_event_video_clip=True,)result = VideoStreamBrowsingHelper.build_sensor_history_data(@@ -526,7 +526,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):response_datetime=base_time,correlation_role_str=str(CorrelationRole.END),correlation_id='base_time',- has_video_stream=True+ has_event_video_clip=True)# Test with invalid window bounds (end before start)@@ -562,7 +562,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):timestamp=same_timestamp, # Same timestamp for allsensor=self.video_sensor,detail_attrs={'sensor_history_id': str(1000 + i)},- has_video_stream=True,+ has_event_video_clip=True,)sensor_responses.append(response)@@ -585,7 +585,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):sensor=self.video_sensor,value='extreme_past',response_datetime=datetime(1970, 1, 1, tzinfo=UTC),- has_video_stream=True+ has_event_video_clip=True)SensorHistory.objects.create(@@ -594,7 +594,7 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):response_datetime=base_time,correlation_role_str=str(CorrelationRole.END),correlation_id='base_time',- has_video_stream=True+ has_event_video_clip=True)# Should handle extreme timestamp ranges@@ -660,7 +660,7 @@ class TestVideoDispatchResult(TransactionTestCase):name='Dispatch Motion Sensor',entity_state=self.entity_state,sensor_type_str='binary',- provides_video_stream=True+ provides_event_video_clip=True)# Create entity without video capability for error testing@@ -709,7 +709,7 @@ class TestVideoDispatchResult(TransactionTestCase):response_datetime=earlier_time,correlation_role_str=str(CorrelationRole.END),correlation_id='earlier',- has_video_stream=True+ has_event_video_clip=True)SensorHistory.objects.create(@@ -718,7 +718,7 @@ class TestVideoDispatchResult(TransactionTestCase):response_datetime=later_time,correlation_role_str=str(CorrelationRole.END),correlation_id='later',- has_video_stream=True+ has_event_video_clip=True)# Test with an earlier view URL that should trigger fallback logic@@ -825,7 +825,7 @@ class TestVideoDispatchResult(TransactionTestCase):sensor=self.video_sensor,value='test_event',response_datetime=base_time - timezone.timedelta(hours=1),- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id='integration_test')@@ -876,7 +876,7 @@ class TestTimezoneHandling(TransactionTestCase):name='Timezone Test Sensor',entity_state=self.entity_state,sensor_type_str='binary',- provides_video_stream=True+ provides_event_video_clip=True)def test_group_responses_by_time_with_user_timezone(self):@@ -895,7 +895,7 @@ class TestTimezoneHandling(TransactionTestCase):response_datetime=utc_time_1,correlation_role_str=str(CorrelationRole.END),correlation_id='utc1',- has_video_stream=True+ has_event_video_clip=True)record_2 = SensorHistory.objects.create(@@ -904,7 +904,7 @@ class TestTimezoneHandling(TransactionTestCase):response_datetime=utc_time_2,correlation_role_str=str(CorrelationRole.END),correlation_id='utc2',- has_video_stream=True+ has_event_video_clip=True)# Create sensor responses@@ -946,7 +946,7 @@ class TestTimezoneHandling(TransactionTestCase):response_datetime=utc_before,correlation_role_str=str(CorrelationRole.END),correlation_id='utc_before',- has_video_stream=True+ has_event_video_clip=True)record_after = SensorHistory.objects.create(@@ -955,7 +955,7 @@ class TestTimezoneHandling(TransactionTestCase):response_datetime=utc_after,correlation_role_str=str(CorrelationRole.END),correlation_id='utc_after',- has_video_stream=True+ has_event_video_clip=True)response_before = VideoStreamBrowsingHelper.create_sensor_response_with_history_id(record_before)@@ -986,14 +986,14 @@ class TestTimezoneHandling(TransactionTestCase):sensor=self.video_sensor,value='late_night',response_datetime=pst_late_night,- has_video_stream=True+ has_event_video_clip=True)record_early = SensorHistory.objects.create(sensor=self.video_sensor,value='early_morning',response_datetime=pst_early_morning,- has_video_stream=True+ has_event_video_clip=True)response_late = VideoStreamBrowsingHelper.create_sensor_response_with_history_id(record_late)@@ -1027,7 +1027,7 @@ class TestTimezoneHandling(TransactionTestCase):sensor=self.video_sensor,value='test_event',response_datetime=utc_time,- has_video_stream=True+ has_event_video_clip=True)response = VideoStreamBrowsingHelper.create_sensor_response_with_history_id(record)@@ -1064,7 +1064,7 @@ class TestTimezoneHandling(TransactionTestCase):sensor=self.video_sensor,value='test_event',response_datetime=utc_time,- has_video_stream=True+ has_event_video_clip=True)# Test build_sensor_history_data_default with timezonediff --git a/src/hi/apps/console/tests/test_view_url_utils.py b/src/hi/apps/console/tests/test_view_url_utils.pyindex cffd83fe..34991f5a 100644--- a/src/hi/apps/console/tests/test_view_url_utils.py+++ b/src/hi/apps/console/tests/test_view_url_utils.py@@ -74,8 +74,7 @@ class TestViewUrlUtils(BaseTestCase):timestamp=datetimeproxy.now(),sensor=self.video_motion_sensor,detail_attrs={},- source_image_url=None,- has_video_stream=False+ has_event_video_clip=False)alarm = Alarm(@@ -112,8 +111,7 @@ class TestViewUrlUtils(BaseTestCase):timestamp=datetimeproxy.now(),sensor=self.temp_sensor,detail_attrs={},- source_image_url=None,- has_video_stream=False+ has_event_video_clip=False)alarm = Alarm(@@ -148,8 +146,7 @@ class TestViewUrlUtils(BaseTestCase):timestamp=datetimeproxy.now(),sensor=None, # No sensor objectdetail_attrs={'event': 'Tornado Warning'},- source_image_url=None,- has_video_stream=False+ has_event_video_clip=False)alarm = Alarm(diff --git a/src/hi/apps/console/tests/test_views.py b/src/hi/apps/console/tests/test_views.pyindex a22a12c3..8af746e7 100644--- a/src/hi/apps/console/tests/test_views.py+++ b/src/hi/apps/console/tests/test_views.py@@ -118,7 +118,7 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):name='Motion Sensor',entity_state=self.entity_state,sensor_type_str='binary',- provides_video_stream=True+ provides_event_video_clip=True)# Create sensor history records for testing@@ -129,7 +129,7 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):sensor=self.video_sensor,value='active' if i % 2 == 0 else 'idle',response_datetime=base_time - timezone.timedelta(hours=i),- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id='test',details='{"test": "data"}'@@ -145,7 +145,7 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):name='Temperature Sensor',entity_state=self.entity_state,sensor_type_str='sensor',- provides_video_stream=False+ provides_event_video_clip=False)view = EntityVideoSensorHistoryView()@@ -174,7 +174,7 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):sensor=self.video_sensor,value=f'motion_detected_{i}',response_datetime=base_time - timezone.timedelta(hours=i),- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id='test',details=f'{{"event": "test_{i}", "confidence": 0.9}}'@@ -233,7 +233,7 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):sensor=self.video_sensor,value=f'older_motion_{i}',response_datetime=base_time - timezone.timedelta(hours=3 + i),- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id='test',details=f'{{"event": "older_{i}", "confidence": 0.8}}'@@ -246,7 +246,7 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):sensor=self.video_sensor,value=f'newer_motion_{i}',response_datetime=base_time - timezone.timedelta(minutes=30 * i),- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id='test',details=f'{{"event": "newer_{i}", "confidence": 0.9}}'@@ -302,7 +302,7 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):sensor=self.video_sensor,value=f'older_motion_{i}',response_datetime=base_time - timezone.timedelta(hours=5 + i),- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id='test',details=f'{{"event": "older_{i}", "confidence": 0.7}}'@@ -315,7 +315,7 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):sensor=self.video_sensor,value=f'newer_motion_{i}',response_datetime=base_time - timezone.timedelta(hours=2.5) + timezone.timedelta(minutes=15 * i),- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id='test',details=f'{{"event": "newer_{i}", "confidence": 0.95}}'@@ -372,14 +372,14 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):sensor=self.video_sensor,value='outside_before_window',response_datetime=base_time - timezone.timedelta(hours=4),- has_video_stream=True+ has_event_video_clip=True)SensorHistory.objects.create(sensor=self.video_sensor,value='outside_after_window',response_datetime=base_time,- has_video_stream=True+ has_event_video_clip=True)# Records inside the window (should appear in results)@@ -389,7 +389,7 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):sensor=self.video_sensor,value=f'inside_window_{i}',response_datetime=base_time - timezone.timedelta(hours=2) + timezone.timedelta(minutes=20 * i),- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id='test',details=f'{{"window_test": "record_{i}"}}'@@ -487,7 +487,7 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):sensor=self.video_sensor,value='active',response_datetime=timezone.now(),- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id='test',details='invalid-json-format{not valid}'@@ -583,7 +583,7 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):sensor=self.video_sensor,value=f'large_dataset_record_{i}',response_datetime=base_time - timezone.timedelta(minutes=i * 10),- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id='test',details=f'{{"large_test": true, "index": {i}}}'@@ -630,7 +630,7 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):sensor=self.video_sensor,value=f'same_time_{i}',response_datetime=same_timestamp,- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id='test',details=f'{{"same_timestamp_test": {i}}}'@@ -642,7 +642,7 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):sensor=self.video_sensor,value='after_midnight',response_datetime=midnight_boundary,- has_video_stream=True+ has_event_video_clip=True)before_midnight = midnight_boundary - timezone.timedelta(minutes=2)@@ -650,7 +650,7 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):sensor=self.video_sensor,value='before_midnight',response_datetime=before_midnight,- has_video_stream=True+ has_event_video_clip=True)view = EntityVideoSensorHistoryView()diff --git a/src/hi/apps/console/video_stream_browsing_helper.py b/src/hi/apps/console/video_stream_browsing_helper.pyindex 5cc0d8aa..f6a21152 100644--- a/src/hi/apps/console/video_stream_browsing_helper.py+++ b/src/hi/apps/console/video_stream_browsing_helper.py@@ -32,7 +32,7 @@ class VideoStreamBrowsingHelper:"""Find the first sensor with video capability for an entity.Uses priority order to select the best sensor and optimizes- queries. Eligibility is sensor-level (``provides_video_stream``);+ queries. Eligibility is sensor-level (``provides_event_video_clip``);independent of whether the parent entity has its own live feed."""if not entity:@@ -54,7 +54,7 @@ class VideoStreamBrowsingHelper:state_type_to_sensors[state_type_str] = []state_type_to_sensors[state_type_str].extend(sensor for sensor in state.sensors.all()- if sensor.provides_video_stream+ if sensor.provides_event_video_clip)# Check sensors in priority order@@ -343,7 +343,7 @@ class VideoStreamBrowsingHelper:current_record = SensorHistory.objects.get(id=current_history_id,sensor=sensor,- has_video_stream=True+ has_event_video_clip=True)except SensorHistory.DoesNotExist:return (None, None)@@ -627,7 +627,7 @@ class VideoStreamBrowsingHelper:current_history_record = SensorHistory.objects.get(id=sensor_history_id,sensor=sensor,- has_video_stream=True+ has_event_video_clip=True)# Check if we should preserve timeline (record is within preserve window)diff --git a/src/hi/apps/console/views.py b/src/hi/apps/console/views.pyindex c8b8b27e..c2998d2f 100644--- a/src/hi/apps/console/views.py+++ b/src/hi/apps/console/views.py@@ -105,7 +105,7 @@ class BaseEntityVideoSensorHistoryView( HiGridView, EntityViewMixin, SenseViewMisensor = self.get_sensor( request, *args, **kwargs )# Check if sensor provides video stream capability- if not sensor.provides_video_stream:+ if not sensor.provides_event_video_clip:raise BadRequest( 'Sensor does not provide video stream capability.' )# Build sensor history data using subclass-specific methoddiff --git a/src/hi/apps/entity/entity_pairing_manager.py b/src/hi/apps/entity/entity_pairing_manager.pyindex 0316a523..608a52ed 100644--- a/src/hi/apps/entity/entity_pairing_manager.py+++ b/src/hi/apps/entity/entity_pairing_manager.py@@ -23,6 +23,7 @@ class EntityPairingManager(Singleton):# added to a location view for the first time.enums.EntityStateType.MOVEMENT: enums.EntityType.AREA,+ enums.EntityStateType.OBJECT_PRESENCE: enums.EntityType.AREA,enums.EntityStateType.PRESENCE: enums.EntityType.AREA,enums.EntityStateType.SOUND_LEVEL: enums.EntityType.AREA,}diff --git a/src/hi/apps/entity/entity_state_history.py b/src/hi/apps/entity/entity_state_history.pyindex 63d19452..f641482a 100644--- a/src/hi/apps/entity/entity_state_history.py+++ b/src/hi/apps/entity/entity_state_history.py@@ -75,8 +75,8 @@ class EntityStateHistoryValue:confirming observation within the window (or where theobservation's value did not match).- Click-through metadata (``sensor_history_id``, ``has_video_stream``,- ``has_details``, ``provides_video_stream``) is populated on+ Click-through metadata (``sensor_history_id``, ``has_event_video_clip``,+ ``has_details``, ``provides_event_video_clip``) is populated onOBSERVATION rows from the underlying ``SensorHistory`` and theparent ``Sensor``. INTENT rows leave these at defaults sincecontrollers don't have video or details to link to."""@@ -88,9 +88,9 @@ class EntityStateHistoryValue:history_value_type : StateHistoryValueTypematched_intent : Optional[ MatchedIntent ] = Nonesensor_history_id : Optional[ int ] = None- has_video_stream : bool = False+ has_event_video_clip : bool = Falsehas_details : bool = False- provides_video_stream : bool = False+ provides_event_video_clip : bool = False@propertydef video_browse_url(self) -> Optional[ str ]:@@ -103,8 +103,8 @@ class EntityStateHistoryValue:entity_id = self.entity_state.entity.id,sensor_id = self.instrument.id,sensor_history_id = self.sensor_history_id,- has_video_stream = self.has_video_stream,- provides_video_stream = self.provides_video_stream,+ has_event_video_clip = self.has_event_video_clip,+ provides_event_video_clip = self.provides_event_video_clip,)@property@@ -238,9 +238,9 @@ def merge_history(history_value_type = StateHistoryValueType.OBSERVATION,matched_intent = matched_intent,sensor_history_id = obs.id,- has_video_stream = obs.has_video_stream,+ has_event_video_clip = obs.has_event_video_clip,has_details = bool( obs.detail_attrs ),- provides_video_stream = obs.sensor.provides_video_stream,+ provides_event_video_clip = obs.sensor.provides_event_video_clip,))continuefor intent_history in unmatched_intents:diff --git a/src/hi/apps/entity/entity_state_role_order.py b/src/hi/apps/entity/entity_state_role_order.pyindex 44ad188c..16dadff4 100644--- a/src/hi/apps/entity/entity_state_role_order.py+++ b/src/hi/apps/entity/entity_state_role_order.py@@ -31,6 +31,7 @@ DEFAULT_ENTITY_STATE_ROLE_ORDER : List[ EntityStateRole ] = [EntityStateRole.CO,EntityStateRole.GAS,EntityStateRole.MOISTURE,+ EntityStateRole.OBJECT_PRESENCE,EntityStateRole.MOVEMENT,EntityStateRole.PRESENCE,EntityStateRole.OPEN_CLOSE,diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.pyindex dd2b4afd..d12f914a 100644--- a/src/hi/apps/entity/enums.py+++ b/src/hi/apps/entity/enums.py@@ -236,6 +236,19 @@ class EntityStateValue(LabeledEnum):GAS_DETECTED = ( 'Gas Detected', '' )GAS_CLEAR = ( 'Clear', '' )+ # OBJECT_PRESENCE values — canonical buckets the integration's+ # converter maps raw upstream object-detection labels onto. The+ # raw label (e.g. Frigate's ``dog`` / ``truck`` / arbitrary+ # custom-model class) is preserved on the sensor's+ # ``detail_attrs``; the typed-enum value lets rule matching and+ # styling key off a stable, bounded vocabulary.+ OBJECT_NONE = ( 'No Object', '' )+ OBJECT_PERSON = ( 'Person', '' )+ OBJECT_CAR = ( 'Car', '' )+ OBJECT_ANIMAL = ( 'Animal', '' )+ OBJECT_PACKAGE = ( 'Package', '' )+ OBJECT_OTHER = ( 'Other Object', '' )+# COLOR_MODE values — modes a smart bulb can be in. UNKNOWN# covers integrations that don't report a mode and cases where# the bulb hasn't yet declared one. Names follow HA's modes;@@ -304,6 +317,7 @@ class EntityStateRole(LabeledEnum):LIGHT_LEVEL = ( 'Light Level' , '' )MOISTURE = ( 'Moisture' , '' )MOVEMENT = ( 'Movement' , '' )+ OBJECT_PRESENCE = ( 'Object Presence' , '' )ON_OFF = ( 'On/Off' , '' )OPEN_CLOSE = ( 'Open/Close' , '' )OPEN_CLOSE_POSITION = ( 'Open/Close Position', '' )@@ -432,7 +446,20 @@ class EntityStateType(LabeledEnum):EntityStateValue.MOISTURE_CLEAR ] )MOVEMENT = ( 'Movement' , '',[ EntityStateValue.ACTIVE,- EntityStateValue.IDLE ] )+ EntityStateValue.IDLE ] )+ # OBJECT_PRESENCE — discrete object-class detection. Value space+ # is the canonical bucket set; the integration's converter+ # (e.g. ``FrigateConverter.to_canonical_object_class``) maps raw+ # upstream labels onto these so rule matching and styling key+ # off a bounded vocabulary. ``OBJECT_NONE`` is the resting+ # value; everything else is an alarm-style detection.+ OBJECT_PRESENCE = ( 'Object Presence' , '',+ [ EntityStateValue.OBJECT_NONE,+ EntityStateValue.OBJECT_PERSON,+ EntityStateValue.OBJECT_CAR,+ EntityStateValue.OBJECT_ANIMAL,+ EntityStateValue.OBJECT_PACKAGE,+ EntityStateValue.OBJECT_OTHER ] )ON_OFF = ( 'On/Off' , '',[ EntityStateValue.ON,EntityStateValue.OFF ] )@@ -522,9 +549,13 @@ class VideoStreamMode(LabeledEnum):class VideoStreamType(LabeledEnum):- """Types of video streams that can be provided by entities or sensor responses."""+ """Discrimination of what kind of media lives at ``VideoStream.source_url``.+ Drives the HI render layer's choice between ``<img>`` (browsers+ render multipart/x-mixed-replace MJPEG inside <img>) and+ ``<video>`` (for actual MP4 / HLS / WebM clips)."""- URL = ('URL', 'Direct video stream URL')+ MJPEG = ('MJPEG', 'multipart/x-mixed-replace stream rendered by <img>')+ MP4 = ('MP4', 'MP4 clip rendered by <video>')OTHER = ('Other', 'Other video stream type for future extensibility')@classmethoddiff --git a/src/hi/apps/entity/state_panels/camera/panel.py b/src/hi/apps/entity/state_panels/camera/panel.pyindex 8b8c658e..718a81fc 100644--- a/src/hi/apps/entity/state_panels/camera/panel.py+++ b/src/hi/apps/entity/state_panels/camera/panel.py@@ -4,10 +4,12 @@ from hi.apps.entity.state_panel_base import EntityStatePanel_OPTIONAL_ROLES = {EntityStateRole.MOVEMENT,+ EntityStateRole.OBJECT_PRESENCE,}_ROLE_DATA_TEMPLATE_ALIASES = {'motion_data': EntityStateRole.MOVEMENT,+ 'object_data': EntityStateRole.OBJECT_PRESENCE,}diff --git a/src/hi/apps/entity/templates/entity/state_panels/camera/modal.html b/src/hi/apps/entity/templates/entity/state_panels/camera/modal.htmlindex 82474afd..fa780039 100644--- a/src/hi/apps/entity/templates/entity/state_panels/camera/modal.html+++ b/src/hi/apps/entity/templates/entity/state_panels/camera/modal.html@@ -1,11 +1,12 @@{# Aliases declared in panel.py (role_data_template_aliases): #}-{# motion_data (optional). #}+{# motion_data (optional), object_data (optional). #}{# #}-{# Stream rendering goes through the standard live-view template so #}-{# the panel inherits its offline placeholder, click-through, and #}-{# polling-driven snapshot refresh. Anything beyond the stream (and #}-{# the optional motion chip) flows into the framework extras section #}-{# beneath the panel body. #}+{# Chip prefers object_data over motion_data when both are present: #}+{# OBJECT_PRESENCE carries the finer-grained class info, and a camera #}+{# is unlikely to have both, but if it does the object class wins. #}+{# Both roles also render as state rows below the stream so the user #}+{# can see the current value and click through to history regardless #}+{# of which one the camera carries. #}<div class="hi-state-panel-camera hi-state-panel-camera--modal"><div class="stream">@@ -14,9 +15,22 @@{% else %}<div class="stream-unavailable">Live view not available</div>{% endif %}- {% if motion_data %}+ {% if object_data %}+ {% include "entity/state_panels/camera/motion_chip.html" with motion_data=object_data %}+ {% elif motion_data %}{% include "entity/state_panels/camera/motion_chip.html" %}{% endif %}</div>+ {% if object_data %}+ <div class="mt-3">+ {% include "entity/state_panels/fallback/state_row.html" with entity_state_status_data=object_data %}+ </div>+ {% endif %}+ {% if motion_data %}+ <div class="mt-3">+ {% include "entity/state_panels/fallback/state_row.html" with entity_state_status_data=motion_data %}+ </div>+ {% endif %}+</div>diff --git a/src/hi/apps/entity/templates/entity/state_panels/camera/row.html b/src/hi/apps/entity/templates/entity/state_panels/camera/row.htmlindex cebc8ce3..0e9a47f3 100644--- a/src/hi/apps/entity/templates/entity/state_panels/camera/row.html+++ b/src/hi/apps/entity/templates/entity/state_panels/camera/row.html@@ -1,11 +1,12 @@{% load humanize tz video_tags %}{# Aliases declared in panel.py (role_data_template_aliases): #}-{# motion_data (optional). #}+{# motion_data (optional), object_data (optional). #}{# #}{# ROW context: thumbnail snapshot (when available) + entity name + #}{# (optional) motion chip + (optional) "Motion N min ago" timestamp. #}{# No live feed embed — a tiny stream is not useful, and the modal #}{# carries the live feed. Card-wide click goes to the modal. #}+{# Chip prefers object_data over motion_data — see modal.html. #}<div class="hi-state-panel-camera hi-state-panel-camera--row">{% if entity.has_video_snapshot %}@@ -28,11 +29,12 @@<div class="entity-name">{{ entity.name }}</div>- {% if motion_data %}+ {% if object_data %}+ {% include "entity/state_panels/camera/motion_chip.html" with motion_data=object_data %}+ {% with summary=object_data.recent_state_value_summary %}{% if summary.penultimate %}<div class="last-event">Last detection {{ summary.penultimate.timestamp|localtime|naturaltime }}</div>{% endif %}{% endwith %}+ {% elif motion_data %}{% include "entity/state_panels/camera/motion_chip.html" %}- {% with summary=motion_data.recent_state_value_summary %}{% if summary.penultimate %}- <div class="last-event">Motion {{ summary.penultimate.timestamp|localtime|naturaltime }}</div>- {% endif %}{% endwith %}+ {% with summary=motion_data.recent_state_value_summary %}{% if summary.penultimate %}<div class="last-event">Motion {{ summary.penultimate.timestamp|localtime|naturaltime }}</div>{% endif %}{% endwith %}{% endif %}</div>diff --git a/src/hi/apps/entity/templates/entity/state_panels/camera/tile.html b/src/hi/apps/entity/templates/entity/state_panels/camera/tile.htmlindex b95b1b17..3860db04 100644--- a/src/hi/apps/entity/templates/entity/state_panels/camera/tile.html+++ b/src/hi/apps/entity/templates/entity/state_panels/camera/tile.html@@ -1,5 +1,6 @@{# Aliases declared in panel.py (role_data_template_aliases): #}-{# motion_data (optional). #}+{# motion_data (optional), object_data (optional). #}+{# Chip prefers object_data over motion_data — see modal.html. #}<div class="hi-state-panel-camera hi-state-panel-camera--tile"><div class="stream">@@ -8,7 +9,9 @@{% else %}<div class="stream-unavailable">Offline</div>{% endif %}- {% if motion_data %}+ {% if object_data %}+ {% include "entity/state_panels/camera/motion_chip.html" with motion_data=object_data %}+ {% elif motion_data %}{% include "entity/state_panels/camera/motion_chip.html" %}{% endif %}</div>diff --git a/src/hi/apps/entity/tests/test_entity_state_history.py b/src/hi/apps/entity/tests/test_entity_state_history.pyindex d09ed30d..61ec4345 100644--- a/src/hi/apps/entity/tests/test_entity_state_history.py+++ b/src/hi/apps/entity/tests/test_entity_state_history.py@@ -360,14 +360,14 @@ class TestMergeHistory( BaseTestCase ):self.assertEqual( len( result ), 1 )self.assertEqual( result[ 0 ].sensor_history_id, obs.id )- def test_observation_row_reflects_has_video_stream_from_source(self):+ def test_observation_row_reflects_has_event_video_clip_from_source(self):obs_with = SensorHistory.objects.create(sensor = self.sensor, value = 'on',- response_datetime = _at( 0 ), has_video_stream = True,+ response_datetime = _at( 0 ), has_event_video_clip = True,)obs_without = SensorHistory.objects.create(sensor = self.sensor, value = 'on',- response_datetime = _at( 1 ), has_video_stream = False,+ response_datetime = _at( 1 ), has_event_video_clip = False,)result = merge_history(@@ -377,8 +377,8 @@ class TestMergeHistory( BaseTestCase ):)by_id = { r.sensor_history_id: r for r in result }- self.assertTrue( by_id[ obs_with.id ].has_video_stream )- self.assertFalse( by_id[ obs_without.id ].has_video_stream )+ self.assertTrue( by_id[ obs_with.id ].has_event_video_clip )+ self.assertFalse( by_id[ obs_without.id ].has_event_video_clip )def test_observation_row_has_details_when_details_present(self):obs_with = SensorHistory.objects.create(@@ -398,15 +398,15 @@ class TestMergeHistory( BaseTestCase ):self.assertTrue( by_id[ obs_with.id ].has_details )self.assertFalse( by_id[ obs_without.id ].has_details )- def test_observation_row_reflects_provides_video_stream_from_sensor(self):- # Two sensors on the same state, one with provides_video_stream+ def test_observation_row_reflects_provides_event_video_clip_from_sensor(self):+ # Two sensors on the same state, one with provides_event_video_clip# set. Each observation row carries its sensor's flag.video_sensor = Sensor.objects.create(entity_state = self.state,name = 'cam-sensor',sensor_type_str = 'DEFAULT',integration_payload = '{}',- provides_video_stream = True,+ provides_event_video_clip = True,)obs_video = self._observation( 'on', _at( 0 ), sensor = video_sensor )obs_plain = self._observation( 'on', _at( 1 ) )@@ -418,8 +418,8 @@ class TestMergeHistory( BaseTestCase ):)by_id = { r.sensor_history_id: r for r in result }- self.assertTrue( by_id[ obs_video.id ].provides_video_stream )- self.assertFalse( by_id[ obs_plain.id ].provides_video_stream )+ self.assertTrue( by_id[ obs_video.id ].provides_event_video_clip )+ self.assertFalse( by_id[ obs_plain.id ].provides_event_video_clip )def test_intent_row_click_through_fields_at_defaults(self):intent = self._intent( 'on', _at( 0 ) )@@ -433,9 +433,9 @@ class TestMergeHistory( BaseTestCase ):self.assertEqual( len( result ), 1 )row = result[ 0 ]self.assertIsNone( row.sensor_history_id )- self.assertFalse( row.has_video_stream )+ self.assertFalse( row.has_event_video_clip )self.assertFalse( row.has_details )- self.assertFalse( row.provides_video_stream )+ self.assertFalse( row.provides_event_video_clip )# ------------------------------------------------------------------# Click-through URL properties on the row type.@@ -443,7 +443,7 @@ class TestMergeHistory( BaseTestCase ):def test_observation_with_video_stream_has_video_browse_url(self):obs = SensorHistory.objects.create(sensor = self.sensor, value = 'on',- response_datetime = _at( 0 ), has_video_stream = True,+ response_datetime = _at( 0 ), has_event_video_clip = True,)result = merge_history(@@ -501,7 +501,7 @@ class TestMergeHistory( BaseTestCase ):obs = SensorHistory.objects.create(sensor = self.sensor, value = 'on',response_datetime = _at( 0 ),- has_video_stream = True,+ has_event_video_clip = True,details = '{"trigger": "motion"}',)diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.pyindex a29de5c9..3c27e21d 100644--- a/src/hi/apps/entity/tests/test_views.py+++ b/src/hi/apps/entity/tests/test_views.py@@ -1220,7 +1220,7 @@ class TestEntityStateHistoryView(DualModeViewTestCase):self.assertIn( '%2B00%3A00', body )def test_video_browse_affordance_rendered_for_video_stream_rows(self):- """Rows whose underlying SensorHistory has_video_stream render a+ """Rows whose underlying SensorHistory has_event_video_clip render aclick-through to the per-event video browser; rows without itdo not."""from django.urls import reverse as _reverse@@ -1229,7 +1229,7 @@ class TestEntityStateHistoryView(DualModeViewTestCase):video_obs = SensorHistory.objects.create(sensor = self.sensor, value = 'on',response_datetime = '2024-03-01T12:00:00Z',- has_video_stream = True,+ has_event_video_clip = True,)expected_url = _reverse('console_entity_video_sensor_history_detail',diff --git a/src/hi/apps/event/tests/test_event_manager.py b/src/hi/apps/event/tests/test_event_manager.pyindex f2d351e9..fec5ab9d 100644--- a/src/hi/apps/event/tests/test_event_manager.py+++ b/src/hi/apps/event/tests/test_event_manager.py@@ -29,7 +29,6 @@ def create_test_sensor_response(value, timestamp, detail_attrs=None):value=value,timestamp=timestamp,detail_attrs=detail_attrs or {},- source_image_url=None)diff --git a/src/hi/apps/event/view_helpers.py b/src/hi/apps/event/view_helpers.pyindex fb045b9f..4ba63891 100644--- a/src/hi/apps/event/view_helpers.py+++ b/src/hi/apps/event/view_helpers.py@@ -67,7 +67,7 @@ class EventHistoryViewHelper:for clause in event_history.event_definition.event_clauses.all():entity = clause.entity_state.entityfor sensor in clause.entity_state.sensors.all():- if sensor.provides_video_stream:+ if sensor.provides_event_video_clip:if entity.id not in video_entities:video_entities[entity.id] = {'entity': entity,diff --git a/src/hi/apps/model_helper.py b/src/hi/apps/model_helper.pyindex efed1de0..25a28ca1 100644--- a/src/hi/apps/model_helper.py+++ b/src/hi/apps/model_helper.py@@ -245,7 +245,7 @@ class HiModelHelper:entity : Entity,integration_key : IntegrationKey = None,name : str = None,- provides_video_stream : bool = False,+ provides_event_video_clip : bool = False,add_default_alarm : bool = False ) -> Sensor:if not name:name = f'{entity.name} Motion'@@ -254,7 +254,7 @@ class HiModelHelper:entity_state_type = EntityStateType.MOVEMENT,name = name,integration_key = integration_key,- provides_video_stream = provides_video_stream,+ provides_event_video_clip = provides_event_video_clip,)if add_default_alarm:cls.create_movement_event_definition(@@ -264,6 +264,30 @@ class HiModelHelper:)return sensor+ @classmethod+ def create_object_presence_sensor( cls,+ entity : Entity,+ integration_key : IntegrationKey = None,+ name : str = None,+ provides_event_video_clip : bool = False,+ provides_event_video_snapshot : bool = False ) -> Sensor:+ """OBJECT_PRESENCE sensor — typed discrete state whose value+ space is the canonical object-class bucket set+ (NONE / PERSON / CAR / ANIMAL / PACKAGE / OTHER). The+ integration's converter is responsible for mapping raw+ upstream labels onto the canonical set; the resting value+ is OBJECT_NONE."""+ if not name:+ name = f'{entity.name} Object'+ return cls.create_sensor(+ entity = entity,+ entity_state_type = EntityStateType.OBJECT_PRESENCE,+ name = name,+ integration_key = integration_key,+ provides_event_video_clip = provides_event_video_clip,+ provides_event_video_snapshot = provides_event_video_snapshot,+ )+@classmethoddef create_presence_sensor( cls,entity : Entity,@@ -532,15 +556,16 @@ class HiModelHelper:@classmethoddef create_sensor( cls,- entity : Entity,- entity_state_type : EntityStateType,- name : str = None,- sensor_type : SensorType = SensorType.DEFAULT,- integration_key : IntegrationKey = None,- value_range_str : str = '',- units : str = None,- entity_state_role : EntityStateRole = None,- provides_video_stream : bool = False ) -> Sensor:+ entity : Entity,+ entity_state_type : EntityStateType,+ name : str = None,+ sensor_type : SensorType = SensorType.DEFAULT,+ integration_key : IntegrationKey = None,+ value_range_str : str = '',+ units : str = None,+ entity_state_role : EntityStateRole = None,+ provides_event_video_clip : bool = False,+ provides_event_video_snapshot : bool = False ) -> Sensor:if not name:name = f'{entity.name}'@@ -559,7 +584,8 @@ class HiModelHelper:name = name,sensor_type_str = str( sensor_type ),persist_history = bool( entity_state_type not in cls.EXCLUDE_FROM_SENSOR_HISTORY ),- provides_video_stream = provides_video_stream,+ provides_event_video_clip = provides_event_video_clip,+ provides_event_video_snapshot = provides_event_video_snapshot,)sensor.integration_key = integration_keysensor.save()@@ -679,7 +705,7 @@ class HiModelHelper:name : str,entity_state : EntityState,integration_key : IntegrationKey = None ) -> EventDefinition:-+return EventManager().create_simple_alarm_event_definition(name = name,event_type = EventType.SECURITY,@@ -695,6 +721,32 @@ class HiModelHelper:integration_key = integration_key,)+ @classmethod+ def create_object_presence_event_definition(+ cls,+ name : str,+ entity_state : EntityState,+ integration_key : IntegrationKey = None ) -> EventDefinition:+ # Conservative default: alarm on PERSON only. The+ # EventClauseOperator vocabulary doesn't yet support NEQ/IN+ # (see Issue #346), so "any detection" can't be expressed as+ # a single clause. Operators wanting broader rules (car,+ # package, etc.) can add EventDefinitions in the UI.+ return EventManager().create_simple_alarm_event_definition(+ name = name,+ event_type = EventType.SECURITY,+ entity_state = entity_state,+ value = EntityStateValue.OBJECT_PERSON,+ security_to_alarm_level = {+ SecurityLevel.HIGH: AlarmLevel.CRITICAL,+ SecurityLevel.LOW: AlarmLevel.INFO,+ },+ event_window_secs = cls.DEFAULT_MOVEMENT_EVENT_WINDOW_SECS,+ dedupe_window_secs = cls.DEFAULT_MOVEMENT_DEDUPE_WINDOW_SECS,+ alarm_lifetime_secs = cls.DEFAULT_MOVEMENT_ALARM_LIFETIME_SECS,+ integration_key = integration_key,+ )+@classmethoddef create_presence_event_definition(cls,diff --git a/src/hi/apps/monitor/display_data.py b/src/hi/apps/monitor/display_data.pyindex 05884f66..8e957ec7 100644--- a/src/hi/apps/monitor/display_data.py+++ b/src/hi/apps/monitor/display_data.py@@ -315,7 +315,10 @@ class EntityStateDisplayData:if self.entity_state.entity_state_type == EntityStateType.MOVEMENT:return self._get_movement_status_style()-++ if self.entity_state.entity_state_type == EntityStateType.OBJECT_PRESENCE:+ return self._get_object_presence_status_style()+if self.entity_state.entity_state_type == EntityStateType.PRESENCE:return self._get_presence_status_style()@@ -408,6 +411,29 @@ class EntityStateDisplayData:return StatusStyle.MovementIdle+ def _get_object_presence_status_style( self ):+ # OBJECT_PRESENCE collapses onto the Movement Active/Recent/+ # Past/Idle vocabulary: any non-OBJECT_NONE value is treated+ # as "active" (detection happening). Same decay thresholds as+ # MOVEMENT so the visual treatment is uniform across both+ # state types — see the StatusStyle.Movement* status_values+ # and the CSS rules keyed off them.+ object_none_value = str(EntityStateValue.OBJECT_NONE)++ if self.latest_sensor_value and self.latest_sensor_value != object_none_value:+ return StatusStyle.MovementActive++ if ( self.penultimate_sensor_value+ and self.penultimate_sensor_value != object_none_value ):+ object_timedelta = datetimeproxy.now() - self.penultimate_sensor_timestamp+ if object_timedelta.total_seconds() < self.RECENT_MOVEMENT_THRESHOLD_SECS:+ return StatusStyle.MovementRecent++ elif object_timedelta.total_seconds() < self.PAST_MOVEMENT_THRESHOLD_SECS:+ return StatusStyle.MovementPast++ return StatusStyle.MovementIdle+def _get_smoke_status_style( self ):if self.latest_sensor_value == str(EntityStateValue.SMOKE_DETECTED):diff --git a/src/hi/apps/monitor/tests/test_status_display_data.py b/src/hi/apps/monitor/tests/test_status_display_data.pyindex 4544a257..e590fc44 100644--- a/src/hi/apps/monitor/tests/test_status_display_data.py+++ b/src/hi/apps/monitor/tests/test_status_display_data.py@@ -318,6 +318,91 @@ class TestEntityStateDisplayData(BaseTestCase):# Should return MovementIdle for inactive presenceself.assertEqual(display_data.svg_status_style, StatusStyle.MovementIdle)+ # OBJECT_PRESENCE State Type Tests+ #+ # Same decay thresholds as MOVEMENT, but the "active" discriminator+ # is "value is not OBJECT_NONE" (any detected class counts).++ @patch('hi.apps.common.datetimeproxy.now')+ def test_object_presence_detected_returns_movement_active(self, mock_now):+ mock_now.return_value = datetime(2023, 1, 1, 12, 0, 0)+ sensor_response = self._create_mock_sensor_response(+ str(EntityStateValue.OBJECT_PERSON),+ )+ status_data = self._create_entity_state_status_data(+ 'OBJECT_PRESENCE', [sensor_response],+ )+ display_data = EntityStateDisplayData(status_data)+ self.assertEqual(display_data.svg_status_style, StatusStyle.MovementActive)++ @patch('hi.apps.common.datetimeproxy.now')+ def test_object_presence_other_class_also_active(self, mock_now):+ # Any non-NONE class — including OTHER — keeps the style active.+ mock_now.return_value = datetime(2023, 1, 1, 12, 0, 0)+ sensor_response = self._create_mock_sensor_response(+ str(EntityStateValue.OBJECT_OTHER),+ )+ status_data = self._create_entity_state_status_data(+ 'OBJECT_PRESENCE', [sensor_response],+ )+ display_data = EntityStateDisplayData(status_data)+ self.assertEqual(display_data.svg_status_style, StatusStyle.MovementActive)++ @patch('hi.apps.common.datetimeproxy.now')+ def test_object_presence_recent_within_threshold(self, mock_now):+ base_time = datetime(2023, 1, 1, 12, 0, 0)+ mock_now.return_value = base_time+ # Penultimate detected a class 60s ago (within RECENT 90s);+ # current is NONE.+ recent_response = self._create_mock_sensor_response(+ str(EntityStateValue.OBJECT_NONE), base_time,+ )+ past_response = self._create_mock_sensor_response(+ str(EntityStateValue.OBJECT_ANIMAL),+ base_time - timedelta(seconds=60),+ )+ status_data = self._create_entity_state_status_data(+ 'OBJECT_PRESENCE', [recent_response, past_response],+ )+ display_data = EntityStateDisplayData(status_data)+ self.assertEqual(display_data.svg_status_style, StatusStyle.MovementRecent)++ @patch('hi.apps.common.datetimeproxy.now')+ def test_object_presence_past_within_threshold(self, mock_now):+ base_time = datetime(2023, 1, 1, 12, 0, 0)+ mock_now.return_value = base_time+ # Penultimate detected a class 120s ago (between 90s and 180s).+ recent_response = self._create_mock_sensor_response(+ str(EntityStateValue.OBJECT_NONE), base_time,+ )+ past_response = self._create_mock_sensor_response(+ str(EntityStateValue.OBJECT_CAR),+ base_time - timedelta(seconds=120),+ )+ status_data = self._create_entity_state_status_data(+ 'OBJECT_PRESENCE', [recent_response, past_response],+ )+ display_data = EntityStateDisplayData(status_data)+ self.assertEqual(display_data.svg_status_style, StatusStyle.MovementPast)++ @patch('hi.apps.common.datetimeproxy.now')+ def test_object_presence_idle_beyond_threshold(self, mock_now):+ base_time = datetime(2023, 1, 1, 12, 0, 0)+ mock_now.return_value = base_time+ # Penultimate detected a class 200s ago (beyond PAST 180s).+ recent_response = self._create_mock_sensor_response(+ str(EntityStateValue.OBJECT_NONE), base_time,+ )+ past_response = self._create_mock_sensor_response(+ str(EntityStateValue.OBJECT_PACKAGE),+ base_time - timedelta(seconds=200),+ )+ status_data = self._create_entity_state_status_data(+ 'OBJECT_PRESENCE', [recent_response, past_response],+ )+ display_data = EntityStateDisplayData(status_data)+ self.assertEqual(display_data.svg_status_style, StatusStyle.MovementIdle)+# OPEN_CLOSE State Type Tests with Time Thresholds@patch('hi.apps.common.datetimeproxy.now')diff --git a/src/hi/apps/sense/admin.py b/src/hi/apps/sense/admin.pyindex c2b1f92d..1725098b 100644--- a/src/hi/apps/sense/admin.py+++ b/src/hi/apps/sense/admin.py@@ -40,10 +40,10 @@ class SensorHistoryAdmin(admin.ModelAdmin):'value','response_datetime','details',- 'has_video_stream',+ 'has_event_video_clip','correlation_role_str','correlation_id',- 'source_image_url',+ 'has_event_video_snapshot',)search_fields = ['sensor__name']diff --git a/src/hi/apps/sense/migrations/0012_event_video_field_renames.py b/src/hi/apps/sense/migrations/0012_event_video_field_renames.pynew file mode 100644index 00000000..47e2dc89--- /dev/null+++ b/src/hi/apps/sense/migrations/0012_event_video_field_renames.py@@ -0,0 +1,68 @@+"""Rename sensor / sensor-history event-video fields to disambiguate+them from entity-level live-feed fields.++This migration performs ONLY field renames (no column drops or adds+beyond the one explicit ``AddField`` for the new+``provides_event_video_snapshot`` capability flag). Each rename+preserves the underlying column data — no data migration step is+needed.+"""+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("sense", "0011_add_previous_integration_identity"),+ ]++ operations = [+ migrations.RenameField(+ model_name="sensor",+ old_name="provides_video_stream",+ new_name="provides_event_video_clip",+ ),+ migrations.RenameField(+ model_name="sensorhistory",+ old_name="has_video_stream",+ new_name="has_event_video_clip",+ ),+ migrations.RenameField(+ model_name="sensorhistory",+ old_name="source_image_url",+ new_name="event_video_snapshot_url",+ ),+ migrations.AlterField(+ model_name="sensor",+ name="provides_event_video_clip",+ field=models.BooleanField(+ default=False,+ verbose_name="Provides Event Video Clip",+ ),+ ),+ migrations.AlterField(+ model_name="sensorhistory",+ name="has_event_video_clip",+ field=models.BooleanField(+ default=False,+ verbose_name="Has Event Video Clip",+ ),+ ),+ migrations.AlterField(+ model_name="sensorhistory",+ name="event_video_snapshot_url",+ field=models.TextField(+ blank=True,+ null=True,+ verbose_name="Event Video Snapshot URL",+ ),+ ),+ migrations.AddField(+ model_name="sensor",+ name="provides_event_video_snapshot",+ field=models.BooleanField(+ default=False,+ verbose_name="Provides Event Video Snapshot",+ ),+ ),+ ]diff --git a/src/hi/apps/sense/migrations/0013_replace_event_video_snapshot_url_with_flag.py b/src/hi/apps/sense/migrations/0013_replace_event_video_snapshot_url_with_flag.pynew file mode 100644index 00000000..7b4095ab--- /dev/null+++ b/src/hi/apps/sense/migrations/0013_replace_event_video_snapshot_url_with_flag.py@@ -0,0 +1,60 @@+"""Replace ``SensorHistory.event_video_snapshot_url`` with a boolean+``has_event_video_snapshot`` flag.++The URL is no longer stored — gateways generate it on demand from+the event id (matching the existing pattern for event video clips).+This makes the snapshot affordance robust against integration+host-relocation: the operator's stored URLs no longer point at a+stale base_url after they move e.g. Frigate to a new host.++Migration shape:+ 1. Add the ``has_event_video_snapshot`` column.+ 2. Backfill: any row that previously stored a non-empty snapshot+ URL had a snapshot, so flag it as such.+ 3. Drop the ``event_video_snapshot_url`` column.++Order matters — the backfill must run between the add and the drop.+"""+from django.db import migrations, models+++def _backfill_has_event_video_snapshot(apps, schema_editor):+ SensorHistory = apps.get_model('sense', 'SensorHistory')+ SensorHistory.objects.exclude(+ event_video_snapshot_url__isnull=True,+ ).exclude(+ event_video_snapshot_url='',+ ).update(has_event_video_snapshot=True)+++def _reverse_noop(apps, schema_editor):+ # The URL column is being dropped in the same migration, so we+ # have nowhere to write the URL back to on reverse. The flag+ # will simply be lost.+ return+++class Migration(migrations.Migration):++ dependencies = [+ ('sense', '0012_event_video_field_renames'),+ ]++ operations = [+ migrations.AddField(+ model_name='sensorhistory',+ name='has_event_video_snapshot',+ field=models.BooleanField(+ default=False,+ verbose_name='Has Event Video Snapshot',+ ),+ ),+ migrations.RunPython(+ _backfill_has_event_video_snapshot,+ _reverse_noop,+ ),+ migrations.RemoveField(+ model_name='sensorhistory',+ name='event_video_snapshot_url',+ ),+ ]diff --git a/src/hi/apps/sense/models.py b/src/hi/apps/sense/models.pyindex c7b84894..03cb0800 100644--- a/src/hi/apps/sense/models.py+++ b/src/hi/apps/sense/models.py@@ -51,8 +51,17 @@ class Sensor( IntegrationDetailsModel ):'Persist History',default = True,)- provides_video_stream = models.BooleanField(- 'Provides Video Stream',+ # Event-level capability flags. These describe what kind of+ # historical-playback artifact each reading of this sensor+ # carries. Distinct from any entity-level live-feed concept+ # (``Entity.has_video_stream`` / ``has_video_snapshot``), which+ # is about observing the camera in real time.+ provides_event_video_clip = models.BooleanField(+ 'Provides Event Video Clip',+ default = False,+ )+ provides_event_video_snapshot = models.BooleanField(+ 'Provides Event Video Snapshot',default = False,)@@ -110,12 +119,12 @@ class SensorHistory(models.Model):'Details',blank = True, null = True,)- source_image_url = models.TextField(- 'Image URL',- blank = True, null = True,+ has_event_video_clip = models.BooleanField(+ 'Has Event Video Clip',+ default = False,)- has_video_stream = models.BooleanField(- 'Has Video Stream',+ has_event_video_snapshot = models.BooleanField(+ 'Has Event Video Snapshot',default = False,)correlation_role_str = models.CharField(@@ -123,6 +132,13 @@ class SensorHistory(models.Model):max_length = 32,null = True, blank = True,)+ # SENSOR-SCOPED identifier — uniqueness is guaranteed only within+ # a single ``Sensor``'s history (the integration's upstream+ # event_id, opaque to us). Never query by ``correlation_id``+ # alone across all SensorHistory rows: scope every lookup with+ # the ``sensor`` foreign key (or, equivalently, the entity_state /+ # entity). A global query risks collisions between independent+ # integrations whose upstream id-space coincidentally overlap.correlation_id = models.CharField('Correlation ID',max_length = 32,@@ -171,15 +187,15 @@ class SensorHistory(models.Model):@propertydef video_browse_url(self) -> str:- if self.has_video_stream:+ if self.has_event_video_clip:return reverse( 'console_entity_video_sensor_history_detail',kwargs = { 'entity_id': self.entity.id,'sensor_id': self.sensor.id,'sensor_history_id': self.id })- if self.sensor.provides_video_stream:+ if self.sensor.provides_event_video_clip:return reverse( 'console_entity_video_sensor_history',kwargs = { 'entity_id': self.entity.id,- 'sensor_id': self.sensor.id })+ 'sensor_id': self.sensor.id })return None@propertydiff --git a/src/hi/apps/sense/sensor_history_urls.py b/src/hi/apps/sense/sensor_history_urls.pyindex 98f358bc..ecf13d88 100644--- a/src/hi/apps/sense/sensor_history_urls.py+++ b/src/hi/apps/sense/sensor_history_urls.py@@ -16,15 +16,15 @@ def sensor_history_video_browse_url(entity_id : int,sensor_id : int,sensor_history_id : Optional[ int ],- has_video_stream : bool,- provides_video_stream : bool,+ has_event_video_clip : bool,+ provides_event_video_clip : bool,) -> Optional[ str ]:"""Best URL to the video event browser for a given sensor-historydata point. Returns the per-event detail URL when the data pointitself has a stream; falls back to the sensor's event-timeline URLwhen the sensor produces streams generally; returns ``None`` whenno video affordance is appropriate."""- if has_video_stream and sensor_history_id:+ if has_event_video_clip and sensor_history_id:return reverse('console_entity_video_sensor_history_detail',kwargs = {@@ -33,7 +33,7 @@ def sensor_history_video_browse_url('sensor_history_id': sensor_history_id,},)- if provides_video_stream:+ if provides_event_video_clip:return reverse('console_entity_video_sensor_history',kwargs = {diff --git a/src/hi/apps/sense/templates/sense/modals/sensor_history_details.html b/src/hi/apps/sense/templates/sense/modals/sensor_history_details.htmlindex 7a5591ce..53103495 100644--- a/src/hi/apps/sense/templates/sense/modals/sensor_history_details.html+++ b/src/hi/apps/sense/templates/sense/modals/sensor_history_details.html@@ -1,4 +1,5 @@-{% extends "modals/action_done.html" %}+{% extends "modals/action_3.html" %}+{% load icons %}{% load video_tags %}{% block title_text %}@@ -9,25 +10,31 @@ Sensor Response Details<div><div class="h4">{{ sensor_history.sensor.name }}</div>{% if sensor_response %}- {% if sensor_response.has_video_stream %}+ {% sensor_response_event_snapshot_url sensor_response as event_snapshot_url %}+ {% if sensor_response.has_event_video_clip %}{% sensor_response_video_stream sensor_response as video_stream %}{% if video_stream and video_stream.source_url %}<div>- <div class="hi-video-recording">- <img class="img-fluid" data-video-recording src="{{ video_stream.source_url }}" alt="Sensor History">- {% include "console/panes/video_recording_replay_button.html" %}+ <div class="hi-video-clip">+ {% if video_stream.stream_type|stringformat:"s" == "mp4" %}+ <video class="img-fluid" data-video-clip controls autoplay muted playsinline+ src="{{ video_stream.source_url }}" aria-label="Sensor History"></video>+ {% else %}+ <img class="img-fluid" data-video-clip src="{{ video_stream.source_url }}" alt="Sensor History">+ {% endif %}+ {% include "console/panes/video_clip_replay_button.html" %}</div></div>- {% elif sensor_response.source_image_url %}+ {% elif event_snapshot_url %}<!-- Fallback to image when video stream is not available --><div>- <img class="img-fluid" src="{{ sensor_response.source_image_url }}" alt="Sensor History">+ <img class="img-fluid" src="{{ event_snapshot_url }}" alt="Sensor History"></div>{% endif %}- {% elif sensor_response.source_image_url %}+ {% elif event_snapshot_url %}<!-- Show image when no video stream capability --><div>- <img class="img-fluid" src="{{ sensor_response.source_image_url }}" alt="Sensor History">+ <img class="img-fluid" src="{{ event_snapshot_url }}" alt="Sensor History"></div>{% endif %}{% endif %}@@ -42,6 +49,27 @@ Sensor Response Details{% endfor %}</tbody></table>- </div>+ </div></div>{% endblock %}++{% block action_left %}+<a class="btn btn-primary"+ href="{% url 'entity_status' entity_id=sensor_history.sensor.entity_state.entity.id %}"+ data-async="modal">+ {% icon "info-circle" size="sm" css_class="hi-icon-left" %}STATUS+</a>+{% endblock %}++{% block action_center %}+<a class="btn btn-primary"+ href="{% url 'entity_history' entity_id=sensor_history.sensor.entity_state.entity.id %}"+ data-async="modal">+ {% icon "history" size="sm" css_class="hi-icon-left" %}HISTORY+</a>+{% endblock %}++{% block action_right %}+<a id="hi-modal-done" role="button" {% if autofocus %}autofocus="autofocus"{% endif %}+ class="btn btn-primary" href="#" data-dismiss="modal">DONE</a>+{% endblock %}diff --git a/src/hi/apps/sense/templates/sense/panes/sensor_response_status_row.html b/src/hi/apps/sense/templates/sense/panes/sensor_response_status_row.htmlindex 61e67189..fe2f417d 100644--- a/src/hi/apps/sense/templates/sense/panes/sensor_response_status_row.html+++ b/src/hi/apps/sense/templates/sense/panes/sensor_response_status_row.html@@ -7,7 +7,7 @@{{ sensor_response.sensor.short_name }}</div><div class="d-flex justify-content-around mt-2">- {% if sensor_response.has_video_stream %}+ {% if sensor_response.has_event_video_clip %}<div><a href="{{ sensor_response.video_browse_url }}"class="btn btn-sm btn-outline-primary"diff --git a/src/hi/apps/sense/tests/synthetic_data.py b/src/hi/apps/sense/tests/synthetic_data.pyindex 6567aa0b..72b42c94 100644--- a/src/hi/apps/sense/tests/synthetic_data.py+++ b/src/hi/apps/sense/tests/synthetic_data.py@@ -76,8 +76,8 @@ class SensorHistorySyntheticData:timestamp=timestamp,sensor=sensor,detail_attrs=detail_attrs,- source_image_url=f'/static/mock/video_{i}.mp4' if is_active else None,- has_video_stream=True,+ has_event_video_clip=True,+ has_event_video_snapshot=is_active,)mock_responses.append(sensor_response)@@ -110,9 +110,9 @@ class SensorHistorySyntheticData:'sensor': sensor,'value': value,'timestamp': timestamp,- 'has_video_stream': has_video,+ 'has_event_video_clip': has_video,+ 'has_event_video_snapshot': has_video,'details': f'{value.capitalize()} state detected',- 'source_image_url': f'/static/mock/snapshot_{timestamp.timestamp()}.jpg' if has_video else None,}@staticmethod@@ -146,7 +146,7 @@ class SensorHistorySyntheticData:'value': 'active' if minute_offset == 0 else 'idle','timestamp': timestamp,'duration_seconds': 120,- 'has_video_stream': True,+ 'has_event_video_clip': True,'details': f'Event at {timestamp.strftime("%H:%M")}',})item_counter += 36@@ -162,7 +162,7 @@ class SensorHistorySyntheticData:'value': 'active','timestamp': timestamp,'duration_seconds': 180,- 'has_video_stream': True,+ 'has_event_video_clip': True,'details': f'Yesterday event at {hour}:00',})item_counter += len(yesterday_hours)@@ -177,7 +177,7 @@ class SensorHistorySyntheticData:'value': 'idle','timestamp': timestamp,'duration_seconds': 90,- 'has_video_stream': True,+ 'has_event_video_clip': True,'details': f'Event {days_ago} days ago',})@@ -225,7 +225,7 @@ class SensorHistorySyntheticData:sensor=sensor,value='active' if hours_ago % 3 == 0 else 'idle',response_datetime=timestamp,- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id=str(hours_ago),details=f'{{"event_id": "{hours_ago}", "duration_seconds": "{60 + hours_ago * 15}"}}'@@ -249,7 +249,7 @@ class SensorHistorySyntheticData:sensor=sensor,value=f'event_{hours_ago}',response_datetime=timestamp,- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id=str(hours_ago),details=f'{{"hours_ago": "{hours_ago}"}}'@@ -278,7 +278,7 @@ class SensorHistorySyntheticData:sensor=sensor,value=f'record_{i}',response_datetime=timestamp,- has_video_stream=True,+ has_event_video_clip=True,correlation_role_str=str(CorrelationRole.END),correlation_id=str(i),details=f'{{"record_index": "{i}", "window_size": "{window}"}}'@@ -335,7 +335,7 @@ class SensorHistorySyntheticData:'duration_seconds': str(90 + i * 30),'details': f'Test event {i} - {timestamp.strftime("%Y-%m-%d %H:%M:%S %Z")}'},- has_video_stream=True+ has_event_video_clip=True)responses.append(response)@@ -346,7 +346,7 @@ class SensorHistorySyntheticData:sensor: Sensor,value: str = 'active',response_datetime: Optional[datetime] = None,- has_video_stream: bool = True,+ has_event_video_clip: bool = True,correlation_role: CorrelationRole = CorrelationRole.END,correlation_id: Optional[str] = None,details: Optional[str] = None@@ -365,7 +365,7 @@ class SensorHistorySyntheticData:sensor=sensor,value=value,response_datetime=response_datetime,- has_video_stream=has_video_stream,+ has_event_video_clip=has_event_video_clip,correlation_role_str=str(correlation_role),correlation_id=correlation_id,details=details@@ -378,7 +378,7 @@ class SensorHistorySyntheticData:base_time: Optional[datetime] = None,time_interval_minutes: int = 1,value_prefix: str = 'test_record',- has_video_stream: bool = True,+ has_event_video_clip: bool = True,correlation_role: CorrelationRole = CorrelationRole.END) -> List[SensorHistory]:"""@@ -394,7 +394,7 @@ class SensorHistorySyntheticData:sensor=sensor,value=f'{value_prefix}_{i}',response_datetime=timestamp,- has_video_stream=has_video_stream,+ has_event_video_clip=has_event_video_clip,correlation_role_str=str(correlation_role),correlation_id=str(i),details=f'{{"{value_prefix}": {i}}}'diff --git a/src/hi/apps/sense/tests/test_sensor_history_manager.py b/src/hi/apps/sense/tests/test_sensor_history_manager.pyindex 5b47993e..84429f48 100644--- a/src/hi/apps/sense/tests/test_sensor_history_manager.py+++ b/src/hi/apps/sense/tests/test_sensor_history_manager.py@@ -149,7 +149,7 @@ class AsyncSensorHistoryManagerTestCase(AsyncTaskFastTestCase):timestamp=timezone.make_aware(datetime(2023, 1, 1, 12, 0, 0)),sensor=self.sensor,detail_attrs={'key': 'value'},- source_image_url='http://example.com/image.jpg'+ has_event_video_snapshot=True)history = response.to_sensor_history()@@ -157,7 +157,7 @@ class AsyncSensorHistoryManagerTestCase(AsyncTaskFastTestCase):self.assertEqual(history.sensor, self.sensor)self.assertEqual(len(history.value), 255) # Should be truncatedself.assertEqual(history.response_datetime, response.timestamp)- self.assertEqual(history.source_image_url, response.source_image_url)+ self.assertEqual(history.has_event_video_snapshot, response.has_event_video_snapshot)self.assertIn('key', history.detail_attrs)diff --git a/src/hi/apps/sense/tests/test_sensor_history_urls.py b/src/hi/apps/sense/tests/test_sensor_history_urls.pyindex 8125147f..3cca312e 100644--- a/src/hi/apps/sense/tests/test_sensor_history_urls.py+++ b/src/hi/apps/sense/tests/test_sensor_history_urls.py@@ -18,7 +18,7 @@ class TestSensorHistoryVideoBrowseUrl( BaseTestCase ):def test_specific_event_url_when_data_point_has_stream(self):url = sensor_history_video_browse_url(entity_id = 1, sensor_id = 2, sensor_history_id = 3,- has_video_stream = True, provides_video_stream = True,+ has_event_video_clip = True, provides_event_video_clip = True,)self.assertIsNotNone( url )self.assertIn( '3', url )@@ -29,7 +29,7 @@ class TestSensorHistoryVideoBrowseUrl( BaseTestCase ):# in the path).url = sensor_history_video_browse_url(entity_id = 1, sensor_id = 2, sensor_history_id = 3,- has_video_stream = False, provides_video_stream = True,+ has_event_video_clip = False, provides_event_video_clip = True,)self.assertIsNotNone( url )self.assertNotIn( '3', url )@@ -37,27 +37,27 @@ class TestSensorHistoryVideoBrowseUrl( BaseTestCase ):def test_none_when_neither_stream_capability(self):url = sensor_history_video_browse_url(entity_id = 1, sensor_id = 2, sensor_history_id = 3,- has_video_stream = False, provides_video_stream = False,+ has_event_video_clip = False, provides_event_video_clip = False,)self.assertIsNone( url )def test_none_when_has_stream_but_no_history_id(self):- # has_video_stream=True without a sensor_history_id can't form- # a per-event URL; the fallback (provides_video_stream=False)+ # has_event_video_clip=True without a sensor_history_id can't form+ # a per-event URL; the fallback (provides_event_video_clip=False)# also doesn't apply, so the result is None.url = sensor_history_video_browse_url(entity_id = 1, sensor_id = 2, sensor_history_id = None,- has_video_stream = True, provides_video_stream = False,+ has_event_video_clip = True, provides_event_video_clip = False,)self.assertIsNone( url )def test_falls_back_to_per_sensor_when_has_stream_but_no_history_id(self):- # Edge: has_video_stream=True but sensor_history_id missing.+ # Edge: has_event_video_clip=True but sensor_history_id missing.# If the sensor itself provides streams, fall back to the# per-sensor timeline.url = sensor_history_video_browse_url(entity_id = 1, sensor_id = 2, sensor_history_id = None,- has_video_stream = True, provides_video_stream = True,+ has_event_video_clip = True, provides_event_video_clip = True,)self.assertIsNotNone( url )self.assertIn( '1', url )diff --git a/src/hi/apps/sense/tests/test_sensor_response.py b/src/hi/apps/sense/tests/test_sensor_response.pyindex 6d42b074..28e269c1 100644--- a/src/hi/apps/sense/tests/test_sensor_response.py+++ b/src/hi/apps/sense/tests/test_sensor_response.py@@ -53,7 +53,7 @@ class TestSensorResponse(BaseTestCase):self.assertEqual(response.timestamp, timestamp)self.assertIsNone(response.sensor)self.assertIsNone(response.detail_attrs)- self.assertIsNone(response.source_image_url)+ self.assertFalse(response.has_event_video_snapshot)def test_sensor_response_initialization_with_all_fields(self):"""Test SensorResponse initializes correctly with all optional fields."""@@ -66,7 +66,7 @@ class TestSensorResponse(BaseTestCase):timestamp=timestamp,sensor=self.sensor,detail_attrs=detail_attrs,- source_image_url='http://example.com/image.jpg'+ has_event_video_snapshot=True)self.assertEqual(response.integration_key, self.integration_key)@@ -74,7 +74,7 @@ class TestSensorResponse(BaseTestCase):self.assertEqual(response.timestamp, timestamp)self.assertEqual(response.sensor, self.sensor)self.assertEqual(response.detail_attrs, detail_attrs)- self.assertEqual(response.source_image_url, 'http://example.com/image.jpg')+ self.assertTrue(response.has_event_video_snapshot)def test_sensor_response_is_on_method_with_on_value(self):"""Test is_on method returns True for ON entity state value."""@@ -136,7 +136,7 @@ class TestSensorResponse(BaseTestCase):timestamp=timestamp,sensor=self.sensor,detail_attrs=detail_attrs,- source_image_url='http://example.com/image.jpg'+ has_event_video_snapshot=True)result_dict = response.to_dict()@@ -146,7 +146,6 @@ class TestSensorResponse(BaseTestCase):self.assertEqual(result_dict['timestamp'], timestamp.isoformat())self.assertEqual(result_dict['sensor_id'], self.sensor.id)self.assertEqual(result_dict['detail_attrs'], detail_attrs)- self.assertEqual(result_dict['source_image_url'], 'http://example.com/image.jpg')def test_sensor_response_to_dict_conversion_with_none_fields(self):"""Test to_dict method handles None fields correctly."""@@ -165,7 +164,6 @@ class TestSensorResponse(BaseTestCase):self.assertEqual(result_dict['timestamp'], timestamp.isoformat())self.assertIsNone(result_dict['sensor_id'])self.assertIsNone(result_dict['detail_attrs'])- self.assertIsNone(result_dict['source_image_url'])def test_sensor_response_str_representation_returns_json(self):"""Test __str__ method returns JSON representation."""@@ -197,7 +195,7 @@ class TestSensorResponse(BaseTestCase):timestamp=timestamp,sensor=self.sensor,detail_attrs=detail_attrs,- source_image_url='http://example.com/image.jpg'+ has_event_video_snapshot=True)history = response.to_sensor_history()@@ -207,7 +205,7 @@ class TestSensorResponse(BaseTestCase):self.assertEqual(history.value, 'test_value')self.assertEqual(history.response_datetime, timestamp)self.assertEqual(history.details, json.dumps(detail_attrs))- self.assertEqual(history.source_image_url, 'http://example.com/image.jpg')+ self.assertTrue(history.has_event_video_snapshot)def test_sensor_response_to_sensor_history_value_truncation(self):"""Test to_sensor_history truncates value to 255 characters."""@@ -251,7 +249,7 @@ class TestSensorResponse(BaseTestCase):value='test_value',response_datetime=timestamp,details=json.dumps(detail_attrs),- source_image_url='http://example.com/image.jpg'+ has_event_video_snapshot=True)response = SensorResponse.from_sensor_history(history)@@ -261,7 +259,7 @@ class TestSensorResponse(BaseTestCase):self.assertEqual(response.timestamp, timestamp)self.assertEqual(response.sensor, self.sensor)self.assertEqual(response.detail_attrs, detail_attrs)- self.assertEqual(response.source_image_url, 'http://example.com/image.jpg')+ self.assertTrue(response.has_event_video_snapshot)def test_sensor_response_from_string_deserialization(self):"""Test from_string class method correctly deserializes JSON string."""@@ -274,7 +272,7 @@ class TestSensorResponse(BaseTestCase):value='test_value',timestamp=timestamp,detail_attrs=detail_attrs,- source_image_url='http://example.com/image.jpg'+ has_event_video_snapshot=True)# Serialize to string@@ -287,7 +285,7 @@ class TestSensorResponse(BaseTestCase):self.assertEqual(deserialized_response.value, 'test_value')self.assertEqual(deserialized_response.timestamp, timestamp)self.assertEqual(deserialized_response.detail_attrs, detail_attrs)- self.assertEqual(deserialized_response.source_image_url, 'http://example.com/image.jpg')+ self.assertTrue(deserialized_response.has_event_video_snapshot)# Note: sensor is not included in serializationdef test_sensor_response_serialization_roundtrip_integrity(self):@@ -300,7 +298,7 @@ class TestSensorResponse(BaseTestCase):value='complex_value',timestamp=timestamp,detail_attrs=detail_attrs,- source_image_url='http://example.com/complex/path.jpg'+ has_event_video_snapshot=True)# Full roundtrip: to_dict -> JSON -> from_string@@ -313,14 +311,14 @@ class TestSensorResponse(BaseTestCase):value=parsed_dict['value'],timestamp=datetime.fromisoformat(parsed_dict['timestamp']),detail_attrs=parsed_dict['detail_attrs'],- source_image_url=parsed_dict['source_image_url']+ has_event_video_snapshot=parsed_dict['has_event_video_snapshot'])self.assertEqual(reconstructed_response.integration_key, original_response.integration_key)self.assertEqual(reconstructed_response.value, original_response.value)self.assertEqual(reconstructed_response.timestamp, original_response.timestamp)self.assertEqual(reconstructed_response.detail_attrs, original_response.detail_attrs)- self.assertEqual(reconstructed_response.source_image_url, original_response.source_image_url)+ self.assertEqual(reconstructed_response.has_event_video_snapshot, original_response.has_event_video_snapshot)def test_sensor_response_handles_special_characters_in_value(self):"""Test SensorResponse correctly handles special characters and unicode."""@@ -365,7 +363,7 @@ class TestSensorResponse(BaseTestCase):value=history.value,response_datetime=history.response_datetime,details=history.details,- source_image_url=history.source_image_url+ has_event_video_snapshot=history.has_event_video_snapshot,)recreated_response = SensorResponse.from_sensor_history(saved_history)diff --git a/src/hi/apps/sense/tests/test_sensor_response_manager.py b/src/hi/apps/sense/tests/test_sensor_response_manager.pyindex 3056cb4e..510e0e53 100644--- a/src/hi/apps/sense/tests/test_sensor_response_manager.py+++ b/src/hi/apps/sense/tests/test_sensor_response_manager.py@@ -210,7 +210,7 @@ class AsyncSensorResponseManagerTestCase(AsyncTaskFastTestCase):value='test_value',timestamp=timezone.make_aware(datetime(2023, 1, 1, 12, 0, 0)),detail_attrs={'key': 'value'},- source_image_url='http://example.com/image.jpg'+ has_event_video_snapshot=True)# Serialize to string@@ -224,7 +224,7 @@ class AsyncSensorResponseManagerTestCase(AsyncTaskFastTestCase):self.assertEqual(deserialized.value, original_response.value)self.assertEqual(deserialized.timestamp, original_response.timestamp)self.assertEqual(deserialized.detail_attrs, original_response.detail_attrs)- self.assertEqual(deserialized.source_image_url, original_response.source_image_url)+ self.assertEqual(deserialized.has_event_video_snapshot, original_response.has_event_video_snapshot)def test_get_latest_sensor_response_map_empty_list_short_circuits(self):"""Empty integration_keys returns empty dict without touching Redis."""diff --git a/src/hi/apps/sense/transient_models.py b/src/hi/apps/sense/transient_models.pyindex ca5c409d..d7465a73 100644--- a/src/hi/apps/sense/transient_models.py+++ b/src/hi/apps/sense/transient_models.py@@ -19,16 +19,23 @@ from .sensor_history_urls import (@dataclassclass SensorResponse:- integration_key : IntegrationKey- value : str- timestamp : datetime- sensor : Sensor = None- detail_attrs : Dict[ str, str ] = None- source_image_url : str = None- has_video_stream : bool = False- correlation_role : Optional[CorrelationRole] = None- correlation_id : Optional[str] = None- sensor_history_id : int = None # Core Django SensorHistory primary key+ """One sensor reading flowing through the live pipeline.++ ``correlation_id`` pairs the START / END readings of a single+ upstream event but is SENSOR-SCOPED — uniqueness is guaranteed+ only within a single Sensor's history. Never compare or look up+ ``correlation_id`` without a sensor scope; independent+ integrations can produce overlapping id strings."""+ integration_key : IntegrationKey+ value : str+ timestamp : datetime+ sensor : Sensor = None+ detail_attrs : Dict[ str, str ] = None+ has_event_video_clip : bool = False+ has_event_video_snapshot : bool = False+ correlation_role : Optional[CorrelationRole] = None+ correlation_id : Optional[str] = None+ sensor_history_id : int = None # Core Django SensorHistory primary keydef __str__(self):return json.dumps( self.to_dict() )@@ -63,8 +70,8 @@ class SensorResponse:entity_id = self.entity.id,sensor_id = self.sensor.id,sensor_history_id = self.sensor_history_id,- has_video_stream = self.has_video_stream,- provides_video_stream = self.sensor.provides_video_stream,+ has_event_video_clip = self.has_event_video_clip,+ provides_event_video_clip = self.sensor.provides_event_video_clip,)@property@@ -81,7 +88,7 @@ class SensorResponse:@propertydef click_url(self):- if self.has_video_stream:+ if self.has_event_video_clip:return self.video_browse_urlif self.sensor_history_id and self.has_details:return self.details_url@@ -94,8 +101,8 @@ class SensorResponse:'timestamp': self.timestamp.isoformat(),'sensor_id': self.sensor.id if self.sensor else None,'detail_attrs': self.detail_attrs,- 'source_image_url': self.source_image_url,- 'has_video_stream': self.has_video_stream,+ 'has_event_video_clip': self.has_event_video_clip,+ 'has_event_video_snapshot': self.has_event_video_snapshot,'correlation_role': str(self.correlation_role) if self.correlation_role else None,'correlation_id': self.correlation_id,'sensor_history_id': self.sensor_history_id,@@ -111,12 +118,12 @@ class SensorResponse:value = self.value[0:255],response_datetime = self.timestamp,details = details,- source_image_url = self.source_image_url,- has_video_stream = self.has_video_stream,+ has_event_video_clip = self.has_event_video_clip,+ has_event_video_snapshot = self.has_event_video_snapshot,correlation_role_str = str(self.correlation_role) if self.correlation_role else None,correlation_id = self.correlation_id,)-+@classmethoddef from_sensor_history( cls, sensor_history : SensorHistory ) -> 'SensorResponse':return SensorResponse(@@ -125,13 +132,13 @@ class SensorResponse:timestamp = sensor_history.response_datetime,sensor = sensor_history.sensor,detail_attrs = sensor_history.detail_attrs,- source_image_url = sensor_history.source_image_url,- has_video_stream = sensor_history.has_video_stream,+ has_event_video_clip = sensor_history.has_event_video_clip,+ has_event_video_snapshot = sensor_history.has_event_video_snapshot,correlation_role = sensor_history.correlation_role,correlation_id = sensor_history.correlation_id,sensor_history_id = sensor_history.id,)-+@classmethoddef from_string( cls, sensor_response_str : str ) -> 'SensorResponse':sensor_response_dict = json.loads( sensor_response_str )@@ -147,11 +154,8 @@ class SensorResponse:value = sensor_response_dict.get('value'),timestamp = datetime.fromisoformat( sensor_response_dict.get('timestamp') ),detail_attrs = sensor_response_dict.get('detail_attrs'),- source_image_url = (- sensor_response_dict.get('source_image_url')- or sensor_response_dict.get('image_url')- ),- has_video_stream = sensor_response_dict.get('has_video_stream', False),+ has_event_video_clip = sensor_response_dict.get('has_event_video_clip', False),+ has_event_video_snapshot = sensor_response_dict.get('has_event_video_snapshot', False),correlation_role = correlation_role,correlation_id = sensor_response_dict.get('correlation_id'),sensor_history_id = sensor_response_dict.get('sensor_history_id'),diff --git a/src/hi/apps/system/health_status_alarm_mapper.py b/src/hi/apps/system/health_status_alarm_mapper.pyindex beb774a4..32563781 100644--- a/src/hi/apps/system/health_status_alarm_mapper.py+++ b/src/hi/apps/system/health_status_alarm_mapper.py@@ -155,8 +155,7 @@ class HealthStatusAlarmMapper:timestamp = transition.timestamp,sensor = None,detail_attrs = detail_attrs,- source_image_url = None,- has_video_stream = False,+ has_event_video_clip = False,),]diff --git a/src/hi/apps/weather/weather_alert_alarm_mapper.py b/src/hi/apps/weather/weather_alert_alarm_mapper.pyindex b06da913..e61eafa9 100644--- a/src/hi/apps/weather/weather_alert_alarm_mapper.py+++ b/src/hi/apps/weather/weather_alert_alarm_mapper.py@@ -355,8 +355,7 @@ class WeatherAlertAlarmMapper:timestamp=weather_alert.effective or datetimeproxy.now(),sensor=None, # No sensor for weather alertsdetail_attrs=detail_attrs,- source_image_url=None, # Weather alerts don't have images- has_video_stream=False+ has_event_video_clip=False, # Weather alerts have no video)]def create_alarm(self, weather_alert: WeatherAlert) -> Optional[Alarm]:diff --git a/src/hi/integrations/integration_gateway.py b/src/hi/integrations/integration_gateway.pyindex af9b5ad2..d7e21853 100644--- a/src/hi/integrations/integration_gateway.py+++ b/src/hi/integrations/integration_gateway.py@@ -96,3 +96,16 @@ class IntegrationGateway:self,sensor_response: SensorResponse) -> Optional[VideoStream]:return None++ def get_sensor_response_event_snapshot_url(+ self,+ sensor_response: SensorResponse) -> Optional[str]:+ """Return the URL to the per-event captured snapshot frame for+ a SensorResponse, or ``None`` when the integration cannot+ produce one. Generated at render time from the event id so the+ URL always reflects current integration configuration (e.g.,+ an operator who moves the upstream host doesn't get stale+ URLs on historical rows). Pair with+ ``SensorResponse.has_event_video_snapshot`` — only call when+ the flag is True."""+ return Nonediff --git a/src/hi/integrations/integration_manager.py b/src/hi/integrations/integration_manager.pyindex cd383e75..6c352db7 100644--- a/src/hi/integrations/integration_manager.py+++ b/src/hi/integrations/integration_manager.py@@ -412,6 +412,14 @@ class IntegrationManager( Singleton ):update_fields = ['description'],track_history = False,)+ # Repair order_id on rows created before+ # _create_integration_attribute started seeding it.+ if existing_attr.order_id != attribute_type.value:+ existing_attr.order_id = attribute_type.value+ existing_attr.save(+ update_fields = ['order_id'],+ track_history = False,+ )continueif new_attribute_types:@@ -431,6 +439,11 @@ class IntegrationManager( Singleton ):integration_id = integration.integration_id,integration_name = str(attribute_type),)+ # LabeledEnum auto-numbers members 1, 2, 3, ... in definition+ # order (see hi.apps.common.enums.LabeledEnum.__new__). Using+ # ``attribute_type.value`` as the row's ``order_id`` makes the+ # config-page render order match the operator-facing order+ # the integration author defined.attribute = IntegrationAttribute(integration = integration,name = attribute_type.label,@@ -442,6 +455,7 @@ class IntegrationManager( Singleton ):attribute_type_str = AttributeType.PREDEFINED,is_editable = attribute_type.is_editable,is_required = attribute_type.is_required,+ order_id = attribute_type.value,)attribute.save( track_history = False ) # Do not want this initial value in historyreturndiff --git a/src/hi/integrations/sync_check.py b/src/hi/integrations/sync_check.pyindex 6ea90173..b3ac3064 100644--- a/src/hi/integrations/sync_check.py+++ b/src/hi/integrations/sync_check.py@@ -249,8 +249,7 @@ class IntegrationSyncCheck:'%Y-%m-%d %H:%M:%S',),},- source_image_url = None,- has_video_stream = False,+ has_event_video_clip = False,)alarm = Alarm(alarm_source = AlarmSource.INTEGRATION,diff --git a/src/hi/services/frigate/__init__.py b/src/hi/services/frigate/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/services/frigate/apps.py b/src/hi/services/frigate/apps.pynew file mode 100644index 00000000..8105e771--- /dev/null+++ b/src/hi/services/frigate/apps.py@@ -0,0 +1,6 @@+from django.apps import AppConfig+++class FrigateConfig(AppConfig):+ default_auto_field = "django.db.models.BigAutoField"+ name = "hi.services.frigate"diff --git a/src/hi/services/frigate/constants.py b/src/hi/services/frigate/constants.pynew file mode 100644index 00000000..bc3dd1b4--- /dev/null+++ b/src/hi/services/frigate/constants.py@@ -0,0 +1,58 @@+class FrigateApi:+ """Centralized Frigate wire-format strings (endpoint paths,+ response field names, object-class constants). All wire-side+ string literals for the Frigate integration MUST be declared+ here — see ``docs/dev/integrations/integration-guidelines.md``.++ Filled out incrementally as each capability is implemented.+ """++ # --- Endpoints (paths under the configured BASE_URL) ---+ EVENTS_PATH = '/api/events'+ STATS_PATH = '/api/stats'+ CONFIG_PATH = '/api/config'++ CAMERA_SNAPSHOT_PATH_TEMPLATE = '/api/{camera_name}/latest.jpg'+ EVENT_SNAPSHOT_PATH_TEMPLATE = '/api/events/{event_id}/snapshot.jpg'+ EVENT_CLIP_PATH_TEMPLATE = '/api/events/{event_id}/clip.mp4'++ # --- Frigate object-class wire values (subset; extended as needed) ---+ OBJECT_CLASS_PERSON = 'person'+ OBJECT_CLASS_CAR = 'car'+ OBJECT_CLASS_DOG = 'dog'+ OBJECT_CLASS_CAT = 'cat'+ OBJECT_CLASS_PACKAGE = 'package'+++class FrigateDetailKeys:+ """``SensorResponse.detail_attrs`` keys used by the Frigate+ integration.++ WARNING: These keys are persisted in the database and surfaced in+ the event-detail UI. Changing them breaks historical data and+ requires a migration. Add new keys; do not rename.+ """+ EVENT_ID = 'Event Id'+ START_TIME = 'Start Time'+ OBJECT_CLASS = 'Object Class'+ SCORE = 'Score'+ SUB_LABEL = 'Sub Label'+ ZONES = 'Zones'+ DURATION_SECS = 'Duration (secs)'+++class FrigateTimeouts:+ """Centralized timing knobs. Polling cadence inherited from the+ ZM defaults as a starting point — tune per real-install behavior."""++ POLLING_INTERVAL_SECS = 4+ API_TIMEOUT_SECS = 10.0++ HEALTH_CHECK_INTERVAL_SECS = 30+ MONITOR_HEARTBEAT_TIMEOUT_SECS = 20++ # Upper bound on how long an event may stay open in HI's tracking+ # set before we force-close it. Frigate normally closes events+ # within minutes; an event still open after this threshold is+ # treated as orphaned (Frigate restart, dropped detection, etc.).+ MAX_OPEN_EVENT_AGE_SECS = 60 * 60diff --git a/src/hi/services/frigate/enums.py b/src/hi/services/frigate/enums.pynew file mode 100644index 00000000..0151cc3b--- /dev/null+++ b/src/hi/services/frigate/enums.py@@ -0,0 +1,42 @@+from hi.apps.attribute.enums import AttributeValueType++from hi.integrations.enums import IntegrationAttributeType+++class FrigateAttributeType( IntegrationAttributeType ):+ """Operator-configurable settings for the Frigate integration.++ v1 assumes Frigate is reachable directly (or behind an operator-managed+ reverse proxy that handles auth). The optional ``AUTH_HEADER`` slot is a+ stretch for installs that gate Frigate behind basic-auth / a static+ bearer token; JWT login is out of v1 scope and will be revisited once+ we have real-install validation.+ """++ BASE_URL = (+ 'Base URL',+ 'e.g., http://frigate.local:5000',+ AttributeValueType.TEXT,+ None,+ True,+ True,+ )+ AUTH_HEADER = (+ 'Authorization Header',+ 'Optional. Verbatim Authorization header value (e.g., '+ '"Bearer xyz" or "Basic <base64>"). Leave blank for unauthenticated '+ 'access or when auth is handled by a reverse proxy.',+ AttributeValueType.SECRET,+ None,+ False,+ False,+ )+ ADD_ALARM_EVENTS = (+ 'Add Alarm Events',+ '',+ AttributeValueType.BOOLEAN,+ None,+ True,+ False,+ True,+ )diff --git a/src/hi/services/frigate/frigate_client.py b/src/hi/services/frigate/frigate_client.pynew file mode 100644index 00000000..39f43a9a--- /dev/null+++ b/src/hi/services/frigate/frigate_client.py@@ -0,0 +1,179 @@+import json+import logging+from typing import Any, Dict, List, Optional++from django.http import Http404+from requests import get++from .constants import FrigateApi, FrigateTimeouts++logger = logging.getLogger(__name__)+++class FrigateClient:+ """Encapsulated HTTP client for Frigate's REST API.++ Modeled on ``HassClient``: per-instance base URL and headers,+ explicit per-method endpoint wrappers, status-code / content-type+ checks at the boundary. Frigate's v1 auth model is "behind a+ reverse proxy" with an optional verbatim ``Authorization`` header+ the operator pastes in (no JWT login flow in v1).++ Methods raise ``ValueError`` with a descriptive message at the+ boundary so the monitor / connection-test paths can record a+ meaningful error rather than letting opaque JSON / decode errors+ bubble up to operators.+ """++ BASE_URL = 'base_url'+ AUTH_HEADER = 'auth_header'++ DEFAULT_TIMEOUT_SECS = FrigateTimeouts.API_TIMEOUT_SECS++ def __init__( self,+ api_options : Dict[ str, str ],+ timeout_secs : Optional[ float ] = None ):+ base_url = api_options.get( self.BASE_URL )+ if not base_url:+ raise ValueError( 'FrigateClient requires a base_url.' )+ self._base_url = base_url.rstrip( '/' )++ self._headers : Dict[ str, str ] = {+ 'Accept': 'application/json',+ }+ auth_value = api_options.get( self.AUTH_HEADER )+ if auth_value:+ self._headers[ 'Authorization' ] = auth_value++ self._timeout_secs = (+ timeout_secs if timeout_secs is not None else self.DEFAULT_TIMEOUT_SECS+ )+ return++ @property+ def base_url(self) -> str:+ return self._base_url++ # ---- Reachability probe (used by test_connection) ------------------++ def ping(self) -> None:+ """Lightweight reachability probe against ``/api/config``.++ Confirms the base URL points at a Frigate instance (or whatever+ is fronting it) and that the response is JSON-shaped — a 200+ with HTML usually means the URL is fronting the Frigate web UI+ rather than the API, and we want ``test_connection`` to fail+ at save time instead of letting the polling path JSONDecode+ later. Returns ``None`` on success; raises ``ValueError`` with+ a diagnostic message on failure. Network errors propagate."""+ self._get_config()+ return++ # ---- Inbound (query) endpoints -------------------------------------++ def get_cameras( self ) -> List[ Dict ]:+ """Camera list, derived from the ``cameras`` map in+ ``/api/config``. Frigate exposes its camera set through the+ live config rather than a dedicated endpoint. Each returned+ dict carries ``{'name': <camera_name>, 'config': <per-camera+ config dict>}``."""+ config_data = self._get_config()+ cameras_map = config_data.get( 'cameras' )+ if not isinstance( cameras_map, dict ):+ raise ValueError(+ f'Frigate /api/config response missing or malformed "cameras"'+ f' field: got {type(cameras_map).__name__}'+ )+ return [+ { 'name': camera_name, 'config': camera_config }+ for camera_name, camera_config in cameras_map.items()+ ]++ def get_events( self,+ after : Optional[ float ] = None,+ limit : Optional[ int ] = None ) -> List[ Dict ]:+ """``GET /api/events`` — list events.++ ``after`` (epoch seconds) is the polling cursor: only events+ whose start_time is at-or-after the cutoff are returned. The+ simulator (and real Frigate) sort newest-first by start_time.+ ``limit`` caps the returned count when set."""+ params : Dict[ str, Any ] = {}+ if after is not None:+ params[ 'after' ] = after+ if limit is not None:+ params[ 'limit' ] = limit+ data = self._get_json(+ path = FrigateApi.EVENTS_PATH,+ params = params or None,+ )+ if not isinstance( data, list ):+ raise ValueError(+ f'Frigate /api/events response was not a list:'+ f' got {type(data).__name__}'+ )+ return data++ def get_event( self, event_id : str ) -> Dict:+ """``GET /api/events/<id>`` — single event detail."""+ path = f'{FrigateApi.EVENTS_PATH}/{event_id}'+ data = self._get_json( path = path )+ if not isinstance( data, dict ):+ raise ValueError(+ f'Frigate /api/events/{event_id} response was not a JSON object:'+ f' got {type(data).__name__}'+ )+ return data++ # ---- Internal: shared request + validation -------------------------++ def _get_config(self) -> Dict:+ """Fetch ``/api/config`` and validate the response is a dict.+ Shared by ``ping()`` and ``get_cameras()``."""+ data = self._get_json( path = FrigateApi.CONFIG_PATH )+ if not isinstance( data, dict ):+ raise ValueError(+ f'Frigate /api/config response was not a JSON object:'+ f' got {type(data).__name__}'+ )+ return data++ def _get_json(+ self,+ path : str,+ params : Optional[ Dict[ str, Any ] ] = None,+ ) -> Any:+ """GET ``path`` against the configured base URL and return+ parsed JSON. Status code, content-type, and JSON-parse errors+ all raise ``ValueError`` with diagnostic messages that include+ the path so monitor / test_connection paths can record what+ failed."""+ url = f'{self._base_url}{path}'+ response = get(+ url,+ headers = self._headers,+ timeout = self._timeout_secs,+ params = params,+ )+ if response.status_code == 404:+ raise Http404( f'Frigate {path}: {response.text}' )+ if response.status_code not in (200, 201):+ raise ValueError(+ f'Frigate {path} request failed:'+ f' {response.status_code} {response.text}'+ )+ content_type = ( response.headers or {} ).get( 'content-type', '' )+ if 'json' not in content_type.lower():+ raise ValueError(+ f'Frigate API URL may be incorrect. Expected JSON response'+ f' from {path} but received'+ f' {content_type or "unknown content type"}.'+ f' Ensure the URL points at the Frigate API root.'+ )+ try:+ return json.loads( response.text )+ except json.JSONDecodeError as e:+ raise ValueError(+ f'Frigate {path} response was not valid JSON: {e}'+ ) from e+diff --git a/src/hi/services/frigate/frigate_client_factory.py b/src/hi/services/frigate/frigate_client_factory.pynew file mode 100644index 00000000..b4b142a1--- /dev/null+++ b/src/hi/services/frigate/frigate_client_factory.py@@ -0,0 +1,50 @@+import logging+from typing import List, Optional++from hi.integrations.models import IntegrationAttribute+from hi.integrations.transient_models import IntegrationKey++from .enums import FrigateAttributeType+from .frigate_client import FrigateClient+from .frigate_metadata import FrigateMetaData++logger = logging.getLogger(__name__)+++class FrigateClientFactory:+ """Builds a ``FrigateClient`` from the integration's persisted+ attribute records. Mirrors ``ZmClientFactory`` in role: read+ attribute values out of the IntegrationAttribute list, construct+ the client. Connection validation lives on the client itself+ (``ping``); this factory is purely configuration translation.+ """++ @classmethod+ def create_client(+ cls,+ integration_attributes : List[ IntegrationAttribute ],+ timeout_secs : Optional[ float ] = None,+ ) -> FrigateClient:+ api_options = cls._attributes_to_options( integration_attributes )+ return FrigateClient(+ api_options = api_options,+ timeout_secs = timeout_secs,+ )++ @staticmethod+ def _attributes_to_options( integration_attributes : List[ IntegrationAttribute ] ) -> dict:+ key_to_attr = {+ attr.integration_key: attr for attr in integration_attributes+ }++ def _lookup( attr_type : FrigateAttributeType ) -> Optional[ str ]:+ key = IntegrationKey(+ integration_id = FrigateMetaData.integration_id,+ integration_name = str( attr_type ),+ )+ attr = key_to_attr.get( key )+ return attr.value if attr else None+ return {+ FrigateClient.BASE_URL: _lookup( FrigateAttributeType.BASE_URL ),+ FrigateClient.AUTH_HEADER: _lookup( FrigateAttributeType.AUTH_HEADER ),+ }diff --git a/src/hi/services/frigate/frigate_controller.py b/src/hi/services/frigate/frigate_controller.pynew file mode 100644index 00000000..7aa4c763--- /dev/null+++ b/src/hi/services/frigate/frigate_controller.py@@ -0,0 +1,40 @@+import logging++from hi.integrations.integration_controller import IntegrationController+from hi.integrations.transient_models import (+ IntegrationControlResult,+ IntegrationDetails,+)++from .frigate_mixins import FrigateMixin++logger = logging.getLogger(__name__)+++class FrigateController( IntegrationController, FrigateMixin ):+ """Routes HI control commands to Frigate.++ v1 has no exposed control surface. Frigate's only operator-toggle+ reachable over HTTP — ``PUT /api/config/set`` for+ ``cameras.<name>.detect.enabled`` — is a config edit rather than+ transient state, with persistence semantics that don't map+ cleanly to HI's control model. A future revision can expose the+ transient detect toggle through Frigate's MQTT+ ``frigate/<cam>/detect/set`` topic instead.+ """++ def do_control(+ self,+ integration_details : IntegrationDetails,+ hi_control_value : str,+ ) -> IntegrationControlResult:+ integration_key = integration_details.key+ message = (+ f'No Frigate control mapping for integration_name '+ f'{integration_key.integration_name!r}.'+ )+ logger.warning( message )+ return IntegrationControlResult(+ new_value = None,+ error_list = [ message ],+ )diff --git a/src/hi/services/frigate/frigate_converter.py b/src/hi/services/frigate/frigate_converter.pynew file mode 100644index 00000000..fc402712--- /dev/null+++ b/src/hi/services/frigate/frigate_converter.py@@ -0,0 +1,73 @@+import logging++from hi.apps.entity.enums import EntityStateValue++logger = logging.getLogger(__name__)+++class FrigateConverter:+ """Wire-format ↔ HI model translation for Frigate.++ Owns the boundary between Frigate's raw event payloads and HI's+ typed model. Today's responsibility: map Frigate's raw+ object-class label (model-dependent — default YOLO has ~80+ classes; custom models can have arbitrary classes) onto the+ canonical ``EntityStateType.OBJECT_PRESENCE`` value range.+ """++ # Raw-label → canonical-bucket map. Entries are lowercase-canonical+ # Frigate class names paired with the matching EntityStateValue+ # member. Anything not listed falls through to ``OBJECT_OTHER``;+ # this is deliberate so a custom-model class that nobody's bucketed+ # yet still surfaces in HI as "something is here" rather than+ # disappearing into ``none``.+ _RAW_TO_CANONICAL = {+ # People+ 'person' : EntityStateValue.OBJECT_PERSON,++ # Vehicles. ``OBJECT_CAR`` is the canonical bucket name but+ # semantically it's "vehicle" — trucks, buses, etc. all map+ # here. Rename of the bucket is a UX decision worth revisiting+ # if/when other vehicle-aware integrations land.+ 'car' : EntityStateValue.OBJECT_CAR,+ 'truck' : EntityStateValue.OBJECT_CAR,+ 'bus' : EntityStateValue.OBJECT_CAR,+ 'motorcycle' : EntityStateValue.OBJECT_CAR,+ 'bicycle' : EntityStateValue.OBJECT_CAR,++ # Animals — covers the COCO classes most likely to fire in+ # a residential install plus the common custom additions.+ 'dog' : EntityStateValue.OBJECT_ANIMAL,+ 'cat' : EntityStateValue.OBJECT_ANIMAL,+ 'bird' : EntityStateValue.OBJECT_ANIMAL,+ 'horse' : EntityStateValue.OBJECT_ANIMAL,+ 'sheep' : EntityStateValue.OBJECT_ANIMAL,+ 'cow' : EntityStateValue.OBJECT_ANIMAL,+ 'bear' : EntityStateValue.OBJECT_ANIMAL,+ 'deer' : EntityStateValue.OBJECT_ANIMAL,+ 'raccoon' : EntityStateValue.OBJECT_ANIMAL,+ 'fox' : EntityStateValue.OBJECT_ANIMAL,+ 'squirrel' : EntityStateValue.OBJECT_ANIMAL,+ 'rabbit' : EntityStateValue.OBJECT_ANIMAL,++ # Packages — Frigate's dedicated class for porch deliveries.+ 'package' : EntityStateValue.OBJECT_PACKAGE,+ }++ OBJECT_NONE_VALUE = str( EntityStateValue.OBJECT_NONE )+ OBJECT_OTHER_VALUE = str( EntityStateValue.OBJECT_OTHER )++ @classmethod+ def to_canonical_object_class( cls, raw_class : str ) -> str:+ """Map a Frigate raw object class onto a canonical+ ``OBJECT_PRESENCE`` value (the wire-format string of the+ matching ``EntityStateValue`` member). Unknown labels fall+ through to ``OBJECT_OTHER`` so detections of custom-model+ classes still register in HI."""+ if not raw_class:+ return cls.OBJECT_OTHER_VALUE+ canonical = cls._RAW_TO_CANONICAL.get( raw_class.lower() )+ if canonical is None:+ return cls.OBJECT_OTHER_VALUE+ return str( canonical )+diff --git a/src/hi/services/frigate/frigate_manage_view_pane.py b/src/hi/services/frigate/frigate_manage_view_pane.pynew file mode 100644index 00000000..4d037556--- /dev/null+++ b/src/hi/services/frigate/frigate_manage_view_pane.py@@ -0,0 +1,17 @@+from typing import Dict++from hi.integrations.integration_data import IntegrationData+from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane+++class FrigateManageViewPane( IntegrationManageViewPane ):+ """Management-pane backing for the Settings → Integrations →+ Frigate page. Renders the management template; v1 doesn't add+ any custom context beyond what the framework provides.+ """++ def get_template_name( self ) -> str:+ return 'frigate/panes/frigate_manage.html'++ def get_template_context( self, integration_data : IntegrationData ) -> Dict[ str, object ]:+ return {}diff --git a/src/hi/services/frigate/frigate_manager.py b/src/hi/services/frigate/frigate_manager.pynew file mode 100644index 00000000..cdbc2999--- /dev/null+++ b/src/hi/services/frigate/frigate_manager.py@@ -0,0 +1,344 @@+import logging+import time+from typing import Dict, List, Optional++from asgiref.sync import sync_to_async++from hi.apps.common.utils import str_to_bool+from hi.apps.system.enums import ApiHealthStatusType++from hi.apps.common.singleton_manager import SingletonManager+from hi.apps.system.aggregate_health_provider import AggregateHealthProvider+from hi.apps.system.api_health_status_provider import ApiHealthStatusProvider+from hi.apps.system.enums import HealthStatusType+from hi.apps.system.provider_info import ProviderInfo++from hi.integrations.models import IntegrationAttribute+from hi.integrations.transient_models import (+ ConnectionTestResult,+ IntegrationKey,+ IntegrationValidationResult,+)++from hi.integrations.models import Integration++from .constants import FrigateApi+from .enums import FrigateAttributeType+from .frigate_client import FrigateClient+from .frigate_client_factory import FrigateClientFactory+from .frigate_metadata import FrigateMetaData++logger = logging.getLogger(__name__)+++class FrigateManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusProvider ):+ """Singleton coordinator for the Frigate integration.++ Owns the lazily-constructed ``FrigateClient`` (built from persisted+ IntegrationAttribute records), brokers configuration validation and+ connection probes, and dispatches settings-changed notifications to+ registered listeners. Mirrors ``ZoneMinderManager`` in role.++ Scaffolding stub: ``_reload_implementation`` is a no-op,+ ``test_connection`` returns a "not yet implemented" failure, and+ ``validate_configuration`` does the minimum schema check (BASE_URL+ must be present). Filled out incrementally during feature work.+ """++ FRIGATE_ENTITY_NAME = 'Frigate'+ FRIGATE_SYSTEM_INTEGRATION_NAME = 'system'+ FRIGATE_CAMERA_INTEGRATION_NAME_PREFIX = 'camera'+ OBJECT_PRESENCE_SENSOR_PREFIX = 'camera.object'+ OBJECT_PRESENCE_EVENT_PREFIX = 'camera.object.event'++ def __init_singleton__(self):+ super().__init_singleton__()+ self._change_listeners = set()+ self._frigate_client : Optional[ FrigateClient ] = None+ self._attribute_map : Dict[ FrigateAttributeType, IntegrationAttribute ] = {}+ self.add_api_health_status_provider( self )+ return++ @classmethod+ def get_provider_info(cls) -> ProviderInfo:+ return ProviderInfo(+ provider_id = 'hi.services.frigate.manager',+ provider_name = 'Frigate Integration',+ description = '',+ )++ @classmethod+ def get_api_provider_info(cls) -> ProviderInfo:+ return ProviderInfo(+ provider_id = 'hi.services.frigate.api',+ provider_name = 'Frigate API',+ description = 'Frigate NVR HTTP API',+ )++ def _reload_implementation(self):+ """Pull current attribute values and (re)build the API client.++ Called under ``SingletonManager``'s data lock. The client is+ nulled on every reload and only re-created when the integration+ DB row is present and enabled. Sync / monitor consumers should+ gate on ``frigate_client is not None`` before calling out."""+ self._frigate_client = None+ self._attribute_map = {}+ try:+ integration = Integration.objects.get(+ integration_id = FrigateMetaData.integration_id,+ )+ except Integration.DoesNotExist:+ self.update_api_health_status( ApiHealthStatusType.DISABLED )+ return+ if not integration.is_enabled:+ self.update_api_health_status( ApiHealthStatusType.DISABLED )+ return+ integration_attributes = list( integration.attributes.all() )+ self._attribute_map = self._build_attribute_map(+ integration_attributes = integration_attributes,+ )+ try:+ self._frigate_client = FrigateClientFactory.create_client(+ integration_attributes = integration_attributes,+ )+ except Exception:+ logger.exception( 'Failed to build Frigate client.' )+ self.update_api_health_status( ApiHealthStatusType.UNAVAILABLE )+ return+ self.update_api_health_status( ApiHealthStatusType.HEALTHY )+ return++ @staticmethod+ def _build_attribute_map(+ integration_attributes : List[ IntegrationAttribute ],+ ) -> Dict[ FrigateAttributeType, IntegrationAttribute ]:+ attribute_map : Dict[ FrigateAttributeType, IntegrationAttribute ] = {}+ for attr_type in FrigateAttributeType:+ target_key = IntegrationKey(+ integration_id = FrigateMetaData.integration_id,+ integration_name = str( attr_type ),+ )+ for attr in integration_attributes:+ if attr.integration_key == target_key:+ attribute_map[ attr_type ] = attr+ break+ continue+ continue+ return attribute_map++ @property+ def should_add_alarm_events( self ) -> bool:+ self.ensure_initialized()+ attribute = self._attribute_map.get( FrigateAttributeType.ADD_ALARM_EVENTS )+ if attribute:+ return str_to_bool( attribute.value )+ return False++ @property+ def frigate_client(self) -> Optional[ FrigateClient ]:+ """Lazily-constructed ``FrigateClient`` built against current+ integration attributes. Returns ``None`` when the integration+ is disabled or the configuration is unusable."""+ self.ensure_initialized()+ return self._frigate_client++ # ---- Integration-key helpers ------------------------------------++ @classmethod+ def _to_integration_key( cls, prefix : str, camera_name : str ) -> IntegrationKey:+ """Build a per-camera ``IntegrationKey`` with a stable scheme:+ ``<prefix>.<camera_name>`` for the integration_name slot. The+ prefixes (``camera`` / ``camera.motion`` / ``camera.object``)+ live as constants on this manager."""+ return IntegrationKey(+ integration_id = FrigateMetaData.integration_id,+ integration_name = f'{prefix}.{camera_name}',+ )++ # ---- Client-facing helpers (used by FrigateMonitor) -------------++ def get_cameras( self ) -> List[ Dict ]:+ """Camera list from ``/api/config``. Raises when the client+ isn't built yet (integration disabled / unconfigured) — the+ monitor's outer try/except records this as a health warning."""+ client = self.frigate_client+ if client is None:+ raise RuntimeError( 'Frigate client not available.' )+ with self.api_call_context( 'frigate_cameras' ):+ return client.get_cameras()++ async def get_cameras_async( self ) -> List[ Dict ]:+ return await sync_to_async(+ self.get_cameras,+ thread_sensitive = True,+ )()++ def get_events( self,+ after : Optional[ float ] = None,+ limit : Optional[ int ] = None ) -> List[ Dict ]:+ """Events from ``/api/events``. ``after`` is the polling+ cursor in epoch seconds; ``limit`` caps the returned count+ when set."""+ client = self.frigate_client+ if client is None:+ raise RuntimeError( 'Frigate client not available.' )+ with self.api_call_context( 'frigate_events' ):+ return client.get_events( after = after, limit = limit )++ async def get_events_async( self,+ after : Optional[ float ] = None,+ limit : Optional[ int ] = None ) -> List[ Dict ]:+ return await sync_to_async(+ self.get_events,+ thread_sensitive = True,+ )( after = after, limit = limit )++ def get_event( self, event_id : str ) -> Dict:+ """Single event detail by id. Raises ``Http404`` when the+ event no longer exists in Frigate (cleared from history)."""+ client = self.frigate_client+ if client is None:+ raise RuntimeError( 'Frigate client not available.' )+ with self.api_call_context( 'frigate_event_detail' ):+ return client.get_event( event_id = event_id )++ async def get_event_async( self, event_id : str ) -> Dict:+ return await sync_to_async(+ self.get_event,+ thread_sensitive = True,+ )( event_id = event_id )++ # ---- Media URL helpers ------------------------------------------++ def get_camera_snapshot_url( self, camera_name : str ) -> Optional[ str ]:+ """Live-frame JPEG URL for a camera. Returns ``None`` when the+ client isn't available."""+ client = self.frigate_client+ if client is None:+ return None+ path = FrigateApi.CAMERA_SNAPSHOT_PATH_TEMPLATE.format(+ camera_name = camera_name,+ )+ return f'{client.base_url}{path}?_t={int(time.time())}'++ def get_event_snapshot_url( self, event_id : str ) -> Optional[ str ]:+ """Event-frame JPEG URL. Returns ``None`` when the client+ isn't available."""+ client = self.frigate_client+ if client is None:+ return None+ path = FrigateApi.EVENT_SNAPSHOT_PATH_TEMPLATE.format(+ event_id = event_id,+ )+ return f'{client.base_url}{path}?_t={int(time.time())}'++ def get_event_clip_url( self, event_id : str ) -> Optional[ str ]:+ """Event-clip MP4 URL. Returns ``None`` when the client+ isn't available."""+ client = self.frigate_client+ if client is None:+ return None+ path = FrigateApi.EVENT_CLIP_PATH_TEMPLATE.format(+ event_id = event_id,+ )+ return f'{client.base_url}{path}?_t={int(time.time())}'++ @classmethod+ def _frigate_integration_key( cls ) -> IntegrationKey:+ """Integration key for the (future) singleton Frigate service+ entity. Held in reserve for v2 when ``/api/stats`` lands;+ unused in v1, which is cameras-only."""+ return IntegrationKey(+ integration_id = FrigateMetaData.integration_id,+ integration_name = cls.FRIGATE_SYSTEM_INTEGRATION_NAME,+ )++ # ---- Settings-change plumbing -----------------------------------++ def register_change_listener( self, callback ):+ if callback not in self._change_listeners:+ logger.debug( f'Adding Frigate setting change listener from {callback.__module__}' )+ self._change_listeners.add( callback )+ return++ def notify_settings_changed(self):+ self.reload()+ for callback in self._change_listeners:+ try:+ callback()+ except Exception:+ logger.exception( 'Problem calling Frigate change-listener callback.' )+ continue+ return++ # ---- Gateway-facing API -----------------------------------------++ def validate_configuration(+ self,+ integration_attributes : List[ IntegrationAttribute ],+ ) -> IntegrationValidationResult:+ """Schema-only validation. No network calls."""+ base_url = self._attr_value(+ integration_attributes = integration_attributes,+ attr_type = FrigateAttributeType.BASE_URL,+ )+ if not base_url:+ return IntegrationValidationResult.error(+ status = HealthStatusType.WARNING,+ error_message = 'Base URL is required.',+ )+ return IntegrationValidationResult.success()++ def test_connection(+ self,+ integration_attributes : List[ IntegrationAttribute ],+ timeout_secs : Optional[ float ],+ ) -> ConnectionTestResult:+ """Live probe against the configured base URL.++ Builds a temporary ``FrigateClient`` from the proposed+ attributes and calls ``ping()``. Bounded by ``timeout_secs``+ so the Configure form can fail interactively rather than+ wait on a stalled host."""+ try:+ client = FrigateClientFactory.create_client(+ integration_attributes = integration_attributes,+ timeout_secs = timeout_secs,+ )+ except ValueError as e:+ return ConnectionTestResult.failure( str( e ) )+ except Exception as e:+ logger.exception( f'Error building Frigate client for test_connection: {e}' )+ return ConnectionTestResult.failure( f'Configuration error: {e}' )++ try:+ client.ping()+ except ValueError as e:+ return ConnectionTestResult.failure( str( e ) )+ except Exception as e:+ return ConnectionTestResult.failure( f'Connection error: {e}' )+ return ConnectionTestResult.success()++ @property+ def integration_id(self) -> str:+ return FrigateMetaData.integration_id++ @staticmethod+ def _attr_value(+ integration_attributes : List[ IntegrationAttribute ],+ attr_type : FrigateAttributeType,+ ) -> Optional[ str ]:+ """Look up an attribute value by type. ``IntegrationAttribute``+ carries an ``integration_key`` whose ``integration_name`` is+ ``str(attr_type)`` (the lowercased slug LabeledEnum yields);+ matching directly on that field is the framework's convention."""+ target_key = IntegrationKey(+ integration_id = FrigateMetaData.integration_id,+ integration_name = str( attr_type ),+ )+ for attr in integration_attributes:+ if attr.integration_key == target_key:+ return attr.value+ continue+ return Nonediff --git a/src/hi/services/frigate/frigate_metadata.py b/src/hi/services/frigate/frigate_metadata.pynew file mode 100644index 00000000..1b92423e--- /dev/null+++ b/src/hi/services/frigate/frigate_metadata.py@@ -0,0 +1,12 @@+from hi.integrations.transient_models import IntegrationMetaData++from .enums import FrigateAttributeType+++FrigateMetaData = IntegrationMetaData(+ integration_id = 'frigate',+ label = 'Frigate',+ attribute_type = FrigateAttributeType,+ allow_entity_deletion = False,+ logo_static_path = 'img/integrations/frigate.png',+)diff --git a/src/hi/services/frigate/frigate_mixins.py b/src/hi/services/frigate/frigate_mixins.pynew file mode 100644index 00000000..8222d1be--- /dev/null+++ b/src/hi/services/frigate/frigate_mixins.py@@ -0,0 +1,35 @@+import asyncio+import logging++from .frigate_manager import FrigateManager++logger = logging.getLogger(__name__)+++class FrigateMixin:+ """Manager-accessor mixin for views / sync / monitor / controller.++ Mirrors ``ZoneMinderMixin``: cache the manager on first access and+ return it on subsequent calls. The async variant uses+ ``asyncio.shield`` so a cancelled init doesn't leave the mixin+ holding a half-constructed manager reference.+ """++ def frigate_manager(self) -> FrigateManager:+ if not hasattr( self, '_frigate_manager' ):+ self._frigate_manager = FrigateManager()+ self._frigate_manager.ensure_initialized()+ return self._frigate_manager++ async def frigate_manager_async(self) -> FrigateManager:+ if not hasattr( self, '_frigate_manager' ):+ self._frigate_manager = FrigateManager()+ try:+ await asyncio.shield( self._frigate_manager.ensure_initialized_async() )+ except asyncio.CancelledError:+ logger.warning( 'Frigate init ensure_initialized_async cancelled.' )+ return None+ except Exception as e:+ logger.warning( f'Frigate init failed: {e}' )+ return None+ return self._frigate_managerdiff --git a/src/hi/services/frigate/frigate_models.py b/src/hi/services/frigate/frigate_models.pynew file mode 100644index 00000000..796ebeb4--- /dev/null+++ b/src/hi/services/frigate/frigate_models.py@@ -0,0 +1,96 @@+from dataclasses import dataclass+from datetime import datetime, timezone+from typing import Any, Dict, List, Optional+++@dataclass+class FrigateEvent:+ """HI-side wrapper for a single Frigate ``/api/events`` record.++ Frigate's event lifecycle (``new`` / ``update`` / ``end``) maps+ onto HI's MOVEMENT correlation pattern the same way ZoneMinder+ events do — see ``ZmEvent`` for the reference shape. Fields are+ populated by ``from_api_dict``.+ """++ event_id : str+ camera_name : str+ object_class : str+ start_datetime : datetime+ end_datetime : Optional[ datetime ] = None+ score : Optional[ float ] = None+ sub_label : Optional[ str ] = None+ zones : Optional[ List[ str ] ] = None+ snapshot_url : Optional[ str ] = None+ clip_url : Optional[ str ] = None+ # Frigate emits ``has_clip``/``has_snapshot`` booleans per event+ # so the UI can avoid offering playback for events whose clip+ # never made it to disk. Default ``True`` matches Frigate's own+ # default behavior (events come with clips unless explicitly+ # disabled).+ has_clip : bool = True+ has_snapshot : bool = True++ @property+ def is_open(self) -> bool:+ return self.end_datetime is None++ @property+ def is_closed(self) -> bool:+ return self.end_datetime is not None++ @classmethod+ def from_api_dict( cls, api_dict : Dict[ str, Any ] ) -> 'FrigateEvent':+ """Parse one entry of the ``/api/events`` JSON array.++ Frigate emits start_time / end_time as epoch-seconds floats;+ we hold them as TZ-aware ``datetime`` (UTC) for parity with+ the rest of HI's datetime handling. Missing required fields+ raise ``ValueError``; missing optional fields default to+ ``None``."""+ try:+ event_id = str( api_dict[ 'id' ] )+ camera_name = api_dict[ 'camera' ]+ object_class = api_dict[ 'label' ]+ start_epoch = api_dict[ 'start_time' ]+ except KeyError as e:+ raise ValueError(+ f'Frigate event payload missing required field: {e}'+ ) from e++ start_datetime = cls._epoch_to_datetime( start_epoch )+ end_epoch = api_dict.get( 'end_time' )+ end_datetime = (+ cls._epoch_to_datetime( end_epoch ) if end_epoch is not None else None+ )+ return cls(+ event_id = event_id,+ camera_name = camera_name,+ object_class = object_class,+ start_datetime = start_datetime,+ end_datetime = end_datetime,+ score = api_dict.get( 'top_score' ),+ sub_label = api_dict.get( 'sub_label' ),+ zones = api_dict.get( 'zones' ),+ has_clip = bool( api_dict.get( 'has_clip', True )),+ has_snapshot = bool( api_dict.get( 'has_snapshot', True )),+ )++ @staticmethod+ def _epoch_to_datetime( epoch_secs : float ) -> datetime:+ return datetime.fromtimestamp( float( epoch_secs ), tz = timezone.utc )+++@dataclass+class TrackedFrigateEvent:+ """A Frigate event the monitor is actively tracking — i.e. seen+ open and not yet observed closed.++ ``first_observed_at`` is captured in HI's clock (not Frigate's+ ``start_time``) so the force-close timeout sidesteps any clock+ skew between the two systems. ``event`` snapshots the payload as+ last seen — it's refreshed on each per-id poll until the event+ closes (``end_time`` set) or is force-closed."""++ event : FrigateEvent+ first_observed_at : datetimediff --git a/src/hi/services/frigate/frigate_sync.py b/src/hi/services/frigate/frigate_sync.pynew file mode 100644index 00000000..c1c90bfc--- /dev/null+++ b/src/hi/services/frigate/frigate_sync.py@@ -0,0 +1,324 @@+import logging+from typing import Dict, List, Optional++from asgiref.sync import sync_to_async+from django.db import transaction++from hi.apps.entity.enums import EntityType+from hi.apps.entity.entity_placement import (+ EntityPlacementGroup,+ EntityPlacementInput,+ EntityPlacementItem,+)+from hi.apps.entity.models import Entity+from hi.apps.model_helper import HiModelHelper++from hi.integrations.integration_synchronizer import IntegrationSynchronizer+from hi.integrations.sync_check import IntegrationSyncCheck, SyncDelta+from hi.integrations.sync_result import IntegrationSyncResult+from hi.integrations.transient_models import IntegrationKey++from .frigate_manager import FrigateManager+from .frigate_metadata import FrigateMetaData+from .frigate_mixins import FrigateMixin++logger = logging.getLogger(__name__)+++class FrigateSynchronizer( IntegrationSynchronizer, FrigateMixin ):+ """Drives the Frigate Import / Refresh workflow.++ Mirrors ``ZoneMinderSynchronizer`` in role: pulls the upstream+ camera list from Frigate (via ``/api/config`` since Frigate has+ no dedicated cameras endpoint), reconciles it against existing+ HI entities by integration_key, creates / updates / removes as+ needed. Frigate v1 has no native moving stream (MJPEG/RTSP+ require go2rtc on the operator's end), so camera entities are+ created with ``has_video_snapshot`` + a non-zero+ ``video_snapshot_stream_fps`` rather than ``has_video_stream``."""++ CAMERA_SNAPSHOT_STREAM_FPS = 1.0++ def get_integration_metadata(self):+ return FrigateMetaData++ def get_description(self, is_initial_import : bool) -> Optional[ str ]:+ if is_initial_import:+ return (+ 'Each Frigate camera becomes a HI camera entity with'+ ' motion and object-presence sensors.'+ )+ return None++ async def check_needs_sync(self) -> Optional[ SyncDelta ]:+ """Sync-check probe (Issue #283 protocol). Pulls the camera+ list from Frigate and compares its integration-key set against+ the keys of the existing camera-shaped HI entities."""+ frigate_manager = await self.frigate_manager_async()+ if frigate_manager is None or frigate_manager.frigate_client is None:+ return None+ prefix = FrigateManager.FRIGATE_CAMERA_INTEGRATION_NAME_PREFIX++ def _fetch_cameras():+ return frigate_manager.frigate_client.get_cameras()++ try:+ cameras = await sync_to_async( _fetch_cameras, thread_sensitive = True )()+ except Exception:+ logger.exception( 'Frigate check_needs_sync: failed to fetch cameras' )+ return None+ upstream_keys = {+ FrigateManager._to_integration_key(+ prefix = prefix,+ camera_name = camera[ 'name' ],+ )+ for camera in cameras+ }+ current_keys = await sync_to_async( self._get_current_camera_integration_keys )(+ prefix = prefix,+ )+ return IntegrationSyncCheck.compute_delta(+ upstream_keys = upstream_keys,+ current_keys = current_keys,+ )++ @staticmethod+ def _get_current_camera_integration_keys( prefix : str ) -> set:+ return {+ IntegrationKey(+ integration_id = integration_id,+ integration_name = integration_name,+ )+ for integration_id, integration_name in Entity.objects.filter(+ integration_id = FrigateMetaData.integration_id,+ integration_name__startswith = prefix,+ ).values_list( 'integration_id', 'integration_name' )+ }++ def _sync_impl( self, is_initial_import : bool ) -> IntegrationSyncResult:+ result = IntegrationSyncResult(+ title = self.get_result_title( is_initial_import = is_initial_import ),+ )+ frigate_manager = self.frigate_manager()+ if frigate_manager.frigate_client is None:+ result.error_list.append( 'Frigate client not available. Integration disabled?' )+ return result++ created_camera_entities = self._sync_cameras( result = result )+ if created_camera_entities:+ result.placement_input = self.group_entities_for_placement(+ entities = created_camera_entities,+ )+ return result++ def group_entities_for_placement( self, entities ) -> EntityPlacementInput:+ """Single 'Cameras' placement group: Frigate cameras usually+ share a wall-of-views layout, so 'all cameras → same place'+ is the right default. Operators can still drill into+ per-camera placement from the dispatcher."""+ if not entities:+ return EntityPlacementInput()+ items = [+ EntityPlacementItem(+ key = self._placement_item_key( entity = entity ),+ label = entity.name,+ entity = entity,+ )+ for entity in entities+ ]+ return EntityPlacementInput(+ groups = [ EntityPlacementGroup( label = 'Cameras', items = items ) ],+ )++ def _sync_cameras( self, result : IntegrationSyncResult ) -> List[ Entity ]:+ integration_key_to_camera = self._fetch_frigate_cameras( result = result )+ result.info_list.append(+ f'Found {len(integration_key_to_camera)} current Frigate cameras.'+ )++ integration_key_to_entity = self._get_existing_camera_entities( result = result )+ result.info_list.append(+ f'Found {len(integration_key_to_entity)} existing Frigate items.'+ )++ # Issue #281 reconnect pre-pass — any disconnected entity whose+ # previous identity matches an unmatched upstream camera is+ # reconnected in place and the main loop below treats it as+ # primary-matched.+ self.reconnect_disconnected_items(+ integration_key_to_upstream = integration_key_to_camera,+ integration_key_to_entity = integration_key_to_entity,+ result = result,+ )++ created_entities = []+ for integration_key, camera in integration_key_to_camera.items():+ entity = integration_key_to_entity.get( integration_key )+ if entity:+ self._update_entity( entity = entity,+ camera = camera,+ result = result )+ else:+ entity = self._create_camera_entity( camera = camera,+ result = result )+ created_entities.append( entity )+ continue++ for integration_key, entity in integration_key_to_entity.items():+ if integration_key not in integration_key_to_camera:+ self._remove_entity( entity = entity, result = result )+ continue++ return created_entities++ def _rebuild_integration_components( self,+ entity : Entity,+ upstream : dict,+ result : IntegrationSyncResult ):+ """Issue #281: dispatch to the camera-entity converter with+ the existing-entity parameter set, so the converter repopulates+ integration-owned components on the previously-disconnected+ entity rather than creating a fresh one."""+ self._create_camera_entity(+ camera = upstream,+ result = result,+ entity = entity,+ )+ return++ def _fetch_frigate_cameras( self, result : IntegrationSyncResult ) -> Dict[ IntegrationKey, dict ]:+ frigate_manager = self.frigate_manager()+ prefix = FrigateManager.FRIGATE_CAMERA_INTEGRATION_NAME_PREFIX+ logger.debug( 'Getting current Frigate cameras.' )+ integration_key_to_camera = dict()+ cameras = frigate_manager.frigate_client.get_cameras()+ for camera in cameras:+ integration_key = FrigateManager._to_integration_key(+ prefix = prefix,+ camera_name = camera[ 'name' ],+ )+ integration_key_to_camera[ integration_key ] = camera+ continue+ return integration_key_to_camera++ def _get_existing_camera_entities( self,+ result : IntegrationSyncResult,+ ) -> Dict[ IntegrationKey, Entity ]:+ logger.debug( 'Getting existing Frigate entities.' )+ prefix = FrigateManager.FRIGATE_CAMERA_INTEGRATION_NAME_PREFIX+ integration_key_to_entity = dict()+ entity_queryset = Entity.objects.filter(+ integration_id = FrigateMetaData.integration_id,+ )+ for entity in entity_queryset:+ integration_key = entity.integration_key+ if not integration_key:+ result.error_list.append(+ f'Frigate item found without integration name: {entity}'+ )+ mock_id = 1000000 + entity.id # disambiguating placeholder+ integration_key = IntegrationKey(+ integration_id = FrigateMetaData.integration_id,+ integration_name = f'{prefix}.placeholder_{mock_id}',+ )+ if integration_key.integration_name.startswith( prefix + '.' ):+ integration_key_to_entity[ integration_key ] = entity+ continue+ return integration_key_to_entity++ def _create_camera_entity( self,+ camera : dict,+ result : IntegrationSyncResult,+ entity : Optional[ Entity ] = None ) -> Entity:+ """Create or repopulate the integration-owned components for+ a Frigate camera. ``entity is None`` is the fresh-import path;+ passing an existing ``entity`` is the auto-reconnect path+ (Issue #281), where integration-owned fields get refilled but+ the user-editable ``name`` is preserved across the+ intervening disconnect."""+ camera_name = camera[ 'name' ]+ # Frigate's camera key (snake_case) is the technical identifier;+ # the ``friendly_name`` on the per-camera config is the operator's+ # display label. Prefer it for the HI entity name and fall back+ # to the snake_case key when no friendly_name is set.+ camera_config = camera.get( 'config' ) or {}+ display_name = camera_config.get( 'friendly_name' ) or camera_name+ with transaction.atomic():+ entity_integration_key = FrigateManager._to_integration_key(+ prefix = FrigateManager.FRIGATE_CAMERA_INTEGRATION_NAME_PREFIX,+ camera_name = camera_name,+ )+ if entity is None:+ entity = Entity(+ name = display_name,+ entity_type_str = str( EntityType.CAMERA ),+ )++ # Integration-owned fields: re-applied on fresh-create and+ # on reconnect so the entity reflects current upstream state.+ entity.integration_key = entity_integration_key+ entity.can_user_delete = FrigateMetaData.allow_entity_deletion+ entity.has_video_stream = False+ entity.has_video_snapshot = True+ entity.video_snapshot_stream_fps = self.CAMERA_SNAPSHOT_STREAM_FPS+ entity.save()++ # Single sensor per camera — OBJECT_PRESENCE subsumes the+ # "is motion happening" signal (any non-OBJECT_NONE value+ # implies motion + the class causing it). Frigate's data+ # model doesn't expose motion independent of object+ # detection, so a separate MOVEMENT sensor would always+ # mirror this one's state.+ object_presence_sensor = HiModelHelper.create_object_presence_sensor(+ entity = entity,+ integration_key = FrigateManager._to_integration_key(+ prefix = FrigateManager.OBJECT_PRESENCE_SENSOR_PREFIX,+ camera_name = camera_name,+ ),+ provides_event_video_clip = True,+ provides_event_video_snapshot = True,+ )++ if self.frigate_manager().should_add_alarm_events:+ HiModelHelper.create_object_presence_event_definition(+ name = f'{object_presence_sensor.name} Alarm',+ entity_state = object_presence_sensor.entity_state,+ integration_key = FrigateManager._to_integration_key(+ prefix = FrigateManager.OBJECT_PRESENCE_EVENT_PREFIX,+ camera_name = camera_name,+ ),+ )++ result.created_list.append( entity.name )+ return entity++ def _update_entity( self,+ entity : Entity,+ camera : dict,+ result : IntegrationSyncResult ):+ """Refresh integration-owned capability flags on an existing+ camera entity. Like the ZM integration, ``entity.name`` is+ treated as user-owned after creation: this method does not+ touch it on update."""+ update_fields = []+ if entity.has_video_stream:+ entity.has_video_stream = False+ update_fields.append( 'has_video_stream' )+ if not entity.has_video_snapshot:+ entity.has_video_snapshot = True+ update_fields.append( 'has_video_snapshot' )+ if entity.video_snapshot_stream_fps != self.CAMERA_SNAPSHOT_STREAM_FPS:+ entity.video_snapshot_stream_fps = self.CAMERA_SNAPSHOT_STREAM_FPS+ update_fields.append( 'video_snapshot_stream_fps' )+ if update_fields:+ entity.save( update_fields = update_fields )+ return++ def _remove_entity( self,+ entity : Entity,+ result : IntegrationSyncResult ):+ """Remove an entity that no longer exists in Frigate. Uses+ ``_remove_entity_intelligently`` to preserve user-attached+ data when present."""+ self._remove_entity_intelligently( entity, result )+ returndiff --git a/src/hi/services/frigate/integration.py b/src/hi/services/frigate/integration.pynew file mode 100644index 00000000..adf111d7--- /dev/null+++ b/src/hi/services/frigate/integration.py@@ -0,0 +1,166 @@+import logging+from typing import List, Optional++from hi.apps.entity.enums import VideoStreamType+from hi.apps.entity.models import Entity+from hi.apps.entity.transient_models import VideoSnapshot, VideoStream+from hi.apps.sense.transient_models import SensorResponse+from hi.apps.monitor.periodic_monitor import PeriodicMonitor+from hi.apps.system.enums import HealthStatusType+from hi.apps.system.health_status_provider import HealthStatusProvider++from hi.integrations.integration_controller import IntegrationController+from hi.integrations.integration_gateway import IntegrationGateway+from hi.integrations.integration_manage_view_pane import IntegrationManageViewPane+from hi.integrations.integration_synchronizer import IntegrationSynchronizer+from hi.integrations.models import IntegrationAttribute+from hi.integrations.transient_models import (+ ConnectionTestResult,+ IntegrationMetaData,+ IntegrationValidationResult,+)++from .frigate_controller import FrigateController+from .frigate_manage_view_pane import FrigateManageViewPane+from .frigate_manager import FrigateManager+from .frigate_metadata import FrigateMetaData+from .frigate_mixins import FrigateMixin+from .frigate_sync import FrigateSynchronizer+from .monitors import FrigateMonitor++logger = logging.getLogger(__name__)+++class FrigateGateway( IntegrationGateway, FrigateMixin ):+ """Framework entry point for the Frigate integration.++ Auto-discovered by ``IntegrationManager.discover_defined_integrations``+ because this module exposes an ``IntegrationGateway`` subclass and+ lives under ``hi.services.*``. Delegates almost everything to the+ other pieces of the integration; see+ ``docs/dev/integrations/integration-guidelines.md`` for the+ contract this class satisfies.+ """++ def get_metadata(self) -> IntegrationMetaData:+ return FrigateMetaData++ def get_manage_view_pane(self) -> IntegrationManageViewPane:+ return FrigateManageViewPane()++ def get_monitor(self) -> PeriodicMonitor:+ return FrigateMonitor()++ def get_controller(self) -> IntegrationController:+ return FrigateController()++ def notify_settings_changed(self):+ try:+ FrigateManager().notify_settings_changed()+ logger.debug( 'Frigate integration notified of settings change.' )+ except Exception as e:+ logger.exception(+ f'Error notifying Frigate integration of settings change: {e}'+ )++ def get_health_status_provider(self) -> HealthStatusProvider:+ return FrigateManager()++ def get_synchronizer(self) -> IntegrationSynchronizer:+ return FrigateSynchronizer()++ def validate_configuration(+ self,+ integration_attributes : List[ IntegrationAttribute ],+ ) -> IntegrationValidationResult:+ try:+ return FrigateManager().validate_configuration(+ integration_attributes = integration_attributes,+ )+ except Exception as e:+ logger.exception( f'Error validating Frigate configuration: {e}' )+ return IntegrationValidationResult.error(+ status = HealthStatusType.WARNING,+ error_message = f'Configuration validation failed: {e}',+ )++ def test_connection(+ self,+ integration_attributes : List[ IntegrationAttribute ],+ timeout_secs : Optional[ float ],+ ) -> ConnectionTestResult:+ try:+ return FrigateManager().test_connection(+ integration_attributes = integration_attributes,+ timeout_secs = timeout_secs,+ )+ except Exception as e:+ logger.exception( f'Error in Frigate connection test: {e}' )+ return ConnectionTestResult.failure( f'Connection test error: {e}' )++ def get_entity_video_snapshot(self, entity : Entity) -> Optional[ VideoSnapshot ]:+ """Live still-frame for the Frigate camera backing this entity+ (``/api/<camera>/latest.jpg``). Returns ``None`` when the+ entity isn't a Frigate camera, when ``has_video_snapshot`` is+ off (operator opt-out), or when the integration client isn't+ ready."""+ if not entity.has_video_snapshot:+ return None+ if entity.integration_id != FrigateMetaData.integration_id:+ return None++ prefix = FrigateManager.FRIGATE_CAMERA_INTEGRATION_NAME_PREFIX + '.'+ integration_name = entity.integration_name or ''+ if not integration_name.startswith( prefix ):+ return None+ camera_name = integration_name[ len( prefix ): ]+ if not camera_name:+ return None++ source_url = FrigateManager().get_camera_snapshot_url(+ camera_name = camera_name,+ )+ if source_url is None:+ return None+ return VideoSnapshot(+ source_url = source_url,+ metadata = { 'camera_name': camera_name },+ )++ def get_sensor_response_event_snapshot_url(+ self,+ sensor_response : SensorResponse,+ ) -> Optional[ str ]:+ """Per-event snapshot URL for a Frigate SensorResponse. Pulls+ the event_id from ``correlation_id`` and builds the URL fresh+ each call so operator-side base_url changes auto-heal every+ historical row."""+ if not sensor_response.has_event_video_snapshot:+ return None+ event_id = sensor_response.correlation_id+ if not event_id:+ return None+ return FrigateManager().get_event_snapshot_url( event_id = event_id )++ def get_sensor_response_video_stream(+ self,+ sensor_response : SensorResponse,+ ) -> Optional[ VideoStream ]:+ """Event-clip MP4 URL for a Frigate SensorResponse.+ Returns ``None`` when the response carries no clip+ (``has_event_video_clip`` False), when the+ ``correlation_id`` — Frigate's event_id — is absent, or when+ the integration client isn't ready."""+ if not sensor_response.has_event_video_clip:+ return None+ event_id = sensor_response.correlation_id+ if not event_id:+ return None+ source_url = FrigateManager().get_event_clip_url( event_id = event_id )+ if source_url is None:+ return None+ return VideoStream(+ stream_type = VideoStreamType.MP4,+ source_url = source_url,+ metadata = { 'event_id': event_id },+ )diff --git a/src/hi/services/frigate/migrations/__init__.py b/src/hi/services/frigate/migrations/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/services/frigate/monitors.py b/src/hi/services/frigate/monitors.pynew file mode 100644index 00000000..64c783f5--- /dev/null+++ b/src/hi/services/frigate/monitors.py@@ -0,0 +1,475 @@+from datetime import datetime, timedelta+import logging+from typing import Dict, List, Optional, Set, Tuple++from django.conf import settings+from django.http import Http404++import hi.apps.common.datetimeproxy as datetimeproxy+from hi.apps.alert.enums import AlarmLevel+from hi.apps.monitor.periodic_monitor import PeriodicMonitor+from hi.apps.sense.enums import CorrelationRole+from hi.apps.sense.sensor_response_manager import SensorResponseMixin+from hi.apps.sense.transient_models import SensorResponse+from hi.apps.system.provider_info import ProviderInfo+from hi.testing.dev_overrides import DevOverrideManager++from .constants import FrigateDetailKeys, FrigateTimeouts+from .frigate_converter import FrigateConverter+from .frigate_manager import FrigateManager+from .frigate_mixins import FrigateMixin+from .frigate_models import FrigateEvent, TrackedFrigateEvent++logger = logging.getLogger(__name__)+++class FrigateMonitor( PeriodicMonitor, FrigateMixin, SensorResponseMixin ):+ """Periodic poll for Frigate cameras and events.++ Frigate's ``/api/events?after=T`` filters strictly on+ ``start_time > T``: once the cursor advances past an event's+ start_time, that event is invisible to cursor scans forever, even+ after it closes. So the pipeline doesn't pin the cursor to keep+ open events visible (the ZM-style approach is incompatible with+ Frigate's filter). Instead:++ Phase 1 — cursor scan (``?after=cursor``): emit START for each+ new event; emit END too if it was already closed when seen;+ track open ones in ``_tracked_events`` by id. Cursor advances+ monotonically to the latest start_time of any event observed.++ Phase 2 — per-id refresh (``GET /api/events/<id>``): for each+ tracked id, fetch its canonical state. Closed → emit END,+ drop from tracking. 404 → force-close, drop. Aged past+ ``MAX_OPEN_EVENT_AGE_SECS`` → force-close, drop.++ Phase 3 — heartbeat: emit OBJECT_NONE for cameras with no+ activity this cycle and no event currently tracked, so quiet+ cameras don't go stale.+ """++ MONITOR_ID = 'hi.services.frigate.monitor'++ POLLING_INTERVAL_SECS = FrigateTimeouts.POLLING_INTERVAL_SECS+ API_TIMEOUT_SECS = FrigateTimeouts.API_TIMEOUT_SECS++ # Force-close an open event whose age in HI's tracking set+ # exceeds this. Pulled into a class attribute so tests can shrink+ # the threshold to exercise the timeout path.+ MAX_OPEN_EVENT_AGE_SECS = FrigateTimeouts.MAX_OPEN_EVENT_AGE_SECS++ def __init__(self):+ super().__init__(+ id = self.MONITOR_ID,+ interval_secs = self.POLLING_INTERVAL_SECS,+ )+ self._poll_cursor_datetime : Optional[ datetime ] = None+ self._tracked_events : Dict[ str, TrackedFrigateEvent ] = {}+ self._was_initialized = False+ return++ def get_api_timeout(self) -> float:+ return self.API_TIMEOUT_SECS++ def alarm_ceiling(self):+ # Frigate is a security-camera dependency; treat outages as+ # serious by default (same posture as the ZM monitor).+ return AlarmLevel.CRITICAL++ @classmethod+ def get_provider_info(cls) -> ProviderInfo:+ return ProviderInfo(+ provider_id = cls.MONITOR_ID,+ provider_name = 'Frigate Monitor',+ description = 'Frigate camera motion + object detection',+ expected_heartbeat_interval_secs = cls.POLLING_INTERVAL_SECS,+ )++ async def _initialize(self):+ frigate_manager = await self.frigate_manager_async()+ if not frigate_manager:+ return+ _ = await self.sensor_response_manager_async()+ self._poll_cursor_datetime = datetimeproxy.now()+ self._tracked_events = {}+ frigate_manager.register_change_listener( self.refresh )+ frigate_manager.add_subordinate_health_status_provider( self )+ self._was_initialized = True+ return++ def refresh(self):+ """Settings-changed callback: reset per-cycle state so the+ next ``do_work`` re-initializes against fresh manager state."""+ self._was_initialized = False+ return++ async def do_work(self):+ if not self._was_initialized:+ await self._initialize()+ if not self._was_initialized:+ logger.warning( 'Frigate monitor failed to initialize. Skipping work cycle.' )+ self.record_warning( 'Was not initialized.' )+ return++ sensor_response_map = dict()+ sensor_response_map.update( await self._process_events() )++ await self.sensor_response_manager().update_with_latest_sensor_responses(+ sensor_response_map = sensor_response_map,+ )+ self.record_healthy( f'Processed {len(sensor_response_map)} Frigate states.' )+ return++ # ---- SensorResponse factory helpers ------------------------------++ def _create_object_presence_sensor_response(+ self,+ camera_name : str,+ value : str,+ timestamp : datetime,+ correlation_role : 'CorrelationRole' = None,+ correlation_id : str = None,+ has_event_video_clip : bool = False,+ has_event_video_snapshot : bool = False,+ detail_attrs : Dict = None,+ ) -> SensorResponse:+ """OBJECT_PRESENCE SensorResponse. ``value`` is one of the+ canonical bucket strings produced by+ ``FrigateConverter.to_canonical_object_class`` or+ ``OBJECT_NONE_VALUE`` for no-detection cycles."""+ return SensorResponse(+ integration_key = FrigateManager._to_integration_key(+ prefix = FrigateManager.OBJECT_PRESENCE_SENSOR_PREFIX,+ camera_name = camera_name,+ ),+ value = value,+ timestamp = timestamp,+ correlation_role = correlation_role,+ correlation_id = correlation_id,+ has_event_video_clip = has_event_video_clip,+ has_event_video_snapshot = has_event_video_snapshot,+ detail_attrs = detail_attrs,+ )++ def _build_event_detail_attrs( self,+ event : FrigateEvent,+ is_closed : bool ) -> Dict[ str, str ]:+ """Pack the event's metadata into a SensorResponse.detail_attrs+ dict so the event-detail UI surfaces the rich payload. Duration+ is omitted for open (START) responses — the value isn't known+ until the event closes."""+ attrs : Dict[ str, str ] = {+ FrigateDetailKeys.EVENT_ID: event.event_id,+ FrigateDetailKeys.START_TIME: event.start_datetime.isoformat(),+ FrigateDetailKeys.OBJECT_CLASS: event.object_class,+ }+ if event.score is not None:+ attrs[ FrigateDetailKeys.SCORE ] = f'{event.score:.2f}'+ if event.sub_label:+ attrs[ FrigateDetailKeys.SUB_LABEL ] = event.sub_label+ if event.zones:+ attrs[ FrigateDetailKeys.ZONES ] = ', '.join( event.zones )+ if is_closed and event.end_datetime is not None:+ duration = ( event.end_datetime - event.start_datetime ).total_seconds()+ attrs[ FrigateDetailKeys.DURATION_SECS ] = f'{duration:.1f}'+ return attrs++ # ---- Event processing pipeline ---------------------------------++ async def _process_events(self) -> Dict:+ current_poll_datetime = datetimeproxy.now()++ scan_map, scan_touched = await self._scan_new_events_phase()+ refresh_map, refresh_touched = await self._refresh_tracked_events_phase(+ current_poll_datetime = current_poll_datetime,+ )+ heartbeat_map = await self._heartbeat_idle_cameras_phase(+ current_poll_datetime = current_poll_datetime,+ cameras_touched = scan_touched | refresh_touched,+ )++ sensor_response_map : Dict = {}+ sensor_response_map.update( scan_map )+ sensor_response_map.update( refresh_map )+ sensor_response_map.update( heartbeat_map )+ return sensor_response_map++ async def _scan_new_events_phase(self) -> Tuple[ Dict, Set[ str ] ]:+ """Query ``?after=cursor`` for events whose ``start_time``+ is past our watermark. Cursor is monotonic so any id returned+ here is new to us (any prior open event has ``start_time+ <= cursor`` and is tracked through phase 2 instead).++ Each new event:+ - emit START transition+ - if already closed: also emit END transition (open-and-close+ collapsed into a single cycle is unavoidable when an+ event's lifetime is shorter than the poll interval)+ - else: enter the open set for phase-2 tracking+ """+ after_epoch = self._poll_cursor_datetime.timestamp()+ try:+ api_events = await self.frigate_manager().get_events_async(+ after = after_epoch,+ )+ except Exception as e:+ logger.error( f'Frigate events API call failed: {e}' )+ raise++ new_events : List[ FrigateEvent ] = []+ for api_event in api_events:+ try:+ event = FrigateEvent.from_api_dict( api_event )+ except ValueError as e:+ logger.warning( f'Skipping malformed Frigate event: {e}' )+ continue+ if event.event_id in self._tracked_events:+ # Cursor is monotonic so this shouldn't happen, but+ # if Frigate ever serves the same id again, defer to+ # phase 2's canonical refresh.+ continue+ new_events.append( event )++ sensor_response_map : Dict = {}+ cameras_touched : Set[ str ] = set()+ now = datetimeproxy.now()+ for event in new_events:+ cameras_touched.add( event.camera_name )+ start_response = self._build_object_presence_response(+ event = event,+ value = FrigateConverter.to_canonical_object_class(+ raw_class = event.object_class,+ ),+ timestamp = event.start_datetime,+ correlation_role = CorrelationRole.START,+ )+ sensor_response_map[ start_response.integration_key ] = start_response+ if event.is_closed:+ end_response = self._build_object_presence_response(+ event = event,+ value = FrigateConverter.OBJECT_NONE_VALUE,+ timestamp = event.end_datetime,+ correlation_role = CorrelationRole.END,+ )+ sensor_response_map[ end_response.integration_key ] = end_response+ else:+ self._tracked_events[ event.event_id ] = TrackedFrigateEvent(+ event = event,+ first_observed_at = now,+ )++ if new_events:+ # Defensive: Frigate's ``?after=`` filter is strict ``>``,+ # so all events here should already have start_time past+ # the cursor — but if upstream ever returns one that+ # doesn't (proxy replay, Frigate bug, clock skew), don't+ # let the cursor regress.+ latest_start = max( e.start_datetime for e in new_events )+ if latest_start > self._poll_cursor_datetime:+ self._poll_cursor_datetime = latest_start+ return sensor_response_map, cameras_touched++ async def _refresh_tracked_events_phase(+ self,+ current_poll_datetime : datetime,+ ) -> Tuple[ Dict, Set[ str ] ]:+ """Per-id refresh for every event currently in the open set.+ Outcomes per id:+ - 404 → force-close (vanished)+ - other failure → leave in set; force-close if aged out+ - closed → emit END, remove from set+ - still open → refresh snapshot; force-close if aged out+ """+ sensor_response_map : Dict = {}+ cameras_touched : Set[ str ] = set()+ tracked_ids = list( self._tracked_events.keys() ) # snapshot+ for event_id in tracked_ids:+ tracked_event = self._tracked_events.get( event_id )+ if tracked_event is None:+ continue+ try:+ api_event = await self.frigate_manager().get_event_async(+ event_id = event_id,+ )+ except Http404:+ self._force_close(+ tracked_event = tracked_event,+ timestamp = current_poll_datetime,+ reason = 'vanished',+ sensor_response_map = sensor_response_map,+ cameras_touched = cameras_touched,+ )+ continue+ except Exception as e:+ logger.warning(+ f'Frigate refresh of open event {event_id} failed: {e}'+ )+ if self._should_force_close( tracked_event, current_poll_datetime ):+ self._force_close(+ tracked_event = tracked_event,+ timestamp = current_poll_datetime,+ reason = 'force_close_timeout',+ sensor_response_map = sensor_response_map,+ cameras_touched = cameras_touched,+ )+ continue++ try:+ frigate_event = FrigateEvent.from_api_dict( api_event )+ except ValueError as e:+ logger.warning(+ f'Open event {event_id} returned malformed payload: {e}'+ )+ continue++ cameras_touched.add( frigate_event.camera_name )+ if frigate_event.is_closed:+ end_response = self._build_object_presence_response(+ event = frigate_event,+ value = FrigateConverter.OBJECT_NONE_VALUE,+ timestamp = frigate_event.end_datetime,+ correlation_role = CorrelationRole.END,+ )+ sensor_response_map[ end_response.integration_key ] = end_response+ del self._tracked_events[ event_id ]+ continue++ tracked_event.event = frigate_event+ if self._should_force_close( tracked_event, current_poll_datetime ):+ self._force_close(+ tracked_event = tracked_event,+ timestamp = current_poll_datetime,+ reason = 'force_close_timeout',+ sensor_response_map = sensor_response_map,+ cameras_touched = cameras_touched,+ )+ return sensor_response_map, cameras_touched++ async def _heartbeat_idle_cameras_phase(+ self,+ current_poll_datetime : datetime,+ cameras_touched : Set[ str ],+ ) -> Dict:+ """Emit OBJECT_NONE for cameras with no event activity this+ cycle and no event currently tracked in the open set.++ Without this, a camera that's been quiet since HI started+ would never produce a SensorResponse and its state would go+ stale. Cameras with active or in-flight events are skipped —+ their state is being driven by phases 1 and 2 already."""+ try:+ cameras = await self.frigate_manager().get_cameras_async()+ except Exception as e:+ logger.warning(+ f'Frigate camera list fetch failed during heartbeat: {e}'+ )+ return {}++ open_camera_names = {+ tracked_event.event.camera_name+ for tracked_event in self._tracked_events.values()+ }+ sensor_response_map : Dict = {}+ for camera in cameras:+ camera_name = camera[ 'name' ]+ if camera_name in cameras_touched:+ continue+ if camera_name in open_camera_names:+ continue+ idle_response = self._create_object_presence_sensor_response(+ camera_name = camera_name,+ value = FrigateConverter.OBJECT_NONE_VALUE,+ timestamp = current_poll_datetime,+ )+ sensor_response_map[ idle_response.integration_key ] = idle_response++ if settings.DEBUG and settings.DEBUG_TRACE_STATE:+ DevOverrideManager.trace_state(+ 'hi.frigate_poll.no_events_object',+ integration_name = idle_response.integration_key.integration_name,+ integration_value = idle_response.value,+ camera_name = camera_name,+ )+ return sensor_response_map++ def _force_close(+ self,+ tracked_event : TrackedFrigateEvent,+ timestamp : datetime,+ reason : str,+ sensor_response_map : Dict,+ cameras_touched : Set[ str ],+ ) -> None:+ """Drop ``tracked_event`` from the open set and emit a synthesized+ END response in ``sensor_response_map``. Used when Frigate's+ canonical state cannot be obtained (404, persistent fetch+ failure past the age threshold)."""+ response = self._build_force_close_response(+ tracked_event = tracked_event,+ timestamp = timestamp,+ reason = reason,+ )+ sensor_response_map[ response.integration_key ] = response+ cameras_touched.add( tracked_event.event.camera_name )+ del self._tracked_events[ tracked_event.event.event_id ]+ return++ def _should_force_close(+ self,+ tracked_event : TrackedFrigateEvent,+ current_poll_datetime : datetime,+ ) -> bool:+ age = current_poll_datetime - tracked_event.first_observed_at+ return age > timedelta( seconds = self.MAX_OPEN_EVENT_AGE_SECS )++ def _build_object_presence_response(+ self,+ event : FrigateEvent,+ value : str,+ timestamp : datetime,+ correlation_role : CorrelationRole,+ ) -> SensorResponse:+ return self._create_object_presence_sensor_response(+ camera_name = event.camera_name,+ value = value,+ timestamp = timestamp,+ correlation_role = correlation_role,+ correlation_id = event.event_id,+ has_event_video_clip = event.has_clip,+ has_event_video_snapshot = event.has_snapshot,+ detail_attrs = self._build_event_detail_attrs(+ event = event,+ is_closed = ( correlation_role == CorrelationRole.END ),+ ),+ )++ def _build_force_close_response(+ self,+ tracked_event : TrackedFrigateEvent,+ timestamp : datetime,+ reason : str,+ ) -> SensorResponse:+ """END response synthesized when we stop tracking an event+ without observing its actual close (404 from Frigate, or+ ``MAX_OPEN_EVENT_AGE_SECS`` exceeded). ``detail_attrs`` use+ the last-known payload — the real end_time was never seen,+ so no Duration field is included."""+ age_secs = ( timestamp - tracked_event.first_observed_at ).total_seconds()+ logger.warning(+ f'Frigate event {tracked_event.event.event_id}'+ f' (camera {tracked_event.event.camera_name})'+ f' force-closed after {age_secs:.0f}s: {reason}'+ )+ return self._create_object_presence_sensor_response(+ camera_name = tracked_event.event.camera_name,+ value = FrigateConverter.OBJECT_NONE_VALUE,+ timestamp = timestamp,+ correlation_role = CorrelationRole.END,+ correlation_id = tracked_event.event.event_id,+ has_event_video_clip = tracked_event.event.has_clip,+ has_event_video_snapshot = tracked_event.event.has_snapshot,+ detail_attrs = self._build_event_detail_attrs(+ event = tracked_event.event,+ is_closed = False,+ ),+ )diff --git a/src/hi/services/frigate/templates/frigate/panes/frigate_manage.html b/src/hi/services/frigate/templates/frigate/panes/frigate_manage.htmlnew file mode 100644index 00000000..b98346e0--- /dev/null+++ b/src/hi/services/frigate/templates/frigate/panes/frigate_manage.html@@ -0,0 +1,7 @@+{% comment %}+ Integration-specific custom content slot for the Frigate manage+ page. The framework owns the page header (title/logo, lifecycle+ actions, sync actions) and the attribute editor; this template+ renders any Frigate-specific UI between them. Currently empty —+ kept as a documented extension point.+{% endcomment %}diff --git a/src/hi/services/frigate/tests/__init__.py b/src/hi/services/frigate/tests/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/services/frigate/tests/test_frigate_client.py b/src/hi/services/frigate/tests/test_frigate_client.pynew file mode 100644index 00000000..6f37a53c--- /dev/null+++ b/src/hi/services/frigate/tests/test_frigate_client.py@@ -0,0 +1,258 @@+import json+import logging+from unittest.mock import Mock, patch++from django.http import Http404+from django.test import TestCase+from requests.exceptions import ConnectionError++from hi.services.frigate.frigate_client import FrigateClient++logging.disable( logging.CRITICAL )+++def _mock_response( status_code = 200,+ body = '',+ content_type = 'application/json' ) -> Mock:+ response = Mock()+ response.status_code = status_code+ response.headers = { 'content-type': content_type }+ response.text = body+ return response+++class TestFrigateClientInit( TestCase ):++ def test_init_strips_trailing_slash(self):+ client = FrigateClient( api_options = {+ FrigateClient.BASE_URL: 'http://frigate.local:5000/',+ })+ self.assertEqual( client.base_url, 'http://frigate.local:5000' )++ def test_init_without_base_url_raises(self):+ with self.assertRaises( ValueError ):+ FrigateClient( api_options = {} )++ def test_init_optional_auth_header_sets_authorization(self):+ client = FrigateClient( api_options = {+ FrigateClient.BASE_URL: 'http://frigate.local:5000',+ FrigateClient.AUTH_HEADER: 'Bearer abc',+ })+ self.assertEqual( client._headers.get( 'Authorization' ), 'Bearer abc' )++ def test_init_without_auth_header_omits_authorization(self):+ client = FrigateClient( api_options = {+ FrigateClient.BASE_URL: 'http://frigate.local:5000',+ })+ self.assertNotIn( 'Authorization', client._headers )+++class TestFrigateClientPing( TestCase ):++ def setUp(self):+ self.client = FrigateClient( api_options = {+ FrigateClient.BASE_URL: 'http://frigate.local:5000',+ })++ def test_ping_returns_none_on_success(self):+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response( body = '{"cameras": {}}' )+ self.assertIsNone( self.client.ping() )++ def test_ping_raises_on_non_2xx(self):+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response(+ status_code = 500, body = 'Internal Server Error',+ )+ with self.assertRaises( ValueError ) as ctx:+ self.client.ping()+ self.assertIn( '500', str( ctx.exception ) )++ def test_ping_raises_on_html_content_type(self):+ """A 200 with HTML body means the configured URL points at the+ Frigate web UI rather than the API — surface clearly instead of+ letting JSON decode fail later."""+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response(+ content_type = 'text/html', body = '<html>not the API</html>',+ )+ with self.assertRaises( ValueError ) as ctx:+ self.client.ping()+ self.assertIn( 'URL may be incorrect', str( ctx.exception ) )++ def test_ping_raises_on_malformed_json(self):+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response( body = 'not json {' )+ with self.assertRaises( ValueError ) as ctx:+ self.client.ping()+ self.assertIn( 'not valid JSON', str( ctx.exception ) )++ def test_ping_propagates_network_errors(self):+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.side_effect = ConnectionError( 'Connection refused' )+ with self.assertRaises( ConnectionError ):+ self.client.ping()+++class TestFrigateClientGetCameras( TestCase ):++ def setUp(self):+ self.client = FrigateClient( api_options = {+ FrigateClient.BASE_URL: 'http://frigate.local:5000',+ })++ def test_get_cameras_returns_empty_list_for_no_cameras(self):+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response( body = '{"cameras": {}}' )+ self.assertEqual( self.client.get_cameras(), [] )++ def test_get_cameras_returns_one_per_map_entry(self):+ cameras_payload = {+ 'cameras': {+ 'front_yard': { 'enabled': True },+ 'back_door': { 'enabled': True },+ },+ }+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response(+ body = json.dumps( cameras_payload ),+ )+ result = self.client.get_cameras()+ self.assertEqual( len( result ), 2 )+ names = { entry[ 'name' ] for entry in result }+ self.assertEqual( names, { 'front_yard', 'back_door' } )++ def test_get_cameras_preserves_per_camera_config(self):+ cameras_payload = {+ 'cameras': {+ 'front_yard': { 'enabled': True, 'extra': 'value' },+ },+ }+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response(+ body = json.dumps( cameras_payload ),+ )+ ( entry, ) = self.client.get_cameras()+ self.assertEqual( entry[ 'name' ], 'front_yard' )+ self.assertEqual(+ entry[ 'config' ], { 'enabled': True, 'extra': 'value' },+ )++ def test_get_cameras_raises_when_cameras_field_missing(self):+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response( body = '{}' )+ with self.assertRaises( ValueError ) as ctx:+ self.client.get_cameras()+ self.assertIn( 'cameras', str( ctx.exception ) )++ def test_get_cameras_raises_when_cameras_field_wrong_type(self):+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response(+ body = '{"cameras": ["front_yard"]}',+ )+ with self.assertRaises( ValueError ):+ self.client.get_cameras()+++class TestFrigateClientGetEvents( TestCase ):++ def setUp(self):+ self.client = FrigateClient( api_options = {+ FrigateClient.BASE_URL: 'http://frigate.local:5000',+ })++ def test_get_events_returns_empty_list_for_no_events(self):+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response( body = '[]' )+ self.assertEqual( self.client.get_events(), [] )++ def test_get_events_returns_parsed_list(self):+ payload = [+ { 'id': '2', 'camera': 'front_yard', 'label': 'dog' },+ { 'id': '1', 'camera': 'front_yard', 'label': 'person' },+ ]+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response( body = json.dumps( payload ) )+ result = self.client.get_events()+ self.assertEqual( result, payload )++ def test_get_events_passes_after_as_query_param(self):+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response( body = '[]' )+ self.client.get_events( after = 1234567890.5 )+ kwargs = mock_get.call_args.kwargs+ self.assertEqual( kwargs[ 'params' ], { 'after': 1234567890.5 } )++ def test_get_events_passes_limit_as_query_param(self):+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response( body = '[]' )+ self.client.get_events( after = 0, limit = 50 )+ kwargs = mock_get.call_args.kwargs+ self.assertEqual( kwargs[ 'params' ], { 'after': 0, 'limit': 50 } )++ def test_get_events_omits_params_when_no_filters(self):+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response( body = '[]' )+ self.client.get_events()+ kwargs = mock_get.call_args.kwargs+ self.assertIsNone( kwargs[ 'params' ] )++ def test_get_events_raises_when_response_not_list(self):+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response( body = '{"events": []}' )+ with self.assertRaises( ValueError ) as ctx:+ self.client.get_events()+ self.assertIn( 'not a list', str( ctx.exception ) )++ def test_get_events_raises_on_non_2xx(self):+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response(+ status_code = 500, body = 'Internal Server Error',+ )+ with self.assertRaises( ValueError ) as ctx:+ self.client.get_events()+ self.assertIn( '500', str( ctx.exception ) )+++class TestFrigateClientGetEvent( TestCase ):++ def setUp(self):+ self.client = FrigateClient( api_options = {+ FrigateClient.BASE_URL: 'http://frigate.local:5000',+ })++ def test_get_event_returns_parsed_dict(self):+ payload = {+ 'id': '42', 'camera': 'front_yard', 'label': 'person',+ 'top_score': 0.9,+ }+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response( body = json.dumps( payload ) )+ self.assertEqual( self.client.get_event( '42' ), payload )++ def test_get_event_targets_correct_url(self):+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response( body = '{"id": "42"}' )+ self.client.get_event( '42' )+ url = mock_get.call_args.args[ 0 ]+ self.assertEqual(+ url,+ 'http://frigate.local:5000/api/events/42',+ )++ def test_get_event_raises_http404_on_404(self):+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response(+ status_code = 404, body = 'Not Found',+ )+ with self.assertRaises( Http404 ):+ self.client.get_event( 'nope' )++ def test_get_event_raises_when_response_not_dict(self):+ with patch( 'hi.services.frigate.frigate_client.get' ) as mock_get:+ mock_get.return_value = _mock_response( body = '[]' )+ with self.assertRaises( ValueError ) as ctx:+ self.client.get_event( '1' )+ self.assertIn( 'not a JSON object', str( ctx.exception ) )++diff --git a/src/hi/services/frigate/tests/test_frigate_integration.py b/src/hi/services/frigate/tests/test_frigate_integration.pynew file mode 100644index 00000000..a007570e--- /dev/null+++ b/src/hi/services/frigate/tests/test_frigate_integration.py@@ -0,0 +1,402 @@+"""Gateway-level + manager URL-helper tests for the Frigate integration.++These cover:+ * ``FrigateManager.get_camera_snapshot_url`` / ``get_event_snapshot_url``+ — the URL helpers HI uses to point at Frigate's still-image+ endpoints.+ * ``FrigateGateway.get_entity_video_snapshot`` — entry point the+ presentation layer uses to fetch a live snapshot for a camera+ entity.+ * ``FrigateManager._reload_implementation`` health-recording —+ keeps the aggregate health honest so the UI banner doesn't show+ a degraded state while the monitor is reporting Healthy.+"""+import logging+from unittest.mock import Mock, patch++from django.test import TestCase++from hi.apps.entity.enums import EntityType+from hi.apps.entity.models import Entity+from hi.apps.system.enums import ApiHealthStatusType+from hi.integrations.models import Integration++from hi.apps.entity.enums import VideoStreamType+from hi.apps.sense.transient_models import SensorResponse+from hi.services.frigate.enums import FrigateAttributeType+from hi.services.frigate.frigate_manager import FrigateManager+from hi.services.frigate.frigate_metadata import FrigateMetaData+from hi.services.frigate.integration import FrigateGateway+from hi.integrations.models import IntegrationAttribute+from hi.integrations.transient_models import IntegrationKey++logging.disable( logging.CRITICAL )+++class TestFrigateManagerSnapshotUrls( TestCase ):+ """Helpers that build the still-image URLs HI emits in <img>+ tags (camera snapshot) and on SensorResponses (event snapshot).+ Returning ``None`` when the client is unavailable lets callers+ treat "no client yet" the same as "no snapshot capability"."""++ def setUp(self):+ self.manager = FrigateManager()+ self.mock_client = Mock( base_url = 'http://frigate.example' )++ def test_camera_snapshot_url_uses_latest_jpg_path(self):+ with patch.object(+ type( self.manager ), 'frigate_client',+ new_callable = lambda: property( lambda _ : self.mock_client ),+ ):+ url = self.manager.get_camera_snapshot_url( camera_name = 'front_yard' )+ self.assertIsNotNone( url )+ self.assertTrue( url.startswith( 'http://frigate.example/api/front_yard/latest.jpg' ) )+ # Cache-bust param keeps re-rendered <img> tags from showing+ # the prior frame.+ self.assertIn( '_t=', url )++ def test_event_snapshot_url_uses_events_snapshot_jpg_path(self):+ with patch.object(+ type( self.manager ), 'frigate_client',+ new_callable = lambda: property( lambda _ : self.mock_client ),+ ):+ url = self.manager.get_event_snapshot_url( event_id = '42' )+ self.assertIsNotNone( url )+ self.assertTrue(+ url.startswith( 'http://frigate.example/api/events/42/snapshot.jpg' )+ )+ self.assertIn( '_t=', url )++ def test_snapshot_urls_return_none_when_client_unavailable(self):+ """Integration disabled / unconfigured ⇒ no client ⇒ no URL.+ Callers must treat ``None`` as "no snapshot capability"."""+ with patch.object(+ type( self.manager ), 'frigate_client',+ new_callable = lambda: property( lambda _ : None ),+ ):+ self.assertIsNone(+ self.manager.get_camera_snapshot_url( camera_name = 'front_yard' )+ )+ self.assertIsNone(+ self.manager.get_event_snapshot_url( event_id = '42' )+ )+++class TestFrigateGatewayVideoSnapshot( TestCase ):+ """``FrigateGateway.get_entity_video_snapshot`` — the presentation+ layer's entry point for a live still frame on a Frigate camera+ entity. Should return ``None`` for non-Frigate entities, entities+ that have opted out (``has_video_snapshot=False``), or when no+ client is available; otherwise a ``VideoSnapshot`` pointing at+ the live JPEG URL."""++ def setUp(self):+ self.gateway = FrigateGateway()++ def _make_camera_entity( self,+ integration_name : str = 'camera.front_yard',+ has_video_snapshot : bool = True,+ integration_id : str = None ) -> Entity:+ return Entity.objects.create(+ name = 'Front Yard',+ entity_type_str = str( EntityType.CAMERA ),+ integration_id = integration_id or FrigateMetaData.integration_id,+ integration_name = integration_name,+ has_video_snapshot = has_video_snapshot,+ has_video_stream = True,+ )++ def test_returns_snapshot_for_frigate_camera_entity(self):+ entity = self._make_camera_entity()+ with patch.object(+ FrigateManager, 'get_camera_snapshot_url',+ return_value = 'http://frigate.example/api/front_yard/latest.jpg?_t=1',+ ):+ snapshot = self.gateway.get_entity_video_snapshot( entity = entity )+ self.assertIsNotNone( snapshot )+ self.assertEqual(+ snapshot.source_url,+ 'http://frigate.example/api/front_yard/latest.jpg?_t=1',+ )+ self.assertEqual( snapshot.metadata, { 'camera_name': 'front_yard' } )++ def test_returns_none_when_entity_opts_out_of_snapshots(self):+ entity = self._make_camera_entity( has_video_snapshot = False )+ self.assertIsNone( self.gateway.get_entity_video_snapshot( entity = entity ))++ def test_returns_none_for_non_frigate_entity(self):+ entity = self._make_camera_entity( integration_id = 'some.other.integration' )+ self.assertIsNone( self.gateway.get_entity_video_snapshot( entity = entity ))++ def test_returns_none_when_integration_name_lacks_camera_prefix(self):+ """Defensive: integration_name should always start with+ ``camera.`` for a Frigate camera entity, but a stray+ non-camera Frigate row shouldn't crash the snapshot path."""+ entity = self._make_camera_entity( integration_name = 'system' )+ self.assertIsNone( self.gateway.get_entity_video_snapshot( entity = entity ))++ def test_returns_none_when_manager_has_no_client(self):+ """When the client isn't built yet (integration disabled),+ ``get_camera_snapshot_url`` returns ``None`` — the gateway+ propagates that as "no snapshot capability"."""+ entity = self._make_camera_entity()+ with patch.object(+ FrigateManager, 'get_camera_snapshot_url', return_value = None,+ ):+ self.assertIsNone( self.gateway.get_entity_video_snapshot( entity = entity ))+++class TestFrigateManagerEventClipUrl( TestCase ):++ def setUp(self):+ self.manager = FrigateManager()+ self.mock_client = Mock( base_url = 'http://frigate.example' )++ def test_event_clip_url_uses_clip_mp4_path(self):+ with patch.object(+ type( self.manager ), 'frigate_client',+ new_callable = lambda: property( lambda _ : self.mock_client ),+ ):+ url = self.manager.get_event_clip_url( event_id = '42' )+ self.assertIsNotNone( url )+ self.assertTrue(+ url.startswith( 'http://frigate.example/api/events/42/clip.mp4' )+ )+ self.assertIn( '_t=', url )++ def test_event_clip_url_returns_none_when_client_unavailable(self):+ with patch.object(+ type( self.manager ), 'frigate_client',+ new_callable = lambda: property( lambda _ : None ),+ ):+ self.assertIsNone( self.manager.get_event_clip_url( event_id = '42' ))+++class TestFrigateGatewayEventSnapshotUrl( TestCase ):+ """``FrigateGateway.get_sensor_response_event_snapshot_url``+ builds the snapshot URL fresh from the response's correlation_id+ each call so the URL always reflects current manager state."""++ def setUp(self):+ self.gateway = FrigateGateway()++ def _make_response( self, has_snapshot = True, correlation_id = 'evt-1' ):+ from datetime import datetime+ return SensorResponse(+ integration_key = IntegrationKey(+ integration_id = FrigateMetaData.integration_id,+ integration_name = 'camera.object.front_yard',+ ),+ value = 'object_person',+ timestamp = datetime.now(),+ correlation_id = correlation_id,+ has_event_video_snapshot = has_snapshot,+ )++ def test_returns_url_for_snapshot_bearing_response(self):+ response = self._make_response()+ with patch.object(+ FrigateManager, 'get_event_snapshot_url',+ return_value = 'http://frigate.example/api/events/evt-1/snapshot.jpg?_t=1',+ ):+ url = self.gateway.get_sensor_response_event_snapshot_url(+ sensor_response = response,+ )+ self.assertEqual(+ url, 'http://frigate.example/api/events/evt-1/snapshot.jpg?_t=1',+ )++ def test_returns_none_when_response_has_no_snapshot(self):+ response = self._make_response( has_snapshot = False )+ self.assertIsNone(+ self.gateway.get_sensor_response_event_snapshot_url(+ sensor_response = response,+ )+ )++ def test_returns_none_when_response_has_no_correlation_id(self):+ response = self._make_response( correlation_id = None )+ self.assertIsNone(+ self.gateway.get_sensor_response_event_snapshot_url(+ sensor_response = response,+ )+ )+++class TestFrigateGatewayVideoStream( TestCase ):+ """``FrigateGateway.get_sensor_response_video_stream`` returns+ the event clip MP4 URL for SensorResponses carrying a clip; None+ otherwise (no clip flag, no event id, or no client)."""++ def setUp(self):+ self.gateway = FrigateGateway()++ def _make_response(+ self, has_clip = True, correlation_id = 'evt-1',+ ) -> SensorResponse:+ from datetime import datetime+ return SensorResponse(+ integration_key = IntegrationKey(+ integration_id = FrigateMetaData.integration_id,+ integration_name = 'camera.object.front_yard',+ ),+ value = 'object_person',+ timestamp = datetime.now(),+ correlation_id = correlation_id,+ has_event_video_clip = has_clip,+ )++ def test_returns_mp4_stream_for_clip_bearing_response(self):+ response = self._make_response()+ with patch.object(+ FrigateManager, 'get_event_clip_url',+ return_value = 'http://frigate.example/api/events/evt-1/clip.mp4?_t=1',+ ):+ stream = self.gateway.get_sensor_response_video_stream(+ sensor_response = response,+ )+ self.assertIsNotNone( stream )+ self.assertEqual( stream.stream_type, VideoStreamType.MP4 )+ self.assertEqual(+ stream.source_url,+ 'http://frigate.example/api/events/evt-1/clip.mp4?_t=1',+ )+ self.assertEqual( stream.metadata, { 'event_id': 'evt-1' } )++ def test_returns_none_when_response_has_no_clip(self):+ response = self._make_response( has_clip = False )+ self.assertIsNone(+ self.gateway.get_sensor_response_video_stream( sensor_response = response )+ )++ def test_returns_none_when_response_has_no_correlation_id(self):+ response = self._make_response( correlation_id = None )+ self.assertIsNone(+ self.gateway.get_sensor_response_video_stream( sensor_response = response )+ )++ def test_returns_none_when_manager_has_no_client(self):+ response = self._make_response()+ with patch.object(+ FrigateManager, 'get_event_clip_url', return_value = None,+ ):+ self.assertIsNone(+ self.gateway.get_sensor_response_video_stream( sensor_response = response )+ )+++class TestFrigateManagerHealthRecording( TestCase ):+ """``FrigateManager._reload_implementation`` must record its own+ API-health outcome on every reload. The manager registers itself+ as an API health provider; without an explicit record_* call the+ default UNKNOWN status leaks into the aggregate and the UI banner+ shows WARNING even when the monitor is reporting Healthy.++ Mirrors ``ZoneMinderManager._reload_implementation`` — same bug+ pattern, same fix shape."""++ def setUp(self):+ # Fresh manager per test — the singleton retains health state+ # across tests otherwise.+ self.manager = FrigateManager()++ def test_no_integration_row_marks_disabled(self):+ Integration.objects.filter(+ integration_id = FrigateMetaData.integration_id,+ ).delete()+ self.manager._reload_implementation()+ self.assertEqual(+ self.manager.api_health_status.status,+ ApiHealthStatusType.DISABLED,+ )+ self.assertIsNone( self.manager._frigate_client )++ def test_disabled_integration_marks_disabled(self):+ integration, _ = Integration.objects.get_or_create(+ integration_id = FrigateMetaData.integration_id,+ defaults = { 'is_enabled': False },+ )+ integration.is_enabled = False+ integration.save()+ self.manager._reload_implementation()+ self.assertEqual(+ self.manager.api_health_status.status,+ ApiHealthStatusType.DISABLED,+ )++ def test_successful_reload_marks_healthy(self):+ integration, _ = Integration.objects.get_or_create(+ integration_id = FrigateMetaData.integration_id,+ defaults = { 'is_enabled': True },+ )+ integration.is_enabled = True+ integration.save()+ with patch(+ 'hi.services.frigate.frigate_manager.FrigateClientFactory.create_client',+ return_value = Mock( base_url = 'http://frigate.example' ),+ ):+ self.manager._reload_implementation()+ self.assertEqual(+ self.manager.api_health_status.status,+ ApiHealthStatusType.HEALTHY,+ )+ self.assertIsNotNone( self.manager._frigate_client )++ def test_client_build_failure_marks_unavailable(self):+ integration, _ = Integration.objects.get_or_create(+ integration_id = FrigateMetaData.integration_id,+ defaults = { 'is_enabled': True },+ )+ integration.is_enabled = True+ integration.save()+ with patch(+ 'hi.services.frigate.frigate_manager.FrigateClientFactory.create_client',+ side_effect = ValueError( 'Base URL is required.' ),+ ):+ self.manager._reload_implementation()+ # record_error pushes the API status to UNAVAILABLE so the+ # aggregate maps the manager's own slot to ERROR rather than+ # the leak-through WARNING that UNKNOWN would produce.+ self.assertEqual(+ self.manager.api_health_status.status,+ ApiHealthStatusType.UNAVAILABLE,+ )+ self.assertIsNone( self.manager._frigate_client )+++class TestFrigateManagerShouldAddAlarmEvents( TestCase ):+ """``FrigateManager.should_add_alarm_events`` reads the boolean+ ``ADD_ALARM_EVENTS`` integration attribute. Default off so a+ freshly-imported install isn't unexpectedly noisy with alarms."""++ def setUp(self):+ self.manager = FrigateManager()+ # Bypass ensure_initialized so the test fixture's+ # _attribute_map isn't clobbered by a reload triggered on+ # first property read.+ self.manager._was_initialized = True+ self.manager._attribute_map = {}++ def _make_attribute( self, value : str ) -> IntegrationAttribute:+ return IntegrationAttribute(+ integration_key = IntegrationKey(+ integration_id = FrigateMetaData.integration_id,+ integration_name = str( FrigateAttributeType.ADD_ALARM_EVENTS ),+ ),+ value = value,+ )++ def test_default_when_attribute_absent_is_false(self):+ self.assertFalse( self.manager.should_add_alarm_events )++ def test_attribute_true_value_returns_true(self):+ self.manager._attribute_map = {+ FrigateAttributeType.ADD_ALARM_EVENTS: self._make_attribute( 'True' ),+ }+ self.assertTrue( self.manager.should_add_alarm_events )++ def test_attribute_false_value_returns_false(self):+ self.manager._attribute_map = {+ FrigateAttributeType.ADD_ALARM_EVENTS: self._make_attribute( 'False' ),+ }+ self.assertFalse( self.manager.should_add_alarm_events )diff --git a/src/hi/services/frigate/tests/test_frigate_monitor.py b/src/hi/services/frigate/tests/test_frigate_monitor.pynew file mode 100644index 00000000..88be3bd0--- /dev/null+++ b/src/hi/services/frigate/tests/test_frigate_monitor.py@@ -0,0 +1,755 @@+"""Tests for the FrigateMonitor polling pipeline.++Frigate's ``?after=T`` filters strictly on ``start_time > T``, so+once the cursor advances past an event's start_time that event is+invisible to cursor scans even after it closes. The pipeline mixes+a monotonic cursor scan for new events with a per-id direct refresh+for events currently in the open-tracking set. These tests cover+each phase's invariants and the open→closed transition that the+cursor-only approach drops.+"""+import logging+from datetime import datetime, timedelta, timezone+from unittest.mock import Mock, patch++from django.test import TestCase++from hi.apps.entity.enums import EntityStateValue+from hi.apps.sense.enums import CorrelationRole+from hi.testing.async_task_utils import AsyncTaskFastTestCase++from hi.services.frigate.frigate_converter import FrigateConverter+from hi.services.frigate.frigate_models import FrigateEvent+from hi.services.frigate.frigate_manager import FrigateManager+from hi.services.frigate.monitors import FrigateMonitor++logging.disable( logging.CRITICAL )+++def _make_event(+ event_id : str,+ camera_name : str = 'front_yard',+ start : datetime = None,+ end : datetime = None,+ label : str = 'person',+ has_clip : bool = True ) -> FrigateEvent:+ if start is None:+ start = datetime( 2026, 5, 20, 12, 0, 0, tzinfo = timezone.utc )+ return FrigateEvent(+ event_id = event_id,+ camera_name = camera_name,+ object_class = label,+ start_datetime = start,+ end_datetime = end,+ has_clip = has_clip,+ )+++class TestFrigateEventDetailAttrs( TestCase ):+ """``_build_event_detail_attrs`` packs a FrigateEvent's metadata+ into the dict that's persisted on SensorResponse.detail_attrs and+ surfaced in the event-detail UI. The keys are wire-stable (see+ FrigateDetailKeys docstring) so regressions need a guard here."""++ def setUp(self):+ self.monitor = FrigateMonitor()+ self.t0 = datetime( 2026, 5, 20, 12, 0, 0, tzinfo = timezone.utc )++ def test_open_event_packs_metadata_without_duration(self):+ opened = _make_event(+ event_id = '99', start = self.t0, label = 'person',+ )+ opened.score = 0.91+ opened.sub_label = 'jane_doe'+ opened.zones = [ 'driveway', 'walkway' ]++ attrs = self.monitor._build_event_detail_attrs(+ event = opened, is_closed = False,+ )+ from hi.services.frigate.constants import FrigateDetailKeys+ self.assertEqual( attrs[ FrigateDetailKeys.EVENT_ID ], '99' )+ self.assertEqual( attrs[ FrigateDetailKeys.OBJECT_CLASS ], 'person' )+ self.assertEqual( attrs[ FrigateDetailKeys.SCORE ], '0.91' )+ self.assertEqual( attrs[ FrigateDetailKeys.SUB_LABEL ], 'jane_doe' )+ self.assertEqual(+ attrs[ FrigateDetailKeys.ZONES ], 'driveway, walkway',+ )+ # Duration is omitted while the event is open — value isn't+ # known until the event closes.+ self.assertNotIn( FrigateDetailKeys.DURATION_SECS, attrs )++ def test_closed_event_includes_duration(self):+ closed = _make_event(+ event_id = '7',+ start = self.t0,+ end = self.t0 + timedelta( seconds = 15 ),+ )+ attrs = self.monitor._build_event_detail_attrs(+ event = closed, is_closed = True,+ )+ from hi.services.frigate.constants import FrigateDetailKeys+ self.assertEqual( attrs[ FrigateDetailKeys.DURATION_SECS ], '15.0' )+++class TestFrigateNoEventIdleResponse( TestCase ):+ """The no-event-this-cycle response that keeps every camera's+ OBJECT_PRESENCE fresh even when nothing happened in the poll+ window."""++ def setUp(self):+ self.monitor = FrigateMonitor()+ self.now = datetime( 2026, 5, 20, 12, 0, 0, tzinfo = timezone.utc )++ def test_uses_object_presence_key_with_object_none_value(self):+ resp = self.monitor._create_object_presence_sensor_response(+ camera_name = 'driveway',+ value = FrigateConverter.OBJECT_NONE_VALUE,+ timestamp = self.now,+ )+ self.assertEqual( resp.value, str( EntityStateValue.OBJECT_NONE ) )+ self.assertEqual( resp.timestamp, self.now )+ self.assertEqual(+ resp.integration_key.integration_name,+ f'{FrigateManager.OBJECT_PRESENCE_SENSOR_PREFIX}.driveway',+ )++ def test_no_correlation_on_unseen_cycle_response(self):+ """No correlation id on the no-event-this-cycle response —+ there's no event to pair with."""+ resp = self.monitor._create_object_presence_sensor_response(+ camera_name = 'driveway',+ value = FrigateConverter.OBJECT_NONE_VALUE,+ timestamp = self.now,+ )+ self.assertIsNone( resp.correlation_role )+ self.assertIsNone( resp.correlation_id )+++class TestFrigateEventFromApiDict( TestCase ):+ """``FrigateEvent.from_api_dict`` is the wire-to-model boundary+ where bad payloads need to surface with a useful error."""++ def test_parses_open_event(self):+ api_dict = {+ 'id': '42',+ 'camera': 'front_yard',+ 'label': 'person',+ 'start_time': 1747750800.0,+ 'end_time': None,+ 'top_score': 0.91,+ 'sub_label': None,+ 'zones': [ 'driveway' ],+ }+ event = FrigateEvent.from_api_dict( api_dict )+ self.assertEqual( event.event_id, '42' )+ self.assertEqual( event.camera_name, 'front_yard' )+ self.assertEqual( event.object_class, 'person' )+ self.assertTrue( event.is_open )+ self.assertFalse( event.is_closed )+ self.assertEqual( event.score, 0.91 )+ self.assertEqual( event.zones, [ 'driveway' ] )++ def test_parses_closed_event(self):+ start_epoch = 1747750800.0+ end_epoch = start_epoch + 30+ api_dict = {+ 'id': '42',+ 'camera': 'front_yard',+ 'label': 'car',+ 'start_time': start_epoch,+ 'end_time': end_epoch,+ }+ event = FrigateEvent.from_api_dict( api_dict )+ self.assertTrue( event.is_closed )+ self.assertFalse( event.is_open )+ self.assertEqual(+ event.start_datetime,+ datetime.fromtimestamp( start_epoch, tz = timezone.utc ),+ )+ self.assertEqual(+ event.end_datetime,+ datetime.fromtimestamp( end_epoch, tz = timezone.utc ),+ )++ def test_parses_has_clip_field(self):+ # Real Frigate emits has_clip / has_snapshot booleans per+ # event; HI carries them through to gate UI playback+ # affordances.+ api_dict = {+ 'id': '42', 'camera': 'front_yard', 'label': 'person',+ 'start_time': 1747750800.0, 'has_clip': False, 'has_snapshot': True,+ }+ event = FrigateEvent.from_api_dict( api_dict )+ self.assertFalse( event.has_clip )+ self.assertTrue( event.has_snapshot )++ def test_has_clip_defaults_to_true_when_absent(self):+ # Older Frigate responses don't carry the boolean. Default to+ # True (Frigate's own startup default).+ event = FrigateEvent.from_api_dict({+ 'id': '42', 'camera': 'front_yard', 'label': 'person',+ 'start_time': 1747750800.0,+ })+ self.assertTrue( event.has_clip )++ def test_missing_required_field_raises(self):+ with self.assertRaises( ValueError ) as ctx:+ FrigateEvent.from_api_dict({+ 'id': '42', 'camera': 'front_yard',+ # missing label + start_time+ })+ self.assertIn( 'missing required field', str( ctx.exception ) )+++class TestFrigateConverterObjectClassMapping( TestCase ):+ """Raw Frigate label → canonical OBJECT_PRESENCE bucket. The+ table is integration-specific (no other integration maps to this+ enum yet) but the contract is stable: unknown labels bucket into+ ``OBJECT_OTHER`` rather than disappearing as ``OBJECT_NONE``."""++ def test_person_maps_to_object_person(self):+ self.assertEqual(+ FrigateConverter.to_canonical_object_class( 'person' ),+ str( EntityStateValue.OBJECT_PERSON ),+ )++ def test_vehicles_bucket_to_object_car(self):+ for raw in [ 'car', 'truck', 'bus', 'motorcycle', 'bicycle' ]:+ with self.subTest( raw = raw ):+ self.assertEqual(+ FrigateConverter.to_canonical_object_class( raw ),+ str( EntityStateValue.OBJECT_CAR ),+ )+ continue++ def test_animals_bucket_to_object_animal(self):+ for raw in [ 'dog', 'cat', 'bird', 'horse', 'cow', 'bear',+ 'deer', 'raccoon', 'fox', 'squirrel', 'rabbit' ]:+ with self.subTest( raw = raw ):+ self.assertEqual(+ FrigateConverter.to_canonical_object_class( raw ),+ str( EntityStateValue.OBJECT_ANIMAL ),+ )+ continue++ def test_package_maps_to_object_package(self):+ self.assertEqual(+ FrigateConverter.to_canonical_object_class( 'package' ),+ str( EntityStateValue.OBJECT_PACKAGE ),+ )++ def test_unknown_label_falls_through_to_object_other(self):+ """Custom-model classes that nobody's bucketed yet still+ register as "something is here" rather than disappearing into+ OBJECT_NONE."""+ for raw in [ 'unicorn', 'drone', 'frog', '' ]:+ with self.subTest( raw = raw ):+ self.assertEqual(+ FrigateConverter.to_canonical_object_class( raw ),+ str( EntityStateValue.OBJECT_OTHER ),+ )+ continue++ def test_label_lookup_is_case_insensitive(self):+ self.assertEqual(+ FrigateConverter.to_canonical_object_class( 'PERSON' ),+ str( EntityStateValue.OBJECT_PERSON ),+ )+ self.assertEqual(+ FrigateConverter.to_canonical_object_class( 'Dog' ),+ str( EntityStateValue.OBJECT_ANIMAL ),+ )+++class _PipelineTestBase( AsyncTaskFastTestCase ):+ """Shared scaffolding for the cursor + per-id refresh pipeline.++ Frigate's ``?after=T`` filters strictly on ``start_time > T``, so+ the cursor advances monotonically over each event's start_time and+ open events are tracked by id and refreshed via direct fetch. These+ tests verify each phase's invariants in isolation and across the+ open→closed transition.+ """++ def setUp(self):+ self.monitor = FrigateMonitor()+ self.monitor._was_initialized = True+ self.start = datetime( 2026, 5, 20, 12, 0, 0, tzinfo = timezone.utc )+ self.monitor._poll_cursor_datetime = self.start+ self.monitor._tracked_events = {}++ # Pin ``datetimeproxy.now`` to ``self.start`` so phase-2 age+ # math operates on test-relative time. Without this, real+ # wall-clock vs ``self.start`` is ~years apart and seeded+ # open events always look aged-out.+ self._now_patcher = patch(+ 'hi.services.frigate.monitors.datetimeproxy.now',+ return_value = self.start,+ )+ self._now_patcher.start()+ self.addCleanup( self._now_patcher.stop )++ self.mock_manager = Mock( spec = FrigateManager )++ async def empty_events( after = None, limit = None ):+ return []++ async def empty_cameras():+ return []++ async def event_not_found( event_id ):+ from django.http import Http404+ raise Http404( event_id )++ self.mock_manager.get_events_async = Mock( side_effect = empty_events )+ self.mock_manager.get_cameras_async = Mock( side_effect = empty_cameras )+ self.mock_manager.get_event_async = Mock( side_effect = event_not_found )+ self.monitor._frigate_manager = self.mock_manager+ return++ def _set_events(self, events_api_list):+ async def fake_events( after = None, limit = None ):+ return events_api_list++ self.mock_manager.get_events_async = Mock( side_effect = fake_events )++ def _set_event_by_id(self, by_id):+ async def fake_event( event_id ):+ from django.http import Http404+ if event_id not in by_id:+ raise Http404( event_id )+ return by_id[ event_id ]++ self.mock_manager.get_event_async = Mock( side_effect = fake_event )++ def _set_cameras(self, names):+ async def fake_cameras():+ return [ { 'name': n, 'config': {} } for n in names ]++ self.mock_manager.get_cameras_async = Mock( side_effect = fake_cameras )++ def _api_event(+ self,+ event_id = '1',+ camera_name = 'front_yard',+ label = 'person',+ start = None,+ end = None,+ has_clip = True,+ has_snapshot = True,+ ):+ if start is None:+ start = self.start + timedelta( seconds = 1 )+ return {+ 'id': event_id,+ 'camera': camera_name,+ 'label': label,+ 'start_time': start.timestamp(),+ 'end_time': end.timestamp() if end is not None else None,+ 'has_clip': has_clip,+ 'has_snapshot': has_snapshot,+ }++ def _find_response(self, responses, camera_name):+ target = f'{FrigateManager.OBJECT_PRESENCE_SENSOR_PREFIX}.{camera_name}'+ for r in responses.values():+ if r.integration_key.integration_name == target:+ return r+ continue+ raise AssertionError( f'No OBJECT_PRESENCE response for {camera_name!r}' )++ async def _run(self):+ return await self.monitor._process_events()+++class TestFrigateScanNewEventsPhase( _PipelineTestBase ):+ """Phase 1: ``?after=cursor`` scan.++ Cursor advance is monotonic on ``start_time``. Each event seen+ here is brand-new to us; START is always emitted, END too if the+ event was already closed when first observed (lifetime shorter+ than poll interval)."""++ def test_cursor_unchanged_when_no_events(self):+ self.run_async( self._run() )+ self.assertEqual( self.monitor._poll_cursor_datetime, self.start )++ def test_cursor_advances_to_latest_start_time(self):+ s1 = self.start + timedelta( seconds = 5 )+ s2 = self.start + timedelta( seconds = 20 )+ self._set_events([+ self._api_event( event_id = '1', start = s1 ),+ self._api_event( event_id = '2', start = s2,+ end = s2 + timedelta( seconds = 10 )),+ ])+ # Phase 2 will refresh id '1'; pretend Frigate still has it.+ self._set_event_by_id({+ '1': self._api_event( event_id = '1', start = s1 ),+ })+ self.run_async( self._run() )+ self.assertEqual( self.monitor._poll_cursor_datetime, s2 )++ def test_open_event_enters_tracked_set_and_emits_start(self):+ """The open→closed transition bug fix: after the open event+ is seen once, the cursor advances PAST its start_time. Future+ cursor scans won't return it — phase 2 must track it by id."""+ open_start = self.start + timedelta( seconds = 5 )+ self._set_events([+ self._api_event( event_id = 'A', start = open_start, end = None ),+ ])+ self._set_event_by_id({+ 'A': self._api_event( event_id = 'A', start = open_start, end = None ),+ })+ responses = self.run_async( self._run() )++ self.assertIn( 'A', self.monitor._tracked_events )+ self.assertEqual( self.monitor._poll_cursor_datetime, open_start )++ obj = self._find_response( responses, 'front_yard' )+ self.assertEqual( obj.value, str( EntityStateValue.OBJECT_PERSON ) )+ self.assertEqual( obj.correlation_role, CorrelationRole.START )+ self.assertEqual( obj.correlation_id, 'A' )++ def test_open_and_closed_within_one_cycle_emits_both_rows(self):+ """Lifetime shorter than poll interval: a single scan returns+ the event already-closed. Emit START and END in this cycle,+ don't enter the open set."""+ s = self.start + timedelta( seconds = 5 )+ e = s + timedelta( seconds = 1 )+ self._set_events([+ self._api_event( event_id = 'X', start = s, end = e ),+ ])+ responses = self.run_async( self._run() )++ self.assertNotIn( 'X', self.monitor._tracked_events )+ # The map is keyed by integration_key so START and END for the+ # same camera collapse to one entry — the latest assignment+ # wins. END should be the survivor since it's assigned after.+ obj = self._find_response( responses, 'front_yard' )+ self.assertEqual( obj.correlation_role, CorrelationRole.END )+ self.assertEqual( obj.correlation_id, 'X' )++ def test_malformed_event_payload_is_skipped(self):+ s = self.start + timedelta( seconds = 5 )+ self._set_events([+ { 'id': 'bad', 'camera': 'front_yard' }, # missing label/start+ self._api_event( event_id = 'good', start = s,+ end = s + timedelta( seconds = 2 )),+ ])+ responses = self.run_async( self._run() )+ self.assertEqual(+ self._find_response( responses, 'front_yard' ).correlation_id,+ 'good',+ )++ def test_cursor_does_not_regress_when_event_returned_below_cursor(self):+ """Defensive: if upstream ever serves an event with+ ``start_time <= cursor`` (Frigate bug, replayed payload),+ the cursor must not move backward."""+ # Advance the cursor first so we have a meaningful "above".+ ahead = self.start + timedelta( seconds = 100 )+ self.monitor._poll_cursor_datetime = ahead++ # Return an event with start_time well below the cursor.+ stale_start = self.start + timedelta( seconds = 5 )+ self._set_events([+ self._api_event( event_id = 'stale', start = stale_start,+ end = stale_start + timedelta( seconds = 1 )),+ ])+ self.run_async( self._run() )+ self.assertEqual( self.monitor._poll_cursor_datetime, ahead )++ def test_duplicate_id_in_tracked_events_is_skipped(self):+ """Cursor is monotonic so phase 1 shouldn't see an id that's+ already in ``_tracked_events`` — but if it does (re-served by+ Frigate after a clock blip), the tracked event must not be+ replaced and no duplicate START must be emitted."""+ from hi.services.frigate.frigate_models import TrackedFrigateEvent+ existing_start = self.start + timedelta( seconds = 1 )+ existing = FrigateEvent(+ event_id = 'A',+ camera_name = 'front_yard',+ object_class = 'person',+ start_datetime = existing_start,+ )+ original_tracked_event = TrackedFrigateEvent(+ event = existing,+ first_observed_at = self.start,+ )+ self.monitor._tracked_events[ 'A' ] = original_tracked_event++ # Frigate returns the same id again (phase 2 will refresh it,+ # so set the by-id mock too).+ self._set_events([+ self._api_event( event_id = 'A', start = existing_start, end = None ),+ ])+ self._set_event_by_id({+ 'A': self._api_event( event_id = 'A', start = existing_start, end = None ),+ })+ self.run_async( self._run() )++ # Tracker object preserved (not replaced) — first_observed_at+ # would have rolled forward otherwise.+ self.assertIs( self.monitor._tracked_events[ 'A' ], original_tracked_event )+ self.assertEqual( original_tracked_event.first_observed_at, self.start )+++class TestFrigateRefreshTrackedEventsPhase( _PipelineTestBase ):+ """Phase 2: per-id refresh for events currently in the open set.++ Each refresh is one ``GET /api/events/<id>``. Closed → emit END,+ remove. 404 → force-close. Aged out → force-close. Still open →+ keep, refresh snapshot."""++ def _seed_open(+ self, event_id = 'A', camera = 'front_yard',+ first_observed_at = None,+ ):+ from hi.services.frigate.frigate_models import TrackedFrigateEvent+ if first_observed_at is None:+ first_observed_at = self.start+ start = self.start + timedelta( seconds = 1 )+ event = FrigateEvent(+ event_id = event_id,+ camera_name = camera,+ object_class = 'person',+ start_datetime = start,+ )+ self.monitor._tracked_events[ event_id ] = TrackedFrigateEvent(+ event = event,+ first_observed_at = first_observed_at,+ )+ # Advance cursor past the open event to mirror what phase 1+ # would have done.+ self.monitor._poll_cursor_datetime = start+ return event++ def test_closed_event_emits_end_and_clears_from_open_set(self):+ """The headline bug fix: a previously-open event, now closed+ in Frigate, must emit an END row with correlation_id matching+ the original event."""+ self._seed_open( event_id = 'A' )+ end_dt = self.start + timedelta( seconds = 30 )+ self._set_event_by_id({+ 'A': self._api_event(+ event_id = 'A',+ start = self.start + timedelta( seconds = 1 ),+ end = end_dt,+ ),+ })+ responses = self.run_async( self._run() )++ self.assertNotIn( 'A', self.monitor._tracked_events )+ obj = self._find_response( responses, 'front_yard' )+ self.assertEqual( obj.correlation_role, CorrelationRole.END )+ self.assertEqual( obj.correlation_id, 'A' )+ self.assertEqual( obj.value, str( EntityStateValue.OBJECT_NONE ) )+ self.assertEqual( obj.timestamp, end_dt )++ def test_still_open_event_stays_tracked(self):+ self._seed_open( event_id = 'A' )+ self._set_event_by_id({+ 'A': self._api_event(+ event_id = 'A',+ start = self.start + timedelta( seconds = 1 ),+ end = None,+ ),+ })+ self.run_async( self._run() )+ self.assertIn( 'A', self.monitor._tracked_events )++ def test_404_force_closes_and_removes(self):+ """Frigate dropped the event (cleared from history) → end the+ correlation pair with a synthesized END so the UI doesn't show+ a dangling start."""+ self._seed_open( event_id = 'gone' )+ self._set_event_by_id({}) # any id → 404+ responses = self.run_async( self._run() )++ self.assertNotIn( 'gone', self.monitor._tracked_events )+ obj = self._find_response( responses, 'front_yard' )+ self.assertEqual( obj.correlation_role, CorrelationRole.END )+ self.assertEqual( obj.correlation_id, 'gone' )++ def test_force_close_timeout_fires_on_aged_open_event(self):+ very_old = self.start - timedelta(+ seconds = self.monitor.MAX_OPEN_EVENT_AGE_SECS + 60,+ )+ self._seed_open( event_id = 'old', first_observed_at = very_old )+ self._set_event_by_id({+ 'old': self._api_event(+ event_id = 'old',+ start = self.start + timedelta( seconds = 1 ),+ end = None,+ ),+ })+ responses = self.run_async( self._run() )++ self.assertNotIn( 'old', self.monitor._tracked_events )+ obj = self._find_response( responses, 'front_yard' )+ self.assertEqual( obj.correlation_role, CorrelationRole.END )+ self.assertEqual( obj.correlation_id, 'old' )++ def test_transient_failure_keeps_event_and_does_not_force_close(self):+ """Non-404 failures (network blip, 500) shouldn't force-close+ unless the age timeout has also been crossed. Next cycle+ retries the refresh."""+ self._seed_open( event_id = 'A', first_observed_at = self.start )++ async def boom( event_id ):+ raise ValueError( 'simulated transport failure' )+ self.mock_manager.get_event_async = Mock( side_effect = boom )++ responses = self.run_async( self._run() )+ self.assertIn( 'A', self.monitor._tracked_events )+ # No END emitted for the still-tracked event.+ with self.assertRaises( AssertionError ):+ obj = self._find_response( responses, 'front_yard' )+ self.assertEqual( obj.correlation_role, CorrelationRole.END )++ def test_malformed_refresh_payload_leaves_event_tracked(self):+ """If the direct-fetch returns a payload we can't parse, the+ open event must stay in the tracking set so a later cycle can+ retry — dropping it silently would orphan the START with no+ END pair."""+ self._seed_open( event_id = 'A' )+ # By-id returns a dict missing required fields → from_api_dict+ # raises, and the refresh path logs + continues.+ self._set_event_by_id({+ 'A': { 'id': 'A', 'camera': 'front_yard' }, # no label / start_time+ })+ responses = self.run_async( self._run() )+ self.assertIn( 'A', self.monitor._tracked_events )+ # No END emitted for the still-tracked event.+ with self.assertRaises( AssertionError ):+ obj = self._find_response( responses, 'front_yard' )+ self.assertEqual( obj.correlation_role, CorrelationRole.END )+++class TestFrigateHeartbeatPhase( _PipelineTestBase ):+ """Phase 3: OBJECT_NONE heartbeat for cameras with no activity+ this cycle and no event in the open set. Without this, a camera+ that's been quiet since startup would never produce a response."""++ def test_idle_camera_gets_object_none_heartbeat(self):+ self._set_cameras([ 'driveway' ])+ responses = self.run_async( self._run() )+ obj = self._find_response( responses, 'driveway' )+ self.assertEqual( obj.value, str( EntityStateValue.OBJECT_NONE ) )+ self.assertIsNone( obj.correlation_role )++ def test_camera_with_open_event_skips_heartbeat(self):+ """A camera that's actively tracking an open event must not+ get an OBJECT_NONE clobber — phase 2's END (or future close)+ is what drives its state."""+ from hi.services.frigate.frigate_models import TrackedFrigateEvent+ event = FrigateEvent(+ event_id = 'A',+ camera_name = 'front_yard',+ object_class = 'person',+ start_datetime = self.start + timedelta( seconds = 1 ),+ )+ self.monitor._tracked_events[ 'A' ] = TrackedFrigateEvent(+ event = event,+ first_observed_at = self.start,+ )+ # Refresh keeps it open.+ self._set_event_by_id({+ 'A': self._api_event(+ event_id = 'A',+ start = self.start + timedelta( seconds = 1 ),+ end = None,+ ),+ })+ self._set_cameras([ 'front_yard', 'back_door' ])+ responses = self.run_async( self._run() )++ # back_door gets a heartbeat; front_yard does not get clobbered.+ back = self._find_response( responses, 'back_door' )+ self.assertEqual( back.value, str( EntityStateValue.OBJECT_NONE ) )+ self.assertIsNone( back.correlation_role )+ # front_yard's response should NOT be OBJECT_NONE — Phase 2+ # left it alone (event still open, no END this cycle).+ target = (+ f'{FrigateManager.OBJECT_PRESENCE_SENSOR_PREFIX}.front_yard'+ )+ for r in responses.values():+ if r.integration_key.integration_name == target:+ self.fail(+ 'front_yard should not receive a phase-3 heartbeat'+ ' while it has an open event in the tracking set.'+ )++ def test_camera_active_this_cycle_skips_heartbeat(self):+ """A camera whose START was emitted this cycle (phase 1) must+ not also get a phase-3 OBJECT_NONE."""+ s = self.start + timedelta( seconds = 5 )+ self._set_events([+ self._api_event( event_id = 'A', start = s, end = None ),+ ])+ self._set_event_by_id({+ 'A': self._api_event( event_id = 'A', start = s, end = None ),+ })+ self._set_cameras([ 'front_yard' ])+ responses = self.run_async( self._run() )++ obj = self._find_response( responses, 'front_yard' )+ # Phase 1's START survives — not overwritten by an OBJECT_NONE.+ self.assertEqual( obj.correlation_role, CorrelationRole.START )++ def test_camera_list_fetch_failure_does_not_break_pipeline(self):+ """A transient failure on ``get_cameras_async`` must not+ propagate — phases 1 and 2 may have produced legitimate+ responses that should still be delivered, just no heartbeat+ responses this cycle."""+ async def boom():+ raise ValueError( 'simulated camera list failure' )+ self.mock_manager.get_cameras_async = Mock( side_effect = boom )++ # No phase-1 or phase-2 activity either — pipeline must still+ # return a dict without raising.+ result = self.run_async( self._run() )+ self.assertEqual( result, {} )+++class TestFrigateOpenCloseTransitionAcrossCycles( _PipelineTestBase ):+ """End-to-end: the bug we're fixing. A typical motion event sees+ its open form on cycle N and its closed form on cycle N+1. The+ old pipeline lost the closure to Frigate's strict ``>`` filter on+ ``start_time``. The new pipeline tracks the event by id."""++ def test_open_then_close_emits_paired_start_and_end_rows(self):+ start_dt = self.start + timedelta( seconds = 5 )+ end_dt = self.start + timedelta( seconds = 30 )++ # Cycle 1: cursor scan returns the open event.+ self._set_events([+ self._api_event( event_id = 'evt', start = start_dt, end = None ),+ ])+ self._set_event_by_id({+ 'evt': self._api_event( event_id = 'evt', start = start_dt, end = None ),+ })+ cycle1 = self.run_async( self._run() )+ start_obj = self._find_response( cycle1, 'front_yard' )+ self.assertEqual( start_obj.correlation_role, CorrelationRole.START )+ self.assertEqual( start_obj.correlation_id, 'evt' )++ # Cycle 2: cursor scan returns nothing (cursor has advanced+ # past the event's start_time). Phase 2's direct fetch+ # returns the now-closed form → END emitted.+ self._set_events([])+ self._set_event_by_id({+ 'evt': self._api_event(+ event_id = 'evt', start = start_dt, end = end_dt,+ ),+ })+ cycle2 = self.run_async( self._run() )+ end_obj = self._find_response( cycle2, 'front_yard' )+ self.assertEqual( end_obj.correlation_role, CorrelationRole.END )+ self.assertEqual( end_obj.correlation_id, 'evt' )+ self.assertEqual( end_obj.timestamp, end_dt )++ # Open set is empty again — ready to receive the next event.+ self.assertEqual( self.monitor._tracked_events, {} )++diff --git a/src/hi/services/frigate/tests/test_frigate_sync.py b/src/hi/services/frigate/tests/test_frigate_sync.pynew file mode 100644index 00000000..aa7ff5e7--- /dev/null+++ b/src/hi/services/frigate/tests/test_frigate_sync.py@@ -0,0 +1,275 @@+import logging+from unittest.mock import Mock++from django.test import TestCase++from hi.apps.control.models import Controller+from hi.apps.entity.enums import EntityStateType, EntityType+from hi.apps.entity.models import Entity+from hi.apps.event.models import EventDefinition+from hi.apps.sense.models import Sensor++from hi.services.frigate.frigate_manager import FrigateManager+from hi.services.frigate.frigate_metadata import FrigateMetaData+from hi.services.frigate.frigate_sync import FrigateSynchronizer++logging.disable( logging.CRITICAL )+++class _FrigateSyncTestBase( TestCase ):++ def setUp(self):+ self.synchronizer = FrigateSynchronizer()+ self.mock_manager = Mock( spec = FrigateManager )+ # Default: alarm-event auto-creation off so tests that don't+ # care about it don't silently exercise the event-creation+ # path. Tests that need it set this to True explicitly.+ self.mock_manager.should_add_alarm_events = False+ self.synchronizer._frigate_manager = self.mock_manager++ def _set_upstream_cameras( self, cameras : list ) -> None:+ """Configure the mocked client to return the given camera list.++ ``cameras`` accepts either bare camera-name strings or+ ``(name, config_dict)`` tuples for tests that want to set+ per-camera config fields like ``friendly_name``."""+ self.mock_manager.frigate_client = Mock()+ normalized = []+ for entry in cameras:+ if isinstance( entry, tuple ):+ name, config = entry+ else:+ name, config = entry, { 'enabled': True }+ normalized.append( { 'name': name, 'config': config } )+ self.mock_manager.frigate_client.get_cameras.return_value = normalized+++class TestFrigateSyncImpl( _FrigateSyncTestBase ):++ def test_sync_returns_error_when_client_missing(self):+ self.mock_manager.frigate_client = None+ result = self.synchronizer._sync_impl( is_initial_import = True )+ self.assertEqual( result.title, 'Import Result' )+ self.assertEqual( len( result.error_list ), 1 )+ self.assertIn( 'integration disabled', result.error_list[0].lower() )+ self.assertEqual( Entity.objects.count(), 0 )++ def test_sync_creates_entity_with_object_presence_sensor(self):+ """Each Frigate camera becomes one HI CAMERA entity carrying+ a single OBJECT_PRESENCE sensor. Frigate couples motion to+ object detection (no motion-without-class signal on the events+ API), so OBJECT_PRESENCE subsumes the "is motion happening"+ signal and a separate MOVEMENT sensor would always mirror it."""+ self._set_upstream_cameras( [ 'front_yard' ] )+ result = self.synchronizer._sync_impl( is_initial_import = True )++ entities = list( Entity.objects.filter(+ integration_id = FrigateMetaData.integration_id,+ ))+ self.assertEqual( len( entities ), 1 )+ entity = entities[0]+ self.assertEqual( entity.name, 'front_yard' )+ self.assertEqual( entity.entity_type_str, str( EntityType.CAMERA ) )+ self.assertEqual( entity.integration_name, 'camera.front_yard' )+ # Frigate v1 has no native MJPEG/RTSP — the camera presents+ # as a pollable snapshot, not a native stream.+ self.assertFalse( entity.has_video_stream )+ self.assertTrue( entity.has_video_snapshot )+ self.assertEqual(+ entity.video_snapshot_stream_fps,+ self.synchronizer.CAMERA_SNAPSHOT_STREAM_FPS,+ )++ sensors = list( Sensor.objects.filter(+ entity_state__entity = entity,+ entity_state__entity_state_type_str = str( EntityStateType.OBJECT_PRESENCE ),+ ))+ self.assertEqual( len( sensors ), 1 )+ sensor = sensors[0]+ self.assertEqual( sensor.integration_name, 'camera.object.front_yard' )+ # Frigate stores a clip + snapshot per event by default;+ # advertise both capabilities so the Video Browse / history+ # views offer the playback affordances.+ self.assertTrue( sensor.provides_event_video_clip )+ self.assertTrue( sensor.provides_event_video_snapshot )++ # v1 exposes no Controllers — Frigate's only HTTP-reachable+ # operator-toggle (cameras.<name>.detect.enabled) is a config+ # edit rather than transient state, so we don't surface it+ # as a HI control. See FrigateController docstring.+ controllers = list( Controller.objects.filter( entity_state__entity = entity ))+ self.assertEqual( controllers, [] )++ self.assertIn( 'front_yard', result.created_list )+ self.assertEqual( result.error_list, [] )++ def test_sync_is_idempotent_for_existing_cameras(self):+ self._set_upstream_cameras( [ 'front_yard' ] )+ first = self.synchronizer._sync_impl( is_initial_import = True )+ self.assertEqual( len( first.created_list ), 1 )++ # Second sync against the same upstream — no new entities,+ # no new sensors, and no error rows.+ second = self.synchronizer._sync_impl( is_initial_import = False )+ self.assertEqual( second.created_list, [] )+ self.assertEqual( second.error_list, [] )+ self.assertEqual(+ Entity.objects.filter(+ integration_id = FrigateMetaData.integration_id,+ ).count(),+ 1,+ )+ object_presence_sensors = Sensor.objects.filter(+ entity_state__entity__integration_id = FrigateMetaData.integration_id,+ entity_state__entity_state_type_str = str( EntityStateType.OBJECT_PRESENCE ),+ )+ self.assertEqual( object_presence_sensors.count(), 1 )++ def test_sync_removes_entities_for_cameras_no_longer_present(self):+ self._set_upstream_cameras( [ 'front_yard', 'back_door' ] )+ self.synchronizer._sync_impl( is_initial_import = True )+ self.assertEqual(+ Entity.objects.filter(+ integration_id = FrigateMetaData.integration_id,+ ).count(),+ 2,+ )++ # Drop 'back_door' upstream. Refresh sync should remove it.+ self._set_upstream_cameras( [ 'front_yard' ] )+ result = self.synchronizer._sync_impl( is_initial_import = False )++ remaining_names = list( Entity.objects.filter(+ integration_id = FrigateMetaData.integration_id,+ ).values_list( 'name', flat = True ))+ self.assertEqual( remaining_names, [ 'front_yard' ] )+ self.assertEqual( result.error_list, [] )++ def test_sync_preserves_user_edited_name_on_update(self):+ self._set_upstream_cameras( [ 'front_yard' ] )+ self.synchronizer._sync_impl( is_initial_import = True )++ entity = Entity.objects.get(+ integration_id = FrigateMetaData.integration_id,+ )+ entity.name = 'Front Porch'+ # Toggle integration-owned flags away from the canonical+ # values so the update path has something to heal.+ entity.has_video_snapshot = False+ entity.video_snapshot_stream_fps = None+ entity.save()++ result = self.synchronizer._sync_impl( is_initial_import = False )++ entity.refresh_from_db()+ self.assertEqual( entity.name, 'Front Porch' )+ self.assertTrue( entity.has_video_snapshot )+ self.assertEqual(+ entity.video_snapshot_stream_fps,+ self.synchronizer.CAMERA_SNAPSHOT_STREAM_FPS,+ )+ self.assertEqual( result.error_list, [] )++ def test_sync_heals_stale_has_video_stream_flag(self):+ """Self-heal: entities created by the earlier sync revision+ flagged ``has_video_stream=True``, but Frigate v1 has no+ native stream. The update path must flip that off so the+ Live View pane routes to the snapshot-as-stream branch+ instead of the (broken) native-stream branch."""+ self._set_upstream_cameras( [ 'front_yard' ] )+ self.synchronizer._sync_impl( is_initial_import = True )++ entity = Entity.objects.get(+ integration_id = FrigateMetaData.integration_id,+ )+ entity.has_video_stream = True # simulate the stale shape+ entity.save( update_fields = [ 'has_video_stream' ] )++ self.synchronizer._sync_impl( is_initial_import = False )+ entity.refresh_from_db()+ self.assertFalse( entity.has_video_stream )++ def test_sync_uses_friendly_name_when_present(self):+ """Real Frigate carries a ``friendly_name`` on each camera's+ config for display; HI should prefer it over the snake_case+ camera key so the imported entity has a human-readable name."""+ self._set_upstream_cameras( [+ ( 'front_yard', { 'enabled': True, 'friendly_name': 'Front Yard' } ),+ ( 'back_door', { 'enabled': True } ), # no friendly_name+ ])+ self.synchronizer._sync_impl( is_initial_import = True )++ names_by_key = dict( Entity.objects.filter(+ integration_id = FrigateMetaData.integration_id,+ ).values_list( 'integration_name', 'name' ))+ self.assertEqual( names_by_key[ 'camera.front_yard' ], 'Front Yard' )+ # No friendly_name → falls back to the camera key.+ self.assertEqual( names_by_key[ 'camera.back_door' ], 'back_door' )++ def test_sync_creates_multiple_camera_entities(self):+ self._set_upstream_cameras( [ 'front_yard', 'back_door', 'driveway' ] )+ result = self.synchronizer._sync_impl( is_initial_import = True )++ names = set( Entity.objects.filter(+ integration_id = FrigateMetaData.integration_id,+ ).values_list( 'name', flat = True ))+ self.assertEqual( names, { 'front_yard', 'back_door', 'driveway' } )+ self.assertEqual( set( result.created_list ), names )++ # Placement input should carry one group with all three cameras.+ self.assertIsNotNone( result.placement_input )+ self.assertEqual( len( result.placement_input.groups ), 1 )+ self.assertEqual( result.placement_input.groups[0].label, 'Cameras' )+ self.assertEqual( len( result.placement_input.groups[0].items ), 3 )++ def test_sync_skips_event_definition_when_alarm_events_disabled(self):+ # Default in setUp is should_add_alarm_events=False.+ self._set_upstream_cameras( [ 'front_yard' ] )+ self.synchronizer._sync_impl( is_initial_import = True )+ self.assertEqual(+ EventDefinition.objects.filter(+ integration_id = FrigateMetaData.integration_id,+ ).count(),+ 0,+ )++ def test_sync_creates_event_definition_when_alarm_events_enabled(self):+ self.mock_manager.should_add_alarm_events = True+ self._set_upstream_cameras( [ 'front_yard' ] )+ self.synchronizer._sync_impl( is_initial_import = True )++ event_definitions = list( EventDefinition.objects.filter(+ integration_id = FrigateMetaData.integration_id,+ ))+ self.assertEqual( len( event_definitions ), 1 )+ event_definition = event_definitions[0]+ self.assertEqual(+ event_definition.integration_name,+ 'camera.object.event.front_yard',+ )+ # One clause keyed on the OBJECT_PRESENCE sensor with the+ # conservative EQ OBJECT_PERSON default (see Issue #346 for+ # the broader operator vocabulary that would let this default+ # widen to "any non-NONE detection").+ clauses = list( event_definition.event_clauses.all() )+ self.assertEqual( len( clauses ), 1 )+ self.assertEqual( clauses[0].value, 'object_person' )+ self.assertEqual(+ clauses[0].entity_state.entity_state_type_str,+ str( EntityStateType.OBJECT_PRESENCE ),+ )++ def test_sync_is_idempotent_for_event_definitions(self):+ self.mock_manager.should_add_alarm_events = True+ self._set_upstream_cameras( [ 'front_yard' ] )+ self.synchronizer._sync_impl( is_initial_import = True )+ self.synchronizer._sync_impl( is_initial_import = False )+ # Second sync against the same upstream — no new event+ # definitions; existing entity's update path doesn't+ # re-create the definition.+ self.assertEqual(+ EventDefinition.objects.filter(+ integration_id = FrigateMetaData.integration_id,+ ).count(),+ 1,+ )diff --git a/src/hi/services/frigate/urls.py b/src/hi/services/frigate/urls.pynew file mode 100644index 00000000..d58763d1--- /dev/null+++ b/src/hi/services/frigate/urls.py@@ -0,0 +1,10 @@+"""URL patterns for the Frigate integration.++Empty for v1 scaffolding — the integration owns no public views of its+own; everything is mediated by the integration framework (management+pane, sync workflow) and the periodic monitor.+"""+from django.urls import path # noqa: F401+++urlpatterns: list = []diff --git a/src/hi/services/frigate/views.py b/src/hi/services/frigate/views.pynew file mode 100644index 00000000..15ada114--- /dev/null+++ b/src/hi/services/frigate/views.py@@ -0,0 +1,4 @@+"""View placeholders for the Frigate integration.++Empty for v1 scaffolding — see ``urls.py``.+"""diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.pyindex 80a0c043..8e094801 100644--- a/src/hi/services/hass/hass_converter.py+++ b/src/hi/services/hass/hass_converter.py@@ -272,7 +272,7 @@ class HassConverter:# 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.+ # stream so has_event_video_clip stays False.(HassApi.SUN_DOMAIN, None, None): EntityStateType.MULTIVALUED,(HassApi.WEATHER_DOMAIN, None, None): EntityStateType.MULTIVALUED,}diff --git a/src/hi/services/zoneminder/integration.py b/src/hi/services/zoneminder/integration.pyindex 09c058a8..8d3a27a0 100644--- a/src/hi/services/zoneminder/integration.py+++ b/src/hi/services/zoneminder/integration.py@@ -141,7 +141,7 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):video_url = self.zm_manager().get_video_stream_url(monitor_id)return VideoStream(- stream_type=VideoStreamType.URL,+ stream_type=VideoStreamType.MJPEG,source_url=video_url,metadata={'monitor_id': monitor_id,@@ -154,11 +154,37 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):return None+ def get_sensor_response_event_snapshot_url(+ self,+ sensor_response: SensorResponse) -> Optional[str]:+ """Per-event snapshot URL for a ZM SensorResponse. Reads the+ event_id from detail_attrs (where the monitor stores it on+ every START / END row), builds the portal URL fresh each+ call so an operator-side portal-URL change auto-heals every+ historical row."""+ if not sensor_response.has_event_video_snapshot:+ return None+ event_id_fieldname = ZmDetailKeys.EVENT_ID_ATTR_NAME+ if not sensor_response.detail_attrs:+ return None+ raw_event_id = sensor_response.detail_attrs.get(event_id_fieldname)+ if raw_event_id is None:+ return None+ try:+ event_id = int(raw_event_id)+ except (ValueError, TypeError):+ logger.warning(+ 'Could not parse event ID from ZM sensor response: %s',+ sensor_response.detail_attrs,+ )+ return None+ return self.zm_manager().get_event_snapshot_url(event_id=event_id)+def get_sensor_response_video_stream(self,sensor_response: SensorResponse) -> Optional[VideoStream]:"""Get video stream from sensor response (recorded events)"""- # if not sensor_response.has_video_stream:+ # if not sensor_response.has_event_video_clip:# return Noneevent_id_fieldname = ZmDetailKeys.EVENT_ID_ATTR_NAME@@ -187,7 +213,7 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):f" {sensor_response.detail_attrs.get(ZmDetailKeys.DURATION_SECS)}")return VideoStream(- stream_type=VideoStreamType.URL,+ stream_type=VideoStreamType.MJPEG,source_url=video_url,metadata=metadata)diff --git a/src/hi/services/zoneminder/monitors.py b/src/hi/services/zoneminder/monitors.pyindex 08d3c472..9773681a 100644--- a/src/hi/services/zoneminder/monitors.py+++ b/src/hi/services/zoneminder/monitors.py@@ -383,7 +383,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )return sensor_response_map- def _has_video_stream_capability(self, detail_attrs: dict = None) -> bool:+ def _has_event_video_clip_capability(self, detail_attrs: dict = None) -> bool:"""Determine if a SensorResponse should have video stream capability.For ZoneMinder, this means the response contains an Event ID.@@ -398,6 +398,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )ZmDetailKeys.START_TIME: all_detail_attrs.get(ZmDetailKeys.START_TIME),ZmDetailKeys.NOTES: all_detail_attrs.get(ZmDetailKeys.NOTES),}+ has_event_id = self._has_event_video_clip_capability(detail_attrs)return SensorResponse(integration_key = self.zm_manager()._to_integration_key(prefix = ZoneMinderManager.MOVEMENT_SENSOR_PREFIX,@@ -406,8 +407,8 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )value = str(EntityStateValue.ACTIVE),timestamp = zm_event.start_datetime,detail_attrs = detail_attrs,- source_image_url = zm_event.image_url( self.zm_manager() ),- has_video_stream = self._has_video_stream_capability(detail_attrs),+ has_event_video_clip = has_event_id,+ has_event_video_snapshot = has_event_id,correlation_role = CorrelationRole.START,correlation_id = all_detail_attrs.get(ZmDetailKeys.EVENT_ID_ATTR_NAME),)@@ -417,6 +418,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )# For idle (end) events, include all detail attributesdetail_attrs = all_detail_attrs+ has_event_id = self._has_event_video_clip_capability(detail_attrs)return SensorResponse(integration_key = self.zm_manager()._to_integration_key(prefix = ZoneMinderManager.MOVEMENT_SENSOR_PREFIX,@@ -425,7 +427,8 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )value = str(EntityStateValue.IDLE),timestamp = zm_event.end_datetime,detail_attrs = detail_attrs,- has_video_stream = self._has_video_stream_capability(detail_attrs),+ has_event_video_clip = has_event_id,+ has_event_video_snapshot = has_event_id,correlation_role = CorrelationRole.END,correlation_id = all_detail_attrs.get(ZmDetailKeys.EVENT_ID_ATTR_NAME),)@@ -438,7 +441,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )),value = str(EntityStateValue.IDLE),timestamp = timestamp,- has_video_stream = False,+ has_event_video_clip = False,)def _create_monitor_function_sensor_response( self, zm_monitor : ZmMonitor, timestamp : datetime ):@@ -450,7 +453,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )),value = str( zm_monitor.function() ),timestamp = timestamp,- has_video_stream = False,+ has_event_video_clip = False,)def _create_run_state_sensor_response( self, run_state_name : str, timestamp : datetime ):@@ -458,6 +461,6 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )integration_key = self.zm_manager()._zm_run_state_integration_key(),value = run_state_name,timestamp = timestamp,- has_video_stream = False,+ has_event_video_clip = False,)diff --git a/src/hi/services/zoneminder/zm_manager.py b/src/hi/services/zoneminder/zm_manager.pyindex d40e73ab..1826c273 100644--- a/src/hi/services/zoneminder/zm_manager.py+++ b/src/hi/services/zoneminder/zm_manager.py@@ -373,6 +373,17 @@ class ZoneMinderManager( SingletonManager, AggregateHealthProvider, ApiHealthStatimestamp = 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_event_snapshot_url( self, event_id : int ) -> Optional[ str ]:+ """Per-event captured-frame URL — points at the snapshot+ attached to a ZoneMinder event (``view=image&fid=snapshot``).+ Returns ``None`` when the ZM client isn't available."""+ if not self.zm_client:+ return None+ return (+ f'{self.zm_client.portal_url}/index.php'+ f'?view=image&eid={event_id}&fid=snapshot'+ )+def get_video_snapshot_url( self, monitor_id : int ):"""Return a URL to a single still frame for the monitor'scurrent view (ZoneMinder's ``mode=single`` variant). Cache-bustdiff --git a/src/hi/services/zoneminder/zm_sync.py b/src/hi/services/zoneminder/zm_sync.pyindex 5218892f..5844c6bb 100644--- a/src/hi/services/zoneminder/zm_sync.py+++ b/src/hi/services/zoneminder/zm_sync.py@@ -341,7 +341,7 @@ class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):prefix = zm_manager.MOVEMENT_SENSOR_PREFIX,zm_monitor_id = zm_monitor.id(),),- provides_video_stream = True,+ provides_event_video_clip = True,)HiModelHelper.create_discrete_controller(entity = entity,diff --git a/src/hi/settings/base.py b/src/hi/settings/base.pyindex 74441eb3..cb04fe71 100644--- a/src/hi/settings/base.py+++ b/src/hi/settings/base.py@@ -127,6 +127,7 @@ INSTALLED_APPS = ['hi.services.zoneminder','hi.services.hass','hi.services.homebox',+ 'hi.services.frigate','hi.apps.profiles',]diff --git a/src/hi/settings/simulator.py b/src/hi/settings/simulator.pyindex aff43d69..28e9f984 100644--- a/src/hi/settings/simulator.py+++ b/src/hi/settings/simulator.py@@ -18,6 +18,7 @@ INSTALLED_APPS = ['hi.simulator.services','hi.simulator.weather_sources','hi.simulator.settings',+ 'hi.simulator.services.frigate','hi.simulator.services.hass','hi.simulator.services.homebox','hi.simulator.services.zoneminder',diff --git a/src/hi/simulator/management/commands/seed_sim_profiles.py b/src/hi/simulator/management/commands/seed_sim_profiles.pyindex dec41916..af68a607 100644--- a/src/hi/simulator/management/commands/seed_sim_profiles.py+++ b/src/hi/simulator/management/commands/seed_sim_profiles.py@@ -23,6 +23,12 @@ own profile namespace), so the seed catalog is partitioned by module:* baseline-changed* volume — 1 server + 10 monitors+ Frigate (hi.simulator.services.frigate)+ * empty+ * baseline+ * baseline-changed+ * volume — 10 cameras+NWS (hi.simulator.weather_sources.nws)* sample — curated 8-alert catalog spanning eventtypes; every alert starts inactive so@@ -108,6 +114,10 @@ from hi.simulator.services.hass.sim_models import (HassWindowBlindCoverFields,HassWindowContactSensorFields,)+from hi.simulator.services.frigate.apps import FrigateConfig+from hi.simulator.services.frigate.sim_models import (+ FrigateCameraSimEntityFields,+)from hi.simulator.services.homebox.apps import HomeBoxConfigfrom hi.simulator.services.homebox.attachment_catalog import AttachmentTemplatefrom hi.simulator.services.homebox.sim_models import (@@ -129,6 +139,7 @@ MODULE_SHORT_NAMES = {'hass': HassConfig.name,'homebox': HomeBoxConfig.name,'zoneminder': ZoneminderConfig.name,+ 'frigate': FrigateConfig.name,'nws': NwsWeatherSimConfig.name,}@@ -195,6 +206,7 @@ class Command(BaseCommand):hass = HassConfig.namehomebox = HomeBoxConfig.namezoneminder = ZoneminderConfig.name+ frigate = FrigateConfig.namenws = NwsWeatherSimConfig.namereturn [( hass , 'empty' , self._build_empty ),@@ -212,6 +224,11 @@ class Command(BaseCommand):( zoneminder , 'baseline-changed' , self._build_zm_baseline_changed ),( zoneminder , 'volume' , self._build_zm_volume ),+ ( frigate , 'empty' , self._build_empty ),+ ( frigate , 'baseline' , self._build_frigate_baseline ),+ ( frigate , 'baseline-changed' , self._build_frigate_baseline_changed ),+ ( frigate , 'volume' , self._build_frigate_volume ),+( nws , 'sample' , self._build_nws_sample ),]@@ -492,6 +509,43 @@ class Command(BaseCommand):)return profile.db_sim_entities.count()+ # ----- Frigate builders -----++ def _build_frigate_baseline(self, profile: SimProfile) -> int:+ # 3 cameras + a ★-prefixed camera anchor for the detach/reconnect+ # cycle.+ self._add_frigate_camera( profile, 'Front Yard', camera_name = 'front_yard' )+ self._add_frigate_camera( profile, 'Driveway' , camera_name = 'driveway' )+ self._add_frigate_camera( profile, 'Kitchen' , camera_name = 'kitchen' )+ self._add_frigate_camera(+ profile, '★ Custom Attr Needed ★ Backyard Camera',+ camera_name = 'backyard',+ )+ return profile.db_sim_entities.count()++ def _build_frigate_baseline_changed(self, profile: SimProfile) -> int:+ # Frigate deltas vs baseline:+ # Front Yard — kept+ # Driveway — REMOVED (no user attr → hard delete)+ # Kitchen — kept+ # ★ Backyard — ABSENT (camera_name absent) → Detached+ # via user-attribute anchor+ # <new> Patio — ADDED (new camera_name)+ self._add_frigate_camera( profile, 'Front Yard', camera_name = 'front_yard' )+ self._add_frigate_camera( profile, 'Kitchen' , camera_name = 'kitchen' )+ self._add_frigate_camera( profile, 'Patio' , camera_name = 'patio' )+ return profile.db_sim_entities.count()++ def _build_frigate_volume(self, profile: SimProfile) -> int:+ # 10 cameras.+ for index in range(10):+ self._add_frigate_camera(+ profile,+ f'Volume Camera {index + 1:02}',+ camera_name = f'volume_camera_{index + 1:02}',+ )+ return profile.db_sim_entities.count()+# ----- NWS builders -----def _build_nws_sample(self, profile: SimProfile) -> int:@@ -980,6 +1034,14 @@ class Command(BaseCommand):fields_kwargs = {'name': name, 'monitor_id': monitor_id},)+ def _add_frigate_camera(self, profile, name, camera_name):+ self._create_db_entity(+ profile = profile,+ fields_class = FrigateCameraSimEntityFields,+ sim_entity_type = SimEntityType.CAMERA,+ fields_kwargs = {'name': name, 'camera_name': camera_name},+ )+def _add_nws_alert(self, profile, *,event_code, event_name,severity, certainty, urgency, category,diff --git a/src/hi/simulator/services/frigate/__init__.py b/src/hi/simulator/services/frigate/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/simulator/services/frigate/api/__init__.py b/src/hi/simulator/services/frigate/api/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/simulator/services/frigate/api/urls.py b/src/hi/simulator/services/frigate/api/urls.pynew file mode 100644index 00000000..977af1ae--- /dev/null+++ b/src/hi/simulator/services/frigate/api/urls.py@@ -0,0 +1,40 @@+"""Frigate API endpoints (simulator-side).++Mirrors the shape of Frigate's real HTTP API. Routes are added in+parallel with the HI client's per-endpoint support — at any given+point only the endpoints HI talks to need to exist.+"""+from django.urls import path++from . import views+++urlpatterns = [++ path( 'config',+ views.ConfigView.as_view(),+ name = 'frigate_api_config' ),++ path( 'events',+ views.EventsListView.as_view(),+ name = 'frigate_api_events' ),++ # ``events/<id>/snapshot.jpg`` and ``events/<id>/clip.mp4`` both+ # precede the generic ``events/<id>`` route so the trailing path+ # segment is matched before the JSON-detail catch-all.+ path( 'events/<str:event_id>/snapshot.jpg',+ views.EventSnapshotJpegView.as_view(),+ name = 'frigate_api_event_snapshot' ),++ path( 'events/<str:event_id>/clip.mp4',+ views.EventClipMp4View.as_view(),+ name = 'frigate_api_event_clip' ),++ path( 'events/<str:event_id>',+ views.EventDetailView.as_view(),+ name = 'frigate_api_event_detail' ),++ path( '<str:camera_name>/latest.jpg',+ views.CameraLatestJpegView.as_view(),+ name = 'frigate_api_camera_snapshot' ),+]diff --git a/src/hi/simulator/services/frigate/api/views.py b/src/hi/simulator/services/frigate/api/views.pynew file mode 100644index 00000000..313a5ac8--- /dev/null+++ b/src/hi/simulator/services/frigate/api/views.py@@ -0,0 +1,200 @@+"""Frigate-shape HTTP API views (simulator-side).++Each view returns the JSON shape (or media-bytes shape) a real+Frigate instance would respond with, so HI's ``FrigateClient`` (and+the browser-side <img> tags HI emits for snapshots) can talk to the+simulator without any client-side branching.+"""+import logging+import os+from datetime import datetime, timezone++from django.http import FileResponse, Http404, HttpResponse, JsonResponse+from django.views.generic import View++from hi.simulator.media import render_jpeg_frame+from hi.simulator.services.frigate.event_manager import FrigateSimEventManager+from hi.simulator.services.frigate.simulator import FrigateSimulator+++# Pre-generated short MP4 (~14 KB, H.264 baseline) ships alongside+# the simulator so the event-playback view shows a labeled,+# animated clip for every event without runtime media synthesis.+_EVENT_PLAYBACK_MP4_PATH = os.path.join(+ os.path.dirname( os.path.dirname( __file__ )),+ 'static_assets', 'event_playback.mp4',+)++logger = logging.getLogger(__name__)+++def _apply_no_cache_headers( response ) -> None:+ """Snapshot URLs are cache-busted by HI with a timestamp param,+ but emit no-store headers as well so re-rendering an <img> tag+ with the same src in a stale cache still triggers a refetch."""+ response[ 'Cache-Control' ] = 'no-store, no-cache, must-revalidate, max-age=0'+ response[ 'Pragma' ] = 'no-cache'+ response[ 'Expires' ] = '0'+ return+++class ConfigView( View ):+ """``GET /api/config`` — Frigate's effective configuration.++ Real Frigate returns a large nested document; HI's integration+ only cares about the ``cameras`` map (camera names are the keys).+ We emit the minimum shape the client needs plus a token of+ per-camera info so the response is recognizable as Frigate JSON.+ """++ def get(self, request, *args, **kwargs):+ try:+ simulator = FrigateSimulator()+ cameras = {}+ for sim_camera in simulator.get_sim_cameras():+ cameras[ sim_camera.camera_name ] = {+ 'name': sim_camera.camera_name,+ 'friendly_name': sim_camera.display_name,+ 'enabled': True,+ }+ return JsonResponse( { 'cameras': cameras } )+ except Exception:+ logger.exception( 'Problem processing Frigate /api/config request.' )+ return JsonResponse( { 'cameras': {} } )+++class EventsListView( View ):+ """``GET /api/events`` — Frigate's events listing.++ v1 supports the ``after`` query parameter (epoch seconds), which+ is what the HI polling cursor will use. Other Frigate filters+ (``before`` / ``cameras`` / ``labels`` / ``zones``) are accepted+ and silently ignored — they're not on the HI integration's read+ path yet. Response is a top-level JSON array, most-recent+ start_time first (Frigate's convention)."""++ def get(self, request, *args, **kwargs):+ try:+ after_param = request.GET.get( 'after' )+ event_manager = FrigateSimEventManager()+ if after_param is not None:+ try:+ after_epoch = float( after_param )+ except ValueError:+ return JsonResponse(+ { 'error': f'Invalid after parameter: {after_param!r}' },+ status = 400,+ )+ cutoff = datetime.fromtimestamp( after_epoch, tz = timezone.utc )+ events = event_manager.get_events_after( start_datetime = cutoff )+ else:+ events = event_manager.all_events()++ # Frigate orders events newest-first by start_time.+ events.sort( key = lambda e : e.start_datetime, reverse = True )+ return JsonResponse(+ [ e.to_api_dict() for e in events ],+ safe = False,+ )+ except Exception:+ logger.exception( 'Problem processing Frigate /api/events request.' )+ return JsonResponse( [], safe = False )+++class EventDetailView( View ):+ """``GET /api/events/<id>`` — single Frigate event detail.++ Used by HI's integration to fetch event-specific data (snapshot+ URL, clip URL, full metadata). 404s for unknown ids so the HI+ client can distinguish "event doesn't exist" from "Frigate is+ broken"."""++ def get(self, request, event_id : str, *args, **kwargs):+ event = FrigateSimEventManager().find_event_by_id( event_id = event_id )+ if event is None:+ raise Http404( f'Unknown Frigate event id: {event_id!r}' )+ return JsonResponse( event.to_api_dict() )+++class CameraLatestJpegView( View ):+ """``GET /api/<camera_name>/latest.jpg`` — live snapshot.++ Real Frigate returns the most recently decoded frame for the+ camera. The simulator returns a synthesized placeholder JPEG+ stamped with the camera name and current time so artifacts viewed+ inside HI are obviously coming from the simulator."""++ def get(self, request, camera_name : str, *args, **kwargs):+ text_lines = [ 'Live Snapshot (simulator)' ]+ sim_camera = self._find_sim_camera( camera_name = camera_name )+ if sim_camera is None:+ text_lines.append( f'camera "{camera_name}" (no record)' )+ else:+ text_lines.append( f'camera: {sim_camera.display_name}' )+ text_lines.append( f'name: {sim_camera.camera_name}' )+ response = HttpResponse(+ render_jpeg_frame( text_lines = text_lines ),+ content_type = 'image/jpeg',+ )+ _apply_no_cache_headers( response )+ return response++ @staticmethod+ def _find_sim_camera( camera_name : str ):+ for sim_camera in FrigateSimulator().get_sim_cameras():+ if sim_camera.camera_name == camera_name:+ return sim_camera+ continue+ return None+++class EventClipMp4View( View ):+ """``GET /api/events/<id>/clip.mp4`` — event clip playback.++ Real Frigate streams an MP4 of the event's clip. The simulator+ serves a fixed-content placeholder MP4 (frame-counter + clock+ overlay) so HI's Video Browse can demonstrate the round-trip+ without runtime media synthesis. 404s for unknown event ids."""++ def get(self, request, event_id : str, *args, **kwargs):+ event = FrigateSimEventManager().find_event_by_id( event_id = event_id )+ if event is None:+ raise Http404( f'Unknown Frigate event id: {event_id!r}' )+ response = FileResponse(+ open( _EVENT_PLAYBACK_MP4_PATH, 'rb' ),+ content_type = 'video/mp4',+ )+ _apply_no_cache_headers( response )+ return response+++class EventSnapshotJpegView( View ):+ """``GET /api/events/<id>/snapshot.jpg`` — event snapshot.++ Real Frigate returns the single frame captured at the time of+ detection. HI's Frigate gateway builds this URL on demand from+ the event id (the SensorResponse carries the existence flag+ ``has_event_video_snapshot``) so the alert / history views can+ show what the camera saw. The simulator returns a placeholder+ JPEG stamped with the event id and label.++ 404s for unknown event ids so the HI client distinguishes "event+ missing" from "simulator broken" — same posture as ``GET+ /api/events/<id>``."""++ def get(self, request, event_id : str, *args, **kwargs):+ event = FrigateSimEventManager().find_event_by_id( event_id = event_id )+ if event is None:+ raise Http404( f'Unknown Frigate event id: {event_id!r}' )+ text_lines = [+ 'Event Snapshot (simulator)',+ f'camera: {event.camera_name}',+ f'event id: {event.event_id}',+ f'label: {event.label}',+ ]+ response = HttpResponse(+ render_jpeg_frame( text_lines = text_lines ),+ content_type = 'image/jpeg',+ )+ _apply_no_cache_headers( response )+ return responsediff --git a/src/hi/simulator/services/frigate/apps.py b/src/hi/simulator/services/frigate/apps.pynew file mode 100644index 00000000..a2b69a45--- /dev/null+++ b/src/hi/simulator/services/frigate/apps.py@@ -0,0 +1,7 @@+from django.apps import AppConfig+++class FrigateConfig( AppConfig ):+ default_auto_field = 'django.db.models.BigAutoField'+ name = 'hi.simulator.services.frigate'+ simulator_module_label = 'Frigate'diff --git a/src/hi/simulator/services/frigate/event_history.py b/src/hi/simulator/services/frigate/event_history.pynew file mode 100644index 00000000..0ed0235a--- /dev/null+++ b/src/hi/simulator/services/frigate/event_history.py@@ -0,0 +1,96 @@+"""Per-camera event history for the Frigate simulator.++Per-camera ring buffer of events. Events are synthesized from the+operator's ObjectPresence sim-state changes — no DB row, no CRUD UI.+"""+from collections import deque+from datetime import datetime+from typing import Callable, List, Optional++import hi.apps.common.datetimeproxy as datetimeproxy++from .sim_models import FrigateSimCamera, FrigateSimEvent+++class FrigateSimEventHistory:+ """Per-camera ring buffer of events.++ The state machine is driven by ``set_current_object(label)``:+ transitioning to a different non-none label closes the current+ event and opens a new one; transitioning to ``none`` closes+ the current event; transitioning to the same label is a no-op.+ """++ DEFAULT_MAX_EVENTS = 500++ def __init__( self,+ frigate_sim_camera : FrigateSimCamera,+ event_id_allocator : Callable[ [], str ],+ none_label : str = 'none',+ max_events : int = DEFAULT_MAX_EVENTS ):+ self._frigate_sim_camera = frigate_sim_camera+ self._event_id_allocator = event_id_allocator+ self._none_label = none_label+ self._events : deque = deque( maxlen = max_events )+ return++ def __len__(self) -> int:+ return len( self._events )++ def set_current_object( self, object_label : str ) -> Optional[ FrigateSimEvent ]:+ """Drive the camera's event lifecycle from the current+ ObjectPresence value.++ Returns the event that was touched (the newly-opened event+ on START or label switch, the just-closed event on transition+ to none, or None if no transition was needed)."""+ latest = self._events[-1] if self._events else None+ currently_open = latest if ( latest is not None and latest.is_open ) else None++ if object_label == self._none_label:+ if currently_open is None:+ return None+ currently_open.close()+ return currently_open++ if currently_open is None:+ return self._open_event( object_label = object_label )++ if currently_open.label == object_label:+ return None++ # Label change while an event is open — close current, open new.+ currently_open.close()+ return self._open_event( object_label = object_label )++ def _open_event( self, object_label : str ) -> FrigateSimEvent:+ event = FrigateSimEvent(+ event_id = self._event_id_allocator(),+ camera_name = self._frigate_sim_camera.camera_name,+ label = object_label,+ start_datetime = datetimeproxy.now(),+ )+ self._events.append( event )+ return event++ def get_events_after( self, start_datetime : datetime ) -> List[ FrigateSimEvent ]:+ """All events whose start time is STRICTLY after ``start_datetime``.++ Mirrors Frigate's own ``/api/events?after=T`` semantics+ (``Event.start_time > T``). The HI monitor depends on this+ strict-``>`` behavior — it advances the cursor past each+ observed event's ``start_time`` and tracks open events by id,+ so an inclusive filter here would let stale events leak back+ into cursor scans and mask bugs that real Frigate would+ surface."""+ return [ e for e in self._events if e.start_datetime > start_datetime ]++ def all_events( self ) -> List[ FrigateSimEvent ]:+ return list( self._events )++ def find_event_by_id( self, event_id : str ) -> Optional[ FrigateSimEvent ]:+ for event in self._events:+ if event.event_id == event_id:+ return event+ continue+ return Nonediff --git a/src/hi/simulator/services/frigate/event_manager.py b/src/hi/simulator/services/frigate/event_manager.pynew file mode 100644index 00000000..9264e0c2--- /dev/null+++ b/src/hi/simulator/services/frigate/event_manager.py@@ -0,0 +1,84 @@+"""Singleton coordinator for synthesized Frigate-simulator events.++Per-camera ``FrigateSimEventHistory`` instances live here, keyed by+camera_name (Frigate's identifier is a string, unlike ZM's integer+monitor id). Mirrors ``ZmSimEventManager`` in role.+"""+from datetime import datetime+import threading+from typing import Dict, List, Optional++from hi.apps.common.singleton import Singleton++from .event_history import FrigateSimEventHistory+from .sim_models import FrigateSimCamera, FrigateSimEvent+++class FrigateSimEventManager( Singleton ):++ def __init_singleton__(self):+ self._histories : Dict[ str, FrigateSimEventHistory ] = dict()+ self._data_lock = threading.Lock()+ # Frigate's wire event_id space is opaque — real Frigate uses+ # ``<epoch>.<microseconds>-<hash>`` strings. For the simulator+ # we use a process-wide monotonic counter, stringified. Stable+ # round-trip is all the integration needs.+ self._next_event_id = 0+ return++ def _allocate_event_id( self ) -> str:+ self._next_event_id += 1+ return str( self._next_event_id )++ def set_current_object( self,+ frigate_sim_camera : FrigateSimCamera,+ object_label : str,+ none_label : str ) -> Optional[ FrigateSimEvent ]:+ """Driven by the camera ObjectPresence sim-state. Routes to+ the per-camera history, allocating one on first use. Returns+ the event the transition touched (or ``None`` when no+ transition was needed). ``none_label`` is the wire value that+ means "no current detection" (e.g. ``'none'``)."""+ with self._data_lock:+ camera_name = frigate_sim_camera.camera_name+ history = self._histories.get( camera_name )+ if history is None:+ history = FrigateSimEventHistory(+ frigate_sim_camera = frigate_sim_camera,+ event_id_allocator = self._allocate_event_id,+ none_label = none_label,+ )+ self._histories[ camera_name ] = history+ return history.set_current_object( object_label = object_label )++ def get_events_after( self, start_datetime : datetime ) -> List[ FrigateSimEvent ]:+ """All events across all cameras with start time at or after+ ``start_datetime``. Used by the simulator's+ ``GET /api/events?after=`` endpoint."""+ results : List[ FrigateSimEvent ] = []+ with self._data_lock:+ for history in self._histories.values():+ results.extend( history.get_events_after(+ start_datetime = start_datetime,+ ))+ continue+ return results++ def all_events( self ) -> List[ FrigateSimEvent ]:+ """All events across all cameras, regardless of time. Used by+ unfiltered ``GET /api/events`` requests."""+ results : List[ FrigateSimEvent ] = []+ with self._data_lock:+ for history in self._histories.values():+ results.extend( history.all_events() )+ continue+ return results++ def find_event_by_id( self, event_id : str ) -> Optional[ FrigateSimEvent ]:+ with self._data_lock:+ for history in self._histories.values():+ match = history.find_event_by_id( event_id = event_id )+ if match is not None:+ return match+ continue+ return Nonediff --git a/src/hi/simulator/services/frigate/migrations/__init__.py b/src/hi/simulator/services/frigate/migrations/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/simulator/services/frigate/service_dispatchers.py b/src/hi/simulator/services/frigate/service_dispatchers.pynew file mode 100644index 00000000..6ea205e0--- /dev/null+++ b/src/hi/simulator/services/frigate/service_dispatchers.py@@ -0,0 +1,50 @@+"""Frigate simulator service dispatcher.++Scaffolding stub. The shape mirrors ``HassServiceDispatcher`` /+``ZoneMinder``'s monitor parameter setter: the simulator's incoming+API requests (e.g., camera detect-on / detect-off) dispatch to a+per-(sim_entity_fields_class) handler that translates the wire call+into SimState updates.++Feature work registers handlers in ``HassServiceDispatcher`` style:++ HassServiceDispatcher._REGISTRY = {+ FrigateCameraSimEntityFields: _camera,+ ...+ }+"""+import logging+from typing import Any, Dict, List, Tuple+++logger = logging.getLogger(__name__)+++class FrigateServiceDispatcher:+ """Routes simulator-side API service calls onto the right per-class+ handler. Empty registry for v0 scaffolding.+ """++ _REGISTRY: Dict = {}++ @classmethod+ def dispatch( cls,+ sim_entity,+ operation_name : str,+ payload : Dict[ str, Any ] ) -> List[ Tuple[ str, str ] ]:+ """Resolve to the per-(fields_class) handler. Returns a list+ of ``(sim_state_id, new_value)`` tuples describing the+ state changes implied by the call."""+ fields_class = sim_entity.sim_entity_fields.__class__+ handler = cls._REGISTRY.get( fields_class )+ if not handler:+ logger.debug(+ f'No Frigate service dispatcher for {fields_class.__name__}'+ f' op={operation_name}'+ )+ return []+ return handler(+ sim_entity = sim_entity,+ operation_name = operation_name,+ payload = payload,+ )diff --git a/src/hi/simulator/services/frigate/sim_models.py b/src/hi/simulator/services/frigate/sim_models.pynew file mode 100644index 00000000..92b89bc1--- /dev/null+++ b/src/hi/simulator/services/frigate/sim_models.py@@ -0,0 +1,186 @@+"""Frigate simulator sim-model definitions.++The simulator emits raw Frigate-style object class labels+(``person``, ``car``, ``dog``, ...) — exactly what a real Frigate+instance would publish. The HI-side ``FrigateConverter`` buckets+these onto the canonical ``OBJECT_PRESENCE`` value range. Including+a deliberately uncategorized label (``unicorn``) in the operator's+choice list keeps the ``other`` bucket on the demo path.+"""+from dataclasses import dataclass+from datetime import datetime+from typing import ClassVar, List, Optional, Tuple++import hi.apps.common.datetimeproxy as datetimeproxy++from hi.simulator.services.base_models import (+ SimEntityDefinition,+ SimEntityFields,+ SimState,+)+from hi.simulator.services.enums import SimEntityType, SimStateType+from hi.simulator.services.sim_entity import SimEntity+++@dataclass( frozen = True )+class FrigateCameraSimEntityFields( SimEntityFields ):+ """Operator-configurable fields for a simulated Frigate camera.++ ``camera_name`` is the per-camera identifier used in Frigate's+ URL paths (``/api/<camera_name>/latest.jpg``) and as the+ ``camera`` field on events. Mirrors Frigate's own config-file+ naming (``cameras:`` map keyed by name)."""++ name : str = 'Frigate Camera'+ camera_name : str = 'sim_camera_1'+++# Raw Frigate-style object labels presented to the operator on the+# ObjectPresence discrete control. Includes one deliberately+# uncategorized label so the ``other`` bucket on the HI side+# remains exercisable.+FRIGATE_OBJECT_LABEL_CHOICES: List[ Tuple[ str, str ] ] = [+ ( 'none', 'No Object' ),+ ( 'person', 'Person' ),+ ( 'car', 'Car' ),+ ( 'truck', 'Truck' ),+ ( 'dog', 'Dog' ),+ ( 'cat', 'Cat' ),+ ( 'package', 'Package' ),+ ( 'unicorn', 'Unicorn (unmapped)' ),+]+FRIGATE_OBJECT_LABEL_NONE = 'none'+++@dataclass+class FrigateCameraObjectPresenceState( SimState ):+ """Currently-detected object class — the SINGLE per-camera state+ the simulator exposes. Frigate's data model couples motion to+ object detection (no motion-without-class signal on the events+ API), so this discrete state is the only control the operator+ needs: pick the raw class to declare "this is what's currently+ being detected"; pick ``none`` to declare "nothing is detected".++ The HI-side ``FrigateConverter`` buckets the raw label onto the+ canonical ``OBJECT_PRESENCE`` set+ (``person`` / ``car`` / ``animal`` / ``package`` / ``other`` /+ ``none``). The simulator's ``set_sim_state`` override translates+ value changes into the underlying event lifecycle (open / close /+ swap), so the operator never has to manage motion + label as+ separate controls.+ """++ OBJECT_PRESENCE_SIM_STATE_ID : ClassVar[ str ] = 'object_presence'++ sim_entity_fields : FrigateCameraSimEntityFields+ sim_state_type : SimStateType = SimStateType.DISCRETE+ sim_state_id : str = OBJECT_PRESENCE_SIM_STATE_ID+ value : str = FRIGATE_OBJECT_LABEL_NONE++ @property+ def name(self):+ return 'Detected Object'++ @property+ def choices(self) -> List[ Tuple[ str, str ] ]:+ return FRIGATE_OBJECT_LABEL_CHOICES+++@dataclass( frozen = True )+class FrigateSimCamera:+ """Per-entity accessor wrapper for a simulated Frigate camera.++ Mirrors ``ZmSimMonitor`` in role: convenient typed property+ access onto a single camera ``SimEntity`` so views / event+ managers don't reach into ``sim_entity_fields`` / ``sim_state_list``+ directly. Pure projection — no behavior beyond reads."""++ sim_entity : SimEntity++ @property+ def camera_name(self) -> str:+ return self.sim_entity.sim_entity_fields.camera_name++ @property+ def display_name(self) -> str:+ return self.sim_entity.sim_entity_fields.name++ @property+ def object_presence_sim_state(self) -> FrigateCameraObjectPresenceState:+ for sim_state in self.sim_entity.sim_state_list:+ if isinstance( sim_state, FrigateCameraObjectPresenceState ):+ return sim_state+ continue+ raise ValueError(+ f'No object-presence sim state for Frigate camera {self.sim_entity}'+ )+++@dataclass+class FrigateSimEvent:+ """One synthesized Frigate event, tracked in memory by+ ``FrigateSimEventHistory``.++ ``label`` is the raw Frigate-side object class (e.g. ``person``,+ ``dog``) — the same value space the camera's ObjectPresence+ sim-state carries. ``start_datetime`` / ``end_datetime`` follow+ Frigate's event lifecycle: ``end_datetime is None`` means the+ event is still open. ``score`` is a generated placeholder for v1;+ real Frigate emits a 0..1 best-score-so-far per event."""++ event_id : str+ camera_name : str+ label : str+ start_datetime : datetime+ end_datetime : Optional[ datetime ] = None+ score : float = 0.85++ @property+ def is_active(self) -> bool:+ return self.end_datetime is None++ @property+ def is_open(self) -> bool:+ return self.end_datetime is None++ @property+ def is_closed(self) -> bool:+ return self.end_datetime is not None++ def close( self ) -> None:+ if self.end_datetime is None:+ self.end_datetime = datetimeproxy.now()+ return++ def to_api_dict(self) -> dict:+ """Frigate-shape ``/api/events`` JSON for one event. Field set+ is the subset HI's integration cares about plus a few real+ Frigate fields kept so the response is recognizable. Times+ are epoch seconds (Frigate's wire convention)."""+ end_epoch = self.end_datetime.timestamp() if self.end_datetime else None+ return {+ 'id': self.event_id,+ 'camera': self.camera_name,+ 'label': self.label,+ 'sub_label': None,+ 'start_time': self.start_datetime.timestamp(),+ 'end_time': end_epoch,+ 'top_score': self.score,+ 'false_positive': False,+ 'zones': [],+ 'thumbnail': None,+ 'has_clip': True,+ 'has_snapshot': True,+ }+++FRIGATE_SIM_ENTITY_DEFINITION_LIST: List[ SimEntityDefinition ] = [+ SimEntityDefinition(+ class_label = 'Camera',+ sim_entity_type = SimEntityType.CAMERA,+ sim_entity_fields_class = FrigateCameraSimEntityFields,+ sim_state_class_list = [+ FrigateCameraObjectPresenceState,+ ],+ ),+]diff --git a/src/hi/simulator/services/frigate/simulator.py b/src/hi/simulator/services/frigate/simulator.pynew file mode 100644index 00000000..2acf7a18--- /dev/null+++ b/src/hi/simulator/services/frigate/simulator.py@@ -0,0 +1,83 @@+from typing import List++from hi.simulator.services.base_models import SimEntityDefinition, SimState+from hi.simulator.services.service_simulator import ServiceSimulator++from .event_manager import FrigateSimEventManager+from .sim_models import (+ FRIGATE_SIM_ENTITY_DEFINITION_LIST,+ FRIGATE_OBJECT_LABEL_NONE,+ FrigateCameraObjectPresenceState,+ FrigateCameraSimEntityFields,+ FrigateSimCamera,+)+++class FrigateSimulator( ServiceSimulator ):+ """Simulator entry point for the Frigate integration.++ Each camera exposes a single discrete ``ObjectPresence``+ sim-state. Picking a class value declares "this is what's+ currently being detected"; picking ``none`` declares+ "nothing is detected". The override below translates value+ changes into the underlying event lifecycle.+ """++ @property+ def id(self) -> str:+ return 'frigate'++ @property+ def label(self) -> str:+ return 'Frigate'++ @property+ def integration_urls(self):+ return [+ ( 'Base URL', 'services/frigate' ),+ ]++ @property+ def sim_entity_definition_list(self) -> List[ SimEntityDefinition ]:+ return FRIGATE_SIM_ENTITY_DEFINITION_LIST++ def get_sim_cameras(self) -> List[ FrigateSimCamera ]:+ """All Frigate camera entities in the active profile, wrapped+ in the ``FrigateSimCamera`` accessor for typed access."""+ return [+ FrigateSimCamera( sim_entity = sim_entity )+ for sim_entity in self.sim_entities+ if sim_entity.sim_entity_definition.sim_entity_fields_class+ == FrigateCameraSimEntityFields+ ]++ def set_sim_state( self,+ sim_entity_id : int,+ sim_state_id : str,+ value_str : str ) -> SimState:+ """Override so ObjectPresence value changes drive Frigate's+ event lifecycle in the ``FrigateSimEventManager``:++ - New value ``none`` → close the currently-open event (if any).+ - New value matches the open event's label → no-op (the+ operator re-picked the same class).+ - New value differs from the open event's label → close current,+ open new event with the new label. Mirrors real Frigate's+ "new object class -> new tracked event" behavior.+ - New value with no open event → open new event with this label.+ """+ sim_state = super().set_sim_state(+ sim_entity_id = sim_entity_id,+ sim_state_id = sim_state_id,+ value_str = value_str,+ )++ if isinstance( sim_state, FrigateCameraObjectPresenceState ):+ sim_entity = self.get_sim_entity_by_id( sim_entity_id = sim_entity_id )+ sim_camera = FrigateSimCamera( sim_entity = sim_entity )+ FrigateSimEventManager().set_current_object(+ frigate_sim_camera = sim_camera,+ object_label = sim_state.value,+ none_label = FRIGATE_OBJECT_LABEL_NONE,+ )+ return sim_statediff --git a/src/hi/simulator/services/frigate/static_assets/event_playback.mp4 b/src/hi/simulator/services/frigate/static_assets/event_playback.mp4new file mode 100644index 00000000..43405526Binary files /dev/null and b/src/hi/simulator/services/frigate/static_assets/event_playback.mp4 differdiff --git a/src/hi/simulator/services/frigate/tests/__init__.py b/src/hi/simulator/services/frigate/tests/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/src/hi/simulator/services/frigate/urls.py b/src/hi/simulator/services/frigate/urls.pynew file mode 100644index 00000000..a537bf41--- /dev/null+++ b/src/hi/simulator/services/frigate/urls.py@@ -0,0 +1,13 @@+"""URL routes for the Frigate simulator.++Mounts the Frigate-shaped HTTP API at ``/services/frigate/api/...``.+The simulator's services-page tab UI is owned by the parent+``hi.simulator.services`` module via the+``service_simulator_manager`` tab dispatch.+"""+from django.urls import include, path+++urlpatterns = [+ path( 'api/', include( 'hi.simulator.services.frigate.api.urls' )),+]diff --git a/src/hi/simulator/services/frigate/views.py b/src/hi/simulator/services/frigate/views.pynew file mode 100644index 00000000..3867f395--- /dev/null+++ b/src/hi/simulator/services/frigate/views.py@@ -0,0 +1,7 @@+"""Top-level views for the Frigate simulator module.++Empty for scaffolding — the simulator's services-tab UI is rendered by+the parent ``hi.simulator.services`` module via the+``service_simulator_manager`` tab dispatch, and the Frigate-shaped+HTTP API lives under ``api/`` (see ``urls.py``).+"""diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.cssindex d715c178..1bfab4cf 100644--- a/src/hi/static/css/main.css+++ b/src/hi/static/css/main.css@@ -2174,12 +2174,12 @@ g[hover] {overflow-y: auto;}-/* Wrapper around a finite-recording <img> + its replay-from-start+/* Wrapper around a finite-clip <img> + its replay-from-startoverlay button. ``position: relative`` anchors the button to theimage's top-right; ``display: block`` and ``line-height: 0`` letthe wrapper shrink to the image's actual rendered dimensions sothe overlay sits on the image, not on padding around it. */-.hi-video-recording {+.hi-video-clip {position: relative;display: block;line-height: 0;@@ -2188,7 +2188,7 @@ g[hover] {/* Replay-from-start overlay button. Always visible (touch screensdon't reliably support hover-reveal), semi-transparent backdropso it reads against any video content underneath. */-.hi-video-recording-replay {+.hi-video-clip-replay {position: absolute;top: 8px;right: 8px;@@ -2221,7 +2221,7 @@ g[hover] {touch-target guidance while keeping the icon compact on the videoframe. Pseudo-element shares the button's pointer-events, so tapsin the extended area dispatch the click handler. */-.hi-video-recording-replay::before {+.hi-video-clip-replay::before {content: '';position: absolute;top: -8px;@@ -2230,13 +2230,13 @@ g[hover] {bottom: -8px;}-.hi-video-recording-replay:hover,-.hi-video-recording-replay:focus {+.hi-video-clip-replay:hover,+.hi-video-clip-replay:focus {opacity: 1;background: rgba(0, 0, 0, 0.75);outline: none;}-.hi-video-recording-replay:active {+.hi-video-clip-replay:active {background: rgba(0, 0, 0, 0.9);transform: scale(0.92);}diff --git a/src/hi/static/img/integrations/frigate.png b/src/hi/static/img/integrations/frigate.pngnew file mode 100644index 00000000..92e6a70aBinary files /dev/null and b/src/hi/static/img/integrations/frigate.png differdiff --git a/src/hi/static/js/video-timeline.js b/src/hi/static/js/video-timeline.jsindex cbebe022..31130c13 100644--- a/src/hi/static/js/video-timeline.js+++ b/src/hi/static/js/video-timeline.js@@ -13,11 +13,11 @@// removal so browser per-host connection slots are released. The// markers themselves are disjoint by content type:// - ``data-video-stream`` : continuous live MJPEG (camera).- // - ``data-video-recording`` : finite recorded MJPEG (event playback).+ // - ``data-video-clip`` : finite recorded MJPEG (event playback).// The replay click handler at the bottom of this file applies- // only to the recording case.+ // only to the clip case.const LONG_LIVED_VIDEO_SELECTOR =- 'img[data-video-stream], img[data-video-recording]';+ 'img[data-video-stream], img[data-video-clip]';// Tracks every long-lived video connection currently attached to// the document.@@ -107,7 +107,7 @@// - ``data-stream-fps`` : polling rate (parallel to the Entity// model's ``video_snapshot_stream_fps``).//- // Distinct from ``data-video-stream`` / ``data-video-recording``+ // Distinct from ``data-video-stream`` / ``data-video-clip``// which are continuous MJPEG fetches managed by VideoConnectionManager.const SnapshotStreamManager = {@@ -205,7 +205,7 @@};// Generic ``error``-event handler for the three video-marker <img>- // elements (``data-video-stream``, ``data-video-recording``,+ // elements (``data-video-stream``, ``data-video-clip``,// ``data-video-snapshot``). On load failure, hides the <img> and// inserts a sibling placeholder; on a subsequent successful load,// hides the placeholder and reveals the <img> again. Self-healing@@ -219,7 +219,7 @@// URI, but we also explicitly skip ``data:`` URLs as defense.const VideoErrorHandler = {- SELECTOR: 'img[data-video-stream], img[data-video-recording], img[data-video-snapshot]',+ SELECTOR: 'img[data-video-stream], img[data-video-clip], img[data-video-snapshot]',PLACEHOLDER_CLASS: 'video-load-error-placeholder',REGISTERED_FLAG: 'videoErrorHandlerRegistered',@@ -232,9 +232,9 @@heading: 'Live View Unavailable',subtitle: 'The integration may be offline or the camera unreachable',},- 'data-video-recording': {+ 'data-video-clip': {heading: 'Video No Longer Available',- subtitle: 'This recording could not be loaded',+ subtitle: 'This clip could not be loaded',},'data-video-snapshot': {heading: 'Snapshot Unavailable',@@ -412,7 +412,7 @@// Tag the current video element with its event id for// debug visibility in console logs / DOM inspection. The// connection manager handles registration itself via the- // ``data-video-stream`` / ``data-video-recording`` markers.+ // ``data-video-stream`` / ``data-video-clip`` markers.this.tagCurrentVideoWithEventId();},@@ -487,39 +487,55 @@SnapshotStreamManager.cleanup();});- // Replay-from-start for finite recordings. Templates wrap each- // ``[data-video-recording]`` <img> in a ``.hi-video-recording``- // container that also holds a ``.hi-video-recording-replay``+ // Replay-from-start for finite clips. Templates wrap each+ // ``[data-video-clip]`` <img> in a ``.hi-video-clip``+ // container that also holds a ``.hi-video-clip-replay``// button. Delegated on body so async-loaded fragments work// without an init pass.//// Mechanism: append a fresh ``_replay`` query parameter to the// cached original URL on each click. The browser sees a new URL,// abandons the previous fetch, and starts a new one. ZoneMinder- // serves the recording from the start on each request+ // serves the clip from the start on each request// (``replay=single``). Avoids blanking the ``src`` — an empty// src would fire ``error`` and trigger ``VideoErrorHandler``'s// placeholder.- function videoRecordingReplayBuster( baseUrl ) {+ function videoClipReplayBuster( baseUrl ) {const sep = baseUrl.includes('?') ? '&' : '?';return baseUrl + sep + '_replay=' + Date.now();}jQuery(function($) {- $( 'body' ).on( 'click', '.hi-video-recording-replay', function( ev ) {+ $( 'body' ).on( 'click', '.hi-video-clip-replay', function( ev ) {ev.preventDefault();ev.stopPropagation();- const wrapper = this.closest( '.hi-video-recording' );- const img = wrapper && wrapper.querySelector( 'img[data-video-recording]' );+ const wrapper = this.closest( '.hi-video-clip' );+ if ( ! wrapper ) return;++ // <video> path (native MP4 clip): seek-to-zero ++ // play. The native element has its own seek/playhead so+ // we don't need the cache-bust trick that <img> uses.+ const video = wrapper.querySelector( 'video[data-video-clip]' );+ if ( video ) {+ try { video.currentTime = 0; } catch ( e ) {}+ const playPromise = video.play();+ if ( playPromise && playPromise.catch ) {+ playPromise.catch( () => {} );+ }+ return;+ }++ // <img> path (multipart MJPEG clip). Cache the+ // original URL on first click; subsequent clicks always+ // rebuild from this cached base so the ``_replay``+ // parameter doesn't stack.+ const img = wrapper.querySelector( 'img[data-video-clip]' );if ( ! img ) return;- // Cache the original URL on first click. Subsequent- // clicks always rebuild from this cached base so the- // ``_replay`` parameter doesn't stack.- if ( ! img.dataset.videoRecordingSrc ) {- img.dataset.videoRecordingSrc = img.src;+ if ( ! img.dataset.videoClipSrc ) {+ img.dataset.videoClipSrc = img.src;}- const baseUrl = img.dataset.videoRecordingSrc;+ const baseUrl = img.dataset.videoClipSrc;if ( ! baseUrl || baseUrl.startsWith('data:') ) return;- img.src = videoRecordingReplayBuster( baseUrl );+ img.src = videoClipReplayBuster( baseUrl );});});