Skip to content

Your home as a live 3D model in the Mac menu bar and on iPhone — lights and ACs via Smart Life, Home Assistant, Philips Hue and Apple Home.

Connect Home Assistant, Philips Hue and Apple Home; ship a notarized DMG

0xProbability3d2cd8c45697
diff --git a/.gitignore b/.gitignore
index a2721e6..2e7396f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -29,6 +29,7 @@ events.log
# and the signing team is personal.
ios/HouseControl.xcodeproj/
ios/Config/Info.plist
+ios/Config/HouseControl.entitlements
ios/Config/Local.xcconfig
ios/build/
core/.build/
diff --git a/README.md b/README.md
index ef6befb..beccddb 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
<p align="center">
Your home as a live 3D model — in the Mac's menu bar, around its notch and on your iPhone —<br>
- controlling its lights and air conditioners, Smart Life / Tuya devices included.
+ controlling its lights and air conditioners through Smart Life, Home Assistant, Philips Hue and Apple Home.
</p>
<p align="center">
@@ -22,6 +22,8 @@
- **Air conditioners.** Power, target temperature, mode and fan speed, with the room temperature from a real sensor if you have one.
- **Scenes.** One tap sets every light and AC — "Cozy", "Movie", "Night", or your own.
- **A visual editor.** Draw the rooms, drop in furniture, place lamps and ACs, and link each one to a real device.
+- **Your devices, wherever they live.** Smart Life / Tuya, Home Assistant (and the thousands of brands it runs),
+ Philips Hue and Apple Home — mixed freely in one home. See [Connect real devices](#connect-real-devices).
- **An island around the notch.** Rest the pointer on the MacBook's notch and a small live model of the home drops
out of it, with scenes and every device one click away. See [The island](#the-island).
- **AI Access.** Give ChatGPT, Claude or any AI assistant a private link — or connect it over MCP — and it runs your
@@ -35,6 +37,15 @@ Both apps are a small native Swift shell (AppKit on the Mac, SwiftUI on the iPho
[Three.js](https://threejs.org) web UI, and share their device clients and sync as a Swift package.
No frameworks, no Electron, no server, no account of its own.
+## Download
+
+Get the latest `HouseControl-<version>.dmg` from [Releases](https://github.com/0xProbabillity/house-control/releases),
+open it and drag **House Control** into **Applications**. It is signed and notarized by Apple and runs on any Mac
+with macOS 13 or newer, Apple silicon or Intel. Open it from Applications and look for the house in the menu bar;
+to start it with your Mac, add it under **System Settings → General → Login Items**.
+
+To build it yourself instead, read on.
+
## Requirements
| | |
@@ -185,25 +196,34 @@ The plan is a single JSON file, `~/Library/Application Support/HouseControl/plan
export it, or import someone else's: see [docs/floor-plan.md](docs/floor-plan.md) for every field.
The demo plans in [`web/public/plans`](web/public/plans) are good starting points.
-## Connect real devices (Smart Life / Tuya)
+## Connect real devices
+
+<p align="center">
+ <img src="docs/connections.png" width="820" alt="The editor's Connections: Smart Life, Home Assistant, Philips Hue and Apple Home">
+</p>
-You need the **Smart Life** (or **Tuya Smart**) phone app with your devices already added to it.
-No Tuya developer account is required.
+Right-click the icon → **Edit Home… → Connections**, and connect what you have:
-1. In the phone app open **Me → ⚙ Settings → Account and Security** and copy the **User Code** at the bottom.
-2. In House Control: right-click the icon → **Edit Home… → Smart Life**. Enter the User Code and press **Show QR code**.
-3. Scan the code with the phone app (the scanner on its Home tab) and confirm the login.
-4. Your devices appear in the editor. Select a lamp or an AC on the plan, pick its device under
- **Smart Life device**, and press **Save & apply**.
+| Platform | How | Details |
+| --- | --- | --- |
+| **Smart Life / Tuya** | Scan a QR code with the Smart Life app. No Tuya developer account | [docs/smart-life.md](docs/smart-life.md) |
+| **Home Assistant** | Found on your network by itself; paste a long-lived access token | [docs/connections.md](docs/connections.md#home-assistant) |
+| **Philips Hue** | Found on your network by itself; press the button on the bridge | [docs/connections.md](docs/connections.md#philips-hue) |
+| **Apple Home** | Allow access on your iPhone; its devices are listed on the Mac for linking | [docs/connections.md](docs/connections.md#apple-home) |
-From then on the panel controls the real device, and re-reads the state of your devices every 12 seconds while it is open.
+Then select a lamp or an AC on the plan, choose its device under **Real device** (lamps take over what the
+device can do), and press **Save & apply**. From then on the panel controls the real device. Changes made
+elsewhere show up at once from Home Assistant and Hue, and within 12 seconds from Smart Life.
-More detail — what works with which device, infrared air conditioners, temperature sensors, the Tuya Cloud
-alternative, and how to diagnose a device that does not react — is in [docs/smart-life.md](docs/smart-life.md).
+Your iPhone receives the Home Assistant and Hue connections from the Mac with the floor plan, and switches
+Apple Home devices itself. Why there is no Google Home or Alexa yet, and how to get Tuya devices into Apple Home:
+[docs/connections.md](docs/connections.md). No hardware at hand? [`tools/lab`](tools/lab/README.md) has pretend
+versions of Home Assistant, a Hue Bridge and a HomeKit bridge.
## Privacy
-House Control talks to Tuya's servers and to nothing else. There is no telemetry and no backend of its own.
+House Control talks to the platforms you connect — Tuya's servers for Smart Life, your own Home Assistant,
+your Hue Bridge, Apple Home on the iPhone — and to nothing else. There is no telemetry and no backend of its own.
The one exception is yours to switch on: [AI Access](#ai-access) opens a Cloudflare tunnel to your Mac while it is on.
Everything personal stays in `~/Library/Application Support/HouseControl/` on your Mac:
@@ -214,6 +234,9 @@ Everything personal stays in `~/Library/Application Support/HouseControl/` on yo
| `settings.json` | Which plan is active |
| `smartlife.json` | The Smart Life session tokens. Readable only by you (mode `600`) |
| `tuya.json` | Tuya Cloud project credentials, only if you use that option. Mode `600` |
+| `homeassistant.json` | Your Home Assistant's address and access token. Mode `600` |
+| `hue.json` | Your Hue Bridge's address, the key it issued and its certificate's fingerprint. Mode `600` |
+| `homekit-devices.json` | The Apple Home devices your iPhone listed for the editor: names and ids |
| `events.log` | Commands sent to real devices and the cloud's answers. No tokens |
| `sync.json` | The key your paired iPhones use. Only there once you paired one. Mode `600` |
| `cloudflared.yml`, `bin/cloudflared` | An empty config for AI Access's tunnel, and Cloudflare's connector if you let the app download it |
@@ -221,7 +244,8 @@ Everything personal stays in `~/Library/Application Support/HouseControl/` on yo
None of these are part of this repository, and the build does not embed them in the app.
**Sign out** in the editor deletes `smartlife.json`. Deleting the folder resets the app to the demo plan.
-On the iPhone the floor plan lives in the app's own folder, and the Smart Life session and the pairing key in the Keychain.
+On the iPhone the floor plan lives in the app's own folder, and the Smart Life session, the pairing key and the
+Home Assistant and Hue connections the Mac shared in the Keychain.
## Development
@@ -230,8 +254,10 @@ web/ the UI: Three.js scene, panel, island, editor, AI Access window and th
core/ what both apps share: Smart Life and Tuya clients, plan store, Mac ⇄ iPhone sync, the AI gateway (SwiftPM, with tests)
macos/ the Mac shell: menu bar item, panel, island and editor windows (SwiftPM)
ios/ the iPhone shell: SwiftUI, generated into an Xcode project by XcodeGen
-scripts/ build-app.sh, build-ios.sh and ios-sim.sh build the apps, make-icon.swift draws the icon
-docs/ floor plan reference, Smart Life guide, screenshots
+scripts/ build-app.sh, build-ios.sh and ios-sim.sh build the apps, release-mac.sh makes the notarized .dmg,
+ make-icon.swift and make-dmg-background.swift draw the icon and the disk image's window
+tools/lab pretend Home Assistant, Hue Bridge and HomeKit bridge for testing without hardware
+docs/ floor plan reference, connection guides, screenshots
```
The shared package has unit tests, including the sync over a real TLS connection:
@@ -260,7 +286,7 @@ Environment variables understood by the app:
| `HOUSE_WEB_DIR=/path/to/dist` | Load the UI from another folder |
| `HOUSE_DATA_DIR=/some/folder` | Keep plan, session and log there instead of Application Support, and do not persist panel state. Handy for a clean test run |
| `HOUSE_OPEN_ON_LAUNCH=1` | Open the panel at launch |
-| `HOUSE_OPEN_EDITOR=1` | Open the editor at launch (`smartlife` opens it on the Smart Life section) |
+| `HOUSE_OPEN_EDITOR=1` | Open the editor at launch (`connections`, `smartlife`, `homeassistant`, `hue` or `homekit` opens it on that screen) |
| `HOUSE_OPEN_DEVICE=<id>` | Start the panel on that light's or AC's sheet |
| `HOUSE_PIN=1` | Keep the panel open when it loses focus |
| `HOUSE_DOCK=1` | Show a Dock icon, so UI automation tools can see the app |
@@ -273,8 +299,9 @@ Environment variables understood by the app:
| `HOUSE_OPEN_AGENT=1` | Open the AI Access window at launch (`start` also starts the link) |
| `HOUSE_AGENT_REACH=local` | Serve AI Access on this Mac only for one run (`internet` for the tunnel) |
| `HOUSE_AGENT_LINK_FILE=/some/file` | Write the live AI Access link there, for scripted tests |
+| `HOUSE_EVAL_DIR=/some/folder` | Scripted UI checks: a `panel.js` / `editor.js` / `island.js` dropped there runs in that page (as an async function body) and its result is written to `<mode>.json` |
-The iPhone app understands `HOUSE_DATA_DIR`, `HOUSE_OPEN_DEVICE` and `HOUSE_SCREEN=home|settings|pairing|smartlife|welcome`;
+The iPhone app understands `HOUSE_DATA_DIR`, `HOUSE_OPEN_DEVICE` and `HOUSE_SCREEN=home|settings|connections|pairing|smartlife|welcome`;
`scripts/ios-sim.sh` passes any `HOUSE_*` variable on to the simulator.
For example, a throw-away instance on the demo plan, pinned open:
@@ -292,13 +319,24 @@ The binary has a few offline self-checks and one read-only diagnostic:
| `HouseControl --selftest-transport` | The Smart Life request envelope for fixed inputs, to compare with the reference SDK |
| `HouseControl --diagnose <device id>…` | What Smart Life reports for those devices. Reads only; sends nothing |
+### Releasing the Mac app
+
+```bash
+ASC_KEY_ID=… ASC_ISSUER_ID=… ./scripts/release-mac.sh --publish
+```
+
+builds a universal app, signs it with your **Developer ID Application** certificate, has Apple notarize it, packs
+it into `build/HouseControl-<version>.dmg` and attaches that to a GitHub release. The script lists what it needs;
+`UNSIGNED=1` makes a test image without any of it.
+
## Limitations
-- Built from source: there is no signed, notarized Mac download, and the iPhone app is not on the App Store.
+- The iPhone app is not on the App Store (it is on TestFlight for the author's testers).
- The floor plan is edited on the Mac only. The iPhone receives it, and only while both are on the same network.
- Rooms are axis-aligned rectangles. An L-shaped room is two rooms.
-- Smart Life is the only device backend. Devices are reached through Tuya's cloud, not over the local network,
- so they need an internet connection.
+- Apple Home devices are switched by the iPhone app only: macOS gives HomeKit to App Store apps only.
+- Smart Life devices are reached through Tuya's cloud, not over the local network, so they need an internet
+ connection (Home Assistant and Hue work on your network alone).
- Infrared air conditioners are one-way: the app shows what was last sent, not what the unit is doing.
## Acknowledgements and disclaimer
diff --git a/core/Sources/HouseCore/DeviceHub.swift b/core/Sources/HouseCore/DeviceHub.swift
index 2583a59..bf9d69e 100644
--- a/core/Sources/HouseCore/DeviceHub.swift
+++ b/core/Sources/HouseCore/DeviceHub.swift
@@ -1,13 +1,21 @@
import Foundation
/// Everything between the UI and the real devices, shared by the Mac and the iPhone app:
-/// which backend is connected, which device of the plan is linked to which Smart Life
-/// device, sending the changes made in the panel and reading the devices' state back.
+/// which platforms are connected (Smart Life, Home Assistant, Philips Hue, Apple Home),
+/// which device of the plan is linked to which real device, sending the changes made in
+/// the panel and reading the devices' state back.
@MainActor
public final class DeviceHub {
public let log: EventLog
private let tuya: TuyaService
private let smartLife: SmartLifeService
+ public let homeAssistant: HomeAssistantService
+ public let hue: HueService
+ /// Apple Home: HomeKit itself on the iPhone, the iPhone's catalog on the Mac.
+ public let homeKit: DeviceService
+ /// The platforms other than Smart Life, by the id a plan's `link.service` uses.
+ public var services: [DeviceService] { [homeAssistant, hue, homeKit] }
+ private func service(_ id: String) -> DeviceService? { services.first { $0.id == id } }
/// The backend real devices are reached through: the QR-linked Smart Life account
/// when there is one, otherwise a Tuya Cloud project, otherwise nothing (simulation).
private var cloud: DeviceCloud? {
@@ -15,6 +23,18 @@ public final class DeviceHub {
}
/// App device id -> its Smart Life link, for the devices of the active plan.
private var links: [String: (kind: String, link: [String: Any])] = [:]
+ /// App device id -> its link to another platform.
+ private struct Link {
+ var kind: DeviceKind
+ var service: String
+ var id: String
+ /// A temperature sensor for an AC's room reading, on any platform.
+ var sensor: (service: String, id: String)?
+ }
+ private var serviceLinks: [String: Link] = [:]
+ /// Sensors from other platforms that report the room of a Smart Life AC.
+ private var tuyaSensors: [String: (service: String, id: String)] = [:]
+ private var refresh: Task<Void, Never>?
/// The command in flight for each real device; the next one waits for it.
private var commandTails: [String: Task<Void, Never>] = [:]
private let infrared = InfraredRemote()
@@ -23,40 +43,97 @@ public final class DeviceHub {
/// devices, so the owner can read their state again.
public var onStale: (() -> Void)?
- /// `session` is where the Smart Life session is kept; by default `smartlife.json` in `directory`.
- public init(directory: URL, session: SecretStore? = nil) {
+ /// `secret(name)` is where a platform's credentials are kept ("smartlife", "homeassistant",
+ /// "hue"); by default `<name>.json` in `directory`, readable by its user only. `homeKit`
+ /// is HomeKit on the iPhone; without one, Apple Home is the catalog a paired iPhone sent.
+ public init(directory: URL, secret: ((String) -> SecretStore)? = nil, homeKit: DeviceService? = nil) {
+ let vault = secret ?? { FileSecretStore(url: directory.appendingPathComponent("\($0).json")) }
log = EventLog(directory: directory)
tuya = TuyaService(directory: directory)
- smartLife = session.map { SmartLifeService(vault: $0) } ?? SmartLifeService(directory: directory)
+ smartLife = SmartLifeService(vault: vault("smartlife"))
+ homeAssistant = HomeAssistantService(vault: vault("homeassistant"))
+ hue = HueService(vault: vault("hue"))
+ self.homeKit = homeKit ?? RemoteCatalogService(id: "homekit", title: "Apple Home",
+ file: directory.appendingPathComponent("homekit-devices.json"))
+ for service in services {
+ service.onChange = { [weak self] in self?.scheduleRefresh() }
+ }
+ }
+
+ /// Changes reported by a platform arrive in bursts: one read for all of them.
+ private func scheduleRefresh() {
+ refresh?.cancel()
+ refresh = Task { @MainActor [weak self] in
+ try? await Task.sleep(nanoseconds: 300_000_000)
+ guard !Task.isCancelled else { return }
+ self?.onStale?()
+ }
}
// MARK: - Links
- public var isConnected: Bool { cloud != nil }
- public var hasLinks: Bool { !links.isEmpty }
- /// True when there is something to read from the cloud at all.
- public var canPoll: Bool { cloud != nil && !links.isEmpty }
- public var linkedDeviceCount: Int { links.count }
+ public var isConnected: Bool { cloud != nil || services.contains { $0.isConnected && $0.controlsDevices } }
+ public var hasLinks: Bool { !links.isEmpty || !serviceLinks.isEmpty }
+ /// True when there is something to read at all.
+ public var canPoll: Bool {
+ (cloud != nil && !links.isEmpty)
+ || serviceLinks.values.contains { service($0.service).map { $0.isConnected && $0.controlsDevices } ?? false }
+ }
+ public var linkedDeviceCount: Int { links.count + serviceLinks.values.filter { !$0.id.isEmpty }.count }
/// Takes the device links from `plan`; nil (a bundled demo) means everything is simulated.
public func setLinks(from plan: [String: Any]?) {
links = [:]
+ serviceLinks = [:]
+ tuyaSensors = [:]
+ defer { watchLinks() }
guard let plan else { return }
for (kind, key) in [("light", "lights"), ("ac", "acs")] {
for device in plan[key] as? [[String: Any]] ?? [] {
- guard let id = device["id"] as? String, let link = device["tuya"] as? [String: Any],
- let deviceId = link["deviceId"] as? String, !deviceId.isEmpty else { continue }
- links[id] = (kind, link)
+ guard let id = device["id"] as? String else { continue }
+ let sensor = Self.sensorLink(device["sensor"])
+ if let link = device["link"] as? [String: Any], let service = link["service"] as? String,
+ let target = link["id"] as? String, !target.isEmpty {
+ serviceLinks[id] = Link(kind: DeviceKind(rawValue: kind) ?? .light, service: service, id: target, sensor: sensor)
+ } else if let link = device["tuya"] as? [String: Any], let deviceId = link["deviceId"] as? String, !deviceId.isEmpty {
+ links[id] = (kind, link)
+ if let sensor { tuyaSensors[id] = sensor }
+ } else if let sensor, kind == "ac" {
+ // A simulated AC can still show a real room temperature.
+ serviceLinks[id] = Link(kind: .ac, service: "", id: "", sensor: sensor)
+ }
}
}
}
+ /// `{"service": "hue", "id": "…"}` in a plan.
+ private static func sensorLink(_ value: Any?) -> (service: String, id: String)? {
+ guard let sensor = value as? [String: Any], let service = sensor["service"] as? String,
+ let id = sensor["id"] as? String, !id.isEmpty else { return nil }
+ return (service, id)
+ }
+
+ /// Tells each platform which of its devices the plan uses, for its live updates.
+ private func watchLinks() {
+ var ids: [String: Set<String>] = [:]
+ for link in serviceLinks.values {
+ if !link.id.isEmpty { ids[link.service, default: []].insert(link.id) }
+ if let sensor = link.sensor { ids[sensor.service, default: []].insert(sensor.id) }
+ }
+ for sensor in tuyaSensors.values { ids[sensor.service, default: []].insert(sensor.id) }
+ for service in services { service.watch(ids[service.id] ?? []) }
+ }
+
// MARK: - Commands
/// Sends a change made in the panel to the real device and tells the panel how it went,
/// so a rejected change can be rolled back there. Commands to one device run strictly
/// one after another, in the order this is called.
public func command(_ message: [String: Any], reply: @escaping ([String: Any]) -> Void) {
+ if let id = message["id"] as? String, let link = serviceLinks[id], !link.id.isEmpty {
+ commandService(link, appId: id, message, reply: reply)
+ return
+ }
guard let cloud, let id = message["id"] as? String, let entry = links[id],
let deviceId = entry.link["deviceId"] as? String else {
reply(["ok": true]) // simulated device: nothing to send
@@ -92,6 +169,30 @@ public final class DeviceHub {
}
}
+ private func commandService(_ link: Link, appId: String, _ message: [String: Any], reply: @escaping ([String: Any]) -> Void) {
+ guard let service = service(link.service), service.isConnected, service.controlsDevices else {
+ reply(["ok": true]) // not reachable from here (Apple Home on the Mac): simulated
+ return
+ }
+ let patch = message["patch"] as? [String: Any] ?? [:]
+ let state = message["state"] as? [String: Any] ?? [:]
+ let key = "\(link.service):\(link.id)"
+ let previous = commandTails[key]
+ commandTails[key] = Task { @MainActor in
+ await previous?.value
+ let what = patch.keys.sorted().map { "\($0)=\(patch[$0] ?? "")" }.joined(separator: " ")
+ do {
+ try await service.send(kind: link.kind, id: link.id, patch: patch, state: state)
+ log.write("\(appId) [\(service.title)] \(what) → ok")
+ reply(["ok": true])
+ } catch {
+ log.write("\(appId) [\(service.title)] \(what) → \(error.localizedDescription)")
+ reply(["error": error.localizedDescription])
+ onStale?()
+ }
+ }
+ }
+
private func send(_ commands: [[String: Any]], to deviceId: String, _ id: String, _ cloud: DeviceCloud) async throws {
guard !commands.isEmpty else { return }
do {
@@ -108,6 +209,61 @@ public final class DeviceHub {
/// What the linked devices report right now, in the shape the panel's `applyRemote`
/// takes. Nil when nothing is connected or the cloud could not be reached.
public func poll() async -> [String: Any]? {
+ async let tuyaPart = pollSmartLife()
+ async let servicePart = pollServices()
+ let (fromTuya, fromServices) = await (tuyaPart, servicePart)
+ guard fromTuya != nil || fromServices != nil else { return nil }
+ var merged: [String: Any] = [:]
+ for key in ["lights", "acs", "features"] {
+ var section = fromTuya?[key] as? [String: Any] ?? [:]
+ for (id, value) in fromServices?[key] as? [String: Any] ?? [:] {
+ if var existing = section[id] as? [String: Any], let more = value as? [String: Any] {
+ existing.merge(more) { $1 }
+ section[id] = existing
+ } else {
+ section[id] = value
+ }
+ }
+ merged[key] = section
+ }
+ return merged
+ }
+
+ /// Home Assistant, Hue and Apple Home, each asked once for all of its linked devices.
+ private func pollServices() async -> [String: Any]? {
+ var wanted: [String: Set<String>] = [:]
+ for link in serviceLinks.values {
+ if !link.id.isEmpty { wanted[link.service, default: []].insert(link.id) }
+ if let sensor = link.sensor { wanted[sensor.service, default: []].insert(sensor.id) }
+ }
+ for sensor in tuyaSensors.values { wanted[sensor.service, default: []].insert(sensor.id) }
+ var readings: [String: [String: DeviceReading]] = [:]
+ var answered = false
+ for (serviceId, ids) in wanted {
+ guard let service = service(serviceId), service.isConnected, service.controlsDevices,
+ let result = try? await service.read(ids) else { continue }
+ readings[serviceId] = result
+ answered = true
+ }
+ guard answered else { return nil }
+ var lights: [String: Any] = [:], acs: [String: Any] = [:], features: [String: Any] = [:]
+ for (id, link) in serviceLinks {
+ let reading = readings[link.service]?[link.id]
+ if link.kind == .light, let light = reading?.light, reading?.online != false { lights[id] = light }
+ if link.kind == .ac {
+ var ac = reading?.online == false ? [:] : reading?.ac ?? [:]
+ if let sensor = link.sensor, let t = readings[sensor.service]?[sensor.id]?.temperature { ac["roomTemp"] = t }
+ if !ac.isEmpty { acs[id] = ac }
+ if let known = reading?.features { features[id] = known }
+ }
+ }
+ for (id, sensor) in tuyaSensors {
+ if let t = readings[sensor.service]?[sensor.id]?.temperature { acs[id] = ["roomTemp": t] }
+ }
+ return ["lights": lights, "acs": acs, "features": features]
+ }
+
+ private func pollSmartLife() async -> [String: Any]? {
let entries = links
guard let cloud, !entries.isEmpty else { return nil }
// Devices plus the temperature sensors that stand in for an AC's room reading.
@@ -143,6 +299,75 @@ public final class DeviceHub {
return try await cloud.listDevices()
}
+ /// Every device of every connected platform, in the editor's terms, plus what went
+ /// wrong with the platforms that could not be asked.
+ public func allDevices() async -> (devices: [[String: Any]], errors: [String: String]) {
+ var devices: [[String: Any]] = []
+ var errors: [String: String] = [:]
+ if cloud != nil {
+ do {
+ devices += try await listDevices().map(Self.smartLifeDevice)
+ } catch {
+ errors["smartlife"] = error.localizedDescription
+ }
+ }
+ for service in services where service.isConnected {
+ do {
+ devices += try await service.devices().map { $0.dictionary(service: service.id) }
+ } catch {
+ errors[service.id] = error.localizedDescription
+ }
+ }
+ return (devices, errors)
+ }
+
+ /// A Smart Life device in the same shape as the other platforms' (plus its Tuya codes).
+ static func smartLifeDevice(_ d: [String: Any]) -> [String: Any] {
+ let codes = Set(d["codes"] as? [String] ?? [])
+ let category = d["category"] as? String ?? ""
+ let kind: DeviceKind
+ if ["kt", "ktkzq", "infrared_ac"].contains(category) || TuyaMapper.isInfraredAC(codes) || codes.contains("temp_set") {
+ kind = .ac
+ } else if ["wsdcg", "wk", "wnykq"].contains(category) || (codes.contains("temp_current") && !codes.contains("switch_led")) {
+ kind = .sensor
+ } else {
+ kind = .light
+ }
+ var caps: [String] = []
+ if codes.contains("bright_value") || codes.contains("bright_value_v2") { caps.append("brightness") }
+ if codes.contains("temp_value") || codes.contains("temp_value_v2") { caps.append("temp") }
+ if codes.contains("colour_data") || codes.contains("colour_data_v2") { caps.append("color") }
+ var out = d
+ out["service"] = "smartlife"
+ out["kind"] = kind.rawValue
+ out["capabilities"] = caps
+ out["room"] = nil
+ out["detail"] = [d["product"] as? String, category].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")
+ return out
+ }
+
+ /// What the editor and the settings show for each platform.
+ public var servicesInfo: [String: Any] {
+ var out: [String: Any] = ["smartlife": smartLifeInfo.merging(["connected": isSmartLifeConnected || tuya.isConfigured]) { $1 }]
+ for service in services { out[service.id] = service.info }
+ return out
+ }
+
+ /// The connections a paired iPhone may take over: Home Assistant and Hue. (Apple Home
+ /// is the phone's own; the Smart Life session cannot be shared, Tuya rotates its tokens.)
+ public var shareableConnections: [String: Any] {
+ var out: [String: Any] = [:]
+ if let ha = homeAssistant.shareable { out["homeassistant"] = ha }
+ if let hue = hue.shareable { out["hue"] = hue }
+ return out
+ }
+
+ /// Takes the connections the Mac shared; a platform missing from them is disconnected.
+ public func adoptConnections(_ shared: [String: Any]) {
+ homeAssistant.adopt(shared["homeassistant"] as? [String: Any])
+ hue.adopt(shared["hue"] as? [String: Any])
+ }
+
/// Read-only snapshot of what Smart Life reports for the given devices.
public func diagnostics(for ids: [String]) async -> [String: Any] {
await smartLife.diagnostics(for: ids)
diff --git a/core/Sources/HouseCore/DeviceService.swift b/core/Sources/HouseCore/DeviceService.swift
new file mode 100644
index 0000000..210137b
--- /dev/null
+++ b/core/Sources/HouseCore/DeviceService.swift
@@ -0,0 +1,220 @@
+import Foundation
+
+/// A smart home platform the plan's lamps and ACs can be linked to, besides Smart Life:
+/// Home Assistant, Philips Hue, Apple Home. Each one speaks the panel's own vocabulary —
+/// a light is `on` / `brightness` 0…1 / `temp` in kelvin / `color` "#rrggbb", an AC is
+/// `on` / `target` / `mode` / `fan` / … — so the hub and the UI never see what is underneath.
+@MainActor
+public protocol DeviceService: AnyObject {
+ /// "homeassistant", "hue", "homekit": what a plan's `link.service` says.
+ var id: String { get }
+ var title: String { get }
+ var isConnected: Bool { get }
+ /// What the editor may show about the connection. Never a token or key.
+ var info: [String: Any] { get }
+ /// Called when the platform says something changed (a lamp switched from its own app),
+ /// so the hub can read the linked devices again without waiting for the next poll.
+ var onChange: (() -> Void)? { get set }
+
+ /// Every device the platform offers, as `ServiceDevice.dictionary`.
+ func devices() async throws -> [ServiceDevice]
+ /// The current state of the given devices. Devices the platform does not know are left out.
+ func read(_ ids: Set<String>) async throws -> [String: DeviceReading]
+ /// Applies a change made in the panel. `state` is the whole new state, for platforms
+ /// that need more than the changed fields (a colour needs the brightness too).
+ func send(kind: DeviceKind, id: String, patch: [String: Any], state: [String: Any]) async throws
+ /// The devices linked in the plan, whose changes should reach `onChange`.
+ func watch(_ ids: Set<String>)
+ /// False for a catalog this device cannot act on (Apple Home on the Mac).
+ var controlsDevices: Bool { get }
+ /// Forgets the connection and its credentials.
+ func disconnect()
+}
+
+public extension DeviceService {
+ func watch(_ ids: Set<String>) {}
+ var controlsDevices: Bool { true }
+}
+
+public enum DeviceKind: String {
+ case light, ac, sensor
+
+ /// A lamp the panel shows as on, given a new brightness or colour, is switched on as well:
+ /// the real one may be off (switched off elsewhere since the last read), and some
+ /// platforms ignore a colour sent to a lamp that is off.
+ static func withPower(_ patch: [String: Any], state: [String: Any]) -> [String: Any] {
+ guard patch["on"] == nil, state["on"] as? Bool == true,
+ ["brightness", "temp", "color"].contains(where: { patch[$0] != nil }) else { return patch }
+ return patch.merging(["on": true]) { a, _ in a }
+ }
+}
+
+/// One device as the editor lists it.
+public struct ServiceDevice {
+ public var id: String
+ public var name: String
+ public var kind: DeviceKind
+ public var room: String?
+ public var online = true
+ /// For lights: which of "brightness", "temp", "color" it supports.
+ public var capabilities: [String] = []
+ /// For ACs: the set-point range it accepts.
+ public var range: (min: Double, max: Double)?
+ /// A short technical description ("light · color_temp, hs").
+ public var detail = ""
+
+ public init(id: String, name: String, kind: DeviceKind, room: String? = nil) {
+ self.id = id
+ self.name = name
+ self.kind = kind
+ self.room = room
+ }
+
+ public func dictionary(service: String) -> [String: Any] {
+ var out: [String: Any] = ["service": service, "id": id, "name": name, "kind": kind.rawValue,
+ "online": online, "capabilities": capabilities, "detail": detail]
+ if let room { out["room"] = room }
+ if let range { out["min"] = range.min; out["max"] = range.max }
+ return out
+ }
+}
+
+/// What one device reports, in the panel's terms.
+public struct DeviceReading {
+ public var light: [String: Any]?
+ public var ac: [String: Any]?
+ /// What an AC can do: `modes`, `fans`, `swing`, `sleep`, `eco` (see the store's acFeatures).
+ public var features: [String: Any]?
+ /// A temperature sensor's reading in °C.
+ public var temperature: Double?
+ public var online = true
+
+ public init(light: [String: Any]? = nil, ac: [String: Any]? = nil, features: [String: Any]? = nil,
+ temperature: Double? = nil, online: Bool = true) {
+ self.light = light
+ self.ac = ac
+ self.features = features
+ self.temperature = temperature
+ self.online = online
+ }
+}
+
+public struct ServiceFailure: LocalizedError {
+ public let message: String
+ public init(_ message: String) { self.message = message }
+ public var errorDescription: String? { message }
+}
+
+// MARK: - Colour
+
+/// Conversions between the panel's "#rrggbb" and what the platforms take.
+public enum ColorMath {
+ public static func rgb(_ hex: String) -> (r: Double, g: Double, b: Double)? {
+ var s = hex.trimmingCharacters(in: .whitespaces)
+ if s.hasPrefix("#") { s.removeFirst() }
+ guard s.count == 6, let v = UInt32(s, radix: 16) else { return nil }
+ return (Double((v >> 16) & 0xFF) / 255, Double((v >> 8) & 0xFF) / 255, Double(v & 0xFF) / 255)
+ }
+
+ public static func hex(r: Double, g: Double, b: Double) -> String {
+ func byte(_ v: Double) -> Int { Int((max(0, min(1, v)) * 255).rounded()) }
+ return String(format: "#%02x%02x%02x", byte(r), byte(g), byte(b))
+ }
+
+ /// Hue in degrees 0…360, saturation and value 0…1.
+ public static func hsv(_ hex: String) -> (h: Double, s: Double, v: Double)? {
+ guard let (r, g, b) = rgb(hex) else { return nil }
+ let hi = max(r, g, b), lo = min(r, g, b), d = hi - lo
+ var h = 0.0
+ if d > 0 {
+ if hi == r { h = 60 * ((g - b) / d).truncatingRemainder(dividingBy: 6) }
+ else if hi == g { h = 60 * ((b - r) / d + 2) }
+ else { h = 60 * ((r - g) / d + 4) }
+ }
+ if h < 0 { h += 360 }
+ return (h, hi == 0 ? 0 : d / hi, hi)
+ }
+
+ /// The colour of a hue and saturation at full value, as the panel shows it.
+ public static func hex(hue: Double, saturation: Double) -> String {
+ let h = (hue.truncatingRemainder(dividingBy: 360) + 360).truncatingRemainder(dividingBy: 360) / 60
+ let s = max(0, min(1, saturation))
+ let c = s, x = c * (1 - abs(h.truncatingRemainder(dividingBy: 2) - 1)), m = 1 - c
+ let (r, g, b): (Double, Double, Double)
+ switch Int(h) {
+ case 0: (r, g, b) = (c, x, 0)
+ case 1: (r, g, b) = (x, c, 0)
+ case 2: (r, g, b) = (0, c, x)
+ case 3: (r, g, b) = (0, x, c)
+ case 4: (r, g, b) = (x, 0, c)
+ default: (r, g, b) = (c, 0, x)
+ }
+ return hex(r: r + m, g: g + m, b: b + m)
+ }
+
+ /// CIE 1931 xy of an sRGB colour (Philips' "wide gamut" conversion).
+ public static func xy(_ hex: String) -> (x: Double, y: Double)? {
+ guard let (r, g, b) = rgb(hex) else { return nil }
+ func linear(_ c: Double) -> Double { c > 0.04045 ? pow((c + 0.055) / 1.055, 2.4) : c / 12.92 }
+ let (lr, lg, lb) = (linear(r), linear(g), linear(b))
+ let X = lr * 0.4124 + lg * 0.3576 + lb * 0.1805
+ let Y = lr * 0.2126 + lg * 0.7152 + lb * 0.0722
+ let Z = lr * 0.0193 + lg * 0.1192 + lb * 0.9505
+ let sum = X + Y + Z
+ guard sum > 0 else { return (0.3127, 0.3290) } // black: the white point
+ return ((X / sum * 10000).rounded() / 10000, (Y / sum * 10000).rounded() / 10000)
+ }
+
+ /// The sRGB colour of an xy chromaticity at full brightness.
+ public static func hex(x: Double, y: Double) -> String {
+ guard y > 0 else { return "#ffffff" }
+ let Y = 1.0, X = Y / y * x, Z = Y / y * (1 - x - y)
+ var r = X * 3.2406 - Y * 1.5372 - Z * 0.4986
+ var g = -X * 0.9689 + Y * 1.8758 + Z * 0.0415
+ var b = X * 0.0557 - Y * 0.2040 + Z * 1.0570
+ let top = max(r, g, b, 1e-9)
+ (r, g, b) = (max(0, r / top), max(0, g / top), max(0, b / top))
+ func gamma(_ c: Double) -> Double { c <= 0.0031308 ? 12.92 * c : 1.055 * pow(c, 1 / 2.4) - 0.055 }
+ return hex(r: gamma(r), g: gamma(g), b: gamma(b))
+ }
+
+ /// Kelvin ↔ mired (what Hue and HomeKit use for white temperature).
+ public static func mired(kelvin: Double) -> Double { 1_000_000 / max(1000, kelvin) }
+ public static func kelvin(mired: Double) -> Double { 1_000_000 / max(1, mired) }
+}
+
+// MARK: - Air conditioner vocabulary
+
+/// Maps whatever a platform calls its fan speeds onto the panel's five.
+enum FanNames {
+ static func panel(_ name: String) -> String? {
+ let n = name.lowercased()
+ if ["turbo", "max", "strong", "highest", "powerful", "boost", "very high"].contains(where: n.contains) { return "turbo" }
+ if n.contains("high") { return "high" }
+ if n.contains("med") || n.contains("mid") { return "medium" }
+ if n.contains("low") || n.contains("quiet") || n.contains("silent") { return "low" }
+ if n.contains("auto") { return "auto" }
+ return nil
+ }
+
+ /// For each panel fan speed, the platform's own name for it (the first one that maps).
+ static func table(_ names: [String]) -> [String: String] {
+ var out: [String: String] = [:]
+ for name in names where name.lowercased() != "off" {
+ if let p = panel(name), out[p] == nil { out[p] = name }
+ }
+ return out
+ }
+
+ static let order = ["auto", "low", "medium", "high", "turbo"]
+}
+
+extension Dictionary where Key == String, Value == Any {
+ func double(_ key: String) -> Double? {
+ if let v = self[key] as? Double { return v }
+ if let v = self[key] as? Int { return Double(v) }
+ if let v = self[key] as? NSNumber { return v.doubleValue }
+ if let v = self[key] as? String { return Double(v) }
+ return nil
+ }
+}
diff --git a/core/Sources/HouseCore/HomeAssistantService.swift b/core/Sources/HouseCore/HomeAssistantService.swift
new file mode 100644
index 0000000..5f07de4
--- /dev/null
+++ b/core/Sources/HouseCore/HomeAssistantService.swift
@@ -0,0 +1,405 @@
+import Foundation
+
+/// A Home Assistant server on the local network (or anywhere it is reachable), through its
+/// REST API with a long-lived access token. Lights and switches become lamps, `climate`
+/// entities become air conditioners and temperature sensors can stand in for an AC's room
+/// reading. A WebSocket subscription tells the hub the moment something changes.
+@MainActor
+public final class HomeAssistantService: DeviceService {
+ public let id = "homeassistant"
+ public let title = "Home Assistant"
+ public var onChange: (() -> Void)?
+
+ struct Config: Codable {
+ var url: String
+ var token: String
+ var name: String?
+ var version: String?
+ }
+
+ private let vault: SecretStore
+ private var config: Config?
+ private let session: URLSession
+ private var socket: URLSessionWebSocketTask?
+ private var socketRetry: Task<Void, Never>?
+ /// Each climate entity's own names for the panel's fan speeds and modes, from the last read.
+ private var fanNames: [String: [String: String]] = [:]
+ private var modeNames: [String: [String: String]] = [:]
+ /// The entities linked in the plan: only their changes are worth a read.
+ private var watched: Set<String> = []
+ private var changePending = false
+
+ public init(vault: SecretStore) {
+ self.vault = vault
+ let configuration = URLSessionConfiguration.ephemeral
+ configuration.timeoutIntervalForRequest = 10
+ session = URLSession(configuration: configuration)
+ config = vault.read().flatMap { try? JSONDecoder().decode(Config.self, from: $0) }
+ if config != nil { listen() }
+ }
+
+ public var isConnected: Bool { config != nil }
+
+ public var info: [String: Any] {
+ guard let config else { return ["connected": false] }
+ return ["connected": true, "url": config.url, "name": config.name ?? "Home Assistant", "version": config.version ?? ""]
+ }
+
+ /// For the iPhone: the Mac shares its connection over the paired, encrypted sync.
+ public var shareable: [String: Any]? {
+ guard let config else { return nil }
+ return ["url": config.url, "token": config.token, "name": config.name ?? "", "version": config.version ?? ""]
+ }
+
+ // MARK: - Connecting
+
+ /// Checks the address and the token, then keeps them.
+ public func connect(url raw: String, token: String) async throws {
+ let url = try Self.normalize(raw)
+ let token = token.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !token.isEmpty else { throw ServiceFailure("Paste a long-lived access token (your profile in Home Assistant → Security).") }
+ var candidate = Config(url: url, token: token)
+ let about = try await request("GET", "/api/config", config: candidate) as? [String: Any] ?? [:]
+ candidate.name = about["location_name"] as? String
+ candidate.version = about["version"] as? String
+ config = candidate
+ vault.write(try? JSONEncoder().encode(candidate))
+ listen()
+ }
+
+ /// Takes a connection shared by the Mac; nil removes it.
+ public func adopt(_ shared: [String: Any]?) {
+ guard let shared, let url = shared["url"] as? String, let token = shared["token"] as? String else {
+ if config != nil { disconnect() }
+ return
+ }
+ let name = (shared["name"] as? String).flatMap { $0.isEmpty ? nil : $0 }
+ guard config?.url != url || config?.token != token || config?.name != name else { return }
+ config = Config(url: url, token: token, name: name, version: shared["version"] as? String)
+ vault.write(try? JSONEncoder().encode(config))
+ listen()
+ }
+
+ public func watch(_ ids: Set<String>) { watched = ids }
+
+ public func disconnect() {
+ config = nil
+ vault.write(nil)
+ socketRetry?.cancel()
+ socket?.cancel(with: .goingAway, reason: nil)
+ socket = nil
+ }
+
+ /// "homeassistant.local:8123" → "http://homeassistant.local:8123".
+ static func normalize(_ raw: String) throws -> String {
+ var s = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !s.isEmpty else { throw ServiceFailure("Enter the address of your Home Assistant, for example http://homeassistant.local:8123") }
+ if !s.contains("://") { s = "http://" + s }
+ while s.hasSuffix("/") { s.removeLast() }
+ guard let url = URL(string: s), url.host != nil, ["http", "https"].contains(url.scheme ?? "") else {
+ throw ServiceFailure("“\(raw)” is not a web address")
+ }
+ if url.port == nil, url.scheme == "http", (url.host ?? "").hasSuffix(".local") || url.host == "homeassistant" {
+ s += ":8123" // Home Assistant's default port, which people leave out
+ }
+ return s
+ }
+
+ // MARK: - Devices
+
+ public func devices() async throws -> [ServiceDevice] {
+ let states = try await request("GET", "/api/states") as? [[String: Any]] ?? []
+ let areas = (try? await areaNames(for: states.compactMap { $0["entity_id"] as? String })) ?? [:]
+ return states.compactMap { state in
+ guard var device = Self.device(from: state) else { return nil }
+ device.room = areas[device.id]
+ return device
+ }.sorted { ($0.kind.rawValue, $0.name) < ($1.kind.rawValue, $1.name) }
+ }
+
+ /// Area of every entity, in one template request (the REST API has no area endpoint).
+ private func areaNames(for ids: [String]) async throws -> [String: String] {
+ let template = "{% for e in states %}{{ e.entity_id }}\t{{ area_name(e.entity_id) or '' }}\n{% endfor %}"
+ guard let text = try await request("POST", "/api/template", body: ["template": template], raw: true) as? String else { return [:] }
+ var out: [String: String] = [:]
+ for line in text.split(separator: "\n") {
+ let parts = line.split(separator: "\t", maxSplits: 1).map(String.init)
+ if parts.count == 2, !parts[1].isEmpty, parts[1] != "None" { out[parts[0]] = parts[1] }
+ }
+ return out
+ }
+
+ public func read(_ ids: Set<String>) async throws -> [String: DeviceReading] {
+ guard !ids.isEmpty else { return [:] }
+ let states = try await request("GET", "/api/states") as? [[String: Any]] ?? []
+ var out: [String: DeviceReading] = [:]
+ for state in states {
+ guard let id = state["entity_id"] as? String, ids.contains(id) else { continue }
+ let attributes = state["attributes"] as? [String: Any] ?? [:]
+ if id.hasPrefix("climate.") {
+ fanNames[id] = FanNames.table(attributes["fan_modes"] as? [String] ?? [])
+ modeNames[id] = Self.modeTable(attributes["hvac_modes"] as? [String] ?? [])
+ }
+ out[id] = Self.reading(from: state)
+ }
+ return out
+ }
+
+ public func send(kind: DeviceKind, id: String, patch: [String: Any], state: [String: Any]) async throws {
+ for call in Self.calls(for: id, patch: patch, state: state,
+ fans: fanNames[id] ?? [:], modes: modeNames[id] ?? [:]) {
+ _ = try await request("POST", "/api/services/\(call.domain)/\(call.service)", body: call.data)
+ }
+ }
+
+ // MARK: - Mapping (static, so the tests can run it without a server)
+
+ static func device(from state: [String: Any]) -> ServiceDevice? {
+ guard let id = state["entity_id"] as? String else { return nil }
+ let attributes = state["attributes"] as? [String: Any] ?? [:]
+ let name = attributes["friendly_name"] as? String ?? id
+ let domain = id.split(separator: ".").first.map(String.init) ?? ""
+ var device: ServiceDevice
+ switch domain {
+ case "light":
+ device = ServiceDevice(id: id, name: name, kind: .light)
+ let modes = attributes["supported_color_modes"] as? [String] ?? []
+ device.capabilities = lightCapabilities(modes)
+ device.detail = "light · " + (modes.isEmpty ? "on/off" : modes.joined(separator: ", "))
+ case "switch":
+ device = ServiceDevice(id: id, name: name, kind: .light)
+ device.detail = "switch · on/off"
+ case "climate":
+ device = ServiceDevice(id: id, name: name, kind: .ac)
+ if let lo = attributes.double("min_temp"), let hi = attributes.double("max_temp") {
+ device.range = (max(lo, 10), min(hi, 32))
+ }
+ device.detail = "climate · " + (attributes["hvac_modes"] as? [String] ?? []).joined(separator: ", ")
+ case "sensor":
+ guard isTemperature(attributes) else { return nil }
+ device = ServiceDevice(id: id, name: name, kind: .sensor)
+ device.detail = "temperature sensor"
+ default:
+ return nil
+ }
+ device.online = !["unavailable", "unknown"].contains(state["state"] as? String ?? "")
+ return device
+ }
+
+ static func lightCapabilities(_ modes: [String]) -> [String] {
+ var caps: [String] = []
+ if modes.contains(where: { $0 != "onoff" }) { caps.append("brightness") }
+ if modes.contains("color_temp") { caps.append("temp") }
+ if modes.contains(where: { ["hs", "xy", "rgb", "rgbw", "rgbww"].contains($0) }) { caps.append("color") }
+ return caps
+ }
+
+ static func isTemperature(_ attributes: [String: Any]) -> Bool {
+ (attributes["device_class"] as? String) == "temperature"
+ || ["°C", "°F"].contains(attributes["unit_of_measurement"] as? String ?? "")
+ }
+
+ /// The panel's AC modes and the climate entity's names for them.
+ static func modeTable(_ hvacModes: [String]) -> [String: String] {
+ var out: [String: String] = [:]
+ for (panel, names) in [("cool", ["cool"]), ("heat", ["heat"]), ("dry", ["dry"]),
+ ("fan", ["fan_only"]), ("auto", ["auto", "heat_cool"])] {
+ if let name = names.first(where: hvacModes.contains) { out[panel] = name }
+ }
+ return out
+ }
+
+ static func reading(from state: [String: Any]) -> DeviceReading {
+ let id = state["entity_id"] as? String ?? ""
+ let value = state["state"] as? String ?? ""
+ let attributes = state["attributes"] as? [String: Any] ?? [:]
+ var reading = DeviceReading(online: !["unavailable", "unknown"].contains(value))
+ guard reading.online else { return reading }
+
+ if id.hasPrefix("light.") || id.hasPrefix("switch.") {
+ var light: [String: Any] = ["on": value == "on"]
+ if value == "on", let b = attributes.double("brightness") { light["brightness"] = max(0.05, min(1, b / 255)) }
+ switch attributes["color_mode"] as? String {
+ case "color_temp":
+ if let k = attributes.double("color_temp_kelvin") { light["temp"] = max(2200, min(6500, k)); light["color"] = NSNull() }
+ case "hs", "xy", "rgb", "rgbw", "rgbww":
+ if let rgb = attributes["rgb_color"] as? [Any], rgb.count == 3 {
+ let c = rgb.compactMap { ($0 as? NSNumber)?.doubleValue }
+ if c.count == 3 { light["color"] = ColorMath.hex(r: c[0] / 255, g: c[1] / 255, b: c[2] / 255) }
+ }
+ default: break
+ }
+ reading.light = light
+ } else if id.hasPrefix("climate.") {
+ let modes = modeTable(attributes["hvac_modes"] as? [String] ?? [])
+ var ac: [String: Any] = ["on": value != "off"]
+ if let mode = modes.first(where: { $0.value == value })?.key { ac["mode"] = mode }
+ if let t = attributes.double("temperature") {
+ ac["target"] = t
+ } else if let lo = attributes.double("target_temp_low"), let hi = attributes.double("target_temp_high") {
+ ac["target"] = ((lo + hi) / 2).rounded()
+ }
+ if let room = attributes.double("current_temperature") { ac["roomTemp"] = room }
+ let fans = FanNames.table(attributes["fan_modes"] as? [String] ?? [])
+ if let current = attributes["fan_mode"] as? String, let fan = FanNames.panel(current), fans[fan] != nil { ac["fan"] = fan }
+ let swings = attributes["swing_modes"] as? [String] ?? []
+ if let swing = attributes["swing_mode"] as? String, !swings.isEmpty { ac["swing"] = swing == "off" ? "off" : "swing" }
+ let presets = attributes["preset_modes"] as? [String] ?? []
+ let preset = attributes["preset_mode"] as? String ?? ""
+ if presets.contains("sleep") { ac["sleep"] = preset == "sleep" }
+ if presets.contains("eco") { ac["eco"] = preset == "eco" }
+ reading.ac = ac
+ reading.features = [
+ "modes": ["cool", "heat", "dry", "fan", "auto"].filter { modes[$0] != nil },
+ "fans": FanNames.order.filter { fans[$0] != nil },
+ "swing": swings.contains("off") && swings.count > 1,
+ "sleep": presets.contains("sleep"), "eco": presets.contains("eco"),
+ ]
+ } else if id.hasPrefix("sensor."), let t = Double(value) {
+ reading.temperature = (attributes["unit_of_measurement"] as? String) == "°F" ? (t - 32) * 5 / 9 : t
+ }
+ return reading
+ }
+
+ struct Call {
+ var domain: String
+ var service: String
+ var data: [String: Any]
+ }
+
+ static func calls(for id: String, patch: [String: Any], state: [String: Any],
+ fans: [String: String], modes: [String: String]) -> [Call] {
+ let domain = id.split(separator: ".").first.map(String.init) ?? ""
+ let target: [String: Any] = ["entity_id": id]
+ func call(_ service: String, _ data: [String: Any] = [:], domain d: String = domain) -> Call {
+ Call(domain: d, service: service, data: target.merging(data) { $1 })
+ }
+
+ if domain == "switch" {
+ guard let on = patch["on"] as? Bool else { return [] }
+ return [call(on ? "turn_on" : "turn_off")]
+ }
+ if domain == "light" {
+ if patch["on"] as? Bool == false { return [call("turn_off")] }
+ var data: [String: Any] = [:]
+ if let b = patch["brightness"] as? Double { data["brightness_pct"] = Int((b * 100).rounded()) }
+ if let k = patch["temp"] as? Double { data["color_temp_kelvin"] = Int(k) }
+ if let hex = patch["color"] as? String, let (r, g, b) = ColorMath.rgb(hex) {
+ data["rgb_color"] = [Int(r * 255), Int(g * 255), Int(b * 255)]
+ }
+ guard !data.isEmpty || patch["on"] as? Bool == true else { return [] }
+ return [call("turn_on", data)]
+ }
+ guard domain == "climate" else { return [] }
+
+ var out: [Call] = []
+ let on = patch["on"] as? Bool
+ if on == false { return [call("set_hvac_mode", ["hvac_mode": "off"])] }
+ // Picking a mode is what switches a climate entity on.
+ if on == true || patch["mode"] != nil {
+ let mode = (patch["mode"] as? String) ?? (state["mode"] as? String) ?? "cool"
+ if let name = modes[mode] ?? modes.values.first { out.append(call("set_hvac_mode", ["hvac_mode": name])) }
+ }
+ if let t = patch["target"] as? Double {
+ out.append(call("set_temperature", ["temperature": t]))
+ }
+ if let fan = patch["fan"] as? String, let name = fans[fan] {
+ out.append(call("set_fan_mode", ["fan_mode": name]))
+ }
+ if let swing = patch["swing"] as? String {
+ out.append(call("set_swing_mode", ["swing_mode": swing == "off" ? "off" : "on"]))
+ }
+ for preset in ["sleep", "eco"] {
+ if let enabled = patch[preset] as? Bool {
+ out.append(call("set_preset_mode", ["preset_mode": enabled ? preset : "none"]))
+ }
+ }
+ return out
+ }
+
+ // MARK: - HTTP
+
+ @discardableResult
+ private func request(_ method: String, _ path: String, body: [String: Any]? = nil,
+ raw: Bool = false, config: Config? = nil) async throws -> Any? {
+ guard let config = config ?? self.config, let url = URL(string: config.url + path) else {
+ throw ServiceFailure("Connect Home Assistant first")
+ }
+ var request = URLRequest(url: url)
+ request.httpMethod = method
+ request.setValue("Bearer \(config.token)", forHTTPHeaderField: "Authorization")
+ if let body {
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ request.httpBody = try JSONSerialization.data(withJSONObject: body)
+ }
+ let data: Data, response: URLResponse
+ do {
+ (data, response) = try await session.data(for: request)
+ } catch {
+ throw ServiceFailure("Home Assistant at \(config.url) did not answer: \(error.localizedDescription)")
+ }
+ let status = (response as? HTTPURLResponse)?.statusCode ?? 0
+ switch status {
+ case 200..<300: break
+ case 401, 403: throw ServiceFailure("Home Assistant refused the token. Create a new long-lived access token and connect again.")
+ case 404: throw ServiceFailure("Home Assistant does not know \(path). Is the API enabled?")
+ default:
+ let text = String(data: data, encoding: .utf8)?.prefix(200) ?? ""
+ throw ServiceFailure("Home Assistant answered \(status) \(text)")
+ }
+ if raw { return String(data: data, encoding: .utf8) }
+ return data.isEmpty ? nil : try? JSONSerialization.jsonObject(with: data)
+ }
+
+ // MARK: - Live updates
+
+ /// Subscribes to state changes of the entities the hub cares about, and says so through
+ /// `onChange`. Reconnects by itself; polling covers the gaps.
+ private func listen() {
+ socketRetry?.cancel()
+ socket?.cancel(with: .goingAway, reason: nil)
+ guard let config, var parts = URLComponents(string: config.url + "/api/websocket") else { return }
+ parts.scheme = parts.scheme == "https" ? "wss" : "ws"
+ guard let url = parts.url else { return }
+ let task = session.webSocketTask(with: url)
+ socket = task
+ task.resume()
+ Task { @MainActor [weak self] in
+ await self?.run(task, token: config.token)
+ }
+ }
+
+ private func run(_ task: URLSessionWebSocketTask, token: String) async {
+ do {
+ _ = try await task.receive() // auth_required
+ try await task.send(.string(Self.json(["type": "auth", "access_token": token])))
+ _ = try await task.receive() // auth_ok
+ try await task.send(.string(Self.json(["id": 1, "type": "subscribe_events", "event_type": "state_changed"])))
+ while task === socket {
+ let message = try await task.receive()
+ guard case .string(let text) = message,
+ let event = (try? JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any])?["event"] as? [String: Any],
+ let entity = (event["data"] as? [String: Any])?["entity_id"] as? String,
+ watched.contains(entity), !changePending else { continue }
+ // A burst of changes (a scene) becomes one read.
+ changePending = true
+ Task { @MainActor [weak self] in
+ try? await Task.sleep(nanoseconds: 400_000_000)
+ self?.changePending = false
+ self?.onChange?()
+ }
+ }
+ } catch {
+ guard task === socket, config != nil else { return }
+ socketRetry = Task { @MainActor [weak self] in
+ try? await Task.sleep(nanoseconds: 15_000_000_000)
+ guard !Task.isCancelled else { return }
+ self?.listen()
+ }
+ }
+ }
+
+ private static func json(_ object: [String: Any]) -> String {
+ (try? JSONSerialization.data(withJSONObject: object)).flatMap { String(data: $0, encoding: .utf8) } ?? "{}"
+ }
+}
diff --git a/core/Sources/HouseCore/HomeKitMapper.swift b/core/Sources/HouseCore/HomeKitMapper.swift
new file mode 100644
index 0000000..59fec76
--- /dev/null
+++ b/core/Sources/HouseCore/HomeKitMapper.swift
@@ -0,0 +1,182 @@
+import Foundation
+
+/// Translates between HomeKit characteristics and the panel's vocabulary. Kept apart from
+/// HomeKit itself (which only exists on iOS) so it can be tested anywhere. Values are keyed
+/// by short names: "on", "brightness", "colorTemperature", "hue", "saturation", "active",
+/// "targetState", "coolingThreshold", "heatingThreshold", "rotationSpeed", "swing",
+/// "currentTemperature", "targetTemperature".
+public enum HomeKitMapper {
+ public enum Kind: String {
+ case light, outlet, heaterCooler, thermostat, sensor
+
+ public var device: DeviceKind {
+ switch self {
+ case .light, .outlet: return .light
+ case .heaterCooler, .thermostat: return .ac
+ case .sensor: return .sensor
+ }
+ }
+ }
+
+ /// HomeKit's service and characteristic type UUIDs, as HMServiceType… / HMCharacteristicType… hold them.
+ public static let serviceKinds: [String: Kind] = [
+ "00000043-0000-1000-8000-0026BB765291": .light, // Lightbulb
+ "00000047-0000-1000-8000-0026BB765291": .outlet, // Outlet
+ "00000049-0000-1000-8000-0026BB765291": .outlet, // Switch
+ "000000BC-0000-1000-8000-0026BB765291": .heaterCooler, // Heater Cooler (most ACs)
+ "0000004A-0000-1000-8000-0026BB765291": .thermostat, // Thermostat
+ "0000008A-0000-1000-8000-0026BB765291": .sensor, // Temperature Sensor
+ ]
+
+ public static let characteristicNames: [String: String] = [
+ "00000025-0000-1000-8000-0026BB765291": "on",
+ "00000008-0000-1000-8000-0026BB765291": "brightness",
+ "000000CE-0000-1000-8000-0026BB765291": "colorTemperature",
+ "00000013-0000-1000-8000-0026BB765291": "hue",
+ "0000002F-0000-1000-8000-0026BB765291": "saturation",
+ "000000B0-0000-1000-8000-0026BB765291": "active",
+ "000000B2-0000-1000-8000-0026BB765291": "targetState", // heater cooler: 0 auto, 1 heat, 2 cool
+ "00000033-0000-1000-8000-0026BB765291": "targetHeatingCooling", // thermostat: 0 off, 1 heat, 2 cool, 3 auto
+ "0000000D-0000-1000-8000-0026BB765291": "coolingThreshold",
+ "00000012-0000-1000-8000-0026BB765291": "heatingThreshold",
+ "00000029-0000-1000-8000-0026BB765291": "rotationSpeed",
+ "000000B6-0000-1000-8000-0026BB765291": "swing",
+ "00000011-0000-1000-8000-0026BB765291": "currentTemperature",
+ "00000035-0000-1000-8000-0026BB765291": "targetTemperature",
+ ]
+
+ public static func kind(ofService type: String) -> Kind? { serviceKinds[type.uppercased()] }
+ public static func name(ofCharacteristic type: String) -> String? { characteristicNames[type.uppercased()] }
+
+ // MARK: - Lights
+
+ public static func capabilities(_ names: Set<String>) -> [String] {
+ var caps: [String] = []
+ if names.contains("brightness") { caps.append("brightness") }
+ if names.contains("colorTemperature") { caps.append("temp") }
+ if names.contains("hue") && names.contains("saturation") { caps.append("color") }
+ return caps
+ }
+
+ /// `whiteMode`: the lamp was last set to a white temperature (HomeKit does not say which
+ /// of its colour and white settings is the one in effect).
+ public static func lightState(_ v: [String: Any], whiteMode: Bool? = nil) -> [String: Any] {
+ var out: [String: Any] = [:]
+ if let on = v["on"] as? Bool ?? (v.double("on").map { $0 != 0 }) { out["on"] = on }
+ if let b = v.double("brightness") { out["brightness"] = max(0.05, min(1, b / 100)) }
+ let hasWhite = v.double("colorTemperature") != nil
+ let hasColour = v.double("hue") != nil && v.double("saturation") != nil
+ let white = whiteMode ?? (hasWhite && (!hasColour || (v.double("saturation") ?? 0) < 15))
+ if white, let mired = v.double("colorTemperature") {
+ out["temp"] = max(2200, min(6500, ColorMath.kelvin(mired: mired).rounded()))
+ out["color"] = NSNull()
+ } else if hasColour, let h = v.double("hue"), let s = v.double("saturation") {
+ out["color"] = ColorMath.hex(hue: h, saturation: s / 100)
+ }
+ return out
+ }
+
+ /// The characteristic writes for a change to a lamp, in order. `limits` holds each
+ /// characteristic's (min, max) where HomeKit reported them.
+ public static func lightWrites(_ patch: [String: Any], kind: Kind, has: Set<String>,
+ limits: [String: (Double, Double)] = [:]) -> [(String, Any)] {
+ var out: [(String, Any)] = []
+ func clamp(_ name: String, _ value: Double) -> Double {
+ guard let (lo, hi) = limits[name] else { return value }
+ return max(lo, min(hi, value))
+ }
+ if let on = patch["on"] as? Bool { out.append(("on", on)) }
+ guard kind == .light else { return out }
+ if let b = patch["brightness"] as? Double, has.contains("brightness") {
+ out.append(("brightness", Int(clamp("brightness", (b * 100).rounded()))))
+ }
+ if let k = patch["temp"] as? Double, has.contains("colorTemperature") {
+ out.append(("colorTemperature", Int(clamp("colorTemperature", ColorMath.mired(kelvin: k).rounded()))))
+ }
+ if let hex = patch["color"] as? String, has.contains("hue"), let (h, s, _) = ColorMath.hsv(hex) {
+ out.append(("hue", (h * 10).rounded() / 10))
+ out.append(("saturation", (s * 1000).rounded() / 10))
+ }
+ return out
+ }
+
+ // MARK: - Air conditioners
+
+ static let heaterCoolerModes: [Int: String] = [0: "auto", 1: "heat", 2: "cool"]
+ static let thermostatModes: [Int: String] = [1: "heat", 2: "cool", 3: "auto"]
+
+ public static func acState(_ v: [String: Any], kind: Kind) -> [String: Any] {
+ var out: [String: Any] = [:]
+ if let room = v.double("currentTemperature") { out["roomTemp"] = (room * 10).rounded() / 10 }
+ if kind == .thermostat {
+ let mode = Int(v.double("targetHeatingCooling") ?? 0)
+ out["on"] = mode != 0
+ if let m = thermostatModes[mode] { out["mode"] = m }
+ if let t = v.double("targetTemperature") { out["target"] = t.rounded() }
+ return out
+ }
+ if let active = v.double("active") ?? (v["active"] as? Bool).map({ $0 ? 1 : 0 }) { out["on"] = active == 1 }
+ let mode = heaterCoolerModes[Int(v.double("targetState") ?? 2)] ?? "cool"
+ out["mode"] = mode
+ let cool = v.double("coolingThreshold"), heat = v.double("heatingThreshold")
+ switch mode {
+ case "heat": if let t = heat ?? cool { out["target"] = t.rounded() }
+ case "auto":
+ if let c = cool, let h = heat { out["target"] = ((c + h) / 2).rounded() } else if let t = cool ?? heat { out["target"] = t.rounded() }
+ default: if let t = cool ?? heat { out["target"] = t.rounded() }
+ }
+ if let speed = v.double("rotationSpeed") { out["fan"] = speed <= 34 ? "low" : speed <= 67 ? "medium" : "high" }
+ if let swing = v.double("swing") { out["swing"] = swing == 1 ? "swing" : "off" }
+ return out
+ }
+
+ /// `validModes`: the target-state values the accessory accepts, when it says.
+ public static func acFeatures(kind: Kind, has: Set<String>, validModes: [Int]? = nil) -> [String: Any] {
+ let table = kind == .thermostat ? thermostatModes : heaterCoolerModes
+ let accepted = validModes.map(Set.init) ?? Set(table.keys)
+ let modes = ["cool", "heat", "auto"].filter { m in table.contains { $0.value == m && accepted.contains($0.key) } }
+ return [
+ "modes": modes,
+ "fans": has.contains("rotationSpeed") ? ["low", "medium", "high"] : [],
+ "swing": has.contains("swing"), "sleep": false, "eco": false,
+ ]
+ }
+
+ public static func acWrites(_ patch: [String: Any], state: [String: Any], kind: Kind, has: Set<String>,
+ limits: [String: (Double, Double)] = [:]) -> [(String, Any)] {
+ var out: [(String, Any)] = []
+ func clamp(_ name: String, _ value: Double) -> Double {
+ guard let (lo, hi) = limits[name] else { return value }
+ return max(lo, min(hi, value))
+ }
+ let mode = (patch["mode"] as? String) ?? (state["mode"] as? String) ?? "cool"
+ if kind == .thermostat {
+ if patch["on"] as? Bool == false { return [("targetHeatingCooling", 0)] }
+ if patch["on"] as? Bool == true || patch["mode"] != nil,
+ let value = thermostatModes.first(where: { $0.value == mode })?.key {
+ out.append(("targetHeatingCooling", value))
+ }
+ if let t = patch["target"] as? Double { out.append(("targetTemperature", clamp("targetTemperature", t))) }
+ return out
+ }
+ if let on = patch["on"] as? Bool { out.append(("active", on ? 1 : 0)) }
+ if patch["mode"] != nil, let value = heaterCoolerModes.first(where: { $0.value == mode })?.key {
+ out.append(("targetState", value))
+ }
+ if let t = (patch["target"] as? Double) ?? (patch["mode"] != nil ? state["target"] as? Double : nil) {
+ switch mode {
+ case "heat": out.append(("heatingThreshold", clamp("heatingThreshold", t)))
+ case "auto":
+ if has.contains("heatingThreshold") { out.append(("heatingThreshold", clamp("heatingThreshold", t - 1))) }
+ if has.contains("coolingThreshold") { out.append(("coolingThreshold", clamp("coolingThreshold", t + 1))) }
+ default: out.append(("coolingThreshold", clamp("coolingThreshold", t)))
+ }
+ }
+ if let fan = patch["fan"] as? String, has.contains("rotationSpeed") {
+ let speed: Double = ["low": 33, "medium": 66, "high": 100, "turbo": 100][fan] ?? 66
+ out.append(("rotationSpeed", clamp("rotationSpeed", speed)))
+ }
+ if let swing = patch["swing"] as? String, has.contains("swing") { out.append(("swing", swing == "off" ? 0 : 1)) }
+ return out
+ }
+}
diff --git a/core/Sources/HouseCore/HomeKitService.swift b/core/Sources/HouseCore/HomeKitService.swift
new file mode 100644
index 0000000..0e92ec3
--- /dev/null
+++ b/core/Sources/HouseCore/HomeKitService.swift
@@ -0,0 +1,242 @@
+#if os(iOS) && canImport(HomeKit)
+import HomeKit
+
+/// Apple Home through HomeKit: every lamp, outlet, air conditioner (heater cooler or
+/// thermostat) and temperature sensor in the user's homes, Matter devices included.
+/// HomeKit is only offered to iPhone and iPad apps (and to Mac Catalyst apps from the
+/// App Store), so the Mac reaches it through the iPhone's catalog — see `RemoteCatalogService`.
+///
+/// Nothing is asked of the user until `enable()` — creating the home manager is what shows
+/// the system's "would like to access your Home Data" prompt.
+@MainActor
+public final class HomeKitService: NSObject, DeviceService {
+ public let id = "homekit"
+ public let title = "Apple Home"
+ public var onChange: (() -> Void)?
+ /// Called whenever the list of homes, accessories or rooms changes.
+ public var onCatalogChange: (() -> Void)?
+
+ private var manager: HMHomeManager?
+ private var ready = false
+ private var waiting: [CheckedContinuation<Void, Never>] = []
+ private var watched: Set<String> = []
+ /// Lamps last set to a white temperature (true) or a colour (false) from this app.
+ private var whiteMode: [String: Bool] = [:]
+ private static let enabledKey = "homekit.enabled"
+
+ public override init() {
+ super.init()
+ if UserDefaults.standard.bool(forKey: Self.enabledKey) { start() }
+ }
+
+ public var isEnabled: Bool { manager != nil }
+ public var isConnected: Bool { manager != nil && authorized }
+ private var authorized: Bool { manager?.authorizationStatus.contains(.authorized) == true }
+ /// True when the user said no to the system prompt (Settings → Privacy → HomeKit undoes it).
+ public var isDenied: Bool {
+ guard let status = manager?.authorizationStatus else { return false }
+ return status.contains(.determined) && !status.contains(.authorized)
+ }
+
+ public var info: [String: Any] {
+ guard let manager else { return ["connected": false] }
+ let homes = manager.homes.map(\.name)
+ return ["connected": isConnected, "denied": isDenied, "homes": homes,
+ "accessories": manager.homes.reduce(0) { $0 + $1.accessories.count }]
+ }
+
+ /// Starts HomeKit (and with it the permission prompt the first time).
+ public func enable() async {
+ UserDefaults.standard.set(true, forKey: Self.enabledKey)
+ start()
+ await untilReady()
+ }
+
+ public func disconnect() {
+ UserDefaults.standard.set(false, forKey: Self.enabledKey)
+ manager?.delegate = nil
+ manager = nil
+ ready = false
+ }
+
+ public func watch(_ ids: Set<String>) {
+ watched = ids
+ subscribe()
+ }
+
+ private func start() {
+ guard manager == nil else { return }
+ let manager = HMHomeManager()
+ manager.delegate = self
+ self.manager = manager
+ }
+
+ private func untilReady(timeout: Double = 20) async {
+ guard !ready, manager != nil else { return }
+ await withCheckedContinuation { continuation in
+ waiting.append(continuation)
+ Task { @MainActor [weak self] in
+ try? await Task.sleep(nanoseconds: UInt64(timeout * 1_000_000_000))
+ self?.release()
+ }
+ }
+ }
+
+ private func release() {
+ let all = waiting
+ waiting = []
+ all.forEach { $0.resume() }
+ }
+
+ // MARK: - Catalog
+
+ private struct Entry {
+ let service: HMService
+ let accessory: HMAccessory
+ let kind: HomeKitMapper.Kind
+ let home: HMHome
+ }
+
+ private func entries() -> [Entry] {
+ var out: [Entry] = []
+ for home in manager?.homes ?? [] {
+ for accessory in home.accessories {
+ for service in accessory.services {
+ guard let kind = HomeKitMapper.kind(ofService: service.serviceType) else { continue }
+ out.append(Entry(service: service, accessory: accessory, kind: kind, home: home))
+ }
+ }
+ }
+ return out
+ }
+
+ private func names(_ service: HMService) -> [String: HMCharacteristic] {
+ var out: [String: HMCharacteristic] = [:]
+ for c in service.characteristics {
+ if let name = HomeKitMapper.name(ofCharacteristic: c.characteristicType) { out[name] = c }
+ }
+ return out
+ }
+
+ public func devices() async throws -> [ServiceDevice] {
+ guard manager != nil else { throw ServiceFailure("Turn on Apple Home first") }
+ await untilReady()
+ guard authorized else { throw ServiceFailure("House Control may not use your Home data. Allow it in Settings → Privacy & Security → HomeKit.") }
+ let several = (manager?.homes.count ?? 0) > 1
+ return entries().map { entry in
+ let characteristics = Set(names(entry.service).keys)
+ let label = entry.service.name.isEmpty ? entry.accessory.name : entry.service.name
+ let room = entry.accessory.room.map { several ? "\(entry.home.name) · \($0.name)" : $0.name }
+ var device = ServiceDevice(id: entry.service.uniqueIdentifier.uuidString, name: label, kind: entry.kind.device, room: room)
+ device.online = entry.accessory.isReachable
+ if entry.kind == .light { device.capabilities = HomeKitMapper.capabilities(characteristics) }
+ if entry.kind.device == .ac {
+ let key = entry.kind == .thermostat ? "targetTemperature" : "coolingThreshold"
+ if let c = names(entry.service)[key], let lo = c.metadata?.minimumValue?.doubleValue,
+ let hi = c.metadata?.maximumValue?.doubleValue { device.range = (lo, hi) }
+ }
+ let maker = entry.accessory.manufacturer.map { "\($0) · " } ?? ""
+ device.detail = maker + entry.kind.rawValue
+ return device
+ }.sorted { ($0.kind.rawValue, $0.name) < ($1.kind.rawValue, $1.name) }
+ }
+
+ public func read(_ ids: Set<String>) async throws -> [String: DeviceReading] {
+ guard isConnected else { return [:] }
+ await untilReady()
+ var out: [String: DeviceReading] = [:]
+ for entry in entries() where ids.contains(entry.service.uniqueIdentifier.uuidString) {
+ let id = entry.service.uniqueIdentifier.uuidString
+ guard entry.accessory.isReachable else { out[id] = DeviceReading(online: false); continue }
+ var values: [String: Any] = [:]
+ for (name, characteristic) in names(entry.service) {
+ try? await characteristic.readValue()
+ if let value = characteristic.value { values[name] = value }
+ }
+ switch entry.kind {
+ case .light, .outlet:
+ out[id] = DeviceReading(light: HomeKitMapper.lightState(values, whiteMode: whiteMode[id]))
+ case .heaterCooler, .thermostat:
+ let has = Set(names(entry.service).keys)
+ let valid = names(entry.service)[entry.kind == .thermostat ? "targetHeatingCooling" : "targetState"]?
+ .metadata?.validValues?.map(\.intValue)
+ out[id] = DeviceReading(ac: HomeKitMapper.acState(values, kind: entry.kind),
+ features: HomeKitMapper.acFeatures(kind: entry.kind, has: has, validModes: valid))
+ case .sensor:
+ out[id] = DeviceReading(temperature: values.double("currentTemperature"))
+ }
+ }
+ return out
+ }
+
+ public func send(kind: DeviceKind, id: String, patch: [String: Any], state: [String: Any]) async throws {
+ guard let entry = entries().first(where: { $0.service.uniqueIdentifier.uuidString == id }) else {
+ throw ServiceFailure("This device is no longer in Apple Home")
+ }
+ guard entry.accessory.isReachable else { throw ServiceFailure("\(entry.accessory.name) is not responding") }
+ let characteristics = names(entry.service)
+ var limits: [String: (Double, Double)] = [:]
+ for (name, c) in characteristics {
+ if let lo = c.metadata?.minimumValue?.doubleValue, let hi = c.metadata?.maximumValue?.doubleValue { limits[name] = (lo, hi) }
+ }
+ let has = Set(characteristics.keys)
+ let writes = kind == .light
+ ? HomeKitMapper.lightWrites(DeviceKind.withPower(patch, state: state), kind: entry.kind, has: has, limits: limits)
+ : HomeKitMapper.acWrites(patch, state: state, kind: entry.kind, has: has, limits: limits)
+ if patch["temp"] != nil { whiteMode[id] = true }
+ if patch["color"] is String { whiteMode[id] = false }
+ for (name, value) in writes {
+ guard let characteristic = characteristics[name] else { continue }
+ do {
+ try await characteristic.writeValue(value)
+ } catch {
+ throw ServiceFailure("\(entry.accessory.name): \(error.localizedDescription)")
+ }
+ }
+ }
+
+ // MARK: - Live updates
+
+ private func subscribe() {
+ for entry in entries() where watched.contains(entry.service.uniqueIdentifier.uuidString) {
+ entry.accessory.delegate = self
+ for (_, characteristic) in names(entry.service)
+ where characteristic.properties.contains(HMCharacteristicPropertySupportsEventNotification) && !characteristic.isNotificationEnabled {
+ characteristic.enableNotification(true) { _ in }
+ }
+ }
+ }
+}
+
+extension HomeKitService: HMHomeManagerDelegate, HMAccessoryDelegate, HMHomeDelegate {
+ nonisolated public func homeManagerDidUpdateHomes(_ manager: HMHomeManager) {
+ MainActor.assumeIsolated {
+ ready = true
+ for home in manager.homes { home.delegate = self }
+ release()
+ subscribe()
+ onCatalogChange?()
+ }
+ }
+
+ nonisolated public func homeManager(_ manager: HMHomeManager, didUpdate status: HMHomeManagerAuthorizationStatus) {
+ MainActor.assumeIsolated { onCatalogChange?() }
+ }
+
+ nonisolated public func home(_ home: HMHome, didAdd accessory: HMAccessory) {
+ MainActor.assumeIsolated { subscribe(); onCatalogChange?() }
+ }
+
+ nonisolated public func home(_ home: HMHome, didRemove accessory: HMAccessory) {
+ MainActor.assumeIsolated { onCatalogChange?() }
+ }
+
+ nonisolated public func accessory(_ accessory: HMAccessory, service: HMService, didUpdateValueFor characteristic: HMCharacteristic) {
+ MainActor.assumeIsolated { onChange?() }
+ }
+
+ nonisolated public func accessoryDidUpdateReachability(_ accessory: HMAccessory) {
+ MainActor.assumeIsolated { onChange?() }
+ }
+}
+#endif
diff --git a/core/Sources/HouseCore/HueService.swift b/core/Sources/HouseCore/HueService.swift
new file mode 100644
index 0000000..91c49c6
--- /dev/null
+++ b/core/Sources/HouseCore/HueService.swift
@@ -0,0 +1,361 @@
+import CryptoKit
+import Foundation
+
+/// A Philips Hue Bridge on the local network, through its own API (CLIP v2). No cloud and no
+/// account: the bridge hands out a key when its round button is pressed. Hue lamps become the
+/// plan's lamps; the temperature reported by Hue motion sensors can stand in for an AC's room
+/// reading. The bridge's event stream tells the hub at once when a lamp changes elsewhere.
+@MainActor
+public final class HueService: DeviceService {
+ public let id = "hue"
+ public let title = "Philips Hue"
+ public var onChange: (() -> Void)?
+
+ struct Config: Codable {
+ var host: String
+ var key: String
+ var bridgeId: String?
+ var name: String?
+ /// SHA-256 of the bridge's certificate, remembered when it was paired: the bridge's
+ /// certificate is self-signed, so it is trusted on first use and checked ever after.
+ var certificate: String?
+ }
+
+ private let vault: SecretStore
+ private var config: Config?
+ private let trust = BridgeTrust()
+ private let session: URLSession
+ /// The event stream stays open for hours: it gets a session without the short timeout.
+ private let streamSession: URLSession
+ private var stream: Task<Void, Never>?
+ private var watched: Set<String> = []
+
+ public init(vault: SecretStore) {
+ self.vault = vault
+ let configuration = URLSessionConfiguration.ephemeral
+ configuration.timeoutIntervalForRequest = 8
+ session = URLSession(configuration: configuration, delegate: trust, delegateQueue: nil)
+ let long = URLSessionConfiguration.ephemeral
+ long.timeoutIntervalForRequest = 600 // the bridge sends a keep-alive well within this
+ streamSession = URLSession(configuration: long, delegate: trust, delegateQueue: nil)
+ config = vault.read().flatMap { try? JSONDecoder().decode(Config.self, from: $0) }
+ if let config { trust.pin(host: config.host, fingerprint: config.certificate); listen() }
+ }
+
+ public var isConnected: Bool { config != nil }
+
+ public var info: [String: Any] {
+ guard let config else { return ["connected": false] }
+ return ["connected": true, "host": config.host, "name": config.name ?? "Hue Bridge", "bridgeId": config.bridgeId ?? ""]
+ }
+
+ public var shareable: [String: Any]? {
+ guard let config, let data = try? JSONEncoder().encode(config) else { return nil }
+ return try? JSONSerialization.jsonObject(with: data) as? [String: Any]
+ }
+
+ public func adopt(_ shared: [String: Any]?) {
+ guard let shared, let data = try? JSONSerialization.data(withJSONObject: shared),
+ let incoming = try? JSONDecoder().decode(Config.self, from: data) else {
+ if config != nil { disconnect() }
+ return
+ }
+ guard incoming.host != config?.host || incoming.key != config?.key else { return }
+ config = incoming
+ vault.write(data)
+ trust.pin(host: incoming.host, fingerprint: incoming.certificate)
+ listen()
+ }
+
+ public func disconnect() {
+ config = nil
+ vault.write(nil)
+ stream?.cancel()
+ stream = nil
+ }
+
+ public func watch(_ ids: Set<String>) { watched = ids }
+
+ // MARK: - Pairing
+
+ /// Asks the bridge at `host` for a key. Throws `ButtonNotPressed` until someone presses
+ /// the round button on the bridge (it then accepts pairing for 30 seconds).
+ public struct ButtonNotPressed: LocalizedError {
+ public var errorDescription: String? { "Press the round button on the Hue Bridge." }
+ }
+
+ public func pair(host raw: String, bridgeId: String? = nil, name: String? = nil) async throws {
+ let host = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ .replacingOccurrences(of: "https://", with: "").replacingOccurrences(of: "http://", with: "")
+ .trimmingCharacters(in: CharacterSet(charactersIn: "/"))
+ guard !host.isEmpty, let url = URL(string: "https://\(host)/api") else { throw ServiceFailure("Enter the bridge’s address") }
+ trust.pin(host: host, fingerprint: nil) // trust on first use, remember below
+ var request = URLRequest(url: url)
+ request.httpMethod = "POST"
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ #if os(iOS)
+ let device = "iPhone"
+ #else
+ let device = "Mac"
+ #endif
+ request.httpBody = try JSONSerialization.data(withJSONObject: ["devicetype": "house_control#\(device)", "generateclientkey": true])
+ let data: Data
+ do {
+ (data, _) = try await session.data(for: request)
+ } catch {
+ throw ServiceFailure("No Hue Bridge answered at \(host): \(error.localizedDescription)")
+ }
+ let answer = (try? JSONSerialization.jsonObject(with: data) as? [[String: Any]])?.first ?? [:]
+ if let error = answer["error"] as? [String: Any] {
+ if (error["type"] as? Int) == 101 { throw ButtonNotPressed() }
+ throw ServiceFailure("The bridge said: \(error["description"] as? String ?? "error")")
+ }
+ guard let key = (answer["success"] as? [String: Any])?["username"] as? String else {
+ throw ServiceFailure("The bridge at \(host) did not answer like a Hue Bridge")
+ }
+ var paired = Config(host: host, key: key, bridgeId: bridgeId, name: name, certificate: trust.fingerprint(for: host))
+ config = paired
+ // Fill in the bridge's own name for the editor.
+ if let bridge = try? await get("/clip/v2/resource/bridge").first,
+ let device = try? await get("/clip/v2/resource/device").first(where: {
+ (($0["services"] as? [[String: Any]]) ?? []).contains { $0["rid"] as? String == bridge["id"] as? String }
+ }) {
+ paired.bridgeId = bridge["bridge_id"] as? String ?? bridgeId
+ paired.name = (device["metadata"] as? [String: Any])?["name"] as? String ?? name
+ }
+ config = paired
+ vault.write(try? JSONEncoder().encode(paired))
+ listen()
+ }
+
+ // MARK: - Devices
+
+ public func devices() async throws -> [ServiceDevice] {
+ async let lights = get("/clip/v2/resource/light")
+ async let rooms = get("/clip/v2/resource/room")
+ async let sensors = get("/clip/v2/resource/temperature")
+ async let hardware = get("/clip/v2/resource/device")
+ async let links = get("/clip/v2/resource/zigbee_connectivity")
+ let (lightList, roomList, sensorList, deviceList, linkList) = try await (lights, rooms, sensors, hardware, links)
+
+ let roomOf = Self.roomIndex(roomList)
+ let deviceName = Dictionary(deviceList.compactMap { d -> (String, String)? in
+ guard let id = d["id"] as? String, let name = (d["metadata"] as? [String: Any])?["name"] as? String else { return nil }
+ return (id, name)
+ }, uniquingKeysWith: { a, _ in a })
+ let offline = Set(linkList.compactMap { l -> String? in
+ (l["status"] as? String) == "connected" ? nil : (l["owner"] as? [String: Any])?["rid"] as? String
+ })
+
+ var out: [ServiceDevice] = []
+ for light in lightList {
+ guard var device = Self.device(fromLight: light) else { continue }
+ let owner = (light["owner"] as? [String: Any])?["rid"] as? String ?? ""
+ device.room = roomOf[owner]
+ device.online = !offline.contains(owner)
+ out.append(device)
+ }
+ for sensor in sensorList {
+ guard let id = sensor["id"] as? String else { continue }
+ let owner = (sensor["owner"] as? [String: Any])?["rid"] as? String ?? ""
+ var device = ServiceDevice(id: id, name: deviceName[owner] ?? "Hue sensor", kind: .sensor, room: roomOf[owner])
+ device.detail = "temperature sensor"
+ device.online = !offline.contains(owner)
+ out.append(device)
+ }
+ return out.sorted { ($0.kind.rawValue, $0.name) < ($1.kind.rawValue, $1.name) }
+ }
+
+ public func read(_ ids: Set<String>) async throws -> [String: DeviceReading] {
+ guard !ids.isEmpty else { return [:] }
+ async let lights = get("/clip/v2/resource/light")
+ async let sensors = get("/clip/v2/resource/temperature")
+ let (lightList, sensorList) = try await (lights, sensors)
+ var out: [String: DeviceReading] = [:]
+ for light in lightList {
+ guard let id = light["id"] as? String, ids.contains(id) else { continue }
+ out[id] = DeviceReading(light: Self.lightState(light))
+ }
+ for sensor in sensorList {
+ guard let id = sensor["id"] as? String, ids.contains(id) else { continue }
+ out[id] = DeviceReading(temperature: Self.temperature(sensor))
+ }
+ return out
+ }
+
+ public func send(kind: DeviceKind, id: String, patch: [String: Any], state: [String: Any]) async throws {
+ guard kind == .light else { throw ServiceFailure("Hue has no air conditioners") }
+ let body = Self.lightBody(patch: DeviceKind.withPower(patch, state: state))
+ guard !body.isEmpty else { return }
+ let answer = try await call("PUT", "/clip/v2/resource/light/\(id)", body: body)
+ if let errors = answer["errors"] as? [[String: Any]], let first = errors.first {
+ throw ServiceFailure("Hue: \(first["description"] as? String ?? "the bridge refused the change")")
+ }
+ }
+
+ // MARK: - Mapping
+
+ static func roomIndex(_ rooms: [[String: Any]]) -> [String: String] {
+ var out: [String: String] = [:]
+ for room in rooms {
+ guard let name = (room["metadata"] as? [String: Any])?["name"] as? String else { continue }
+ for child in room["children"] as? [[String: Any]] ?? [] {
+ if let rid = child["rid"] as? String { out[rid] = name }
+ }
+ }
+ return out
+ }
+
+ static func device(fromLight light: [String: Any]) -> ServiceDevice? {
+ guard let id = light["id"] as? String else { return nil }
+ let name = (light["metadata"] as? [String: Any])?["name"] as? String ?? "Hue light"
+ var device = ServiceDevice(id: id, name: name, kind: .light)
+ var caps: [String] = []
+ if light["dimming"] != nil { caps.append("brightness") }
+ if light["color_temperature"] != nil { caps.append("temp") }
+ if light["color"] != nil { caps.append("color") }
+ device.capabilities = caps
+ let archetype = (light["metadata"] as? [String: Any])?["archetype"] as? String ?? "light"
+ device.detail = "\(archetype.replacingOccurrences(of: "_", with: " ")) · " + (caps.isEmpty ? "on/off" : caps.joined(separator: ", "))
+ return device
+ }
+
+ static func lightState(_ light: [String: Any]) -> [String: Any] {
+ var out: [String: Any] = [:]
+ if let on = (light["on"] as? [String: Any])?["on"] as? Bool { out["on"] = on }
+ if let b = (light["dimming"] as? [String: Any])?.double("brightness") { out["brightness"] = max(0.05, min(1, b / 100)) }
+ let ct = light["color_temperature"] as? [String: Any]
+ if ct?["mirek_valid"] as? Bool == true, let mirek = ct?.double("mirek") {
+ out["temp"] = max(2200, min(6500, ColorMath.kelvin(mired: mirek)))
+ out["color"] = NSNull()
+ } else if let xy = (light["color"] as? [String: Any])?["xy"] as? [String: Any],
+ let x = xy.double("x"), let y = xy.double("y") {
+ out["color"] = ColorMath.hex(x: x, y: y)
+ }
+ return out
+ }
+
+ static func temperature(_ sensor: [String: Any]) -> Double? {
+ let t = sensor["temperature"] as? [String: Any]
+ return (t?["temperature_report"] as? [String: Any])?.double("temperature") ?? t?.double("temperature")
+ }
+
+ static func lightBody(patch: [String: Any]) -> [String: Any] {
+ var body: [String: Any] = [:]
+ if let on = patch["on"] as? Bool { body["on"] = ["on": on] }
+ if let b = patch["brightness"] as? Double { body["dimming"] = ["brightness": (b * 1000).rounded() / 10] }
+ if let k = patch["temp"] as? Double { body["color_temperature"] = ["mirek": Int(ColorMath.mired(kelvin: k).rounded())] }
+ if let hex = patch["color"] as? String, let (x, y) = ColorMath.xy(hex) { body["color"] = ["xy": ["x": x, "y": y]] }
+ return body
+ }
+
+ // MARK: - HTTP
+
+ private func get(_ path: String) async throws -> [[String: Any]] {
+ try await call("GET", path)["data"] as? [[String: Any]] ?? []
+ }
+
+ private func call(_ method: String, _ path: String, body: [String: Any]? = nil) async throws -> [String: Any] {
+ guard let config, let url = URL(string: "https://\(config.host)\(path)") else { throw ServiceFailure("Pair a Hue Bridge first") }
+ var request = URLRequest(url: url)
+ request.httpMethod = method
+ request.setValue(config.key, forHTTPHeaderField: "hue-application-key")
+ if let body {
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ request.httpBody = try JSONSerialization.data(withJSONObject: body)
+ }
+ let data: Data, response: URLResponse
+ do {
+ (data, response) = try await session.data(for: request)
+ } catch {
+ throw ServiceFailure("The Hue Bridge at \(config.host) did not answer: \(error.localizedDescription)")
+ }
+ let status = (response as? HTTPURLResponse)?.statusCode ?? 0
+ if status == 403 || status == 401 { throw ServiceFailure("The Hue Bridge no longer accepts this Mac’s key. Pair it again.") }
+ let json = (try? JSONSerialization.jsonObject(with: data) as? [String: Any]) ?? [:]
+ guard (200..<300).contains(status) else {
+ let reason = ((json["errors"] as? [[String: Any]])?.first?["description"] as? String) ?? "status \(status)"
+ throw ServiceFailure("Hue: \(reason)")
+ }
+ return json
+ }
+
+ // MARK: - Event stream
+
+ private func listen() {
+ stream?.cancel()
+ guard let config, let url = URL(string: "https://\(config.host)/eventstream/clip/v2") else { return }
+ stream = Task { @MainActor [weak self] in
+ while !Task.isCancelled {
+ var request = URLRequest(url: url, timeoutInterval: 3600)
+ request.setValue(config.key, forHTTPHeaderField: "hue-application-key")
+ request.setValue("text/event-stream", forHTTPHeaderField: "Accept")
+ do {
+ guard let session = self?.streamSession, let trust = self?.trust else { return }
+ let (bytes, _) = try await session.bytes(for: request, delegate: trust)
+ for try await line in bytes.lines where line.hasPrefix("data:") {
+ guard let self else { return }
+ if self.watched.contains(where: { line.contains($0) }) { self.onChange?() }
+ }
+ } catch {}
+ try? await Task.sleep(nanoseconds: 10_000_000_000) // the bridge restarted or the Wi-Fi dropped
+ }
+ }
+ }
+}
+
+/// Trusts each Hue Bridge's self-signed certificate the first time, and only that
+/// certificate afterwards.
+final class BridgeTrust: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
+ private let lock = NSLock()
+ private var pins: [String: String?] = [:]
+ private var seen: [String: String] = [:]
+
+ func pin(host: String, fingerprint: String?) {
+ lock.lock(); defer { lock.unlock() }
+ pins[Self.bare(host)] = .some(fingerprint)
+ }
+
+ func fingerprint(for host: String) -> String? {
+ lock.lock(); defer { lock.unlock() }
+ return seen[Self.bare(host)]
+ }
+
+ /// "192.168.1.2:8443" → "192.168.1.2", "[fe80::1]:443" → "fe80::1": what TLS challenges name.
+ static func bare(_ host: String) -> String {
+ if host.hasPrefix("["), let end = host.firstIndex(of: "]") {
+ return String(host[host.index(after: host.startIndex)..<end])
+ }
+ let parts = host.split(separator: ":")
+ return parts.count == 2 ? String(parts[0]) : host
+ }
+
+ // A streaming task (the event stream) asks its task-level delegate, the others the session's.
+ func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge,
+ completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
+ urlSession(session, didReceive: challenge, completionHandler: completionHandler)
+ }
+
+ func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge,
+ completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
+ let host = challenge.protectionSpace.host
+ guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
+ let trust = challenge.protectionSpace.serverTrust,
+ let chain = SecTrustCopyCertificateChain(trust) as? [SecCertificate], let leaf = chain.first else {
+ completionHandler(.performDefaultHandling, nil)
+ return
+ }
+ let fingerprint = SHA256.hash(data: SecCertificateCopyData(leaf) as Data).map { String(format: "%02x", $0) }.joined()
+ lock.lock()
+ let expected = pins[host]
+ seen[host] = fingerprint
+ lock.unlock()
+ switch expected {
+ case .none: completionHandler(.performDefaultHandling, nil) // not a bridge we know
+ case .some(nil): completionHandler(.useCredential, URLCredential(trust: trust)) // pairing now
+ case .some(let pinned?):
+ completionHandler(pinned == fingerprint ? .useCredential : .cancelAuthenticationChallenge,
+ pinned == fingerprint ? URLCredential(trust: trust) : nil)
+ }
+ }
+}
diff --git a/core/Sources/HouseCore/RemoteCatalogService.swift b/core/Sources/HouseCore/RemoteCatalogService.swift
new file mode 100644
index 0000000..1b38f13
--- /dev/null
+++ b/core/Sources/HouseCore/RemoteCatalogService.swift
@@ -0,0 +1,58 @@
+import Foundation
+
+/// A platform this device cannot reach itself, known from the list another device sent:
+/// Apple Home on the Mac, as seen by the paired iPhone. Its devices can be linked in the
+/// editor; they are switched from the iPhone, and stay simulated on the Mac.
+@MainActor
+public final class RemoteCatalogService: DeviceService {
+ public let id: String
+ public let title: String
+ public var onChange: (() -> Void)?
+ private let file: URL
+ private var catalog: [String: Any]
+
+ /// The catalog is cached in `file`, so the editor has it while the phone is away.
+ public init(id: String, title: String, file: URL) {
+ self.id = id
+ self.title = title
+ self.file = file
+ catalog = (try? Data(contentsOf: file)).flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] } ?? [:]
+ }
+
+ public var isConnected: Bool { !(catalog["devices"] as? [[String: Any]] ?? []).isEmpty }
+ public var controlsDevices: Bool { false }
+
+ public var info: [String: Any] {
+ ["connected": isConnected, "remote": true, "from": catalog["from"] as? String ?? "",
+ "updated": catalog["updated"] as? Double ?? 0, "count": (catalog["devices"] as? [Any])?.count ?? 0]
+ }
+
+ /// Stores what `device` (the iPhone's name) reported.
+ public func update(devices: [[String: Any]], from device: String) {
+ catalog = ["devices": devices, "from": device, "updated": Date().timeIntervalSince1970]
+ if let data = try? JSONSerialization.data(withJSONObject: catalog) { try? data.write(to: file, options: .atomic) }
+ onChange?()
+ }
+
+ public func devices() async throws -> [ServiceDevice] {
+ (catalog["devices"] as? [[String: Any]] ?? []).compactMap { d in
+ guard let id = d["id"] as? String, let name = d["name"] as? String,
+ let kind = DeviceKind(rawValue: d["kind"] as? String ?? "") else { return nil }
+ var device = ServiceDevice(id: id, name: name, kind: kind, room: d["room"] as? String)
+ device.online = d["online"] as? Bool ?? true
+ device.capabilities = d["capabilities"] as? [String] ?? []
+ if let lo = d.double("min"), let hi = d.double("max") { device.range = (lo, hi) }
+ device.detail = d["detail"] as? String ?? ""
+ return device
+ }
+ }
+
+ public func read(_ ids: Set<String>) async throws -> [String: DeviceReading] { [:] }
+
+ public func send(kind: DeviceKind, id: String, patch: [String: Any], state: [String: Any]) async throws {}
+
+ public func disconnect() {
+ catalog = [:]
+ try? FileManager.default.removeItem(at: file)
+ }
+}
diff --git a/core/Sources/HouseCore/ServiceDiscovery.swift b/core/Sources/HouseCore/ServiceDiscovery.swift
new file mode 100644
index 0000000..358ac02
--- /dev/null
+++ b/core/Sources/HouseCore/ServiceDiscovery.swift
@@ -0,0 +1,106 @@
+import Foundation
+import Network
+
+/// A value that only ever changes on one serial queue.
+private final class QueueBox<T>: @unchecked Sendable {
+ var value: T
+ init(_ value: T) { self.value = value }
+}
+
+/// Finds Home Assistant servers and Hue Bridges on the local network with Bonjour, so
+/// connecting one is a click rather than typing an address.
+public enum ServiceDiscovery {
+ public struct Found {
+ public var name: String
+ public var host: String
+ public var port: Int
+ public var txt: [String: String]
+
+ public var dictionary: [String: Any] { ["name": name, "host": host, "port": port, "txt": txt] }
+ }
+
+ /// Everything advertising `type` ("_hue._tcp", "_home-assistant._tcp") within `seconds`.
+ public static func browse(_ type: String, seconds: Double = 3) async -> [Found] {
+ let browser = NWBrowser(for: .bonjourWithTXTRecord(type: type, domain: nil), using: .tcp)
+ let results: Set<NWBrowser.Result> = await withCheckedContinuation { continuation in
+ let queue = DispatchQueue(label: "house.discovery")
+ let latest = QueueBox<Set<NWBrowser.Result>>([]) // touched on `queue` only
+ browser.browseResultsChangedHandler = { results, _ in latest.value = results }
+ browser.start(queue: queue)
+ queue.asyncAfter(deadline: .now() + seconds) {
+ browser.cancel()
+ continuation.resume(returning: latest.value)
+ }
+ }
+ var out: [Found] = []
+ for result in results {
+ guard case .service(let name, _, _, _) = result.endpoint else { continue }
+ var txt: [String: String] = [:]
+ if case .bonjour(let record) = result.metadata {
+ for (key, value) in record.dictionary { txt[key] = value }
+ }
+ guard let (host, port) = await resolve(result.endpoint) else { continue }
+ out.append(Found(name: name, host: host, port: port, txt: txt))
+ }
+ return out.sorted { $0.name < $1.name }
+ }
+
+ /// The address behind a Bonjour service, found by opening (and closing) a connection to it.
+ private static func resolve(_ endpoint: NWEndpoint) async -> (String, Int)? {
+ await withCheckedContinuation { continuation in
+ let connection = NWConnection(to: endpoint, using: .tcp)
+ let queue = DispatchQueue(label: "house.discovery.resolve")
+ let done = QueueBox(false) // touched on `queue` only
+ let finish: @Sendable ((String, Int)?) -> Void = { value in
+ guard !done.value else { return }
+ done.value = true
+ connection.cancel()
+ continuation.resume(returning: value)
+ }
+ connection.stateUpdateHandler = { state in
+ switch state {
+ case .ready:
+ if case .hostPort(let host, let port) = connection.currentPath?.remoteEndpoint {
+ var name = "\(host)"
+ if let percent = name.firstIndex(of: "%") { name = String(name[..<percent]) } // drop "%en0"
+ if name.contains(":") { name = "[\(name)]" }
+ finish((name, Int(port.rawValue)))
+ } else {
+ finish(nil)
+ }
+ case .failed, .cancelled: finish(nil)
+ default: break
+ }
+ }
+ connection.start(queue: queue)
+ queue.asyncAfter(deadline: .now() + 3) { finish(nil) }
+ }
+ }
+
+ /// Home Assistant servers: their advertised address when they have one.
+ public static func homeAssistants() async -> [[String: Any]] {
+ await browse("_home-assistant._tcp").map { found in
+ let url = [found.txt["internal_url"], found.txt["base_url"]].compactMap { $0 }.first { !$0.isEmpty }
+ ?? "http://\(found.host):\(found.port)"
+ return ["name": found.txt["location_name"] ?? found.name, "url": url, "version": found.txt["version"] ?? ""]
+ }
+ }
+
+ /// Hue Bridges: Bonjour first, then Philips' discovery service for networks that block it.
+ public static func hueBridges() async -> [[String: Any]] {
+ var out = await browse("_hue._tcp").map { found -> [String: Any] in
+ // Real bridges serve HTTPS on 443; anything else (the lab's bridge) keeps its port.
+ ["name": found.name, "host": found.port == 443 ? found.host : "\(found.host):\(found.port)",
+ "bridgeId": found.txt["bridgeid"] ?? ""]
+ }
+ if out.isEmpty, let url = URL(string: "https://discovery.meethue.com/"),
+ let (data, _) = try? await URLSession.shared.data(from: url),
+ let list = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] {
+ out = list.compactMap { b in
+ guard let ip = b["internalipaddress"] as? String else { return nil }
+ return ["name": "Hue Bridge", "host": ip, "bridgeId": b["id"] as? String ?? ""]
+ }
+ }
+ return out
+ }
+}
diff --git a/core/Sources/HouseCore/SyncClient.swift b/core/Sources/HouseCore/SyncClient.swift
index 5daa8bd..21bc75a 100644
--- a/core/Sources/HouseCore/SyncClient.swift
+++ b/core/Sources/HouseCore/SyncClient.swift
@@ -27,6 +27,8 @@ public final class SyncClient {
/// What the Mac should be showing for this phone, and whether it has been told yet.
private var qrContent: String?
private var qrUnsent = false
+ /// This phone's Apple Home devices, waiting to be sent to the Mac.
+ private var catalog: [[String: Any]]?
/// Set to connect straight to a host and port instead of browsing (tests).
var fixedEndpoint: NWEndpoint?
@@ -101,6 +103,19 @@ public final class SyncClient {
return flushQR()
}
+ /// Hands the Mac this phone's Apple Home devices (the Mac cannot see Apple Home itself),
+ /// now or as soon as it is connected.
+ public func sendCatalog(_ devices: [[String: Any]]) {
+ catalog = devices
+ flushCatalog()
+ }
+
+ private func flushCatalog() {
+ guard let catalog, let channel, status == .connected else { return }
+ channel.send(["type": "catalog", "devices": catalog])
+ self.catalog = nil
+ }
+
private func flushQR() -> Bool {
guard qrUnsent, let channel, status == .connected else { return false }
var message: [String: Any] = ["type": "showQR"]
@@ -175,6 +190,7 @@ public final class SyncClient {
guard let self, let state = SyncState(message: message) else { return }
self.set(.connected)
_ = self.flushQR()
+ self.flushCatalog()
self.onState?(state)
}
channel.onClose = { [weak self] error in
diff --git a/core/Sources/HouseCore/SyncProtocol.swift b/core/Sources/HouseCore/SyncProtocol.swift
index 81eb92a..c2d5766 100644
--- a/core/Sources/HouseCore/SyncProtocol.swift
+++ b/core/Sources/HouseCore/SyncProtocol.swift
@@ -73,19 +73,26 @@ public struct SyncState {
/// It identifies the account; it is not a credential.
public var userCode: String
public var smartLifeConnected: Bool
+ /// The Mac's Home Assistant and Hue connections (address and token / bridge key), so the
+ /// phone controls the same devices without setting anything up. Only ever sent over this
+ /// channel, which nothing but a paired phone can open. Nil from a Mac that predates them.
+ public var connections: [String: Any]?
- public init(macName: String, revision: String, plan: Data?, userCode: String, smartLifeConnected: Bool) {
+ public init(macName: String, revision: String, plan: Data?, userCode: String, smartLifeConnected: Bool,
+ connections: [String: Any]? = nil) {
self.macName = macName
self.revision = revision
self.plan = plan
self.userCode = userCode
self.smartLifeConnected = smartLifeConnected
+ self.connections = connections
}
func message(includingPlan: Bool) -> [String: Any] {
var out: [String: Any] = ["type": "state", "mac": macName, "rev": revision,
"userCode": userCode, "smartLife": smartLifeConnected]
if includingPlan, let plan, let text = String(data: plan, encoding: .utf8) { out["plan"] = text }
+ if let connections { out["connections"] = connections }
return out
}
@@ -95,7 +102,8 @@ public struct SyncState {
revision: message["rev"] as? String ?? "",
plan: (message["plan"] as? String).map { Data($0.utf8) },
userCode: message["userCode"] as? String ?? "",
- smartLifeConnected: message["smartLife"] as? Bool ?? false)
+ smartLifeConnected: message["smartLife"] as? Bool ?? false,
+ connections: message["connections"] as? [String: Any])
}
}
diff --git a/core/Sources/HouseCore/SyncServer.swift b/core/Sources/HouseCore/SyncServer.swift
index 0b0b3d4..f9b38ce 100644
--- a/core/Sources/HouseCore/SyncServer.swift
+++ b/core/Sources/HouseCore/SyncServer.swift
@@ -32,6 +32,8 @@ public final class SyncServer {
/// A phone that disconnects does not take its code down: it is scanned from another
/// app on that phone, and iOS cuts the connection as soon as ours leaves the screen.
public var onShowQR: ((String?, String) -> Void)?
+ /// A phone sends the devices of its Apple Home (which only it can reach), for the editor.
+ public var onCatalog: (([[String: Any]], String) -> Void)?
/// `store` keeps the pairing (by default `sync.json` next to the plan, readable by its user only).
public init(store: SecretStore) {
@@ -165,6 +167,9 @@ public final class SyncServer {
case "showQR":
guard !peer.name.isEmpty else { return }
onShowQR?(message["content"] as? String, peer.name)
+ case "catalog":
+ guard !peer.name.isEmpty, let devices = message["devices"] as? [[String: Any]] else { return }
+ onCatalog?(devices, peer.name)
default:
break
}
diff --git a/core/Tests/HouseCoreTests/DeviceTests.swift b/core/Tests/HouseCoreTests/DeviceTests.swift
index 1f86506..5dcf1a2 100644
--- a/core/Tests/HouseCoreTests/DeviceTests.swift
+++ b/core/Tests/HouseCoreTests/DeviceTests.swift
@@ -50,7 +50,7 @@ final class DeviceTests: XCTestCase {
let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: dir) }
- let hub = DeviceHub(directory: dir, session: MemorySecretStore())
+ let hub = DeviceHub(directory: dir, secret: { _ in MemorySecretStore() })
hub.setLinks(from: ["lights": [["id": "a", "tuya": ["deviceId": "dev1"]], ["id": "b"], ["id": "c", "tuya": ["deviceId": ""]]],
"acs": [["id": "ac", "tuya": ["deviceId": "dev2", "sensorId": "s1"]]]])
XCTAssertEqual(hub.linkedDeviceCount, 2)
diff --git a/core/Tests/HouseCoreTests/ServiceTests.swift b/core/Tests/HouseCoreTests/ServiceTests.swift
new file mode 100644
index 0000000..4d9fdd8
--- /dev/null
+++ b/core/Tests/HouseCoreTests/ServiceTests.swift
@@ -0,0 +1,378 @@
+import XCTest
+@testable import HouseCore
+
+/// Home Assistant, Philips Hue and Apple Home: their translation to and from the panel's
+/// vocabulary, and the hub's routing. `HOUSE_TEST_HA_URL` + `HOUSE_TEST_HA_TOKEN` also run
+/// the Home Assistant client against a real server (tools/lab/homeassistant.sh starts one).
+@MainActor
+final class ServiceTests: XCTestCase {
+
+ // MARK: - Colour
+
+ func testColourConversionsRoundTrip() {
+ for hex in ["#ff0000", "#00ff00", "#0000ff", "#ffa040", "#8050ff"] {
+ let (h, s, _) = ColorMath.hsv(hex)!
+ XCTAssertEqual(ColorMath.hex(hue: h, saturation: s), hex)
+ let (x, y) = ColorMath.xy(hex)!
+ let back = ColorMath.rgb(ColorMath.hex(x: x, y: y))!, orig = ColorMath.rgb(hex)!
+ XCTAssertEqual(back.r, orig.r, accuracy: 0.03, hex)
+ XCTAssertEqual(back.g, orig.g, accuracy: 0.03, hex)
+ XCTAssertEqual(back.b, orig.b, accuracy: 0.03, hex)
+ }
+ XCTAssertEqual(ColorMath.mired(kelvin: 2500), 400)
+ XCTAssertEqual(ColorMath.kelvin(mired: 250), 4000)
+ XCTAssertNil(ColorMath.rgb("red"))
+ }
+
+ // MARK: - Home Assistant
+
+ func testHomeAssistantListsLightsClimateAndSensors() {
+ let light = HomeAssistantService.device(from: [
+ "entity_id": "light.bed_light", "state": "off",
+ "attributes": ["friendly_name": "Bed Light", "supported_color_modes": ["color_temp", "hs"]],
+ ])
+ XCTAssertEqual(light?.kind, .light)
+ XCTAssertEqual(light?.capabilities, ["brightness", "temp", "color"])
+ let plug = HomeAssistantService.device(from: ["entity_id": "switch.decorative_lights", "state": "unavailable", "attributes": [:]])
+ XCTAssertEqual(plug?.capabilities, [])
+ XCTAssertEqual(plug?.online, false)
+ let ac = HomeAssistantService.device(from: [
+ "entity_id": "climate.hvac", "state": "cool", "attributes": ["min_temp": 7, "max_temp": 35, "hvac_modes": ["off", "cool"]],
+ ])
+ XCTAssertEqual(ac?.kind, .ac)
+ XCTAssertEqual(ac?.range?.min, 10)
+ XCTAssertEqual(ac?.range?.max, 32)
+ XCTAssertEqual(HomeAssistantService.device(from: [
+ "entity_id": "sensor.outside", "state": "15.6", "attributes": ["unit_of_measurement": "°C"],
+ ])?.kind, .sensor)
+ XCTAssertNil(HomeAssistantService.device(from: ["entity_id": "sensor.power", "state": "3", "attributes": ["unit_of_measurement": "W"]]))
+ XCTAssertNil(HomeAssistantService.device(from: ["entity_id": "media_player.tv", "state": "on", "attributes": [:]]))
+ }
+
+ func testHomeAssistantReadsLightState() {
+ let white = HomeAssistantService.reading(from: [
+ "entity_id": "light.ceiling", "state": "on",
+ "attributes": ["brightness": 255, "color_mode": "color_temp", "color_temp_kelvin": 2631],
+ ]).light!
+ XCTAssertEqual(white["on"] as? Bool, true)
+ XCTAssertEqual(white["brightness"] as? Double, 1)
+ XCTAssertEqual(white["temp"] as? Double, 2631)
+ XCTAssertTrue(white["color"] is NSNull)
+ let colour = HomeAssistantService.reading(from: [
+ "entity_id": "light.kitchen", "state": "on",
+ "attributes": ["brightness": 180, "color_mode": "hs", "rgb_color": [255, 64, 112]],
+ ]).light!
+ XCTAssertEqual(colour["color"] as? String, "#ff4070")
+ XCTAssertEqual(HomeAssistantService.reading(from: ["entity_id": "light.x", "state": "unavailable", "attributes": [:]]).online, false)
+ }
+
+ func testHomeAssistantReadsClimate() {
+ let reading = HomeAssistantService.reading(from: [
+ "entity_id": "climate.hvac", "state": "fan_only",
+ "attributes": ["hvac_modes": ["off", "heat", "cool", "auto", "dry", "fan_only"], "temperature": 21,
+ "current_temperature": 22, "fan_modes": ["on_low", "on_high", "auto_low", "auto_high", "off"],
+ "fan_mode": "on_high", "swing_modes": ["auto", "1", "off"], "swing_mode": "off",
+ "preset_modes": ["home", "eco"], "preset_mode": "eco"],
+ ])
+ XCTAssertEqual(reading.ac?["on"] as? Bool, true)
+ XCTAssertEqual(reading.ac?["mode"] as? String, "fan")
+ XCTAssertEqual(reading.ac?["target"] as? Double, 21)
+ XCTAssertEqual(reading.ac?["roomTemp"] as? Double, 22)
+ XCTAssertEqual(reading.ac?["fan"] as? String, "high")
+ XCTAssertEqual(reading.ac?["swing"] as? String, "off")
+ XCTAssertEqual(reading.ac?["eco"] as? Bool, true)
+ XCTAssertEqual(reading.features?["modes"] as? [String], ["cool", "heat", "dry", "fan", "auto"])
+ XCTAssertEqual(reading.features?["fans"] as? [String], ["low", "high"])
+ XCTAssertEqual(reading.features?["eco"] as? Bool, true)
+ XCTAssertEqual(reading.features?["sleep"] as? Bool, false)
+ // A heat_cool-only thermostat reports a range instead of one set-point.
+ let range = HomeAssistantService.reading(from: [
+ "entity_id": "climate.ecobee", "state": "heat_cool",
+ "attributes": ["hvac_modes": ["off", "heat_cool"], "target_temp_low": 21, "target_temp_high": 24],
+ ])
+ XCTAssertEqual(range.ac?["mode"] as? String, "auto")
+ XCTAssertEqual(range.ac?["target"] as? Double, 23)
+ }
+
+ func testHomeAssistantBuildsServiceCalls() {
+ let off = HomeAssistantService.calls(for: "light.a", patch: ["on": false], state: [:], fans: [:], modes: [:])
+ XCTAssertEqual(off.map(\.service), ["turn_off"])
+ let dim = HomeAssistantService.calls(for: "light.a", patch: ["brightness": 0.5, "temp": 3000.0], state: [:], fans: [:], modes: [:])
+ XCTAssertEqual(dim.first?.service, "turn_on")
+ XCTAssertEqual(dim.first?.data["brightness_pct"] as? Int, 50)
+ XCTAssertEqual(dim.first?.data["color_temp_kelvin"] as? Int, 3000)
+ XCTAssertEqual(dim.first?.data["entity_id"] as? String, "light.a")
+ let colour = HomeAssistantService.calls(for: "light.a", patch: ["color": "#ff8000"], state: [:], fans: [:], modes: [:])
+ XCTAssertEqual(colour.first?.data["rgb_color"] as? [Int], [255, 128, 0])
+ XCTAssertEqual(HomeAssistantService.calls(for: "switch.p", patch: ["on": true], state: [:], fans: [:], modes: [:]).map(\.service), ["turn_on"])
+
+ let modes = HomeAssistantService.modeTable(["off", "cool", "heat_cool", "fan_only"])
+ XCTAssertEqual(modes, ["cool": "cool", "auto": "heat_cool", "fan": "fan_only"])
+ let fans = FanNames.table(["on_low", "on_high", "auto_low", "off"])
+ XCTAssertEqual(fans, ["low": "on_low", "high": "on_high"])
+ let on = HomeAssistantService.calls(for: "climate.x", patch: ["on": true], state: ["mode": "auto"], fans: fans, modes: modes)
+ XCTAssertEqual(on.first?.data["hvac_mode"] as? String, "heat_cool")
+ let change = HomeAssistantService.calls(for: "climate.x", patch: ["target": 23.0, "fan": "high", "eco": true],
+ state: ["mode": "cool"], fans: fans, modes: modes)
+ XCTAssertEqual(Set(change.map(\.service)), ["set_temperature", "set_fan_mode", "set_preset_mode"])
+ XCTAssertEqual(HomeAssistantService.calls(for: "climate.x", patch: ["on": false], state: [:], fans: fans, modes: modes)
+ .first?.data["hvac_mode"] as? String, "off")
+ }
+
+ func testHomeAssistantAddressIsNormalized() throws {
+ XCTAssertEqual(try HomeAssistantService.normalize("homeassistant.local"), "http://homeassistant.local:8123")
+ XCTAssertEqual(try HomeAssistantService.normalize(" http://10.0.0.5:8123/ "), "http://10.0.0.5:8123")
+ XCTAssertEqual(try HomeAssistantService.normalize("https://ha.example.com"), "https://ha.example.com")
+ XCTAssertThrowsError(try HomeAssistantService.normalize(""))
+ }
+
+ // MARK: - Hue
+
+ func testHueReadsAndWritesLights() {
+ let white: [String: Any] = [
+ "id": "l1", "metadata": ["name": "Desk", "archetype": "classic_bulb"], "on": ["on": true],
+ "dimming": ["brightness": 50.0], "color_temperature": ["mirek": 400, "mirek_valid": true],
+ "color": ["xy": ["x": 0.5, "y": 0.4]],
+ ]
+ let state = HueService.lightState(white)
+ XCTAssertEqual(state["on"] as? Bool, true)
+ XCTAssertEqual(state["brightness"] as? Double, 0.5)
+ XCTAssertEqual(state["temp"] as? Double, 2500)
+ let colour = HueService.lightState(["on": ["on": true], "color_temperature": ["mirek": NSNull(), "mirek_valid": false],
+ "color": ["xy": ["x": 0.6915, "y": 0.3083]]])
+ XCTAssertEqual(colour["color"] as? String, "#ff0000")
+ XCTAssertEqual(HueService.device(fromLight: white)?.capabilities, ["brightness", "temp", "color"])
+ XCTAssertEqual(HueService.device(fromLight: ["id": "p", "on": ["on": false]])?.capabilities, [])
+
+ let body = HueService.lightBody(patch: ["on": true, "brightness": 0.42, "temp": 2500.0, "color": "#ff0000"])
+ XCTAssertEqual((body["on"] as? [String: Bool])?["on"], true)
+ XCTAssertEqual((body["dimming"] as? [String: Double])?["brightness"], 42)
+ XCTAssertEqual((body["color_temperature"] as? [String: Int])?["mirek"], 400)
+ XCTAssertEqual(((body["color"] as? [String: Any])?["xy"] as? [String: Double])?["x"] ?? 0, 0.64, accuracy: 0.01)
+ XCTAssertEqual(HueService.roomIndex([["metadata": ["name": "Living"], "children": [["rid": "dev1", "rtype": "device"]]]]),
+ ["dev1": "Living"])
+ XCTAssertEqual(HueService.temperature(["temperature": ["temperature_report": ["temperature": 21.5]]]), 21.5)
+ }
+
+ // MARK: - Apple Home
+
+ func testHomeKitMapsLights() {
+ XCTAssertEqual(HomeKitMapper.kind(ofService: "00000043-0000-1000-8000-0026bb765291"), .light)
+ XCTAssertEqual(HomeKitMapper.name(ofCharacteristic: "000000CE-0000-1000-8000-0026BB765291"), "colorTemperature")
+ XCTAssertEqual(HomeKitMapper.capabilities(["on", "brightness", "hue", "saturation"]), ["brightness", "color"])
+ let white = HomeKitMapper.lightState(["on": true, "brightness": 40, "colorTemperature": 250, "hue": 30, "saturation": 5])
+ XCTAssertEqual(white["temp"] as? Double, 4000)
+ XCTAssertEqual(white["brightness"] as? Double, 0.4)
+ let colour = HomeKitMapper.lightState(["on": 1, "hue": 120, "saturation": 100])
+ XCTAssertEqual(colour["color"] as? String, "#00ff00")
+ XCTAssertEqual(colour["on"] as? Bool, true)
+ let writes = HomeKitMapper.lightWrites(["on": true, "brightness": 0.5, "temp": 6500.0, "color": "#0000ff"],
+ kind: .light, has: ["on", "brightness", "colorTemperature", "hue", "saturation"],
+ limits: ["colorTemperature": (153, 500)])
+ XCTAssertEqual(writes.map(\.0), ["on", "brightness", "colorTemperature", "hue", "saturation"])
+ XCTAssertEqual(writes[2].1 as? Int, 154)
+ XCTAssertEqual(writes[3].1 as? Double, 240)
+ XCTAssertEqual(HomeKitMapper.lightWrites(["on": false, "brightness": 0.3], kind: .outlet, has: ["on"]).map(\.0), ["on"])
+ }
+
+ func testHomeKitMapsAirConditioners() {
+ let ac = HomeKitMapper.acState(["active": 1, "targetState": 1, "heatingThreshold": 22, "coolingThreshold": 25,
+ "currentTemperature": 20.46, "rotationSpeed": 100, "swing": 0], kind: .heaterCooler)
+ XCTAssertEqual(ac["on"] as? Bool, true)
+ XCTAssertEqual(ac["mode"] as? String, "heat")
+ XCTAssertEqual(ac["target"] as? Double, 22)
+ XCTAssertEqual(ac["roomTemp"] as? Double, 20.5)
+ XCTAssertEqual(ac["fan"] as? String, "high")
+ XCTAssertEqual(ac["swing"] as? String, "off")
+ let features = HomeKitMapper.acFeatures(kind: .heaterCooler, has: ["active", "rotationSpeed"], validModes: [1, 2])
+ XCTAssertEqual(features["modes"] as? [String], ["cool", "heat"])
+ XCTAssertEqual(features["fans"] as? [String], ["low", "medium", "high"])
+ XCTAssertEqual(features["swing"] as? Bool, false)
+
+ let cool = HomeKitMapper.acWrites(["mode": "cool", "target": 24.0], state: ["mode": "heat"], kind: .heaterCooler,
+ has: ["active", "targetState", "coolingThreshold", "heatingThreshold"])
+ XCTAssertEqual(cool.map(\.0), ["targetState", "coolingThreshold"])
+ XCTAssertEqual(cool[0].1 as? Int, 2)
+ let off = HomeKitMapper.acWrites(["on": false], state: [:], kind: .thermostat, has: ["targetHeatingCooling"])
+ XCTAssertEqual(off.first?.1 as? Int, 0)
+ let thermostat = HomeKitMapper.acState(["targetHeatingCooling": 3, "targetTemperature": 21.4], kind: .thermostat)
+ XCTAssertEqual(thermostat["mode"] as? String, "auto")
+ XCTAssertEqual(thermostat["target"] as? Double, 21)
+ }
+
+ // MARK: - Hub routing
+
+ func testHubRoutesLinkedDevicesToTheirPlatform() async {
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let fake = FakeService()
+ let hub = DeviceHub(directory: dir, secret: { _ in MemorySecretStore() }, homeKit: fake)
+ hub.setLinks(from: [
+ "lights": [["id": "lamp", "link": ["service": "homekit", "id": "L1"]], ["id": "sim"]],
+ "acs": [["id": "ac", "link": ["service": "homekit", "id": "A1"], "sensor": ["service": "homekit", "id": "S1"]],
+ ["id": "ac2", "sensor": ["service": "homekit", "id": "S1"]]],
+ ])
+ XCTAssertEqual(hub.linkedDeviceCount, 2)
+ XCTAssertTrue(hub.canPoll)
+ XCTAssertEqual(fake.watched, ["L1", "A1", "S1"])
+
+ let sent = expectation(description: "sent")
+ hub.command(["id": "lamp", "kind": "light", "patch": ["on": true], "state": ["on": true]]) { reply in
+ XCTAssertEqual(reply["ok"] as? Bool, true)
+ sent.fulfill()
+ }
+ await fulfillment(of: [sent], timeout: 2)
+ XCTAssertEqual(fake.sent.first?.id, "L1")
+ XCTAssertEqual(fake.sent.first?.kind, .light)
+
+ fake.failNext = true
+ let refused = expectation(description: "refused")
+ hub.command(["id": "ac", "kind": "ac", "patch": ["target": 22.0]]) { reply in
+ XCTAssertEqual(reply["error"] as? String, "nope")
+ refused.fulfill()
+ }
+ await fulfillment(of: [refused], timeout: 2)
+
+ let update = await hub.poll()
+ XCTAssertEqual((update?["lights"] as? [String: [String: Any]])?["lamp"]?["on"] as? Bool, true)
+ let acs = update?["acs"] as? [String: [String: Any]]
+ XCTAssertEqual(acs?["ac"]?["target"] as? Double, 23)
+ XCTAssertEqual(acs?["ac"]?["roomTemp"] as? Double, 19.5) // from the sensor, not the unit
+ XCTAssertEqual(acs?["ac2"]?["roomTemp"] as? Double, 19.5) // a simulated AC with a real sensor
+ XCTAssertNotNil((update?["features"] as? [String: Any])?["ac"])
+
+ var simulated: [String: Any]?
+ hub.command(["id": "sim", "kind": "light", "patch": ["on": true]]) { simulated = $0 }
+ XCTAssertEqual(simulated?["ok"] as? Bool, true)
+ XCTAssertTrue(fake.sent.count == 1)
+ }
+
+ func testSmartLifeDevicesGetAKind() {
+ XCTAssertEqual(DeviceHub.smartLifeDevice(["id": "1", "category": "dj", "codes": ["switch_led", "bright_value_v2", "temp_value_v2"]])["kind"] as? String, "light")
+ XCTAssertEqual(DeviceHub.smartLifeDevice(["id": "2", "category": "infrared_ac", "codes": ["PowerOn", "T"]])["kind"] as? String, "ac")
+ XCTAssertEqual(DeviceHub.smartLifeDevice(["id": "3", "category": "wsdcg", "codes": ["temp_current"]])["kind"] as? String, "sensor")
+ XCTAssertEqual(DeviceHub.smartLifeDevice(["id": "1", "category": "dj", "codes": ["switch_led", "bright_value_v2"]])["capabilities"] as? [String], ["brightness"])
+ }
+
+ // MARK: - A real Home Assistant (opt-in)
+
+ func testLiveHomeAssistant() async throws {
+ let env = ProcessInfo.processInfo.environment
+ guard let url = env["HOUSE_TEST_HA_URL"], let token = env["HOUSE_TEST_HA_TOKEN"] else {
+ throw XCTSkip("Set HOUSE_TEST_HA_URL and HOUSE_TEST_HA_TOKEN (tools/lab/homeassistant.sh prints them)")
+ }
+ let service = HomeAssistantService(vault: MemorySecretStore())
+ do {
+ try await service.connect(url: url, token: "wrong")
+ XCTFail("a wrong token must be refused")
+ } catch {}
+ try await service.connect(url: url, token: token)
+ XCTAssertTrue(service.isConnected)
+ let devices = try await service.devices()
+ let light = try XCTUnwrap(devices.first { $0.id == "light.bed_light" })
+ XCTAssertEqual(light.capabilities, ["brightness", "temp", "color"])
+ XCTAssertTrue(devices.contains { $0.kind == .ac })
+ XCTAssertTrue(devices.contains { $0.kind == .sensor })
+
+ try await service.send(kind: .light, id: "light.bed_light", patch: ["on": true, "brightness": 0.4, "temp": 3000.0], state: [:])
+ var state = try await service.read(["light.bed_light"])["light.bed_light"]?.light
+ XCTAssertEqual(state?["on"] as? Bool, true)
+ XCTAssertEqual(state?["brightness"] as? Double ?? 0, 0.4, accuracy: 0.01)
+ XCTAssertEqual(state?["temp"] as? Double ?? 0, 3000, accuracy: 30)
+ try await service.send(kind: .light, id: "light.bed_light", patch: ["color": "#00ff00"], state: [:])
+ state = try await service.read(["light.bed_light"])["light.bed_light"]?.light
+ XCTAssertEqual(state?["color"] as? String, "#00ff00")
+ try await service.send(kind: .light, id: "light.bed_light", patch: ["on": false], state: [:])
+ state = try await service.read(["light.bed_light"])["light.bed_light"]?.light
+ XCTAssertEqual(state?["on"] as? Bool, false)
+
+ _ = try await service.read(["climate.hvac"]) // learns its mode and fan names
+ try await service.send(kind: .ac, id: "climate.hvac", patch: ["mode": "heat", "target": 23.0, "fan": "high"], state: ["mode": "heat"])
+ let ac = try await service.read(["climate.hvac"])["climate.hvac"]
+ XCTAssertEqual(ac?.ac?["mode"] as? String, "heat")
+ XCTAssertEqual(ac?.ac?["target"] as? Double, 23)
+ XCTAssertEqual(ac?.ac?["fan"] as? String, "high")
+ try await service.send(kind: .ac, id: "climate.hvac", patch: ["on": false], state: [:])
+ let off = try await service.read(["climate.hvac"])["climate.hvac"]
+ XCTAssertEqual(off?.ac?["on"] as? Bool, false)
+ try await service.send(kind: .ac, id: "climate.hvac", patch: ["on": true], state: ["mode": "cool"])
+ service.disconnect()
+ XCTAssertFalse(service.isConnected)
+ }
+
+ // MARK: - A Hue Bridge (opt-in)
+
+ /// `HOUSE_TEST_HUE_HOST=localhost:8443` with tools/lab/hue.mjs --auto running.
+ func testLiveHueBridge() async throws {
+ guard let host = ProcessInfo.processInfo.environment["HOUSE_TEST_HUE_HOST"] else {
+ throw XCTSkip("Set HOUSE_TEST_HUE_HOST and run tools/lab/hue.mjs --auto")
+ }
+ let found = await ServiceDiscovery.hueBridges()
+ XCTAssertTrue(found.contains { ($0["bridgeId"] as? String) == "ecb5fafffe0lab01" }, "announced over Bonjour: \(found)")
+
+ let service = HueService(vault: MemorySecretStore())
+ try await service.pair(host: host)
+ XCTAssertTrue(service.isConnected)
+ XCTAssertEqual(service.info["name"] as? String, "Hue Bridge Lab")
+ let devices = try await service.devices()
+ let lamp = try XCTUnwrap(devices.first { $0.name == "Hue color lamp" })
+ XCTAssertEqual(lamp.capabilities, ["brightness", "temp", "color"])
+ XCTAssertEqual(lamp.room, "Living room")
+ XCTAssertEqual(devices.first { $0.name == "Hue smart plug" }?.capabilities, [])
+ let sensor = try XCTUnwrap(devices.first { $0.kind == .sensor })
+
+ let changed = expectation(description: "event stream")
+ changed.assertForOverFulfill = false
+ service.watch([lamp.id])
+ service.onChange = { changed.fulfill() }
+ try await Task.sleep(nanoseconds: 500_000_000) // let the stream connect
+ try await service.send(kind: .light, id: lamp.id, patch: ["on": true, "brightness": 0.3, "color": "#0000ff"], state: [:])
+ await fulfillment(of: [changed], timeout: 5)
+ var readings = try await service.read([lamp.id, sensor.id])
+ XCTAssertEqual(readings[lamp.id]?.light?["on"] as? Bool, true)
+ XCTAssertEqual(readings[lamp.id]?.light?["brightness"] as? Double ?? 0, 0.3, accuracy: 0.001)
+ let blue = ColorMath.rgb(readings[lamp.id]?.light?["color"] as? String ?? "")
+ XCTAssertGreaterThan(blue?.b ?? 0, 0.9)
+ XCTAssertNotNil(readings[sensor.id]?.temperature)
+ try await service.send(kind: .light, id: lamp.id, patch: ["temp": 2700.0], state: [:])
+ readings = try await service.read([lamp.id])
+ XCTAssertEqual(readings[lamp.id]?.light?["temp"] as? Double ?? 0, 2700, accuracy: 20)
+
+ // The key and the certificate travel to the iPhone together.
+ let phone = HueService(vault: MemorySecretStore())
+ phone.adopt(service.shareable)
+ let onPhone = try await phone.devices()
+ XCTAssertEqual(onPhone.count, devices.count)
+ service.disconnect()
+ phone.disconnect()
+ }
+}
+
+/// A platform that answers from memory.
+@MainActor
+private final class FakeService: DeviceService {
+ let id = "homekit"
+ let title = "Fake"
+ var onChange: (() -> Void)?
+ var isConnected: Bool { true }
+ var info: [String: Any] { ["connected": true] }
+ var sent: [(kind: DeviceKind, id: String, patch: [String: Any])] = []
+ var watched: Set<String> = []
+ var failNext = false
+
+ func devices() async throws -> [ServiceDevice] { [] }
+ func read(_ ids: Set<String>) async throws -> [String: DeviceReading] {
+ [
+ "L1": DeviceReading(light: ["on": true, "brightness": 0.5]),
+ "A1": DeviceReading(ac: ["on": true, "target": 23.0, "roomTemp": 26.0], features: ["modes": ["cool"]]),
+ "S1": DeviceReading(temperature: 19.5),
+ ].filter { ids.contains($0.key) }
+ }
+ func send(kind: DeviceKind, id: String, patch: [String: Any], state: [String: Any]) async throws {
+ if failNext { failNext = false; throw ServiceFailure("nope") }
+ sent.append((kind, id, patch))
+ }
+ func watch(_ ids: Set<String>) { watched = ids }
+ func disconnect() {}
+}
diff --git a/core/Tests/HouseCoreTests/SyncTests.swift b/core/Tests/HouseCoreTests/SyncTests.swift
index 658b836..692ad88 100644
--- a/core/Tests/HouseCoreTests/SyncTests.swift
+++ b/core/Tests/HouseCoreTests/SyncTests.swift
@@ -141,6 +141,33 @@ final class SyncTests: XCTestCase {
await fulfillment(of: [back, hidden], timeout: 10)
}
+ func testConnectionsGoToThePhoneAndAppleHomeComesBack() async throws {
+ let (server, client) = makePair()
+ defer { client.stop(); server.stop() }
+ let shared: [String: Any] = ["homeassistant": ["url": "http://ha.local:8123", "token": "t"],
+ "hue": ["host": "10.0.0.2", "key": "k"]]
+ server.snapshot = { SyncState(macName: "Test Mac", revision: "", plan: nil, userCode: "", smartLifeConnected: false,
+ connections: shared) }
+ // Catalogs sent before the Mac is reachable are delivered once it is.
+ client.sendCatalog([["id": "A1", "name": "Hall lamp", "kind": "light"]])
+ let state = expectation(description: "state")
+ var connections: [String: Any]?
+ client.onState = { connections = $0.connections; state.fulfill() }
+ let catalog = expectation(description: "catalog")
+ server.onCatalog = { devices, phone in
+ XCTAssertEqual(phone, "Test iPhone")
+ XCTAssertEqual(devices.first?["name"] as? String, "Hall lamp")
+ catalog.fulfill()
+ }
+ client.fixedEndpoint = try await waitForPort(server)
+ client.start()
+ await fulfillment(of: [state, catalog], timeout: 10)
+ XCTAssertEqual((connections?["homeassistant"] as? [String: Any])?["token"] as? String, "t")
+ XCTAssertEqual((connections?["hue"] as? [String: Any])?["key"] as? String, "k")
+ // A Mac that predates connections sends none: the phone must keep its own.
+ XCTAssertNil(SyncState(message: ["type": "state", "mac": "Old Mac"])?.connections)
+ }
+
func testAWrongKeyIsRefused() async throws {
let (server, client) = makePair(clientKey: Data(repeating: 7, count: 32))
defer { client.stop(); server.stop() }
diff --git a/docs/connections.md b/docs/connections.md
new file mode 100644
index 0000000..d3fcd5a
--- /dev/null
+++ b/docs/connections.md
@@ -0,0 +1,117 @@
+# Connecting real devices
+
+House Control links the lamps and air conditioners of your floor plan to real devices on four platforms.
+One home can mix them: Hue lamps, a Home Assistant air conditioner and a Smart Life plug side by side.
+Everything you do not link stays simulated.
+
+| Platform | Mac | iPhone | How it connects | What you need |
+| --- | --- | --- | --- | --- |
+| **Smart Life / Tuya** | ✓ | ✓ | Tuya's cloud, signed in with a QR code | The Smart Life or Tuya Smart app — see [smart-life.md](smart-life.md) |
+| **Home Assistant** | ✓ | ✓ (from the Mac) | Your server's API, on your network | A long-lived access token |
+| **Philips Hue** | ✓ | ✓ (from the Mac) | The Hue Bridge's own API, on your network | Press the bridge's button once |
+| **Apple Home** | Linking only | ✓ | HomeKit, on the iPhone | Allow access to your Home data |
+
+All four are set up in the editor: right-click the menu bar icon → **Edit Home… → Connections**. Then select a
+lamp or an AC on the plan, choose its device under **Real device**, and press **Save & apply**. Picking a lamp
+fills in what it can do (dimming, white temperature, colour); picking an AC takes over its temperature range.
+
+The iPhone gets the Home Assistant and Hue connections from the Mac together with the floor plan, over the
+paired, encrypted link, so there is nothing to set up twice.
+
+## Home Assistant
+
+[Home Assistant](https://www.home-assistant.io) runs your home locally and speaks to thousands of brands —
+Zigbee and Z-Wave sticks, Matter, Google Nest, Xiaomi, Aqara, IKEA, Sonoff, SmartThings, Daikin, Mitsubishi,
+Tuya — so connecting it brings all of them in at once.
+
+1. In Home Assistant, open your profile (your name at the bottom left) → **Security** → **Long-lived access
+ tokens** → **Create token**. Name it "House Control" and copy it.
+2. In House Control: **Connections → Home Assistant**. Servers on your network are found by themselves — press
+ **Use**, or type the address (`http://homeassistant.local:8123`). Paste the token and press **Connect**.
+
+| Home Assistant | In House Control |
+| --- | --- |
+| `light.*` | A lamp: on/off, brightness, white temperature and colour as its colour modes allow |
+| `switch.*` | A lamp on a plug: on/off |
+| `climate.*` | An air conditioner: power, target, the modes it has (`cool`, `heat`, `dry`, `fan_only`, `auto`/`heat_cool`), its fan speeds, swing, `eco` and `sleep` presets |
+| `sensor.*` with `device_class: temperature` | A thermometer for an AC's room |
+
+Areas become the room shown next to each device. House Control subscribes to Home Assistant's events, so a
+lamp switched from a wall switch or an automation shows up in the panel within a second.
+
+**Bring your Tuya devices in without a developer account:** in Home Assistant, **Settings → Devices & services →
+Add integration → Tuya**, and sign in with the User Code and QR code from the Smart Life app — the same sign-in
+House Control uses.
+
+## Philips Hue
+
+1. In House Control: **Connections → Philips Hue**. Bridges on your network are found by themselves (or type the
+ address shown in the Hue app under **Settings → My Hue system**).
+2. Press **Pair**, then the round button on top of the bridge within a minute.
+
+Lamps, Hue Play bars, light strips and smart plugs appear with what each can do; the thermometers inside Hue
+motion sensors can serve as an AC's room temperature. The bridge's event stream makes changes from the Hue app
+show up at once. No Hue account or internet connection is involved.
+
+The bridge's certificate is self-signed. House Control trusts it the first time and remembers its fingerprint,
+so a different device answering at that address later is refused.
+
+## Apple Home
+
+Apple offers HomeKit to iPhone and iPad apps, and to Mac apps only through the Mac App Store. House Control is a
+download, so on the Mac it can list Apple Home devices but not switch them:
+
+1. Pair your iPhone with the Mac (right-click the menu bar icon → **Pair iPhone…**).
+2. On the iPhone: **Settings → More connections → Apple Home → Connect**, and allow access to your Home data.
+3. The iPhone sends the list of your lamps, outlets, air conditioners (heater-coolers and thermostats) and
+ thermometers to the Mac. Link them in the editor like any other device.
+
+The iPhone app then switches them, including Matter accessories added to Apple Home. On the Mac they show what
+you set but stay simulated.
+
+| HomeKit service | In House Control |
+| --- | --- |
+| Lightbulb | A lamp: on/off, brightness, colour temperature, hue and saturation |
+| Outlet, Switch | A lamp on a plug |
+| Heater Cooler | An AC: active, cool / heat / auto, the matching threshold, rotation speed as low / medium / high, swing |
+| Thermostat | An AC: off / heat / cool / auto, target temperature |
+| Temperature Sensor | A thermometer for an AC's room |
+
+### Your Tuya devices in Apple Home
+
+Smart Life devices are not HomeKit accessories, but there are three free ways to put them there:
+
+- **Home Assistant's HomeKit Bridge** (recommended): add the Tuya integration as above, then
+ **Add integration → HomeKit Bridge**, choose the domains (lights, switches, climate) and scan the code it
+ shows with the Home app. Every Tuya device appears in Apple Home — and in House Control's iPhone app.
+- **Homebridge** with a Tuya plugin, if you already run Homebridge.
+- **Matter**: newer Tuya devices and hubs that support Matter can be added to Apple Home directly
+ (**+ → Add Accessory** and scan their Matter code), and shared with other apps at the same time.
+
+## Why not Google Home, Amazon Alexa or SmartThings — yet
+
+- **Amazon Alexa** has no interface that lets another app switch the devices in your Alexa account; it only goes
+ the other way (devices exposed *to* Alexa).
+- **Google Home** offers its Home APIs to iPhone and Android apps only, behind a Google Cloud project, a Google
+ sign-in and App Attest (which cannot run in the iOS Simulator), and an SDK that is downloaded after signing in to
+ Google's developer site. Its new Home MCP server needs Google Home Premium Advanced and is US-only for now.
+- **Samsung SmartThings** needs an OAuth app registered with Samsung; its personal tokens expire after 24 hours.
+
+Until then, the practical route for any of them is Home Assistant: it has integrations for SmartThings and Google
+Nest, and Matter devices from a Google or Amazon ecosystem can be shared with Home Assistant or Apple Home
+(Matter "multi-admin": in the Google Home or Alexa app, open the device → **Linked Matter apps & services**).
+
+## Trying it without hardware
+
+`tools/lab` has pretend versions of all three new platforms — a Home Assistant full of demo devices, a Hue Bridge
+emulator and a HomeKit bridge you can add to the Home app. See [tools/lab/README.md](../tools/lab/README.md).
+
+## Privacy
+
+Credentials stay on your Mac, in `~/Library/Application Support/HouseControl/` (readable only by you):
+`homeassistant.json` (address and token), `hue.json` (bridge address, key and certificate fingerprint) and
+`homekit-devices.json` (the device list your iPhone sent: names and HomeKit ids, no credentials).
+**Disconnect** deletes them. Paired iPhones receive the Home Assistant and Hue connections over their encrypted
+link and keep them in the Keychain. Nothing goes through a server of ours — there is none.
+
+When something does not react, **Reveal Device Log** in the menu bar icon's menu shows each command and the answer.
diff --git a/docs/connections.png b/docs/connections.png
new file mode 100644
index 0000000..eff4273
Binary files /dev/null and b/docs/connections.png differ
diff --git a/docs/floor-plan.md b/docs/floor-plan.md
index e77d250..baa9581 100644
--- a/docs/floor-plan.md
+++ b/docs/floor-plan.md
@@ -129,7 +129,7 @@ Decoration only. Every piece has `type`, `pos` (`[x, z]` of its centre) and an o
| `length` | Length of a `strip` |
| `capabilities` | Any of `brightness`, `temp`, `color`. Leave it out for a plain smart plug that only switches |
| `color` | Initial colour of a colour light |
-| `tuya` | Link to a real device — see below |
+| `link`, `tuya` | Link to a real device — see below |
## `acs`
@@ -140,7 +140,8 @@ Decoration only. Every piece has `type`, `pos` (`[x, z]` of its centre) and an o
| `pos` | `[x, z]`, on that wall |
| `y` | Height. Default `2.2` |
| `min`, `max` | Range of the target temperature. Defaults `16` and `30` |
-| `tuya` | Link to a real device — see below |
+| `link`, `tuya` | Link to a real device — see below |
+| `sensor` | A thermometer for the room — see below |
## `scenes`
@@ -155,26 +156,37 @@ In both maps the key `"*"` applies to every device, and a device's own entry ove
## Linking real devices
-A light or an AC becomes real when it has a `tuya` object. The editor fills it in when you pick a device;
-by hand it looks like this:
+A light or an AC becomes real when it is linked to a device of a connected platform. The editor fills the link
+in when you pick a device under **Real device**; by hand it looks like this:
```jsonc
+// Home Assistant (an entity id), Philips Hue (the bridge's light id), Apple Home (HomeKit's service id)
{ "id": "living.floor", "name": "Floor lamp", "room": "living", "type": "floor", "pos": [5.8, 0.6],
- "tuya": { "deviceId": "<device id>" } }
+ "link": { "service": "homeassistant", "id": "light.floor_lamp" } }
+// An AC with a thermometer from any platform for its room temperature
{ "id": "living.ac", "name": "Living AC", "room": "living", "wall": "west", "pos": [0, 0.8],
- "tuya": { "deviceId": "<device id>", "sensorId": "<id of a temperature sensor in the room>" } }
+ "link": { "service": "homeassistant", "id": "climate.living_room" },
+ "sensor": { "service": "hue", "id": "<id of a Hue motion sensor's thermometer>" } }
+
+// Smart Life keeps its own object
+{ "id": "bed.ac", "name": "Bedroom AC", "room": "bedroom", "wall": "north", "pos": [2, 0],
+ "tuya": { "deviceId": "<device id>", "sensorId": "<id of a Smart Life temperature sensor in the room>" } }
```
| Field | Meaning |
| --- | --- |
-| `deviceId` | The Smart Life device |
-| `sensorId` | ACs only, optional: a temperature sensor whose reading is shown as the room temperature |
-| `codes.switch` | Optional: the data point that switches the device, when it is not the usual one — e.g. `"switch_2"` for the second gang of a double switch |
+| `link.service` | `homeassistant`, `hue` or `homekit` |
+| `link.id` | The device on that platform |
+| `sensor` | ACs only, optional: `{ "service", "id" }` of a temperature sensor whose reading is shown as the room temperature. A simulated AC can have one too |
+| `tuya.deviceId` | The Smart Life device |
+| `tuya.sensorId` | ACs linked to Smart Life only, optional: a Smart Life temperature sensor |
+| `tuya.codes.switch` | Optional: the data point that switches the device, when it is not the usual one — e.g. `"switch_2"` for the second gang of a double switch |
-Devices without a `tuya` object stay simulated, so a plan can mix real and imaginary ones.
+Devices without a link stay simulated, so a plan can mix real and imaginary ones, and one home can mix
+platforms: Hue lamps, a Home Assistant air conditioner and a Smart Life plug side by side.
-Device IDs identify your hardware. Remove the `tuya` objects before you share a plan.
+Device IDs identify your hardware. Remove the `link`, `sensor` and `tuya` objects before you share a plan.
## Errors
diff --git a/docs/smart-life.md b/docs/smart-life.md
index df98da5..e1e8d1c 100644
--- a/docs/smart-life.md
+++ b/docs/smart-life.md
@@ -8,7 +8,7 @@ every device in the plan is simulated.
You need the phone app with your devices already added to it. No Tuya developer account is required.
1. In the phone app: **Me → ⚙ Settings → Account and Security**. Copy the **User Code** at the bottom of the screen.
-2. In House Control: right-click the menu bar icon → **Edit Home… → Smart Life**. Enter the User Code and press **Show QR code**.
+2. In House Control: right-click the menu bar icon → **Edit Home… → Connections → Smart Life**. Enter the User Code and press **Show QR code**.
3. Scan the code with the phone app (the scanner icon on its Home tab) and confirm.
4. The editor lists the devices of the account.
@@ -21,12 +21,13 @@ user, and is refreshed automatically. **Sign out** in the editor deletes it.
## Linking devices to the plan
-Select a lamp or an AC in the editor, choose its device under **Smart Life device**, and press **Save & apply**.
+Select a lamp or an AC in the editor, choose its device under **Real device**, and press **Save & apply**.
-- A lamp's sliders follow the plan, not the device: give the light the capabilities it really has
- (`brightness`, `temp`, `color`). A smart plug has none and only switches.
-- For an AC you can also enter the device ID of a **temperature sensor** in the same room. The sheet then
- shows the measured room temperature instead of an estimate.
+- A lamp's sliders follow the plan: picking a device sets the capabilities it reports (`brightness`, `temp`,
+ `color`); adjust them under **What it can do** if the device reports less than it can do. A smart plug has
+ none and only switches.
+- For an AC you can also pick a **thermometer** in the same room. The sheet then shows the measured room
+ temperature instead of an estimate.
While the panel is open, the app reads the state of all linked devices every 12 seconds, so changes made in
the phone app or on a wall switch show up.
diff --git a/ios/Sources/AppModel.swift b/ios/Sources/AppModel.swift
index 2550aa1..612080b 100644
--- a/ios/Sources/AppModel.swift
+++ b/ios/Sources/AppModel.swift
@@ -9,6 +9,14 @@ struct Banner: Equatable, Identifiable {
var tint: Color = Theme.accent
}
+enum HomeKitStatus: Equatable {
+ case off
+ /// Asking iOS, or waiting for HomeKit to load the homes.
+ case waiting
+ case denied
+ case ready(homes: [String], accessories: Int)
+}
+
/// Where the settings sheet opens.
enum SettingsRoute: Hashable {
case pairing
@@ -39,6 +47,12 @@ final class AppModel {
private(set) var macName: String?
private(set) var lastSync: Date?
+ // Home Assistant and Hue (shared by the Mac), Apple Home (this phone's own)
+ private(set) var homeAssistantName: String?
+ private(set) var hueName: String?
+ private(set) var homeKit: HomeKitStatus = .off
+ @ObservationIgnored let homeKitService = HomeKitService()
+
// Smart Life
private(set) var smartLifeConnected: Bool
private(set) var smartLifeAccount: String
@@ -61,7 +75,7 @@ final class AppModel {
sandboxed ? FileSecretStore(url: directory.appendingPathComponent("\(name).json"))
: KeychainSecretStore(service: "io.github.0xprobabillity.HouseControl", account: name)
}
- hub = DeviceHub(directory: directory, session: secret("smartlife"))
+ hub = DeviceHub(directory: directory, secret: secret, homeKit: homeKitService)
sync = SyncClient(store: secret("sync"))
web = HomeWeb(persistent: !sandboxed)
@@ -75,7 +89,14 @@ final class AppModel {
lastSync = UserDefaults.standard.object(forKey: "lastSync") as? Date
hub.onStale = { [weak self] in self?.poll() }
+ homeKitService.onCatalogChange = { [weak self] in
+ guard let self else { return }
+ self.refreshConnections()
+ self.sendCatalog()
+ self.startPolling()
+ }
reloadLinks()
+ refreshConnections()
sync.deviceName = UIDevice.current.name
sync.planRevision = { [plans] in plans.customPlanRevision }
@@ -93,6 +114,7 @@ final class AppModel {
case "settings": showSettings = true
case "pairing": showSettings = true; settingsPath = [.pairing]
case "smartlife": showSettings = true; settingsPath = [.smartLife]
+ case "connections": showSettings = true
case "welcome": showWelcome = true
case "home": break
default: showWelcome = !sandboxed && !UserDefaults.standard.bool(forKey: "welcomed")
@@ -229,6 +251,12 @@ final class AppModel {
lastSync = Date()
UserDefaults.standard.set(lastSync, forKey: "lastSync")
suggestedUserCode = state.userCode
+ if let shared = state.connections {
+ hub.adoptConnections(shared)
+ refreshConnections()
+ startPolling()
+ }
+ sendCatalog()
guard let data = state.plan, (try? PlanStore.validate(data)) != nil else { return }
// The first plan from the Mac becomes this phone's home; later ones only replace it
// (someone who switched to a demo plan stays there).
@@ -274,6 +302,53 @@ final class AppModel {
pollTimer = nil
}
+ // MARK: - Home Assistant, Hue, Apple Home
+
+ private func refreshConnections() {
+ let ha = hub.homeAssistant.info
+ homeAssistantName = ha["connected"] as? Bool == true ? (ha["name"] as? String ?? "Home Assistant") : nil
+ let hue = hub.hue.info
+ hueName = hue["connected"] as? Bool == true ? (hue["name"] as? String ?? "Hue Bridge") : nil
+ let info = homeKitService.info
+ if !homeKitService.isEnabled {
+ homeKit = .off
+ } else if homeKitService.isDenied {
+ homeKit = .denied
+ } else if info["connected"] as? Bool == true {
+ homeKit = .ready(homes: info["homes"] as? [String] ?? [], accessories: info["accessories"] as? Int ?? 0)
+ } else {
+ homeKit = .waiting
+ }
+ linkedDevices = hub.linkedDeviceCount
+ }
+
+ /// Turns Apple Home on: iOS asks for permission the first time.
+ func connectHomeKit() {
+ homeKit = .waiting
+ Task { @MainActor in
+ await homeKitService.enable()
+ refreshConnections()
+ sendCatalog()
+ startPolling()
+ if case .ready = homeKit { Haptics.shared.play("success") }
+ }
+ }
+
+ func disconnectHomeKit() {
+ homeKitService.disconnect()
+ sync.sendCatalog([])
+ refreshConnections()
+ }
+
+ /// The Mac cannot see Apple Home, so this phone tells it what is there, for the editor.
+ private func sendCatalog() {
+ guard homeKitService.isConnected, sync.isPaired else { return }
+ Task { @MainActor in
+ guard let devices = try? await homeKitService.devices() else { return }
+ sync.sendCatalog(devices.map { $0.dictionary(service: "homekit") })
+ }
+ }
+
// MARK: - Welcome, banners
func finishWelcome(pairing: Bool) {
diff --git a/ios/Sources/SettingsView.swift b/ios/Sources/SettingsView.swift
index 665c9b8..9e2e0bc 100644
--- a/ios/Sources/SettingsView.swift
+++ b/ios/Sources/SettingsView.swift
@@ -19,6 +19,7 @@ struct SettingsView: View {
homeSection
macSection
smartLifeSection
+ connectionsSection
aboutSection
}
.padding(.horizontal, 18)
@@ -227,8 +228,8 @@ struct SettingsView: View {
HStack(alignment: .top, spacing: 14) {
IconBadge(symbol: "lightbulb.2.fill", tint: Theme.warm)
VStack(alignment: .leading, spacing: 4) {
- Text("Devices are simulated").font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
- Text("Sign in with your Smart Life or Tuya Smart account and the lamps and air conditioners linked in your floor plan become the real ones.")
+ Text("Not signed in").font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ Text("Sign in with your Smart Life or Tuya Smart account and the lamps and air conditioners linked to it in your floor plan become the real ones.")
.font(.system(size: 14))
.foregroundStyle(Theme.muted)
.fixedSize(horizontal: false, vertical: true)
@@ -243,6 +244,90 @@ struct SettingsView: View {
}
}
+ // MARK: - Home Assistant, Hue, Apple Home
+
+ private var connectionsSection: some View {
+ VStack(spacing: 10) {
+ SectionTitle("More connections")
+ Card {
+ serviceRow(symbol: "server.rack", tint: Color(red: 0.09, green: 0.74, blue: 0.95), title: "Home Assistant",
+ detail: model.homeAssistantName.map { "\($0) · from \(model.macName ?? "your Mac")" } ?? "Connect it on the Mac; it comes over by itself",
+ on: model.homeAssistantName != nil)
+ RowDivider()
+ serviceRow(symbol: "lightbulb.led.fill", tint: Color(red: 0.76, green: 0.55, blue: 1), title: "Philips Hue",
+ detail: model.hueName.map { "\($0) · from \(model.macName ?? "your Mac")" } ?? "Pair the bridge on the Mac; it comes over by itself",
+ on: model.hueName != nil)
+ RowDivider()
+ homeKitRow
+ }
+ footnote(homeKitFootnote)
+ }
+ }
+
+ private func serviceRow(symbol: String, tint: Color, title: String, detail: String, on: Bool) -> some View {
+ HStack(spacing: 14) {
+ IconBadge(symbol: symbol, tint: tint)
+ VStack(alignment: .leading, spacing: 3) {
+ Text(title).font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ HStack(spacing: 7) {
+ if on { StatusDot(color: Theme.green, pulsing: false) }
+ Text(detail).font(.system(size: 13.5)).foregroundStyle(Theme.muted).lineLimit(2)
+ }
+ }
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, 14)
+ .frame(minHeight: 70)
+ .accessibilityElement(children: .combine)
+ }
+
+ private var homeKitRow: some View {
+ HStack(spacing: 14) {
+ IconBadge(symbol: "homekit", tint: Color(red: 1, green: 0.7, blue: 0.25))
+ VStack(alignment: .leading, spacing: 3) {
+ Text("Apple Home").font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ HStack(spacing: 7) {
+ if case .ready = model.homeKit { StatusDot(color: Theme.green, pulsing: false) }
+ Text(homeKitDetail).font(.system(size: 13.5)).foregroundStyle(Theme.muted).lineLimit(2)
+ }
+ }
+ Spacer(minLength: 8)
+ switch model.homeKit {
+ case .off:
+ Button("Connect") { model.connectHomeKit() }.buttonStyle(PillButtonStyle())
+ case .waiting:
+ ProgressView().tint(Theme.muted)
+ case .denied:
+ Button("Allow") {
+ if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) }
+ }.buttonStyle(PillButtonStyle())
+ case .ready:
+ Button("Turn off") { model.disconnectHomeKit() }.buttonStyle(PillButtonStyle(tint: Theme.muted))
+ }
+ }
+ .padding(.horizontal, 14)
+ .frame(minHeight: 70)
+ .animation(.snappy, value: model.homeKit)
+ }
+
+ private var homeKitDetail: String {
+ switch model.homeKit {
+ case .off: return "Lamps, ACs and sensors from the Home app"
+ case .waiting: return "Opening your homes…"
+ case .denied: return "Not allowed. Turn on House Control in Settings → Privacy → HomeKit"
+ case .ready(let homes, let accessories):
+ if homes.isEmpty { return "No homes yet. Set one up in the Home app" }
+ return "\(accessories) accessor\(accessories == 1 ? "y" : "ies") · \(homes.joined(separator: ", "))"
+ }
+ }
+
+ private var homeKitFootnote: String {
+ if case .ready = model.homeKit, model.macName != nil {
+ return "Your Apple Home devices are listed in the Mac's editor, to link to the lamps and ACs of the plan. This iPhone switches them; macOS lets only App Store apps use HomeKit."
+ }
+ return "Home Assistant and Hue are set up once on the Mac and come over with the floor plan, over your paired, encrypted link."
+ }
+
// MARK: - About
private var aboutSection: some View {
@@ -253,7 +338,7 @@ struct SettingsView: View {
RowDivider().padding(.leading, -52)
infoRow("Privacy", value: "No account, no analytics")
}
- footnote("House Control talks to Tuya's servers to reach your devices, and to your own Mac. Nothing else leaves this iPhone.")
+ footnote("House Control talks to your own devices: Tuya's servers for Smart Life, your Home Assistant, your Hue Bridge, Apple Home, and your Mac. Nothing else leaves this iPhone.")
}
}
diff --git a/ios/Sources/Theme.swift b/ios/Sources/Theme.swift
index 4ebb5b4..6850978 100644
--- a/ios/Sources/Theme.swift
+++ b/ios/Sources/Theme.swift
@@ -127,3 +127,19 @@ struct RowButtonStyle: ButtonStyle {
.background(configuration.isPressed ? Theme.surfaceHigh : .clear)
}
}
+
+/// A small capsule button at the end of a row ("Connect", "Turn off").
+struct PillButtonStyle: ButtonStyle {
+ var tint: Color = Theme.accent
+
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .font(.system(size: 14, weight: .semibold))
+ .foregroundStyle(tint == Theme.accent ? .white : tint)
+ .padding(.horizontal, 14)
+ .frame(minHeight: 32)
+ .background(tint == Theme.accent ? AnyShapeStyle(Theme.accent) : AnyShapeStyle(Theme.surfaceHigh), in: Capsule())
+ .scaleEffect(configuration.isPressed ? 0.94 : 1)
+ .animation(.spring(response: 0.3, dampingFraction: 0.7), value: configuration.isPressed)
+ }
+}
diff --git a/ios/project.yml b/ios/project.yml
index 0a260c4..a005431 100644
--- a/ios/project.yml
+++ b/ios/project.yml
@@ -25,6 +25,10 @@ targets:
buildPhase: resources
dependencies:
- package: HouseCore
+ entitlements:
+ path: Config/HouseControl.entitlements
+ properties:
+ com.apple.developer.homekit: true
info:
path: Config/Info.plist
properties:
@@ -38,8 +42,12 @@ targets:
UIRequiresFullScreen: true
UIUserInterfaceStyle: Dark
ITSAppUsesNonExemptEncryption: false
- NSLocalNetworkUsageDescription: House Control looks for your Mac on this Wi-Fi network to receive the floor plan you made there.
+ NSLocalNetworkUsageDescription: House Control looks for your Mac on this Wi-Fi network to receive the floor plan you made there, and talks to your Home Assistant and Hue Bridge.
NSBonjourServices: [_housecontrol._tcp]
+ NSHomeKitUsageDescription: House Control shows the lamps, air conditioners and thermometers of your homes in its 3D view and switches them for you.
+ # Home Assistant answers plain HTTP on the local network, the Hue Bridge HTTPS with its own certificate.
+ NSAppTransportSecurity:
+ NSAllowsLocalNetworking: true
NSCameraUsageDescription: The camera reads the pairing code shown by House Control on your Mac.
CFBundleURLTypes:
- CFBundleURLName: io.github.0xprobabillity.HouseControl.pair
diff --git a/macos/Sources/HouseControl/AppDelegate.swift b/macos/Sources/HouseControl/AppDelegate.swift
index 473217b..9fe5212 100644
--- a/macos/Sources/HouseControl/AppDelegate.swift
+++ b/macos/Sources/HouseControl/AppDelegate.swift
@@ -194,7 +194,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
var boot = plans.bootPayload()
boot["tuya"] = hub.tuyaInfo
boot["smartLife"] = hub.smartLifeInfo
- if ProcessInfo.processInfo.environment["HOUSE_OPEN_EDITOR"] == "smartlife" { boot["section"] = "tuya" }
+ boot["services"] = hub.servicesInfo
+ switch ProcessInfo.processInfo.environment["HOUSE_OPEN_EDITOR"] {
+ case "smartlife": boot["section"] = "service:smartlife"
+ case "homeassistant", "hue", "homekit", "connections":
+ let section = ProcessInfo.processInfo.environment["HOUSE_OPEN_EDITOR"]!
+ boot["section"] = section == "connections" ? "connections" : "service:\(section)"
+ default: break
+ }
boot["agentLive"] = agent.isLive
// HOUSE_OPEN_DEVICE=<id> starts the panel on that light's or AC's detail sheet.
if let device = ProcessInfo.processInfo.environment["HOUSE_OPEN_DEVICE"] { boot["openDevice"] = device }
@@ -205,6 +212,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
hub.setLinks(from: plans.activePlan == "custom" ? plans.customPlan() : nil)
}
+ /// A platform was connected or disconnected: read the devices again and tell the phones.
+ private func connectionsChanged() {
+ reloadLinks()
+ setPolling(false) // reads at once while the panel or the island is open
+ sync.broadcast()
+ }
+
@objc private func reloadAll() {
reloadLinks()
panel.host.load()
@@ -369,6 +383,48 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
hub.signOut()
host.reply(to: message, hub.smartLifeInfo)
sync.broadcast()
+
+ // Home Assistant, Philips Hue, Apple Home
+ case "services.info":
+ host.reply(to: message, hub.servicesInfo)
+ case "devices.all":
+ Task { @MainActor in
+ let (devices, errors) = await hub.allDevices()
+ host.reply(to: message, ["devices": devices, "errors": errors])
+ }
+ case "services.discover":
+ let service = message["service"] as? String ?? ""
+ Task { @MainActor in
+ let found = service == "hue" ? await ServiceDiscovery.hueBridges() : await ServiceDiscovery.homeAssistants()
+ host.reply(to: message, ["found": found])
+ }
+ case "homeassistant.connect":
+ Task { @MainActor in
+ do {
+ try await hub.homeAssistant.connect(url: message["url"] as? String ?? "", token: message["token"] as? String ?? "")
+ connectionsChanged()
+ host.reply(to: message, hub.servicesInfo)
+ } catch {
+ host.reply(to: message, ["error": error.localizedDescription])
+ }
+ }
+ case "hue.pair":
+ Task { @MainActor in
+ do {
+ try await hub.hue.pair(host: message["host"] as? String ?? "", bridgeId: message["bridgeId"] as? String,
+ name: message["name"] as? String)
+ connectionsChanged()
+ host.reply(to: message, hub.servicesInfo)
+ } catch is HueService.ButtonNotPressed {
+ host.reply(to: message, ["waiting": true])
+ } catch {
+ host.reply(to: message, ["error": error.localizedDescription])
+ }
+ }
+ case "service.disconnect":
+ hub.services.first { $0.id == message["service"] as? String }?.disconnect()
+ connectionsChanged()
+ host.reply(to: message, hub.servicesInfo)
default:
break
}
@@ -446,7 +502,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
revision: self.plans.customPlanRevision ?? "",
plan: try? Data(contentsOf: self.plans.customPlanURL),
userCode: self.hub.smartLifeUserCode,
- smartLifeConnected: self.hub.isSmartLifeConnected)
+ smartLifeConnected: self.hub.isSmartLifeConnected,
+ connections: self.hub.shareableConnections)
+ }
+ sync.onCatalog = { [weak self] devices, phone in
+ guard let self, let catalog = self.hub.homeKit as? RemoteCatalogService else { return }
+ catalog.update(devices: devices, from: phone)
+ self.editor?.host.call("servicesChanged", self.hub.servicesInfo)
}
sync.onPeersChanged = { [weak self] in self?.refreshPairingWindow() }
sync.onShowQR = { [weak self] content, device in self?.showLoginCode(content, for: device) }
diff --git a/macos/Sources/HouseControl/WebHost.swift b/macos/Sources/HouseControl/WebHost.swift
index 6277eea..d0f0f0c 100644
--- a/macos/Sources/HouseControl/WebHost.swift
+++ b/macos/Sources/HouseControl/WebHost.swift
@@ -17,6 +17,7 @@ final class WebHost: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
/// True once the page has started and reported "ready"; false again while it reloads.
private(set) var isReady = false
private var bootProvider: () -> [String: Any]
+ private var evalTimer: Timer?
/// Where the web UI lives: the app bundle, or a directory / dev server given by the environment.
static var assetRoot: URL {
@@ -48,6 +49,29 @@ final class WebHost: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
webView.responds(to: Selector(("_setWindowOcclusionDetectionEnabled:"))) {
webView.setValue(false, forKey: "windowOcclusionDetectionEnabled")
}
+ if let folder = ProcessInfo.processInfo.environment["HOUSE_EVAL_DIR"] { watchScripts(in: URL(fileURLWithPath: folder)) }
+ }
+
+ /// HOUSE_EVAL_DIR=<folder>: scripted UI checks. A file `<mode>.js` put there is run in that
+ /// page as the body of an async function, then removed; what it returns is written to
+ /// `<mode>.json` (or `{"error": …}`). For test instances only.
+ private func watchScripts(in folder: URL) {
+ let script = folder.appendingPathComponent("\(mode).js")
+ let result = folder.appendingPathComponent("\(mode).json")
+ evalTimer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: true) { [weak self] _ in
+ guard let self, let source = try? String(contentsOf: script, encoding: .utf8) else { return }
+ try? FileManager.default.removeItem(at: script)
+ self.webView.callAsyncJavaScript(source, arguments: [:], in: nil, in: .page) { outcome in
+ let value: Any
+ switch outcome {
+ case .success(let v): value = ["result": v]
+ case .failure(let e): value = ["error": "\(e)"]
+ }
+ let data = (try? JSONSerialization.data(withJSONObject: value, options: [.prettyPrinted, .fragmentsAllowed]))
+ ?? Data("{\"result\": \"(not JSON)\"}".utf8)
+ try? data.write(to: result, options: .atomic)
+ }
+ }
}
func load() {
diff --git a/macos/dmg-background.tiff b/macos/dmg-background.tiff
new file mode 100644
index 0000000..6fe6fcd
Binary files /dev/null and b/macos/dmg-background.tiff differ
diff --git a/scripts/build-app.sh b/scripts/build-app.sh
index f3c684d..a279fae 100755
--- a/scripts/build-app.sh
+++ b/scripts/build-app.sh
@@ -1,8 +1,14 @@
#!/bin/bash
# Builds HouseControl.app: web UI (Vite) + native shell (SwiftPM), assembled into build/.
+# UNIVERSAL=1 one binary for Apple silicon and Intel Macs (what scripts/release-mac.sh ships)
+# CODESIGN_IDENTITY=… sign with your certificate instead of ad hoc (see the end of this file)
+# APP_PATH=… where to put the app (default build/HouseControl.app)
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
-APP="$ROOT/build/HouseControl.app"
+APP="${APP_PATH:-$ROOT/build/HouseControl.app}"
+# One version for both apps: the iPhone app's MARKETING_VERSION / CURRENT_PROJECT_VERSION.
+VERSION="${VERSION:-$(sed -n 's/^MARKETING_VERSION *= *//p' "$ROOT/ios/Config/Base.xcconfig")}"
+BUILD="${BUILD:-$(sed -n 's/^CURRENT_PROJECT_VERSION *= *//p' "$ROOT/ios/Config/Base.xcconfig")}"
echo "▸ Building web UI"
cd "$ROOT/web"
@@ -11,8 +17,10 @@ npm run build --silent
echo "▸ Building native shell"
cd "$ROOT/macos"
-swift build -c release 2>&1 | grep -E "error|warning: unused|Build complete" || true
-BIN="$(swift build -c release --show-bin-path)/HouseControl"
+ARCH_FLAGS=()
+[ -n "${UNIVERSAL:-}" ] && ARCH_FLAGS=(--arch arm64 --arch x86_64)
+swift build -c release ${ARCH_FLAGS[@]+"${ARCH_FLAGS[@]}"} 2>&1 | grep -E "error|warning: unused|Build complete" || true
+BIN="$(swift build -c release ${ARCH_FLAGS[@]+"${ARCH_FLAGS[@]}"} --show-bin-path)/HouseControl"
[ -x "$BIN" ] || { echo "Swift build failed"; exit 1; }
echo "▸ Assembling $APP"
@@ -32,12 +40,14 @@ cat > "$APP/Contents/Info.plist" <<PLIST
<key>CFBundleExecutable</key><string>HouseControl</string>
<key>CFBundleIconFile</key><string>AppIcon</string>
<key>CFBundlePackageType</key><string>APPL</string>
- <key>CFBundleShortVersionString</key><string>0.1.0</string>
- <key>CFBundleVersion</key><string>1</string>
+ <key>CFBundleShortVersionString</key><string>$VERSION</string>
+ <key>CFBundleVersion</key><string>$BUILD</string>
<key>LSMinimumSystemVersion</key><string>13.0</string>
+ <key>LSApplicationCategoryType</key><string>public.app-category.utilities</string>
+ <key>NSHumanReadableCopyright</key><string>© 0xProbability. MIT License.</string>
<key>LSUIElement</key><true/>
- <key>NSLocalNetworkUsageDescription</key><string>House Control lets the iPhones you paired find this Mac on your network to receive your floor plan.</string>
- <key>NSBonjourServices</key><array><string>_housecontrol._tcp</string></array>
+ <key>NSLocalNetworkUsageDescription</key><string>House Control finds your Home Assistant and Hue Bridge on this network, and lets the iPhones you paired find this Mac to receive your floor plan.</string>
+ <key>NSBonjourServices</key><array><string>_housecontrol._tcp</string><string>_hue._tcp</string><string>_home-assistant._tcp</string></array>
<key>NSHighResolutionCapable</key><true/>
</dict>
</plist>
@@ -46,5 +56,10 @@ PLIST
# to the signature, and an ad-hoc one changes with every build, so it asks again each time.
# CODESIGN_IDENTITY="Apple Development: …" (see `security find-identity -v -p codesigning`)
# signs with your own certificate and the permission sticks.
-codesign --force --sign "${CODESIGN_IDENTITY:--}" "$APP" >/dev/null 2>&1 || echo " (signing skipped)"
+# A real identity also gets the hardened runtime and a secure timestamp, which notarization requires.
+if [ -n "${CODESIGN_IDENTITY:-}" ]; then
+ codesign --force --options runtime --timestamp --sign "$CODESIGN_IDENTITY" "$APP" || { echo "Signing failed"; exit 1; }
+else
+ codesign --force --sign - "$APP" >/dev/null 2>&1 || echo " (signing skipped)"
+fi
echo "✓ Done: $APP"
diff --git a/scripts/dmg-settings.py b/scripts/dmg-settings.py
new file mode 100644
index 0000000..b28cf80
--- /dev/null
+++ b/scripts/dmg-settings.py
@@ -0,0 +1,26 @@
+# Layout of the House Control disk image, for dmgbuild (scripts/release-mac.sh runs it).
+# The positions match the arrow drawn by scripts/make-dmg-background.swift.
+import os
+
+app = defines["app"] # noqa: F821 (dmgbuild passes -D app=… -D root=…)
+root = defines["root"] # noqa: F821
+
+format = "ULFO" # LZFSE: smallest, opens on macOS 10.11 and later
+files = [app]
+symlinks = {"Applications": "/Applications"}
+icon = os.path.join(root, "macos", "AppIcon.icns")
+background = os.path.join(root, "macos", "dmg-background.tiff")
+
+window_rect = ((200, 160), (640, 400))
+default_view = "icon-view"
+show_status_bar = False
+show_tab_view = False
+show_toolbar = False
+show_pathbar = False
+show_sidebar = False
+icon_size = 112
+text_size = 13
+icon_locations = {
+ os.path.basename(app): (170, 200),
+ "Applications": (470, 200),
+}
diff --git a/scripts/make-dmg-background.swift b/scripts/make-dmg-background.swift
new file mode 100755
index 0000000..71e9ec1
--- /dev/null
+++ b/scripts/make-dmg-background.swift
@@ -0,0 +1,88 @@
+#!/usr/bin/swift
+// Draws the background of the disk image window (the app on the left, Applications on the
+// right, an arrow between them) and writes macos/dmg-background.tiff with 1x and 2x images.
+// Usage: ./scripts/make-dmg-background.swift (scripts/release-mac.sh uses the result)
+import AppKit
+
+let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
+// Must match the window and icon positions in scripts/dmg-settings.py.
+let size = CGSize(width: 640, height: 400)
+let appCenter = CGPoint(x: 170, y: 200)
+let applicationsCenter = CGPoint(x: 470, y: 200)
+
+func render(scale: CGFloat) -> NSBitmapImageRep {
+ let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width * scale), pixelsHigh: Int(size.height * scale),
+ bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
+ colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
+ rep.size = size
+ NSGraphicsContext.saveGraphicsState()
+ NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
+ // The context is already scaled from points to the rep's pixels (rep.size is in points).
+ let ctx = NSGraphicsContext.current!.cgContext
+ // AppKit's origin is bottom-left; the layout above is written top-down.
+ ctx.translateBy(x: 0, y: size.height)
+ ctx.scaleBy(x: 1, y: -1)
+
+ // A light dawn sky: Finder draws the icon labels in black on a background picture,
+ // even in dark mode, so the window has to stay light.
+ let space = CGColorSpaceCreateDeviceRGB()
+ let sky = CGGradient(colorsSpace: space, colors: [
+ NSColor(red: 0.93, green: 0.94, blue: 0.98, alpha: 1).cgColor,
+ NSColor(red: 0.98, green: 0.95, blue: 0.91, alpha: 1).cgColor,
+ ] as CFArray, locations: [0, 1])!
+ ctx.drawLinearGradient(sky, start: .zero, end: CGPoint(x: 0, y: size.height), options: [])
+
+ // A warm glow under the app, as if its windows were lit.
+ let glow = CGGradient(colorsSpace: space, colors: [
+ NSColor(red: 1.0, green: 0.66, blue: 0.30, alpha: 0.28).cgColor,
+ NSColor(red: 1.0, green: 0.72, blue: 0.36, alpha: 0).cgColor,
+ ] as CFArray, locations: [0, 1])!
+ ctx.drawRadialGradient(glow, startCenter: appCenter, startRadius: 0, endCenter: appCenter, endRadius: 150, options: [])
+
+ // The arrow from the app to Applications.
+ let from = CGPoint(x: appCenter.x + 78, y: appCenter.y)
+ let to = CGPoint(x: applicationsCenter.x - 78, y: appCenter.y)
+ ctx.setStrokeColor(NSColor(red: 0.16, green: 0.18, blue: 0.26, alpha: 0.45).cgColor)
+ ctx.setLineWidth(3)
+ ctx.setLineCap(.round)
+ ctx.setLineJoin(.round)
+ ctx.setLineDash(phase: 0, lengths: [1, 9])
+ ctx.move(to: from)
+ ctx.addLine(to: CGPoint(x: to.x - 6, y: to.y))
+ ctx.strokePath()
+ ctx.setLineDash(phase: 0, lengths: [])
+ ctx.move(to: CGPoint(x: to.x - 12, y: to.y - 10))
+ ctx.addLine(to: to)
+ ctx.addLine(to: CGPoint(x: to.x - 12, y: to.y + 10))
+ ctx.strokePath()
+
+ // The caption, drawn the right way up.
+ ctx.saveGState()
+ ctx.translateBy(x: 0, y: size.height)
+ ctx.scaleBy(x: 1, y: -1)
+ let style = NSMutableParagraphStyle()
+ style.alignment = .center
+ let caption = NSAttributedString(string: "Drag House Control into Applications", attributes: [
+ .font: NSFont.systemFont(ofSize: 15, weight: .semibold),
+ .foregroundColor: NSColor(red: 0.10, green: 0.11, blue: 0.16, alpha: 0.9),
+ .paragraphStyle: style,
+ ])
+ caption.draw(in: CGRect(x: 0, y: 72, width: size.width, height: 22))
+ let hint = NSAttributedString(string: "Then open it from Applications and look for the house in the menu bar.", attributes: [
+ .font: NSFont.systemFont(ofSize: 12),
+ .foregroundColor: NSColor(red: 0.10, green: 0.11, blue: 0.16, alpha: 0.5),
+ .paragraphStyle: style,
+ ])
+ hint.draw(in: CGRect(x: 0, y: 50, width: size.width, height: 18))
+ ctx.restoreGState()
+
+ NSGraphicsContext.restoreGraphicsState()
+ return rep
+}
+
+let image = NSImage(size: size)
+image.addRepresentation(render(scale: 1))
+image.addRepresentation(render(scale: 2))
+let out = root.appendingPathComponent("macos/dmg-background.tiff")
+try! image.tiffRepresentation(using: .lzw, factor: 0)!.write(to: out)
+print("✓ \(out.path)")
diff --git a/scripts/release-mac.sh b/scripts/release-mac.sh
new file mode 100755
index 0000000..c79ebaa
--- /dev/null
+++ b/scripts/release-mac.sh
@@ -0,0 +1,78 @@
+#!/bin/bash
+# Builds the Mac app people download: universal, signed with a Developer ID, notarized by
+# Apple and packed into a disk image, so it opens on any Mac without a warning.
+# ./scripts/release-mac.sh build/HouseControl-<version>.dmg
+# ./scripts/release-mac.sh --publish …and attach it to a GitHub release v<version> (needs `gh`)
+#
+# Needs:
+# a "Developer ID Application" certificate in your keychain (Xcode → Settings → Accounts →
+# Manage Certificates → + → Developer ID Application). Picked up by itself, or set CODESIGN_IDENTITY.
+# for notarization, either an App Store Connect API key
+# ASC_KEY_ID, ASC_ISSUER_ID (key file AuthKey_<id>.p8 in ~/.appstoreconnect/private_keys)
+# or a profile stored with `xcrun notarytool store-credentials`: NOTARY_PROFILE=<name>.
+# uv (brew install uv), which runs dmgbuild to lay out the disk image.
+# UNSIGNED=1 skips signing and notarization: a disk image for testing the layout only —
+# macOS will refuse to open the app in it until the user allows it in System Settings.
+# The version is MARKETING_VERSION in ios/Config/Base.xcconfig, shared with the iPhone app.
+set -euo pipefail
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+VERSION="$(sed -n 's/^MARKETING_VERSION *= *//p' "$ROOT/ios/Config/Base.xcconfig")"
+# Its own folder, so a release build never replaces the app you run from build/.
+# The bundle is named with a space here, which is what people see in Applications.
+APP="$ROOT/build/release/House Control.app"
+DMG="$ROOT/build/HouseControl-$VERSION.dmg"
+command -v uvx >/dev/null || { echo "Install uv first: brew install uv"; exit 1; }
+
+if [ -z "${UNSIGNED:-}" ]; then
+ if [ -z "${CODESIGN_IDENTITY:-}" ]; then
+ CODESIGN_IDENTITY="$(security find-identity -v -p codesigning | sed -n 's/.*"\(Developer ID Application: .*\)"/\1/p' | head -1)"
+ fi
+ [ -n "$CODESIGN_IDENTITY" ] || {
+ echo "No Developer ID Application certificate in the keychain."
+ echo "Create one in Xcode → Settings → Accounts → Manage Certificates → + → Developer ID Application,"
+ echo "or run with UNSIGNED=1 for a test image."
+ exit 1
+ }
+ if [ -n "${NOTARY_PROFILE:-}" ]; then
+ NOTARY=(--keychain-profile "$NOTARY_PROFILE")
+ else
+ : "${ASC_KEY_ID:?Set ASC_KEY_ID and ASC_ISSUER_ID (or NOTARY_PROFILE) for notarization}"
+ : "${ASC_ISSUER_ID:?Set ASC_ISSUER_ID to your App Store Connect issuer ID}"
+ KEY_FILE="${ASC_KEY_FILE:-$HOME/.appstoreconnect/private_keys/AuthKey_$ASC_KEY_ID.p8}"
+ [ -f "$KEY_FILE" ] || { echo "No API key file at $KEY_FILE"; exit 1; }
+ NOTARY=(--key "$KEY_FILE" --key-id "$ASC_KEY_ID" --issuer "$ASC_ISSUER_ID")
+ fi
+ echo "▸ Signing as $CODESIGN_IDENTITY"
+ export CODESIGN_IDENTITY
+fi
+
+UNIVERSAL=1 APP_PATH="$APP" "$ROOT/scripts/build-app.sh"
+lipo -archs "$APP/Contents/MacOS/HouseControl"
+
+[ -f "$ROOT/macos/dmg-background.tiff" ] || "$ROOT/scripts/make-dmg-background.swift"
+echo "▸ Packing $DMG"
+rm -f "$DMG"
+uvx --quiet dmgbuild -s "$ROOT/scripts/dmg-settings.py" -D app="$APP" -D root="$ROOT" "House Control $VERSION" "$DMG"
+
+if [ -z "${UNSIGNED:-}" ]; then
+ codesign --force --timestamp --sign "$CODESIGN_IDENTITY" "$DMG"
+ echo "▸ Notarizing (usually a few minutes)"
+ xcrun notarytool submit "$DMG" "${NOTARY[@]}" --wait --timeout 30m | tee "$ROOT/build/notary.log"
+ grep -q "status: Accepted" "$ROOT/build/notary.log" || {
+ id="$(sed -n 's/^ *id: //p' "$ROOT/build/notary.log" | head -1)"
+ echo "Notarization failed. Details: xcrun notarytool log $id ${NOTARY[*]}"
+ exit 1
+ }
+ xcrun stapler staple "$DMG"
+ echo "▸ Checking it the way Gatekeeper will"
+ spctl --assess --type open --context context:primary-signature --verbose=2 "$DMG"
+fi
+shasum -a 256 "$DMG" | tee "$DMG.sha256"
+echo "✓ $DMG"
+
+if [ "${1:-}" = "--publish" ]; then
+ [ -z "${UNSIGNED:-}" ] || { echo "Refusing to publish an unsigned image"; exit 1; }
+ echo "▸ Publishing release v$VERSION"
+ cd "$ROOT"
+ gh release create "v$VERSION" "$DMG" "$DMG.sha256" --title "House Control $VERSION" --generate-notes
+fi
diff --git a/tools/lab/.gitignore b/tools/lab/.gitignore
new file mode 100644
index 0000000..64ec460
--- /dev/null
+++ b/tools/lab/.gitignore
@@ -0,0 +1,4 @@
+.homekit/
+.hue/
+.ha/
+node_modules/
diff --git a/tools/lab/README.md b/tools/lab/README.md
new file mode 100644
index 0000000..4fc8db8
--- /dev/null
+++ b/tools/lab/README.md
@@ -0,0 +1,60 @@
+# The lab: smart homes to test against
+
+Pretend versions of the platforms House Control connects to, so it can be built and tested without owning the
+hardware. Each runs on your Mac and behaves like the real thing on the network: it is found by the app's
+discovery, speaks the real protocol and prints every command it receives.
+
+| Command | What it is |
+| --- | --- |
+| `./tools/lab/homeassistant.sh` | A real Home Assistant (installed into `tools/lab/.ha` on first run, about 1 GB) with its demo devices: lights with every colour mode, three climate devices, fans, a thermometer. Prints the address and an access token |
+| `cd tools/lab && npm install && npm run hue` | A Philips Hue Bridge emulator: five lamps (colour, white ambiance, dimmable, a plug) in three rooms, a motion sensor with a thermometer. Press Enter to "press" the link button, or start it with `npm run hue -- --auto` |
+| `cd tools/lab && npm run homekit` | A HomeKit bridge with lamps, a plug, two air conditioners and a thermometer, built on [HAP-NodeJS](https://github.com/homebridge/HAP-NodeJS). Add it in the Home app on your iPhone with **+ → Add Accessory → More options… → House Control Lab**, setup code **031-45-154** |
+
+Needs [uv](https://github.com/astral-sh/uv) for Home Assistant (`brew install uv`) and Node.js for the other two.
+
+## A full run
+
+1. Start the lab Home Assistant and the Hue emulator (`npm run hue -- --auto`).
+2. Start a throw-away House Control, so your own plan and sign-ins stay untouched:
+
+ ```bash
+ HOUSE_DATA_DIR=/tmp/house-lab HOUSE_OPEN_EDITOR=connections build/HouseControl.app/Contents/MacOS/HouseControl
+ ```
+
+3. **Connections → Home Assistant**: the lab server is listed; press **Use**, paste the token, **Connect**.
+ **Connections → Philips Hue**: press **Pair**.
+4. Link a few lamps and an AC under **Real device**, **Save & apply**, and use the panel. The emulators print each
+ command; change something in Home Assistant's web UI and watch the panel follow.
+5. To test the iPhone app, run it in the simulator and pair it with that instance (`scripts/ios-sim.sh`; see
+ the README's development section). Home Assistant and Hue come over with the plan.
+
+Apple Home needs a real iPhone: the iOS Simulator grants HomeKit access but cannot create a home without an
+iCloud account. Add the lab's HomeKit bridge to your Home app, then **Settings → More connections → Apple Home**
+in House Control on the phone.
+
+## Automated tests
+
+The unit tests cover the translation to and from each platform and the hub's routing. Two more run against the lab:
+
+```bash
+cd core
+HOUSE_TEST_HA_URL=http://127.0.0.1:8123 HOUSE_TEST_HA_TOKEN=$(cat ../tools/lab/.ha/token) \
+HOUSE_TEST_HUE_HOST=localhost:8443 swift test --filter ServiceTests
+```
+
+The Hue test expects the emulator started with `--auto`.
+
+## Your real Tuya devices, through the lab
+
+The lab Home Assistant is a real one: **Settings → Devices & services → Add integration → Tuya** signs in with
+your Smart Life User Code, and your own lamps and air conditioners appear next to the demo devices — and in
+House Control's Home Assistant list. (To put them into Apple Home as well, use **HomeKit Bridge** on a Home
+Assistant that runs on its own box — a Raspberry Pi, Home Assistant Green, a Linux machine: the lab's cannot
+announce a HomeKit bridge on macOS, see below.)
+
+Run as a plain process on macOS, Home Assistant cannot use Bluetooth (macOS would stop it), so the lab replaces
+that integration with a stub in `homeassistant/custom_components/bluetooth`. Its own Bonjour announcements do
+not reach the network either; `homeassistant.sh` announces the server with `dns-sd`, in the same format (which
+is enough for House Control, but not for a HomeKit Bridge).
+
+Delete `tools/lab/.ha`, `.hue` or `.homekit` to start any of them from scratch.
diff --git a/tools/lab/homeassistant.sh b/tools/lab/homeassistant.sh
new file mode 100755
index 0000000..740e060
--- /dev/null
+++ b/tools/lab/homeassistant.sh
@@ -0,0 +1,57 @@
+#!/bin/bash
+# Runs a Home Assistant full of pretend devices on this Mac, for testing House Control's
+# Home Assistant connection without hardware. The first run installs Home Assistant into
+# tools/lab/.ha (about 1 GB, a few minutes; needs uv: brew install uv).
+#
+# ./tools/lab/homeassistant.sh → http://<this Mac>:8123, prints a token for House Control
+#
+# Sign in to the web UI as lab / lab-lab-lab. Delete tools/lab/.ha to start from scratch.
+# To try your real devices too, add their integration in the web UI (Settings → Devices &
+# services): "Tuya" signs in to Smart Life with the same QR code as House Control does.
+set -euo pipefail
+LAB="$(cd "$(dirname "$0")" && pwd)"
+HA="${HA_HOME:-$LAB/.ha}"
+PORT=8123
+command -v uv >/dev/null || { echo "Install uv first: brew install uv"; exit 1; }
+
+if [ ! -x "$HA/venv/bin/hass" ]; then
+ echo "▸ Installing Home Assistant into $HA (first run only)"
+ uv venv --quiet --python 3.13 "$HA/venv"
+ VIRTUAL_ENV="$HA/venv" uv pip install --quiet homeassistant numpy av PyTurboJPEG
+fi
+
+mkdir -p "$HA/config"
+cp "$LAB/homeassistant/configuration.yaml" "$HA/config/"
+rm -rf "$HA/config/custom_components"
+cp -R "$LAB/homeassistant/custom_components" "$HA/config/"
+
+echo "▸ Starting Home Assistant (log: $HA/hass.log)"
+"$HA/venv/bin/hass" -c "$HA/config" >"$HA/hass.log" 2>&1 &
+HASS=$!
+trap 'kill $HASS 2>/dev/null' EXIT
+until curl -fs "http://127.0.0.1:$PORT/api/onboarding" >/dev/null 2>&1; do
+ kill -0 $HASS 2>/dev/null || { echo "Home Assistant stopped; see $HA/hass.log"; exit 1; }
+ sleep 1
+done
+TOKEN="$("$HA/venv/bin/python" "$LAB/homeassistant/onboard.py" --url "http://127.0.0.1:$PORT" --out "$HA/token")"
+
+HOST="$(scutil --get LocalHostName 2>/dev/null || echo localhost).local"
+# Home Assistant announces itself with Bonjour, but run as a plain process on macOS its own
+# announcer cannot share the port with the system's: announce it the same way through dns-sd.
+VERSION="$("$HA/venv/bin/python" -c 'from homeassistant.const import __version__; print(__version__)')"
+dns-sd -R "House Control Lab" _home-assistant._tcp local $PORT location_name="House Control Lab" \
+ internal_url="http://$HOST:$PORT" base_url="http://$HOST:$PORT" version="$VERSION" requires_api_password=True >/dev/null &
+ANNOUNCE=$!
+trap 'kill $HASS $ANNOUNCE 2>/dev/null' EXIT
+cat <<EOF
+
+Home Assistant is running with pretend lights, heat pumps and sensors.
+ Web UI http://$HOST:$PORT (lab / lab-lab-lab)
+
+In House Control: Edit Home… → Connections → Home Assistant
+ Address http://$HOST:$PORT
+ Token $TOKEN
+
+Ctrl-C stops it.
+EOF
+wait $HASS
diff --git a/tools/lab/homeassistant/configuration.yaml b/tools/lab/homeassistant/configuration.yaml
new file mode 100644
index 0000000..c7dbdfa
--- /dev/null
+++ b/tools/lab/homeassistant/configuration.yaml
@@ -0,0 +1,23 @@
+# A Home Assistant with pretend devices, for testing House Control without hardware.
+# Started by ../homeassistant.sh. The "demo" integration adds lights (dimmable, white,
+# colour), thermostats / heat pumps and temperature sensors that answer like real ones.
+homeassistant:
+ name: House Control Lab
+ unit_system: metric
+ temperature_unit: C
+ time_zone: UTC
+ country: GB
+ latitude: 51.5
+ longitude: -0.12
+ elevation: 10
+
+http:
+ server_port: 8123
+
+api:
+websocket_api:
+frontend:
+config:
+zeroconf:
+
+demo:
diff --git a/tools/lab/homeassistant/custom_components/bluetooth/__init__.py b/tools/lab/homeassistant/custom_components/bluetooth/__init__.py
new file mode 100644
index 0000000..060dc8d
--- /dev/null
+++ b/tools/lab/homeassistant/custom_components/bluetooth/__init__.py
@@ -0,0 +1,9 @@
+"""Stands in for Home Assistant's Bluetooth integration in the House Control lab.
+
+Run as a plain process on macOS, Home Assistant is killed the moment it touches
+Bluetooth (it has no Bluetooth permission), and the lab has no Bluetooth devices anyway.
+"""
+
+
+async def async_setup(hass, config):
+ return True
diff --git a/tools/lab/homeassistant/custom_components/bluetooth/manifest.json b/tools/lab/homeassistant/custom_components/bluetooth/manifest.json
new file mode 100644
index 0000000..4664244
--- /dev/null
+++ b/tools/lab/homeassistant/custom_components/bluetooth/manifest.json
@@ -0,0 +1,8 @@
+{
+ "domain": "bluetooth",
+ "name": "Bluetooth (disabled in the lab)",
+ "version": "0.0.1",
+ "documentation": "https://github.com/0xProbabillity/house-control",
+ "codeowners": [],
+ "iot_class": "local_push"
+}
diff --git a/tools/lab/homeassistant/onboard.py b/tools/lab/homeassistant/onboard.py
new file mode 100644
index 0000000..c6c4a2f
--- /dev/null
+++ b/tools/lab/homeassistant/onboard.py
@@ -0,0 +1,57 @@
+"""Finishes the first-run setup of the lab's Home Assistant and prints a long-lived token.
+
+Run by ../homeassistant.sh with Home Assistant's own Python (it needs aiohttp).
+Creates the owner account "lab" (password "lab-lab-lab"): a throw-away instance on this Mac.
+"""
+import argparse
+import asyncio
+import json
+import pathlib
+
+import aiohttp
+
+
+async def main(url: str, out: pathlib.Path) -> None:
+ client_id = f"{url}/"
+ async with aiohttp.ClientSession() as http:
+ async with http.get(f"{url}/api/onboarding") as r:
+ steps = {s["step"]: s["done"] for s in await r.json()}
+ if steps.get("user"):
+ if out.exists():
+ print(out.read_text().strip())
+ return
+ raise SystemExit("Already set up by someone else: delete the lab's .ha/config folder to start over.")
+
+ async with http.post(f"{url}/api/onboarding/users", json={
+ "client_id": client_id, "name": "Lab", "username": "lab", "password": "lab-lab-lab", "language": "en",
+ }) as r:
+ code = (await r.json())["auth_code"]
+ async with http.post(f"{url}/auth/token", data={
+ "grant_type": "authorization_code", "code": code, "client_id": client_id,
+ }) as r:
+ access = (await r.json())["access_token"]
+ auth = {"Authorization": f"Bearer {access}"}
+ for step, body in (("core_config", {}), ("analytics", {}),
+ ("integration", {"client_id": client_id, "redirect_uri": f"{url}/?auth_callback=1"})):
+ async with http.post(f"{url}/api/onboarding/{step}", json=body, headers=auth) as r:
+ r.raise_for_status()
+
+ async with http.ws_connect(f"{url}/api/websocket") as ws:
+ await ws.receive_json() # auth_required
+ await ws.send_json({"type": "auth", "access_token": access})
+ await ws.receive_json() # auth_ok
+ await ws.send_json({"id": 1, "type": "auth/long_lived_access_token",
+ "client_name": "House Control lab", "lifespan": 3650})
+ token = (await ws.receive_json())["result"]
+
+ out.write_text(token + "\n")
+ out.chmod(0o600)
+ print(token)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--url", default="http://127.0.0.1:8123")
+ parser.add_argument("--out", type=pathlib.Path, required=True)
+ args = parser.parse_args()
+ asyncio.run(main(args.url.rstrip("/"), args.out))
diff --git a/tools/lab/homekit.mjs b/tools/lab/homekit.mjs
new file mode 100644
index 0000000..9337b0f
--- /dev/null
+++ b/tools/lab/homekit.mjs
@@ -0,0 +1,126 @@
+// A pretend HomeKit home for testing House Control's Apple Home support without any hardware:
+// a bridge with dimmable, white-tunable and colour lamps, a plug, two air conditioners
+// (HomeKit "heater coolers") and a temperature sensor. Add it in the Home app — or in the
+// iOS Simulator — like a real accessory, using the setup code it prints.
+//
+// cd tools/lab && npm install && npm run homekit
+//
+// Every change an app makes is printed, and the sensor's reading drifts, so you can watch both
+// directions. State is kept in tools/lab/.homekit (delete it to unpair and start over).
+import { Accessory, Bridge, Categories, Characteristic, HAPStorage, MDNSAdvertiser, Service, uuid } from 'hap-nodejs';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+HAPStorage.setCustomStoragePath(path.join(here, '.homekit'));
+
+const PIN = process.env.PIN || '031-45-154';
+const PORT = Number(process.env.PORT || 51826);
+const NAME = process.env.NAME || 'House Control Lab';
+
+const bridge = new Bridge(NAME, uuid.generate(`house-control-lab:${NAME}`));
+bridge.getService(Service.AccessoryInformation)
+ .setCharacteristic(Characteristic.Manufacturer, 'House Control')
+ .setCharacteristic(Characteristic.Model, 'Lab bridge')
+ .setCharacteristic(Characteristic.SerialNumber, 'HC-LAB-1');
+
+const log = (who, what, value) => console.log(`${new Date().toLocaleTimeString()} ${who.padEnd(18)} ${what} → ${JSON.stringify(value)}`);
+
+// Characteristics keep their own value; a setter just has to accept it.
+function watch(name, service, characteristic) {
+ service.getCharacteristic(characteristic).on('set', (value, done) => { log(name, characteristic.name || 'value', value); done(); });
+}
+
+function accessory(name, category) {
+ const a = new Accessory(name, uuid.generate(`house-control-lab:${NAME}:${name}`));
+ a.category = category;
+ a.getService(Service.AccessoryInformation)
+ .setCharacteristic(Characteristic.Manufacturer, 'House Control Lab')
+ .setCharacteristic(Characteristic.Model, name)
+ .setCharacteristic(Characteristic.SerialNumber, uuid.generate(name).slice(0, 8));
+ bridge.addBridgedAccessory(a);
+ return a;
+}
+
+function lamp(name, { dim = false, white = false, colour = false } = {}) {
+ const a = accessory(name, Categories.LIGHTBULB);
+ const s = a.addService(Service.Lightbulb, name);
+ watch(name, s, Characteristic.On);
+ if (dim) { s.getCharacteristic(Characteristic.Brightness).updateValue(70); watch(name, s, Characteristic.Brightness); }
+ if (white) { s.getCharacteristic(Characteristic.ColorTemperature).updateValue(320); watch(name, s, Characteristic.ColorTemperature); }
+ if (colour) {
+ s.getCharacteristic(Characteristic.Hue).updateValue(30);
+ s.getCharacteristic(Characteristic.Saturation).updateValue(60);
+ watch(name, s, Characteristic.Hue);
+ watch(name, s, Characteristic.Saturation);
+ }
+ return s;
+}
+
+function plug(name) {
+ const a = accessory(name, Categories.OUTLET);
+ const s = a.addService(Service.Outlet, name);
+ watch(name, s, Characteristic.On);
+ return s;
+}
+
+function airConditioner(name, roomTemp) {
+ const a = accessory(name, Categories.AIR_CONDITIONER);
+ const s = a.addService(Service.HeaterCooler, name);
+ s.getCharacteristic(Characteristic.CurrentTemperature).updateValue(roomTemp);
+ s.getCharacteristic(Characteristic.TargetHeaterCoolerState).updateValue(Characteristic.TargetHeaterCoolerState.COOL);
+ s.getCharacteristic(Characteristic.CoolingThresholdTemperature).updateValue(24).setProps({ minValue: 16, maxValue: 30, minStep: 1 });
+ s.getCharacteristic(Characteristic.HeatingThresholdTemperature).updateValue(22).setProps({ minValue: 16, maxValue: 30, minStep: 1 });
+ s.getCharacteristic(Characteristic.RotationSpeed).setProps({ minValue: 0, maxValue: 100, minStep: 25 }).updateValue(50);
+ s.getCharacteristic(Characteristic.SwingMode).updateValue(0);
+ for (const c of [Characteristic.Active, Characteristic.TargetHeaterCoolerState, Characteristic.CoolingThresholdTemperature,
+ Characteristic.HeatingThresholdTemperature, Characteristic.RotationSpeed, Characteristic.SwingMode]) watch(name, s, c);
+ // The unit reports what it is doing from what it was asked to do.
+ const current = () => {
+ const active = s.getCharacteristic(Characteristic.Active).value === 1;
+ const target = s.getCharacteristic(Characteristic.TargetHeaterCoolerState).value;
+ const C = Characteristic.CurrentHeaterCoolerState;
+ s.getCharacteristic(C).updateValue(!active ? C.INACTIVE : target === 1 ? C.HEATING : target === 2 ? C.COOLING : C.IDLE);
+ };
+ s.getCharacteristic(Characteristic.Active).on('change', current);
+ s.getCharacteristic(Characteristic.TargetHeaterCoolerState).on('change', current);
+ current();
+ return s;
+}
+
+function sensor(name, value) {
+ const a = accessory(name, Categories.SENSOR);
+ const s = a.addService(Service.TemperatureSensor, name);
+ s.getCharacteristic(Characteristic.CurrentTemperature).updateValue(value);
+ return s;
+}
+
+lamp('Living Ceiling', { dim: true, white: true });
+lamp('Floor Lamp', { dim: true });
+lamp('TV Backlight', { dim: true, colour: true });
+lamp('Kitchen Spots', { dim: true, white: true, colour: true });
+plug('Bedside Plug');
+const livingAC = airConditioner('Living AC', 26.5);
+airConditioner('Bedroom AC', 25);
+const thermometer = sensor('Living Thermometer', 26.5);
+
+// The room cools while the living room AC runs, and warms again when it stops.
+setInterval(() => {
+ const t = thermometer.getCharacteristic(Characteristic.CurrentTemperature);
+ const on = livingAC.getCharacteristic(Characteristic.Active).value === 1;
+ const goal = on ? livingAC.getCharacteristic(Characteristic.CoolingThresholdTemperature).value : 27;
+ const next = Math.round((t.value + Math.sign(goal - t.value) * Math.min(0.2, Math.abs(goal - t.value))) * 10) / 10;
+ if (next !== t.value) { t.updateValue(next); livingAC.getCharacteristic(Characteristic.CurrentTemperature).updateValue(next); }
+}, 5000);
+
+bridge.publish({
+ username: process.env.USERNAME || '0E:5C:A1:AB:00:01',
+ pincode: PIN,
+ port: PORT,
+ category: Categories.BRIDGE,
+ advertiser: MDNSAdvertiser.CIAO,
+});
+
+console.log(`\n${NAME} is on the network (port ${PORT}).`);
+console.log(`Add it in the Home app: + → Add Accessory → More options… → ${NAME}, setup code ${PIN}`);
+console.log(`Setup URI (for a QR code): ${bridge.setupURI()}\n`);
diff --git a/tools/lab/hue.mjs b/tools/lab/hue.mjs
new file mode 100644
index 0000000..3163901
--- /dev/null
+++ b/tools/lab/hue.mjs
@@ -0,0 +1,153 @@
+// A pretend Philips Hue Bridge for testing House Control's Hue support without hardware.
+// It speaks the bridge's local API (CLIP v2 over HTTPS with a self-signed certificate,
+// link-button pairing, the event stream) for a handful of lamps and a motion sensor with a
+// thermometer, and announces itself on the network as a Hue Bridge does.
+//
+// cd tools/lab && npm run hue then: Edit Home… → Connections → Philips Hue
+//
+// Pairing needs the round button: press Enter here to "press" it (or start with --auto,
+// which presses it for every pairing attempt). Changes made by an app are printed.
+// Needs openssl (macOS has it) to make the certificate, kept in tools/lab/.hue.
+import https from 'node:https';
+import { execFileSync, spawn } from 'node:child_process';
+import { randomUUID, randomBytes } from 'node:crypto';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const dir = path.join(here, '.hue');
+mkdirSync(dir, { recursive: true });
+const PORT = Number(process.env.PORT || 8443);
+const AUTO = process.argv.includes('--auto');
+const BRIDGE_ID = 'ECB5FAFFFE0LAB01';
+
+// Like a real bridge: a self-signed certificate whose common name is the bridge id.
+const keyFile = path.join(dir, 'key.pem'), certFile = path.join(dir, 'cert.pem');
+if (!existsSync(certFile)) {
+ execFileSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
+ '-keyout', keyFile, '-out', certFile, '-days', '3650', '-subj', `/C=NL/O=Philips Hue/CN=${BRIDGE_ID.toLowerCase()}`], { stdio: 'ignore' });
+}
+
+// Paired apps survive a restart.
+const keysFile = path.join(dir, 'keys.json');
+const keys = new Set(existsSync(keysFile) ? JSON.parse(readFileSync(keysFile, 'utf8')) : []);
+let buttonUntil = 0;
+const press = () => { buttonUntil = Date.now() + 30_000; console.log('● Link button pressed: pairing is open for 30 s'); };
+
+const id = () => randomUUID();
+const resources = [];
+const add = (r) => { resources.push(r); return r; };
+
+function device(name, archetype) {
+ return add({ id: id(), type: 'device', metadata: { name, archetype }, product_data: { manufacturer_name: 'Signify Netherlands B.V.' }, services: [] });
+}
+function light(name, room, { dim = true, ct = false, colour = false, archetype = 'classic_bulb' } = {}) {
+ const dev = device(name, archetype);
+ const l = add({
+ id: id(), id_v1: `/lights/${resources.filter((r) => r.type === 'light').length + 1}`, type: 'light',
+ owner: { rid: dev.id, rtype: 'device' }, metadata: { name, archetype }, on: { on: false }, mode: 'normal',
+ });
+ if (dim) l.dimming = { brightness: 80, min_dim_level: 0.2 };
+ if (ct) l.color_temperature = { mirek: 366, mirek_valid: true, mirek_schema: { mirek_minimum: 153, mirek_maximum: 500 } };
+ if (colour) l.color = { xy: { x: 0.4573, y: 0.41 }, gamut_type: 'C', gamut: { red: { x: 0.6915, y: 0.3083 }, green: { x: 0.17, y: 0.7 }, blue: { x: 0.1532, y: 0.0475 } } };
+ dev.services.push({ rid: l.id, rtype: 'light' });
+ const zigbee = add({ id: id(), type: 'zigbee_connectivity', owner: { rid: dev.id, rtype: 'device' }, status: 'connected' });
+ dev.services.push({ rid: zigbee.id, rtype: 'zigbee_connectivity' });
+ room.children.push({ rid: dev.id, rtype: 'device' });
+ return l;
+}
+function room(name, archetype) { return add({ id: id(), type: 'room', metadata: { name, archetype }, children: [], services: [] }); }
+
+const bridgeDevice = device('Hue Bridge Lab', 'bridge_v2');
+const bridge = add({ id: id(), type: 'bridge', owner: { rid: bridgeDevice.id, rtype: 'device' }, bridge_id: BRIDGE_ID.toLowerCase(), time_zone: { time_zone: 'Europe/Amsterdam' } });
+bridgeDevice.services.push({ rid: bridge.id, rtype: 'bridge' });
+
+const living = room('Living room', 'living_room');
+const bedroom = room('Bedroom', 'bedroom');
+const kitchen = room('Kitchen', 'kitchen');
+light('Hue color lamp', living, { ct: true, colour: true, archetype: 'sultan_bulb' });
+light('Hue Play', living, { ct: true, colour: true, archetype: 'hue_play' });
+light('Hue white ambiance', bedroom, { ct: true, archetype: 'pendant_round' });
+light('Hue white lamp', kitchen, { archetype: 'ceiling_round' });
+light('Hue smart plug', living, { dim: false, archetype: 'plug' });
+const sensorDevice = device('Hue motion sensor', 'unknown_archetype');
+const thermometer = add({ id: id(), type: 'temperature', owner: { rid: sensorDevice.id, rtype: 'device' }, enabled: true,
+ temperature: { temperature: 22.4, temperature_valid: true, temperature_report: { changed: new Date().toISOString(), temperature: 22.4 } } });
+sensorDevice.services.push({ rid: thermometer.id, rtype: 'temperature' });
+living.children.push({ rid: sensorDevice.id, rtype: 'device' });
+
+// The event stream.
+const listeners = new Set();
+function emit(type, data) {
+ const event = `id: ${Date.now()}:0\ndata: ${JSON.stringify([{ creationtime: new Date().toISOString(), id: id(), type, data }])}\n\n`;
+ for (const res of listeners) res.write(event);
+}
+setInterval(() => {
+ const t = Math.round((thermometer.temperature.temperature + (Math.random() - 0.5) * 0.4) * 10) / 10;
+ thermometer.temperature.temperature = t;
+ thermometer.temperature.temperature_report = { changed: new Date().toISOString(), temperature: t };
+ emit('update', [{ id: thermometer.id, type: 'temperature', temperature: thermometer.temperature }]);
+}, 30_000);
+
+const json = (res, status, body) => { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(body)); };
+const merge = (target, patch) => {
+ for (const [k, v] of Object.entries(patch)) {
+ if (v && typeof v === 'object' && !Array.isArray(v) && target[k] && typeof target[k] === 'object') merge(target[k], v);
+ else target[k] = v;
+ }
+};
+
+const server = https.createServer({ key: readFileSync(keyFile), cert: readFileSync(certFile) }, (req, res) => {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ const url = new URL(req.url, 'https://bridge');
+ if (req.method === 'POST' && url.pathname === '/api') {
+ if (AUTO) press();
+ if (Date.now() > buttonUntil) return json(res, 200, [{ error: { type: 101, address: '', description: 'link button not pressed' } }]);
+ const username = randomBytes(20).toString('hex');
+ keys.add(username);
+ writeFileSync(keysFile, JSON.stringify([...keys]));
+ console.log(`✓ Paired ${JSON.parse(body || '{}').devicetype || 'an app'}`);
+ return json(res, 200, [{ success: { username, clientkey: randomBytes(16).toString('hex').toUpperCase() } }]);
+ }
+ if (!keys.has(req.headers['hue-application-key'])) return json(res, 403, { errors: [{ description: 'unauthorized user' }], data: [] });
+
+ if (url.pathname === '/eventstream/clip/v2') {
+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive', 'X-Content-Type-Options': 'nosniff' });
+ res.write(': hi\n\n');
+ listeners.add(res);
+ res.on('close', () => listeners.delete(res));
+ return;
+ }
+ const m = url.pathname.match(/^\/clip\/v2\/resource\/([a-z_]+)(?:\/([0-9a-f-]+))?$/);
+ if (!m) return json(res, 404, { errors: [{ description: `unknown resource ${url.pathname}` }], data: [] });
+ const [, type, rid] = m;
+ const list = resources.filter((r) => r.type === type && (!rid || r.id === rid));
+ if (req.method === 'GET') return json(res, rid && !list.length ? 404 : 200, { errors: [], data: list });
+ if (req.method === 'PUT' && rid && list.length) {
+ let patch;
+ try { patch = JSON.parse(body); } catch { return json(res, 400, { errors: [{ description: 'body contains invalid JSON' }], data: [] }); }
+ const target = list[0];
+ if (patch.color_temperature?.mirek != null) { patch.color_temperature.mirek_valid = true; }
+ if (patch.color?.xy && target.color_temperature) { target.color_temperature.mirek = null; target.color_temperature.mirek_valid = false; }
+ if (patch.dimming && !target.dimming) return json(res, 400, { errors: [{ description: 'device (dimming) is not available' }], data: [] });
+ merge(target, patch);
+ console.log(`${new Date().toLocaleTimeString()} ${target.metadata?.name.padEnd(20)} ${JSON.stringify(patch)}`);
+ emit('update', [{ id: target.id, type, ...patch }]);
+ return json(res, 200, { errors: [], data: [{ rid: target.id, rtype: type }] });
+ }
+ json(res, 405, { errors: [{ description: 'method not available' }], data: [] });
+ });
+});
+
+server.listen(PORT, () => {
+ // Announce it the way a bridge does (dns-sd ships with macOS).
+ const announcer = spawn('dns-sd', ['-R', 'Hue Bridge Lab', '_hue._tcp', 'local', String(PORT), `bridgeid=${BRIDGE_ID.toLowerCase()}`, 'modelid=BSB002'], { stdio: 'ignore' });
+ process.on('exit', () => announcer.kill());
+ process.on('SIGINT', () => process.exit(0));
+ console.log(`Hue Bridge Lab is on https://localhost:${PORT} and announced as “Hue Bridge Lab”.`);
+ console.log(AUTO ? 'The link button presses itself for every pairing attempt.' : 'Press Enter to press the link button.');
+});
+process.stdin.on('data', press);
diff --git a/tools/lab/package-lock.json b/tools/lab/package-lock.json
new file mode 100644
index 0000000..b52c0b8
--- /dev/null
+++ b/tools/lab/package-lock.json
@@ -0,0 +1,388 @@
+{
+ "name": "house-control-lab",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "house-control-lab",
+ "dependencies": {
+ "hap-nodejs": "1.2.0"
+ }
+ },
+ "node_modules/@homebridge/ciao": {
+ "version": "1.3.12",
+ "resolved": "https://registry.npmjs.org/@homebridge/ciao/-/ciao-1.3.12.tgz",
+ "integrity": "sha512-84/0u0kqKy4qcKupIDaTtbkmk+3qFDuMzxTC0NPfVlHcUT+jHGdP+QCqwEw94/GJxRezDeBLwxaclkBZgCdeUg==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.3",
+ "fast-deep-equal": "^3.1.3",
+ "source-map-support": "^0.5.21",
+ "tslib": "^2.8.1"
+ },
+ "bin": {
+ "ciao-bcs": "lib/bonjour-conformance-testing.js"
+ }
+ },
+ "node_modules/@homebridge/dbus-native": {
+ "version": "0.7.9",
+ "resolved": "https://registry.npmjs.org/@homebridge/dbus-native/-/dbus-native-0.7.9.tgz",
+ "integrity": "sha512-PFOeWyXfH2eoM4o6Zmj9PzCUDlrrbtrbAJVzHYXpXK5rh/dz84Ygu79WHKK3DWW2/oXieYPV6up+i1izSPbc3g==",
+ "license": "MIT",
+ "dependencies": {
+ "event-stream": "^4.0.1",
+ "hexy": "^0.4.0",
+ "long": "^5.3.2",
+ "minimist": "^1.2.8",
+ "safe-buffer": "^5.2.1",
+ "xml2js": "^0.6.2"
+ },
+ "bin": {
+ "dbus2js": "bin/dbus2js.js"
+ }
+ },
+ "node_modules/@leichtgewicht/ip-codec": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz",
+ "integrity": "sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==",
+ "license": "MIT"
+ },
+ "node_modules/bonjour-hap": {
+ "version": "3.10.5",
+ "resolved": "https://registry.npmjs.org/bonjour-hap/-/bonjour-hap-3.10.5.tgz",
+ "integrity": "sha512-8E81oIQF0pjlDNVAKcAGwPYYG9BKD42Q8Fi7eJ/vYxEwyL/M8YpjM4gnFC1QTmagWI3jzbw7jPI0q2C1qWfQLQ==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.3",
+ "multicast-dns": "^7.2.5",
+ "multicast-dns-service-types": "^1.1.0"
+ }
+ },
+ "node_modules/buffer-from": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
+ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
+ "license": "MIT"
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/dns-packet": {
+ "version": "5.6.1",
+ "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-5.6.1.tgz",
+ "integrity": "sha512-l4gcSouhcgIKRvyy99RNVOgxXiicE+2jZoNmaNmZ6JXiGajBOJAesk1OBlJuM5k2c+eudGdLxDqXuPCKIj6kpw==",
+ "license": "MIT",
+ "dependencies": {
+ "@leichtgewicht/ip-codec": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/duplexer": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.2.tgz",
+ "integrity": "sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg==",
+ "license": "MIT"
+ },
+ "node_modules/event-stream": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/event-stream/-/event-stream-4.0.1.tgz",
+ "integrity": "sha512-qACXdu/9VHPBzcyhdOWR5/IahhGMf0roTeZJfzz077GwylcDd90yOHLouhmv7GJ5XzPi6ekaQWd8AvPP2nOvpA==",
+ "license": "MIT",
+ "dependencies": {
+ "duplexer": "^0.1.1",
+ "from": "^0.1.7",
+ "map-stream": "0.0.7",
+ "pause-stream": "^0.0.11",
+ "split": "^1.0.1",
+ "stream-combiner": "^0.2.2",
+ "through": "^2.3.8"
+ }
+ },
+ "node_modules/fast-deep-equal": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
+ "license": "MIT"
+ },
+ "node_modules/fast-srp-hap": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/fast-srp-hap/-/fast-srp-hap-2.0.4.tgz",
+ "integrity": "sha512-lHRYYaaIbMrhZtsdGTwPN82UbqD9Bv8QfOlKs+Dz6YRnByZifOh93EYmf2iEWFtkOEIqR2IK8cFD0UN5wLIWBQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.17.0"
+ }
+ },
+ "node_modules/from": {
+ "version": "0.1.7",
+ "resolved": "https://registry.npmjs.org/from/-/from-0.1.7.tgz",
+ "integrity": "sha512-twe20eF1OxVxp/ML/kq2p1uc6KvFK/+vs8WjEbeKmV2He22MKm7YF2ANIt+EOqhJ5L3K/SuuPhk0hWQDjOM23g==",
+ "license": "MIT"
+ },
+ "node_modules/futoin-hkdf": {
+ "version": "1.5.3",
+ "resolved": "https://registry.npmjs.org/futoin-hkdf/-/futoin-hkdf-1.5.3.tgz",
+ "integrity": "sha512-SewY5KdMpaoCeh7jachEWFsh1nNlaDjNHZXWqL5IGwtpEYHTgkr2+AMCgNwKWkcc0wpSYrZfR7he4WdmHFtDxQ==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/hap-nodejs": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/hap-nodejs/-/hap-nodejs-1.2.0.tgz",
+ "integrity": "sha512-MusfG+9BJsLbjv7xtF5PDcYmgeYpbtchUhrvTvVBnXPoGMcPePhYt2bo7RphrOskzOpCuSJc8cOMTjJIlHwMNw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@homebridge/ciao": "^1.3.2",
+ "@homebridge/dbus-native": "^0.7.1",
+ "bonjour-hap": "^3.9.0",
+ "debug": "^4.4.1",
+ "fast-srp-hap": "^2.0.4",
+ "futoin-hkdf": "^1.5.3",
+ "node-persist": "^0.0.12",
+ "source-map-support": "^0.5.21",
+ "tslib": "^2.8.1",
+ "tweetnacl": "^1.0.3"
+ },
+ "engines": {
+ "node": "^18 || ^20 || ^22"
+ }
+ },
+ "node_modules/hexy": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/hexy/-/hexy-0.4.0.tgz",
+ "integrity": "sha512-HxJ6HCV/zrSBeAVRNEhr3CE6yTlCYklMHfCVfJkp7kC+HJqSP1SQ+howWPiHK37t++ELUtgoAoGJut5HyRhIvg==",
+ "license": "MIT",
+ "bin": {
+ "hexy": "bin/hexy_cmd.js"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/long": {
+ "version": "5.3.2",
+ "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
+ "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/map-stream": {
+ "version": "0.0.7",
+ "resolved": "https://registry.npmjs.org/map-stream/-/map-stream-0.0.7.tgz",
+ "integrity": "sha512-C0X0KQmGm3N2ftbTGBhSyuydQ+vV1LC3f3zPvT3RXHXNZrvfPZcoXp/N5DOa8vedX/rTMm2CjTtivFg2STJMRQ==",
+ "license": "MIT"
+ },
+ "node_modules/minimist": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/mkdirp": {
+ "version": "0.5.6",
+ "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
+ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
+ "license": "MIT",
+ "dependencies": {
+ "minimist": "^1.2.6"
+ },
+ "bin": {
+ "mkdirp": "bin/cmd.js"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/multicast-dns": {
+ "version": "7.2.5",
+ "resolved": "https://registry.npmjs.org/multicast-dns/-/multicast-dns-7.2.5.tgz",
+ "integrity": "sha512-2eznPJP8z2BFLX50tf0LuODrpINqP1RVIm/CObbTcBRITQgmC/TjcREF1NeTBzIcR5XO/ukWo+YHOjBbFwIupg==",
+ "license": "MIT",
+ "dependencies": {
+ "dns-packet": "^5.2.2",
+ "thunky": "^1.0.2"
+ },
+ "bin": {
+ "multicast-dns": "cli.js"
+ }
+ },
+ "node_modules/multicast-dns-service-types": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/multicast-dns-service-types/-/multicast-dns-service-types-1.1.0.tgz",
+ "integrity": "sha512-cnAsSVxIDsYt0v7HmC0hWZFwwXSh+E6PgCrREDuN/EsjgLwA5XRmlMHhSiDPrt6HxY1gTivEa/Zh7GtODoLevQ==",
+ "license": "MIT"
+ },
+ "node_modules/node-persist": {
+ "version": "0.0.12",
+ "resolved": "https://registry.npmjs.org/node-persist/-/node-persist-0.0.12.tgz",
+ "integrity": "sha512-Fbia3FYnURzaql53wLu0t19dmAwQg/tXT6O7YPmdwNwysNKEyFmgoT2BQlPD3XXQnYeiQVNvR5lfvufGwKuxhg==",
+ "license": "MIT",
+ "dependencies": {
+ "mkdirp": "~0.5.1",
+ "q": "~1.1.1"
+ }
+ },
+ "node_modules/pause-stream": {
+ "version": "0.0.11",
+ "resolved": "https://registry.npmjs.org/pause-stream/-/pause-stream-0.0.11.tgz",
+ "integrity": "sha512-e3FBlXLmN/D1S+zHzanP4E/4Z60oFAa3O051qt1pxa7DEJWKAyil6upYVXCWadEnuoqa4Pkc9oUx9zsxYeRv8A==",
+ "license": [
+ "MIT",
+ "Apache2"
+ ],
+ "dependencies": {
+ "through": "~2.3"
+ }
+ },
+ "node_modules/q": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/q/-/q-1.1.2.tgz",
+ "integrity": "sha512-ROtylwux7Vkc4C07oKE/ReigUmb33kVoLtcR4SJ1QVqwaZkBEDL3vX4/kwFzIERQ5PfCl0XafbU8u2YUhyGgVA==",
+ "deprecated": "You or someone you depend on is using Q, the JavaScript Promise library that gave JavaScript developers strong feelings about promises. They can almost certainly migrate to the native JavaScript promise now. Thank you literally everyone for joining me in this bet against the odds. Be excellent to each other.\n\n(For a CapTP with native promises, see @endo/eventual-send and @endo/captp)",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.6.0",
+ "teleport": ">=0.2.0"
+ }
+ },
+ "node_modules/safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/sax": {
+ "version": "1.6.1",
+ "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
+ "integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": ">=11.0.0"
+ }
+ },
+ "node_modules/source-map": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/source-map-support": {
+ "version": "0.5.21",
+ "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
+ "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",
+ "license": "MIT",
+ "dependencies": {
+ "buffer-from": "^1.0.0",
+ "source-map": "^0.6.0"
+ }
+ },
+ "node_modules/split": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/split/-/split-1.0.1.tgz",
+ "integrity": "sha512-mTyOoPbrivtXnwnIxZRFYRrPNtEFKlpB2fvjSnCQUiAA6qAZzqwna5envK4uk6OIeP17CsdF3rSBGYVBsU0Tkg==",
+ "license": "MIT",
+ "dependencies": {
+ "through": "2"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/stream-combiner": {
+ "version": "0.2.2",
+ "resolved": "https://registry.npmjs.org/stream-combiner/-/stream-combiner-0.2.2.tgz",
+ "integrity": "sha512-6yHMqgLYDzQDcAkL+tjJDC5nSNuNIx0vZtRZeiPh7Saef7VHX9H5Ijn9l2VIol2zaNYlYEX6KyuT/237A58qEQ==",
+ "license": "MIT",
+ "dependencies": {
+ "duplexer": "~0.1.1",
+ "through": "~2.3.4"
+ }
+ },
+ "node_modules/through": {
+ "version": "2.3.8",
+ "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz",
+ "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==",
+ "license": "MIT"
+ },
+ "node_modules/thunky": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz",
+ "integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA==",
+ "license": "MIT"
+ },
+ "node_modules/tslib": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+ "license": "0BSD"
+ },
+ "node_modules/tweetnacl": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
+ "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",
+ "license": "Unlicense"
+ },
+ "node_modules/xml2js": {
+ "version": "0.6.2",
+ "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz",
+ "integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==",
+ "license": "MIT",
+ "dependencies": {
+ "sax": ">=0.6.0",
+ "xmlbuilder": "~11.0.0"
+ },
+ "engines": {
+ "node": ">=4.0.0"
+ }
+ },
+ "node_modules/xmlbuilder": {
+ "version": "11.0.1",
+ "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz",
+ "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4.0"
+ }
+ }
+ }
+}
diff --git a/tools/lab/package.json b/tools/lab/package.json
new file mode 100644
index 0000000..c0683ad
--- /dev/null
+++ b/tools/lab/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "house-control-lab",
+ "private": true,
+ "description": "Pretend smart homes for testing House Control without hardware",
+ "type": "module",
+ "scripts": {
+ "homekit": "node homekit.mjs",
+ "hue": "node hue.mjs"
+ },
+ "dependencies": {
+ "hap-nodejs": "1.2.0"
+ }
+}
diff --git a/web/src/agent/plan-edit.js b/web/src/agent/plan-edit.js
index 7eb3dd8..283f661 100644
--- a/web/src/agent/plan-edit.js
+++ b/web/src/agent/plan-edit.js
@@ -1,6 +1,6 @@
// Edits to the floor plan an AI asks for: small, checked operations on the plan as it is
// written on disk. Nothing here touches the page, so it runs (and is tested) under Node too.
-import { normalize, LIGHT_KINDS, FLOOR_KINDS } from '../config.js';
+import { normalize, LIGHT_KINDS, FLOOR_KINDS, LINK_FIELDS, isLinked } from '../config.js';
import { FURNITURE_TYPES, footprint } from '../three/furniture.js';
export const SCENE_ICONS = ['sun', 'sofa', 'film', 'moon', 'door', 'bed', 'tv', 'sparkles'];
@@ -22,7 +22,10 @@ export function redactPlan(raw) {
const plan = structuredClone(raw);
for (const list of [plan.lights || [], plan.acs || []]) {
for (const d of list) {
- if (d.tuya) { delete d.tuya; d.linked = true; }
+ if (LINK_FIELDS.some((k) => d[k])) {
+ for (const k of LINK_FIELDS) delete d[k];
+ d.linked = true;
+ }
}
}
return plan;
@@ -31,11 +34,11 @@ export function redactPlan(raw) {
/** Puts the hardware links of `old` back into a plan an AI wrote from a redacted copy. */
export function restoreLinks(plan, old) {
for (const key of ['lights', 'acs']) {
- const links = new Map((old[key] || []).filter((d) => d.tuya).map((d) => [d.id, d.tuya]));
+ const links = new Map((old[key] || []).map((d) => [d.id, pick(d, LINK_FIELDS)]));
for (const d of plan[key] || []) {
delete d.linked;
- delete d.tuya; // an AI cannot invent links to devices; they are made in the editor
- if (links.has(d.id)) d.tuya = links.get(d.id);
+ for (const k of LINK_FIELDS) delete d[k]; // an AI cannot invent links to devices; they are made in the editor
+ Object.assign(d, links.get(d.id) || {});
}
}
return plan;
@@ -149,7 +152,7 @@ export function applyOperations(raw, operations) {
case 'remove_room': {
const i = findById(plan.rooms, op.id, 'room');
const devices = [...plan.lights, ...plan.acs].filter((d) => d.room === op.id);
- if (devices.some((d) => d.tuya)) fail(`${where}: this room has devices linked to real hardware; unlink them in the editor first`);
+ if (devices.some(isLinked)) fail(`${where}: this room has devices linked to real hardware; unlink them in the editor first`);
const room = plan.rooms[i];
plan.furniture.forEach((f, k) => { if (k < originalFurniture && roomAt({ rooms: [room] }, f.pos)) dropFurniture.add(k); });
plan.lights = plan.lights.filter((d) => d.room !== op.id);
@@ -223,7 +226,7 @@ export function applyOperations(raw, operations) {
const list = isLight ? plan.lights : plan.acs;
const i = findById(list, op.id, isLight ? 'light' : 'AC');
const set = pick(op.set, (isLight ? LIGHT_KEYS : AC_KEYS).filter((k) => k !== 'id'));
- if (op.set?.tuya || op.set?.linked != null) fail(`${where}: links to real devices are made in the editor, not here`);
+ if (LINK_FIELDS.some((k) => op.set?.[k]) || op.set?.linked != null) fail(`${where}: links to real devices are made in the editor, not here`);
Object.assign(list[i], set);
changes.push(`changed ${list[i].name || list[i].id}`);
break;
@@ -233,7 +236,7 @@ export function applyOperations(raw, operations) {
const isLight = op.op === 'remove_light';
const list = isLight ? plan.lights : plan.acs;
const i = findById(list, op.id, isLight ? 'light' : 'AC');
- if (list[i].tuya) fail(`${where}: "${list[i].name}" is a real device; unlink it in the editor before removing it`);
+ if (isLinked(list[i])) fail(`${where}: "${list[i].name}" is a real device; unlink it in the editor before removing it`);
const [gone] = list.splice(i, 1);
for (const s of plan.scenes) delete s[isLight ? 'lights' : 'acs']?.[gone.id];
changes.push(`removed ${gone.name || gone.id}`);
@@ -301,7 +304,7 @@ export function replacePlan(old, next) {
const plan = restoreLinks(structuredClone(next), old);
plan.furniture = (plan.furniture || []).map((f, i) => cleanFurniture(f, `Furniture #${i}`));
if (old.version != null && plan.version == null) plan.version = old.version;
- const lost = [...(old.lights || []), ...(old.acs || [])].filter((d) => d.tuya
+ const lost = [...(old.lights || []), ...(old.acs || [])].filter((d) => isLinked(d)
&& ![...(plan.lights || []), ...(plan.acs || [])].some((n) => n.id === d.id));
if (lost.length) {
fail(`The new plan drops devices linked to real hardware: ${lost.map((d) => `${d.name} (${d.id})`).join(', ')}. Keep them, with the same ids.`);
diff --git a/web/src/agent/tools.js b/web/src/agent/tools.js
index 55337fc..bb7b728 100644
--- a/web/src/agent/tools.js
+++ b/web/src/agent/tools.js
@@ -4,7 +4,7 @@
// shell only carries requests here (see AgentGateway.swift).
import { AC_MODES, AC_FANS } from '../store.js';
import { applyOperations, replacePlan, redactPlan, furnitureCatalog, PlanEditError, SCENE_ICONS, WALLS } from './plan-edit.js';
-import { LIGHT_KINDS, FLOOR_KINDS } from '../config.js';
+import { LIGHT_KINDS, FLOOR_KINDS, isLinked } from '../config.js';
export const COLORS = {
red: '#ff3b30', orange: '#ff9500', yellow: '#ffd60a', green: '#34c759',
@@ -48,11 +48,11 @@ export function createAgent({ store, config, raw, render, onAction }) {
const lightJSON = (cfg) => ({
id: cfg.id, name: cfg.name, room: cfg.room, type: cfg.type, abilities: cfg.capabilities,
- real: Boolean(cfg.tuya?.deviceId), ...state.lights[cfg.id],
+ real: isLinked(cfg), ...state.lights[cfg.id],
brightness: Math.round(state.lights[cfg.id].brightness * 100),
});
const acJSON = (cfg) => ({
- id: cfg.id, name: cfg.name, room: cfg.room, real: Boolean(cfg.tuya?.deviceId),
+ id: cfg.id, name: cfg.name, room: cfg.room, real: isLinked(cfg),
min: cfg.min, max: cfg.max, modes: store.acFeatures(cfg.id).modes, fans: store.acFeatures(cfg.id).fans,
on: state.acs[cfg.id].on, target: state.acs[cfg.id].target, mode: state.acs[cfg.id].mode,
fan: state.acs[cfg.id].fan, roomTemp: state.acs[cfg.id].roomTemp,
diff --git a/web/src/config.js b/web/src/config.js
index c5fbf3c..377a9e0 100644
--- a/web/src/config.js
+++ b/web/src/config.js
@@ -7,6 +7,27 @@ const WALLS = ['north', 'south', 'east', 'west'];
export class ConfigError extends Error {}
export const LIGHT_KINDS = LIGHT_TYPES;
+
+// A lamp or an AC is real when it is linked to a device of a connected platform:
+// `link: { service, id }` (Home Assistant, Philips Hue, Apple Home) or, for Smart Life,
+// `tuya: { deviceId }`. An AC's `sensor: { service, id }` is a thermometer for its room.
+export const LINK_FIELDS = ['tuya', 'link', 'sensor'];
+
+export function linkOf(d) {
+ if (d?.link?.service && d.link.id) return { service: d.link.service, id: d.link.id };
+ if (d?.tuya?.deviceId) return { service: 'smartlife', id: d.tuya.deviceId };
+ return null;
+}
+
+export const isLinked = (d) => Boolean(linkOf(d));
+
+/** The platforms House Control can link to, in the order the editor lists them. */
+export const SERVICES = {
+ smartlife: { name: 'Smart Life', short: 'Smart Life' },
+ homeassistant: { name: 'Home Assistant', short: 'Home Assistant' },
+ hue: { name: 'Philips Hue', short: 'Hue' },
+ homekit: { name: 'Apple Home', short: 'Apple Home' },
+};
export const FLOOR_KINDS = ['oak', 'walnut', 'tile', 'stone'];
// The plan exactly as written on disk (the editor works on this form).
diff --git a/web/src/editor/connections.js b/web/src/editor/connections.js
new file mode 100644
index 0000000..7e1b8bd
--- /dev/null
+++ b/web/src/editor/connections.js
@@ -0,0 +1,411 @@
+// The editor's "Connections": the smart home platforms House Control can link the plan's
+// lamps and ACs to (Smart Life, Home Assistant, Philips Hue, Apple Home), the screens that
+// connect each one, and the pickers that link a lamp or an AC to one of their devices.
+import { h } from '../ui/dom.js';
+import { icon } from '../ui/icons.js';
+import { isNative, call } from '../bridge.js';
+import { SERVICES, linkOf } from '../config.js';
+
+const ORDER = ['smartlife', 'homeassistant', 'hue', 'homekit'];
+const LOOK = {
+ smartlife: { icon: 'plug', tint: '#ff7a3d', blurb: 'Tuya, Smart Life and the many brands built on them' },
+ homeassistant: { icon: 'homeassistant', tint: '#18bcf2', blurb: 'Everything it runs: Zigbee, Matter, Nest, Xiaomi, Sonoff…' },
+ hue: { icon: 'bulb', tint: '#c38bff', blurb: 'A Hue Bridge on this network. No account needed' },
+ homekit: { icon: 'home', tint: '#ffb340', blurb: 'HomeKit and Matter accessories, through your iPhone' },
+};
+const KIND_TITLES = { light: 'Lights and plugs', ac: 'Air conditioners', sensor: 'Temperature sensors' };
+
+export function createConnections({ rerender, toast, usedBy, onOpen }) {
+ const boot = window.__HOUSE_BOOT__ || {};
+ const state = {
+ info: boot.services || {},
+ devices: null,
+ errors: {},
+ loading: false,
+ found: {}, // service -> discovered servers / bridges
+ scanning: {},
+ pairing: null, // { host, until } while waiting for the Hue button
+ };
+
+ const connected = (id) => Boolean(state.info[id]?.connected);
+ const anyConnected = () => ORDER.some(connected);
+ const devicesOf = (id) => (state.devices || []).filter((d) => d.service === id);
+
+ async function refreshInfo() {
+ if (!isNative) return;
+ try { state.info = await call('services.info'); } catch { /* keep what we had */ }
+ }
+
+ async function load({ quiet = false } = {}) {
+ if (!isNative || !anyConnected()) { state.devices = null; rerender(); return; }
+ state.loading = true;
+ if (!quiet) rerender();
+ try {
+ const r = await call('devices.all');
+ state.devices = r.devices;
+ state.errors = r.errors || {};
+ } catch (e) {
+ state.errors = { all: e.message };
+ }
+ state.loading = false;
+ rerender();
+ }
+
+ // The Mac pushes this when the paired iPhone sent its Apple Home devices.
+ window.house = window.house || {};
+ window.house.servicesChanged = (info) => { state.info = info; load({ quiet: true }); };
+
+ /* ---------- sidebar ---------- */
+
+ function sidebarRow(active, select) {
+ const n = ORDER.filter(connected).length;
+ return h(`button.row.tuya-row${active ? '.active' : ''}`, { onclick: select },
+ icon('link', 15), h('span.row-name', 'Connections'),
+ h(`span.pill${n ? '.on' : ''}`, n ? `${n} connected` : 'Demo mode'));
+ }
+
+ /* ---------- overview ---------- */
+
+ function tile(id, size = 34) {
+ return h('span.svc-tile', { vars: { '--tint': LOOK[id].tint, '--size': `${size}px` } }, icon(LOOK[id].icon, Math.round(size * 0.52), 2));
+ }
+
+ function statusText(id) {
+ const info = state.info[id] || {};
+ if (id === 'homekit' && info.remote) {
+ return info.connected ? `${info.count} devices from ${info.from || 'your iPhone'}` : 'Set up on your iPhone';
+ }
+ if (!info.connected) return 'Not connected';
+ const count = devicesOf(id).length;
+ const name = id === 'homeassistant' ? info.name : id === 'hue' ? info.name : id === 'smartlife' ? info.account : '';
+ return [name, state.devices ? `${count} device${count === 1 ? '' : 's'}` : null].filter(Boolean).join(' · ') || 'Connected';
+ }
+
+ function overview() {
+ if (anyConnected() && !state.devices && !state.loading) setTimeout(() => load(), 0);
+ return [
+ h('div.svc-cards', ORDER.map((id) => h('button.svc-card', { onclick: () => onOpen(id) },
+ tile(id),
+ h('div.svc-text', h('b', SERVICES[id].name), h('span', LOOK[id].blurb)),
+ h(`span.svc-status${connected(id) ? '.on' : ''}`, connected(id) ? icon('ok', 13, 2.4) : null, statusText(id)),
+ icon('next', 16)))),
+ h('p.note', 'Lamps and ACs stay simulated until you link them: pick one on the plan, then choose its device under “Real device”. One home can mix all four.'),
+ isNative ? null : h('p.note.bad', 'Connecting is only available inside the macOS app (this is the browser preview).'),
+ ];
+ }
+
+ /* ---------- shared pieces ---------- */
+
+ const section = (title, ...nodes) => h('section.block', h('h3', title), nodes);
+
+ function deviceList(id) {
+ if (state.loading) return h('p.note.busy', icon('spinner', 13), 'Asking for the devices…');
+ if (state.errors[id]) return h('p.note.bad', state.errors[id]);
+ const list = devicesOf(id);
+ if (!state.devices) return null;
+ if (!list.length) return h('p.note', 'Connected, but no lamps, air conditioners or temperature sensors were found.');
+ const used = usedBy();
+ const groups = ['light', 'ac', 'sensor'].map((kind) => [kind, list.filter((d) => d.kind === kind)]).filter(([, l]) => l.length);
+ return h('div.devices-list', groups.map(([kind, items]) => [
+ h('h3', `${KIND_TITLES[kind]} · ${items.length}`),
+ items.map((d) => h('div.device',
+ h(`span.dot${d.online ? '.on' : ''}`, { title: d.online ? 'Online' : 'Offline' }),
+ h('div', h('b', d.name), h('span', [d.room, d.detail].filter(Boolean).join(' · ') || d.id)),
+ used.get(`${d.service}|${d.id}`) ? h('span.pill.on', used.get(`${d.service}|${d.id}`)) : null)),
+ ]));
+ }
+
+ function connectedHeader(id, title, name, line) {
+ return section(title,
+ h('div.device', h('span.dot.on'), h('div', h('b', name), h('span', line))),
+ h('div.fields',
+ h('button.btn', { onclick: () => load() }, 'Refresh devices'),
+ h('button.btn', { onclick: () => disconnect(id) }, 'Disconnect')));
+ }
+
+ async function disconnect(id) {
+ try {
+ state.info = await call('service.disconnect', { service: id });
+ state.devices = state.devices?.filter((d) => d.service !== id) ?? null;
+ toast(`${SERVICES[id].name} disconnected`);
+ } catch (e) { toast(e.message, true); }
+ rerender();
+ }
+
+ async function scan(id) {
+ if (!isNative || state.scanning[id]) return;
+ state.scanning[id] = true;
+ rerender();
+ try {
+ state.found[id] = (await call('services.discover', { service: id })).found;
+ } catch { state.found[id] = []; }
+ state.scanning[id] = false;
+ rerender();
+ }
+
+ /* ---------- Home Assistant ---------- */
+
+ const ha = { url: '', token: '', error: null, busy: false };
+
+ function homeAssistant() {
+ const info = state.info.homeassistant || {};
+ if (info.connected) {
+ if (!state.devices && !state.loading) setTimeout(() => load(), 0);
+ return [connectedHeader('homeassistant', 'Server', info.name, [info.url, info.version && `version ${info.version}`].filter(Boolean).join(' · ')),
+ deviceList('homeassistant')];
+ }
+ if (!state.found.homeassistant && !state.scanning.homeassistant) setTimeout(() => scan('homeassistant'), 0);
+ const url = h('input', { type: 'url', spellcheck: 'false', placeholder: 'http://homeassistant.local:8123', value: ha.url });
+ const token = h('input', { type: 'password', autocomplete: 'off', placeholder: 'Long-lived access token', value: ha.token });
+ const ready = () => isNative && !ha.busy && ha.url.trim() && ha.token.trim();
+ url.addEventListener('input', () => { ha.url = url.value; button.disabled = !ready(); });
+ token.addEventListener('input', () => { ha.token = token.value; button.disabled = !ready(); });
+ const connect = async () => {
+ ha.busy = true; ha.error = null; rerender();
+ try {
+ state.info = await call('homeassistant.connect', { url: ha.url, token: ha.token });
+ ha.token = '';
+ toast(`Connected to ${state.info.homeassistant?.name || 'Home Assistant'}`);
+ await load();
+ } catch (e) { ha.error = e.message; }
+ ha.busy = false;
+ rerender();
+ };
+ const button = h('button.btn.primary.wide', { onclick: connect, disabled: !ready() }, ha.busy ? 'Connecting…' : 'Connect');
+ const found = state.found.homeassistant || [];
+ return [
+ section('On your network',
+ state.scanning.homeassistant ? h('p.note.busy', icon('spinner', 13), 'Looking for Home Assistant…')
+ : found.length ? found.map((s) => h('div.device',
+ h('span.dot.on'), h('div', h('b', s.name), h('span', [s.url, s.version && `version ${s.version}`].filter(Boolean).join(' · '))),
+ h('button.btn', { onclick: () => { ha.url = s.url; rerender(); } }, ha.url === s.url ? 'Selected' : 'Use')))
+ : h('p.note', 'None found by itself. Type its address below.'),
+ state.scanning.homeassistant ? null : h('button.btn.link', { onclick: () => scan('homeassistant') }, icon('radar', 13), 'Look again')),
+ section('Connect',
+ h('label.field', h('span', 'Address'), url),
+ h('label.field', h('span', 'Access token'), token),
+ h('ol.steps',
+ h('li', 'In Home Assistant, open your profile (your name at the bottom left) → Security.'),
+ h('li', 'Under “Long-lived access tokens” press Create token, name it “House Control”, copy it here.')),
+ button,
+ ha.error ? h('p.note.bad', ha.error) : null,
+ h('p.note', 'The token stays on this Mac (and goes to the iPhones you paired, over their encrypted link). Lights, switches, climate devices and temperature sensors appear here.')),
+ ];
+ }
+
+ /* ---------- Philips Hue ---------- */
+
+ let pairTimer = 0;
+ function stopPairing() { clearInterval(pairTimer); pairTimer = 0; state.pairing = null; }
+
+ function pairHue(bridge) {
+ stopPairing();
+ state.pairing = { ...bridge, until: Date.now() + 60_000, error: null };
+ const attempt = async () => {
+ if (!state.pairing) return;
+ if (Date.now() > state.pairing.until) {
+ state.pairing.error = 'Nobody pressed the button in time. Try again.';
+ clearInterval(pairTimer);
+ rerender();
+ return;
+ }
+ try {
+ const r = await call('hue.pair', { host: bridge.host, bridgeId: bridge.bridgeId, name: bridge.name });
+ if (r.waiting) { rerender(); return; }
+ stopPairing();
+ state.info = r;
+ toast(`Paired with ${state.info.hue?.name || 'the Hue Bridge'}`);
+ await load();
+ } catch (e) {
+ if (state.pairing) state.pairing.error = e.message;
+ clearInterval(pairTimer);
+ }
+ rerender();
+ };
+ attempt();
+ pairTimer = setInterval(attempt, 2000);
+ rerender();
+ }
+
+ const hueManual = { host: '' };
+
+ function hue() {
+ const info = state.info.hue || {};
+ if (info.connected) {
+ if (!state.devices && !state.loading) setTimeout(() => load(), 0);
+ return [connectedHeader('hue', 'Bridge', info.name, [info.host, info.bridgeId].filter(Boolean).join(' · ')),
+ deviceList('hue')];
+ }
+ if (state.pairing) {
+ const left = Math.max(0, Math.ceil((state.pairing.until - Date.now()) / 1000));
+ return [section('Pairing',
+ h('div.press',
+ h('div.press-button', h('span')),
+ h('div', h('b', 'Press the round button on the bridge'), h('span', state.pairing.error || `${state.pairing.name || state.pairing.host} · waiting ${left} s`))),
+ h('div.fields',
+ state.pairing.error ? h('button.btn', { onclick: () => pairHue(state.pairing) }, 'Try again') : null,
+ h('button.btn', { onclick: () => { stopPairing(); rerender(); } }, 'Cancel')),
+ h('p.note', 'The big button on top of the Hue Bridge lets one app in for 30 seconds. House Control keeps the key it gets, on this Mac.'))];
+ }
+ if (!state.found.hue && !state.scanning.hue) setTimeout(() => scan('hue'), 0);
+ const found = state.found.hue || [];
+ const host = h('input', { type: 'text', spellcheck: 'false', placeholder: 'e.g. 192.168.1.20', value: hueManual.host });
+ const pairButton = h('button.btn.wide', { onclick: () => pairHue({ host: hueManual.host.trim(), name: 'Hue Bridge' }), disabled: !isNative || !hueManual.host.trim() }, 'Pair');
+ host.addEventListener('input', () => { hueManual.host = host.value; pairButton.disabled = !isNative || !host.value.trim(); });
+ return [
+ section('On your network',
+ state.scanning.hue ? h('p.note.busy', icon('spinner', 13), 'Looking for Hue Bridges…')
+ : found.length ? found.map((b) => h('div.device',
+ h('span.dot.on'), h('div', h('b', b.name), h('span', [b.host, b.bridgeId].filter(Boolean).join(' · '))),
+ h('button.btn.primary', { onclick: () => pairHue(b), disabled: !isNative }, 'Pair')))
+ : h('p.note', 'No bridge found by itself. Type its address below (the Hue app shows it under Settings → My Hue system).'),
+ state.scanning.hue ? null : h('button.btn.link', { onclick: () => scan('hue') }, icon('radar', 13), 'Look again')),
+ section('Or by address',
+ h('label.field', h('span', 'Bridge address'), host),
+ pairButton),
+ ];
+ }
+
+ /* ---------- Apple Home ---------- */
+
+ function homeKit() {
+ const info = state.info.homekit || {};
+ const nodes = [];
+ if (info.connected) {
+ if (!state.devices && !state.loading) setTimeout(() => load(), 0);
+ const when = info.updated ? new Date(info.updated * 1000).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) : '';
+ nodes.push(section('From your iPhone',
+ h('div.device', h('span.dot.on'), h('div', h('b', info.from || 'iPhone'), h('span', `${info.count} devices · sent ${when}`))),
+ h('div.fields', h('button.btn', { onclick: () => disconnect('homekit') }, 'Forget this list'))),
+ deviceList('homekit'));
+ }
+ nodes.push(section(info.connected ? 'How it works' : 'Set it up on your iPhone',
+ h('ol.steps',
+ h('li', 'Pair your iPhone with this Mac: right-click the menu bar icon → Pair iPhone….'),
+ h('li', 'On the iPhone: House Control → Settings → Apple Home → Connect, and allow access to your Home data.'),
+ h('li', 'Its lamps, air conditioners and thermometers appear here. Link them like any other device.')),
+ h('p.note', 'Apple lets only iPhone, iPad and App Store apps use HomeKit, so the iPhone app switches these devices. On the Mac they show what you set, but stay simulated.')));
+ return nodes;
+ }
+
+ /* ---------- detail screen ---------- */
+
+ function detail(id, smartLifePanel) {
+ if (id === 'smartlife') return smartLifePanel();
+ if (id === 'homeassistant') return homeAssistant();
+ if (id === 'hue') return hue();
+ return homeKit();
+ }
+
+ /* ---------- linking a lamp or an AC ---------- */
+
+ function optionLabel(d) {
+ return `${d.name}${d.room ? ` — ${d.room}` : ''}${d.online ? '' : ' (offline)'}`;
+ }
+
+ function picker(kind, current, include = () => true) {
+ const select = h('select');
+ select.append(h('option', { value: '' }, kind === 'sensor' ? 'None — estimated' : 'Not linked — simulated'));
+ let found = false;
+ for (const id of ORDER) {
+ const list = devicesOf(id).filter((d) => d.kind === kind && include(d));
+ if (!list.length) continue;
+ select.append(h('optgroup', { label: SERVICES[id].name }, list.map((d) => {
+ const value = `${d.service}|${d.id}`;
+ if (value === current) found = true;
+ return h('option', { value }, optionLabel(d));
+ })));
+ }
+ if (current && !found) {
+ const [service, id] = current.split('|');
+ select.append(h('option', { value: current }, `${SERVICES[service]?.short || service}: ${id} (not found now)`));
+ }
+ select.value = current;
+ return select;
+ }
+
+ const find = (value) => (state.devices || []).find((d) => `${d.service}|${d.id}` === value);
+
+ /** The "Real device" section of a lamp or an AC. `onLinked(device)` adapts the item. */
+ function deviceSection(item, kind, { snapshot, changed }) {
+ const link = linkOf(item);
+ const current = link ? `${link.service}|${link.id}` : '';
+ if (!anyConnected()) {
+ return section('Real device',
+ h('p.note', 'Simulated. Connect Smart Life, Home Assistant, Philips Hue or Apple Home to control the real one.'),
+ h('button.btn.wide', { onclick: () => onOpen(null) }, icon('link', 14), 'Open Connections'));
+ }
+ if (!state.devices && !state.loading) setTimeout(() => load({ quiet: true }), 0);
+ const select = picker(kind, current);
+ select.addEventListener('change', () => {
+ snapshot();
+ const value = select.value;
+ delete item.link;
+ if (item.tuya) { delete item.tuya.deviceId; if (!Object.keys(item.tuya).length) delete item.tuya; }
+ const device = find(value);
+ if (value) {
+ const [service, id] = value.split('|');
+ if (service === 'smartlife') item.tuya = { ...(item.tuya || {}), deviceId: id };
+ else item.link = { service, id };
+ // Smart Life sensors only work beside a Smart Life AC.
+ if (service !== 'smartlife' && item.tuya) delete item.tuya;
+ }
+ let note = null;
+ if (device && kind === 'light' && device.capabilities) {
+ item.capabilities = [...device.capabilities];
+ note = device.capabilities.length ? `Matched what it can do: ${device.capabilities.join(', ').replace('temp', 'white temperature').replace('color', 'colour')}` : 'Matched: an on/off switch';
+ }
+ if (device && kind === 'ac' && device.min != null) { item.min = Math.round(device.min); item.max = Math.round(device.max); }
+ changed(note);
+ });
+ const device = find(current);
+ const info = device ? [SERVICES[device.service].name, device.detail, device.room].filter(Boolean).join(' · ')
+ : current && state.devices ? 'This device was not found in its platform right now.'
+ : state.loading ? 'Loading your devices…' : '';
+ const offline = device && !device.online;
+ return section('Real device',
+ h('label.field', h('span', 'Device'), select),
+ info ? h(`p.note${offline ? '.bad' : ''}`, offline ? `${info} · offline` : info) : null,
+ device?.service === 'homekit' && state.info.homekit?.remote ? h('p.note', 'Switched from your iPhone; simulated on this Mac.') : null,
+ Object.keys(state.errors).length ? h('p.note.bad', Object.entries(state.errors).map(([s, e]) => `${SERVICES[s]?.name || s}: ${e}`).join(' · ')) : null);
+ }
+
+ /** An AC's thermometer: any platform's sensor (a Smart Life one only beside a Smart Life AC). */
+ function sensorSection(item, { snapshot, changed }) {
+ const link = linkOf(item);
+ const current = item.sensor?.id ? `${item.sensor.service}|${item.sensor.id}`
+ : item.tuya?.sensorId ? `smartlife|${item.tuya.sensorId}` : '';
+ const select = picker('sensor', current, (d) => d.service !== 'smartlife' || link?.service === 'smartlife');
+ select.addEventListener('change', () => {
+ snapshot();
+ delete item.sensor;
+ if (item.tuya) delete item.tuya.sensorId;
+ const [service, id] = select.value ? select.value.split('|') : [];
+ if (service === 'smartlife') item.tuya = { ...(item.tuya || {}), sensorId: id };
+ else if (service) item.sensor = { service, id };
+ changed();
+ });
+ return section('Room temperature',
+ h('label.field', h('span', 'Thermometer'), select),
+ h('p.note', 'A temperature sensor in the same room. Without one, the AC’s own reading is used, or the temperature is estimated.'));
+ }
+
+ /** "id → plan item name" for every device the plan links, to mark them in the lists. */
+ function usedMap(doc) {
+ const out = new Map();
+ for (const d of [...doc.lights, ...doc.acs]) {
+ const l = linkOf(d);
+ if (l) out.set(`${l.service}|${l.id}`, d.name || d.id);
+ if (d.sensor?.id) out.set(`${d.sensor.service}|${d.sensor.id}`, `${d.name || d.id} · room`);
+ if (d.tuya?.sensorId) out.set(`smartlife|${d.tuya.sensorId}`, `${d.name || d.id} · room`);
+ }
+ return out;
+ }
+
+ return {
+ state, load, refreshInfo, sidebarRow, overview, detail, tile, deviceSection, sensorSection, usedMap,
+ connected, stopPairing,
+ title: (id) => SERVICES[id]?.name,
+ blurb: (id) => LOOK[id]?.blurb,
+ };
+}
diff --git a/web/src/editor/editor.css b/web/src/editor/editor.css
index 4f185a2..3e228c5 100644
--- a/web/src/editor/editor.css
+++ b/web/src/editor/editor.css
@@ -81,7 +81,7 @@ html.mode-editor, html.mode-editor body { user-select: none; }
.row .del:hover { background: rgba(255, 90, 80, 0.3); color: #fff; }
.home-row, .tuya-row { height: 36px; font-weight: 600; }
.tuya-row { margin-top: 4px; }
-.pill { flex: none; padding: 2px 8px; border-radius: 999px; font-size: 10.5px; font-weight: 700; color: var(--muted); background: rgba(255, 255, 255, 0.08); white-space: nowrap; }
+.pill { flex: none; display: inline-flex; align-items: center; height: 19px; padding: 0 8px; border-radius: 999px; font-size: 10.5px; font-weight: 700; color: var(--muted); background: rgba(255, 255, 255, 0.08); white-space: nowrap; }
.pill.on { color: #0b2a17; background: #6ee7a0; }
/* ---------- plan ---------- */
@@ -198,3 +198,70 @@ html.mode-editor, html.mode-editor body { user-select: none; }
.advanced { margin-top: 22px; padding-top: 14px; border-top: 1px solid var(--line); }
.advanced summary { cursor: pointer; font-size: 12px; font-weight: 600; color: var(--muted); margin-bottom: 8px; }
.advanced summary:hover { color: var(--text); }
+
+/* ---------- connections ---------- */
+
+.svc-tile {
+ flex: none; width: var(--size, 34px); height: var(--size, 34px); border-radius: calc(var(--size, 34px) * 0.3);
+ display: grid; place-items: center; color: #fff;
+ background:
+ radial-gradient(120% 120% at 20% 10%, rgba(255, 255, 255, 0.35), transparent 55%),
+ var(--tint);
+ box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.18), 0 6px 16px -6px var(--tint);
+}
+.svc-cards { display: grid; gap: 8px; margin-top: 16px; }
+.svc-card {
+ display: grid; grid-template-columns: auto 1fr auto; grid-template-rows: auto auto; column-gap: 12px; align-items: center;
+ width: 100%; padding: 12px; border-radius: 14px; text-align: left; color: var(--text); cursor: pointer;
+ background: var(--glass); border: 1px solid var(--line);
+ transition: background 160ms, border-color 160ms, transform 220ms var(--spring);
+}
+.svc-card:hover { background: var(--glass-hi); border-color: rgba(255, 255, 255, 0.16); }
+.svc-card:active { transform: scale(0.985); }
+.svc-card .svc-tile { grid-row: 1 / 3; }
+.svc-card > .icon { grid-row: 1 / 3; grid-column: 3; color: var(--faint); }
+.svc-text { min-width: 0; }
+.svc-text b { display: block; font-size: 13.5px; font-weight: 650; }
+.svc-text span { display: block; margin-top: 1px; font-size: 11.5px; line-height: 1.35; color: var(--faint); }
+.svc-status {
+ grid-column: 2; display: flex; align-items: center; gap: 5px; margin-top: 7px;
+ font-size: 11px; font-weight: 650; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+}
+.svc-status.on { color: #6ee7a0; }
+.svc-head { display: flex; align-items: center; gap: 12px; margin-top: 4px; }
+.svc-head h2 { text-transform: none; }
+.back-link {
+ display: inline-flex; align-items: center; gap: 2px; margin: 0 0 10px -4px; padding: 3px 8px 3px 4px; border-radius: 8px;
+ font-size: 12px; font-weight: 600; color: #7fb2ff; cursor: pointer;
+}
+.back-link:hover { background: var(--glass); }
+.btn.link { display: inline-flex; align-items: center; gap: 6px; margin-top: 2px; height: 28px; background: transparent; border-color: transparent; color: #7fb2ff; padding: 0 8px; }
+.btn.link:hover { background: var(--glass); color: #a8caff; }
+.block .device .btn { flex: none; width: auto; height: 28px; padding: 0 12px; }
+.note.busy { display: flex; align-items: center; gap: 7px; color: var(--muted); }
+.note.busy .icon { animation: spin 0.9s linear infinite; }
+@keyframes spin { to { transform: rotate(360deg); } }
+
+/* "Press the button on the bridge" */
+.press { display: flex; align-items: center; gap: 14px; padding: 14px; border-radius: 14px; background: var(--glass); border: 1px solid var(--line); margin-bottom: 10px; }
+.press b { display: block; font-size: 13px; }
+.press div > span { display: block; margin-top: 2px; font-size: 11.5px; color: var(--faint); }
+.press-button {
+ position: relative; flex: none; width: 52px; height: 52px; border-radius: 16px;
+ background: linear-gradient(160deg, #f4f5f8, #c9ccd6); box-shadow: inset 0 -3px 0 rgba(0, 0, 0, 0.12), 0 6px 18px rgba(0, 0, 0, 0.35);
+}
+.press-button span {
+ position: absolute; inset: 13px; border-radius: 50%;
+ background: radial-gradient(circle at 40% 35%, #ffffff, #dfe3ea 60%, #c3c8d2);
+ box-shadow: 0 0 0 2px rgba(60, 130, 255, 0.0);
+ animation: press 1.6s var(--ease) infinite;
+}
+@keyframes press {
+ 0%, 100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(60, 140, 255, 0.55); }
+ 40% { transform: scale(0.9); box-shadow: 0 0 0 3px rgba(60, 140, 255, 0.55); }
+ 70% { box-shadow: 0 0 0 10px rgba(60, 140, 255, 0); }
+}
+@media (prefers-reduced-motion: reduce) {
+ .press-button span { animation: none; box-shadow: 0 0 0 3px rgba(60, 140, 255, 0.55); }
+ .note.busy .icon { animation-duration: 2.4s; }
+}
diff --git a/web/src/editor/editor.js b/web/src/editor/editor.js
index 6ba857b..56ecc11 100644
--- a/web/src/editor/editor.js
+++ b/web/src/editor/editor.js
@@ -1,12 +1,13 @@
// Home editor (separate window): a top-down plan you can drag things around on,
-// an inspector for the selected item, a live 3D preview and the Smart Life links.
+// an inspector for the selected item, a live 3D preview and the links to real devices.
import './editor.css';
-import { normalize, loadRawConfig, LIGHT_KINDS, FLOOR_KINDS } from '../config.js';
+import { normalize, loadRawConfig, LIGHT_KINDS, FLOOR_KINDS, isLinked } from '../config.js';
import { createWorld } from '../three/world.js';
import { FURNITURE_TYPES, footprint } from '../three/furniture.js';
import { h, clamp } from '../ui/dom.js';
import { icon } from '../ui/icons.js';
import { isNative, call } from '../bridge.js';
+import { createConnections } from './connections.js';
const SVG = 'http://www.w3.org/2000/svg';
const sv = (tag, attrs = {}, ...kids) => {
@@ -34,7 +35,11 @@ export async function bootEditor(root) {
let doc = structuredClone(await loadRawConfig());
for (const key of Object.values(KEYS)) doc[key] ||= [];
- let sel = { kind: window.__HOUSE_BOOT__?.section === 'tuya' ? 'tuya' : 'home' };
+ // HOUSE_OPEN_EDITOR=connections|smartlife|homeassistant|hue|homekit opens a connection screen.
+ const startAt = window.__HOUSE_BOOT__?.section || new URLSearchParams(location.search).get('section') || '';
+ let sel = startAt === 'connections' ? { kind: 'connections' }
+ : startAt.startsWith('service:') ? { kind: 'service', service: startAt.slice(8) }
+ : startAt === 'tuya' ? { kind: 'service', service: 'smartlife' } : { kind: 'home' };
let dirty = false;
let world = null;
let previewLights = true;
@@ -46,6 +51,17 @@ export async function bootEditor(root) {
devices: null, busy: false, error: null, qr: null,
get linked() { return this.account.connected || this.info.configured; },
};
+ const links = createConnections({
+ rerender: () => {
+ renderSidebar();
+ if (['connections', 'service', 'light', 'ac'].includes(sel.kind)) renderInspector();
+ },
+ toast,
+ usedBy: () => links.usedMap(doc),
+ onOpen: (service) => select(service ? { kind: 'service', service } : { kind: 'connections' }),
+ });
+ // Smart Life signed in or out on its own screen: the overview and the pickers follow.
+ const smartLifeChanged = () => links.refreshInfo().then(() => links.load({ quiet: true }));
/* ---------- layout ---------- */
@@ -127,10 +143,10 @@ export async function bootEditor(root) {
function validate() {
try {
valid = normalize(structuredClone(doc));
- const linked = [...doc.lights, ...doc.acs].filter((d) => d.tuya?.deviceId).length;
+ const linked = [...doc.lights, ...doc.acs].filter(isLinked).length;
status.className = 'status';
status.replaceChildren(h('span.ok', '●'), ` ${doc.rooms.length} rooms · ${doc.lights.length} lights · ${doc.acs.length} ACs · `,
- `${linked} linked to Smart Life`, dirty ? h('span.dirty', ' · unsaved changes') : '');
+ `${linked} linked to real devices`, dirty ? h('span.dirty', ' · unsaved changes') : '');
} catch (e) {
valid = null;
status.className = 'status bad';
@@ -194,9 +210,7 @@ export async function bootEditor(root) {
function renderSidebar() {
const nodes = [h(`button.row.home-row${sel.kind === 'home' ? '.active' : ''}`, { onclick: () => select({ kind: 'home' }) },
icon('home', 15), h('span.row-name', 'Home settings')),
- h(`button.row.tuya-row${sel.kind === 'tuya' ? '.active' : ''}`, { onclick: () => select({ kind: 'tuya' }) },
- icon('plug', 15), h('span.row-name', 'Smart Life'),
- h(`span.pill${tuya.linked ? '.on' : ''}`, tuya.linked ? 'Connected' : 'Demo mode'))];
+ links.sidebarRow(sel.kind === 'connections' || sel.kind === 'service', () => select({ kind: 'connections' }))];
for (const kind of Object.keys(KEYS)) {
const items = doc[KEYS[kind]];
nodes.push(h('div.group',
@@ -207,7 +221,7 @@ export async function bootEditor(root) {
const active = sel.kind === kind && sel.index === index;
nodes.push(h(`div.row${active ? '.active' : ''}`, { role: 'button', tabindex: 0, onclick: () => select({ kind, index }) },
h('span.row-name', name),
- item.tuya?.deviceId ? h('span.linked', { title: 'Linked to a Smart Life device' }, icon('plug', 12, 2.2)) : null,
+ isLinked(item) ? h('span.linked', { title: 'Linked to a real device' }, icon('link', 12, 2.2)) : null,
h('span.row-sub', sub),
h('button.del', { title: 'Remove', 'aria-label': `Remove ${name}`, onclick: (e) => { e.stopPropagation(); remove(kind, index); } }, icon('close', 13, 2.4))));
});
@@ -332,7 +346,7 @@ export async function bootEditor(root) {
doc.lights.forEach((l, i) => {
const g = sv('g', {
- class: `p-light ${l.type}${isSel('light', i) ? ' sel' : ''}${l.tuya?.deviceId ? ' linked' : ''}`, 'data-kind': 'light', 'data-index': i,
+ class: `p-light ${l.type}${isSel('light', i) ? ' sel' : ''}${isLinked(l) ? ' linked' : ''}`, 'data-kind': 'light', 'data-index': i,
transform: `translate(${l.pos[0]} ${l.pos[1]}) rotate(${-(l.rot || 0)})`,
});
if (l.type === 'strip') {
@@ -486,31 +500,8 @@ export async function bootEditor(root) {
const row = (...fields) => h('div.fields', fields);
const section = (title, ...nodes) => h('section.block', h('h3', title), nodes);
- function deviceLink(item) {
- const current = item.tuya?.deviceId || '';
- const setId = (id) => {
- if (!id) delete item.tuya;
- else item.tuya = { ...(item.tuya || {}), deviceId: id };
- };
- const options = [['', 'Not linked — simulated']];
- for (const d of tuya.devices || []) options.push([d.id, `${d.name}${d.online ? '' : ' (offline)'}`]);
- if (current && !options.some((o) => o[0] === current)) options.push([current, `${current} (manual)`]);
- const picker = choice(options);
- const manual = text();
- manual.placeholder = 'or paste a device ID';
- const info = h('p.note');
- const describe = () => {
- const d = (tuya.devices || []).find((x) => x.id === item.tuya?.deviceId);
- info.textContent = d ? `${d.product || d.category} · functions: ${d.codes.join(', ') || 'none reported'}`
- : tuya.linked ? (tuya.devices ? '' : 'Open “Smart Life” on the left to load your devices, then pick one here.')
- : 'Set up the Smart Life connection to control a real device. Until then this device is simulated.';
- };
- describe();
- return section('Smart Life device',
- bind('Device', picker, { get: () => current, set: (v) => { setId(v); manual.value = v; describe(); }, event: 'change' }),
- bind('Device ID', manual, { get: () => current, set: (v) => { setId(v.trim()); describe(); } }),
- info);
- }
+ // Linking to a real device: links.deviceSection / links.sensorSection (connections.js).
+ const linkHooks = { snapshot: () => snapshot(), changed: (note) => { touch(); if (note) toast(note); } };
function renderInspector() {
const kind = sel.kind;
@@ -531,9 +522,14 @@ export async function bootEditor(root) {
h('p.note', 'Walls facing the camera are cut away, so the azimuth decides which side of the home is open.')),
section('How it works',
h('p.note', 'Pick anything on the plan or in the list to edit it. “Save & apply” writes the plan to disk and reloads the menu bar panel. Coordinates are metres: x grows to the right (east), z grows downwards (south).')));
- } else if (kind === 'tuya') {
- head('Smart Life', 'Control the real devices of your Smart Life account');
- nodes.push(...tuyaPanel());
+ } else if (kind === 'connections') {
+ head('Connections', 'Where your real lamps and air conditioners live');
+ nodes.push(...links.overview());
+ } else if (kind === 'service') {
+ nodes.push(h('button.back-link', { onclick: () => { links.stopPairing(); select({ kind: 'connections' }); } }, icon('back', 14, 2.2), 'Connections'));
+ nodes.push(h('div.insp-head.svc-head', links.tile(sel.service, 40),
+ h('div', h('h2', links.title(sel.service)), h('span', links.blurb(sel.service)))));
+ nodes.push(...[links.detail(sel.service, tuyaPanel)].flat());
} else if (!item) {
head('Nothing selected');
} else if (kind === 'room') {
@@ -567,7 +563,7 @@ export async function bootEditor(root) {
bind('White temperature', h('input', { type: 'checkbox' }), { ...cap('temp'), event: 'change' }),
bind('Colour', h('input', { type: 'checkbox' }), { ...cap('color'), event: 'change' })),
h('p.note', 'Leave all three off for a lamp on a plain smart plug: it is then a simple on/off switch.')),
- deviceLink(item));
+ links.deviceSection(item, 'light', linkHooks));
} else if (kind === 'ac') {
head(item.name || item.id, `id: ${item.id}`);
nodes.push(section('Air conditioner',
@@ -583,17 +579,8 @@ export async function bootEditor(root) {
parse: (v) => { const m = /^(\d+)\s*-\s*(\d+)$/.exec(v.trim()); return m && +m[1] < +m[2] ? [+m[1], +m[2]] : undefined; },
})),
h('p.note', 'Dragging the unit on the plan snaps it to the nearest wall of its room.')),
- deviceLink(item),
- section('Room temperature',
- bind('Temperature sensor (device ID, optional)', text(), {
- get: () => item.tuya?.sensorId || '',
- set: (v) => {
- const id = v.trim();
- if (id) item.tuya = { ...(item.tuya || {}), sensorId: id };
- else if (item.tuya) delete item.tuya.sensorId;
- },
- }),
- h('p.note', 'A Smart Life temperature sensor in the same room. Without one the room temperature is estimated.')));
+ links.deviceSection(item, 'ac', linkHooks),
+ links.sensorSection(item, linkHooks));
} else if (kind === 'furniture') {
head(item.type, 'Decoration only');
nodes.push(section('Furniture',
@@ -636,11 +623,21 @@ export async function bootEditor(root) {
event: 'change',
})));
}
- const key = `${sel.kind}:${sel.index}`;
- const top = key === inspector.dataset.key ? inspector.scrollTop : 0;
+ const key = `${sel.kind}:${sel.index ?? sel.service ?? ''}`;
+ const same = key === inspector.dataset.key;
+ const top = same ? inspector.scrollTop : 0;
+ // A refresh of the same screen (devices arriving) keeps the field being typed in.
+ const fields = () => [...inspector.querySelectorAll('input, select, textarea')];
+ const focused = same ? fields().indexOf(document.activeElement) : -1;
+ const caret = focused >= 0 ? [document.activeElement.selectionStart, document.activeElement.selectionEnd] : null;
inspector.dataset.key = key;
- inspector.replaceChildren(...nodes.flat().filter(Boolean));
+ inspector.replaceChildren(...nodes.flat(2).filter(Boolean));
inspector.scrollTop = top;
+ if (focused >= 0) {
+ const el = fields()[focused];
+ el?.focus();
+ try { if (caret?.[0] != null) el.setSelectionRange(caret[0], caret[1]); } catch { /* not a text field */ }
+ }
}
/* ---------- Smart Life ---------- */
@@ -650,7 +647,7 @@ export async function bootEditor(root) {
async function fetchDevices() {
tuya.busy = true; tuya.error = null;
- if (sel.kind === 'tuya') renderInspector();
+ if (sel.kind === 'service') renderInspector();
try {
tuya.devices = (await call('tuya.devices')).devices;
} catch (e) {
@@ -659,7 +656,7 @@ export async function bootEditor(root) {
}
tuya.busy = false;
renderSidebar();
- if (sel.kind === 'tuya') renderInspector();
+ if (sel.kind === 'service') renderInspector();
}
function deviceList() {
@@ -688,6 +685,7 @@ export async function bootEditor(root) {
tuya.account = await call('smartlife.signOut');
tuya.devices = null; tuya.qr = null;
renderSidebar(); renderInspector();
+ smartLifeChanged();
} }, 'Sign out')),
h('p.note', 'Pick a lamp or an AC on the plan, choose its device under “Smart Life device”, then press “Save & apply”.')),
deviceList());
@@ -717,6 +715,7 @@ export async function bootEditor(root) {
tuya.account = r.info;
renderSidebar();
renderInspector();
+ smartLifeChanged();
}, 2000);
} catch (e) {
message.className = 'note bad';
@@ -746,6 +745,7 @@ export async function bootEditor(root) {
try {
tuya.info = await call('tuya.save', { accessId: idInput.value, accessSecret: secretInput.value, region: region.value });
renderSidebar();
+ smartLifeChanged();
if (tuya.info.configured) await fetchDevices(); else renderInspector();
} catch (e) { toast(e.message, true); }
};
@@ -857,5 +857,5 @@ export async function bootEditor(root) {
dirty = false;
validate();
schedulePreview(0);
- window.__editor = { get doc() { return doc; }, select, tuya };
+ window.__editor = { get doc() { return doc; }, select, tuya, links };
}
diff --git a/web/src/main.js b/web/src/main.js
index c5a6c61..7558220 100644
--- a/web/src/main.js
+++ b/web/src/main.js
@@ -1,4 +1,4 @@
-import { loadRawConfig, normalize } from './config.js';
+import { loadRawConfig, normalize, isLinked } from './config.js';
import { createStore } from './store.js';
import { createWorld } from './three/world.js';
import { createPanel } from './ui/panel.js';
@@ -51,7 +51,7 @@ async function boot() {
}
const store = createStore(config);
- const linked = [...config.lights, ...config.acs].some((d) => d.tuya?.deviceId);
+ const linked = [...config.lights, ...config.acs].some(isLinked);
// Never invent a starting state for real hardware: it reports its own.
if (!store.restored && !linked) {
// First launch: start with something worth looking at.
diff --git a/web/src/store.js b/web/src/store.js
index 01b30af..0cb5877 100644
--- a/web/src/store.js
+++ b/web/src/store.js
@@ -250,7 +250,8 @@ export function createStore(config) {
setInterval(() => {
let any = false;
for (const [id, a] of Object.entries(state.acs)) {
- if (acCfg.get(id).tuya?.sensorId) continue; // a real sensor reports this room
+ const cfg = acCfg.get(id);
+ if (cfg.tuya?.sensorId || cfg.sensor?.id || cfg.link?.id) continue; // a real sensor or unit reports this room
const ambient = Math.min(config.outdoorTemp - 2, 27);
const goal = a.on && a.mode !== 'fan' ? a.target : ambient;
const step = a.on ? 0.2 : 0.1;
diff --git a/web/src/ui/icons.js b/web/src/ui/icons.js
index 2996ba5..86ec3ef 100644
--- a/web/src/ui/icons.js
+++ b/web/src/ui/icons.js
@@ -5,6 +5,7 @@ import {
Tv, BedDouble, Palette, RefreshCw, X,
ShieldCheck, Link2, Copy, MessageSquareText, BookOpen, Terminal, RotateCcw, Globe, Laptop, Clock, Box, Download,
Undo2, Activity, KeyRound, ArrowUpRight, Camera, Square,
+ HouseWifi, Smartphone, Radar, CircleCheck, CircleAlert, ChevronRight, Unlink, LoaderCircle, Router,
} from 'lucide';
const ICONS = {
@@ -18,6 +19,8 @@ const ICONS = {
shield: ShieldCheck, link: Link2, copy: Copy, chat: MessageSquareText, book: BookOpen, terminal: Terminal,
rotate: RotateCcw, globe: Globe, laptop: Laptop, clock: Clock, box: Box, download: Download, undo: Undo2,
activity: Activity, key: KeyRound, external: ArrowUpRight, camera: Camera, stop: Square,
+ homeassistant: HouseWifi, phone: Smartphone, radar: Radar, ok: CircleCheck, alert: CircleAlert,
+ next: ChevronRight, unlink: Unlink, spinner: LoaderCircle, bridge: Router, bulb: Lightbulb,
};
export function icon(name, size = 18, stroke = 1.8) {