Skip to content

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

Add-on: Smart Home

מקס חייםcd9729d4a1da
diff --git a/addons/README.md b/addons/README.md
index c3f00031d..422ac38fd 100644
--- a/addons/README.md
+++ b/addons/README.md
@@ -20,6 +20,7 @@ the core bigger or change how it behaves. You install an add-on only if you want
| [TV Static](tv-static/) | An off-the-air moment each time the screen turns on: the picture opens from a bright line, snow and hiss, colour bars or an old "no signal" screen for 3 to 10 s, then fades into what was on screen; the card sets style, sound and length | [@luyzfernando08](https://github.com/luyzfernando08) | Xiaomi Mi Box S (Android TV 9), Philco by Skyworth (Android TV 14) | foreground service (screen-on watcher), start at boot, display over other apps | <img src="tv-static/screenshot.jpg" width="240" alt="TV Static on a TV"> |
| [Brightness](brightness/) | Dims the picture below the TV's own minimum over every app (and the picture settings on Realtek TVs), with a warm night mode on a schedule and a one-press normal screen | [@maxhayim](https://github.com/maxhayim) | MOKA R8G (Android 14) | overlay, foreground service, start at boot | <img src="brightness/screenshot.jpg" width="240" alt="Brightness on a TV"> |
| [Sleep Timer](sleep-timer/) | A sleep timer: 15 to 120 minutes, a one-minute countdown over what is playing with "15 more minutes", then standby; over HDMI-CEC the TV turns off with the box | [@luyzfernando08](https://github.com/luyzfernando08) | Xiaomi Mi Box S (Android TV 9) | accessibility (lock-screen action only), display over other apps, exact alarms | <img src="sleep-timer/screenshot.jpg" width="240" alt="Sleep Timer on a TV"> |
+| [Smart Home](smart-home/) | Home Assistant on the TV: scenes, lights and switches (OK toggles, left and right dim), climate, temperature and humidity, doors and windows, and locks shown but never opened | [@maxhayim](https://github.com/maxhayim) | MOKA R8G (Android 14) | `INTERNET` (your Home Assistant only) | <img src="smart-home/screenshot.jpg" width="240" alt="Smart Home on a TV"> |
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.
diff --git a/addons/smart-home/.gitignore b/addons/smart-home/.gitignore
new file mode 100644
index 000000000..a7e04a21b
--- /dev/null
+++ b/addons/smart-home/.gitignore
@@ -0,0 +1,4 @@
+.gradle/
+build/
+app/build/
+local.properties
diff --git a/addons/smart-home/README.md b/addons/smart-home/README.md
new file mode 100644
index 000000000..ed1274077
--- /dev/null
+++ b/addons/smart-home/README.md
@@ -0,0 +1,77 @@
+# Smart Home
+
+Your [Home Assistant](https://www.home-assistant.io) on the TV: scenes, lights and switches, climate, temperature
+and humidity sensors, doors and windows, and locks, in sections you work with the remote. OK runs a scene or
+switches a light; ◀ ▶ dims a light by 10 % or moves a thermostat by half a degree. A community add-on, not made by
+or affiliated with the Home Assistant project. For the [Clean Your TV](../../README.md) launcher it declares a
+[module card](../../docs/modules.md): once you answer **Show card** its tile reads "Smart Home" with a blue glow.
+On any other Android TV home it is an ordinary app.
+
+![Smart Home on a TV, with demo data](screenshot.jpg)
+
+| Section | Shows | With the remote |
+|---|---|---|
+| Scenes | `scene.*` | OK runs it |
+| Lights and switches | `light.*`, `switch.*`, `fan.*`, `input_boolean.*`, on or off with brightness | OK toggles, ◀ ▶ dims a light |
+| Climate | `climate.*`: room temperature → set temperature | ◀ ▶ moves the set temperature |
+| Sensors | `sensor.*` with device class temperature or humidity | Shown only |
+| Doors and windows | `binary_sensor.*` with device class door, window, garage door or opening | Shown only |
+| Locks | `lock.*`, locked or unlocked | **Shown only: a TV remote never unlocks a door** |
+
+At most 80 entities, sorted by name within each section; unavailable ones are dimmed. It reads `GET /api/states`
+every 10 seconds while the screen is open, and nothing when it is closed.
+
+## Setup
+
+You need the server's address (for example `http://192.168.1.10:8123`) and a long-lived access token: in Home
+Assistant, open your profile, then Security, then Long-lived access tokens, Create token. Then either:
+
+- open the app and fill in **Home Assistant address** and **Access token** with the TV's keyboard (or the phone
+ remote's), or
+- put both in a file and push it from a computer, so the token is never typed on the TV or put on a command line:
+
+ ```bash
+ echo '{"url": "http://192.168.1.10:8123", "token": "eyJ..."}' > backup/smart-home.json
+ TV_HOST=<tv ip> addons/smart-home/install.sh backup/smart-home.json
+ ```
+
+ The app takes the file into its own storage and deletes it. Keep the file outside the repo (`backup/` is
+ git-ignored).
+
+## Permissions
+
+| Permission | Why |
+|---|---|
+| `INTERNET` | Your Home Assistant server, and nothing else: no telemetry, no update checks, no ads. |
+
+Plain `http://` is allowed for the home network (`res/xml/network.xml`); use `https://` with a certificate from a
+public authority (Nabu Casa, Let's Encrypt). The token stays in the app's own storage (backups are off) and is
+sent only to the address you entered, as `Authorization: Bearer`. `ConfigProvider` takes a pushed file and only
+the ADB shell can use it (it requires `WRITE_SECURE_SETTINGS`, as Frigate Glance's does). No background service,
+accounts or libraries.
+
+## Build and install
+
+JDK 17 and Android SDK platform 34 with build-tools 34.0.0, as for the launcher:
+
+```bash
+TV_HOST=<tv ip> addons/smart-home/install.sh [config.json]
+```
+
+To build only: `cd addons/smart-home && ./gradlew assembleRelease`; the JVM tests run with
+`./gradlew testReleaseUnitTest`.
+
+## Limits
+
+- **Self-signed HTTPS** certificates are refused. Use `http://` on the home network or a public certificate.
+- **`homeassistant.local`** names only resolve where the TV's network does mDNS name lookups; use the IP address
+ if it doesn't.
+- **Which entities** is fixed by domain and device class; there is no picker yet.
+
+## Tested on
+
+MOKA R8G (Android 14), on a home app that implements the module-card spec, against a stand-in server on the home network answering with Home Assistant's documented response shapes: the config pushed through `ConfigProvider`, reading the states, running a scene and dimming a light (the requests arrived as the REST API documents them). **Not yet tried against a real Home Assistant:** the author's server was down; a report from someone with one is welcome. The screenshot shows that demo data, with the address blurred. The JVM tests cover parsing, the service calls, the request headers against a local stand-in, and errors.
+
+## Maintainer
+
+[@maxhayim](https://github.com/maxhayim)
diff --git a/addons/smart-home/app/build.gradle b/addons/smart-home/app/build.gradle
new file mode 100644
index 000000000..ac813793f
--- /dev/null
+++ b/addons/smart-home/app/build.gradle
@@ -0,0 +1,41 @@
+plugins {
+ id 'com.android.application'
+}
+
+android {
+ namespace 'io.github.maxhayim.smarthome'
+ compileSdk 34
+
+ defaultConfig {
+ applicationId 'io.github.maxhayim.smarthome'
+ 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 {
+ // No libraries in the APK. Test only: plain JVM tests in 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/smart-home/app/proguard-rules.pro b/addons/smart-home/app/proguard-rules.pro
new file mode 100644
index 000000000..a4435d69a
--- /dev/null
+++ b/addons/smart-home/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/smart-home/app/src/main/AndroidManifest.xml b/addons/smart-home/app/src/main/AndroidManifest.xml
new file mode 100644
index 000000000..c53dea498
--- /dev/null
+++ b/addons/smart-home/app/src/main/AndroidManifest.xml
@@ -0,0 +1,42 @@
+<?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" />
+
+ <!-- Your Home Assistant server, and nothing else. -->
+ <uses-permission android:name="android.permission.INTERNET" />
+
+ <application
+ android:allowBackup="false"
+ android:banner="@drawable/banner"
+ android:icon="@mipmap/ic_launcher"
+ android:label="@string/app_name"
+ android:networkSecurityConfig="@xml/network"
+ android:theme="@android:style/Theme.DeviceDefault.NoActionBar">
+
+ <activity
+ android:name=".MainActivity"
+ android:exported="true"
+ android:launchMode="singleTask"
+ android:windowSoftInputMode="adjustPan">
+ <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>
+
+ <!-- install.sh writes the server address and token here with `content write`, so the token never sits on
+ a command line. Write-only, one file name, and only the ADB shell may call it. -->
+ <provider
+ android:name=".ConfigProvider"
+ android:authorities="${applicationId}.config"
+ android:exported="true"
+ android:permission="android.permission.WRITE_SECURE_SETTINGS" />
+ </application>
+</manifest>
diff --git a/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/Config.java b/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/Config.java
new file mode 100644
index 000000000..e2aa69aed
--- /dev/null
+++ b/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/Config.java
@@ -0,0 +1,65 @@
+package io.github.maxhayim.smarthome;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+
+import org.json.JSONObject;
+
+import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+
+/**
+ * The server address and token, in the app's own storage (backups are off). They arrive typed on the TV, or as
+ * config.json pushed by install.sh, which is read once and deleted.
+ */
+final class Config {
+ static final String PUSHED = "config.json";
+
+ final String url;
+ final String token;
+
+ Config(String url, String token) {
+ this.url = url;
+ this.token = token;
+ }
+
+ boolean complete() {
+ return !url.isEmpty() && !token.isEmpty();
+ }
+
+ private static SharedPreferences prefs(Context c) {
+ return c.getSharedPreferences("server", Context.MODE_PRIVATE);
+ }
+
+ static Config load(Context c) {
+ SharedPreferences p = prefs(c);
+ return new Config(p.getString("url", ""), p.getString("token", ""));
+ }
+
+ static void saveUrl(Context c, String url) {
+ prefs(c).edit().putString("url", Ha.normalizeUrl(url)).apply();
+ }
+
+ static void saveToken(Context c, String token) {
+ prefs(c).edit().putString("token", token == null ? "" : token.trim()).apply();
+ }
+
+ /** Takes a pushed config.json ({"url": ..., "token": ...}) if there is one, and deletes it. True when taken. */
+ static boolean importPushed(Context c) {
+ File dir = c.getExternalFilesDir(null);
+ File f = dir == null ? null : new File(dir, PUSHED);
+ if (f == null || !f.isFile()) return false;
+ try {
+ JSONObject o = new JSONObject(new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8));
+ if (o.has("url")) saveUrl(c, o.optString("url"));
+ if (o.has("token")) saveToken(c, o.optString("token"));
+ return true;
+ } catch (Exception e) {
+ return false;
+ } finally {
+ //noinspection ResultOfMethodCallIgnored
+ f.delete();
+ }
+ }
+}
diff --git a/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/ConfigProvider.java b/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/ConfigProvider.java
new file mode 100644
index 000000000..c44dd2d37
--- /dev/null
+++ b/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/ConfigProvider.java
@@ -0,0 +1,41 @@
+package io.github.maxhayim.smarthome;
+
+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;
+
+/**
+ * install.sh writes config.json here with `content write`, so the token travels as a file, never on a command
+ * line. Write-only, one file name, and only the ADB shell can call it (WRITE_SECURE_SETTINGS on the provider).
+ * The file is taken into the app's storage and deleted once it is closed.
+ */
+public class ConfigProvider extends ContentProvider {
+ @Override
+ public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
+ if (!mode.contains("w") || !Config.PUSHED.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, Config.PUSHED),
+ ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE,
+ new Handler(Looper.getMainLooper()),
+ e -> Config.importPushed(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/smart-home/app/src/main/java/io/github/maxhayim/smarthome/Ha.java b/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/Ha.java
new file mode 100644
index 000000000..0a0c78c72
--- /dev/null
+++ b/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/Ha.java
@@ -0,0 +1,218 @@
+package io.github.maxhayim.smarthome;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * Home Assistant's REST API (https://developers.home-assistant.io/docs/api/rest): what GET /api/states returns,
+ * turned into the rows this app shows, and the service calls its buttons make. No Android types and no network,
+ * so the JVM tests cover it against the documented responses.
+ */
+final class Ha {
+ /** At most this many rows, so a large installation can't make the screen slow. */
+ static final int MAX_ENTITIES = 80;
+
+ enum Kind { SCENE, TOGGLE, CLIMATE, SENSOR, OPENING, LOCK }
+
+ static final class Entity {
+ final String id;
+ final Kind kind;
+ final String name;
+ final String state;
+ /** Lights: 0 to 100, or -1. */
+ final int brightness;
+ final double current;
+ final double target;
+ final String unit;
+
+ Entity(String id, Kind kind, String name, String state, int brightness, double current, double target, String unit) {
+ this.id = id;
+ this.kind = kind;
+ this.name = name;
+ this.state = state;
+ this.brightness = brightness;
+ this.current = current;
+ this.target = target;
+ this.unit = unit;
+ }
+
+ String domain() {
+ int dot = id.indexOf('.');
+ return dot < 0 ? "" : id.substring(0, dot);
+ }
+
+ boolean available() {
+ return !"unavailable".equals(state) && !"unknown".equals(state);
+ }
+
+ /** What the row shows on the right. */
+ String value() {
+ if (!available()) return "Unavailable";
+ switch (kind) {
+ case SCENE:
+ return "Run";
+ case TOGGLE:
+ boolean on = "on".equals(state);
+ return on && brightness >= 0 ? "On · " + brightness + " %" : on ? "On" : "Off";
+ case CLIMATE:
+ String now = Double.isNaN(current) ? "" : number(current) + unit;
+ String set = Double.isNaN(target) ? "" : number(target) + unit;
+ return now.isEmpty() ? set : set.isEmpty() ? now : now + " → " + set;
+ case SENSOR:
+ try {
+ return number(Double.parseDouble(state)) + (unit.isEmpty() ? "" : " " + unit).replace(" °", "°");
+ } catch (NumberFormatException e) {
+ return state;
+ }
+ case OPENING:
+ return "on".equals(state) ? "Open" : "Closed";
+ case LOCK:
+ return "locked".equals(state) ? "Locked" : "unlocked".equals(state) ? "Unlocked" : capital(state);
+ default:
+ return state;
+ }
+ }
+ }
+
+ /** One service call: POST path with body. */
+ static final class Call {
+ final String path;
+ final String body;
+
+ Call(String path, String body) {
+ this.path = path;
+ this.body = body;
+ }
+ }
+
+ private Ha() {
+ }
+
+ /** The rows, sorted into sections (scenes, lights and switches, climate, sensors, doors and windows, locks). */
+ static List<Entity> parse(String json) throws JSONException {
+ JSONArray all = new JSONArray(json);
+ List<Entity> out = new ArrayList<>();
+ for (int i = 0; i < all.length(); i++) {
+ JSONObject o = all.optJSONObject(i);
+ if (o == null) continue;
+ Entity e = entity(o);
+ if (e != null) out.add(e);
+ }
+ out.sort((a, b) -> a.kind != b.kind ? a.kind.compareTo(b.kind) : a.name.compareToIgnoreCase(b.name));
+ return out.size() > MAX_ENTITIES ? new ArrayList<>(out.subList(0, MAX_ENTITIES)) : out;
+ }
+
+ static Entity entity(JSONObject o) {
+ String id = o.optString("entity_id", "");
+ String state = o.optString("state", "");
+ JSONObject a = o.optJSONObject("attributes");
+ if (a == null) a = new JSONObject();
+ int dot = id.indexOf('.');
+ if (dot <= 0) return null;
+ String domain = id.substring(0, dot);
+ String name = a.optString("friendly_name", id.substring(dot + 1).replace('_', ' '));
+ String deviceClass = a.optString("device_class", "");
+ String unit = a.optString("unit_of_measurement", "");
+ switch (domain) {
+ case "scene":
+ return new Entity(id, Kind.SCENE, name, state, -1, Double.NaN, Double.NaN, "");
+ case "light":
+ int b = a.has("brightness") && !a.isNull("brightness") ? (int) Math.round(a.optDouble("brightness", 0) * 100 / 255) : -1;
+ return new Entity(id, Kind.TOGGLE, name, state, b, Double.NaN, Double.NaN, "");
+ case "switch":
+ case "fan":
+ case "input_boolean":
+ return new Entity(id, Kind.TOGGLE, name, state, -1, Double.NaN, Double.NaN, "");
+ case "climate":
+ return new Entity(id, Kind.CLIMATE, name, state, -1, a.optDouble("current_temperature", Double.NaN),
+ a.optDouble("temperature", Double.NaN), "°");
+ case "sensor":
+ if (!deviceClass.equals("temperature") && !deviceClass.equals("humidity")) return null;
+ return new Entity(id, Kind.SENSOR, name, state, -1, Double.NaN, Double.NaN, unit);
+ case "binary_sensor":
+ if (!deviceClass.equals("door") && !deviceClass.equals("window") && !deviceClass.equals("garage_door")
+ && !deviceClass.equals("opening")) return null;
+ return new Entity(id, Kind.OPENING, name, state, -1, Double.NaN, Double.NaN, "");
+ case "lock":
+ return new Entity(id, Kind.LOCK, name, state, -1, Double.NaN, Double.NaN, "");
+ default:
+ return null;
+ }
+ }
+
+ /** OK on a row; null when the row does nothing (sensors, and locks: a TV remote never unlocks a door). */
+ static Call press(Entity e) {
+ if (!e.available()) return null;
+ switch (e.kind) {
+ case SCENE:
+ return call("scene", "turn_on", e.id, null);
+ case TOGGLE:
+ return call("homeassistant", "toggle", e.id, null);
+ default:
+ return null;
+ }
+ }
+
+ /** Left (-1) or Right (+1) on a row: dims a light by 10 %, or moves a thermostat by half a degree. */
+ static Call step(Entity e, int direction) {
+ if (!e.available()) return null;
+ if (e.kind == Kind.TOGGLE && e.domain().equals("light")) {
+ return call("light", "turn_on", e.id, "\"brightness_step_pct\":" + (direction * 10));
+ }
+ if (e.kind == Kind.CLIMATE && !Double.isNaN(e.target)) {
+ return call("climate", "set_temperature", e.id, "\"temperature\":" + number(e.target + direction * 0.5));
+ }
+ return null;
+ }
+
+ private static Call call(String domain, String service, String entity, String extra) {
+ String body = "{\"entity_id\":" + JSONObject.quote(entity) + (extra == null ? "" : "," + extra) + "}";
+ return new Call("/api/services/" + domain + "/" + service, body);
+ }
+
+ static String section(Kind k) {
+ switch (k) {
+ case SCENE: return "Scenes";
+ case TOGGLE: return "Lights and switches";
+ case CLIMATE: return "Climate";
+ case SENSOR: return "Sensors";
+ case OPENING: return "Doors and windows";
+ default: return "Locks";
+ }
+ }
+
+ /** "http://192.168.1.10:8123" from what was typed: a scheme added when missing, trailing slashes dropped. */
+ static String normalizeUrl(String typed) {
+ if (typed == null) return "";
+ String u = typed.trim();
+ if (u.isEmpty()) return "";
+ if (!u.contains("://")) u = "http://" + u;
+ while (u.endsWith("/")) u = u.substring(0, u.length() - 1);
+ return u;
+ }
+
+ static boolean validUrl(String url) {
+ return url.matches("https?://[^\\s/?#]+(:[0-9]{1,5})?(/[^\\s?#]*)?");
+ }
+
+ /** What a failed request means for the person in front of the TV. */
+ static String problem(int code) {
+ if (code == 401 || code == 403) return "Home Assistant refused the access token.";
+ if (code == 404) return "That address answers, but it isn't Home Assistant's API.";
+ if (code <= 0) return "Can't reach Home Assistant at that address.";
+ return "Home Assistant answered with error " + code + ".";
+ }
+
+ static String number(double v) {
+ return v == Math.rint(v) ? String.valueOf((long) v) : String.format(Locale.ROOT, "%.1f", v);
+ }
+
+ private static String capital(String s) {
+ return s.isEmpty() ? s : Character.toUpperCase(s.charAt(0)) + s.substring(1);
+ }
+}
diff --git a/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/HaClient.java b/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/HaClient.java
new file mode 100644
index 000000000..e07b54c09
--- /dev/null
+++ b/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/HaClient.java
@@ -0,0 +1,88 @@
+package io.github.maxhayim.smarthome;
+
+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.nio.charset.StandardCharsets;
+
+/** Plain HTTP to Home Assistant with the owner's long-lived access token. Blocking: call it off the main thread. */
+final class HaClient {
+ /** Status code (0 when the server couldn't be reached) and the body. */
+ static final class Reply {
+ final int code;
+ final String body;
+
+ Reply(int code, String body) {
+ this.code = code;
+ this.body = body;
+ }
+
+ boolean ok() {
+ return code >= 200 && code < 300;
+ }
+ }
+
+ private static final int TIMEOUT_MS = 6000;
+ /** Larger answers are cut off: /api/states on a big installation is still well under this. */
+ private static final int MAX_BODY = 4 * 1024 * 1024;
+
+ private final String base;
+ private final String token;
+
+ HaClient(String base, String token) {
+ this.base = base;
+ this.token = token;
+ }
+
+ Reply get(String path) {
+ return request("GET", path, null);
+ }
+
+ Reply post(String path, String body) {
+ return request("POST", path, body);
+ }
+
+ private Reply request(String method, String path, String body) {
+ HttpURLConnection c = null;
+ try {
+ c = (HttpURLConnection) new URL(base + path).openConnection();
+ c.setRequestMethod(method);
+ c.setConnectTimeout(TIMEOUT_MS);
+ c.setReadTimeout(TIMEOUT_MS);
+ c.setInstanceFollowRedirects(false);
+ c.setRequestProperty("Authorization", "Bearer " + token);
+ c.setRequestProperty("Accept", "application/json");
+ if (body != null) {
+ c.setDoOutput(true);
+ c.setRequestProperty("Content-Type", "application/json");
+ byte[] b = body.getBytes(StandardCharsets.UTF_8);
+ c.setFixedLengthStreamingMode(b.length);
+ try (OutputStream out = c.getOutputStream()) {
+ out.write(b);
+ }
+ }
+ int code = c.getResponseCode();
+ InputStream in = code >= 400 ? c.getErrorStream() : c.getInputStream();
+ return new Reply(code, in == null ? "" : read(in));
+ } catch (IOException | RuntimeException e) {
+ return new Reply(0, String.valueOf(e.getMessage()));
+ } finally {
+ if (c != null) c.disconnect();
+ }
+ }
+
+ private static String read(InputStream in) throws IOException {
+ try (InputStream s = in) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ byte[] buf = new byte[16384];
+ for (int n; (n = s.read(buf)) > 0; ) {
+ out.write(buf, 0, n);
+ if (out.size() > MAX_BODY) break;
+ }
+ return out.toString(StandardCharsets.UTF_8.name());
+ }
+ }
+}
diff --git a/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/MainActivity.java b/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/MainActivity.java
new file mode 100644
index 000000000..502f7875a
--- /dev/null
+++ b/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/MainActivity.java
@@ -0,0 +1,242 @@
+package io.github.maxhayim.smarthome;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.text.InputType;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+import org.json.JSONException;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+/**
+ * The tile and module card open this: your Home Assistant's scenes, lights and switches, climate, sensors, doors
+ * and windows, and locks, in sections. OK runs a scene or switches a light; Left and Right dim a light or move a
+ * thermostat. Locks are shown, never opened. It reads Home Assistant only while this screen is open.
+ */
+public class MainActivity extends Activity {
+ private static final long REFRESH_MS = 10_000;
+
+ private final Handler main = new Handler(Looper.getMainLooper());
+ private final ExecutorService net = Executors.newSingleThreadExecutor();
+ private LinearLayout rows;
+ private TextView status;
+ private Config config;
+ private List<Ha.Entity> entities = new ArrayList<>();
+ private String problem;
+ private final Runnable refresh = new Runnable() {
+ @Override
+ public void run() {
+ load();
+ main.postDelayed(this, REFRESH_MS);
+ }
+ };
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ 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);
+ ScrollView scroll = new ScrollView(this);
+ rows = new LinearLayout(this);
+ rows.setOrientation(LinearLayout.VERTICAL);
+ scroll.addView(rows);
+ page.addView(scroll, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f));
+ setContentView(page);
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ Config.importPushed(this);
+ config = Config.load(this);
+ build();
+ if (config.complete()) main.post(refresh);
+ }
+
+ @Override
+ protected void onPause() {
+ main.removeCallbacks(refresh);
+ super.onPause();
+ }
+
+ @Override
+ protected void onDestroy() {
+ net.shutdownNow();
+ super.onDestroy();
+ }
+
+ private void load() {
+ Config c = config;
+ net.execute(() -> {
+ HaClient.Reply r = new HaClient(c.url, c.token).get("/api/states");
+ List<Ha.Entity> found = null;
+ String why = null;
+ if (r.ok()) {
+ try {
+ found = Ha.parse(r.body);
+ } catch (JSONException e) {
+ why = "Home Assistant's answer couldn't be read.";
+ }
+ } else {
+ why = Ha.problem(r.code);
+ }
+ List<Ha.Entity> f = found;
+ String w = why;
+ main.post(() -> {
+ if (isFinishing()) return;
+ problem = w;
+ if (f != null) entities = f;
+ build();
+ });
+ });
+ }
+
+ private void send(Ha.Call call) {
+ if (call == null) return;
+ Config c = config;
+ net.execute(() -> {
+ HaClient.Reply r = new HaClient(c.url, c.token).post(call.path, call.body);
+ main.post(() -> {
+ if (!r.ok()) status.setText(Ha.problem(r.code));
+ main.postDelayed(this::load, 600);
+ });
+ });
+ }
+
+ /** Rebuilds the list; focus stays on the row it was on. */
+ private void build() {
+ int focused = rows.indexOfChild(rows.getFocusedChild());
+ rows.removeAllViews();
+ if (!config.complete()) {
+ status.setText("Add your Home Assistant's address and a long-lived access token (your profile page in"
+ + " Home Assistant, under Security).");
+ } else if (problem != null) {
+ status.setText(problem);
+ } else {
+ status.setText(entities.isEmpty() ? "Reading Home Assistant…" : "Connected to " + config.url + ".");
+ }
+ Ha.Kind section = null;
+ for (Ha.Entity e : entities) {
+ if (e.kind != section) {
+ section = e.kind;
+ heading(Ha.section(section));
+ }
+ Ha.Call press = Ha.press(e);
+ boolean steps = Ha.step(e, 1) != null;
+ boolean bar = e.kind == Ha.Kind.TOGGLE && e.brightness >= 0;
+ Row r = add(new Row(this, e.name, null, bar, press == null ? null : () -> send(Ha.press(e)),
+ steps ? d -> send(Ha.step(e, d)) : null));
+ r.setValue(e.value());
+ if (bar) r.setBar("on".equals(e.state) ? e.brightness / 100f : 0f);
+ if (!e.available()) r.setAlpha(0.5f);
+ if (e.kind == Ha.Kind.LOCK) r.setDetail("Shown only: locks aren't opened from the TV.");
+ }
+ heading("Connection");
+ Row url = add(new Row(this, "Home Assistant address", "For example http://192.168.1.10:8123", false,
+ this::editUrl, null));
+ url.setValue(config.url.isEmpty() ? "Not set" : config.url);
+ Row token = add(new Row(this, "Access token", "Stored on this TV only.", false, this::editToken, null));
+ token.setValue(config.token.isEmpty() ? "Not set" : "Set");
+
+ View keep = focused >= 0 && focused < rows.getChildCount() ? rows.getChildAt(focused) : null;
+ if (keep != null && keep.isFocusable()) keep.requestFocus();
+ else if (!config.complete()) url.requestFocus();
+ else for (int i = 0; i < rows.getChildCount(); i++) {
+ if (rows.getChildAt(i).isFocusable()) {
+ rows.getChildAt(i).requestFocus();
+ break;
+ }
+ }
+ }
+
+ private void editUrl() {
+ edit("Home Assistant address", config.url.isEmpty() ? "http://" : config.url,
+ InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI, v -> {
+ String u = Ha.normalizeUrl(v);
+ if (!u.isEmpty() && !Ha.validUrl(u)) {
+ status.setText("That doesn't look like an address: " + u);
+ return;
+ }
+ Config.saveUrl(this, u);
+ reload();
+ });
+ }
+
+ private void editToken() {
+ edit("Access token", "", InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD, v -> {
+ if (v.trim().isEmpty()) return;
+ Config.saveToken(this, v);
+ reload();
+ });
+ }
+
+ private void reload() {
+ config = Config.load(this);
+ problem = null;
+ entities = new ArrayList<>();
+ main.removeCallbacks(refresh);
+ build();
+ if (config.complete()) main.post(refresh);
+ }
+
+ private interface Done {
+ void done(String value);
+ }
+
+ private void edit(String title, String start, int type, Done done) {
+ EditText field = new EditText(this);
+ field.setInputType(type);
+ field.setSingleLine(true);
+ field.setText(start);
+ field.setSelection(start.length());
+ new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Dialog_Alert)
+ .setTitle(title)
+ .setView(field)
+ .setPositiveButton("Save", (d, w) -> done.done(field.getText().toString()))
+ .setNegativeButton("Cancel", null)
+ .show();
+ field.requestFocus();
+ }
+
+ private void heading(String text) {
+ TextView h = new TextView(this);
+ h.setText(text);
+ h.setTextSize(13);
+ h.setTextColor(0xFF41BDF5);
+ h.setPadding(px(16), px(18), 0, px(4));
+ rows.addView(h);
+ }
+
+ private Row add(Row r) {
+ rows.addView(r, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
+ return r;
+ }
+
+ private int px(int dp) {
+ return Math.round(dp * getResources().getDisplayMetrics().density);
+ }
+}
diff --git a/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/Row.java b/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/Row.java
new file mode 100644
index 000000000..31b2940e7
--- /dev/null
+++ b/addons/smart-home/app/src/main/java/io/github/maxhayim/smarthome/Row.java
@@ -0,0 +1,103 @@
+package io.github.maxhayim.smarthome;
+
+import android.content.Context;
+import android.view.Gravity;
+import android.view.KeyEvent;
+import android.view.View;
+import android.widget.FrameLayout;
+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 onClick;
+ * Left and Right run onStep with -1 or +1, held keys repeat. A row with a bar draws its value as a slider.
+ */
+final class Row extends LinearLayout {
+ interface Step {
+ void step(int direction);
+ }
+
+ private final TextView value;
+ private final TextView desc;
+ private final View fill;
+ private final View rest;
+
+ Row(Context context, String name, String description, boolean bar, Runnable onClick, Step onStep) {
+ 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);
+ boolean active = onClick != null || onStep != null;
+ setFocusable(active);
+ setClickable(onClick != null);
+ if (onClick != null) setOnClickListener(v -> onClick.run());
+ if (onStep != null) {
+ setOnKeyListener((v, code, e) -> {
+ if (code != KeyEvent.KEYCODE_DPAD_LEFT && code != KeyEvent.KEYCODE_DPAD_RIGHT) return false;
+ if (e.getAction() == KeyEvent.ACTION_DOWN) onStep.step(code == KeyEvent.KEYCODE_DPAD_LEFT ? -1 : 1);
+ return true;
+ });
+ }
+
+ 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));
+
+ if (bar) {
+ LinearLayout track = new LinearLayout(context);
+ track.setOrientation(HORIZONTAL);
+ track.setBackgroundColor(0x33FFFFFF);
+ fill = new View(context);
+ fill.setBackgroundColor(0xFF41BDF5);
+ rest = new View(context);
+ track.addView(fill, new LayoutParams(0, LayoutParams.MATCH_PARENT, 0f));
+ track.addView(rest, new LayoutParams(0, LayoutParams.MATCH_PARENT, 1f));
+ FrameLayout holder = new FrameLayout(context);
+ holder.addView(track, new FrameLayout.LayoutParams(Math.round(200 * dp), Math.round(6 * dp), Gravity.CENTER_VERTICAL));
+ LayoutParams hp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
+ hp.rightMargin = Math.round(16 * dp);
+ addView(holder, hp);
+ } else {
+ fill = rest = null;
+ }
+
+ value = new TextView(context);
+ value.setTextSize(17);
+ value.setTextColor(0xFFC9D1D9);
+ value.setGravity(Gravity.END);
+ value.setMinWidth(Math.round(90 * dp));
+ addView(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);
+ }
+
+ /** The slider's position, 0 to 1. */
+ void setBar(float fraction) {
+ if (fill == null) return;
+ float f = Math.max(0f, Math.min(1f, fraction));
+ ((LayoutParams) fill.getLayoutParams()).weight = f;
+ ((LayoutParams) rest.getLayoutParams()).weight = 1f - f;
+ fill.requestLayout();
+ }
+}
diff --git a/addons/smart-home/app/src/main/res/drawable/banner.xml b/addons/smart-home/app/src/main/res/drawable/banner.xml
new file mode 100644
index 000000000..a4a493b77
--- /dev/null
+++ b/addons/smart-home/app/src/main/res/drawable/banner.xml
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 16:9 banner: a house with a lit bulb and a thermometer. 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:strokeColor="#41BDF5" android:strokeWidth="8" android:fillColor="#00000000" android:pathData="M100,90l60,-50l60,50v54h-120z" />
+ <path android:fillColor="#FFD54F" android:pathData="M160,82a16,16 0 1 1 -0.1,0zM152,112h16v10h-16z" />
+ <path android:fillColor="#FFFFFF" android:pathData="M244,60h10v56h-10zM249,128a10,10 0 1 1 -0.1,0z" />
+</vector>
diff --git a/addons/smart-home/app/src/main/res/drawable/ic_foreground.xml b/addons/smart-home/app/src/main/res/drawable/ic_foreground.xml
new file mode 100644
index 000000000..82ffb5fd8
--- /dev/null
+++ b/addons/smart-home/app/src/main/res/drawable/ic_foreground.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- A house inside the adaptive icon's safe zone. Own art. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp" android:height="108dp"
+ android:viewportWidth="108" android:viewportHeight="108">
+ <path android:strokeColor="#41BDF5" android:strokeWidth="4" android:fillColor="#00000000" android:pathData="M38,56l16,-14l16,14v16h-32z" />
+ <path android:fillColor="#FFD54F" android:pathData="M54,56a5,5 0 1 1 -0.1,0z" />
+</vector>
diff --git a/addons/smart-home/app/src/main/res/drawable/row_background.xml b/addons/smart-home/app/src/main/res/drawable/row_background.xml
new file mode 100644
index 000000000..03ccab9f5
--- /dev/null
+++ b/addons/smart-home/app/src/main/res/drawable/row_background.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- A settings row: transparent until focused, then a glass highlight like the launcher's. -->
+<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>
+ <item>
+ <shape android:shape="rectangle">
+ <solid android:color="#00000000" />
+ <corners android:radius="12dp" />
+ </shape>
+ </item>
+</selector>
diff --git a/addons/smart-home/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/addons/smart-home/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 000000000..0a99b20b1
--- /dev/null
+++ b/addons/smart-home/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/smart-home/app/src/main/res/values/strings.xml b/addons/smart-home/app/src/main/res/values/strings.xml
new file mode 100644
index 000000000..be9775f89
--- /dev/null
+++ b/addons/smart-home/app/src/main/res/values/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Smart Home</string>
+</resources>
diff --git a/addons/smart-home/app/src/main/res/xml/module_card.xml b/addons/smart-home/app/src/main/res/xml/module_card.xml
new file mode 100644
index 000000000..3f637b3ed
--- /dev/null
+++ b/addons/smart-home/app/src/main/res/xml/module_card.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="utf-8"?>
+<card spec="1" label="Smart Home" caption="Lights" accent="#41BDF5" />
diff --git a/addons/smart-home/app/src/main/res/xml/network.xml b/addons/smart-home/app/src/main/res/xml/network.xml
new file mode 100644
index 000000000..b00295a71
--- /dev/null
+++ b/addons/smart-home/app/src/main/res/xml/network.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Home Assistant often runs at http://<ip>:8123 on the home network, so plain HTTP is allowed. Use https:// when
+ the server has a certificate (Nabu Casa, Let's Encrypt). -->
+<network-security-config>
+ <base-config cleartextTrafficPermitted="true" />
+</network-security-config>
diff --git a/addons/smart-home/app/src/test/java/io/github/maxhayim/smarthome/HaClientTest.java b/addons/smart-home/app/src/test/java/io/github/maxhayim/smarthome/HaClientTest.java
new file mode 100644
index 000000000..bde85c590
--- /dev/null
+++ b/addons/smart-home/app/src/test/java/io/github/maxhayim/smarthome/HaClientTest.java
@@ -0,0 +1,104 @@
+package io.github.maxhayim.smarthome;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.BufferedReader;
+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.concurrent.atomic.AtomicReference;
+
+/** The requests as Home Assistant's REST API expects them, against a stand-in server on this machine. */
+public class HaClientTest {
+ private ServerSocket server;
+ private Thread loop;
+ private final AtomicReference<String> auth = new AtomicReference<>(), body = new AtomicReference<>(),
+ type = new AtomicReference<>();
+
+ /** A one-request-at-a-time HTTP/1.1 stand-in: enough for HttpURLConnection, nothing more. */
+ @Before
+ public void start() throws Exception {
+ server = new ServerSocket(0, 5, InetAddress.getByName("127.0.0.1"));
+ loop = new Thread(() -> {
+ while (!server.isClosed()) {
+ try (Socket s = server.accept()) {
+ BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), StandardCharsets.UTF_8));
+ in.readLine();
+ int length = 0;
+ String a = null, ct = null;
+ for (String h; (h = in.readLine()) != null && !h.isEmpty(); ) {
+ String lower = h.toLowerCase();
+ if (lower.startsWith("authorization:")) a = h.substring(14).trim();
+ if (lower.startsWith("content-type:")) ct = h.substring(13).trim();
+ if (lower.startsWith("content-length:")) length = Integer.parseInt(h.substring(15).trim());
+ }
+ char[] b = new char[length];
+ for (int n = 0; n < length; ) n += in.read(b, n, length - n);
+ auth.set(a);
+ type.set(ct);
+ body.set(new String(b));
+ boolean ok = "Bearer good".equals(a);
+ byte[] out = (ok ? HaTest.STATES : "{\"message\":\"401: Unauthorized\"}").getBytes(StandardCharsets.UTF_8);
+ OutputStream o = s.getOutputStream();
+ o.write(("HTTP/1.1 " + (ok ? "200 OK" : "401 Unauthorized") + "\r\nContent-Type: application/json\r\n"
+ + "Content-Length: " + out.length + "\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.UTF_8));
+ o.write(out);
+ o.flush();
+ } catch (Exception ignored) {
+ // Closed by stop(), or a test's dropped connection.
+ }
+ }
+ });
+ loop.start();
+ }
+
+ @After
+ public void stop() throws Exception {
+ server.close();
+ loop.join(2000);
+ }
+
+ private String base() {
+ return "http://127.0.0.1:" + server.getLocalPort();
+ }
+
+ @Test
+ public void readsStatesWithTheToken() throws Exception {
+ HaClient.Reply r = new HaClient(base(), "good").get("/api/states");
+ assertEquals(200, r.code);
+ assertEquals("Bearer good", auth.get());
+ assertEquals(10, Ha.parse(r.body).size());
+ }
+
+ @Test
+ public void postsServiceCallsAsJson() {
+ HaClient.Reply r = new HaClient(base(), "good").post("/api/services/scene/turn_on", "{\"entity_id\":\"scene.good_night\"}");
+ assertTrue(r.ok());
+ assertEquals("application/json", type.get());
+ assertEquals("{\"entity_id\":\"scene.good_night\"}", body.get());
+ }
+
+ @Test
+ public void aRefusedTokenIsReported() {
+ HaClient.Reply r = new HaClient(base(), "bad").get("/api/states");
+ assertEquals(401, r.code);
+ assertTrue(Ha.problem(r.code).contains("token"));
+ }
+
+ @Test
+ public void anUnreachableServerIsCodeZero() throws Exception {
+ String gone = base();
+ stop();
+ assertEquals(0, new HaClient(gone, "good").get("/api/states").code);
+ }
+
+
+}
diff --git a/addons/smart-home/app/src/test/java/io/github/maxhayim/smarthome/HaTest.java b/addons/smart-home/app/src/test/java/io/github/maxhayim/smarthome/HaTest.java
new file mode 100644
index 000000000..ce03f12d5
--- /dev/null
+++ b/addons/smart-home/app/src/test/java/io/github/maxhayim/smarthome/HaTest.java
@@ -0,0 +1,113 @@
+package io.github.maxhayim.smarthome;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+import java.util.List;
+
+/** Against the shapes Home Assistant's REST API documents for GET /api/states and the service calls. */
+public class HaTest {
+ // The documented example, plus one entity of each kind this app shows, as Home Assistant reports them.
+ static final String STATES = "["
+ + "{\"attributes\":{},\"entity_id\":\"sun.sun\",\"last_changed\":\"2016-05-30T21:43:32.418320+00:00\",\"state\":\"below_horizon\"},"
+ + "{\"attributes\":{},\"entity_id\":\"process.Dropbox\",\"last_changed\":\"22016-05-30T21:43:32.418320+00:00\",\"state\":\"on\"},"
+ + "{\"entity_id\":\"light.living_room\",\"state\":\"on\",\"attributes\":{\"friendly_name\":\"Living room\",\"brightness\":153}},"
+ + "{\"entity_id\":\"light.hall\",\"state\":\"off\",\"attributes\":{\"friendly_name\":\"Hall\",\"brightness\":null}},"
+ + "{\"entity_id\":\"switch.fan_plug\",\"state\":\"off\",\"attributes\":{\"friendly_name\":\"Fan plug\"}},"
+ + "{\"entity_id\":\"scene.good_night\",\"state\":\"2026-10-22T21:00:00+00:00\",\"attributes\":{\"friendly_name\":\"Good night\"}},"
+ + "{\"entity_id\":\"climate.nursery\",\"state\":\"heat\",\"attributes\":{\"friendly_name\":\"Nursery\",\"current_temperature\":21.4,\"temperature\":22}},"
+ + "{\"entity_id\":\"sensor.nursery_temperature\",\"state\":\"21.43\",\"attributes\":{\"friendly_name\":\"Nursery temperature\",\"device_class\":\"temperature\",\"unit_of_measurement\":\"°C\"}},"
+ + "{\"entity_id\":\"sensor.nursery_humidity\",\"state\":\"48\",\"attributes\":{\"friendly_name\":\"Nursery humidity\",\"device_class\":\"humidity\",\"unit_of_measurement\":\"%\"}},"
+ + "{\"entity_id\":\"sensor.power\",\"state\":\"120\",\"attributes\":{\"device_class\":\"power\",\"unit_of_measurement\":\"W\"}},"
+ + "{\"entity_id\":\"binary_sensor.front_door\",\"state\":\"off\",\"attributes\":{\"friendly_name\":\"Front door\",\"device_class\":\"door\"}},"
+ + "{\"entity_id\":\"binary_sensor.motion\",\"state\":\"on\",\"attributes\":{\"device_class\":\"motion\"}},"
+ + "{\"entity_id\":\"lock.front_door\",\"state\":\"locked\",\"attributes\":{\"friendly_name\":\"Front door lock\"}},"
+ + "{\"entity_id\":\"light.garage\",\"state\":\"unavailable\",\"attributes\":{\"friendly_name\":\"Garage\"}}"
+ + "]";
+
+ private static Ha.Entity find(List<Ha.Entity> all, String id) {
+ for (Ha.Entity e : all) if (e.id.equals(id)) return e;
+ return null;
+ }
+
+ @Test
+ public void keepsOnlyWhatTheScreenShowsInSections() throws Exception {
+ List<Ha.Entity> all = Ha.parse(STATES);
+ assertNull(find(all, "sun.sun"));
+ assertNull(find(all, "sensor.power"));
+ assertNull(find(all, "binary_sensor.motion"));
+ assertEquals(Ha.Kind.SCENE, all.get(0).kind);
+ assertEquals(Ha.Kind.LOCK, all.get(all.size() - 1).kind);
+ assertEquals(10, all.size());
+ }
+
+ @Test
+ public void values() throws Exception {
+ List<Ha.Entity> all = Ha.parse(STATES);
+ assertEquals("On · 60 %", find(all, "light.living_room").value());
+ assertEquals("Off", find(all, "light.hall").value());
+ assertEquals("21.4° → 22°", find(all, "climate.nursery").value());
+ assertEquals("21.4°C", find(all, "sensor.nursery_temperature").value());
+ assertEquals("48 %", find(all, "sensor.nursery_humidity").value());
+ assertEquals("Closed", find(all, "binary_sensor.front_door").value());
+ assertEquals("Locked", find(all, "lock.front_door").value());
+ assertEquals("Unavailable", find(all, "light.garage").value());
+ assertEquals("Run", find(all, "scene.good_night").value());
+ }
+
+ @Test
+ public void serviceCalls() throws Exception {
+ List<Ha.Entity> all = Ha.parse(STATES);
+ Ha.Call scene = Ha.press(find(all, "scene.good_night"));
+ assertEquals("/api/services/scene/turn_on", scene.path);
+ assertEquals("{\"entity_id\":\"scene.good_night\"}", scene.body);
+ assertEquals("/api/services/homeassistant/toggle", Ha.press(find(all, "switch.fan_plug")).path);
+ Ha.Call dim = Ha.step(find(all, "light.living_room"), -1);
+ assertEquals("/api/services/light/turn_on", dim.path);
+ assertEquals("{\"entity_id\":\"light.living_room\",\"brightness_step_pct\":-10}", dim.body);
+ Ha.Call warmer = Ha.step(find(all, "climate.nursery"), 1);
+ assertEquals("/api/services/climate/set_temperature", warmer.path);
+ assertEquals("{\"entity_id\":\"climate.nursery\",\"temperature\":22.5}", warmer.body);
+ }
+
+ @Test
+ public void sensorsLocksAndUnavailableDoNothing() throws Exception {
+ List<Ha.Entity> all = Ha.parse(STATES);
+ assertNull("a TV remote never unlocks a door", Ha.press(find(all, "lock.front_door")));
+ assertNull(Ha.step(find(all, "lock.front_door"), 1));
+ assertNull(Ha.press(find(all, "sensor.nursery_temperature")));
+ assertNull(Ha.press(find(all, "light.garage")));
+ assertNull("switches don't dim", Ha.step(find(all, "switch.fan_plug"), 1));
+ }
+
+ @Test
+ public void bigInstallationsAreCapped() throws Exception {
+ StringBuilder b = new StringBuilder("[");
+ for (int i = 0; i < 200; i++) {
+ if (i > 0) b.append(',');
+ b.append("{\"entity_id\":\"switch.s").append(i).append("\",\"state\":\"off\",\"attributes\":{}}");
+ }
+ assertEquals(Ha.MAX_ENTITIES, Ha.parse(b.append(']').toString()).size());
+ }
+
+ @Test
+ public void addresses() {
+ assertEquals("http://192.168.1.10:8123", Ha.normalizeUrl(" 192.168.1.10:8123/ "));
+ assertEquals("https://ha.example.com", Ha.normalizeUrl("https://ha.example.com//"));
+ assertTrue(Ha.validUrl("http://192.168.1.10:8123"));
+ assertTrue(Ha.validUrl("https://abc.ui.nabu.casa"));
+ assertFalse(Ha.validUrl("http://"));
+ assertFalse(Ha.validUrl("http://a b"));
+ }
+
+ @Test
+ public void problems() {
+ assertTrue(Ha.problem(401).contains("token"));
+ assertTrue(Ha.problem(0).contains("Can't reach"));
+ assertTrue(Ha.problem(404).contains("isn't"));
+ }
+}
diff --git a/addons/smart-home/build.gradle b/addons/smart-home/build.gradle
new file mode 100644
index 000000000..48978475f
--- /dev/null
+++ b/addons/smart-home/build.gradle
@@ -0,0 +1,3 @@
+plugins {
+ id 'com.android.application' version '8.5.2' apply false
+}
diff --git a/addons/smart-home/gradle.properties b/addons/smart-home/gradle.properties
new file mode 100644
index 000000000..18825f968
--- /dev/null
+++ b/addons/smart-home/gradle.properties
@@ -0,0 +1,3 @@
+org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
+android.useAndroidX=true
+android.nonTransitiveRClass=true
diff --git a/addons/smart-home/gradle/wrapper/gradle-wrapper.jar b/addons/smart-home/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 000000000..2c3521197
Binary files /dev/null and b/addons/smart-home/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/addons/smart-home/gradle/wrapper/gradle-wrapper.properties b/addons/smart-home/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000..77f5d0ba6
--- /dev/null
+++ b/addons/smart-home/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/smart-home/gradlew b/addons/smart-home/gradlew
new file mode 100755
index 000000000..f5feea6d6
--- /dev/null
+++ b/addons/smart-home/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/smart-home/gradlew.bat b/addons/smart-home/gradlew.bat
new file mode 100644
index 000000000..9d21a2183
--- /dev/null
+++ b/addons/smart-home/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/smart-home/install.sh b/addons/smart-home/install.sh
new file mode 100755
index 000000000..60153ab6f
--- /dev/null
+++ b/addons/smart-home/install.sh
@@ -0,0 +1,38 @@
+#!/usr/bin/env bash
+# Build Smart Home, install it on the TV and, optionally, push its Home Assistant address and token.
+# TV_HOST=<tv ip> addons/smart-home/install.sh [config.json] # {"url": "http://192.168.1.10:8123", "token": "..."}
+set -euo pipefail
+CONFIG="${1:-}"
+if [ -n "$CONFIG" ]; then
+ [ -f "$CONFIG" ] || { echo "no such file: $CONFIG" >&2; exit 1; }
+ CONFIG="$(cd "$(dirname "$CONFIG")" && pwd)/$(basename "$CONFIG")"
+ if command -v cygpath >/dev/null 2>&1; then CONFIG="$(cygpath -m "$CONFIG")"; fi
+fi
+: "${TV_HOST:?set TV_HOST to the TV IP address}"
+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.maxhayim.smarthome
+# Script paths stay relative: with MSYS_NO_PATHCONV, Git Bash would hand Windows Python a /c/... path.
+tv() { "$PY" -I ../../tools/tv.py "$@"; }
+
+[ -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/smart-home.apk
+OUT=$(tv 'pm install -r /data/local/tmp/smart-home.apk; rm -f /data/local/tmp/smart-home.apk')
+echo "$OUT"
+case "$OUT" in *Success*) ;; *) echo "ERROR: pm install failed" >&2; exit 1 ;; esac
+
+# The server and login go in as a file through the app's provider (only the ADB shell may write it), so the
+# password never sits on a command line on the TV. The app reads it once and deletes it.
+if [ -n "$CONFIG" ]; then
+ STAGE=/data/local/tmp/smart-home-config.json
+ tv --push "$CONFIG" "$STAGE" >/dev/null
+ tv "content write --uri content://$PKG.config/config.json < $STAGE; rm -f $STAGE; echo config pushed"
+fi
+tv "am start -n $PKG/.MainActivity >/dev/null; echo opened"
+echo "Installed. Smart Home is open on the TV; press Home and answer Show card for the card."
diff --git a/addons/smart-home/screenshot.jpg b/addons/smart-home/screenshot.jpg
new file mode 100644
index 000000000..7ffe4534b
Binary files /dev/null and b/addons/smart-home/screenshot.jpg differ
diff --git a/addons/smart-home/settings.gradle b/addons/smart-home/settings.gradle
new file mode 100644
index 000000000..558459dba
--- /dev/null
+++ b/addons/smart-home/settings.gradle
@@ -0,0 +1,16 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+rootProject.name = "smart-home"
+include ':app'