Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

addons: Frigate Glance, Frigate camera pop-ups over whatever is playing

NickLD0ed210839122
diff --git a/addons/README.md b/addons/README.md
index 49aca7ff5..e0a8ecc47 100644
--- a/addons/README.md
+++ b/addons/README.md
@@ -9,9 +9,10 @@ the core bigger or change how it behaves. You install an add-on only if you want
| Add-on | What it does | Author | Tested on | Permissions |
|---|---|---|---|---|
+| [Frigate Glance](frigate-glance/) | Frigate camera pop-ups over whatever is playing | NickLD | TCL 65Q650G | overlay, accessibility (card keys), network, foreground service |
-None yet. A widget, an info tile, a storage or smart-home card: if it can live as its own small app,
-it can live here. See the rules below.
+A widget, an info tile, a storage or smart-home card: if it can live as its own small app, it can live
+here. See the rules below.
## How an add-on works
diff --git a/addons/frigate-glance/.gitignore b/addons/frigate-glance/.gitignore
new file mode 100644
index 000000000..a7e04a21b
--- /dev/null
+++ b/addons/frigate-glance/.gitignore
@@ -0,0 +1,4 @@
+.gradle/
+build/
+app/build/
+local.properties
diff --git a/addons/frigate-glance/README.md b/addons/frigate-glance/README.md
new file mode 100644
index 000000000..1bafcc456
--- /dev/null
+++ b/addons/frigate-glance/README.md
@@ -0,0 +1,110 @@
+# Frigate Glance
+
+A community add-on, not made by or affiliated with the Frigate project.
+
+## What it does
+
+While you watch anything on the TV (an app, Live TV, an HDMI input), a small card slides into a corner the
+moment [Frigate](https://frigate.video) raises an alert: which camera, what it saw (and who or which plate,
+when Frigate knows), the picture with a box around the object, and a thin bar along the top of the picture
+that is red while the event goes on and runs down once it has ended, as in Peek. The card leaves by itself
+a few seconds after the event ends.
+
+While a card is up, the remote buttons named on the card act on it: **Dismiss** (default ◀) closes it,
+**Snooze** (default ▶) closes it and keeps every card away for a while (default 1 hour), and the optional
+**Full screen** (default ▲) opens that camera on the whole screen until Back. Each can be set to act only
+when held, against an accidental press while moving around an app; a pill then draws itself around the
+action as it is held and turns green when letting go will act. Every other button keeps controlling what you
+watch, and when no card is up the add-on reads no buttons at all. A badge on the picture shows whether it is
+live video (a camera icon on red) or snapshots (stacked frames).
+
+By default only Frigate **alerts** open a card, so what counts as worth interrupting a film is set once, in
+Frigate's review settings (for example a person in a required zone), and the settings screen narrows it
+further by camera and object.
+
+![The add-on's card in the launcher's grid](docs/card-in-grid.jpg)
+
+## Permissions
+
+| Permission | Why |
+|---|---|
+| Display over other apps (`SYSTEM_ALERT_WINDOW`) | To draw the card over whatever is playing. The card never takes focus or touches. Granted by `install.sh` (TCL hides it in Settings). |
+| Accessibility service (`KeyService`) | To catch the card's buttons (Dismiss, Snooze, and Full screen when on) while a card is up. It switches key filtering on only while a card shows and off again after, and reads no other keys and no screen content. |
+| Internet (`INTERNET`) | To reach your MQTT broker and your Frigate server, and nothing else: no telemetry, no update checks, no ads. |
+| Foreground service (`FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_DATA_SYNC`) | One background service keeps the MQTT connection open (a keep-alive every 30 s, no polling). |
+| Start at boot (`RECEIVE_BOOT_COMPLETED`) | To reconnect after a reboot. On TCL sets `install.sh` also allows the `APP_AUTO_START` app-op, without which TCL's firmware blocks it. |
+
+Two components only the ADB shell can use (they need `WRITE_SECURE_SETTINGS`, as the launcher's
+ThemeProvider): `ConfigProvider` takes `config.json` on firmware that locks the shell out of `Android/data`,
+and `TestCardReceiver` shows a test card over whatever is playing.
+
+## Setup
+
+1. Make a config file from [`config.example.json`](config.example.json) and keep it outside the repo
+ (`backup/` is git-ignored). Use a Frigate user with the **viewer** role (Frigate user names take no `-`)
+ and an MQTT user of its own rather than your main accounts.
+2. Install, from the repo root, with ADB on as for the launcher:
+
+ ```bash
+ TV_HOST=<tv ip> addons/frigate-glance/install.sh backup/frigate-glance-config.json
+ ```
+
+ It builds the add-on, installs it, grants the overlay and auto-start, pushes the config, turns on the key
+ service next to any the launcher uses, and prints `MQTT: ok` and `Frigate: ok` (or what went wrong), then
+ shows a test card. The pushed file is deleted on the TV once the add-on has read it.
+3. Press Home and answer **Show card** when the launcher asks about the add-on's card. Open it for the
+ settings, in five sections: **Overview** (snooze, connection status), **Cameras** (which cameras, and
+ whether cameras added later count), **Alerts** (alerts only or detections too, which objects), **Card**
+ (a test card for any camera, size, corner, how long it stays, live video, boxes) and **Remote** (each key
+ picked by pressing it, hold to act, full screen). Settings changed there stay until the next config push.
+
+## Config keys
+
+| Key | Default | Meaning |
+|---|---|---|
+| `mqtt` | required | `mqtt://user:password@host:1883`; percent-encode `@ : /` in the user or password |
+| `frigateUrl` | required | `https://host:8971` (authenticated port) or `http://host:5000` |
+| `frigateUser`, `frigatePassword` | empty | Frigate login; the certificate is trusted on first contact and pinned |
+| `topicPrefix` | `frigate` | Frigate's MQTT topic prefix |
+| `cameras` | `{}` (all) | camera name to the name shown on the card; listed cameras only |
+| `newCameras` | `false` | with `cameras` listed: cameras Frigate gains later open cards too |
+| `camerasOff` | `[]` | cameras switched off (the settings screen writes this) |
+| `labels` | `[]` (all) | objects that may open a card, e.g. `["person"]` |
+| `severity` | `alerts` | `alerts`, or `alerts_and_detections` |
+| `corner` | `top-right` | `top-left`, `bottom-left`, `bottom-right` |
+| `cardScale` | `100` | card size in percent (50 to 200), picture and text together |
+| `dismissSeconds` | `8` | seconds the card stays after the event ends (1 to 120) |
+| `snoozeMinutes` | `60` | length of a snooze (5 to 720) |
+| `liveVideo` | `true` | live picture from go2rtc's RTSP port 8554; `false` refreshes a snapshot every second |
+| `streams` | `{}` | camera to the go2rtc stream for live video, when Frigate's own live stream is too big |
+| `rtspUser`, `rtspPassword` | empty | go2rtc RTSP credentials, if set |
+| `boxes` | `true` | boxes around detected objects |
+| `fullscreen`, `fullscreenKey` | `false`, `KEYCODE_DPAD_UP` | a third card key that opens the camera full screen; Back returns |
+| `dismissHold`, `snoozeHold`, `fullscreenHold` | `false` | that key acts only when held for 0.6 s; a quick press does nothing |
+| `dismissKey`, `snoozeKey` | `KEYCODE_DPAD_LEFT`, `KEYCODE_DPAD_RIGHT` | Android key names; Back, OK, Enter and Home are refused |
+
+## Live video
+
+Live video comes from go2rtc's RTSP port (8554) on the Frigate host, decoded by the TV's own video decoder.
+While another app is playing sound, the card shows snapshots instead: on the test TV a second video stream
+next to a playing YouTube video failed and made YouTube stall for a moment. Over Home and menus it plays
+live, the first frame after about 1.3 s. A camera's main stream can be large (the test cameras send
+2560x1920); publishing the camera's sub-stream in go2rtc and naming it in `streams` makes it lighter.
+
+A Frigate debug replay (camera `_replay_<name>`) counts as the camera it replays and shows as "Name
+(replay)". Frigate publishes no review items for a replay, so each tracked object stands in for an alert, and
+go2rtc has no stream for it, so a replay card always shows snapshots.
+
+## Tested on
+
+TCL 65Q650G (Android TV 11, Realtek RTD2851, 2 GB) with the reference launcher 2.6, Frigate 0.18.2 and the
+Home Assistant Mosquitto broker. Checked with the real remote: Dismiss and Snooze over a playing YouTube
+video without it seeking, every other key passing through, the launcher's Netflix, YouTube, Prime, Settings
+and Input buttons unchanged, the card over Home, YouTube and the settings screen, reconnecting after a
+reboot without opening the app, hold to snooze, and a Frigate debug replay of a camera. Memory: about 25 MB idle, 40 to 53 MB with a card and live video up, about
+35 MB after a card.
+
+## Credits
+
+The idea, the timer bar and the config keys follow [Peek](https://github.com/casi-3/peek) (MIT), the desktop
+version.
diff --git a/addons/frigate-glance/app/build.gradle b/addons/frigate-glance/app/build.gradle
new file mode 100644
index 000000000..5641b545c
--- /dev/null
+++ b/addons/frigate-glance/app/build.gradle
@@ -0,0 +1,44 @@
+plugins {
+ id 'com.android.application'
+}
+
+android {
+ namespace 'io.github.nickld.frigateglance'
+ compileSdk 34
+
+ defaultConfig {
+ applicationId 'io.github.nickld.frigateglance'
+ minSdk 26
+ targetSdk 34
+ versionCode 1
+ versionName '0.1'
+ }
+
+ buildTypes {
+ release {
+ minifyEnabled true
+ shrinkResources true
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
+ // Sideloaded over ADB, never published: signed with the debug key, like the launcher.
+ signingConfig signingConfigs.debug
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_17
+ targetCompatibility JavaVersion.VERSION_17
+ }
+
+ testOptions {
+ unitTests.returnDefaultValues = true
+ }
+}
+
+dependencies {
+ implementation 'androidx.media3:media3-exoplayer:1.4.1'
+ implementation 'androidx.media3:media3-exoplayer-rtsp:1.4.1'
+ implementation 'androidx.media3:media3-ui:1.4.1'
+ // Test only (never in the APK): plain JVM tests, src/test. org.json because android.jar's copy is a stub there.
+ testImplementation 'junit:junit:4.13.2'
+ testImplementation 'org.json:json:20231013'
+}
diff --git a/addons/frigate-glance/app/proguard-rules.pro b/addons/frigate-glance/app/proguard-rules.pro
new file mode 100644
index 000000000..a4435d69a
--- /dev/null
+++ b/addons/frigate-glance/app/proguard-rules.pro
@@ -0,0 +1,2 @@
+# Keep class and method names: readable stack traces matter more than the last few KB in a sideloaded app.
+-dontobfuscate
diff --git a/addons/frigate-glance/app/src/main/AndroidManifest.xml b/addons/frigate-glance/app/src/main/AndroidManifest.xml
new file mode 100644
index 000000000..28c95a9e2
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/AndroidManifest.xml
@@ -0,0 +1,83 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <uses-feature android:name="android.software.leanback" android:required="false" />
+ <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
+
+ <!-- The MQTT broker and Frigate, nothing else. -->
+ <uses-permission android:name="android.permission.INTERNET" />
+ <!-- The card is drawn over whatever is playing. -->
+ <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
+ <!-- One foreground service keeps the MQTT connection. -->
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
+ <!-- Reconnect after a reboot. -->
+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
+
+ <application
+ android:allowBackup="false"
+ android:banner="@drawable/banner"
+ android:icon="@mipmap/ic_launcher"
+ android:label="@string/app_name"
+ android:theme="@android:style/Theme.DeviceDefault.NoActionBar">
+
+ <activity
+ android:name=".SettingsActivity"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
+ </intent-filter>
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="com.gathin.tvhome.category.DOCK_CARD" />
+ </intent-filter>
+ <meta-data android:name="com.gathin.tvhome.card" android:resource="@xml/module_card" />
+ </activity>
+
+ <activity
+ android:name=".FullscreenActivity"
+ android:exported="false"
+ android:excludeFromRecents="true"
+ android:launchMode="singleTask"
+ android:taskAffinity="io.github.nickld.frigateglance.fullscreen"
+ android:theme="@android:style/Theme.DeviceDefault.NoActionBar.Fullscreen" />
+
+ <service
+ android:name=".GlanceService"
+ android:exported="false"
+ android:foregroundServiceType="dataSync" />
+
+ <service
+ android:name=".KeyService"
+ android:exported="false"
+ android:label="@string/app_name"
+ android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
+ <intent-filter>
+ <action android:name="android.accessibilityservice.AccessibilityService" />
+ </intent-filter>
+ <meta-data
+ android:name="android.accessibilityservice"
+ android:resource="@xml/key_service" />
+ </service>
+
+ <provider
+ android:name=".ConfigProvider"
+ android:authorities="${applicationId}.config"
+ android:exported="true"
+ android:permission="android.permission.WRITE_SECURE_SETTINGS" />
+
+ <receiver
+ android:name=".TestCardReceiver"
+ android:exported="true"
+ android:permission="android.permission.WRITE_SECURE_SETTINGS" />
+
+ <receiver
+ android:name=".BootReceiver"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="android.intent.action.BOOT_COMPLETED" />
+ </intent-filter>
+ </receiver>
+ </application>
+</manifest>
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/BootReceiver.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/BootReceiver.java
new file mode 100644
index 000000000..c2960f2ed
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/BootReceiver.java
@@ -0,0 +1,13 @@
+package io.github.nickld.frigateglance;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+
+/** Reconnects after a reboot. TCL firmware also needs the APP_AUTO_START app-op for this to run. */
+public class BootReceiver extends BroadcastReceiver {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) GlanceService.start(context);
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/BoxView.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/BoxView.java
new file mode 100644
index 000000000..e97f40afa
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/BoxView.java
@@ -0,0 +1,41 @@
+package io.github.nickld.frigateglance;
+
+import android.content.Context;
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.RectF;
+import android.view.View;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** Draws the detected objects' boxes, given as fractions of the frame, over the picture. */
+final class BoxView extends View {
+ private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
+ private final RectF rect = new RectF();
+ private final float radius;
+ private List<float[]> boxes = new ArrayList<>();
+
+ BoxView(Context context) {
+ super(context);
+ float dp = context.getResources().getDisplayMetrics().density;
+ paint.setStyle(Paint.Style.STROKE);
+ paint.setStrokeWidth(2 * dp);
+ paint.setColor(0xFF3DDC84);
+ radius = 4 * dp;
+ }
+
+ void setBoxes(List<float[]> b) {
+ boxes = b == null ? new ArrayList<>() : b;
+ invalidate();
+ }
+
+ @Override
+ protected void onDraw(Canvas canvas) {
+ int w = getWidth(), h = getHeight();
+ for (float[] b : boxes) {
+ rect.set(b[0] * w, b[1] * h, b[2] * w, b[3] * h);
+ canvas.drawRoundRect(rect, radius, radius, paint);
+ }
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/CameraPickerDialog.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/CameraPickerDialog.java
new file mode 100644
index 000000000..05f16df21
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/CameraPickerDialog.java
@@ -0,0 +1,49 @@
+package io.github.nickld.frigateglance;
+
+import android.app.Dialog;
+import android.content.Context;
+import android.graphics.Color;
+import android.graphics.drawable.ColorDrawable;
+import android.view.Window;
+import android.widget.LinearLayout;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+import java.util.Map;
+import java.util.function.Consumer;
+
+/** "Which camera?" for a test card: one row per camera, OK picks it, Back closes. */
+final class CameraPickerDialog extends Dialog {
+ /** cameras: Frigate's camera name to the name shown. */
+ CameraPickerDialog(Context context, Map<String, String> cameras, Consumer<String> onPicked) {
+ super(context);
+ requestWindowFeature(Window.FEATURE_NO_TITLE);
+ float dp = context.getResources().getDisplayMetrics().density;
+ LinearLayout box = new LinearLayout(context);
+ box.setOrientation(LinearLayout.VERTICAL);
+ box.setBackgroundResource(R.drawable.card_glass);
+ int pad = Math.round(24 * dp);
+ box.setPadding(pad, pad, pad, pad);
+ TextView title = new TextView(context);
+ title.setText("Show a test card for");
+ title.setTextSize(20);
+ title.setTextColor(0xFFFFFFFF);
+ title.setPadding(Math.round(16 * dp), 0, 0, Math.round(8 * dp));
+ box.addView(title);
+ LinearLayout list = new LinearLayout(context);
+ list.setOrientation(LinearLayout.VERTICAL);
+ for (Map.Entry<String, String> cam : cameras.entrySet()) {
+ list.addView(new SettingRow(context, cam.getValue(), "", () -> {
+ dismiss();
+ onPicked.accept(cam.getKey());
+ }), new LinearLayout.LayoutParams(Math.round(360 * dp), LinearLayout.LayoutParams.WRAP_CONTENT));
+ }
+ ScrollView scroll = new ScrollView(context);
+ scroll.addView(list);
+ box.addView(scroll);
+ setContentView(box);
+ Window w = getWindow();
+ if (w != null) w.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
+ if (list.getChildCount() > 0) list.getChildAt(0).requestFocus();
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/CardController.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/CardController.java
new file mode 100644
index 000000000..f85994701
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/CardController.java
@@ -0,0 +1,181 @@
+package io.github.nickld.frigateglance;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.LongSupplier;
+
+/**
+ * When a card shows, changes and leaves. One card at a time: a new matching review replaces it. It leaves
+ * dismissSeconds after its review ends, and at the latest 120 s after its last news, so a lost "end"
+ * message can never leave a card on screen. Not thread-safe: the service calls it from one thread.
+ */
+public final class CardController {
+ static final long HARD_LIMIT_MS = 120_000;
+ /** A replay's camera can vanish without an "end"; its card leaves this long after its last message. */
+ static final long REPLAY_QUIET_MS = 15_000;
+ static final String TEST_ID = "test";
+ private static final long TEST_EXTRA_MS = 10_000;
+
+ private final CardView view;
+ private final ReviewFilter filter;
+ private final Map<String, String> displayNames;
+ private final int dismissSeconds;
+ private final LongSupplier clock;
+
+ private Review shown;
+ private final Map<String, Detection> detections = new LinkedHashMap<>();
+ private long deadline;
+ /** True once the shown card is counting down to leaving (its review ended, or a test card). */
+ private boolean ending;
+ private long snoozedUntil;
+ /** Reviews that had a card which then left (dismissed, ended, replaced): their updates never reopen one. */
+ private final java.util.Set<String> closed = java.util.Collections.newSetFromMap(
+ new java.util.LinkedHashMap<String, Boolean>() {
+ @Override
+ protected boolean removeEldestEntry(Map.Entry<String, Boolean> e) {
+ return size() > 64;
+ }
+ });
+
+ public CardController(CardView view, ReviewFilter filter, Map<String, String> displayNames, int dismissSeconds,
+ LongSupplier clock) {
+ this.view = view;
+ this.filter = filter;
+ this.displayNames = displayNames;
+ this.dismissSeconds = dismissSeconds;
+ this.clock = clock;
+ }
+
+ public void onReview(Review r) {
+ long now = clock.getAsLong();
+ boolean isShown = shown != null && shown.id.equals(r.id);
+ // An update opens a card too when nothing is up and this review never had one: the add-on connected
+ // mid-event (a reconnect, a reinstall, a Frigate debug replay already running).
+ boolean late = "update".equals(r.type) && !isShown && shown == null && !closed.contains(r.id);
+ if ("new".equals(r.type) || late) {
+ if (!filter.shows(r, now, snoozedUntil)) return;
+ if (shown != null) closed.add(shown.id);
+ shown = r;
+ detections.clear();
+ deadline = now + quietLimit(r);
+ ending = false;
+ view.show(model());
+ } else if (isShown && "update".equals(r.type)) {
+ shown = r;
+ deadline = now + quietLimit(r);
+ ending = false;
+ view.update(model());
+ } else if (isShown && "end".equals(r.type)) {
+ shown = r;
+ deadline = now + dismissSeconds * 1000L;
+ ending = true;
+ view.update(model());
+ }
+ }
+
+ private static long quietLimit(Review r) {
+ return r.camera.startsWith(ReviewFilter.REPLAY_PREFIX) ? REPLAY_QUIET_MS : HARD_LIMIT_MS;
+ }
+
+ public void onDetection(Detection d) {
+ if (shown == null || !shown.detectionIds.contains(d.id)) return;
+ if (d.ended) detections.remove(d.id);
+ else detections.put(d.id, d);
+ view.update(model());
+ }
+
+ public void onAvailable(boolean online) {
+ if (!online) hideNow();
+ }
+
+ /** A card that does not come from Frigate, to check placement and the buttons. */
+ public void showTest(String camera) {
+ String after = "{\"id\":\"" + TEST_ID + "\",\"camera\":\"" + camera + "\",\"severity\":\"alert\",\"data\":{}}";
+ shown = Review.parse("{\"type\":\"new\",\"after\":" + after + "}");
+ detections.clear();
+ deadline = clock.getAsLong() + dismissSeconds * 1000L + TEST_EXTRA_MS;
+ ending = true;
+ view.show(model());
+ }
+
+ public void dismiss() {
+ hideNow();
+ }
+
+ public void snooze(int minutes) {
+ snoozedUntil = clock.getAsLong() + minutes * 60_000L;
+ hideNow();
+ }
+
+ public void resume() {
+ snoozedUntil = 0;
+ }
+
+ public long snoozedUntil() {
+ return snoozedUntil > clock.getAsLong() ? snoozedUntil : 0;
+ }
+
+ /** The camera of the card on screen, or null. */
+ public String shownCamera() {
+ return shown == null ? null : shown.camera;
+ }
+
+ public boolean isShowing() {
+ return shown != null;
+ }
+
+ /** Called once a second. */
+ public void tick() {
+ if (shown != null && clock.getAsLong() >= deadline) hideNow();
+ }
+
+ private void hideNow() {
+ if (shown == null) return;
+ closed.add(shown.id);
+ shown = null;
+ detections.clear();
+ view.hide();
+ }
+
+ private CardModel model() {
+ List<float[]> boxes = new ArrayList<>();
+ for (Detection d : detections.values()) if (d.box != null) boxes.add(d.box);
+ long countdown = ending ? Math.max(0, deadline - clock.getAsLong()) : 0;
+ return new CardModel(shown.id, shown.camera, displayName(shown.camera), detail(), boxes, countdown);
+ }
+
+ private String detail() {
+ if (TEST_ID.equals(shown.id)) return "Test card";
+ Set<String> parts = new LinkedHashSet<>();
+ for (String o : shown.objects) parts.add(pretty(o));
+ for (Detection d : detections.values()) {
+ if (d.subLabel != null) parts.add(d.subLabel);
+ if (d.plate != null) parts.add(d.plate);
+ }
+ for (String z : shown.zones) parts.add(pretty(z));
+ return String.join(" · ", parts);
+ }
+
+ private String displayName(String camera) {
+ String base = ReviewFilter.baseCamera(camera);
+ if (!base.equals(camera)) return displayName(base) + " (replay)";
+ String n = displayNames.get(camera);
+ return n != null && !n.isEmpty() ? n : pretty(camera);
+ }
+
+ /** Peek's prettyName: separators become spaces, each word capitalised. */
+ static String pretty(String name) {
+ StringBuilder out = new StringBuilder();
+ for (String w : name.split("[_\\-\\s]+")) {
+ if (w.isEmpty()) continue;
+ if (out.length() > 0) out.append(' ');
+ out.append(w.substring(0, 1).toUpperCase(Locale.ROOT)).append(w.substring(1));
+ }
+ return out.toString();
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/CardModel.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/CardModel.java
new file mode 100644
index 000000000..c8a92087e
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/CardModel.java
@@ -0,0 +1,21 @@
+package io.github.nickld.frigateglance;
+
+import java.util.List;
+
+/** Everything a card shows, apart from the picture. */
+public final class CardModel {
+ public final String reviewId, camera, title, detail;
+ /** Normalised boxes, x1, y1, x2, y2. */
+ public final List<float[]> boxes;
+ /** 0 while the event goes on; once it has ended, the time left before the card leaves (Peek's timer bar). */
+ public final long countdownMs;
+
+ CardModel(String reviewId, String camera, String title, String detail, List<float[]> boxes, long countdownMs) {
+ this.reviewId = reviewId;
+ this.camera = camera;
+ this.title = title;
+ this.detail = detail;
+ this.boxes = boxes;
+ this.countdownMs = countdownMs;
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/CardText.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/CardText.java
new file mode 100644
index 000000000..f018af428
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/CardText.java
@@ -0,0 +1,55 @@
+package io.github.nickld.frigateglance;
+
+import java.util.Locale;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/** The card's footer: which button does what, in words a remote's owner recognises. */
+final class CardText {
+ private static final Map<String, String> SHORT = Map.of(
+ "KEYCODE_DPAD_LEFT", "◀",
+ "KEYCODE_DPAD_RIGHT", "▶",
+ "KEYCODE_DPAD_UP", "▲",
+ "KEYCODE_DPAD_DOWN", "▼",
+ "KEYCODE_PROG_RED", "Red",
+ "KEYCODE_PROG_GREEN", "Green",
+ "KEYCODE_PROG_YELLOW", "Yellow",
+ "KEYCODE_PROG_BLUE", "Blue");
+
+ private CardText() {}
+
+ static String footer(String dismissKey, String snoozeKey, int snoozeMinutes) {
+ return footer(dismissKey, snoozeKey, snoozeMinutes, null);
+ }
+
+ /** fullscreenKey null while the full screen feature is off. Keys that need a hold get a pill on the card, no word. */
+ static String footer(String dismissKey, String snoozeKey, int snoozeMinutes, String fullscreenKey) {
+ return String.join(" · ", parts(dismissKey, snoozeKey, snoozeMinutes, fullscreenKey).values());
+ }
+
+ /** The footer's actions in order (KeyRules.DISMISS, SNOOZE, FULLSCREEN) with their labels. */
+ static Map<Integer, String> parts(String dismissKey, String snoozeKey, int snoozeMinutes, String fullscreenKey) {
+ Map<Integer, String> m = new LinkedHashMap<>();
+ m.put(KeyRules.DISMISS, key(dismissKey) + " Dismiss");
+ m.put(KeyRules.SNOOZE, key(snoozeKey) + " Snooze " + duration(snoozeMinutes));
+ if (fullscreenKey != null) m.put(KeyRules.FULLSCREEN, key(fullscreenKey) + " Full screen");
+ return m;
+ }
+
+ static String duration(int minutes) {
+ return minutes % 60 == 0 ? (minutes / 60) + "h" : minutes + " min";
+ }
+
+ static String key(String name) {
+ String s = SHORT.get(name);
+ if (s != null) return s;
+ String[] words = name.replaceFirst("^KEYCODE_", "").toLowerCase(Locale.ROOT).split("_");
+ StringBuilder out = new StringBuilder();
+ for (String w : words) {
+ if (w.isEmpty()) continue;
+ if (out.length() > 0) out.append(' ');
+ out.append(Character.toUpperCase(w.charAt(0))).append(w.substring(1));
+ }
+ return out.toString();
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/CardView.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/CardView.java
new file mode 100644
index 000000000..897a64f95
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/CardView.java
@@ -0,0 +1,10 @@
+package io.github.nickld.frigateglance;
+
+/** What the card on screen can be told to do; OverlayCard draws it, tests record it. */
+public interface CardView {
+ void show(CardModel m);
+
+ void update(CardModel m);
+
+ void hide();
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/ConfigProvider.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/ConfigProvider.java
new file mode 100644
index 000000000..261678e42
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/ConfigProvider.java
@@ -0,0 +1,45 @@
+package io.github.nickld.frigateglance;
+
+import android.content.ContentProvider;
+import android.content.ContentValues;
+import android.database.Cursor;
+import android.net.Uri;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.ParcelFileDescriptor;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+
+/**
+ * For firmware that locks the shell out of Android/data (TCL G07, Android 11): install.sh writes config.json
+ * here with `content write`, as tools/theme.sh does for the launcher. Write-only, one file name, and only the
+ * shell can call it (WRITE_SECURE_SETTINGS on the provider). The file is imported once it is closed.
+ */
+public class ConfigProvider extends ContentProvider {
+ private static final String NAME = "config.json";
+
+ @Override
+ public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
+ if (!mode.contains("w") || !NAME.equals(uri.getLastPathSegment())) throw new FileNotFoundException(uri.toString());
+ File dir = getContext().getExternalFilesDir(null);
+ if (dir == null || (!dir.isDirectory() && !dir.mkdirs())) throw new FileNotFoundException("no files folder");
+ try {
+ return ParcelFileDescriptor.open(new File(dir, NAME),
+ ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE,
+ new Handler(Looper.getMainLooper()),
+ e -> {
+ if (e == null && new ConfigStore(getContext()).importPushed()) GlanceService.reload(getContext());
+ });
+ } catch (java.io.IOException e) {
+ throw new FileNotFoundException(e.getMessage());
+ }
+ }
+
+ @Override public boolean onCreate() { return true; }
+ @Override public String getType(Uri uri) { return null; }
+ @Override public Cursor query(Uri uri, String[] p, String s, String[] a, String o) { return null; }
+ @Override public Uri insert(Uri uri, ContentValues values) { return null; }
+ @Override public int update(Uri uri, ContentValues v, String s, String[] a) { return 0; }
+ @Override public int delete(Uri uri, String s, String[] a) { return 0; }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/ConfigStore.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/ConfigStore.java
new file mode 100644
index 000000000..57a210a35
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/ConfigStore.java
@@ -0,0 +1,117 @@
+package io.github.nickld.frigateglance;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.util.Log;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * Where the config lives on the TV. A config.json pushed over ADB lands in the app's external files folder
+ * (or arrives through ConfigProvider); importPushed() validates it, keeps it in private storage and deletes
+ * the pushed copy, so the passwords do not stay in a folder the shell can read. The settings screen's
+ * choices are kept as overrides until the next pushed file replaces them.
+ */
+public final class ConfigStore {
+ static final String TAG = "FrigateGlance";
+ private static final String PRIVATE_NAME = "config.json";
+ private static final String KEY_OVERRIDES = "overrides";
+ private static final String KEY_PIN = "certSha256";
+
+ private final Context context;
+ private final SharedPreferences prefs;
+
+ public ConfigStore(Context context) {
+ this.context = context.getApplicationContext();
+ this.prefs = this.context.getSharedPreferences("settings", Context.MODE_PRIVATE);
+ }
+
+ /** The config with the settings screen's overrides, or null when none has been imported yet. */
+ public GlanceConfig load() {
+ File f = new File(context.getFilesDir(), PRIVATE_NAME);
+ if (!f.isFile()) return null;
+ try {
+ GlanceConfig base = GlanceConfig.parse(read(f));
+ try {
+ return base.withOverrides(new JSONObject(prefs.getString(KEY_OVERRIDES, "{}")));
+ } catch (IllegalArgumentException | JSONException e) {
+ Log.w(TAG, "settings ignored: " + e.getMessage());
+ return base;
+ }
+ } catch (IOException | IllegalArgumentException e) {
+ Log.w(TAG, "config unreadable: " + e.getMessage());
+ return null;
+ }
+ }
+
+ /** Imports a pushed config.json, if there is one. True when one was imported. */
+ public boolean importPushed() {
+ File dir = context.getExternalFilesDir(null);
+ File pushed = dir == null ? null : new File(dir, PRIVATE_NAME);
+ if (pushed == null || !pushed.isFile()) return false;
+ try {
+ return importJson(read(pushed));
+ } catch (IOException e) {
+ Log.w(TAG, "pushed config unreadable: " + e.getMessage());
+ return false;
+ } finally {
+ if (!pushed.delete()) Log.w(TAG, "could not delete the pushed config");
+ }
+ }
+
+ /** Validates and stores a config file's text; clears the settings overrides. */
+ public boolean importJson(String json) {
+ try {
+ GlanceConfig.parse(json);
+ } catch (IllegalArgumentException e) {
+ Log.w(TAG, "pushed config rejected: " + e.getMessage());
+ return false;
+ }
+ try (FileOutputStream out = new FileOutputStream(new File(context.getFilesDir(), PRIVATE_NAME))) {
+ out.write(json.getBytes(StandardCharsets.UTF_8));
+ } catch (IOException e) {
+ Log.w(TAG, "could not store config: " + e.getMessage());
+ return false;
+ }
+ prefs.edit().remove(KEY_OVERRIDES).remove(KEY_PIN).apply();
+ Log.i(TAG, "config imported");
+ return true;
+ }
+
+ /** Saves one setting from the settings screen. */
+ public void saveSetting(String key, Object value) {
+ try {
+ JSONObject o = new JSONObject(prefs.getString(KEY_OVERRIDES, "{}"));
+ o.put(key, value);
+ prefs.edit().putString(KEY_OVERRIDES, o.toString()).apply();
+ } catch (JSONException e) {
+ Log.w(TAG, "setting not saved: " + e.getMessage());
+ }
+ }
+
+ public String certPin() {
+ return prefs.getString(KEY_PIN, "");
+ }
+
+ public void saveCertPin(String sha256) {
+ prefs.edit().putString(KEY_PIN, sha256).apply();
+ }
+
+ private static String read(File f) throws IOException {
+ try (InputStream in = new FileInputStream(f)) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ byte[] buf = new byte[4096];
+ for (int n; (n = in.read(buf)) > 0; ) out.write(buf, 0, n);
+ return out.toString("UTF-8");
+ }
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/Detection.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/Detection.java
new file mode 100644
index 000000000..1181eb0ca
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/Detection.java
@@ -0,0 +1,63 @@
+package io.github.nickld.frigateglance;
+
+import java.util.List;
+import java.util.Map;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * One tracked object from frigate/events: what it is, who or which plate, and where. The box is scaled to
+ * 0..1 by the camera's detect size, as Peek's normalizeBox does, so it can be drawn over any picture size.
+ */
+public final class Detection {
+ public final String id, camera, label, subLabel, plate;
+ public final double score;
+ /** x1, y1, x2, y2 as fractions of the frame, or null when the camera's detect size is unknown. */
+ public final float[] box;
+ public final List<String> zones;
+ /** Frigate stopped tracking it ("end"): it has left the picture, so its box goes. */
+ public final boolean ended;
+
+ private Detection(JSONObject a, Map<String, int[]> detectSize, boolean ended) {
+ this.ended = ended;
+ id = a.optString("id", "");
+ camera = a.optString("camera", "");
+ label = a.optString("label", "");
+ subLabel = subLabel(a.opt("sub_label"));
+ String p = a.optString("recognized_license_plate", "");
+ plate = p.isEmpty() || "null".equals(p) ? null : p;
+ score = a.optDouble("score", a.optDouble("top_score", 0));
+ box = box(a.optJSONArray("box"), detectSize.get(camera));
+ zones = Json.strings(a.optJSONArray("entered_zones"));
+ }
+
+ /** The parsed message, or null when it is not an event message. */
+ public static Detection parse(String payload, Map<String, int[]> detectSize) {
+ try {
+ JSONObject o = new JSONObject(payload);
+ JSONObject after = o.optJSONObject("after");
+ if (after == null) return null;
+ Detection d = new Detection(after, detectSize, "end".equals(o.optString("type", "")));
+ return d.id.isEmpty() || d.camera.isEmpty() ? null : d;
+ } catch (JSONException e) {
+ return null;
+ }
+ }
+
+ private static String subLabel(Object v) {
+ if (v instanceof JSONArray) v = ((JSONArray) v).opt(0);
+ if (v == null || v == JSONObject.NULL) return null;
+ String s = v.toString();
+ return s.isEmpty() ? null : s;
+ }
+
+ private static float[] box(JSONArray b, int[] size) {
+ if (b == null || b.length() < 4 || size == null || size[0] <= 0 || size[1] <= 0) return null;
+ return new float[] {
+ (float) (b.optDouble(0) / size[0]), (float) (b.optDouble(1) / size[1]),
+ (float) (b.optDouble(2) / size[0]), (float) (b.optDouble(3) / size[1]),
+ };
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/FrigateApi.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/FrigateApi.java
new file mode 100644
index 000000000..db9e2f234
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/FrigateApi.java
@@ -0,0 +1,232 @@
+package io.github.nickld.frigateglance;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * Frigate's HTTP API, as Peek uses it: log in on the authenticated port (8971) for a frigate_token cookie,
+ * read /api/config, fetch a camera's latest frame. Frigate's certificate is usually self-signed, so it is
+ * trusted on first contact and pinned (SHA-256 of the leaf certificate) from then on.
+ */
+public final class FrigateApi {
+ public interface PinListener {
+ void onFirstPin(String sha256);
+ }
+
+ private static final int TIMEOUT_MS = 10_000;
+
+ private final String baseUrl, user, password;
+ private final PinListener pinListener;
+ private volatile String pin;
+ private volatile String token;
+
+ public FrigateApi(String baseUrl, String user, String password, String pinnedSha256, PinListener onFirstPin) {
+ this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
+ this.user = user == null ? "" : user;
+ this.password = password == null ? "" : password;
+ this.pin = pinnedSha256 == null ? "" : pinnedSha256;
+ this.pinListener = onFirstPin;
+ }
+
+ public JSONObject config() throws IOException {
+ try {
+ return new JSONObject(new String(get("/api/config"), StandardCharsets.UTF_8));
+ } catch (JSONException e) {
+ throw new IOException("Frigate sent an unreadable config: " + e.getMessage(), e);
+ }
+ }
+
+ public byte[] latestJpeg(String camera, int height) throws IOException {
+ return get("/api/" + URLEncoder.encode(camera, "UTF-8") + "/latest.jpg?h=" + height);
+ }
+
+ /** camera name to {width, height} of its detect stream; boxes in events are in these pixels. */
+ public static Map<String, int[]> detectSizes(JSONObject config) {
+ Map<String, int[]> out = new HashMap<>();
+ JSONObject cams = config.optJSONObject("cameras");
+ if (cams == null) return out;
+ for (Iterator<String> it = cams.keys(); it.hasNext(); ) {
+ String name = it.next();
+ JSONObject cam = cams.optJSONObject(name);
+ JSONObject detect = cam == null ? null : cam.optJSONObject("detect");
+ if (detect == null) continue;
+ int w = detect.optInt("width", 0), h = detect.optInt("height", 0);
+ if (w > 0 && h > 0) out.put(name, new int[] {w, h});
+ }
+ return out;
+ }
+
+ /** camera name to its go2rtc stream: the first of cameras.<name>.live.streams, else the camera name. */
+ public static Map<String, String> liveStreams(JSONObject config) {
+ Map<String, String> out = new HashMap<>();
+ JSONObject cams = config.optJSONObject("cameras");
+ if (cams == null) return out;
+ for (Iterator<String> it = cams.keys(); it.hasNext(); ) {
+ String name = it.next();
+ JSONObject cam = cams.optJSONObject(name);
+ JSONObject live = cam == null ? null : cam.optJSONObject("live");
+ JSONObject streams = live == null ? null : live.optJSONObject("streams");
+ String stream = name;
+ if (streams != null) {
+ Iterator<String> keys = streams.keys();
+ if (keys.hasNext()) stream = streams.optString(keys.next(), name);
+ }
+ out.put(name, stream);
+ }
+ return out;
+ }
+
+ static String tokenFromSetCookie(List<String> headers) {
+ if (headers == null) return null;
+ for (String h : headers) {
+ for (String part : h.split(";")) {
+ String p = part.trim();
+ if (p.startsWith("frigate_token=")) return p.substring("frigate_token=".length());
+ }
+ }
+ return null;
+ }
+
+ private byte[] get(String path) throws IOException {
+ if (!user.isEmpty() && token == null) login();
+ HttpURLConnection c = open(path);
+ int code = c.getResponseCode();
+ if (code == 401 && !user.isEmpty()) {
+ c.disconnect();
+ login();
+ c = open(path);
+ code = c.getResponseCode();
+ }
+ if (code != 200) {
+ c.disconnect();
+ throw new IOException("Frigate answered HTTP " + code + " for " + path.replaceFirst("\\?.*", ""));
+ }
+ try (InputStream in = c.getInputStream()) {
+ return readAll(in);
+ } finally {
+ c.disconnect();
+ }
+ }
+
+ private void login() throws IOException {
+ token = null;
+ HttpURLConnection c = connection("/api/login");
+ c.setRequestMethod("POST");
+ c.setDoOutput(true);
+ c.setRequestProperty("Content-Type", "application/json");
+ byte[] body;
+ try {
+ body = new JSONObject().put("user", user).put("password", password).toString().getBytes(StandardCharsets.UTF_8);
+ } catch (JSONException e) {
+ throw new IOException(e);
+ }
+ try (OutputStream out = c.getOutputStream()) {
+ out.write(body);
+ }
+ int code = c.getResponseCode();
+ String t = null;
+ for (Map.Entry<String, List<String>> e : c.getHeaderFields().entrySet()) {
+ if (e.getKey() != null && e.getKey().toLowerCase(Locale.ROOT).equals("set-cookie")) t = tokenFromSetCookie(e.getValue());
+ if (t != null) break;
+ }
+ c.disconnect();
+ if (code == 401 || code == 400) throw new IOException("Frigate refused the username or password");
+ if (code != 200 || t == null) throw new IOException("Frigate login failed (HTTP " + code + ")");
+ token = t;
+ }
+
+ private HttpURLConnection open(String path) throws IOException {
+ HttpURLConnection c = connection(path);
+ if (token != null) c.setRequestProperty("Cookie", "frigate_token=" + token);
+ return c;
+ }
+
+ private HttpURLConnection connection(String path) throws IOException {
+ HttpURLConnection c = (HttpURLConnection) new URL(baseUrl + path).openConnection();
+ c.setConnectTimeout(TIMEOUT_MS);
+ c.setReadTimeout(TIMEOUT_MS);
+ c.setUseCaches(false);
+ if (c instanceof HttpsURLConnection) {
+ HttpsURLConnection https = (HttpsURLConnection) c;
+ https.setSSLSocketFactory(pinnedFactory());
+ // The pin is checked in the trust manager; the certificate rarely names the IP Frigate is reached on.
+ https.setHostnameVerifier((host, session) -> true);
+ }
+ return c;
+ }
+
+ private SSLSocketFactory pinnedFactory() throws IOException {
+ X509TrustManager tm = new X509TrustManager() {
+ @Override
+ public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
+ throw new CertificateException("not a server");
+ }
+
+ @Override
+ public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
+ if (chain == null || chain.length == 0) throw new CertificateException("no certificate");
+ String seen = sha256(chain[0].getEncoded());
+ if (pin.isEmpty()) {
+ pin = seen;
+ pinListener.onFirstPin(seen);
+ } else if (!pin.equals(seen)) {
+ throw new CertificateException("Frigate's certificate changed (pinned " + pin.substring(0, 12) + ")");
+ }
+ }
+
+ @Override
+ public X509Certificate[] getAcceptedIssuers() {
+ return new X509Certificate[0];
+ }
+ };
+ try {
+ SSLContext ctx = SSLContext.getInstance("TLS");
+ ctx.init(null, new TrustManager[] {tm}, null);
+ return ctx.getSocketFactory();
+ } catch (java.security.GeneralSecurityException e) {
+ throw new IOException(e);
+ }
+ }
+
+ static String sha256(byte[] der) {
+ try {
+ byte[] d = MessageDigest.getInstance("SHA-256").digest(der);
+ StringBuilder s = new StringBuilder();
+ for (byte b : d) s.append(String.format(Locale.ROOT, "%02x", b));
+ return s.toString();
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ private static byte[] readAll(InputStream in) throws IOException {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ byte[] buf = new byte[16384];
+ for (int n; (n = in.read(buf)) > 0; ) out.write(buf, 0, n);
+ return out.toByteArray();
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/FullscreenActivity.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/FullscreenActivity.java
new file mode 100644
index 000000000..6eb5925d0
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/FullscreenActivity.java
@@ -0,0 +1,149 @@
+package io.github.nickld.frigateglance;
+
+import android.app.Activity;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.view.Gravity;
+import android.view.TextureView;
+import android.view.View;
+import android.view.WindowManager;
+import android.widget.FrameLayout;
+import android.widget.ImageView;
+import android.widget.TextView;
+
+import java.io.IOException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+/**
+ * One camera full screen, opened from a card with the full screen key: live video, or a snapshot every second
+ * when it cannot start. Back closes it and the app that was playing comes back.
+ */
+public class FullscreenActivity extends Activity {
+ static final String EXTRA_CAMERA = "camera";
+ static final String EXTRA_TITLE = "title";
+
+ private final Handler main = new Handler(Looper.getMainLooper());
+ private final ExecutorService loader = Executors.newSingleThreadExecutor();
+ private LiveVideo live;
+ private ImageView image;
+ private TextureView video;
+ private ModeBadge badge;
+ private String camera;
+ private boolean refreshing;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+ camera = getIntent().getStringExtra(EXTRA_CAMERA);
+ float dp = getResources().getDisplayMetrics().density;
+ FrameLayout root = new FrameLayout(this);
+ root.setBackgroundColor(0xFF000000);
+ float aspect = GlanceService.aspect(camera);
+ FrameLayout picture = new FrameLayout(this);
+ image = new ImageView(this);
+ image.setScaleType(ImageView.ScaleType.FIT_XY);
+ video = new TextureView(this);
+ video.setAlpha(0f);
+ picture.addView(image, new FrameLayout.LayoutParams(-1, -1));
+ picture.addView(video, new FrameLayout.LayoutParams(-1, -1));
+ root.addView(picture, new FrameLayout.LayoutParams(-1, -1, Gravity.CENTER));
+ // Fill the height in the camera's own shape, centred, so the picture is never stretched.
+ root.addOnLayoutChangeListener((v, l, t, r, b, ol, ot, or, ob) -> {
+ int h = b - t, w = Math.min(r - l, Math.round(h * aspect));
+ FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) picture.getLayoutParams();
+ if (lp.width != w || lp.height != Math.round(w / aspect)) {
+ lp.width = w;
+ lp.height = Math.round(w / aspect);
+ picture.setLayoutParams(lp);
+ }
+ });
+ TextView title = new TextView(this);
+ title.setText(getIntent().getStringExtra(EXTRA_TITLE) + " Back closes");
+ title.setTextColor(0xFFFFFFFF);
+ title.setTextSize(16);
+ title.setShadowLayer(6, 0, 0, 0xFF000000);
+ int pad = Math.round(24 * dp);
+ title.setPadding(pad, pad, pad, pad);
+ root.addView(title, new FrameLayout.LayoutParams(-2, -2, Gravity.TOP | Gravity.START));
+ badge = new ModeBadge(this, 24);
+ FrameLayout.LayoutParams bp = new FrameLayout.LayoutParams(-2, -2, Gravity.TOP | Gravity.END);
+ bp.setMargins(0, pad, pad, 0);
+ root.addView(badge, bp);
+ setContentView(root);
+ View decor = getWindow().getDecorView();
+ decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
+ snapshot();
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ String url = GlanceService.liveUrl(camera);
+ if (url == null) {
+ startRefresh();
+ return;
+ }
+ live = new LiveVideo(this, new LiveVideo.Listener() {
+ @Override
+ public void onPlaying() {
+ video.animate().alpha(1f).setDuration(300).start();
+ badge.setLive(true);
+ }
+
+ @Override
+ public void onGaveUp() {
+ video.setAlpha(0f);
+ badge.setLive(false);
+ startRefresh();
+ }
+ });
+ live.start(url, video);
+ }
+
+ @Override
+ protected void onPause() {
+ refreshing = false;
+ if (live != null) {
+ live.release();
+ live = null;
+ }
+ super.onPause();
+ // Leaving (Back, Home, another app) ends the view: it is a glance, not a place to stay.
+ finish();
+ }
+
+ @Override
+ protected void onDestroy() {
+ loader.shutdownNow();
+ super.onDestroy();
+ }
+
+ private void startRefresh() {
+ refreshing = true;
+ main.postDelayed(new Runnable() {
+ @Override
+ public void run() {
+ if (!refreshing) return;
+ snapshot();
+ main.postDelayed(this, OverlayCard.SNAPSHOT_REFRESH_MS);
+ }
+ }, OverlayCard.SNAPSHOT_REFRESH_MS);
+ }
+
+ private void snapshot() {
+ loader.execute(() -> {
+ try {
+ byte[] jpeg = GlanceService.snapshot(camera);
+ Bitmap bmp = jpeg == null ? null : BitmapFactory.decodeByteArray(jpeg, 0, jpeg.length);
+ if (bmp != null) main.post(() -> image.setImageBitmap(bmp));
+ } catch (IOException | RuntimeException ignored) {
+ // keep the last picture
+ }
+ });
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/GlanceConfig.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/GlanceConfig.java
new file mode 100644
index 000000000..b9c7cb2f9
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/GlanceConfig.java
@@ -0,0 +1,212 @@
+package io.github.nickld.frigateglance;
+
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.Map;
+import java.util.Set;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * The add-on's settings: the pushed config.json (keys as in Peek's config.json where they mean the same
+ * thing), with the settings screen's choices laid over it. Immutable; parse() validates and clamps.
+ */
+public final class GlanceConfig {
+ static final Set<String> CORNERS = Set.of("top-right", "top-left", "bottom-right", "bottom-left");
+ static final Set<String> SEVERITIES = Set.of("alerts", "alerts_and_detections");
+ /** Keys people press out of habit to control playback; never caught. */
+ static final Set<String> FORBIDDEN_KEYS = Set.of("KEYCODE_BACK", "KEYCODE_DPAD_CENTER", "KEYCODE_ENTER", "KEYCODE_HOME");
+
+ public final String mqttUrl, frigateUrl, frigateUser, frigatePassword, topicPrefix, rtspUser, rtspPassword;
+ public final String corner, severity, dismissKey, snoozeKey;
+ /** Camera name to display name; empty means every camera. */
+ public final Map<String, String> cameras;
+ /** Camera name to the go2rtc stream for live video, when it should not be Frigate's live stream. */
+ public final Map<String, String> streams;
+ /** Cameras switched off on the settings screen. */
+ public final Set<String> camerasOff;
+ /** Cameras Frigate gains later (not in "cameras") open cards too. Only matters while "cameras" lists some. */
+ public final boolean newCameras;
+ /** Object labels that may open a card; empty means every label. */
+ public final Set<String> labels;
+ public final int dismissSeconds, snoozeMinutes;
+ /** Card size in percent of the standard card (picture, text and bar together). */
+ public final int cardScale;
+ public final boolean liveVideo, boxes;
+ /** A third card key opens the camera full screen; off by default. */
+ public final boolean fullscreen;
+ public final String fullscreenKey;
+ /** Keys that act only when held (KeyRules.HOLD_MS), against accidental presses while moving around an app. */
+ public final boolean dismissHold, snoozeHold, fullscreenHold;
+
+ private final JSONObject source;
+
+ private GlanceConfig(JSONObject o) {
+ source = o;
+ mqttUrl = mqtt(required(o, "mqtt"));
+ frigateUrl = stripSlash(required(o, "frigateUrl"));
+ frigateUser = o.optString("frigateUser", "");
+ frigatePassword = o.optString("frigatePassword", "");
+ topicPrefix = o.optString("topicPrefix", "frigate").isEmpty() ? "frigate" : o.optString("topicPrefix", "frigate");
+ rtspUser = o.optString("rtspUser", "");
+ rtspPassword = o.optString("rtspPassword", "");
+ corner = oneOf(o.optString("corner", "top-right"), CORNERS, "top-right");
+ severity = oneOf(o.optString("severity", "alerts"), SEVERITIES, "alerts");
+ dismissSeconds = clamp(o.optInt("dismissSeconds", 8), 1, 120);
+ snoozeMinutes = clamp(o.optInt("snoozeMinutes", 60), 5, 720);
+ cardScale = clamp(o.optInt("cardScale", 100), 50, 200);
+ liveVideo = o.optBoolean("liveVideo", true);
+ boxes = o.optBoolean("boxes", true);
+ dismissKey = key(o, "dismissKey", "KEYCODE_DPAD_LEFT");
+ snoozeKey = key(o, "snoozeKey", "KEYCODE_DPAD_RIGHT");
+ if (dismissKey.equals(snoozeKey)) throw new IllegalArgumentException("dismissKey and snoozeKey are the same key");
+ fullscreen = o.optBoolean("fullscreen", false);
+ dismissHold = o.optBoolean("dismissHold", false);
+ snoozeHold = o.optBoolean("snoozeHold", false);
+ fullscreenHold = o.optBoolean("fullscreenHold", false);
+ fullscreenKey = key(o, "fullscreenKey", "KEYCODE_DPAD_UP");
+ if (fullscreen && (fullscreenKey.equals(dismissKey) || fullscreenKey.equals(snoozeKey))) {
+ throw new IllegalArgumentException("fullscreenKey is the same key as dismissKey or snoozeKey");
+ }
+ cameras = cameras(o.optJSONObject("cameras"));
+ streams = cameras(o.optJSONObject("streams"));
+ camerasOff = labels(o.optJSONArray("camerasOff"));
+ newCameras = o.optBoolean("newCameras", false);
+ labels = labels(o.optJSONArray("labels"));
+ }
+
+ /** Parses and validates a config file; IllegalArgumentException names what is wrong. */
+ public static GlanceConfig parse(String json) {
+ try {
+ return new GlanceConfig(new JSONObject(json));
+ } catch (JSONException e) {
+ // Android's org.json repeats the whole input in its messages: passwords included. Say only where.
+ throw new IllegalArgumentException("config is not valid JSON");
+ }
+ }
+
+ /** This config with the settings screen's values laid over it; validated the same way. */
+ public GlanceConfig withOverrides(JSONObject settings) {
+ try {
+ JSONObject merged = new JSONObject(source.toString());
+ for (Iterator<String> it = settings.keys(); it.hasNext(); ) {
+ String k = it.next();
+ merged.put(k, settings.get(k));
+ }
+ return new GlanceConfig(merged);
+ } catch (JSONException e) {
+ throw new IllegalArgumentException(e.getMessage(), e);
+ }
+ }
+
+ /** Every key, normalised, so a re-parse gives the same config. */
+ public String toJson() {
+ try {
+ JSONObject o = new JSONObject();
+ o.put("mqtt", mqttUrl);
+ o.put("frigateUrl", frigateUrl);
+ o.put("frigateUser", frigateUser);
+ o.put("frigatePassword", frigatePassword);
+ o.put("topicPrefix", topicPrefix);
+ o.put("rtspUser", rtspUser);
+ o.put("rtspPassword", rtspPassword);
+ o.put("cameras", new JSONObject(cameras));
+ o.put("streams", new JSONObject(streams));
+ o.put("camerasOff", new JSONArray(camerasOff));
+ o.put("newCameras", newCameras);
+ o.put("labels", new JSONArray(labels));
+ o.put("severity", severity);
+ o.put("corner", corner);
+ o.put("dismissSeconds", dismissSeconds);
+ o.put("snoozeMinutes", snoozeMinutes);
+ o.put("cardScale", cardScale);
+ o.put("liveVideo", liveVideo);
+ o.put("boxes", boxes);
+ o.put("dismissKey", dismissKey);
+ o.put("snoozeKey", snoozeKey);
+ o.put("fullscreen", fullscreen);
+ o.put("fullscreenKey", fullscreenKey);
+ o.put("dismissHold", dismissHold);
+ o.put("snoozeHold", snoozeHold);
+ o.put("fullscreenHold", fullscreenHold);
+ return o.toString();
+ } catch (JSONException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ /** The host part of frigateUrl, for the RTSP address. */
+ public String frigateHost() {
+ String s = frigateUrl.replaceFirst("^[a-zA-Z]+://", "");
+ int end = s.length();
+ for (char c : new char[] {':', '/'}) {
+ int i = s.indexOf(c);
+ if (i >= 0 && i < end) end = i;
+ }
+ return s.substring(0, end);
+ }
+
+ /** mqtt://user:password@host:port with a host; the message never repeats the value (it holds a password). */
+ private static String mqtt(String url) {
+ try {
+ java.net.URI u = new java.net.URI(url);
+ if ("mqtt".equalsIgnoreCase(u.getScheme()) && u.getHost() != null) return url;
+ } catch (java.net.URISyntaxException e) {
+ // reported below
+ }
+ throw new IllegalArgumentException("\"mqtt\" must look like mqtt://user:password@host:1883, with characters"
+ + " other than letters and digits in the user or password percent-encoded");
+ }
+
+ private static String required(JSONObject o, String k) {
+ String v = o.optString(k, "").trim();
+ if (v.isEmpty()) throw new IllegalArgumentException("config needs \"" + k + "\"");
+ return v;
+ }
+
+ private static String key(JSONObject o, String k, String fallback) {
+ String v = o.optString(k, fallback).trim();
+ if (v.isEmpty()) v = fallback;
+ if (!v.startsWith("KEYCODE_")) throw new IllegalArgumentException(k + " must be a KEYCODE_ name");
+ if (FORBIDDEN_KEYS.contains(v)) throw new IllegalArgumentException(k + " may not be " + v);
+ return v;
+ }
+
+ private static String oneOf(String v, Set<String> allowed, String fallback) {
+ return allowed.contains(v) ? v : fallback;
+ }
+
+ private static int clamp(int v, int min, int max) {
+ return Math.max(min, Math.min(max, v));
+ }
+
+ private static String stripSlash(String url) {
+ return url.endsWith("/") ? url.substring(0, url.length() - 1) : url;
+ }
+
+ private static Map<String, String> cameras(JSONObject o) {
+ Map<String, String> m = new LinkedHashMap<>();
+ if (o != null) {
+ for (Iterator<String> it = o.keys(); it.hasNext(); ) {
+ String k = it.next();
+ m.put(k, o.optString(k, k));
+ }
+ }
+ return Collections.unmodifiableMap(m);
+ }
+
+ private static Set<String> labels(JSONArray a) {
+ Set<String> s = new LinkedHashSet<>();
+ if (a != null) {
+ for (int i = 0; i < a.length(); i++) {
+ String v = a.optString(i, "").trim();
+ if (!v.isEmpty()) s.add(v);
+ }
+ }
+ return Collections.unmodifiableSet(s);
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/GlanceService.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/GlanceService.java
new file mode 100644
index 000000000..11463377e
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/GlanceService.java
@@ -0,0 +1,489 @@
+package io.github.nickld.frigateglance;
+
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.app.Service;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ServiceInfo;
+import android.os.Build;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.IBinder;
+import android.os.SystemClock;
+import android.provider.Settings;
+import android.util.Log;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import javax.net.SocketFactory;
+
+import org.json.JSONObject;
+
+/**
+ * Stays connected to MQTT and turns Frigate's messages into cards. One thread runs the connection and
+ * reconnects with backoff; another owns the CardController, so card decisions never race.
+ */
+public class GlanceService extends Service {
+ private static final String TAG = ConfigStore.TAG;
+ private static final String CHANNEL = "status";
+ private static final int NOTIFICATION_ID = 1;
+
+ private static volatile GlanceService instance;
+ private static volatile String status = "Starting";
+
+ private HandlerThread cardThread;
+ private Handler cards;
+ private Thread network;
+ private volatile boolean running;
+ /** Bumped on every restart; a connection loop from an older generation stops. */
+ private volatile int generation;
+ private volatile MqttClient mqtt;
+ private volatile GlanceConfig config;
+ private volatile FrigateApi frigate;
+ private volatile Map<String, int[]> detectSizes = Collections.emptyMap();
+ private volatile Map<String, String> liveStreams = Collections.emptyMap();
+ private volatile List<String> cameraNames = Collections.emptyList();
+ private volatile JSONObject frigateConfig;
+ private CardController controller;
+ /** Re-reads Frigate's config off the network thread when an unknown camera appears (a replay, a new camera). */
+ private final java.util.concurrent.ExecutorService refetcher = java.util.concurrent.Executors.newSingleThreadExecutor();
+ private volatile long lastRefetch;
+ private static final long REFETCH_EVERY_MS = 60_000;
+ private OverlayCard card;
+ private volatile boolean mqttUp, frigateUp;
+ /** Wall-clock times for the settings screen's Overview: 0 means never. */
+ private volatile long mqttSince, frigateSince, lastMessageAt;
+ private volatile String mqttError = "", frigateError = "";
+
+ public static void start(Context context) {
+ context.startForegroundService(new Intent(context, GlanceService.class));
+ }
+
+ /** Re-reads the config and reconnects; for the settings screen and a newly pushed config. */
+ public static void reload(Context context) {
+ GlanceService s = instance;
+ if (s == null) start(context);
+ else s.restartNetwork();
+ }
+
+ /** Applies a change from the settings screen without reconnecting: filters, card look, keys. */
+ public static void settingsChanged(Context context) {
+ GlanceService s = instance;
+ if (s == null) {
+ start(context);
+ return;
+ }
+ GlanceConfig c = new ConfigStore(s).load();
+ if (c == null) return;
+ s.config = c;
+ s.cards.post(() -> s.setUpCards(c));
+ }
+
+ /** A test card asked for before the service was ready; shown once cards are set up. "" = first camera. */
+ private static volatile String pendingTest;
+
+ public static void showTestCard(Context context, String camera) {
+ GlanceService s = instance;
+ if (s == null || s.cards == null || s.controller == null) {
+ pendingTest = camera == null ? "" : camera;
+ if (s == null) start(context);
+ return;
+ }
+ s.cards.post(() -> {
+ if (s.controller == null) return;
+ String cam = camera;
+ if (cam == null) cam = s.firstCamera();
+ s.controller.showTest(cam);
+ });
+ }
+
+ public static void dismissCard() {
+ GlanceService s = instance;
+ if (s != null && s.cards != null) s.cards.post(() -> {
+ if (s.controller == null) return;
+ s.controller.dismiss();
+ Log.i(TAG, "card dismissed");
+ });
+ }
+
+ public static void snoozeCard() {
+ GlanceService s = instance;
+ if (s != null && s.cards != null) {
+ s.cards.post(() -> {
+ if (s.controller == null || s.config == null) return;
+ s.controller.snooze(s.config.snoozeMinutes);
+ Log.i(TAG, "snoozed for " + s.config.snoozeMinutes + " min");
+ });
+ }
+ }
+
+ public static void resume() {
+ GlanceService s = instance;
+ if (s != null && s.cards != null) s.cards.post(() -> { if (s.controller != null) s.controller.resume(); });
+ }
+
+ /** When snooze ends, in System.currentTimeMillis() terms, or 0. */
+ public static long snoozedUntilWallClock() {
+ GlanceService s = instance;
+ CardController c = s == null ? null : s.controller;
+ if (c == null) return 0;
+ long until = c.snoozedUntil();
+ return until == 0 ? 0 : System.currentTimeMillis() + (until - SystemClock.elapsedRealtime());
+ }
+
+ /** Width over height of a camera's frame; 16/9 when unknown. */
+ static float aspect(String camera) {
+ GlanceService s = instance;
+ int[] size = s == null ? null : s.detectSizes.get(camera);
+ return size == null ? 16f / 9f : (float) size[0] / size[1];
+ }
+
+ /** The camera's RTSP address, whatever the live video setting (the full screen view always tries it). */
+ static String liveUrl(String camera) {
+ GlanceService s = instance;
+ GlanceConfig cfg = s == null ? null : s.config;
+ // A debug replay plays a recording inside Frigate; go2rtc has no stream for it, so there is no live video.
+ if (cfg == null || camera.startsWith(ReviewFilter.REPLAY_PREFIX)) return null;
+ String stream = cfg.streams.containsKey(camera) ? cfg.streams.get(camera) : s.streamFor(camera);
+ return LiveVideo.rtspUrl(cfg.frigateHost(), cfg.rtspUser, cfg.rtspPassword, stream);
+ }
+
+ /** A full-size snapshot for the full screen view. */
+ static byte[] snapshot(String camera) throws IOException {
+ GlanceService s = instance;
+ FrigateApi f = s == null ? null : s.frigate;
+ return f == null ? null : f.latestJpeg(camera, 1080);
+ }
+
+ /** The full screen key: the card closes and its camera opens full screen over whatever was playing. */
+ public static void openFullscreen() {
+ GlanceService s = instance;
+ if (s == null || s.cards == null) return;
+ s.cards.post(() -> {
+ if (s.controller == null || s.controller.shownCamera() == null) return;
+ String camera = s.controller.shownCamera();
+ String base = ReviewFilter.baseCamera(camera);
+ GlanceConfig c = s.config;
+ String title = c != null && c.cameras.containsKey(base) ? c.cameras.get(base) : CardController.pretty(base);
+ s.controller.dismiss();
+ Intent i = new Intent(s, FullscreenActivity.class)
+ .putExtra(FullscreenActivity.EXTRA_CAMERA, camera)
+ .putExtra(FullscreenActivity.EXTRA_TITLE, title)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
+ s.startActivity(i);
+ Log.i(TAG, "full screen: " + camera);
+ });
+ }
+
+ /** A hold key is down on a card: show its progress. action is KeyRules.DISMISS, SNOOZE or FULLSCREEN. */
+ static void holdStarted(int action) {
+ GlanceService s = instance;
+ if (s != null && s.card != null) s.card.showHold(action);
+ }
+
+ static void holdEnded() {
+ GlanceService s = instance;
+ if (s != null && s.card != null) s.card.endHold();
+ }
+
+ public static boolean isCardShowing() {
+ GlanceService s = instance;
+ return s != null && s.card != null && s.card.reviewId() != null;
+ }
+
+ /** What the Overview shows; read from the settings screen's thread, so a copy of volatile fields. */
+ static final class Overview {
+ boolean running, mqttUp, frigateUp;
+ String mqttHost = "", frigateHost = "", mqttError = "", frigateError = "";
+ long mqttSince, frigateSince, lastMessageAt;
+ int cameras;
+ }
+
+ static Overview overview() {
+ Overview o = new Overview();
+ GlanceService s = instance;
+ if (s == null) return o;
+ o.running = true;
+ o.mqttUp = s.mqttUp;
+ o.frigateUp = s.frigateUp;
+ o.mqttSince = s.mqttSince;
+ o.frigateSince = s.frigateSince;
+ o.lastMessageAt = s.lastMessageAt;
+ o.mqttError = s.mqttError;
+ o.frigateError = s.frigateError;
+ o.cameras = s.cameraNames.size();
+ GlanceConfig c = s.config;
+ if (c != null) {
+ o.mqttHost = hostPort(c.mqttUrl, 1883);
+ o.frigateHost = hostPort(c.frigateUrl, -1);
+ }
+ return o;
+ }
+
+ /** host:port of a URL, without the user and password it may carry. */
+ static String hostPort(String url, int defaultPort) {
+ try {
+ java.net.URI u = new java.net.URI(url);
+ int port = u.getPort() > 0 ? u.getPort() : defaultPort;
+ return u.getHost() + (port > 0 ? ":" + port : "");
+ } catch (java.net.URISyntaxException | RuntimeException e) {
+ return "";
+ }
+ }
+
+ public static String statusLine() {
+ return status;
+ }
+
+ /** Frigate's config as last fetched, or null; for the settings screen's camera and object lists. */
+ public static JSONObject frigateConfig() {
+ GlanceService s = instance;
+ return s == null ? null : s.frigateConfig;
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ instance = this;
+ NotificationManager nm = getSystemService(NotificationManager.class);
+ nm.createNotificationChannel(new NotificationChannel(CHANNEL, getString(R.string.app_name), NotificationManager.IMPORTANCE_MIN));
+ if (Build.VERSION.SDK_INT >= 29) {
+ startForeground(NOTIFICATION_ID, notification(), ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC);
+ } else {
+ startForeground(NOTIFICATION_ID, notification());
+ }
+ cardThread = new HandlerThread("glance-cards");
+ cardThread.start();
+ cards = new Handler(cardThread.getLooper());
+ cards.postDelayed(this::tick, 1000);
+ restartNetwork();
+ }
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ return START_STICKY;
+ }
+
+ @Override
+ public void onDestroy() {
+ running = false;
+ MqttClient m = mqtt;
+ if (m != null) m.stop();
+ if (card != null) card.hide();
+ cardThread.quitSafely();
+ refetcher.shutdownNow();
+ instance = null;
+ super.onDestroy();
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return null;
+ }
+
+ private void restartNetwork() {
+ int gen = ++generation;
+ running = true;
+ MqttClient m = mqtt;
+ if (m != null) m.stop();
+ network = new Thread(() -> connectLoop(gen), "glance-network");
+ network.start();
+ }
+
+ private void connectLoop(int gen) {
+ ConfigStore store = new ConfigStore(this);
+ store.importPushed();
+ GlanceConfig c = store.load();
+ if (c == null) {
+ setStatus("No config yet: push one with install.sh");
+ Log.w(TAG, "mqtt error: no config");
+ return;
+ }
+ config = c;
+ frigate = new FrigateApi(c.frigateUrl, c.frigateUser, c.frigatePassword, store.certPin(), store::saveCertPin);
+ cards.post(() -> setUpCards(c));
+ String clientId = "frigate-glance-" + androidIdPrefix();
+ String p = c.topicPrefix;
+ List<String> topics = List.of(p + "/reviews", p + "/events", p + "/available");
+ for (int attempt = 0; running && gen == generation; ) {
+ fetchFrigateConfig();
+ boolean[] connected = {false};
+ MqttClient client;
+ try {
+ client = new MqttClient(c.mqttUrl, clientId, topics, new MqttClient.Listener() {
+ @Override
+ public void onConnected() {
+ connected[0] = true;
+ mqttUp = true;
+ mqttSince = System.currentTimeMillis();
+ mqttError = "";
+ Log.i(TAG, "mqtt connected");
+ updateStatus();
+ }
+
+ @Override
+ public void onMessage(String topic, byte[] payload) {
+ lastMessageAt = System.currentTimeMillis();
+ route(topic, new String(payload, StandardCharsets.UTF_8));
+ }
+
+ @Override
+ public void onDisconnected(Exception cause) {
+ mqttUp = false;
+ mqttSince = System.currentTimeMillis();
+ mqttError = cause.getMessage() == null ? "" : cause.getMessage();
+ if (running && gen == generation) Log.w(TAG, "mqtt error: " + cause.getMessage());
+ updateStatus();
+ }
+ });
+ } catch (RuntimeException e) {
+ Log.w(TAG, "mqtt error: the mqtt address in the config is not usable");
+ return;
+ }
+ mqtt = client;
+ client.run(SocketFactory.getDefault());
+ if (connected[0]) attempt = 0;
+ if (!running || gen != generation) break;
+ try {
+ Thread.sleep(MqttClient.backoffMs(attempt++));
+ } catch (InterruptedException e) {
+ return;
+ }
+ }
+ }
+
+ private void fetchFrigateConfig() {
+ try {
+ JSONObject fc = frigate.config();
+ frigateConfig = fc;
+ detectSizes = FrigateApi.detectSizes(fc);
+ liveStreams = FrigateApi.liveStreams(fc);
+ List<String> names = new ArrayList<>();
+ JSONObject cams = fc.optJSONObject("cameras");
+ if (cams != null) for (java.util.Iterator<String> it = cams.keys(); it.hasNext(); ) names.add(it.next());
+ Collections.sort(names);
+ cameraNames = names;
+ if (!frigateUp) frigateSince = System.currentTimeMillis();
+ frigateUp = true;
+ frigateError = "";
+ Log.i(TAG, "frigate ok");
+ } catch (IOException | RuntimeException e) {
+ if (frigateUp || frigateSince == 0) frigateSince = System.currentTimeMillis();
+ frigateUp = false;
+ frigateError = e.getMessage() == null ? "" : e.getMessage();
+ Log.w(TAG, "frigate error: " + e.getMessage());
+ }
+ updateStatus();
+ }
+
+ private void setUpCards(GlanceConfig c) {
+ if (card == null) {
+ card = new OverlayCard(this, c, new OverlayCard.Source() {
+ @Override
+ public byte[] snapshot(String camera) throws IOException {
+ return frigate.latestJpeg(camera, 360);
+ }
+
+ @Override
+ public float aspect(String camera) {
+ return GlanceService.aspect(camera);
+ }
+
+ @Override
+ public String liveUrl(String camera) {
+ GlanceConfig cfg = config;
+ return cfg == null || !cfg.liveVideo ? null : GlanceService.liveUrl(camera);
+ }
+ }, KeyService::setFiltering);
+ } else {
+ card.setConfig(c);
+ card.hide();
+ }
+ long snoozed = controller == null ? 0 : controller.snoozedUntil();
+ KeyService.reloadKeys(this);
+ controller = new CardController(card, new ReviewFilter(c), c.cameras, c.dismissSeconds, SystemClock::elapsedRealtime);
+ if (snoozed > 0) controller.snooze((int) Math.max(1, (snoozed - SystemClock.elapsedRealtime()) / 60_000));
+ String test = pendingTest;
+ pendingTest = null;
+ if (test != null) controller.showTest(test.isEmpty() ? firstCamera() : test);
+ }
+
+ private void route(String topic, String payload) {
+ GlanceConfig c = config;
+ if (c == null) return;
+ String p = c.topicPrefix;
+ if (topic.equals(p + "/reviews")) {
+ Review r = Review.parse(payload);
+ if (r != null) refetchIfUnknown(r.camera);
+ if (r != null) cards.post(() -> { if (controller != null) controller.onReview(r); });
+ } else if (topic.equals(p + "/events")) {
+ Review replay = Review.fromReplayEvent(payload);
+ if (replay != null) {
+ refetchIfUnknown(replay.camera);
+ cards.post(() -> { if (controller != null) controller.onReview(replay); });
+ }
+ Detection d = Detection.parse(payload, detectSizes);
+ if (d != null) cards.post(() -> { if (controller != null) controller.onDetection(d); });
+ } else if (topic.equals(p + "/available")) {
+ boolean online = "online".equals(payload.trim());
+ cards.post(() -> { if (controller != null) controller.onAvailable(online); });
+ }
+ }
+
+ private void refetchIfUnknown(String camera) {
+ long now = SystemClock.elapsedRealtime();
+ if (detectSizes.containsKey(camera) || frigate == null || now - lastRefetch < REFETCH_EVERY_MS) return;
+ lastRefetch = now;
+ refetcher.execute(this::fetchFrigateConfig);
+ }
+
+ private void tick() {
+ if (controller != null) controller.tick();
+ cards.postDelayed(this::tick, 1000);
+ }
+
+ private String firstCamera() {
+ GlanceConfig c = config;
+ if (c != null && !c.cameras.isEmpty()) return c.cameras.keySet().iterator().next();
+ List<String> names = cameraNames;
+ return names.isEmpty() ? "camera" : names.get(0);
+ }
+
+ /** go2rtc stream for a camera, for live video. */
+ String streamFor(String camera) {
+ String s = liveStreams.get(camera);
+ return s == null ? camera : s;
+ }
+
+ private String androidIdPrefix() {
+ String id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
+ return id == null || id.length() < 8 ? "tv" : id.substring(0, 8);
+ }
+
+ private void updateStatus() {
+ String overlay = Settings.canDrawOverlays(this) ? "" : " · overlay not allowed";
+ setStatus("MQTT " + (mqttUp ? "connected" : "not connected") + " · Frigate " + (frigateUp ? "ok" : "not reached") + overlay);
+ }
+
+ private void setStatus(String s) {
+ status = s;
+ NotificationManager nm = getSystemService(NotificationManager.class);
+ if (nm != null) nm.notify(NOTIFICATION_ID, notification());
+ }
+
+ private Notification notification() {
+ return new Notification.Builder(this, CHANNEL)
+ .setSmallIcon(R.drawable.ic_foreground)
+ .setContentTitle(getString(R.string.app_name))
+ .setContentText(status)
+ .setOngoing(true)
+ .build();
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/Json.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/Json.java
new file mode 100644
index 000000000..524ef597c
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/Json.java
@@ -0,0 +1,22 @@
+package io.github.nickld.frigateglance;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.json.JSONArray;
+
+/** Small helpers for Frigate's payloads. */
+final class Json {
+ private Json() {}
+
+ static List<String> strings(JSONArray a) {
+ if (a == null) return Collections.emptyList();
+ List<String> out = new ArrayList<>(a.length());
+ for (int i = 0; i < a.length(); i++) {
+ String s = a.optString(i, "");
+ if (!s.isEmpty() && !"null".equals(s)) out.add(s);
+ }
+ return Collections.unmodifiableList(out);
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/KeyChoice.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/KeyChoice.java
new file mode 100644
index 000000000..4fd050f44
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/KeyChoice.java
@@ -0,0 +1,39 @@
+package io.github.nickld.frigateglance;
+
+/** Whether a button pressed in the key picker may become a card key, and if not, the reason shown to the owner. */
+final class KeyChoice {
+ private KeyChoice() {}
+
+ static String problem(String key, String otherKey) {
+ return problem(key, otherKey, "other card");
+ }
+
+ /** others: name of each other card key ("Snooze", "Full screen") to its key. */
+ static String problem(String key, java.util.Map<String, String> others) {
+ String p = problem(key, "", "");
+ if (p != null) return p;
+ for (java.util.Map.Entry<String, String> e : others.entrySet()) {
+ if (key.equals(e.getValue())) return "That button is already the " + e.getKey() + " key.";
+ }
+ return null;
+ }
+
+ /** Null when the key can be used; otherwise one sentence saying why not. */
+ static String problem(String key, String otherKey, String otherName) {
+ switch (key) {
+ case "KEYCODE_DPAD_CENTER":
+ case "KEYCODE_ENTER":
+ return "OK pauses and plays what you watch, so it can't be a card key.";
+ case "KEYCODE_BACK":
+ return "Back leaves what you watch, so it can't be a card key.";
+ case "KEYCODE_HOME":
+ return "Home leaves what you watch, so it can't be a card key.";
+ case "KEYCODE_UNKNOWN":
+ return "That button sends nothing Android can name, so it can't be used. Try another.";
+ default:
+ break;
+ }
+ if (key.equals(otherKey)) return "That button is already the " + otherName + " key.";
+ return null;
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/KeyPickerDialog.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/KeyPickerDialog.java
new file mode 100644
index 000000000..4a5bdae7e
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/KeyPickerDialog.java
@@ -0,0 +1,69 @@
+package io.github.nickld.frigateglance;
+
+import android.app.Dialog;
+import android.content.Context;
+import android.graphics.Color;
+import android.graphics.drawable.ColorDrawable;
+import android.view.KeyEvent;
+import android.view.Window;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+import java.util.function.Consumer;
+
+/**
+ * "Press the button you want": the next button pressed on the remote becomes the key, if KeyChoice allows it.
+ * Back closes the window without a change. Buttons the system or the launcher keep for themselves (Home, the
+ * app buttons) never arrive here, so they cannot be picked.
+ */
+final class KeyPickerDialog extends Dialog {
+ private final TextView message;
+
+ KeyPickerDialog(Context context, String what, java.util.Map<String, String> others, Consumer<String> onPicked) {
+ super(context);
+ requestWindowFeature(Window.FEATURE_NO_TITLE);
+ float dp = context.getResources().getDisplayMetrics().density;
+ LinearLayout box = new LinearLayout(context);
+ box.setOrientation(LinearLayout.VERTICAL);
+ box.setBackgroundResource(R.drawable.card_glass);
+ int pad = Math.round(28 * dp);
+ box.setPadding(pad, pad, pad, pad);
+ TextView title = new TextView(context);
+ title.setText("Press the button you want for " + what);
+ title.setTextSize(22);
+ title.setTextColor(0xFFFFFFFF);
+ message = new TextView(context);
+ message.setTextSize(15);
+ message.setTextColor(0xFF8B949E);
+ message.setPadding(0, Math.round(10 * dp), 0, Math.round(10 * dp));
+ message.setText("It only acts while a camera card is on screen. OK, Back and Home can't be used.");
+ TextView hint = new TextView(context);
+ hint.setText("Back closes this without a change.");
+ hint.setTextSize(13);
+ hint.setTextColor(0xFF8B949E);
+ box.addView(title);
+ box.addView(message);
+ box.addView(hint);
+ setContentView(box);
+ Window w = getWindow();
+ if (w != null) w.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
+
+ setOnKeyListener((d, code, event) -> {
+ if (event.getAction() != KeyEvent.ACTION_DOWN || event.getRepeatCount() > 0) return true;
+ if (code == KeyEvent.KEYCODE_BACK) {
+ dismiss();
+ return true;
+ }
+ String name = KeyEvent.keyCodeToString(code);
+ String problem = KeyChoice.problem(name, others);
+ if (problem != null) {
+ message.setText(problem);
+ message.setTextColor(0xFFFF7B72);
+ return true;
+ }
+ onPicked.accept(name);
+ dismiss();
+ return true;
+ });
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/KeyRules.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/KeyRules.java
new file mode 100644
index 000000000..6a994260a
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/KeyRules.java
@@ -0,0 +1,70 @@
+package io.github.nickld.frigateglance;
+
+/**
+ * Which remote keys the card catches: only its keys, only while it shows. A key's up goes wherever its down
+ * went, so an app never sees half a press. A key set to "hold" acts only when released at least HOLD_MS after
+ * it went down, so a quick press made while moving around an app does not dismiss or snooze by accident.
+ * Hold is measured from down to up rather than from key repeats, which some TCL firmware stops sending while a
+ * key filter is active.
+ */
+final class KeyRules {
+ static final int PASS = 0, SWALLOW = 1, DISMISS = 2, SNOOZE = 3, FULLSCREEN = 4;
+ static final long HOLD_MS = 600;
+ private static final int ACTION_DOWN = 0;
+
+ private final int dismissCode, snoozeCode, fullscreenCode;
+ private final boolean dismissHold, snoozeHold, fullscreenHold;
+ private int held;
+ private long heldSince;
+
+ /** Key codes from KeyEvent.keyCodeFromString; 0 (KEYCODE_UNKNOWN) catches nothing. */
+ KeyRules(int dismissCode, int snoozeCode) {
+ this(dismissCode, snoozeCode, 0);
+ }
+
+ /** fullscreenCode 0 while the full screen feature is off. */
+ KeyRules(int dismissCode, int snoozeCode, int fullscreenCode) {
+ this(dismissCode, snoozeCode, fullscreenCode, false, false, false);
+ }
+
+ KeyRules(int dismissCode, int snoozeCode, int fullscreenCode,
+ boolean dismissHold, boolean snoozeHold, boolean fullscreenHold) {
+ this.dismissCode = dismissCode;
+ this.snoozeCode = snoozeCode;
+ this.fullscreenCode = fullscreenCode;
+ this.dismissHold = dismissHold;
+ this.snoozeHold = snoozeHold;
+ this.fullscreenHold = fullscreenHold;
+ }
+
+ /** eventTimeMs: the key event's time (KeyEvent.getEventTime), used to measure a hold. */
+ int decide(int keyCode, int action, long eventTimeMs, boolean cardShowing) {
+ if (keyCode == 0 || (keyCode != dismissCode && keyCode != snoozeCode && keyCode != fullscreenCode)) return PASS;
+ if (action == ACTION_DOWN) {
+ if (held == keyCode) return SWALLOW; // a repeat of the key already held: the clock keeps running
+ if (!cardShowing) return PASS;
+ held = keyCode;
+ heldSince = eventTimeMs;
+ return SWALLOW;
+ }
+ if (held != keyCode) return PASS;
+ held = 0;
+ boolean longEnough = eventTimeMs - heldSince >= HOLD_MS;
+ if (keyCode == dismissCode) return dismissHold && !longEnough ? SWALLOW : DISMISS;
+ if (keyCode == snoozeCode) return snoozeHold && !longEnough ? SWALLOW : SNOOZE;
+ return fullscreenHold && !longEnough ? SWALLOW : FULLSCREEN;
+ }
+
+ /** The action of the key being held, while it is a key that needs a hold; 0 otherwise. */
+ int pendingHold() {
+ if (held == 0) return 0;
+ if (held == dismissCode) return dismissHold ? DISMISS : 0;
+ if (held == snoozeCode) return snoozeHold ? SNOOZE : 0;
+ return fullscreenHold ? FULLSCREEN : 0;
+ }
+
+ /** True while a caught key is down, so filtering must stay on for its up. */
+ boolean holding() {
+ return held != 0;
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/KeyService.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/KeyService.java
new file mode 100644
index 000000000..29b3b8f68
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/KeyService.java
@@ -0,0 +1,104 @@
+package io.github.nickld.frigateglance;
+
+import android.accessibilityservice.AccessibilityService;
+import android.accessibilityservice.AccessibilityServiceInfo;
+import android.content.Context;
+import android.os.Handler;
+import android.os.Looper;
+import android.util.Log;
+import android.view.KeyEvent;
+import android.view.accessibility.AccessibilityEvent;
+
+/**
+ * Dismiss and Snooze from the remote while a card shows. Key filtering is switched on only while a card is
+ * up (and until a caught key is released): the rest of the time this service sees no keys at all, so it
+ * cannot slow or change anything (some TCL firmware drops key repeat while any service filters keys).
+ */
+public class KeyService extends AccessibilityService {
+ private static volatile KeyService instance;
+ private static volatile boolean showing;
+
+ private final Handler main = new Handler(Looper.getMainLooper());
+ private KeyRules rules = new KeyRules(0, 0);
+
+ /** True while Android has the service bound, so the remote buttons can work. */
+ static boolean isRunning() {
+ return instance != null;
+ }
+
+ /** Called when a card appears or leaves. */
+ static void setFiltering(boolean cardShowing) {
+ showing = cardShowing;
+ KeyService s = instance;
+ if (s != null) s.main.post(s::applyFilter);
+ }
+
+ /** Re-reads the dismiss and snooze keys after a settings change. */
+ static void reloadKeys(Context context) {
+ KeyService s = instance;
+ if (s != null) s.main.post(s::loadKeys);
+ }
+
+ @Override
+ protected void onServiceConnected() {
+ super.onServiceConnected();
+ instance = this;
+ loadKeys();
+ applyFilter();
+ }
+
+ @Override
+ public boolean onUnbind(android.content.Intent intent) {
+ instance = null;
+ return super.onUnbind(intent);
+ }
+
+ @Override
+ protected boolean onKeyEvent(KeyEvent event) {
+ int pendingBefore = rules.pendingHold();
+ int d = rules.decide(event.getKeyCode(), event.getAction(), event.getEventTime(), showing);
+ int pendingNow = rules.pendingHold();
+ if (pendingNow != 0 && pendingBefore == 0) GlanceService.holdStarted(pendingNow);
+ else if (pendingBefore != 0 && pendingNow == 0) GlanceService.holdEnded();
+ if (d == KeyRules.DISMISS) GlanceService.dismissCard();
+ else if (d == KeyRules.SNOOZE) GlanceService.snoozeCard();
+ else if (d == KeyRules.FULLSCREEN) GlanceService.openFullscreen();
+ if (!rules.holding() && !showing) applyFilter();
+ return d != KeyRules.PASS;
+ }
+
+ @Override
+ public void onAccessibilityEvent(AccessibilityEvent event) {
+ // Keys only.
+ }
+
+ @Override
+ public void onInterrupt() {
+ // Nothing to stop.
+ }
+
+ private void loadKeys() {
+ GlanceConfig c = new ConfigStore(this).load();
+ if (c == null) {
+ rules = new KeyRules(0, 0);
+ return;
+ }
+ int dismiss = KeyEvent.keyCodeFromString(c.dismissKey);
+ int snooze = KeyEvent.keyCodeFromString(c.snoozeKey);
+ if (dismiss == KeyEvent.KEYCODE_UNKNOWN) Log.w(ConfigStore.TAG, "unknown dismissKey " + c.dismissKey);
+ if (snooze == KeyEvent.KEYCODE_UNKNOWN) Log.w(ConfigStore.TAG, "unknown snoozeKey " + c.snoozeKey);
+ int fullscreen = c.fullscreen ? KeyEvent.keyCodeFromString(c.fullscreenKey) : 0;
+ rules = new KeyRules(dismiss, snooze, fullscreen, c.dismissHold, c.snoozeHold, c.fullscreenHold);
+ }
+
+ private void applyFilter() {
+ AccessibilityServiceInfo info = getServiceInfo();
+ if (info == null) return;
+ boolean want = showing || rules.holding();
+ boolean has = (info.flags & AccessibilityServiceInfo.FLAG_REQUEST_FILTER_KEY_EVENTS) != 0;
+ if (want == has) return;
+ if (want) info.flags |= AccessibilityServiceInfo.FLAG_REQUEST_FILTER_KEY_EVENTS;
+ else info.flags &= ~AccessibilityServiceInfo.FLAG_REQUEST_FILTER_KEY_EVENTS;
+ setServiceInfo(info);
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/LiveVideo.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/LiveVideo.java
new file mode 100644
index 000000000..b75bce5c1
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/LiveVideo.java
@@ -0,0 +1,113 @@
+package io.github.nickld.frigateglance;
+
+import android.content.Context;
+import android.os.Handler;
+import android.os.Looper;
+import android.util.Log;
+import android.view.TextureView;
+
+import androidx.annotation.OptIn;
+import androidx.media3.common.C;
+import androidx.media3.common.MediaItem;
+import androidx.media3.common.PlaybackException;
+import androidx.media3.common.Player;
+import androidx.media3.common.util.UnstableApi;
+import androidx.media3.exoplayer.DefaultLoadControl;
+import androidx.media3.exoplayer.ExoPlayer;
+import androidx.media3.exoplayer.rtsp.RtspMediaSource;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+
+/**
+ * Live picture for the card: go2rtc's RTSP stream through Media3, decoded by the TV's hardware decoder.
+ * Muted, small buffers, and given up on after four seconds without a frame, so the card falls back to
+ * refreshing snapshots instead of showing a frozen box. Main thread only.
+ */
+@OptIn(markerClass = UnstableApi.class)
+final class LiveVideo {
+ interface Listener {
+ void onPlaying();
+
+ void onGaveUp();
+ }
+
+ static final long GIVE_UP_MS = 4000;
+ static final int RTSP_PORT = 8554;
+
+ private final Context context;
+ private final Listener listener;
+ private final Handler main = new Handler(Looper.getMainLooper());
+ private ExoPlayer player;
+ private boolean playing;
+ private long startedAt;
+ private final Runnable giveUp = this::fail;
+
+ LiveVideo(Context context, Listener listener) {
+ this.context = context;
+ this.listener = listener;
+ }
+
+ static String rtspUrl(String host, String user, String password, String stream) {
+ String auth = user.isEmpty() ? "" : enc(user) + (password.isEmpty() ? "" : ":" + enc(password)) + "@";
+ return "rtsp://" + auth + host + ":" + RTSP_PORT + "/" + enc(stream);
+ }
+
+ void start(String rtspUrl, TextureView surface) {
+ release();
+ playing = false;
+ startedAt = android.os.SystemClock.elapsedRealtime();
+ DefaultLoadControl load = new DefaultLoadControl.Builder()
+ .setBufferDurationsMs(1000, 3000, 500, 500)
+ .build();
+ player = new ExoPlayer.Builder(context).setLoadControl(load).build();
+ // The card is silent: skip the camera's audio track entirely, which also spares the decoder its timestamps.
+ player.setTrackSelectionParameters(player.getTrackSelectionParameters().buildUpon()
+ .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, true).build());
+ player.setVideoTextureView(surface);
+ player.addListener(new Player.Listener() {
+ @Override
+ public void onRenderedFirstFrame() {
+ if (playing) return;
+ playing = true;
+ main.removeCallbacks(giveUp);
+ Log.i(ConfigStore.TAG, "live video playing after " + (android.os.SystemClock.elapsedRealtime() - startedAt) + " ms");
+ listener.onPlaying();
+ }
+
+ @Override
+ public void onPlayerError(PlaybackException error) {
+ Log.w(ConfigStore.TAG, "live video: " + error.getErrorCodeName());
+ fail();
+ }
+ });
+ player.setMediaSource(new RtspMediaSource.Factory().setForceUseRtpTcp(true)
+ .createMediaSource(MediaItem.fromUri(rtspUrl)));
+ player.setPlayWhenReady(true);
+ player.prepare();
+ main.postDelayed(giveUp, GIVE_UP_MS);
+ }
+
+ void release() {
+ main.removeCallbacks(giveUp);
+ if (player != null) {
+ player.release();
+ player = null;
+ }
+ }
+
+ private void fail() {
+ boolean wasActive = player != null;
+ if (wasActive) Log.i(ConfigStore.TAG, "live video gave up; refreshing snapshots");
+ release();
+ if (wasActive) listener.onGaveUp();
+ }
+
+ private static String enc(String s) {
+ try {
+ return URLEncoder.encode(s, "UTF-8").replace("+", "%20");
+ } catch (UnsupportedEncodingException e) {
+ return s;
+ }
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/ModeBadge.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/ModeBadge.java
new file mode 100644
index 000000000..c19d6dfd7
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/ModeBadge.java
@@ -0,0 +1,29 @@
+package io.github.nickld.frigateglance;
+
+import android.content.Context;
+import android.graphics.drawable.GradientDrawable;
+import android.widget.ImageView;
+
+/** The corner badge on the picture: a video camera on red while live video plays, stacked frames for snapshots. */
+final class ModeBadge extends ImageView {
+ private final GradientDrawable background = new GradientDrawable();
+
+ /** size: the icon's height in dp, before padding. */
+ ModeBadge(Context context, float size) {
+ super(context);
+ float dp = context.getResources().getDisplayMetrics().density;
+ background.setCornerRadius(size * dp / 3f);
+ setBackground(background);
+ int pad = Math.round(size * dp / 5f);
+ setPadding(pad * 2, pad, pad * 2, pad);
+ setAdjustViewBounds(true);
+ setMaxHeight(Math.round(size * dp) + 2 * pad);
+ setLive(false);
+ }
+
+ void setLive(boolean live) {
+ setImageResource(live ? R.drawable.ic_live : R.drawable.ic_frames);
+ background.setColor(live ? 0xD9DC3C3C : 0x99000000);
+ setContentDescription(live ? "Live video" : "Snapshots");
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/MqttClient.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/MqttClient.java
new file mode 100644
index 000000000..8ab394ad2
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/MqttClient.java
@@ -0,0 +1,241 @@
+package io.github.nickld.frigateglance;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.net.SocketTimeoutException;
+import java.net.URI;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+
+import javax.net.SocketFactory;
+
+/**
+ * A subscribe-only MQTT 3.1.1 client: CONNECT, SUBSCRIBE at QoS 0, then PUBLISH messages in and PINGREQ out.
+ * That is all Frigate's topics need, in a few KB instead of a client library. One run() is one session;
+ * the caller reconnects, waiting backoffMs(attempt) in between.
+ */
+public final class MqttClient {
+ public interface Listener {
+ void onConnected();
+
+ void onMessage(String topic, byte[] payload);
+
+ void onDisconnected(Exception cause);
+ }
+
+ static final int KEEPALIVE_S = 60;
+ static final int PING_EVERY_MS = 30_000;
+ private static final int CONNECT_TIMEOUT_MS = 10_000;
+ private static final String[] REFUSALS = {
+ "", "unacceptable protocol version", "identifier rejected", "server unavailable",
+ "bad user name or password", "not authorised",
+ };
+
+ private final String host, user, password, clientId;
+ private final int port;
+ private final List<String> topics;
+ private final Listener listener;
+ private final java.util.function.LongSupplier clock;
+ private long lastWrite;
+ private volatile Socket socket;
+ private volatile boolean stopped;
+
+ /** url: mqtt://user:pass@host:port, user and password percent-encoded; port 1883 when left out. */
+ public MqttClient(String url, String clientId, List<String> topics, Listener listener) {
+ this(url, clientId, topics, listener, android.os.SystemClock::elapsedRealtime);
+ }
+
+ /** clock: milliseconds, for the keep-alive; tests pass their own. */
+ MqttClient(String url, String clientId, List<String> topics, Listener listener, java.util.function.LongSupplier clock) {
+ this.clock = clock;
+ URI u = URI.create(url);
+ host = u.getHost();
+ port = u.getPort() > 0 ? u.getPort() : 1883;
+ String info = u.getRawUserInfo();
+ if (info == null) {
+ user = null;
+ password = null;
+ } else {
+ int c = info.indexOf(':');
+ user = decode(c < 0 ? info : info.substring(0, c));
+ password = c < 0 ? null : decode(info.substring(c + 1));
+ }
+ this.clientId = clientId;
+ this.topics = topics;
+ this.listener = listener;
+ }
+
+ /** One session over a socket. Blocks until it ends; always ends with onDisconnected. */
+ public void run(SocketFactory factory) {
+ try {
+ Socket s = factory.createSocket();
+ socket = s;
+ if (stopped) throw new IOException("stopped");
+ s.connect(new InetSocketAddress(host, port), CONNECT_TIMEOUT_MS);
+ s.setSoTimeout(PING_EVERY_MS);
+ session(s.getInputStream(), s.getOutputStream());
+ } catch (IOException | RuntimeException e) {
+ listener.onDisconnected(e instanceof IOException ? e : new IOException("bad broker address or packet", e));
+ } finally {
+ closeQuietly();
+ }
+ }
+
+ public void stop() {
+ stopped = true;
+ closeQuietly();
+ }
+
+ /** Wait before reconnect attempt n (0 based): 1 s doubling to 60 s. */
+ public static long backoffMs(int attempt) {
+ return attempt >= 6 ? 60_000 : Math.min(60_000, 1000L << attempt);
+ }
+
+ /** The protocol, over any pair of streams. Reports the end through onDisconnected. */
+ void session(InputStream rawIn, OutputStream out) {
+ try {
+ DataInputStream in = new DataInputStream(rawIn);
+ out.write(connectPacket());
+ out.flush();
+ int[] header = readHeader(in, out);
+ if (header[0] != 0x20 || header[1] != 2) throw new IOException("broker did not answer CONNECT");
+ in.readUnsignedByte();
+ int rc = in.readUnsignedByte();
+ if (rc != 0) {
+ throw new IOException("broker refused: " + (rc < REFUSALS.length ? REFUSALS[rc] : "code " + rc));
+ }
+ out.write(subscribePacket());
+ out.flush();
+ lastWrite = clock.getAsLong();
+ listener.onConnected();
+ while (!stopped) {
+ header = readHeader(in, out);
+ byte[] body = new byte[header[1]];
+ in.readFully(body);
+ if ((header[0] & 0xF0) == 0x30) deliver(header[0], body);
+ // A steady stream of messages never lets the read time out, but the broker drops a client it
+ // has not heard from for 1.5 keep-alives: ping on schedule whatever arrives.
+ if (clock.getAsLong() - lastWrite >= PING_EVERY_MS) {
+ out.write(new byte[] {(byte) 0xC0, 0x00});
+ out.flush();
+ lastWrite = clock.getAsLong();
+ }
+ }
+ throw new IOException("stopped");
+ } catch (IOException e) {
+ listener.onDisconnected(e);
+ } catch (RuntimeException e) {
+ listener.onDisconnected(new IOException("unreadable packet from the broker", e));
+ }
+ }
+
+ private void deliver(int flags, byte[] body) {
+ int topicLength = ((body[0] & 0xff) << 8) | (body[1] & 0xff);
+ String topic = new String(body, 2, topicLength, StandardCharsets.UTF_8);
+ int start = 2 + topicLength + (((flags >> 1) & 3) > 0 ? 2 : 0);
+ byte[] payload = new byte[body.length - start];
+ System.arraycopy(body, start, payload, 0, payload.length);
+ listener.onMessage(topic, payload);
+ }
+
+ /** Packet type byte and remaining length. A read timeout sends PINGREQ; two in a row end the session. */
+ private static int[] readHeader(DataInputStream in, OutputStream out) throws IOException {
+ int first = -1;
+ for (int quiet = 0; first < 0; ) {
+ try {
+ first = in.read();
+ if (first < 0) throw new EOFException("broker closed the connection");
+ } catch (SocketTimeoutException e) {
+ if (++quiet > 1) throw new IOException("broker stopped answering");
+ out.write(new byte[] {(byte) 0xC0, 0x00});
+ out.flush();
+ }
+ }
+ int length = 0;
+ for (int shift = 0, b; ; shift += 7) {
+ if (shift > 21) throw new IOException("bad remaining length");
+ b = in.readUnsignedByte();
+ length |= (b & 0x7F) << shift;
+ if ((b & 0x80) == 0) break;
+ }
+ return new int[] {first, length};
+ }
+
+ private byte[] connectPacket() {
+ ByteArrayOutputStream body = new ByteArrayOutputStream();
+ writeString(body, "MQTT");
+ body.write(4);
+ int flags = 0x02;
+ if (user != null) flags |= 0x80;
+ if (password != null) flags |= 0x40;
+ body.write(flags);
+ body.write(KEEPALIVE_S >> 8);
+ body.write(KEEPALIVE_S & 0xff);
+ writeString(body, clientId);
+ if (user != null) writeString(body, user);
+ if (password != null) writeString(body, password);
+ return packet(0x10, body.toByteArray());
+ }
+
+ private byte[] subscribePacket() {
+ ByteArrayOutputStream body = new ByteArrayOutputStream();
+ body.write(0);
+ body.write(1);
+ for (String t : topics) {
+ writeString(body, t);
+ body.write(0);
+ }
+ return packet(0x82, body.toByteArray());
+ }
+
+ private static byte[] packet(int type, byte[] body) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ out.write(type);
+ byte[] len = remainingLength(body.length);
+ out.write(len, 0, len.length);
+ out.write(body, 0, body.length);
+ return out.toByteArray();
+ }
+
+ static byte[] remainingLength(int n) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ do {
+ int b = n % 128;
+ n /= 128;
+ out.write(n > 0 ? b | 0x80 : b);
+ } while (n > 0);
+ return out.toByteArray();
+ }
+
+ private static void writeString(ByteArrayOutputStream out, String s) {
+ byte[] b = s.getBytes(StandardCharsets.UTF_8);
+ out.write(b.length >> 8);
+ out.write(b.length & 0xff);
+ out.write(b, 0, b.length);
+ }
+
+ private static String decode(String s) {
+ try {
+ return URLDecoder.decode(s.replace("+", "%2B"), "UTF-8");
+ } catch (java.io.UnsupportedEncodingException e) {
+ return s;
+ }
+ }
+
+ private void closeQuietly() {
+ Socket s = socket;
+ if (s == null) return;
+ try {
+ s.close();
+ } catch (IOException ignored) {
+ // closing anyway
+ }
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/OverlayCard.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/OverlayCard.java
new file mode 100644
index 000000000..128b8aa2d
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/OverlayCard.java
@@ -0,0 +1,443 @@
+package io.github.nickld.frigateglance;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.PixelFormat;
+import android.graphics.Typeface;
+import android.media.AudioManager;
+import android.os.Handler;
+import android.text.SpannableStringBuilder;
+import android.text.style.ForegroundColorSpan;
+import android.text.style.StyleSpan;
+import android.os.Looper;
+import android.util.Log;
+import android.view.Gravity;
+import android.view.TextureView;
+import android.view.View;
+import android.view.WindowManager;
+import android.view.animation.LinearInterpolator;
+import android.widget.FrameLayout;
+import android.widget.ImageView;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+import java.io.IOException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+/**
+ * The card on screen: a window over every app that never takes focus or touches, so the remote keeps
+ * controlling what is playing. Called from the service's thread; does its view work on the main thread.
+ */
+final class OverlayCard implements CardView {
+ /** Where the picture comes from; the service answers from Frigate. */
+ interface Source {
+ byte[] snapshot(String camera) throws IOException;
+
+ /** Width over height of the camera's frame, so boxes line up; 16/9 when unknown. */
+ float aspect(String camera);
+
+ /** RTSP address for live video, or null when live video is off. */
+ String liveUrl(String camera);
+ }
+
+ /** Told when a card appears and leaves, so the key service filters keys only meanwhile. */
+ interface ShowingListener {
+ void onShowing(boolean showing);
+ }
+
+ static final int WIDTH_DP = 320;
+ static final int MAX_HEIGHT_DP = 180;
+ private static final int MARGIN_DP = 24;
+ static final long SNAPSHOT_REFRESH_MS = 1000;
+
+ private final Context context;
+ private final WindowManager wm;
+ private final Handler main = new Handler(Looper.getMainLooper());
+ private final ExecutorService loader = Executors.newSingleThreadExecutor();
+ private final Source source;
+ private final ShowingListener showingListener;
+ private final float dp;
+
+ private GlanceConfig config;
+ private LinearLayout root;
+ private FrameLayout picture;
+ private ImageView image;
+ private TextureView video;
+ private LiveVideo live;
+ private boolean refreshing;
+ private int refreshLoop;
+ private BoxView boxes;
+ /** Peek's timer bar: red and full while the event goes on, white and shrinking once it has ended. */
+ private View timerBar;
+ private ModeBadge badge;
+ private boolean countingDown;
+ private TextView info;
+ /** One label per action ("◀ Dismiss", "Hold ▶ Snooze 1h"), so a hold can draw its pill around just one. */
+ private LinearLayout footer;
+ private final java.util.Map<Integer, TextView> actionLabels = new java.util.HashMap<>();
+ private String footerText = "";
+ private android.animation.ValueAnimator holdAnim;
+ private volatile String reviewId;
+ private boolean snapshotLogged;
+
+ OverlayCard(Context context, GlanceConfig config, Source source, ShowingListener showingListener) {
+ this.context = context;
+ this.wm = context.getSystemService(WindowManager.class);
+ this.config = config;
+ this.source = source;
+ this.showingListener = showingListener;
+ this.dp = context.getResources().getDisplayMetrics().density;
+ }
+
+ void setConfig(GlanceConfig c) {
+ config = c;
+ }
+
+ /** The last card shown, for the settings screen's Overview. */
+ static volatile String lastTitle = "";
+ static volatile long lastShownAt;
+
+ @Override
+ public void show(CardModel m) {
+ reviewId = m.reviewId;
+ lastTitle = m.title + (m.detail.isEmpty() ? "" : " · " + m.detail);
+ lastShownAt = System.currentTimeMillis();
+ main.post(() -> {
+ boolean fresh = root == null;
+ if (fresh) build();
+ fill(m, true);
+ if (fresh) {
+ try {
+ wm.addView(root, params());
+ } catch (RuntimeException e) {
+ Log.w(ConfigStore.TAG, "card not shown (display over other apps not allowed?): " + e.getMessage());
+ root = null;
+ return;
+ }
+ slideIn();
+ showingListener.onShowing(true);
+ }
+ });
+ loadSnapshot(m.reviewId, m.camera);
+ main.post(() -> startPicture(m.reviewId, m.camera));
+ }
+
+ /** Live video when it is on and starts; otherwise a snapshot refreshed every second. */
+ private void startPicture(String id, String camera) {
+ if (root == null || !id.equals(reviewId)) return;
+ stopPicture();
+ String url = source.liveUrl(camera);
+ // Something already playing holds the TV's video decoder; a second stream fails there and makes the
+ // playing app stall for a moment (TCL 65Q650G with YouTube). Snapshots then, live video over menus.
+ AudioManager audio = context.getSystemService(AudioManager.class);
+ if (url != null && audio != null && audio.isMusicActive()) {
+ Log.i(ConfigStore.TAG, "media playing; snapshots instead of live video");
+ url = null;
+ }
+ if (url == null) {
+ refresh(id, camera);
+ return;
+ }
+ live = new LiveVideo(context, new LiveVideo.Listener() {
+ @Override
+ public void onPlaying() {
+ if (badge != null) badge.setLive(true);
+ if (video != null) video.animate().alpha(1f).setDuration(300).start();
+ }
+
+ @Override
+ public void onGaveUp() {
+ if (badge != null) badge.setLive(false);
+ if (video != null) video.setAlpha(0f);
+ refresh(id, camera);
+ }
+ });
+ live.start(url, video);
+ }
+
+ /**
+ * A new snapshot a second after the last one arrived (or failed), never more than one in flight, so a slow
+ * Frigate is not buried in requests. One loop per card: a newer loop or stopPicture ends the old one.
+ */
+ private void refresh(String id, String camera) {
+ refreshing = true;
+ int loop = ++refreshLoop;
+ main.postDelayed(new Runnable() {
+ @Override
+ public void run() {
+ if (!refreshing || loop != refreshLoop || root == null || !id.equals(reviewId)) return;
+ Runnable again = this;
+ loadSnapshot(id, camera, () -> main.postDelayed(again, SNAPSHOT_REFRESH_MS));
+ }
+ }, SNAPSHOT_REFRESH_MS);
+ }
+
+ private void stopPicture() {
+ refreshing = false;
+ refreshLoop++;
+ if (live != null) {
+ live.release();
+ live = null;
+ }
+ if (video != null) video.setAlpha(0f);
+ if (badge != null) badge.setLive(false);
+ }
+
+ @Override
+ public void update(CardModel m) {
+ main.post(() -> {
+ if (root != null && m.reviewId.equals(reviewId)) fill(m, false);
+ });
+ }
+
+ /** A hold key went down: a pill outline draws itself around its action over HOLD_MS, green once closed. */
+ void showHold(int action) {
+ main.post(() -> {
+ clearHold();
+ TextView label = actionLabels.get(action);
+ if (label == null || root == null) return;
+ PillProgress pill = new PillProgress(Math.max(1f, 1.5f * dp * scale()));
+ label.setBackground(pill);
+ holdAnim = android.animation.ValueAnimator.ofFloat(0f, 1f).setDuration(KeyRules.HOLD_MS);
+ holdAnim.setInterpolator(new LinearInterpolator());
+ holdAnim.addUpdateListener(a -> pill.setProgress((float) a.getAnimatedValue()));
+ holdAnim.start();
+ });
+ }
+
+ /** The hold key came up: the pill goes. */
+ void endHold() {
+ main.post(this::clearHold);
+ }
+
+ private void clearHold() {
+ if (holdAnim != null) holdAnim.cancel();
+ holdAnim = null;
+ for (TextView t : actionLabels.values()) t.setBackground(null);
+ }
+
+ @Override
+ public void hide() {
+ reviewId = null;
+ main.post(() -> {
+ if (root == null) return;
+ View gone = root;
+ stopPicture();
+ root = null;
+ video = null;
+ showingListener.onShowing(false);
+ gone.animate().translationX(slideDistance()).alpha(0f).setDuration(200)
+ .withEndAction(() -> removeQuietly(gone)).start();
+ });
+ }
+
+ private void build() {
+ root = new LinearLayout(context);
+ root.setOrientation(LinearLayout.VERTICAL);
+ root.setBackgroundResource(R.drawable.card_glass);
+ int pad = px(8);
+ root.setPadding(pad, pad, pad, pad);
+
+ // Camera and what was seen above the picture, the two buttons in a small line under it.
+ info = text(13, 0xFFC9D1D9, Typeface.DEFAULT);
+ LinearLayout.LayoutParams ip = new LinearLayout.LayoutParams(-1, -2);
+ ip.bottomMargin = px(5);
+ root.addView(info, ip);
+
+ picture = new FrameLayout(context);
+ picture.setBackgroundResource(R.drawable.picture_frame);
+ picture.setClipToOutline(true);
+ image = new ImageView(context);
+ image.setScaleType(ImageView.ScaleType.FIT_XY);
+ video = new TextureView(context);
+ video.setAlpha(0f);
+ boxes = new BoxView(context);
+ picture.addView(image, new FrameLayout.LayoutParams(-1, -1));
+ picture.addView(video, new FrameLayout.LayoutParams(-1, -1));
+ picture.addView(boxes, new FrameLayout.LayoutParams(-1, -1));
+ timerBar = new View(context);
+ timerBar.setPivotX(0f);
+ picture.addView(timerBar, new FrameLayout.LayoutParams(-1, px(3), Gravity.TOP));
+ badge = new ModeBadge(context, 14 * scale());
+ FrameLayout.LayoutParams bp = new FrameLayout.LayoutParams(-2, -2, Gravity.TOP | Gravity.END);
+ bp.setMargins(0, px(8), px(6), 0);
+ picture.addView(badge, bp);
+ root.addView(picture, new LinearLayout.LayoutParams(px(WIDTH_DP), px(WIDTH_DP * 9 / 16)));
+
+ footer = new LinearLayout(context);
+ footer.setOrientation(LinearLayout.HORIZONTAL);
+ footer.setGravity(Gravity.CENTER_VERTICAL);
+ footerText = "";
+ actionLabels.clear();
+ LinearLayout.LayoutParams fp = new LinearLayout.LayoutParams(-1, -2);
+ fp.topMargin = px(4);
+ root.addView(footer, fp);
+ }
+
+ private void fill(CardModel m, boolean newCard) {
+ if (newCard) {
+ // At most 320 dp wide and 180 dp tall (a 16:9 frame fills both), in the camera's own shape so boxes line up.
+ sizePicture(source.aspect(m.camera));
+ image.setImageDrawable(null);
+ countingDown = false;
+ }
+ SpannableStringBuilder t = new SpannableStringBuilder(m.title);
+ t.setSpan(new StyleSpan(Typeface.BOLD), 0, t.length(), 0);
+ t.setSpan(new ForegroundColorSpan(0xFFFFFFFF), 0, t.length(), 0);
+ if (!m.detail.isEmpty()) t.append(" ").append(m.detail);
+ info.setText(t);
+ java.util.Map<Integer, String> parts = CardText.parts(config.dismissKey, config.snoozeKey, config.snoozeMinutes,
+ config.fullscreen ? config.fullscreenKey : null);
+ String text = String.join(" · ", parts.values());
+ if (!text.equals(footerText)) {
+ footerText = text;
+ footer.removeAllViews();
+ actionLabels.clear();
+ int padH = px(5), padV = px(2);
+ for (java.util.Map.Entry<Integer, String> e : parts.entrySet()) {
+ if (footer.getChildCount() > 0) footer.addView(text(10, 0xFF8B949E, Typeface.DEFAULT));
+ TextView label = text(10, 0xFF8B949E, Typeface.DEFAULT);
+ label.setText(e.getValue());
+ label.setPadding(padH, padV, padH, padV);
+ footer.addView(label);
+ actionLabels.put(e.getKey(), label);
+ }
+ for (int k = 0; k < footer.getChildCount(); k++) {
+ TextView sep = (TextView) footer.getChildAt(k);
+ if (!actionLabels.containsValue(sep)) sep.setText("·");
+ }
+ }
+ boxes.setBoxes(config.boxes ? m.boxes : null);
+ updateTimerBar(m.countdownMs);
+ }
+
+ private void updateTimerBar(long countdownMs) {
+ if (countdownMs <= 0) {
+ countingDown = false;
+ timerBar.animate().cancel();
+ timerBar.setScaleX(1f);
+ timerBar.setBackgroundColor(0xD9DC3C3C);
+ return;
+ }
+ if (countingDown) return;
+ countingDown = true;
+ timerBar.setBackgroundColor(0xBFFFFFFF);
+ timerBar.setScaleX(1f);
+ timerBar.animate().scaleX(0f).setDuration(countdownMs).setInterpolator(new LinearInterpolator()).start();
+ }
+
+ private void sizePicture(float aspect) {
+ int h = Math.min(px(MAX_HEIGHT_DP), Math.round(px(WIDTH_DP) / aspect));
+ LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) picture.getLayoutParams();
+ int w = Math.round(h * aspect);
+ if (lp.height == h && lp.width == w) return;
+ lp.height = h;
+ lp.width = w;
+ picture.setLayoutParams(lp);
+ }
+
+ void loadSnapshot(String id, String camera) {
+ loadSnapshot(id, camera, null);
+ }
+
+ private void loadSnapshot(String id, String camera, Runnable done) {
+ loader.execute(() -> {
+ if (!id.equals(reviewId)) return; // the card it was for has gone
+ try {
+ byte[] jpeg = source.snapshot(camera);
+ Bitmap bmp = decode(jpeg);
+ main.post(() -> {
+ if (root == null || !id.equals(reviewId) || bmp == null) return;
+ // The frame's own shape, in case Frigate's camera sizes were not known when the card opened.
+ sizePicture((float) bmp.getWidth() / bmp.getHeight());
+ image.setImageBitmap(bmp);
+ });
+ } catch (IOException | RuntimeException e) {
+ if (!snapshotLogged) Log.w(ConfigStore.TAG, "frigate error: snapshot " + camera + ": " + e.getMessage());
+ snapshotLogged = true;
+ } finally {
+ if (done != null) main.post(done);
+ }
+ });
+ }
+
+ /** Current review id on screen, or null. */
+ String reviewId() {
+ return reviewId;
+ }
+
+ private Bitmap decode(byte[] jpeg) {
+ BitmapFactory.Options o = new BitmapFactory.Options();
+ o.inJustDecodeBounds = true;
+ BitmapFactory.decodeByteArray(jpeg, 0, jpeg.length, o);
+ int sample = 1;
+ while (o.outWidth / (sample * 2) >= px(WIDTH_DP)) sample *= 2;
+ BitmapFactory.Options d = new BitmapFactory.Options();
+ d.inSampleSize = sample;
+ d.inPreferredConfig = Bitmap.Config.RGB_565;
+ return BitmapFactory.decodeByteArray(jpeg, 0, jpeg.length, d);
+ }
+
+ private WindowManager.LayoutParams params() {
+ WindowManager.LayoutParams p = new WindowManager.LayoutParams(
+ WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
+ WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
+ | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
+ PixelFormat.TRANSLUCENT);
+ p.gravity = gravity(config.corner);
+ p.x = Math.round(MARGIN_DP * dp); // the gap from the screen edge does not grow with the card
+ p.y = Math.round(MARGIN_DP * dp);
+ p.setTitle("Frigate Glance");
+ return p;
+ }
+
+ static int gravity(String corner) {
+ switch (corner) {
+ case "top-left": return Gravity.TOP | Gravity.LEFT;
+ case "bottom-left": return Gravity.BOTTOM | Gravity.LEFT;
+ case "bottom-right": return Gravity.BOTTOM | Gravity.RIGHT;
+ default: return Gravity.TOP | Gravity.RIGHT;
+ }
+ }
+
+ private void slideIn() {
+ root.setTranslationX(slideDistance());
+ root.setAlpha(0f);
+ root.animate().translationX(0f).alpha(1f).setDuration(250).start();
+ }
+
+ private float slideDistance() {
+ float d = px(WIDTH_DP + MARGIN_DP);
+ return config.corner.endsWith("left") ? -d : d;
+ }
+
+ private TextView text(int sp, int color, Typeface face) {
+ TextView t = new TextView(context);
+ t.setTextSize(sp * scale());
+ t.setTextColor(color);
+ t.setTypeface(face);
+ t.setSingleLine(true);
+ t.setEllipsize(android.text.TextUtils.TruncateAt.END);
+ return t;
+ }
+
+ /** Card dimensions in pixels, at the card size chosen in the settings (cardScale). */
+ private int px(int dps) {
+ return Math.round(dps * dp * scale());
+ }
+
+ private float scale() {
+ return config.cardScale / 100f;
+ }
+
+ private void removeQuietly(View v) {
+ try {
+ wm.removeView(v);
+ } catch (RuntimeException ignored) {
+ // already gone
+ }
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/PillProgress.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/PillProgress.java
new file mode 100644
index 000000000..0ad6926f2
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/PillProgress.java
@@ -0,0 +1,69 @@
+package io.github.nickld.frigateglance;
+
+import android.graphics.Canvas;
+import android.graphics.ColorFilter;
+import android.graphics.Paint;
+import android.graphics.Path;
+import android.graphics.PathMeasure;
+import android.graphics.PixelFormat;
+import android.graphics.RectF;
+import android.graphics.drawable.Drawable;
+
+/**
+ * A pill outline around a footer action that draws itself clockwise from the top centre as a hold key is held.
+ * White while it is drawing; green once it closes, which is when letting go acts.
+ */
+final class PillProgress extends Drawable {
+ private static final int DRAWING = 0xFFFFFFFF, CLOSED = 0xFF3DDC84;
+
+ private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
+ private final Path outline = new Path();
+ private final Path part = new Path();
+ private final PathMeasure measure = new PathMeasure();
+ private float progress;
+
+ PillProgress(float strokePx) {
+ paint.setStyle(Paint.Style.STROKE);
+ paint.setStrokeWidth(strokePx);
+ paint.setStrokeCap(Paint.Cap.ROUND);
+ }
+
+ /** 0 to 1; at 1 the pill is closed and turns green. */
+ void setProgress(float p) {
+ progress = Math.max(0f, Math.min(1f, p));
+ invalidateSelf();
+ }
+
+ @Override
+ protected void onBoundsChange(android.graphics.Rect b) {
+ float inset = paint.getStrokeWidth() / 2f;
+ RectF r = new RectF(b.left + inset, b.top + inset, b.right - inset, b.bottom - inset);
+ float radius = r.height() / 2f;
+ // Start at the top centre and go clockwise, so the stroke grows out from above the label.
+ outline.reset();
+ outline.moveTo(r.centerX(), r.top);
+ outline.lineTo(r.right - radius, r.top);
+ outline.arcTo(new RectF(r.right - 2 * radius, r.top, r.right, r.bottom), -90, 180);
+ outline.lineTo(r.left + radius, r.bottom);
+ outline.arcTo(new RectF(r.left, r.top, r.left + 2 * radius, r.bottom), 90, 180);
+ outline.close();
+ measure.setPath(outline, false);
+ }
+
+ @Override
+ public void draw(Canvas canvas) {
+ if (progress <= 0f) return;
+ paint.setColor(progress >= 1f ? CLOSED : DRAWING);
+ if (progress >= 1f) {
+ canvas.drawPath(outline, paint);
+ return;
+ }
+ part.reset();
+ measure.getSegment(0, measure.getLength() * progress, part, true);
+ canvas.drawPath(part, paint);
+ }
+
+ @Override public void setAlpha(int alpha) { paint.setAlpha(alpha); }
+ @Override public void setColorFilter(ColorFilter cf) { paint.setColorFilter(cf); }
+ @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/Review.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/Review.java
new file mode 100644
index 000000000..f3c1783a9
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/Review.java
@@ -0,0 +1,71 @@
+package io.github.nickld.frigateglance;
+
+import java.util.List;
+import java.util.Set;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/** One message from frigate/reviews: a review item starting (new), changing (update) or ending (end). */
+public final class Review {
+ private static final Set<String> TYPES = Set.of("new", "update", "end");
+
+ public final String type, id, camera, severity;
+ public final List<String> objects, zones, detectionIds;
+
+ private Review(String type, JSONObject after) {
+ this.type = type;
+ id = after.optString("id", "");
+ camera = after.optString("camera", "");
+ severity = after.optString("severity", "");
+ JSONObject data = after.optJSONObject("data");
+ objects = Json.strings(data == null ? null : data.optJSONArray("objects"));
+ zones = Json.strings(data == null ? null : data.optJSONArray("zones"));
+ detectionIds = Json.strings(data == null ? null : data.optJSONArray("detections"));
+ }
+
+ private Review(String type, String id, String camera, List<String> objects, List<String> zones, String eventId) {
+ this.type = type;
+ this.id = id;
+ this.camera = camera;
+ this.severity = "alert";
+ this.objects = objects;
+ this.zones = zones;
+ this.detectionIds = List.of(eventId);
+ }
+
+ /**
+ * Frigate's debug replay ("_replay_<camera>") publishes tracked-object events but no review items, so for
+ * those cameras each event stands in for an alert of its own: new opens, update refreshes, end counts down.
+ * Null for any other camera, whose cards come from real reviews only.
+ */
+ public static Review fromReplayEvent(String payload) {
+ try {
+ JSONObject o = new JSONObject(payload);
+ String type = o.optString("type", "");
+ JSONObject a = o.optJSONObject("after");
+ if (!TYPES.contains(type) || a == null) return null;
+ String camera = a.optString("camera", "");
+ String id = a.optString("id", "");
+ String label = a.optString("label", "");
+ if (!camera.startsWith(ReviewFilter.REPLAY_PREFIX) || id.isEmpty() || label.isEmpty()) return null;
+ return new Review(type, "replay-" + id, camera, List.of(label), Json.strings(a.optJSONArray("entered_zones")), id);
+ } catch (JSONException e) {
+ return null;
+ }
+ }
+
+ /** The parsed message, or null when it is not a review message this add-on understands. */
+ public static Review parse(String payload) {
+ try {
+ JSONObject o = new JSONObject(payload);
+ String type = o.optString("type", "");
+ JSONObject after = o.optJSONObject("after");
+ if (!TYPES.contains(type) || after == null) return null;
+ Review r = new Review(type, after);
+ return r.id.isEmpty() || r.camera.isEmpty() || r.severity.isEmpty() ? null : r;
+ } catch (JSONException e) {
+ return null;
+ }
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/ReviewFilter.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/ReviewFilter.java
new file mode 100644
index 000000000..67447d45d
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/ReviewFilter.java
@@ -0,0 +1,36 @@
+package io.github.nickld.frigateglance;
+
+/** Decides whether a review may open a card: severity, camera, objects and snooze. */
+public final class ReviewFilter {
+ private final GlanceConfig config;
+
+ public ReviewFilter(GlanceConfig config) {
+ this.config = config;
+ }
+
+ static final String REPLAY_PREFIX = "_replay_";
+
+ /** Frigate's debug replay runs a recording as camera "_replay_<name>"; it counts as <name>. */
+ static String baseCamera(String camera) {
+ return camera.startsWith(REPLAY_PREFIX) ? camera.substring(REPLAY_PREFIX.length()) : camera;
+ }
+
+ /** Switched off on the settings screen: never. Else listed in "cameras", or every camera when the list is empty
+ * or newCameras is on. */
+ static boolean cameraOn(GlanceConfig c, String camera) {
+ if (c.camerasOff.contains(camera)) return false;
+ return c.newCameras || c.cameras.isEmpty() || c.cameras.containsKey(camera);
+ }
+
+ public boolean shows(Review r, long nowMs, long snoozedUntilMs) {
+ if (nowMs < snoozedUntilMs) return false;
+ if (!"alert".equals(r.severity)
+ && !("detection".equals(r.severity) && "alerts_and_detections".equals(config.severity))) {
+ return false;
+ }
+ if (!cameraOn(config, baseCamera(r.camera))) return false;
+ if (config.labels.isEmpty()) return true;
+ for (String o : r.objects) if (config.labels.contains(o)) return true;
+ return false;
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/SettingRow.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/SettingRow.java
new file mode 100644
index 000000000..5dab10990
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/SettingRow.java
@@ -0,0 +1,66 @@
+package io.github.nickld.frigateglance;
+
+import android.content.Context;
+import android.view.Gravity;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+/** One settings row: a name with a line saying what it does on the left, its value on the right; OK runs it. */
+final class SettingRow extends LinearLayout {
+ private final TextView value;
+ private final TextView desc;
+
+ SettingRow(Context context, String name, String value, Runnable onClick) {
+ this(context, name, null, value, onClick);
+ }
+
+ SettingRow(Context context, String name, String description, String value, Runnable onClick) {
+ super(context);
+ float dp = context.getResources().getDisplayMetrics().density;
+ setOrientation(HORIZONTAL);
+ setGravity(Gravity.CENTER_VERTICAL);
+ int ph = Math.round(16 * dp), pv = Math.round(10 * dp);
+ setPadding(ph, pv, ph, pv);
+ setBackgroundResource(R.drawable.row_background);
+ setFocusable(onClick != null);
+ setClickable(onClick != null);
+ if (onClick != null) setOnClickListener(v -> onClick.run());
+
+ LinearLayout text = new LinearLayout(context);
+ text.setOrientation(VERTICAL);
+ TextView label = new TextView(context);
+ label.setText(name);
+ label.setTextSize(17);
+ label.setTextColor(0xFFFFFFFF);
+ text.addView(label);
+ desc = new TextView(context);
+ desc.setTextSize(12);
+ desc.setTextColor(0xFF8B949E);
+ desc.setPadding(0, Math.round(2 * dp), Math.round(16 * dp), 0);
+ text.addView(desc);
+ setDetail(description);
+ addView(text, new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f));
+
+ this.value = new TextView(context);
+ this.value.setTextSize(17);
+ this.value.setTextColor(0xFFC9D1D9);
+ this.value.setText(value);
+ addView(this.value, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
+ }
+
+ void setDetail(String d) {
+ desc.setText(d == null ? "" : d);
+ desc.setVisibility(d == null || d.isEmpty() ? GONE : VISIBLE);
+ }
+
+ void setValue(String v) {
+ value.setText(v);
+ }
+
+ /** A value that needs to stand out, such as the snooze state: coloured and bold. */
+ void setValue(String v, int color) {
+ value.setText(v);
+ value.setTextColor(color);
+ value.setTypeface(value.getTypeface(), android.graphics.Typeface.BOLD);
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/SettingsActivity.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/SettingsActivity.java
new file mode 100644
index 000000000..5b19ec7a7
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/SettingsActivity.java
@@ -0,0 +1,417 @@
+package io.github.nickld.frigateglance;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.text.SpannableStringBuilder;
+import android.text.format.DateFormat;
+import android.text.style.ForegroundColorSpan;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.LinearLayout;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * The tile and module card open this: a menu of sections on the left, that section's rows on the right.
+ * Moving through the menu switches the right side; Right enters the rows, Left goes back to the menu. Every
+ * row changes with OK. No text fields: addresses and passwords come from the pushed config file.
+ */
+public class SettingsActivity extends Activity {
+ private static final long REFRESH_MS = 2000;
+ private static final int SNOOZED = 0xFFFFB454, CARDS_ON = 0xFF3DDC84;
+ private static final String[] SECTIONS = {"Overview", "Cameras", "Alerts", "Card", "Remote"};
+ private static final Map<String, String> CORNER_NAMES = Map.of(
+ "top-right", "Top right", "top-left", "Top left", "bottom-left", "Bottom left", "bottom-right", "Bottom right");
+
+ private final Handler main = new Handler(Looper.getMainLooper());
+ private LinearLayout menu, rows;
+ private ConfigStore store;
+ private TextView status;
+ private SettingRow snoozeRow, mqttRow, frigateRow, messagesRow, lastCardRow, tvRow;
+ private int section;
+ private boolean waitingForFrigate;
+ private final Runnable refresh = new Runnable() {
+ @Override
+ public void run() {
+ updateLive();
+ main.postDelayed(this, REFRESH_MS);
+ }
+ };
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ store = new ConfigStore(this);
+ LinearLayout page = new LinearLayout(this);
+ page.setOrientation(LinearLayout.VERTICAL);
+ page.setBackgroundColor(0xFF0D1117);
+ page.setPadding(px(48), px(32), px(48), px(24));
+ TextView title = new TextView(this);
+ title.setText(R.string.app_name);
+ title.setTextSize(28);
+ title.setTextColor(0xFFFFFFFF);
+ status = new TextView(this);
+ status.setTextSize(15);
+ status.setTextColor(0xFF8B949E);
+ status.setPadding(0, 0, 0, px(16));
+ page.addView(title);
+ page.addView(status);
+
+ LinearLayout panes = new LinearLayout(this);
+ panes.setOrientation(LinearLayout.HORIZONTAL);
+ menu = new LinearLayout(this);
+ menu.setOrientation(LinearLayout.VERTICAL);
+ panes.addView(menu, new LinearLayout.LayoutParams(px(220), ViewGroup.LayoutParams.WRAP_CONTENT));
+ View divider = new View(this);
+ divider.setBackgroundColor(0x22FFFFFF);
+ LinearLayout.LayoutParams dp = new LinearLayout.LayoutParams(px(1), ViewGroup.LayoutParams.MATCH_PARENT);
+ dp.leftMargin = px(16);
+ dp.rightMargin = px(16);
+ panes.addView(divider, dp);
+ ScrollView scroll = new ScrollView(this);
+ rows = new LinearLayout(this);
+ rows.setOrientation(LinearLayout.VERTICAL);
+ scroll.addView(rows);
+ panes.addView(scroll, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1f));
+ page.addView(panes, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f));
+ setContentView(page);
+
+ for (int i = 0; i < SECTIONS.length; i++) {
+ int index = i;
+ SettingRow item = new SettingRow(this, SECTIONS[i], "", () -> focusFirstRow());
+ item.setId(View.generateViewId());
+ item.setOnFocusChangeListener((v, has) -> {
+ if (has && section != index) {
+ section = index;
+ buildRows(-1);
+ }
+ });
+ menu.addView(item, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
+ }
+ GlanceService.start(this);
+ buildRows(-1);
+ menu.getChildAt(0).requestFocus();
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ // A config pushed while this screen was open: take it now and reconnect with it.
+ if (store.importPushed()) {
+ GlanceService.reload(this);
+ buildRows(-1);
+ }
+ main.post(refresh);
+ }
+
+ @Override
+ protected void onPause() {
+ main.removeCallbacks(refresh);
+ super.onPause();
+ }
+
+ /** Rebuilds the right side for the current section; focusIndex keeps focus on a row after a change. */
+ private void buildRows(int focusIndex) {
+ rows.removeAllViews();
+ snoozeRow = mqttRow = frigateRow = messagesRow = lastCardRow = tvRow = null;
+ GlanceConfig c = store.load();
+ if (c == null) {
+ rows.addView(new SettingRow(this, "No config yet", "push one with install.sh", null));
+ return;
+ }
+ JSONObject frigate = GlanceService.frigateConfig();
+ waitingForFrigate = frigate == null;
+ switch (SECTIONS[section]) {
+ case "Overview":
+ snoozeRow = row("Snooze", "No cards from any camera for the snooze length (Remote section). OK again resumes.", "", () -> {
+ if (GlanceService.snoozedUntilWallClock() > 0) GlanceService.resume();
+ else GlanceService.snoozeCard();
+ main.postDelayed(this::updateLive, 200);
+ });
+ divider();
+ mqttRow = info("MQTT broker", "");
+ frigateRow = info("Frigate", "");
+ messagesRow = info("Last message from Frigate", "");
+ lastCardRow = info("Last card", "");
+ tvRow = info("On this TV", "");
+ break;
+ case "Cameras":
+ List<String> cameras = SettingsModel.cameraNames(frigate);
+ row("New cameras", "Cameras added to Frigate later open cards too, without switching them on here."
+ + " Cameras switched off below stay off.", onOff(c.newCameras || c.cameras.isEmpty()),
+ () -> save(cfg -> {
+ boolean on = cfg.newCameras || cfg.cameras.isEmpty();
+ if (on && cfg.cameras.isEmpty()) {
+ // "No list" meant every camera: switching new ones off keeps today's as the list.
+ JSONObject names = new JSONObject();
+ try {
+ for (String cam : cameras) names.put(cam, CardController.pretty(cam));
+ } catch (JSONException ignored) {
+ // names stay as far as they got
+ }
+ store.saveSetting("cameras", names);
+ }
+ store.saveSetting("newCameras", !on);
+ }));
+ divider();
+ if (cameras.isEmpty()) rows.addView(new SettingRow(this, "Cameras", "waiting for Frigate", null));
+ for (String cam : cameras) {
+ String name = c.cameras.containsKey(cam) ? c.cameras.get(cam) : CardController.pretty(cam);
+ row(name, "Alerts from this camera open a card.",
+ onOff(SettingsModel.cameraOn(c, cam)), () -> save(cfg -> {
+ try {
+ JSONObject changes = SettingsModel.toggleCamera(cfg, cameras, cam);
+ for (java.util.Iterator<String> it = changes.keys(); it.hasNext(); ) {
+ String key = it.next();
+ store.saveSetting(key, changes.get(key));
+ }
+ } catch (JSONException ignored) {
+ // unchanged
+ }
+ }));
+ }
+ break;
+ case "Alerts":
+ row("Show", "Alerts are what Frigate's review settings mark as important (zones, objects). Detections"
+ + " are everything else it tracks, such as cars passing on the street.",
+ "alerts".equals(c.severity) ? "Alerts only" : "Alerts and detections", () -> save(cfg ->
+ store.saveSetting("severity", SettingsModel.next(SettingsModel.SEVERITIES, cfg.severity))));
+ divider();
+ List<String> labels = SettingsModel.labelNames(frigate);
+ if (labels.isEmpty()) rows.addView(new SettingRow(this, "Objects", "waiting for Frigate", null));
+ for (String label : labels) {
+ row(CardController.pretty(label), "Alerts with this object open a card.",
+ onOff(SettingsModel.labelOn(c, label)),
+ () -> save(cfg -> store.saveSetting("labels", SettingsModel.toggleLabel(cfg, labels, label))));
+ }
+ break;
+ case "Card":
+ row("Show a test card", "Pick a camera and its card shows now, to check where it sits and that the remote buttons work.",
+ "", () -> pickTestCamera(c));
+ divider();
+ row("Card size", "How big the card is, picture and text together.", c.cardScale + "%", () -> save(cfg ->
+ store.saveSetting("cardScale", SettingsModel.next(SettingsModel.CARD_SCALES, cfg.cardScale))));
+ row("Corner", "Which corner of the screen the card slides into.", CORNER_NAMES.get(c.corner),
+ () -> save(cfg -> store.saveSetting("corner", SettingsModel.next(SettingsModel.CORNERS, cfg.corner))));
+ row("Card stays", "How long the card stays once the event has ended, while the bar on top runs down.",
+ c.dismissSeconds + " s", () -> save(cfg -> store.saveSetting(
+ "dismissSeconds", SettingsModel.next(SettingsModel.DISMISS_SECONDS, cfg.dismissSeconds))));
+ row("Live video", "Moving picture from the camera. Off, or while another app plays sound, a snapshot every second instead.",
+ onOff(c.liveVideo), () -> save(cfg -> store.saveSetting("liveVideo", !cfg.liveVideo)));
+ row("Boxes", "Outlines around the objects Frigate detected, gone when the object leaves.", onOff(c.boxes), () -> save(cfg -> store.saveSetting("boxes", !cfg.boxes)));
+ break;
+ default:
+ row("Dismiss key", "The remote button that closes a card. It only does this while a card is up. OK, then press it.",
+ CardText.key(c.dismissKey), () -> pickKey("Dismiss", "dismissKey", others(c, "Dismiss")));
+ row("Hold to dismiss", "Dismiss only when the button is held for a moment, so a quick press while"
+ + " moving around an app does nothing.", onOff(c.dismissHold),
+ () -> save(cfg -> store.saveSetting("dismissHold", !cfg.dismissHold)));
+ row("Snooze key", "The remote button that closes a card and keeps cards away for the snooze length."
+ + " OK, then press it.", CardText.key(c.snoozeKey), () -> pickKey("Snooze", "snoozeKey", others(c, "Snooze")));
+ row("Hold to snooze", "Snooze only when the button is held for a moment.", onOff(c.snoozeHold),
+ () -> save(cfg -> store.saveSetting("snoozeHold", !cfg.snoozeHold)));
+ row("Snooze length", "How long a snooze lasts, from the remote or from Overview.", CardText.duration(c.snoozeMinutes), () -> save(cfg -> store.saveSetting(
+ "snoozeMinutes", SettingsModel.next(SettingsModel.SNOOZE_MINUTES, cfg.snoozeMinutes))));
+ divider();
+ row("Full screen", "A third card key that opens the camera full screen. Back returns to what was playing.",
+ onOff(c.fullscreen), () -> save(cfg -> {
+ if (!cfg.fullscreen) {
+ // Its key must differ from the other two: take the first free one if it clashes.
+ for (String k : new String[] {cfg.fullscreenKey, "KEYCODE_DPAD_UP", "KEYCODE_DPAD_DOWN",
+ "KEYCODE_MENU", "KEYCODE_PROG_RED", "KEYCODE_PROG_GREEN"}) {
+ if (!k.equals(cfg.dismissKey) && !k.equals(cfg.snoozeKey)) {
+ store.saveSetting("fullscreenKey", k);
+ break;
+ }
+ }
+ }
+ store.saveSetting("fullscreen", !cfg.fullscreen);
+ }));
+ if (c.fullscreen) {
+ row("Full screen key", "The remote button that opens the card's camera full screen. OK, then press it.",
+ CardText.key(c.fullscreenKey), () -> pickKey("Full screen", "fullscreenKey", others(c, "Full screen")));
+ row("Hold for full screen", "Open full screen only when the button is held for a moment.",
+ onOff(c.fullscreenHold), () -> save(cfg -> store.saveSetting("fullscreenHold", !cfg.fullscreenHold)));
+ }
+ break;
+ }
+ // Left from any row goes back to this section's menu item; Right from the menu enters at the first row.
+ int back = menu.getChildAt(section).getId();
+ int first = View.NO_ID;
+ for (int i = 0; i < rows.getChildCount(); i++) {
+ View r = rows.getChildAt(i);
+ r.setNextFocusLeftId(back);
+ if (first == View.NO_ID && r.isFocusable()) {
+ r.setId(View.generateViewId());
+ first = r.getId();
+ }
+ }
+ for (int i = 0; i < menu.getChildCount(); i++) {
+ menu.getChildAt(i).setActivated(i == section);
+ menu.getChildAt(i).setNextFocusRightId(first);
+ }
+ updateLive();
+ if (focusIndex >= 0 && focusIndex < rows.getChildCount()) rows.getChildAt(focusIndex).requestFocus();
+ }
+
+ private void focusFirstRow() {
+ for (int i = 0; i < rows.getChildCount(); i++) {
+ if (rows.getChildAt(i).isFocusable()) {
+ rows.getChildAt(i).requestFocus();
+ return;
+ }
+ }
+ }
+
+ /** The camera list for a test card; falls back to the first camera while Frigate's list is not in yet. */
+ private void pickTestCamera(GlanceConfig c) {
+ List<String> cameras = SettingsModel.cameraNames(GlanceService.frigateConfig());
+ if (cameras.isEmpty()) {
+ GlanceService.showTestCard(this, null);
+ return;
+ }
+ Map<String, String> names = new java.util.LinkedHashMap<>();
+ for (String cam : cameras) names.put(cam, c.cameras.containsKey(cam) ? c.cameras.get(cam) : CardController.pretty(cam));
+ new CameraPickerDialog(this, names, cam -> GlanceService.showTestCard(this, cam)).show();
+ }
+
+ /** Opens the "press the button" window; the button pressed is saved like any other setting. */
+ private void pickKey(String what, String key, Map<String, String> others) {
+ new KeyPickerDialog(this, what, others, name -> save(cfg -> store.saveSetting(key, name))).show();
+ }
+
+ /** The card keys other than this one, by name, for the picker's "already the ... key" check. */
+ private static Map<String, String> others(GlanceConfig c, String self) {
+ Map<String, String> m = new java.util.LinkedHashMap<>();
+ if (!self.equals("Dismiss")) m.put("Dismiss", c.dismissKey);
+ if (!self.equals("Snooze")) m.put("Snooze", c.snoozeKey);
+ if (c.fullscreen && !self.equals("Full screen")) m.put("Full screen", c.fullscreenKey);
+ return m;
+ }
+
+ private interface Change {
+ void apply(GlanceConfig current);
+ }
+
+ private void save(Change change) {
+ GlanceConfig c = store.load();
+ if (c == null) return;
+ View focused = getCurrentFocus();
+ int index = focused == null ? -1 : rows.indexOfChild(focused);
+ change.apply(c);
+ GlanceService.settingsChanged(this);
+ // Removing the old rows would hand focus to the menu on the left, which reads as backing out of the
+ // section; keep the menu out of reach while the rows are rebuilt, then put focus back on the same row.
+ menu.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
+ buildRows(index);
+ menu.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
+ if (index >= 0 && index < rows.getChildCount()) {
+ View again = rows.getChildAt(index);
+ again.requestFocus();
+ rows.post(again::requestFocus);
+ }
+ }
+
+ /** A thin line between a section's switch or action and the list of rows it governs. */
+ private void divider() {
+ View line = new View(this);
+ line.setBackgroundColor(0x22FFFFFF);
+ LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, px(1));
+ lp.setMargins(px(16), px(8), px(16), px(8));
+ rows.addView(line, lp);
+ }
+
+ /** A status line in Overview: not focusable, refreshed every two seconds by updateLive. */
+ private SettingRow info(String name, String value) {
+ SettingRow r = new SettingRow(this, name, "", value, null);
+ rows.addView(r, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
+ return r;
+ }
+
+ private SettingRow row(String name, String description, String value, Runnable onClick) {
+ SettingRow r = new SettingRow(this, name, description, value, onClick);
+ rows.addView(r, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
+ return r;
+ }
+
+ private void updateLive() {
+ status.setText(GlanceService.statusLine());
+ if (mqttRow != null) {
+ GlanceService.Overview o = GlanceService.overview();
+ mqttRow.setDetail(o.mqttHost);
+ mqttRow.setValue(!o.running ? "Not running" : o.mqttUp ? "Connected " + ago(o.mqttSince)
+ : "Not connected" + (o.mqttError.isEmpty() ? "" : ": " + o.mqttError));
+ frigateRow.setDetail(o.frigateHost + (o.cameras > 0 ? " · " + o.cameras + " cameras" : ""));
+ frigateRow.setValue(!o.running ? "Not running" : o.frigateUp ? "Reachable"
+ : "Not reached" + (o.frigateError.isEmpty() ? "" : ": " + o.frigateError));
+ messagesRow.setDetail("An alert or a tracked object. Quiet is normal while nothing moves.");
+ messagesRow.setValue(o.lastMessageAt == 0 ? "None yet" : ago(o.lastMessageAt));
+ lastCardRow.setDetail(OverlayCard.lastTitle);
+ lastCardRow.setValue(OverlayCard.lastShownAt == 0 ? "None yet" : ago(OverlayCard.lastShownAt));
+ boolean overlay = android.provider.Settings.canDrawOverlays(this);
+ tvRow.setDetail("Version " + version() + " · display over other apps " + (overlay ? "allowed" : "NOT allowed")
+ + " · remote buttons " + (KeyService.isRunning() ? "on" : "off (run install.sh)"));
+ tvRow.setValue(overlay && KeyService.isRunning() ? "Ready" : "Needs install.sh");
+ }
+ long until = GlanceService.snoozedUntilWallClock();
+ String snoozedText = until > 0 ? "Snoozed until " + DateFormat.getTimeFormat(this).format(new Date(until)) : null;
+ if (snoozedText != null) {
+ // Seen from every section: the status line under the title says it too.
+ SpannableStringBuilder line = new SpannableStringBuilder(GlanceService.statusLine() + " · ");
+ int from = line.length();
+ line.append(snoozedText);
+ line.setSpan(new ForegroundColorSpan(SNOOZED), from, line.length(), 0);
+ status.setText(line);
+ }
+ if (snoozeRow != null) {
+ GlanceConfig c = store.load();
+ int minutes = c == null ? 60 : c.snoozeMinutes;
+ if (snoozedText != null) {
+ snoozeRow.setValue(snoozedText, SNOOZED);
+ snoozeRow.setDetail("Cards are paused. OK resumes them.");
+ } else {
+ snoozeRow.setValue("Cards on", CARDS_ON);
+ snoozeRow.setDetail("OK snoozes cards from every camera for " + CardText.duration(minutes) + ".");
+ }
+ }
+ // The camera and object lists appear once Frigate's config has been read.
+ if (waitingForFrigate && GlanceService.frigateConfig() != null) {
+ View focused = getCurrentFocus();
+ buildRows(focused == null ? -1 : rows.indexOfChild(focused));
+ }
+ }
+
+ /** "12 s ago", "5 min ago", or the time of day for anything older than an hour. */
+ private String ago(long when) {
+ if (when == 0) return "";
+ long s = (System.currentTimeMillis() - when) / 1000;
+ if (s < 60) return Math.max(0, s) + " s ago";
+ if (s < 3600) return (s / 60) + " min ago";
+ return "at " + DateFormat.getTimeFormat(this).format(new Date(when));
+ }
+
+ private String version() {
+ try {
+ return getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
+ } catch (android.content.pm.PackageManager.NameNotFoundException e) {
+ return "?";
+ }
+ }
+
+ private int px(int dp) {
+ return Math.round(dp * getResources().getDisplayMetrics().density);
+ }
+
+ private static String onOff(boolean on) {
+ return on ? "On" : "Off";
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/SettingsModel.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/SettingsModel.java
new file mode 100644
index 000000000..5da1c11ae
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/SettingsModel.java
@@ -0,0 +1,110 @@
+package io.github.nickld.frigateglance;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/** The settings screen's choices, as values the config understands. No Android here, so it is unit-tested. */
+final class SettingsModel {
+ static final List<String> CORNERS = List.of("top-right", "top-left", "bottom-left", "bottom-right");
+ static final List<String> SEVERITIES = List.of("alerts", "alerts_and_detections");
+ static final List<Integer> DISMISS_SECONDS = List.of(4, 8, 15, 30);
+ static final List<Integer> SNOOZE_MINUTES = List.of(15, 30, 60, 120, 240);
+ static final List<Integer> CARD_SCALES = List.of(70, 85, 100, 115, 130, 150);
+
+ private SettingsModel() {}
+
+ static List<String> cameraNames(JSONObject frigate) {
+ List<String> out = new ArrayList<>();
+ JSONObject cams = frigate == null ? null : frigate.optJSONObject("cameras");
+ if (cams != null) {
+ for (Iterator<String> it = cams.keys(); it.hasNext(); ) {
+ String name = it.next();
+ // A debug replay counts as the camera it replays, so it gets no switch of its own.
+ if (!name.startsWith(ReviewFilter.REPLAY_PREFIX)) out.add(name);
+ }
+ }
+ Collections.sort(out);
+ return out;
+ }
+
+ /** Every label a camera alerts on or tracks. */
+ static List<String> labelNames(JSONObject frigate) {
+ Set<String> out = new TreeSet<>();
+ JSONObject cams = frigate == null ? null : frigate.optJSONObject("cameras");
+ if (cams == null) return new ArrayList<>(out);
+ for (Iterator<String> it = cams.keys(); it.hasNext(); ) {
+ JSONObject cam = cams.optJSONObject(it.next());
+ if (cam == null) continue;
+ JSONObject review = cam.optJSONObject("review");
+ JSONObject alerts = review == null ? null : review.optJSONObject("alerts");
+ out.addAll(Json.strings(alerts == null ? null : alerts.optJSONArray("labels")));
+ JSONObject objects = cam.optJSONObject("objects");
+ out.addAll(Json.strings(objects == null ? null : objects.optJSONArray("track")));
+ }
+ return new ArrayList<>(out);
+ }
+
+ static boolean cameraOn(GlanceConfig c, String camera) {
+ return ReviewFilter.cameraOn(c, camera);
+ }
+
+ static boolean labelOn(GlanceConfig c, String label) {
+ return c.labels.isEmpty() || c.labels.contains(label);
+ }
+
+ /**
+ * The settings to save after switching one camera: "camerasOff", and "cameras" when a camera outside that list
+ * is switched on. Empty when nothing changes (the last camera on cannot be switched off).
+ */
+ static JSONObject toggleCamera(GlanceConfig c, List<String> all, String camera) throws JSONException {
+ JSONObject changes = new JSONObject();
+ Set<String> off = new TreeSet<>(c.camerasOff);
+ if (cameraOn(c, camera)) {
+ int on = 0;
+ for (String name : all) if (cameraOn(c, name)) on++;
+ if (on <= 1) return changes;
+ off.add(camera);
+ } else {
+ off.remove(camera);
+ if (!c.newCameras && !c.cameras.isEmpty() && !c.cameras.containsKey(camera)) {
+ JSONObject cams = new JSONObject();
+ for (Map.Entry<String, String> e : c.cameras.entrySet()) cams.put(e.getKey(), e.getValue());
+ cams.put(camera, displayName(c, camera));
+ changes.put("cameras", cams);
+ }
+ }
+ changes.put("camerasOff", new JSONArray(off));
+ return changes;
+ }
+
+ /** The "labels" value after switching one label; empty means every label. */
+ static JSONArray toggleLabel(GlanceConfig c, List<String> all, String label) {
+ List<String> on = new ArrayList<>();
+ for (String name : all) {
+ boolean isOn = labelOn(c, name);
+ if (name.equals(label)) isOn = !isOn;
+ if (isOn) on.add(name);
+ }
+ return new JSONArray(on.isEmpty() || on.size() == all.size() ? Collections.emptyList() : on);
+ }
+
+ static <T> T next(List<T> values, T current) {
+ int i = values.indexOf(current);
+ return values.get((i + 1) % values.size());
+ }
+
+
+ private static String displayName(GlanceConfig c, String camera) {
+ String n = c.cameras.get(camera);
+ return n != null && !n.isEmpty() ? n : CardController.pretty(camera);
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/TestCardReceiver.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/TestCardReceiver.java
new file mode 100644
index 000000000..34957aa1f
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/TestCardReceiver.java
@@ -0,0 +1,17 @@
+package io.github.nickld.frigateglance;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+
+/**
+ * Shows a test card from ADB without bringing this app to the front, so a card can be checked over
+ * whatever is playing: am broadcast -n io.github.nickld.frigateglance/.TestCardReceiver [--es camera NAME].
+ * Only the shell can send it (WRITE_SECURE_SETTINGS, as the launcher's ThemeProvider).
+ */
+public class TestCardReceiver extends BroadcastReceiver {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ GlanceService.showTestCard(context, intent.getStringExtra("camera"));
+ }
+}
diff --git a/addons/frigate-glance/app/src/main/res/drawable/banner.xml b/addons/frigate-glance/app/src/main/res/drawable/banner.xml
new file mode 100644
index 000000000..faa9483f2
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/res/drawable/banner.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 16:9 banner: a dark screen with a small card in its top-right corner. Own art. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="320dp" android:height="180dp"
+ android:viewportWidth="320" android:viewportHeight="180">
+ <path android:fillColor="#101418" android:pathData="M0,0h320v180h-320z" />
+ <path android:fillColor="#1E2630" android:pathData="M24,24h272v132h-272z" />
+ <path android:fillColor="#3DDC84" android:pathData="M196,36h88a6,6 0 0 1 6,6v50a6,6 0 0 1 -6,6h-88a6,6 0 0 1 -6,-6v-50a6,6 0 0 1 6,-6z" />
+ <path android:fillColor="#101418" android:pathData="M202,42h76v40h-76z" />
+ <path android:strokeColor="#3DDC84" android:strokeWidth="2" android:fillColor="#00000000" android:pathData="M226,50h24v26h-24z" />
+</vector>
diff --git a/addons/frigate-glance/app/src/main/res/drawable/card_glass.xml b/addons/frigate-glance/app/src/main/res/drawable/card_glass.xml
new file mode 100644
index 000000000..3ca405b4d
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/res/drawable/card_glass.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Frosted-glass card: dark translucent fill with a faint light edge, as the launcher's pills. -->
+<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
+ <solid android:color="#E6161B22" />
+ <stroke android:width="1dp" android:color="#33FFFFFF" />
+ <corners android:radius="14dp" />
+</shape>
diff --git a/addons/frigate-glance/app/src/main/res/drawable/ic_foreground.xml b/addons/frigate-glance/app/src/main/res/drawable/ic_foreground.xml
new file mode 100644
index 000000000..75c866623
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/res/drawable/ic_foreground.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp" android:height="108dp"
+ android:viewportWidth="108" android:viewportHeight="108">
+ <path android:fillColor="#3DDC84" android:pathData="M58,30h18a4,4 0 0 1 4,4v14a4,4 0 0 1 -4,4h-18a4,4 0 0 1 -4,-4v-14a4,4 0 0 1 4,-4z" />
+ <path android:strokeColor="#FFFFFF" android:strokeWidth="3" android:fillColor="#00000000" android:pathData="M30,40h48v38h-48z" />
+</vector>
diff --git a/addons/frigate-glance/app/src/main/res/drawable/ic_frames.xml b/addons/frigate-glance/app/src/main/res/drawable/ic_frames.xml
new file mode 100644
index 000000000..269c3f02c
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/res/drawable/ic_frames.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Stacked frames: snapshots refreshing, not live video. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp"
+ android:viewportWidth="24" android:viewportHeight="24">
+ <path android:fillColor="#00000000" android:strokeColor="#99FFFFFF" android:strokeWidth="1.6"
+ android:pathData="M8,3h11a2,2 0 0 1 2,2v8" />
+ <path android:fillColor="#00000000" android:strokeColor="#CCFFFFFF" android:strokeWidth="1.6"
+ android:pathData="M5,6h11a2,2 0 0 1 2,2v8" />
+ <path android:fillColor="#FFFFFFFF"
+ android:pathData="M4,9h10a2,2 0 0 1 2,2v7a2,2 0 0 1 -2,2h-10a2,2 0 0 1 -2,-2v-7a2,2 0 0 1 2,-2z" />
+</vector>
diff --git a/addons/frigate-glance/app/src/main/res/drawable/ic_live.xml b/addons/frigate-glance/app/src/main/res/drawable/ic_live.xml
new file mode 100644
index 000000000..4f26623ac
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/res/drawable/ic_live.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Video camera: live video is playing. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp"
+ android:viewportWidth="24" android:viewportHeight="24">
+ <path android:fillColor="#FFFFFFFF"
+ android:pathData="M4,6h10a2,2 0 0 1 2,2v8a2,2 0 0 1 -2,2h-10a2,2 0 0 1 -2,-2v-8a2,2 0 0 1 2,-2z" />
+ <path android:fillColor="#FFFFFFFF" android:pathData="M17,10.5l5,-3v9l-5,-3z" />
+</vector>
diff --git a/addons/frigate-glance/app/src/main/res/drawable/picture_frame.xml b/addons/frigate-glance/app/src/main/res/drawable/picture_frame.xml
new file mode 100644
index 000000000..e6cb489cf
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/res/drawable/picture_frame.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
+ <solid android:color="#FF22272E" />
+ <corners android:radius="9dp" />
+</shape>
diff --git a/addons/frigate-glance/app/src/main/res/drawable/row_background.xml b/addons/frigate-glance/app/src/main/res/drawable/row_background.xml
new file mode 100644
index 000000000..913cb23f5
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/res/drawable/row_background.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- A settings row: transparent until focused, then the launcher's glass highlight. -->
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+ <item android:state_focused="true">
+ <shape android:shape="rectangle">
+ <solid android:color="#33FFFFFF" />
+ <stroke android:width="1dp" android:color="#55FFFFFF" />
+ <corners android:radius="12dp" />
+ </shape>
+ </item>
+ <!-- The menu's current section while focus is on its rows. -->
+ <item android:state_activated="true">
+ <shape android:shape="rectangle">
+ <solid android:color="#1AFFFFFF" />
+ <corners android:radius="12dp" />
+ </shape>
+ </item>
+ <item>
+ <shape android:shape="rectangle">
+ <solid android:color="#00000000" />
+ <corners android:radius="12dp" />
+ </shape>
+ </item>
+</selector>
diff --git a/addons/frigate-glance/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/addons/frigate-glance/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 000000000..0a99b20b1
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@android:color/black" />
+ <foreground android:drawable="@drawable/ic_foreground" />
+</adaptive-icon>
diff --git a/addons/frigate-glance/app/src/main/res/values/strings.xml b/addons/frigate-glance/app/src/main/res/values/strings.xml
new file mode 100644
index 000000000..bd32f1e4a
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/res/values/strings.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Frigate Glance</string>
+ <string name="key_service_description">Lets two remote buttons dismiss or snooze a camera card while one is on screen. No other key is read, and none at all while no card shows.</string>
+</resources>
diff --git a/addons/frigate-glance/app/src/main/res/xml/key_service.xml b/addons/frigate-glance/app/src/main/res/xml/key_service.xml
new file mode 100644
index 000000000..4430f7426
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/res/xml/key_service.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Keys only, and KeyService switches filtering on only while a card shows. -->
+<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
+ android:accessibilityFeedbackType="feedbackGeneric"
+ android:accessibilityFlags="flagRequestFilterKeyEvents"
+ android:canRequestFilterKeyEvents="true"
+ android:description="@string/key_service_description" />
diff --git a/addons/frigate-glance/app/src/main/res/xml/module_card.xml b/addons/frigate-glance/app/src/main/res/xml/module_card.xml
new file mode 100644
index 000000000..f4d76d781
--- /dev/null
+++ b/addons/frigate-glance/app/src/main/res/xml/module_card.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="utf-8"?>
+<card spec="1" label="Frigate Glance" caption="Camera pop-ups" accent="#3DDC84" />
diff --git a/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/CardControllerTest.java b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/CardControllerTest.java
new file mode 100644
index 000000000..79af401b9
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/CardControllerTest.java
@@ -0,0 +1,312 @@
+package io.github.nickld.frigateglance;
+
+import static io.github.nickld.frigateglance.Fixtures.reviewJson;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class CardControllerTest {
+ private static final float[] BOX = {0f, 0f, 0.5f, 0.5f};
+
+ /** Records what the controller asks the card to do. */
+ static final class FakeView implements CardView {
+ final List<String> calls = new ArrayList<>();
+ CardModel lastModel;
+
+ @Override public void show(CardModel m) { calls.add("show:" + m.reviewId); lastModel = m; }
+ @Override public void update(CardModel m) { calls.add("update:" + m.reviewId); lastModel = m; }
+ @Override public void hide() { calls.add("hide"); }
+
+ String last() { return calls.get(calls.size() - 1); }
+ }
+
+ private FakeView view;
+ private long now;
+ private CardController c;
+
+ @Before
+ public void setUp() {
+ view = new FakeView();
+ now = 1_000_000L;
+ GlanceConfig config = GlanceConfig.parse("{\"mqtt\":\"mqtt://h:1883\",\"frigateUrl\":\"https://h:8971\"}");
+ c = new CardController(view, new ReviewFilter(config), Map.of("frontdoooor", "Front door"), 8, () -> now);
+ }
+
+ private static Review rev(String type, String id, String camera, String severity) {
+ return Review.parse(reviewJson(type, id, camera, severity, "person"));
+ }
+
+ private static Review revWithDetection(String id, String eventId) {
+ String after = "{\"id\":\"" + id + "\",\"camera\":\"frontdoooor\",\"severity\":\"alert\",\"data\":{\"detections\":[\""
+ + eventId + "\"],\"objects\":[\"person\"],\"zones\":[\"entire_front_yard\"]}}";
+ return Review.parse("{\"type\":\"new\",\"after\":" + after + "}");
+ }
+
+ private static Detection det(String eventId, float[] box) {
+ String b = box == null ? "null" : "[" + (box[0] * 100) + "," + (box[1] * 100) + "," + (box[2] * 100) + "," + (box[3] * 100) + "]";
+ return Detection.parse("{\"type\":\"update\",\"after\":{\"id\":\"" + eventId + "\",\"camera\":\"frontdoooor\",\"label\":\"person\","
+ + "\"sub_label\":[\"Nick\",0.9],\"score\":0.9,\"box\":" + b + "}}", Map.of("frontdoooor", new int[] {100, 100}));
+ }
+
+ @Test
+ public void newAlertShowsCard() {
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ assertEquals(List.of("show:r1"), view.calls);
+ assertTrue(c.isShowing());
+ }
+
+ @Test
+ public void filteredReviewShowsNothing() {
+ c.onReview(rev("new", "r1", "driveway", "detection"));
+ assertTrue(view.calls.isEmpty());
+ }
+
+ @Test
+ public void secondReviewReplacesFirst() {
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ c.onReview(rev("new", "r2", "driveway", "alert"));
+ assertEquals("show:r2", view.last());
+ assertTrue(c.isShowing());
+ }
+
+ @Test
+ public void updateForShownCardRefreshesIt() {
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ c.onReview(rev("update", "r1", "frontdoooor", "alert"));
+ assertEquals("update:r1", view.last());
+ }
+
+ @Test
+ public void updateForOtherReviewIsIgnored() {
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ c.onReview(rev("update", "r9", "frontdoooor", "alert"));
+ assertEquals(List.of("show:r1"), view.calls);
+ }
+
+ @Test
+ public void endHidesAfterDismissSeconds() {
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ c.onReview(rev("end", "r1", "frontdoooor", "alert"));
+ now += 7_999;
+ c.tick();
+ assertTrue(c.isShowing());
+ now += 2;
+ c.tick();
+ assertFalse(c.isShowing());
+ assertEquals("hide", view.last());
+ }
+
+ @Test
+ public void missingEndHidesAfter120s() {
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ now += 119_999;
+ c.tick();
+ assertTrue(c.isShowing());
+ now += 2;
+ c.tick();
+ assertFalse(c.isShowing());
+ }
+
+ @Test
+ public void updateExtendsTheHardDeadline() {
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ now += 100_000;
+ c.onReview(rev("update", "r1", "frontdoooor", "alert"));
+ now += 100_000;
+ c.tick();
+ assertTrue(c.isShowing());
+ }
+
+ @Test
+ public void detectionAddsBoxAndNameToShownCard() {
+ c.onReview(revWithDetection("r1", "ev1"));
+ c.onDetection(det("ev1", BOX));
+ assertEquals(1, view.lastModel.boxes.size());
+ assertEquals("Person · Nick · Entire Front Yard", view.lastModel.detail);
+ }
+
+ @Test
+ public void detectionForOtherReviewIgnored() {
+ c.onReview(revWithDetection("r1", "ev1"));
+ c.onDetection(det("ev9", BOX));
+ assertEquals(0, view.lastModel.boxes.size());
+ }
+
+ @Test
+ public void detectionWithoutBoxStillUpdatesName() {
+ c.onReview(revWithDetection("r1", "ev1"));
+ c.onDetection(det("ev1", null));
+ assertEquals(0, view.lastModel.boxes.size());
+ assertEquals("Person · Nick · Entire Front Yard", view.lastModel.detail);
+ }
+
+ @Test
+ public void dismissHides() {
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ c.dismiss();
+ assertFalse(c.isShowing());
+ assertEquals("hide", view.last());
+ }
+
+ @Test
+ public void snoozeHidesAndBlocksNewCards() {
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ c.snooze(60);
+ assertFalse(c.isShowing());
+ assertEquals(now + 60 * 60_000L, c.snoozedUntil());
+ c.onReview(rev("new", "r2", "frontdoooor", "alert"));
+ assertFalse(c.isShowing());
+ now += 60 * 60_000L;
+ c.onReview(rev("new", "r3", "frontdoooor", "alert"));
+ assertTrue(c.isShowing());
+ }
+
+ @Test
+ public void resumeEndsSnooze() {
+ c.snooze(60);
+ c.resume();
+ assertEquals(0, c.snoozedUntil());
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ assertTrue(c.isShowing());
+ }
+
+ @Test
+ public void frigateOfflineHidesCard() {
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ c.onAvailable(false);
+ assertFalse(c.isShowing());
+ }
+
+ @Test
+ public void displayNameFromConfig() {
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ assertEquals("Front door", view.lastModel.title);
+ }
+
+ @Test
+ public void prettyNameWithoutDisplayName() {
+ c.onReview(rev("new", "r1", "front_door", "alert"));
+ assertEquals("Front Door", view.lastModel.title);
+ }
+
+ @Test
+ public void testCardShowsAndLeavesOnItsOwn() {
+ c.showTest("driveway");
+ assertEquals("show:test", view.last());
+ assertEquals("Test card", view.lastModel.detail);
+ assertEquals("driveway", view.lastModel.camera);
+ now += 18_001;
+ c.tick();
+ assertFalse(c.isShowing());
+ }
+
+ @Test
+ public void activeCardHasNoCountdown() {
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ assertEquals(0, view.lastModel.countdownMs);
+ c.onReview(rev("update", "r1", "frontdoooor", "alert"));
+ assertEquals(0, view.lastModel.countdownMs);
+ }
+
+ @Test
+ public void endStartsCountdownOfDismissSeconds() {
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ c.onReview(rev("end", "r1", "frontdoooor", "alert"));
+ assertEquals(8000, view.lastModel.countdownMs);
+ }
+
+ @Test
+ public void detectionAfterEndKeepsTheCountdownRunning() {
+ c.onReview(revWithDetection("r1", "ev1"));
+ c.onReview(Review.parse("{\"type\":\"end\",\"after\":{\"id\":\"r1\",\"camera\":\"frontdoooor\",\"severity\":\"alert\",\"data\":{\"detections\":[\"ev1\"],\"objects\":[\"person\"]}}}"));
+ now += 3000;
+ c.onDetection(det("ev1", BOX));
+ assertEquals(5000, view.lastModel.countdownMs);
+ }
+
+ @Test
+ public void testCardCountsDownItsWholeLife() {
+ c.showTest("driveway");
+ assertEquals(18_000, view.lastModel.countdownMs);
+ }
+
+ @Test
+ public void replayCardSaysReplay() {
+ c.onReview(rev("new", "r1", "_replay_frontdoooor", "alert"));
+ assertEquals("Front door (replay)", view.lastModel.title);
+ }
+
+ @Test
+ public void updateForAnAlertNeverShownOpensACard() {
+ // Connected mid-event (a reconnect, a reinstall): only updates arrive for it.
+ c.onReview(rev("update", "r1", "frontdoooor", "alert"));
+ assertEquals("show:r1", view.last());
+ }
+
+ @Test
+ public void dismissedAlertDoesNotReopenOnUpdate() {
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ c.dismiss();
+ c.onReview(rev("update", "r1", "frontdoooor", "alert"));
+ assertFalse(c.isShowing());
+ }
+
+ @Test
+ public void replacedAlertDoesNotStealTheCardBack() {
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ c.onReview(rev("new", "r2", "driveway", "alert"));
+ c.onReview(rev("update", "r1", "frontdoooor", "alert"));
+ assertEquals("show:r2", view.last());
+ }
+
+ @Test
+ public void endedAlertDoesNotReopen() {
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ c.onReview(rev("end", "r1", "frontdoooor", "alert"));
+ now += 9000;
+ c.tick();
+ c.onReview(rev("update", "r1", "frontdoooor", "alert"));
+ assertFalse(c.isShowing());
+ }
+
+ @Test
+ public void endedObjectLosesItsBox() {
+ c.onReview(revWithDetection("r1", "ev1"));
+ c.onDetection(det("ev1", BOX));
+ assertEquals(1, view.lastModel.boxes.size());
+ c.onDetection(Detection.parse("{\"type\":\"end\",\"after\":{\"id\":\"ev1\",\"camera\":\"frontdoooor\",\"label\":\"person\",\"box\":[0,0,50,50]}}",
+ Map.of("frontdoooor", new int[] {100, 100})));
+ assertEquals(0, view.lastModel.boxes.size());
+ }
+
+ @Test
+ public void replayCardLeavesSoonAfterTheReplayGoesQuiet() {
+ // Stopping a replay removes its camera with no "end": the card must not wait the full 120 s.
+ c.onReview(Review.fromReplayEvent("{\"type\":\"new\",\"after\":{\"id\":\"e1\",\"camera\":\"_replay_shop\",\"label\":\"person\"}}"));
+ assertTrue(c.isShowing());
+ now += 10_000;
+ c.onReview(Review.fromReplayEvent("{\"type\":\"update\",\"after\":{\"id\":\"e1\",\"camera\":\"_replay_shop\",\"label\":\"person\"}}"));
+ now += 14_999;
+ c.tick();
+ assertTrue(c.isShowing());
+ now += 2;
+ c.tick();
+ assertFalse(c.isShowing());
+ }
+
+ @Test
+ public void shownCameraIsKnownForFullScreen() {
+ assertEquals(null, c.shownCamera());
+ c.onReview(rev("new", "r1", "frontdoooor", "alert"));
+ assertEquals("frontdoooor", c.shownCamera());
+ c.dismiss();
+ assertEquals(null, c.shownCamera());
+ }
+}
diff --git a/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/CardTextTest.java b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/CardTextTest.java
new file mode 100644
index 000000000..378c88fa1
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/CardTextTest.java
@@ -0,0 +1,58 @@
+package io.github.nickld.frigateglance;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class CardTextTest {
+ @Test
+ public void defaultFooter() {
+ assertEquals("◀ Dismiss · ▶ Snooze 1h", CardText.footer("KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_RIGHT", 60));
+ }
+
+ @Test
+ public void namedKeysAndMinutes() {
+ assertEquals("Menu Dismiss · Info Snooze 30 min", CardText.footer("KEYCODE_MENU", "KEYCODE_INFO", 30));
+ }
+
+ @Test
+ public void colourKeysAndHours() {
+ assertEquals("Red Dismiss · Green Snooze 4h", CardText.footer("KEYCODE_PROG_RED", "KEYCODE_PROG_GREEN", 240));
+ }
+
+ @Test
+ public void unusualKeyNameIsReadable() {
+ assertEquals("Media Play Pause Dismiss · ▼ Snooze 90 min",
+ CardText.footer("KEYCODE_MEDIA_PLAY_PAUSE", "KEYCODE_DPAD_DOWN", 90));
+ }
+
+ @Test
+ public void snoozeLength() {
+ assertEquals("15 min", CardText.duration(15));
+ assertEquals("1h", CardText.duration(60));
+ assertEquals("2h", CardText.duration(120));
+ assertEquals("90 min", CardText.duration(90));
+ }
+
+ @Test
+ public void footerNamesTheFullscreenKeyWhenOn() {
+ assertEquals("◀ Dismiss · ▶ Snooze 1h · ▲ Full screen",
+ CardText.footer("KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_RIGHT", 60, "KEYCODE_DPAD_UP"));
+ assertEquals("◀ Dismiss · ▶ Snooze 1h", CardText.footer("KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_RIGHT", 60, null));
+ }
+
+ @Test
+ public void holdKeysNeedNoWordForItTheCardDrawsAPill() {
+ assertEquals("◀ Dismiss · ▶ Snooze 1h · ▲ Full screen",
+ CardText.footer("KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_RIGHT", 60, "KEYCODE_DPAD_UP"));
+ }
+
+
+ @Test
+ public void footerPartsAreOnePerAction() {
+ java.util.Map<Integer, String> p = CardText.parts("KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_RIGHT", 60, "KEYCODE_DPAD_UP");
+ assertEquals(java.util.List.of(KeyRules.DISMISS, KeyRules.SNOOZE, KeyRules.FULLSCREEN), new java.util.ArrayList<>(p.keySet()));
+ assertEquals("▶ Snooze 1h", p.get(KeyRules.SNOOZE));
+ assertEquals(2, CardText.parts("KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_RIGHT", 60, null).size());
+ }
+}
diff --git a/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/Fixtures.java b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/Fixtures.java
new file mode 100644
index 000000000..87c63e579
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/Fixtures.java
@@ -0,0 +1,27 @@
+package io.github.nickld.frigateglance;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+
+final class Fixtures {
+ private Fixtures() {}
+
+ static String fixture(String name) {
+ try (InputStream in = Fixtures.class.getClassLoader().getResourceAsStream(name)) {
+ if (in == null) throw new IllegalArgumentException("no fixture " + name);
+ return new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ /** A review payload as Frigate publishes it on frigate/reviews. */
+ static String reviewJson(String type, String id, String camera, String severity, String... objects) {
+ StringBuilder objs = new StringBuilder();
+ for (String o : objects) objs.append(objs.length() == 0 ? "" : ",").append('"').append(o).append('"');
+ String after = "{\"id\":\"" + id + "\",\"camera\":\"" + camera + "\",\"severity\":\"" + severity
+ + "\",\"data\":{\"detections\":[],\"objects\":[" + objs + "],\"zones\":[]}}";
+ return "{\"type\":\"" + type + "\",\"before\":" + after + ",\"after\":" + after + "}";
+ }
+}
diff --git a/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/FrigateApiTest.java b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/FrigateApiTest.java
new file mode 100644
index 000000000..ce9271dca
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/FrigateApiTest.java
@@ -0,0 +1,117 @@
+package io.github.nickld.frigateglance;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.json.JSONObject;
+import org.junit.After;
+import org.junit.Test;
+
+public class FrigateApiTest {
+ private static final String CONFIG = "{\"cameras\":{"
+ + "\"driveway\":{\"detect\":{\"width\":1280,\"height\":720},\"live\":{\"streams\":{\"Main\":\"driveway_1\"}}},"
+ + "\"shop\":{\"detect\":{\"width\":640,\"height\":480}}}}";
+
+ private TinyHttp server;
+
+ @After
+ public void stop() throws IOException {
+ if (server != null) server.close();
+ }
+
+ private static TinyHttp.Response loginOk(String token) {
+ TinyHttp.Response r = new TinyHttp.Response(200, "{}");
+ r.headers.put("Set-Cookie", "frigate_token=" + token + "; Path=/");
+ return r;
+ }
+
+ @Test
+ public void tokenFromSetCookie() {
+ assertEquals("abc.def",
+ FrigateApi.tokenFromSetCookie(List.of("other=1", "frigate_token=abc.def; Path=/; HttpOnly")));
+ assertNull(FrigateApi.tokenFromSetCookie(List.of("other=1")));
+ }
+
+ @Test
+ public void detectSizesFromConfig() throws Exception {
+ assertArrayEquals(new int[] {1280, 720}, FrigateApi.detectSizes(new JSONObject(CONFIG)).get("driveway"));
+ assertArrayEquals(new int[] {640, 480}, FrigateApi.detectSizes(new JSONObject(CONFIG)).get("shop"));
+ }
+
+ @Test
+ public void liveStreamFromConfigOrCameraName() throws Exception {
+ assertEquals("driveway_1", FrigateApi.liveStreams(new JSONObject(CONFIG)).get("driveway"));
+ assertEquals("shop", FrigateApi.liveStreams(new JSONObject(CONFIG)).get("shop"));
+ }
+
+ @Test
+ public void reLoginOnceOn401() throws Exception {
+ AtomicInteger logins = new AtomicInteger();
+ AtomicInteger configCalls = new AtomicInteger();
+ server = new TinyHttp()
+ .on("/api/login", r -> loginOk("t" + logins.incrementAndGet()))
+ .on("/api/config", r -> {
+ configCalls.incrementAndGet();
+ // The first token counts as expired: Frigate answers 401 until the second login.
+ String cookie = r.headers.get("cookie");
+ return cookie != null && cookie.contains("frigate_token=t2")
+ ? new TinyHttp.Response(200, CONFIG) : new TinyHttp.Response(401, "");
+ })
+ .start();
+ FrigateApi api = new FrigateApi(server.url(), "viewer", "pw", "", pin -> {});
+ assertTrue(api.config().has("cameras"));
+ assertEquals(2, logins.get());
+ assertEquals(2, configCalls.get());
+ }
+
+ @Test
+ public void givesUpAfterSecond401() throws Exception {
+ AtomicInteger logins = new AtomicInteger();
+ server = new TinyHttp()
+ .on("/api/login", r -> loginOk("x" + logins.incrementAndGet()))
+ .on("/api/config", r -> new TinyHttp.Response(401, ""))
+ .start();
+ FrigateApi api = new FrigateApi(server.url(), "viewer", "pw", "", pin -> {});
+ try {
+ api.config();
+ fail("expected IOException");
+ } catch (IOException e) {
+ assertTrue(e.getMessage(), e.getMessage().contains("401"));
+ }
+ assertEquals(2, logins.get());
+ }
+
+ @Test
+ public void badPasswordIsNamed() throws Exception {
+ server = new TinyHttp().on("/api/login", r -> new TinyHttp.Response(401, "")).start();
+ FrigateApi api = new FrigateApi(server.url(), "viewer", "bad", "", pin -> {});
+ try {
+ api.config();
+ fail("expected IOException");
+ } catch (IOException e) {
+ assertTrue(e.getMessage(), e.getMessage().contains("username or password"));
+ }
+ }
+
+ @Test
+ public void noLoginWithoutUser() throws Exception {
+ AtomicInteger logins = new AtomicInteger();
+ String[] query = new String[1];
+ server = new TinyHttp()
+ .on("/api/login", r -> { logins.incrementAndGet(); return new TinyHttp.Response(200, "{}"); })
+ .on("/api/frontdoooor/latest.jpg", r -> { query[0] = r.query; return new TinyHttp.Response(200, "JPEG"); })
+ .start();
+ FrigateApi api = new FrigateApi(server.url(), "", "", "", pin -> {});
+ assertEquals("JPEG", new String(api.latestJpeg("frontdoooor", 360), StandardCharsets.UTF_8));
+ assertEquals("h=360", query[0]);
+ assertEquals(0, logins.get());
+ }
+}
diff --git a/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/GlanceConfigTest.java b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/GlanceConfigTest.java
new file mode 100644
index 000000000..8839b66b6
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/GlanceConfigTest.java
@@ -0,0 +1,204 @@
+package io.github.nickld.frigateglance;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.json.JSONObject;
+import org.junit.Test;
+
+public class GlanceConfigTest {
+ private static final String REQUIRED =
+ "\"mqtt\":\"mqtt://u:[email protected]:1883\",\"frigateUrl\":\"https://192.168.1.11:8971\"";
+ private static final String FULL = "{" + REQUIRED
+ + ",\"frigateUser\":\"viewer\",\"frigatePassword\":\"pw\",\"topicPrefix\":\"frigate\""
+ + ",\"rtspUser\":\"r\",\"rtspPassword\":\"rp\",\"cameras\":{\"frontdoooor\":\"Front door\"}"
+ + ",\"labels\":[\"person\"],\"severity\":\"alerts_and_detections\",\"corner\":\"top-left\""
+ + ",\"dismissSeconds\":15,\"snoozeMinutes\":30,\"liveVideo\":false,\"boxes\":false"
+ + ",\"dismissKey\":\"KEYCODE_MENU\",\"snoozeKey\":\"KEYCODE_INFO\"}";
+
+ private static String requiredPlus(String extra) {
+ return "{" + REQUIRED + "," + extra + "}";
+ }
+
+ @Test
+ public void defaultsApplyWhenOnlyRequiredKeysGiven() {
+ GlanceConfig c = GlanceConfig.parse("{" + REQUIRED + "}");
+ assertEquals("frigate", c.topicPrefix);
+ assertEquals("alerts", c.severity);
+ assertEquals("top-right", c.corner);
+ assertEquals(8, c.dismissSeconds);
+ assertEquals(60, c.snoozeMinutes);
+ assertTrue(c.liveVideo);
+ assertTrue(c.boxes);
+ assertTrue(c.cameras.isEmpty());
+ assertTrue(c.labels.isEmpty());
+ assertEquals("KEYCODE_DPAD_LEFT", c.dismissKey);
+ assertEquals("KEYCODE_DPAD_RIGHT", c.snoozeKey);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void missingMqttIsRejected() {
+ GlanceConfig.parse("{\"frigateUrl\":\"https://h:8971\"}");
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void missingFrigateUrlIsRejected() {
+ GlanceConfig.parse("{\"mqtt\":\"mqtt://h:1883\"}");
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void invalidJsonIsRejected() {
+ GlanceConfig.parse("not json");
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void backAsDismissKeyIsRejected() {
+ GlanceConfig.parse(requiredPlus("\"dismissKey\":\"KEYCODE_BACK\""));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void okAsSnoozeKeyIsRejected() {
+ GlanceConfig.parse(requiredPlus("\"snoozeKey\":\"KEYCODE_DPAD_CENTER\""));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void enterAsSnoozeKeyIsRejected() {
+ GlanceConfig.parse(requiredPlus("\"snoozeKey\":\"KEYCODE_ENTER\""));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void sameKeyTwiceIsRejected() {
+ GlanceConfig.parse(requiredPlus("\"dismissKey\":\"KEYCODE_MENU\",\"snoozeKey\":\"KEYCODE_MENU\""));
+ }
+
+ @Test
+ public void outOfRangeNumbersAreClamped() {
+ GlanceConfig c = GlanceConfig.parse(requiredPlus("\"dismissSeconds\":999,\"snoozeMinutes\":1"));
+ assertEquals(120, c.dismissSeconds);
+ assertEquals(5, c.snoozeMinutes);
+ }
+
+ @Test
+ public void unknownCornerFallsBackToTopRight() {
+ assertEquals("top-right", GlanceConfig.parse(requiredPlus("\"corner\":\"middle\"")).corner);
+ }
+
+ @Test
+ public void unknownSeverityFallsBackToAlerts() {
+ assertEquals("alerts", GlanceConfig.parse(requiredPlus("\"severity\":\"everything\"")).severity);
+ }
+
+ @Test
+ public void readsEveryKey() {
+ GlanceConfig c = GlanceConfig.parse(FULL);
+ assertEquals("viewer", c.frigateUser);
+ assertEquals("Front door", c.cameras.get("frontdoooor"));
+ assertTrue(c.labels.contains("person"));
+ assertEquals("alerts_and_detections", c.severity);
+ assertEquals("top-left", c.corner);
+ assertEquals(15, c.dismissSeconds);
+ assertEquals(30, c.snoozeMinutes);
+ assertFalse(c.liveVideo);
+ assertFalse(c.boxes);
+ assertEquals("KEYCODE_MENU", c.dismissKey);
+ assertEquals("rp", c.rtspPassword);
+ }
+
+ @Test
+ public void roundTripsThroughJson() {
+ GlanceConfig c = GlanceConfig.parse(FULL);
+ assertEquals(c.toJson(), GlanceConfig.parse(c.toJson()).toJson());
+ }
+
+ @Test
+ public void overridesFromSettingsWin() throws Exception {
+ GlanceConfig c = GlanceConfig.parse(FULL)
+ .withOverrides(new JSONObject("{\"liveVideo\":false,\"corner\":\"bottom-left\"}"));
+ assertFalse(c.liveVideo);
+ assertEquals("bottom-left", c.corner);
+ assertEquals("viewer", c.frigateUser);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void overridesAreValidatedToo() throws Exception {
+ GlanceConfig.parse(FULL).withOverrides(new JSONObject("{\"dismissKey\":\"KEYCODE_BACK\"}"));
+ }
+
+ @Test
+ public void streamsMapCamerasToGo2rtcStreams() {
+ GlanceConfig c = GlanceConfig.parse(requiredPlus("\"streams\":{\"frontdoooor\":\"frontdoooor_sub\"}"));
+ assertEquals("frontdoooor_sub", c.streams.get("frontdoooor"));
+ assertTrue(GlanceConfig.parse("{" + REQUIRED + "}").streams.isEmpty());
+ }
+
+ @Test
+ public void streamsSurviveRoundTrip() {
+ GlanceConfig c = GlanceConfig.parse(requiredPlus("\"streams\":{\"shop\":\"shop_sub\"}"));
+ assertEquals("shop_sub", GlanceConfig.parse(c.toJson()).streams.get("shop"));
+ }
+
+ @Test
+ public void frigateHostFromUrl() {
+ assertEquals("192.168.1.11", GlanceConfig.parse("{" + REQUIRED + "}").frigateHost());
+ }
+
+ @Test
+ public void mqttWithoutSchemeIsRejectedWithoutEchoingIt() {
+ try {
+ GlanceConfig.parse("{\"mqtt\":\"u:[email protected]:1883\",\"frigateUrl\":\"https://h:8971\"}");
+ org.junit.Assert.fail("expected IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ assertFalse(e.getMessage(), e.getMessage().contains("secretpw"));
+ }
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void mqttWithUnencodedCharactersIsRejected() {
+ GlanceConfig.parse("{\"mqtt\":\"mqtt://u:p#w%@h:1883\",\"frigateUrl\":\"https://h:8971\"}");
+ }
+
+ @Test
+ public void invalidJsonMessageDoesNotEchoTheFile() {
+ try {
+ GlanceConfig.parse("{\"frigatePassword\":\"secretpw\" oops}");
+ org.junit.Assert.fail("expected IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ assertFalse(e.getMessage(), e.getMessage().contains("secretpw"));
+ }
+ }
+
+ @Test
+ public void cardScaleDefaultsTo100AndIsClamped() {
+ assertEquals(100, GlanceConfig.parse("{" + REQUIRED + "}").cardScale);
+ assertEquals(130, GlanceConfig.parse(requiredPlus("\"cardScale\":130")).cardScale);
+ assertEquals(50, GlanceConfig.parse(requiredPlus("\"cardScale\":10")).cardScale);
+ assertEquals(200, GlanceConfig.parse(requiredPlus("\"cardScale\":900")).cardScale);
+ }
+
+ @Test
+ public void fullscreenIsOffByDefaultWithUpAsItsKey() {
+ GlanceConfig c = GlanceConfig.parse("{" + REQUIRED + "}");
+ assertFalse(c.fullscreen);
+ assertEquals("KEYCODE_DPAD_UP", c.fullscreenKey);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void fullscreenKeyMayNotRepeatAnotherCardKey() {
+ GlanceConfig.parse(requiredPlus("\"fullscreen\":true,\"fullscreenKey\":\"KEYCODE_DPAD_LEFT\""));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void fullscreenKeyMayNotBeOk() {
+ GlanceConfig.parse(requiredPlus("\"fullscreenKey\":\"KEYCODE_DPAD_CENTER\""));
+ }
+
+ @Test
+ public void holdIsOffForEveryKeyByDefault() {
+ GlanceConfig c = GlanceConfig.parse("{" + REQUIRED + "}");
+ assertFalse(c.dismissHold);
+ assertFalse(c.snoozeHold);
+ assertFalse(c.fullscreenHold);
+ assertTrue(GlanceConfig.parse(requiredPlus("\"snoozeHold\":true")).snoozeHold);
+ }
+}
diff --git a/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/HostPortTest.java b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/HostPortTest.java
new file mode 100644
index 000000000..074da6abc
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/HostPortTest.java
@@ -0,0 +1,15 @@
+package io.github.nickld.frigateglance;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class HostPortTest {
+ @Test
+ public void overviewShowsHostAndPortButNeverTheLogin() {
+ assertEquals("192.168.1.10:1883", GlanceService.hostPort("mqtt://user:[email protected]:1883", 1883));
+ assertEquals("192.168.1.10:1883", GlanceService.hostPort("mqtt://192.168.1.10", 1883));
+ assertEquals("192.168.1.11:8971", GlanceService.hostPort("https://192.168.1.11:8971", -1));
+ assertEquals("", GlanceService.hostPort("not a url at all", 1883));
+ }
+}
diff --git a/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/KeyChoiceTest.java b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/KeyChoiceTest.java
new file mode 100644
index 000000000..7a7dbdd0f
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/KeyChoiceTest.java
@@ -0,0 +1,39 @@
+package io.github.nickld.frigateglance;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class KeyChoiceTest {
+ @Test
+ public void anOrdinaryButtonIsAccepted() {
+ assertNull(KeyChoice.problem("KEYCODE_PROG_RED", "KEYCODE_DPAD_RIGHT"));
+ }
+
+ @Test
+ public void okBackAndHomeAreRefused() {
+ assertTrue(KeyChoice.problem("KEYCODE_DPAD_CENTER", "x").contains("OK"));
+ assertTrue(KeyChoice.problem("KEYCODE_ENTER", "x").contains("OK"));
+ assertTrue(KeyChoice.problem("KEYCODE_BACK", "x").contains("Back"));
+ assertTrue(KeyChoice.problem("KEYCODE_HOME", "x").contains("Home"));
+ }
+
+ @Test
+ public void theOtherCardKeyIsRefused() {
+ assertEquals("That button is already the Snooze key.", KeyChoice.problem("KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_LEFT", "Snooze"));
+ }
+
+ @Test
+ public void unknownKeysAreRefused() {
+ assertTrue(KeyChoice.problem("KEYCODE_UNKNOWN", "x").contains("can't"));
+ }
+
+ @Test
+ public void eachOtherCardKeyIsNamed() {
+ assertEquals("That button is already the Full screen key.",
+ KeyChoice.problem("KEYCODE_DPAD_UP", java.util.Map.of("Snooze", "KEYCODE_DPAD_RIGHT", "Full screen", "KEYCODE_DPAD_UP")));
+ assertNull(KeyChoice.problem("KEYCODE_MENU", java.util.Map.of("Snooze", "KEYCODE_DPAD_RIGHT")));
+ }
+}
diff --git a/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/KeyRulesTest.java b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/KeyRulesTest.java
new file mode 100644
index 000000000..bfe772d82
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/KeyRulesTest.java
@@ -0,0 +1,112 @@
+package io.github.nickld.frigateglance;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class KeyRulesTest {
+ private static final int LEFT = 21, RIGHT = 22, UP = 19, BACK = 4, DOWN = 0, UPA = 1;
+ private final KeyRules rules = new KeyRules(LEFT, RIGHT);
+
+ @Test
+ public void nothingCaughtWithoutACard() {
+ assertEquals(KeyRules.PASS, rules.decide(LEFT, DOWN, 0, false));
+ assertEquals(KeyRules.PASS, rules.decide(LEFT, UPA, 100, false));
+ }
+
+ @Test
+ public void dismissKeyIsSwallowedOnDownAndActsOnUp() {
+ assertEquals(KeyRules.SWALLOW, rules.decide(LEFT, DOWN, 0, true));
+ assertEquals(KeyRules.DISMISS, rules.decide(LEFT, UPA, 100, true));
+ }
+
+ @Test
+ public void snoozeKeyActsOnUp() {
+ assertEquals(KeyRules.SWALLOW, rules.decide(RIGHT, DOWN, 0, true));
+ assertEquals(KeyRules.SNOOZE, rules.decide(RIGHT, UPA, 100, true));
+ }
+
+ @Test
+ public void otherKeysPassWhileACardShows() {
+ assertEquals(KeyRules.PASS, rules.decide(UP, DOWN, 0, true));
+ assertEquals(KeyRules.PASS, rules.decide(BACK, UPA, 100, true));
+ }
+
+ @Test
+ public void upWithoutItsDownStillPassesAfterTheCardWent() {
+ // Down arrived while no card was up, so it went to the app; its up must follow it there.
+ assertEquals(KeyRules.PASS, rules.decide(LEFT, DOWN, 0, false));
+ assertEquals(KeyRules.PASS, rules.decide(LEFT, UPA, 100, true));
+ }
+
+ @Test
+ public void upIsStillSwallowedIfTheCardLeftAfterDown() {
+ assertEquals(KeyRules.SWALLOW, rules.decide(LEFT, DOWN, 0, true));
+ assertEquals(KeyRules.DISMISS, rules.decide(LEFT, UPA, 100, false));
+ }
+
+ @Test
+ public void unknownKeyCodesCatchNothing() {
+ KeyRules none = new KeyRules(0, 0);
+ assertEquals(KeyRules.PASS, none.decide(0, DOWN, 0, true));
+ assertEquals(KeyRules.PASS, none.decide(LEFT, DOWN, 0, true));
+ }
+
+ @Test
+ public void fullscreenKeyActsOnUpWhenSet() {
+ KeyRules r = new KeyRules(LEFT, RIGHT, UP);
+ assertEquals(KeyRules.SWALLOW, r.decide(UP, DOWN, 0, true));
+ assertEquals(KeyRules.FULLSCREEN, r.decide(UP, UPA, 100, true));
+ }
+
+ @Test
+ public void upPassesWhenFullscreenIsOff() {
+ assertEquals(KeyRules.PASS, rules.decide(UP, DOWN, 0, true));
+ }
+
+ @Test
+ public void holdKeyIgnoresAShortPress() {
+ KeyRules r = new KeyRules(LEFT, RIGHT, 0, true, false, false);
+ assertEquals(KeyRules.SWALLOW, r.decide(LEFT, DOWN, 1000, true));
+ assertEquals(KeyRules.SWALLOW, r.decide(LEFT, UPA, 1000 + KeyRules.HOLD_MS - 1, true));
+ }
+
+ @Test
+ public void holdKeyActsWhenHeldLongEnough() {
+ KeyRules r = new KeyRules(LEFT, RIGHT, 0, true, false, false);
+ assertEquals(KeyRules.SWALLOW, r.decide(LEFT, DOWN, 1000, true));
+ assertEquals(KeyRules.DISMISS, r.decide(LEFT, UPA, 1000 + KeyRules.HOLD_MS, true));
+ }
+
+ @Test
+ public void repeatsWhileHeldAreSwallowedAndDoNotRestartTheClock() {
+ KeyRules r = new KeyRules(LEFT, RIGHT, 0, false, true, false);
+ assertEquals(KeyRules.SWALLOW, r.decide(RIGHT, DOWN, 1000, true));
+ assertEquals(KeyRules.SWALLOW, r.decide(RIGHT, DOWN, 1400, true));
+ assertEquals(KeyRules.SNOOZE, r.decide(RIGHT, UPA, 1000 + KeyRules.HOLD_MS, true));
+ }
+
+ @Test
+ public void holdOnOneKeyLeavesTheOthersQuick() {
+ KeyRules r = new KeyRules(LEFT, RIGHT, UP, true, false, false);
+ assertEquals(KeyRules.SWALLOW, r.decide(RIGHT, DOWN, 0, true));
+ assertEquals(KeyRules.SNOOZE, r.decide(RIGHT, UPA, 50, true));
+ }
+
+ @Test
+ public void heldHoldKeyIsReportedUntilReleased() {
+ KeyRules r = new KeyRules(LEFT, RIGHT, 0, false, true, false);
+ assertEquals(0, r.pendingHold());
+ r.decide(RIGHT, DOWN, 0, true);
+ assertEquals(KeyRules.SNOOZE, r.pendingHold());
+ r.decide(RIGHT, UPA, 100, true);
+ assertEquals(0, r.pendingHold());
+ }
+
+ @Test
+ public void quickKeyIsNeverAPendingHold() {
+ KeyRules r = new KeyRules(LEFT, RIGHT, 0, false, true, false);
+ r.decide(LEFT, DOWN, 0, true);
+ assertEquals(0, r.pendingHold());
+ }
+}
diff --git a/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/LiveVideoTest.java b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/LiveVideoTest.java
new file mode 100644
index 000000000..f018feb5f
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/LiveVideoTest.java
@@ -0,0 +1,22 @@
+package io.github.nickld.frigateglance;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class LiveVideoTest {
+ @Test
+ public void rtspUrlWithoutCredentials() {
+ assertEquals("rtsp://192.168.1.11:8554/frontdoooor_1", LiveVideo.rtspUrl("192.168.1.11", "", "", "frontdoooor_1"));
+ }
+
+ @Test
+ public void rtspUrlEncodesCredentials() {
+ assertEquals("rtsp://us%40r:p%3Ass@h:8554/s", LiveVideo.rtspUrl("h", "us@r", "p:ss", "s"));
+ }
+
+ @Test
+ public void streamNameIsEncoded() {
+ assertEquals("rtsp://h:8554/front%20door", LiveVideo.rtspUrl("h", "", "", "front door"));
+ }
+}
diff --git a/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/MqttClientTest.java b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/MqttClientTest.java
new file mode 100644
index 000000000..387bc43b5
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/MqttClientTest.java
@@ -0,0 +1,170 @@
+package io.github.nickld.frigateglance;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class MqttClientTest {
+ private static final List<String> TOPICS = List.of("frigate/reviews", "frigate/events", "frigate/available");
+
+ static final class Recorder implements MqttClient.Listener {
+ boolean connected;
+ final List<String> topics = new ArrayList<>();
+ final List<byte[]> payloads = new ArrayList<>();
+ Exception cause;
+
+ @Override public void onConnected() { connected = true; }
+ @Override public void onMessage(String topic, byte[] payload) { topics.add(topic); payloads.add(payload); }
+ @Override public void onDisconnected(Exception c) { cause = c; }
+ }
+
+ private static final byte[] CONNACK_OK = {0x20, 0x02, 0x00, 0x00};
+ private static final byte[] SUBACK = {(byte) 0x90, 0x05, 0x00, 0x01, 0x00, 0x00, 0x00};
+
+ private static byte[] publish(String topic, byte[] payload) {
+ ByteArrayOutputStream body = new ByteArrayOutputStream();
+ byte[] t = topic.getBytes(StandardCharsets.UTF_8);
+ body.write(t.length >> 8);
+ body.write(t.length & 0xff);
+ body.writeBytes(t);
+ body.writeBytes(payload);
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ out.write(0x30);
+ out.writeBytes(MqttClient.remainingLength(body.size()));
+ out.writeBytes(body.toByteArray());
+ return out.toByteArray();
+ }
+
+ private static byte[] concat(byte[]... parts) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ for (byte[] p : parts) out.writeBytes(p);
+ return out.toByteArray();
+ }
+
+ private static Recorder runAgainst(byte[] brokerBytes, ByteArrayOutputStream sent, String url) {
+ Recorder r = new Recorder();
+ new MqttClient(url, "frigate-glance-test", TOPICS, r).session(new ByteArrayInputStream(brokerBytes), sent);
+ return r;
+ }
+
+ @Test
+ public void sendsConnectWithCredentialsAndSubscribes() {
+ ByteArrayOutputStream sent = new ByteArrayOutputStream();
+ runAgainst(concat(CONNACK_OK, SUBACK), sent, "mqtt://u:p@broker:1883");
+ byte[] b = sent.toByteArray();
+ assertEquals(0x10, b[0] & 0xff);
+ String s = new String(b, StandardCharsets.ISO_8859_1);
+ assertTrue(s.contains("\u0000\u0004MQTT\u0004"));
+ int flagsAt = s.indexOf("MQTT") + 5;
+ assertEquals(0xC2, b[flagsAt] & 0xff); // user, password, clean session
+ assertEquals(60, ((b[flagsAt + 1] & 0xff) << 8) | (b[flagsAt + 2] & 0xff));
+ assertTrue(s.contains("frigate-glance-test"));
+ assertTrue(s.contains("\u0000\u0001u\u0000\u0001p"));
+ int sub = s.indexOf((char) 0x82);
+ assertTrue("SUBSCRIBE sent after CONNECT", sub > 0);
+ for (String t : TOPICS) assertTrue(s.indexOf(t, sub) > sub);
+ }
+
+ @Test
+ public void noCredentialsWhenUrlHasNone() {
+ ByteArrayOutputStream sent = new ByteArrayOutputStream();
+ runAgainst(concat(CONNACK_OK, SUBACK), sent, "mqtt://broker");
+ byte[] b = sent.toByteArray();
+ int flagsAt = new String(b, StandardCharsets.ISO_8859_1).indexOf("MQTT") + 5;
+ assertEquals(0x02, b[flagsAt] & 0xff);
+ }
+
+ @Test
+ public void deliversPublishPayload() {
+ byte[] payload = "{\"type\":\"new\"}".getBytes(StandardCharsets.UTF_8);
+ Recorder r = runAgainst(concat(CONNACK_OK, SUBACK, publish("frigate/reviews", payload)),
+ new ByteArrayOutputStream(), "mqtt://broker:1883");
+ assertTrue(r.connected);
+ assertEquals(List.of("frigate/reviews"), r.topics);
+ assertArrayEquals(payload, r.payloads.get(0));
+ assertNotNull("stream end is a disconnect", r.cause);
+ }
+
+ @Test
+ public void refusedConnackEndsWithDisconnected() {
+ Recorder r = runAgainst(new byte[] {0x20, 0x02, 0x00, 0x05}, new ByteArrayOutputStream(), "mqtt://u:p@broker");
+ assertTrue(!r.connected);
+ assertTrue(r.cause.getMessage(), r.cause.getMessage().contains("not authorised"));
+ }
+
+ @Test
+ public void badPasswordIsNamed() {
+ Recorder r = runAgainst(new byte[] {0x20, 0x02, 0x00, 0x04}, new ByteArrayOutputStream(), "mqtt://u:p@broker");
+ assertTrue(r.cause.getMessage(), r.cause.getMessage().contains("bad user name or password"));
+ }
+
+ @Test
+ public void decodesMultiByteRemainingLength() {
+ byte[] payload = new byte[300];
+ for (int i = 0; i < payload.length; i++) payload[i] = (byte) ('a' + i % 26);
+ Recorder r = runAgainst(concat(CONNACK_OK, SUBACK, publish("frigate/events", payload)),
+ new ByteArrayOutputStream(), "mqtt://broker");
+ assertArrayEquals(payload, r.payloads.get(0));
+ }
+
+ @Test
+ public void qos1PublishSkipsPacketId() {
+ byte[] t = "frigate/events".getBytes(StandardCharsets.UTF_8);
+ ByteArrayOutputStream body = new ByteArrayOutputStream();
+ body.write(0);
+ body.write(t.length);
+ body.writeBytes(t);
+ body.write(0);
+ body.write(7);
+ body.writeBytes("x".getBytes(StandardCharsets.UTF_8));
+ byte[] pub = concat(new byte[] {0x32}, MqttClient.remainingLength(body.size()), body.toByteArray());
+ Recorder r = runAgainst(concat(CONNACK_OK, SUBACK, pub), new ByteArrayOutputStream(), "mqtt://broker");
+ assertEquals("x", new String(r.payloads.get(0), StandardCharsets.UTF_8));
+ }
+
+ @Test
+ public void percentEncodedCredentialsAreDecoded() {
+ ByteArrayOutputStream sent = new ByteArrayOutputStream();
+ runAgainst(concat(CONNACK_OK, SUBACK), sent, "mqtt://us%40r:p%3Ass@broker");
+ String s = new String(sent.toByteArray(), StandardCharsets.ISO_8859_1);
+ assertTrue(s.contains("us@r") && s.contains("p:ss"));
+ }
+
+ @Test
+ public void backoffDoublesToSixtySeconds() {
+ assertEquals(1000, MqttClient.backoffMs(0));
+ assertEquals(8000, MqttClient.backoffMs(3));
+ assertEquals(60_000, MqttClient.backoffMs(10));
+ assertEquals(60_000, MqttClient.backoffMs(100));
+ }
+
+ @Test
+ public void pingsDuringSteadyTrafficSoTheBrokerKeepsUs() {
+ // Messages every 20 s never let a 30 s read time out; the client must still ping within the keep-alive.
+ byte[] pub = publish("frigate/events", "x".getBytes(StandardCharsets.UTF_8));
+ ByteArrayOutputStream sent = new ByteArrayOutputStream();
+ long[] now = {0};
+ MqttClient client = new MqttClient("mqtt://broker", "t", TOPICS, new Recorder(), () -> now[0] += 20_000);
+ client.session(new ByteArrayInputStream(concat(CONNACK_OK, SUBACK, pub, pub, pub, pub)), sent);
+ byte[] b = sent.toByteArray();
+ boolean ping = false;
+ for (int i = 0; i + 1 < b.length; i++) if ((b[i] & 0xff) == 0xC0 && b[i + 1] == 0) ping = true;
+ assertTrue("PINGREQ sent while messages kept arriving", ping);
+ }
+
+ @Test
+ public void badBrokerPacketEndsTheSessionInsteadOfCrashing() {
+ byte[] broken = {0x30, 0x02, 0x00, 0x09}; // topic length 9 but no topic bytes
+ Recorder r = runAgainst(concat(CONNACK_OK, SUBACK, broken), new ByteArrayOutputStream(), "mqtt://broker");
+ assertNotNull(r.cause);
+ }
+}
diff --git a/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/ReviewFilterTest.java b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/ReviewFilterTest.java
new file mode 100644
index 000000000..94a8181c7
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/ReviewFilterTest.java
@@ -0,0 +1,78 @@
+package io.github.nickld.frigateglance;
+
+import static io.github.nickld.frigateglance.Fixtures.reviewJson;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class ReviewFilterTest {
+ private static final long NOW = 1_000_000L;
+
+ private static ReviewFilter filter(String extraJson) {
+ String extra = extraJson.substring(1, extraJson.length() - 1);
+ return new ReviewFilter(GlanceConfig.parse("{\"mqtt\":\"mqtt://h:1883\",\"frigateUrl\":\"https://h:8971\""
+ + (extra.isEmpty() ? "" : "," + extra) + "}"));
+ }
+
+ private static Review review(String severity, String camera, String... objects) {
+ return Review.parse(reviewJson("new", "r1", camera, severity, objects));
+ }
+
+ @Test
+ public void alertShownByDefault() {
+ assertTrue(filter("{}").shows(review("alert", "driveway", "person"), NOW, 0));
+ }
+
+ @Test
+ public void detectionHiddenWhenAlertsOnly() {
+ assertFalse(filter("{}").shows(review("detection", "driveway", "car"), NOW, 0));
+ }
+
+ @Test
+ public void detectionShownWhenAlertsAndDetections() {
+ assertTrue(filter("{\"severity\":\"alerts_and_detections\"}").shows(review("detection", "driveway", "car"), NOW, 0));
+ }
+
+ @Test
+ public void cameraNotListedIsHidden() {
+ assertFalse(filter("{\"cameras\":{\"frontdoooor\":\"Front door\"}}").shows(review("alert", "shop", "person"), NOW, 0));
+ assertTrue(filter("{\"cameras\":{\"frontdoooor\":\"Front door\"}}").shows(review("alert", "frontdoooor", "person"), NOW, 0));
+ }
+
+ @Test
+ public void labelFilterNeedsOneMatchingObject() {
+ assertTrue(filter("{\"labels\":[\"person\"]}").shows(review("alert", "driveway", "car", "person"), NOW, 0));
+ assertFalse(filter("{\"labels\":[\"person\"]}").shows(review("alert", "driveway", "car"), NOW, 0));
+ }
+
+ @Test
+ public void snoozedHidesEverythingUntilItExpires() {
+ assertFalse(filter("{}").shows(review("alert", "driveway", "person"), NOW, NOW + 1));
+ assertTrue(filter("{}").shows(review("alert", "driveway", "person"), NOW, NOW));
+ }
+
+ @Test
+ public void replayCameraCountsAsTheCameraItReplays() {
+ assertTrue(filter("{\"cameras\":{\"shop\":\"Shop\"}}").shows(review("alert", "_replay_shop", "person"), NOW, 0));
+ assertFalse(filter("{\"cameras\":{\"driveway\":\"Drive\"}}").shows(review("alert", "_replay_shop", "person"), NOW, 0));
+ }
+
+ @Test
+ public void baseCameraOfReplay() {
+ assertEquals("shop", ReviewFilter.baseCamera("_replay_shop"));
+ assertEquals("shop", ReviewFilter.baseCamera("shop"));
+ }
+
+ @Test
+ public void newCamerasLetsACameraOutsideTheListIn() {
+ assertTrue(filter("{\"cameras\":{\"driveway\":\"D\"},\"newCameras\":true}").shows(review("alert", "backyard", "person"), NOW, 0));
+ assertFalse(filter("{\"cameras\":{\"driveway\":\"D\"}}").shows(review("alert", "backyard", "person"), NOW, 0));
+ }
+
+ @Test
+ public void cameraSwitchedOffStaysOffEvenWithNewCameras() {
+ assertFalse(filter("{\"newCameras\":true,\"camerasOff\":[\"shop\"]}").shows(review("alert", "_replay_shop", "person"), NOW, 0));
+ }
+}
diff --git a/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/ReviewTest.java b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/ReviewTest.java
new file mode 100644
index 000000000..8573c2b89
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/ReviewTest.java
@@ -0,0 +1,90 @@
+package io.github.nickld.frigateglance;
+
+import static io.github.nickld.frigateglance.Fixtures.fixture;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Test;
+
+public class ReviewTest {
+ @Test
+ public void parsesNewAlert() {
+ Review r = Review.parse(fixture("review_new.json"));
+ assertEquals("new", r.type);
+ assertEquals("1761100000.1-abc", r.id);
+ assertEquals("frontdoooor", r.camera);
+ assertEquals("alert", r.severity);
+ assertEquals(List.of("person"), r.objects);
+ assertEquals(List.of("entire_front_yard"), r.zones);
+ assertEquals(List.of("1761100000.0-ev1"), r.detectionIds);
+ }
+
+ @Test
+ public void updateCarriesNewObjectsAndDetections() {
+ Review r = Review.parse(fixture("review_update.json"));
+ assertEquals("update", r.type);
+ assertEquals(List.of("person", "car"), r.objects);
+ assertEquals(2, r.detectionIds.size());
+ }
+
+ @Test
+ public void parsesEnd() {
+ assertEquals("end", Review.parse(fixture("review_end.json")).type);
+ }
+
+ @Test
+ public void malformedReviewIsNull() {
+ assertNull(Review.parse("{\"type\":\"new\"}"));
+ assertNull(Review.parse("not json"));
+ assertNull(Review.parse("{\"type\":\"bogus\",\"after\":{\"id\":\"x\",\"camera\":\"c\",\"severity\":\"alert\"}}"));
+ }
+
+ @Test
+ public void boxIsNormalisedByDetectSize() {
+ Detection d = Detection.parse(fixture("event_update.json"), Map.of("driveway", new int[] {1280, 720}));
+ assertArrayEquals(new float[] {0.5f, 0.25f, 0.75f, 1.0f}, d.box, 1e-4f);
+ assertEquals("1761100000.0-ev1", d.id);
+ assertEquals("car", d.label);
+ assertEquals("ABC1234", d.plate);
+ assertEquals(0.81, d.score, 1e-9);
+ assertEquals(List.of("entiredriveway"), d.zones);
+ assertNull(d.subLabel);
+ }
+
+ @Test
+ public void unknownDetectSizeMeansNoBox() {
+ assertNull(Detection.parse(fixture("event_update.json"), Map.of()).box);
+ }
+
+ @Test
+ public void subLabelArrayTakesFirstElement() {
+ assertEquals("Nick", Detection.parse(fixture("event_sublabel_array.json"), Map.of()).subLabel);
+ }
+
+ @Test
+ public void malformedEventIsNull() {
+ assertNull(Detection.parse("{}", Map.of()));
+ assertNull(Detection.parse("[]", Map.of()));
+ }
+
+ @Test
+ public void replayEventStandsInForAReview() {
+ Review r = Review.fromReplayEvent(fixture("event_replay_new.json"));
+ assertEquals("new", r.type);
+ assertEquals("_replay_shop", r.camera);
+ assertEquals("alert", r.severity);
+ assertEquals(List.of("person"), r.objects);
+ assertEquals(List.of("1761110000.5-xyz"), r.detectionIds);
+ assertEquals("replay-1761110000.5-xyz", r.id);
+ }
+
+ @Test
+ public void onlyReplayCameraEventsStandIn() {
+ assertNull(Review.fromReplayEvent(fixture("event_update.json")));
+ assertNull(Review.fromReplayEvent("not json"));
+ }
+}
diff --git a/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/SettingsModelTest.java b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/SettingsModelTest.java
new file mode 100644
index 000000000..73a6afde3
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/SettingsModelTest.java
@@ -0,0 +1,107 @@
+package io.github.nickld.frigateglance;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.List;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.junit.Test;
+
+public class SettingsModelTest {
+ private static final String FRIGATE = "{\"cameras\":{"
+ + "\"driveway\":{\"review\":{\"alerts\":{\"labels\":[\"person\",\"car\"]}}},"
+ + "\"shop\":{\"review\":{\"alerts\":{\"labels\":[\"person\"]}},\"objects\":{\"track\":[\"person\",\"dog\"]}},"
+ + "\"frontdoooor\":{}}}";
+
+ private static GlanceConfig config(String extra) {
+ return GlanceConfig.parse("{\"mqtt\":\"mqtt://h\",\"frigateUrl\":\"https://h:8971\"" + extra + "}");
+ }
+
+ @Test
+ public void replayCamerasGetNoSwitchOfTheirOwn() throws Exception {
+ assertEquals(List.of("shop"), SettingsModel.cameraNames(new JSONObject("{\"cameras\":{\"shop\":{},\"_replay_shop\":{}}}")));
+ }
+
+ @Test
+ public void camerasComeSortedFromFrigate() throws Exception {
+ assertEquals(List.of("driveway", "frontdoooor", "shop"), SettingsModel.cameraNames(new JSONObject(FRIGATE)));
+ }
+
+ @Test
+ public void labelsAreAlertLabelsAndTrackedObjects() throws Exception {
+ assertEquals(List.of("car", "dog", "person"), SettingsModel.labelNames(new JSONObject(FRIGATE)));
+ }
+
+ @Test
+ public void everyCameraIsOnWhenNoneAreListed() {
+ assertTrue(SettingsModel.cameraOn(config(""), "shop"));
+ }
+
+ @Test
+ public void turningACameraOffListsItAsOff() throws Exception {
+ JSONObject ch = SettingsModel.toggleCamera(config(""), List.of("driveway", "frontdoooor", "shop"), "shop");
+ assertEquals("[\"shop\"]", ch.getJSONArray("camerasOff").toString());
+ assertFalse(SettingsModel.cameraOn(config(",\"camerasOff\":[\"shop\"]"), "shop"));
+ }
+
+ @Test
+ public void turningItBackOnClearsIt() throws Exception {
+ JSONObject ch = SettingsModel.toggleCamera(config(",\"camerasOff\":[\"shop\"]"), List.of("driveway", "shop"), "shop");
+ assertEquals(0, ch.getJSONArray("camerasOff").length());
+ }
+
+ @Test
+ public void aCameraMissingFromTheListIsAddedWithItsName() throws Exception {
+ GlanceConfig c = config(",\"cameras\":{\"driveway\":\"Drive\"}");
+ assertFalse(SettingsModel.cameraOn(c, "shop"));
+ JSONObject cams = SettingsModel.toggleCamera(c, List.of("driveway", "shop"), "shop").getJSONObject("cameras");
+ assertEquals("Drive", cams.getString("driveway"));
+ assertEquals("Shop", cams.getString("shop"));
+ }
+
+ @Test
+ public void newCamerasOnLetsUnlistedCamerasIn() {
+ GlanceConfig c = config(",\"cameras\":{\"driveway\":\"Drive\"},\"newCameras\":true");
+ assertTrue(SettingsModel.cameraOn(c, "backyard"));
+ assertFalse(SettingsModel.cameraOn(config(",\"cameras\":{\"driveway\":\"Drive\"},\"newCameras\":true,\"camerasOff\":[\"backyard\"]"), "backyard"));
+ }
+
+ @Test
+ public void labelToggleWorksTheSameWay() throws Exception {
+ JSONArray l = SettingsModel.toggleLabel(config(""), List.of("car", "person"), "car");
+ assertEquals("[\"person\"]", l.toString());
+ GlanceConfig c = config(",\"labels\":[\"person\"]");
+ assertEquals(0, SettingsModel.toggleLabel(c, List.of("car", "person"), "car").length());
+ }
+
+ @Test
+ public void lastCameraCannotBeTurnedOff() throws Exception {
+ GlanceConfig c = config(",\"cameras\":{\"shop\":\"Shop\"}");
+ assertEquals(0, SettingsModel.toggleCamera(c, List.of("driveway", "shop"), "shop").length());
+ }
+
+ @Test
+ public void cycleWrapsAround() {
+ assertEquals("top-left", SettingsModel.next(List.of("top-right", "top-left"), "top-right"));
+ assertEquals("top-right", SettingsModel.next(List.of("top-right", "top-left"), "top-left"));
+ assertEquals("top-right", SettingsModel.next(List.of("top-right", "top-left"), "unknown"));
+ }
+
+ @Test
+ public void durationsCycle() {
+ assertEquals(Integer.valueOf(15), SettingsModel.next(SettingsModel.DISMISS_SECONDS, 8));
+ assertEquals(Integer.valueOf(4), SettingsModel.next(SettingsModel.DISMISS_SECONDS, 30));
+ assertEquals(Integer.valueOf(120), SettingsModel.next(SettingsModel.SNOOZE_MINUTES, 60));
+ assertEquals(Integer.valueOf(15), SettingsModel.next(SettingsModel.SNOOZE_MINUTES, 240));
+ }
+
+ @Test
+ public void cardSizeCycles() {
+ assertEquals(Integer.valueOf(115), SettingsModel.next(SettingsModel.CARD_SCALES, 100));
+ assertEquals(Integer.valueOf(70), SettingsModel.next(SettingsModel.CARD_SCALES, 150));
+ assertEquals(Integer.valueOf(70), SettingsModel.next(SettingsModel.CARD_SCALES, 123));
+ }
+}
diff --git a/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/TinyHttp.java b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/TinyHttp.java
new file mode 100644
index 000000000..779240610
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/java/io/github/nickld/frigateglance/TinyHttp.java
@@ -0,0 +1,107 @@
+package io.github.nickld.frigateglance;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+
+/** A one-request-per-connection HTTP/1.1 server for tests, because com.sun.net.httpserver is not on the Android test classpath. */
+final class TinyHttp implements AutoCloseable {
+ static final class Request {
+ String method, path, query;
+ final Map<String, String> headers = new HashMap<>();
+ }
+
+ static final class Response {
+ int code = 200;
+ String body = "";
+ final Map<String, String> headers = new HashMap<>();
+
+ Response(int code, String body) {
+ this.code = code;
+ this.body = body;
+ }
+ }
+
+ interface Handler {
+ Response handle(Request r);
+ }
+
+ private final ServerSocket server;
+ private final Map<String, Handler> handlers = new HashMap<>();
+ private final Thread thread;
+
+ TinyHttp() throws IOException {
+ server = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
+ thread = new Thread(this::loop, "TinyHttp");
+ thread.setDaemon(true);
+ }
+
+ TinyHttp on(String path, Handler h) {
+ handlers.put(path, h);
+ return this;
+ }
+
+ TinyHttp start() {
+ thread.start();
+ return this;
+ }
+
+ String url() {
+ return "http://127.0.0.1:" + server.getLocalPort();
+ }
+
+ private void loop() {
+ while (!server.isClosed()) {
+ try (Socket s = server.accept()) {
+ serve(s);
+ } catch (IOException e) {
+ return;
+ }
+ }
+ }
+
+ private void serve(Socket s) throws IOException {
+ BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), StandardCharsets.ISO_8859_1));
+ String line = in.readLine();
+ if (line == null) return;
+ Request r = new Request();
+ String[] parts = line.split(" ");
+ r.method = parts[0];
+ String target = parts[1];
+ int q = target.indexOf('?');
+ r.path = q < 0 ? target : target.substring(0, q);
+ r.query = q < 0 ? null : target.substring(q + 1);
+ int length = 0;
+ while ((line = in.readLine()) != null && !line.isEmpty()) {
+ int c = line.indexOf(':');
+ String name = line.substring(0, c).trim().toLowerCase(Locale.ROOT);
+ String value = line.substring(c + 1).trim();
+ r.headers.put(name, value);
+ if (name.equals("content-length")) length = Integer.parseInt(value);
+ }
+ for (int i = 0; i < length; i++) in.read();
+ Handler h = handlers.get(r.path);
+ Response resp = h == null ? new Response(404, "") : h.handle(r);
+ byte[] body = resp.body.getBytes(StandardCharsets.UTF_8);
+ StringBuilder head = new StringBuilder("HTTP/1.1 " + resp.code + " X\r\n");
+ for (Map.Entry<String, String> e : resp.headers.entrySet()) head.append(e.getKey()).append(": ").append(e.getValue()).append("\r\n");
+ head.append("Content-Length: ").append(body.length).append("\r\nConnection: close\r\n\r\n");
+ OutputStream out = s.getOutputStream();
+ out.write(head.toString().getBytes(StandardCharsets.ISO_8859_1));
+ out.write(body);
+ out.flush();
+ }
+
+ @Override
+ public void close() throws IOException {
+ server.close();
+ }
+}
diff --git a/addons/frigate-glance/app/src/test/resources/event_replay_new.json b/addons/frigate-glance/app/src/test/resources/event_replay_new.json
new file mode 100644
index 000000000..60381d607
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/resources/event_replay_new.json
@@ -0,0 +1 @@
+{"type":"new","before":{"id":"1761110000.5-xyz","camera":"_replay_shop","label":"person"},"after":{"id":"1761110000.5-xyz","camera":"_replay_shop","label":"person","sub_label":null,"score":0.88,"top_score":0.9,"box":[10,20,110,220],"entered_zones":[],"current_zones":[]}}
diff --git a/addons/frigate-glance/app/src/test/resources/event_sublabel_array.json b/addons/frigate-glance/app/src/test/resources/event_sublabel_array.json
new file mode 100644
index 000000000..6d2f6c938
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/resources/event_sublabel_array.json
@@ -0,0 +1 @@
+{"type":"update","after":{"id":"1761100000.0-ev1","camera":"frontdoooor","label":"person","sub_label":["Nick",0.93],"score":0.9,"top_score":0.92,"box":[10,20,110,220],"entered_zones":[]}}
diff --git a/addons/frigate-glance/app/src/test/resources/event_update.json b/addons/frigate-glance/app/src/test/resources/event_update.json
new file mode 100644
index 000000000..034960c29
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/resources/event_update.json
@@ -0,0 +1 @@
+{"type":"update","before":{"id":"1761100000.0-ev1","camera":"driveway","label":"car","score":0.7},"after":{"id":"1761100000.0-ev1","camera":"driveway","frame_time":1761100002.4,"label":"car","sub_label":null,"top_score":0.84,"score":0.81,"box":[640,180,960,720],"area":172800,"region":[600,100,1000,720],"stationary":false,"active":true,"current_zones":["entiredriveway"],"entered_zones":["entiredriveway"],"has_snapshot":true,"has_clip":true,"recognized_license_plate":"ABC1234"}}
diff --git a/addons/frigate-glance/app/src/test/resources/review_end.json b/addons/frigate-glance/app/src/test/resources/review_end.json
new file mode 100644
index 000000000..cbc4e0d8a
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/resources/review_end.json
@@ -0,0 +1 @@
+{"type":"end","before":{"id":"1761100000.1-abc","camera":"frontdoooor","severity":"alert","data":{"detections":["1761100000.0-ev1"],"objects":["person"],"zones":[]}},"after":{"id":"1761100000.1-abc","camera":"frontdoooor","start_time":1761100000.1,"end_time":1761100030.5,"severity":"alert","data":{"detections":["1761100000.0-ev1"],"objects":["person"],"sub_labels":[],"zones":["entire_front_yard"],"audio":[]}}}
diff --git a/addons/frigate-glance/app/src/test/resources/review_new.json b/addons/frigate-glance/app/src/test/resources/review_new.json
new file mode 100644
index 000000000..f38a78f9e
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/resources/review_new.json
@@ -0,0 +1 @@
+{"type":"new","before":{"id":"1761100000.1-abc","camera":"frontdoooor","start_time":1761100000.1,"end_time":null,"severity":"alert","thumb_path":"/media/frigate/clips/review/thumb-frontdoooor-1761100000.1-abc.webp","data":{"detections":["1761100000.0-ev1"],"objects":["person"],"sub_labels":[],"zones":["entire_front_yard"],"audio":[]}},"after":{"id":"1761100000.1-abc","camera":"frontdoooor","start_time":1761100000.1,"end_time":null,"severity":"alert","thumb_path":"/media/frigate/clips/review/thumb-frontdoooor-1761100000.1-abc.webp","data":{"detections":["1761100000.0-ev1"],"objects":["person"],"sub_labels":[],"zones":["entire_front_yard"],"audio":[]}}}
diff --git a/addons/frigate-glance/app/src/test/resources/review_update.json b/addons/frigate-glance/app/src/test/resources/review_update.json
new file mode 100644
index 000000000..84bbb72d4
--- /dev/null
+++ b/addons/frigate-glance/app/src/test/resources/review_update.json
@@ -0,0 +1 @@
+{"type":"update","before":{"id":"1761100000.1-abc","camera":"frontdoooor","severity":"alert","data":{"detections":["1761100000.0-ev1"],"objects":["person"],"zones":["entire_front_yard"]}},"after":{"id":"1761100000.1-abc","camera":"frontdoooor","start_time":1761100000.1,"end_time":null,"severity":"alert","data":{"detections":["1761100000.0-ev1","1761100003.2-ev2"],"objects":["person","car"],"sub_labels":["Nick"],"zones":["entire_front_yard"],"audio":[]}}}
diff --git a/addons/frigate-glance/build.gradle b/addons/frigate-glance/build.gradle
new file mode 100644
index 000000000..48978475f
--- /dev/null
+++ b/addons/frigate-glance/build.gradle
@@ -0,0 +1,3 @@
+plugins {
+ id 'com.android.application' version '8.5.2' apply false
+}
diff --git a/addons/frigate-glance/config.example.json b/addons/frigate-glance/config.example.json
new file mode 100644
index 000000000..a3ead2089
--- /dev/null
+++ b/addons/frigate-glance/config.example.json
@@ -0,0 +1,10 @@
+{
+ "mqtt": "mqtt://MQTT_USER:[email protected]:1883",
+ "frigateUrl": "https://192.168.1.11:8971",
+ "frigateUser": "FRIGATE_VIEWER_USER",
+ "frigatePassword": "FRIGATE_VIEWER_PASSWORD",
+ "cameras": {
+ "front_door": "Front door",
+ "driveway": "Driveway"
+ }
+}
diff --git a/addons/frigate-glance/docs/card-in-grid.jpg b/addons/frigate-glance/docs/card-in-grid.jpg
new file mode 100644
index 000000000..f20750701
Binary files /dev/null and b/addons/frigate-glance/docs/card-in-grid.jpg differ
diff --git a/addons/frigate-glance/gradle.properties b/addons/frigate-glance/gradle.properties
new file mode 100644
index 000000000..18825f968
--- /dev/null
+++ b/addons/frigate-glance/gradle.properties
@@ -0,0 +1,3 @@
+org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
+android.useAndroidX=true
+android.nonTransitiveRClass=true
diff --git a/addons/frigate-glance/gradle/wrapper/gradle-wrapper.jar b/addons/frigate-glance/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 000000000..2c3521197
Binary files /dev/null and b/addons/frigate-glance/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/addons/frigate-glance/gradle/wrapper/gradle-wrapper.properties b/addons/frigate-glance/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000..77f5d0ba6
--- /dev/null
+++ b/addons/frigate-glance/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,8 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
+distributionSha256Sum=d725d707bfabd4dfdc958c624003b3c80accc03f7037b5122c4b1d0ef15cecab
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/addons/frigate-glance/gradlew b/addons/frigate-glance/gradlew
new file mode 100644
index 000000000..f5feea6d6
--- /dev/null
+++ b/addons/frigate-glance/gradlew
@@ -0,0 +1,252 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
+' "$PWD" ) || exit
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ if ! command -v java >/dev/null 2>&1
+ then
+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/addons/frigate-glance/gradlew.bat b/addons/frigate-glance/gradlew.bat
new file mode 100644
index 000000000..9d21a2183
--- /dev/null
+++ b/addons/frigate-glance/gradlew.bat
@@ -0,0 +1,94 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/addons/frigate-glance/install.sh b/addons/frigate-glance/install.sh
new file mode 100644
index 000000000..d79568306
--- /dev/null
+++ b/addons/frigate-glance/install.sh
@@ -0,0 +1,79 @@
+#!/usr/bin/env bash
+# Build Frigate Glance, install it on the TV, push its config and check it reaches MQTT and Frigate.
+# TV_HOST=<tv ip> addons/frigate-glance/install.sh <config.json>
+# The config holds passwords: keep it outside the repo (backup/ is git-ignored). This script never prints it.
+set -euo pipefail
+CONFIG="${1:?usage: TV_HOST=<tv ip> $0 <config.json>}"
+: "${TV_HOST:?set TV_HOST to the TV IP address}"
+CONFIG="$(cd "$(dirname "$CONFIG")" && pwd)/$(basename "$CONFIG")"
+# Git Bash on Windows: the venv's Python wants C:/... rather than /c/...
+if command -v cygpath >/dev/null 2>&1; then CONFIG="$(cygpath -m "$CONFIG")"; fi
+cd "$(dirname "$0")"
+TOOLS="$(cd ../../tools && pwd)"
+PY=$TOOLS/venv/bin/python
+[ -x "$PY" ] || PY=$TOOLS/venv/Scripts/python.exe
+export MSYS_NO_PATHCONV=1
+PKG=io.github.nickld.frigateglance
+# Script paths stay relative: with MSYS_NO_PATHCONV, Git Bash would hand Windows Python a /c/... path.
+tv() { "$PY" -I ../../tools/tv.py "$@"; }
+
+"$PY" -I - "$CONFIG" <<'EOF' || exit 1
+import json, sys
+try:
+ c = json.load(open(sys.argv[1], encoding="utf-8"))
+except Exception as e:
+ sys.exit(f"{sys.argv[1]} is not valid JSON: {e}")
+missing = [k for k in ("mqtt", "frigateUrl") if not str(c.get(k, "")).strip()]
+if missing:
+ sys.exit("config needs " + ", ".join(missing))
+from urllib.parse import urlsplit
+try:
+ u = urlsplit(c["mqtt"])
+ ok = u.scheme == "mqtt" and bool(u.hostname) and not any(ch in c["mqtt"] for ch in " #?")
+except ValueError:
+ ok = False
+if not ok: # the value holds a password: never print it
+ sys.exit('"mqtt" must look like mqtt://user:password@host:1883, special characters percent-encoded')
+EOF
+
+[ -f local.properties ] || { [ -n "${ANDROID_HOME:-}" ] && echo "sdk.dir=$ANDROID_HOME" > local.properties; } || true
+if [ -n "${JAVA_HOME:-}" ]; then export PATH="$JAVA_HOME/bin:$PATH"; fi
+./gradlew assembleRelease -q --console=plain
+
+"$PY" -I ../../tools/b64push.py app/build/outputs/apk/release/app-release.apk /data/local/tmp/fg.apk
+OUT=$(tv 'pm install -r /data/local/tmp/fg.apk; rm -f /data/local/tmp/fg.apk')
+echo "$OUT"
+case "$OUT" in *Success*) ;; *) echo "ERROR: pm install failed" >&2; exit 1 ;; esac
+
+# Display over other apps (TCL's Settings hide it) and TCL's auto-start, so the service reconnects after a reboot.
+tv "appops set $PKG SYSTEM_ALERT_WINDOW allow; cmd appops set $PKG APP_AUTO_START allow 2>/dev/null; echo permissions granted"
+
+# The config goes into the app's files folder, or through its provider where the shell may not write there.
+# The log is cleared first: through the provider the service picks the config up, and logs its connection, at once.
+tv "logcat -c" >/dev/null
+STAGE=/data/local/tmp/fg-config.json
+tv --push "$CONFIG" "$STAGE" >/dev/null
+OUT=$(tv "d=/sdcard/Android/data/$PKG/files; if { mkdir -p \$d 2>/dev/null && cp $STAGE \$d/config.json 2>/dev/null; } || content write --uri content://$PKG.config/config.json < $STAGE; then echo config pushed; else echo config not written; fi; rm -f $STAGE")
+echo "$OUT"
+case "$OUT" in *"config pushed"*) ;; *) echo "ERROR: the config could not be written on the TV" >&2; exit 1 ;; esac
+
+# The key service, added to whatever accessibility services are already on (the launcher's, for one). A service
+# that was already listed is unbound by the reinstall and binds again only once the list changes.
+SVC=$PKG/.KeyService
+tv "s=\$(settings get secure enabled_accessibility_services); case \"\$s\" in *$SVC*) settings put secure enabled_accessibility_services \"\$s\"; settings put secure accessibility_enabled 1; sleep 1; settings put secure enabled_accessibility_services ''; settings put secure accessibility_enabled 0; sleep 1; settings put secure enabled_accessibility_services \"\$s\" ;; null|'') settings put secure enabled_accessibility_services $SVC ;; *) settings put secure enabled_accessibility_services \"\$s:$SVC\" ;; esac; settings put secure accessibility_enabled 1; echo key service enabled"
+
+# Start it, then wait up to 20 s for the connection lines the service logs.
+tv "am start -n $PKG/.SettingsActivity >/dev/null" >/dev/null
+LOG=""
+for _ in $(seq 1 10); do
+ sleep 2
+ LOG=$(tv "logcat -d -s FrigateGlance:*" | tr -d '\r')
+ case "$LOG" in *"mqtt connected"*|*"mqtt error"*) case "$LOG" in *"frigate ok"*|*"frigate error"*) break ;; esac ;; esac
+done
+mqtt=$(printf '%s\n' "$LOG" | grep -o 'mqtt connected\|mqtt error: .*' | tail -n 1 || true)
+frigate=$(printf '%s\n' "$LOG" | grep -o 'frigate ok\|frigate error: .*' | tail -n 1 || true)
+case "$mqtt" in "mqtt connected") echo "MQTT: ok" ;; "") echo "MQTT: no answer within 20 s" ;; *) echo "MQTT: ${mqtt#mqtt error: }" ;; esac
+case "$frigate" in "frigate ok") echo "Frigate: ok" ;; "") echo "Frigate: no answer within 20 s" ;; *) echo "Frigate: ${frigate#frigate error: }" ;; esac
+[ "$mqtt" = "mqtt connected" ] && [ "$frigate" = "frigate ok" ] || exit 1
+tv "am broadcast -n $PKG/.TestCardReceiver >/dev/null; echo test card shown"
+echo "Installed. A test card is on the TV now; real ones follow Frigate's alerts."
diff --git a/addons/frigate-glance/settings.gradle b/addons/frigate-glance/settings.gradle
new file mode 100644
index 000000000..a3304847b
--- /dev/null
+++ b/addons/frigate-glance/settings.gradle
@@ -0,0 +1,16 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+rootProject.name = "frigate-glance"
+include ':app'