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.

iPhone app without a Mac: editor, connections and device links on the phone

0xProbabilityd51a8c32c0de
diff --git a/README.md b/README.md
index b2b3528..fa699f7 100644
--- a/README.md
+++ b/README.md
@@ -38,7 +38,8 @@
- **Widgets and controls.** The home in 3D on the iPhone's Home Screen and the Mac's desktop, scenes, lamps and
air conditioners a tap away, Lock Screen and Control Center controls, and quick actions on the app icon.
See [Widgets](#widgets).
-- **An iPhone app.** The same home in your pocket, kept in sync with the Mac over your own Wi-Fi.
+- **An iPhone app that needs no Mac.** Draw the home, connect Smart Life, Home Assistant, Hue and Apple Home and
+ link the devices, all on the phone. Pair a Mac later and both stay in sync, whichever one you edit.
See [iPhone app](#iphone-app).
- **Works without any hardware.** Until you sign in, every device is simulated, so you can try everything first.
@@ -185,6 +186,18 @@ Details, every tool, and the privacy model: [docs/ai-access.md](docs/ai-access.m
The iPhone app is the panel made for a thumb: tap a lamp in the 3D view or its tile, drag across a tile to dim,
touch and hold a light for brightness and colour, pinch the model to zoom, swipe in from the left edge to go back.
+It needs no Mac. Everything is set up on the phone, under **Settings** (the sliders button):
+
+- **New home** starts your own plan — one room, or the Studio or Apartment layout to adapt — and opens the editor.
+- **Edit floor plan** is the Mac's editor laid out for a finger: tap a room, lamp or AC to select it, drag what is
+ selected, drag anywhere else to pan, pinch to zoom. Its details come up in a sheet from the bottom; **Add**,
+ **Items**, **3D** and **Home** sit along the bottom edge. **Save** keeps the plan on the phone (and sends it to a
+ paired Mac).
+- **Devices** lists every lamp and AC of the plan by room; tap one and pick its real device from everything your
+ connected platforms have, or **Add devices to a room** to put several in at once, already linked.
+- **Smart Life**, **Home Assistant**, **Philips Hue** and **Apple Home** connect right there. Home Assistant servers
+ and Hue Bridges on the Wi-Fi are found by themselves.
+
Try it in the simulator:
```bash
@@ -197,16 +210,18 @@ on your device. `./scripts/build-ios.sh --upload` archives it and sends it to Te
### Sync with the Mac
-Your floor plan — rooms, furniture, lamps, scenes and the links to real devices — is drawn on the Mac and travels
-to the phone by itself.
+Optional. Pair a Mac and your floor plan — rooms, furniture, lamps, scenes and the links to real devices — plus the
+Home Assistant and Hue connections stay the same on both, whichever one you set up or edit first.
1. On the Mac: right-click the menu bar icon → **Pair iPhone…**. A QR code appears.
macOS asks once whether House Control may find devices on your local network: allow it.
2. On the iPhone: **Settings** (the sliders button) → **Pair with Mac**, and point the camera at the code.
Or press **Copy Pairing Link** on the Mac and paste it on the phone.
-From then on, whenever both are on the same Wi-Fi and the app is open, the phone has what the Mac has:
-**Save & apply** in the editor updates the phone a moment later.
+From then on, whenever both are on the same Wi-Fi and the app is open, a plan saved on one reaches the other a
+moment later. A home set up on the phone first goes to the Mac when you pair them. If both changed the plan while
+apart, the phone asks which one to keep. A Home Assistant or Hue Bridge connected, or disconnected, on either side
+is the newest one on both.
Nothing goes through a server. The Mac advertises itself with Bonjour and the two talk over TLS with a
pre-shared key that only the QR code carries, so a device that never saw the code cannot connect.
@@ -216,7 +231,8 @@ pre-shared key that only the QR code carries, so a device that never saw the cod
The phone signs in to Smart Life on its own: **Settings → Connect Smart Life**. The User Code is filled in from the
Mac if you are signed in there. The sign-in code has to be scanned by the Smart Life app, which is on the very phone
-you are holding — so the paired Mac puts the code on its screen for you. Without a Mac, share the code to any other screen.
+you are holding. So **Save code to Photos**, then in Smart Life tap **+ → Scan** and open the picture from its photo
+button. A paired Mac also puts the code on its screen for you, and **Share code** sends it to any other screen.
The session is kept in the iPhone's Keychain and never leaves the device.
@@ -364,7 +380,8 @@ Environment variables understood by the app:
| `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|connections|pairing|smartlife|welcome`;
+The iPhone app understands `HOUSE_DATA_DIR`, `HOUSE_OPEN_DEVICE`, `HOUSE_SYNC_ENDPOINT=host:port` (a Mac test instance
+without Bonjour) and `HOUSE_SCREEN=home|settings|connections|pairing|smartlife|homeassistant|hue|devices|newhome|editor|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:
diff --git a/core/Sources/HouseCore/DeviceHub.swift b/core/Sources/HouseCore/DeviceHub.swift
index bf9d69e..27b35a4 100644
--- a/core/Sources/HouseCore/DeviceHub.swift
+++ b/core/Sources/HouseCore/DeviceHub.swift
@@ -49,6 +49,7 @@ public final class DeviceHub {
public init(directory: URL, secret: ((String) -> SecretStore)? = nil, homeKit: DeviceService? = nil) {
let vault = secret ?? { FileSecretStore(url: directory.appendingPathComponent("\($0).json")) }
log = EventLog(directory: directory)
+ stampsURL = directory.appendingPathComponent("connections-sync.json")
tuya = TuyaService(directory: directory)
smartLife = SmartLifeService(vault: vault("smartlife"))
homeAssistant = HomeAssistantService(vault: vault("homeassistant"))
@@ -353,19 +354,96 @@ public final class DeviceHub {
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.)
+ // MARK: - Connections shared between the Mac and its iPhones
+
+ /// The platforms whose connection travels between paired devices. (Apple Home is the
+ /// phone's own; a Smart Life session cannot be shared, Tuya rotates its tokens.)
+ public static let shareablePlatforms = ["homeassistant", "hue"]
+
+ /// When each shareable platform was last connected or disconnected on this device, or
+ /// adopted from another one: the newer side wins when two devices disagree.
+ private var stamps: [String: Double] {
+ get {
+ guard let data = try? Data(contentsOf: stampsURL),
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Double] else { return [:] }
+ return json
+ }
+ set { try? JSONSerialization.data(withJSONObject: newValue).write(to: stampsURL, options: .atomic) }
+ }
+ private let stampsURL: URL
+
+ private func shareable(_ id: String) -> [String: Any]? {
+ id == "homeassistant" ? homeAssistant.shareable : id == "hue" ? hue.shareable : nil
+ }
+
+ /// Connects Home Assistant (checking the address and token first) and remembers when.
+ public func connectHomeAssistant(url: String, token: String) async throws {
+ try await homeAssistant.connect(url: url, token: token)
+ stamp("homeassistant")
+ }
+
+ /// Pairs with a Hue Bridge; throws `HueService.ButtonNotPressed` until its button is pressed.
+ public func pairHue(host: String, bridgeId: String?, name: String?) async throws {
+ try await hue.pair(host: host, bridgeId: bridgeId, name: name)
+ stamp("hue")
+ }
+
+ /// Disconnects a platform; for Home Assistant and Hue the paired devices follow.
+ public func disconnect(service id: String) {
+ services.first { $0.id == id }?.disconnect()
+ if Self.shareablePlatforms.contains(id) { stamp(id) }
+ }
+
+ private func stamp(_ id: String) {
+ var all = stamps
+ all[id] = max(Date().timeIntervalSince1970, (all[id] ?? 0) + 0.001)
+ stamps = all
+ }
+
+ /// This device's Home Assistant and Hue connections for its paired devices: the address
+ /// and token / bridge key plus when they were set, or `removed` after a disconnect.
public var shareableConnections: [String: Any] {
+ let known = stamps
var out: [String: Any] = [:]
- if let ha = homeAssistant.shareable { out["homeassistant"] = ha }
- if let hue = hue.shareable { out["hue"] = hue }
+ for id in Self.shareablePlatforms {
+ let updated = known[id] ?? 0
+ if var config = shareable(id) {
+ config["updated"] = updated
+ out[id] = config
+ } else if updated > 0 {
+ out[id] = ["removed": true, "updated": updated]
+ }
+ }
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])
+ /// Takes what another device shared, platform by platform, where it is newer than what
+ /// this device has. A platform missing from `shared` is left alone. Returns true when a
+ /// connection changed here.
+ @discardableResult
+ public func adoptConnections(_ shared: [String: Any]) -> Bool {
+ var known = stamps
+ var changed = false
+ for id in Self.shareablePlatforms {
+ guard let incoming = shared[id] as? [String: Any] else { continue }
+ let theirs = (incoming["updated"] as? NSNumber)?.doubleValue ?? 0
+ let ours = known[id]
+ // A peer without stamps (an older version) only fills in what was never set here.
+ let newer = theirs > 0 ? theirs > (ours ?? 0) : (ours ?? 0) == 0
+ guard newer else { continue }
+ let before = shareable(id).map { NSDictionary(dictionary: $0) }
+ if incoming["removed"] as? Bool == true {
+ services.first { $0.id == id }?.disconnect()
+ } else if id == "homeassistant" {
+ homeAssistant.adopt(incoming)
+ } else {
+ hue.adopt(incoming)
+ }
+ known[id] = theirs
+ if shareable(id).map({ NSDictionary(dictionary: $0) }) != before { changed = true }
+ }
+ stamps = known
+ return changed
}
/// Read-only snapshot of what Smart Life reports for the given devices.
diff --git a/core/Sources/HouseCore/PlanEditor.swift b/core/Sources/HouseCore/PlanEditor.swift
new file mode 100644
index 0000000..1503b7f
--- /dev/null
+++ b/core/Sources/HouseCore/PlanEditor.swift
@@ -0,0 +1,321 @@
+import Foundation
+
+/// Small edits to a floor plan that the iPhone makes without the drawing editor: linking a
+/// lamp or an AC to a real device, adding real devices to a room, starting a new home.
+/// Works on the plan exactly as stored (`[String: Any]`), the same form the web editor
+/// edits, and follows its rules (`web/src/editor/connections.js`, `web/src/config.js`).
+public struct PlanEditor {
+ public private(set) var plan: [String: Any]
+
+ public init(plan: [String: Any]) { self.plan = plan }
+
+ /// A lamp or an AC of the plan, for lists.
+ public struct Item: Identifiable, Equatable {
+ public let id: String
+ public let kind: DeviceKind
+ public let name: String
+ public let room: String
+ public let roomName: String
+ /// `service` is "smartlife" for a Smart Life link.
+ public let link: DeviceRef?
+ /// An AC's thermometer.
+ public let sensor: DeviceRef?
+ }
+
+ public struct DeviceRef: Hashable {
+ public let service: String
+ public let id: String
+ public init(service: String, id: String) {
+ self.service = service
+ self.id = id
+ }
+ }
+
+ public struct Room: Identifiable, Equatable {
+ public let id: String
+ public let name: String
+ }
+
+ // MARK: - Reading
+
+ public var name: String { plan["name"] as? String ?? "Home" }
+
+ public var rooms: [Room] {
+ (plan["rooms"] as? [[String: Any]] ?? []).compactMap { room in
+ guard let id = room["id"] as? String else { return nil }
+ return Room(id: id, name: (room["name"] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? id)
+ }
+ }
+
+ public var items: [Item] {
+ let names = Dictionary(rooms.map { ($0.id, $0.name) }, uniquingKeysWith: { a, _ in a })
+ var out: [Item] = []
+ for (kind, key) in [(DeviceKind.light, "lights"), (.ac, "acs")] {
+ for device in plan[key] as? [[String: Any]] ?? [] {
+ guard let id = device["id"] as? String else { continue }
+ let room = device["room"] as? String ?? ""
+ out.append(Item(id: id, kind: kind, name: (device["name"] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? id,
+ room: room, roomName: names[room] ?? room,
+ link: Self.link(of: device), sensor: Self.sensor(of: device)))
+ }
+ }
+ return out
+ }
+
+ static func link(of device: [String: Any]) -> DeviceRef? {
+ if let link = device["link"] as? [String: Any], let service = link["service"] as? String,
+ let id = link["id"] as? String, !service.isEmpty, !id.isEmpty {
+ return DeviceRef(service: service, id: id)
+ }
+ if let tuya = device["tuya"] as? [String: Any], let id = tuya["deviceId"] as? String, !id.isEmpty {
+ return DeviceRef(service: "smartlife", id: id)
+ }
+ return nil
+ }
+
+ static func sensor(of device: [String: Any]) -> DeviceRef? {
+ if let sensor = device["sensor"] as? [String: Any], let service = sensor["service"] as? String,
+ let id = sensor["id"] as? String, !id.isEmpty {
+ return DeviceRef(service: service, id: id)
+ }
+ if let tuya = device["tuya"] as? [String: Any], let id = tuya["sensorId"] as? String, !id.isEmpty {
+ return DeviceRef(service: "smartlife", id: id)
+ }
+ return nil
+ }
+
+ /// Real devices already used by the plan, with the name of what uses them.
+ public var usedDevices: [DeviceRef: String] {
+ var out: [DeviceRef: String] = [:]
+ for item in items {
+ if let link = item.link { out[link] = item.name }
+ if let sensor = item.sensor { out[sensor] = "\(item.name) · room" }
+ }
+ return out
+ }
+
+ // MARK: - Linking
+
+ private func index(of id: String) -> (key: String, index: Int)? {
+ for key in ["lights", "acs"] {
+ if let i = (plan[key] as? [[String: Any]] ?? []).firstIndex(where: { $0["id"] as? String == id }) { return (key, i) }
+ }
+ return nil
+ }
+
+ private mutating func update(_ id: String, _ change: (inout [String: Any]) -> Void) {
+ guard let (key, i) = index(of: id), var list = plan[key] as? [[String: Any]] else { return }
+ change(&list[i])
+ plan[key] = list
+ }
+
+ /// Links the lamp or AC `id` to `device` (a device as `DeviceHub.allDevices` lists it),
+ /// or unlinks it (nil). A lamp takes over what the device can do, an AC its range.
+ public mutating func link(_ id: String, to device: [String: Any]?) {
+ update(id) { item in
+ item["link"] = nil
+ if var tuya = item["tuya"] as? [String: Any] {
+ tuya["deviceId"] = nil
+ item["tuya"] = tuya.isEmpty ? nil : tuya
+ }
+ guard let device, let service = device["service"] as? String, let target = device["id"] as? String else { return }
+ if service == "smartlife" {
+ var tuya = item["tuya"] as? [String: Any] ?? [:]
+ tuya["deviceId"] = target
+ item["tuya"] = tuya
+ } else {
+ item["link"] = ["service": service, "id": target]
+ // A Smart Life thermometer only works beside a Smart Life AC.
+ item["tuya"] = nil
+ }
+ let isAC = item["wall"] != nil
+ if !isAC, let caps = device["capabilities"] as? [String] { item["capabilities"] = caps }
+ if isAC, let min = (device["min"] as? NSNumber)?.doubleValue,
+ let max = (device["max"] as? NSNumber)?.doubleValue {
+ item["min"] = Int(min.rounded())
+ item["max"] = Int(max.rounded())
+ }
+ }
+ }
+
+ /// Sets the thermometer of the AC `id` (a device with `kind` "sensor"), or removes it.
+ public mutating func setSensor(_ id: String, to device: [String: Any]?) {
+ update(id) { item in
+ item["sensor"] = nil
+ if var tuya = item["tuya"] as? [String: Any] {
+ tuya["sensorId"] = nil
+ item["tuya"] = tuya.isEmpty ? nil : tuya
+ }
+ guard let device, let service = device["service"] as? String, let target = device["id"] as? String else { return }
+ if service == "smartlife" {
+ var tuya = item["tuya"] as? [String: Any] ?? [:]
+ tuya["sensorId"] = target
+ item["tuya"] = tuya
+ } else {
+ item["sensor"] = ["service": service, "id": target]
+ }
+ }
+ }
+
+ // MARK: - Adding devices
+
+ private var allIds: Set<String> {
+ var ids = Set<String>()
+ for key in ["rooms", "lights", "acs", "scenes"] {
+ for entry in plan[key] as? [[String: Any]] ?? [] { if let id = entry["id"] as? String { ids.insert(id) } }
+ }
+ return ids
+ }
+
+ private func uniqueId(_ base: String, taken: Set<String>) -> String {
+ if !taken.contains(base) { return base }
+ var i = 2
+ while taken.contains("\(base)\(i)") { i += 1 }
+ return "\(base)\(i)"
+ }
+
+ private func rect(of room: String) -> [Double]? {
+ guard let entry = (plan["rooms"] as? [[String: Any]] ?? []).first(where: { $0["id"] as? String == room }),
+ let rect = entry["rect"] as? [NSNumber], rect.count == 4 else { return nil }
+ return rect.map(\.doubleValue)
+ }
+
+ private static func fix(_ v: Double) -> Double { (v * 1000).rounded() / 1000 }
+
+ /// The fixture a lamp probably is, from its name.
+ static func fixture(for name: String) -> String {
+ let n = name.lowercased()
+ if n.contains("strip") || n.contains("лент") { return "strip" }
+ if n.contains("floor") || n.contains("торшер") { return "floor" }
+ if ["desk", "table", "bedside", "night", "насто", "ночн"].contains(where: n.contains) { return "table" }
+ if n.contains("pendant") || n.contains("люстр") { return "pendant" }
+ if n.contains("spot") { return "spots" }
+ return "ceiling"
+ }
+
+ /// Adds real devices (as `DeviceHub.allDevices` lists them) to `room` as linked lamps
+ /// and ACs, spread over the room so none stands on another. Sensors are skipped.
+ /// Returns the ids of the new items.
+ @discardableResult
+ public mutating func add(_ devices: [[String: Any]], to room: String) -> [String] {
+ guard let r = rect(of: room) else { return [] }
+ let (x, z, w, d) = (r[0], r[1], r[2], r[3])
+ var taken = allIds
+ var lights = plan["lights"] as? [[String: Any]] ?? []
+ var acs = plan["acs"] as? [[String: Any]] ?? []
+ let newLights = devices.filter { ($0["kind"] as? String) == "light" }
+ let newACs = devices.filter { ($0["kind"] as? String) == "ac" }
+ var added: [String] = []
+
+ // Lamps on a grid inside the room, away from the lamps already there.
+ let existing = lights.filter { $0["room"] as? String == room }.count
+ let total = existing + newLights.count
+ let columns = max(1, Int(Double(total).squareRoot().rounded(.up)))
+ let rows = max(1, Int((Double(total) / Double(columns)).rounded(.up)))
+ for (n, device) in newLights.enumerated() {
+ let slot = existing + n
+ let cx = x + w * (Double(slot % columns) + 0.5) / Double(columns)
+ let cz = z + d * (Double(slot / columns) + 0.5) / Double(rows)
+ let name = device["name"] as? String ?? "Light"
+ let id = uniqueId("\(room).light", taken: taken)
+ taken.insert(id)
+ var light: [String: Any] = ["id": id, "name": name, "room": room, "type": Self.fixture(for: name),
+ "pos": [Self.fix(cx), Self.fix(cz)],
+ "capabilities": device["capabilities"] as? [String] ?? []]
+ if light["type"] as? String == "strip" { light["length"] = 1.0 }
+ lights.append(light)
+ added.append(id)
+ }
+
+ // ACs along the north wall, then the others, spaced out.
+ let walls = ["north", "south", "west", "east"]
+ let existingACs = acs.filter { $0["room"] as? String == room }.count
+ for (n, device) in newACs.enumerated() {
+ let slot = existingACs + n
+ let wall = walls[slot % 4]
+ let along = Double(slot / 4 + 1) / Double(slot / 4 + 2)
+ let pos: [Double]
+ switch wall {
+ case "north": pos = [x + w * along, z]
+ case "south": pos = [x + w * along, z + d]
+ case "west": pos = [x, z + d * along]
+ default: pos = [x + w, z + d * along]
+ }
+ let id = uniqueId("\(room).ac", taken: taken)
+ taken.insert(id)
+ var ac: [String: Any] = ["id": id, "name": device["name"] as? String ?? "AC", "room": room, "wall": wall,
+ "pos": pos.map(Self.fix), "y": 2.2]
+ if let min = (device["min"] as? NSNumber)?.doubleValue, let max = (device["max"] as? NSNumber)?.doubleValue {
+ ac["min"] = Int(min.rounded())
+ ac["max"] = Int(max.rounded())
+ }
+ acs.append(ac)
+ added.append(id)
+ }
+ plan["lights"] = lights
+ plan["acs"] = acs
+ // Link each new item to its device.
+ for (id, device) in zip(added, newLights + newACs) { link(id, to: device) }
+ return added
+ }
+
+ /// Removes a lamp or an AC, and its mentions in the scenes.
+ public mutating func remove(_ id: String) {
+ guard let (key, i) = index(of: id), var list = plan[key] as? [[String: Any]] else { return }
+ list.remove(at: i)
+ plan[key] = list
+ guard var scenes = plan["scenes"] as? [[String: Any]] else { return }
+ for s in scenes.indices {
+ for map in ["lights", "acs"] {
+ if var rules = scenes[s][map] as? [String: Any] {
+ rules[id] = nil
+ scenes[s][map] = rules
+ }
+ }
+ }
+ plan["scenes"] = scenes
+ }
+
+ /// Adds a room east of the others; returns its id.
+ @discardableResult
+ public mutating func addRoom(named name: String, width: Double = 4, depth: Double = 3.5) -> String {
+ var rooms = plan["rooms"] as? [[String: Any]] ?? []
+ let rects = rooms.compactMap { ($0["rect"] as? [NSNumber])?.map(\.doubleValue) }.filter { $0.count == 4 }
+ let maxX = rects.map { $0[0] + $0[2] }.max() ?? 0
+ let minZ = rects.map { $0[1] }.min() ?? 0
+ let base = Self.slug(name)
+ let id = uniqueId(base, taken: allIds)
+ rooms.append(["id": id, "name": name, "rect": [Self.fix(maxX), Self.fix(minZ), width, depth], "floor": "oak"])
+ plan["rooms"] = rooms
+ return id
+ }
+
+ static func slug(_ text: String) -> String {
+ let s = text.lowercased().unicodeScalars.map { CharacterSet.alphanumerics.contains($0) && $0.isASCII ? String($0) : "-" }.joined()
+ let trimmed = s.split(separator: "-").joined(separator: "-")
+ return trimmed.isEmpty ? "room" : trimmed
+ }
+
+ // MARK: - New home
+
+ /// A new home with one room, ready to be drawn further: the starting point of a home set
+ /// up on the phone.
+ public static func blank(name: String) -> [String: Any] {
+ [
+ "version": 1,
+ "name": name,
+ "wallHeight": 2.6,
+ "interiorWallHeight": 1.25,
+ "camera": ["azimuth": 34, "elevation": 47],
+ "rooms": [["id": "living", "name": "Living room", "rect": [0.0, 0.0, 5.0, 4.0], "floor": "oak"]],
+ "openings": [[String: Any]](),
+ "furniture": [[String: Any]](),
+ "lights": [[String: Any]](),
+ "acs": [[String: Any]](),
+ "scenes": [
+ ["id": "bright", "name": "Bright", "icon": "sun", "lights": ["*": ["on": true, "brightness": 1]]],
+ ["id": "off", "name": "All off", "icon": "moon", "lights": ["*": ["on": false]], "acs": ["*": ["on": false]]],
+ ],
+ ]
+ }
+}
diff --git a/core/Sources/HouseCore/SyncClient.swift b/core/Sources/HouseCore/SyncClient.swift
index 21bc75a..24641bc 100644
--- a/core/Sources/HouseCore/SyncClient.swift
+++ b/core/Sources/HouseCore/SyncClient.swift
@@ -29,6 +29,9 @@ public final class SyncClient {
private var qrUnsent = false
/// This phone's Apple Home devices, waiting to be sent to the Mac.
private var catalog: [[String: Any]]?
+ /// This phone's Home Assistant and Hue connections and Smart Life User Code, waiting to be
+ /// sent to the Mac.
+ private var connections: (shared: [String: Any], userCode: String)?
/// Set to connect straight to a host and port instead of browsing (tests).
var fixedEndpoint: NWEndpoint?
@@ -110,6 +113,29 @@ public final class SyncClient {
flushCatalog()
}
+ /// Hands the Mac this phone's connections, now or as soon as it is connected. The Mac
+ /// keeps whichever side changed a platform last.
+ public func sendConnections(_ shared: [String: Any], userCode: String) {
+ connections = (shared, userCode)
+ flushConnections()
+ }
+
+ private func flushConnections() {
+ guard let connections, let channel, status == .connected else { return }
+ channel.send(["type": "connections", "connections": connections.shared, "userCode": connections.userCode])
+ self.connections = nil
+ }
+
+ /// Sends a floor plan edited on this phone to the Mac (the file byte for byte, so both
+ /// sides compute the same revision). Not queued: false when the Mac is not connected
+ /// right now, and the next state it sends decides what happens to the edit.
+ @discardableResult
+ public func sendPlan(_ data: Data) -> Bool {
+ guard let channel, status == .connected, let text = String(data: data, encoding: .utf8) else { return false }
+ channel.send(["type": "plan", "plan": text])
+ return true
+ }
+
private func flushCatalog() {
guard let catalog, let channel, status == .connected else { return }
channel.send(["type": "catalog", "devices": catalog])
@@ -191,6 +217,7 @@ public final class SyncClient {
self.set(.connected)
_ = self.flushQR()
self.flushCatalog()
+ self.flushConnections()
self.onState?(state)
}
channel.onClose = { [weak self] error in
diff --git a/core/Sources/HouseCore/SyncServer.swift b/core/Sources/HouseCore/SyncServer.swift
index f9b38ce..25fbf3e 100644
--- a/core/Sources/HouseCore/SyncServer.swift
+++ b/core/Sources/HouseCore/SyncServer.swift
@@ -34,6 +34,12 @@ public final class SyncServer {
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)?
+ /// A phone sends the floor plan it edited (the file byte for byte, already checked to be
+ /// a plan) and its name. The Mac stores it and calls `broadcast()`.
+ public var onPlan: ((Data, String) -> Void)?
+ /// A phone sends its Home Assistant and Hue connections (see `DeviceHub.adoptConnections`)
+ /// and the Smart Life User Code it signed in with, if any.
+ public var onConnections: (([String: Any], String, String) -> Void)?
/// `store` keeps the pairing (by default `sync.json` next to the plan, readable by its user only).
public init(store: SecretStore) {
@@ -170,6 +176,16 @@ public final class SyncServer {
case "catalog":
guard !peer.name.isEmpty, let devices = message["devices"] as? [[String: Any]] else { return }
onCatalog?(devices, peer.name)
+ case "plan":
+ guard !peer.name.isEmpty, let text = message["plan"] as? String else { return }
+ let data = Data(text.utf8)
+ guard (try? PlanStore.validate(data)) != nil else { return }
+ // The phone holds this revision now: the broadcast that follows need not echo it.
+ peer.revision = PlanStore.revision(of: data)
+ onPlan?(data, peer.name)
+ case "connections":
+ guard !peer.name.isEmpty, let shared = message["connections"] as? [String: Any] else { return }
+ onConnections?(shared, message["userCode"] as? String ?? "", peer.name)
default:
break
}
diff --git a/core/Tests/HouseCoreTests/PlanEditorTests.swift b/core/Tests/HouseCoreTests/PlanEditorTests.swift
new file mode 100644
index 0000000..8cf071f
--- /dev/null
+++ b/core/Tests/HouseCoreTests/PlanEditorTests.swift
@@ -0,0 +1,106 @@
+import XCTest
+@testable import HouseCore
+
+final class PlanEditorTests: XCTestCase {
+ private func sample() -> [String: Any] {
+ var plan = PlanEditor.blank(name: "Flat")
+ plan["lights"] = [["id": "living.light", "name": "Ceiling", "room": "living", "type": "ceiling", "pos": [2.5, 2], "capabilities": []]]
+ plan["acs"] = [["id": "living.ac", "name": "AC", "room": "living", "wall": "north", "pos": [2.5, 0],
+ "tuya": ["deviceId": "old", "sensorId": "s1"]]]
+ return plan
+ }
+
+ func testItemsAndLinks() {
+ let editor = PlanEditor(plan: sample())
+ XCTAssertEqual(editor.rooms.map(\.name), ["Living room"])
+ XCTAssertEqual(editor.items.map(\.id), ["living.light", "living.ac"])
+ XCTAssertNil(editor.items[0].link)
+ XCTAssertEqual(editor.items[1].link, .init(service: "smartlife", id: "old"))
+ XCTAssertEqual(editor.items[1].sensor, .init(service: "smartlife", id: "s1"))
+ XCTAssertEqual(editor.items[1].roomName, "Living room")
+ }
+
+ func testLinkingFollowsTheWebEditorsRules() {
+ var editor = PlanEditor(plan: sample())
+ editor.link("living.light", to: ["service": "hue", "id": "h1", "kind": "light", "capabilities": ["brightness", "temp"]])
+ var light = (editor.plan["lights"] as! [[String: Any]])[0]
+ XCTAssertEqual(light["link"] as? [String: String], ["service": "hue", "id": "h1"])
+ XCTAssertEqual(light["capabilities"] as? [String], ["brightness", "temp"])
+
+ editor.link("living.light", to: ["service": "smartlife", "id": "t1", "kind": "light"])
+ light = (editor.plan["lights"] as! [[String: Any]])[0]
+ XCTAssertNil(light["link"])
+ XCTAssertEqual((light["tuya"] as? [String: Any])?["deviceId"] as? String, "t1")
+
+ // An AC moved to Home Assistant loses its Smart Life thermometer and takes the range.
+ editor.link("living.ac", to: ["service": "homeassistant", "id": "climate.x", "kind": "ac", "min": 17.0, "max": 31.0])
+ var ac = (editor.plan["acs"] as! [[String: Any]])[0]
+ XCTAssertNil(ac["tuya"])
+ XCTAssertEqual(ac["min"] as? Int, 17)
+ XCTAssertEqual(ac["max"] as? Int, 31)
+ XCTAssertNil(ac["capabilities"])
+
+ editor.setSensor("living.ac", to: ["service": "hue", "id": "temp1", "kind": "sensor"])
+ ac = (editor.plan["acs"] as! [[String: Any]])[0]
+ XCTAssertEqual(ac["sensor"] as? [String: String], ["service": "hue", "id": "temp1"])
+ XCTAssertEqual(editor.usedDevices[.init(service: "hue", id: "temp1")], "AC · room")
+
+ editor.link("living.ac", to: nil)
+ editor.setSensor("living.ac", to: nil)
+ ac = (editor.plan["acs"] as! [[String: Any]])[0]
+ XCTAssertNil(ac["link"])
+ XCTAssertNil(ac["sensor"])
+ XCTAssertNil(editor.items[1].link)
+ }
+
+ func testAddingDevicesMakesAValidLinkedPlan() throws {
+ var editor = PlanEditor(plan: sample())
+ let added = editor.add([
+ ["service": "smartlife", "id": "p1", "kind": "light", "name": "Desk lamp", "capabilities": []],
+ ["service": "hue", "id": "h2", "kind": "light", "name": "LED strip", "capabilities": ["color"]],
+ ["service": "homeassistant", "id": "climate.y", "kind": "ac", "name": "Bedroom AC", "min": 16.0, "max": 30.0],
+ ["service": "hue", "id": "t", "kind": "sensor", "name": "Motion"],
+ ], to: "living")
+ XCTAssertEqual(added, ["living.light2", "living.light3", "living.ac2"])
+ let lights = editor.plan["lights"] as! [[String: Any]]
+ XCTAssertEqual(lights[1]["type"] as? String, "table")
+ XCTAssertEqual(lights[2]["type"] as? String, "strip")
+ XCTAssertEqual(lights[2]["capabilities"] as? [String], ["color"])
+ XCTAssertEqual((lights[1]["tuya"] as? [String: Any])?["deviceId"] as? String, "p1")
+ // Every new lamp stands inside the room, none on another.
+ let spots = lights.map { ($0["pos"] as! [Double]) }
+ XCTAssertEqual(Set(spots.map { "\($0)" }).count, spots.count)
+ for p in spots { XCTAssertTrue((0...5).contains(p[0]) && (0...4).contains(p[1])) }
+ let ac = (editor.plan["acs"] as! [[String: Any]])[1]
+ XCTAssertEqual(ac["wall"] as? String, "south") // the north wall already has one
+ XCTAssertEqual(ac["pos"] as? [Double], [2.5, 4])
+ XCTAssertEqual(ac["link"] as? [String: String], ["service": "homeassistant", "id": "climate.y"])
+ // Still a plan the stores accept.
+ _ = try PlanStore.validate(PlanStore.encode(editor.plan))
+ }
+
+ func testRoomsAndRemoval() {
+ var editor = PlanEditor(plan: sample())
+ let id = editor.addRoom(named: "Спальня")
+ XCTAssertEqual(id, "room")
+ XCTAssertEqual(editor.addRoom(named: "Kids' room"), "kids-room")
+ let rects = (editor.plan["rooms"] as! [[String: Any]]).map { ($0["rect"] as! [NSNumber]).map(\.doubleValue) }
+ XCTAssertEqual(rects[1][0], 5) // east of the living room
+ XCTAssertEqual(rects[2][0], 9)
+
+ var plan = editor.plan
+ plan["scenes"] = [["id": "s", "lights": ["living.light": ["on": true], "*": ["on": false]]]]
+ editor = PlanEditor(plan: plan)
+ editor.remove("living.light")
+ XCTAssertEqual(editor.items.map(\.id), ["living.ac"])
+ let rules = (editor.plan["scenes"] as! [[String: Any]])[0]["lights"] as! [String: Any]
+ XCTAssertEqual(Array(rules.keys), ["*"])
+ }
+
+ func testFixtureGuess() {
+ XCTAssertEqual(PlanEditor.fixture(for: "Bedside Lamp"), "table")
+ XCTAssertEqual(PlanEditor.fixture(for: "Hue color lamp"), "ceiling")
+ XCTAssertEqual(PlanEditor.fixture(for: "Торшер"), "floor")
+ XCTAssertEqual(PlanEditor.fixture(for: "Kitchen"), "ceiling")
+ }
+}
diff --git a/core/Tests/HouseCoreTests/SyncTests.swift b/core/Tests/HouseCoreTests/SyncTests.swift
index 692ad88..2eae754 100644
--- a/core/Tests/HouseCoreTests/SyncTests.swift
+++ b/core/Tests/HouseCoreTests/SyncTests.swift
@@ -168,6 +168,81 @@ final class SyncTests: XCTestCase {
XCTAssertNil(SyncState(message: ["type": "state", "mac": "Old Mac"])?.connections)
}
+ func testPhoneSendsItsPlanAndConnectionsToTheMac() async throws {
+ let (server, client) = makePair()
+ defer { client.stop(); server.stop() }
+ var macPlan: Data?
+ server.snapshot = {
+ SyncState(macName: "Test Mac", revision: macPlan.map(PlanStore.revision(of:)) ?? "", plan: macPlan,
+ userCode: "", smartLifeConnected: false)
+ }
+ let phonePlan = Data("{\"name\":\"Phone home\",\"rooms\":[{\"id\":\"a\",\"rect\":[0,0,3,3]}]}".utf8)
+ client.planRevision = { PlanStore.revision(of: phonePlan) }
+ let connected = expectation(description: "connected")
+ client.onState = { _ in connected.fulfill() }
+ client.fixedEndpoint = try await waitForPort(server)
+ client.start()
+ await fulfillment(of: [connected], timeout: 10)
+
+ // The plan arrives byte for byte; the Mac's broadcast does not send it back.
+ let arrived = expectation(description: "plan on the Mac")
+ server.onPlan = { data, phone in
+ XCTAssertEqual(phone, "Test iPhone")
+ macPlan = data
+ arrived.fulfill()
+ server.broadcast()
+ }
+ let echoed = expectation(description: "state after the push")
+ var after: SyncState?
+ client.onState = { after = $0; echoed.fulfill() }
+ XCTAssertTrue(client.sendPlan(phonePlan))
+ await fulfillment(of: [arrived, echoed], timeout: 10)
+ XCTAssertEqual(macPlan, phonePlan)
+ XCTAssertEqual(after?.revision, PlanStore.revision(of: phonePlan))
+ XCTAssertNil(after?.plan)
+
+ // Something that is not a plan is dropped.
+ server.onPlan = { _, _ in XCTFail("not a plan") }
+ let shared = expectation(description: "connections on the Mac")
+ server.onConnections = { connections, userCode, _ in
+ XCTAssertEqual((connections["hue"] as? [String: Any])?["key"] as? String, "k")
+ XCTAssertEqual(userCode, "u9")
+ shared.fulfill()
+ }
+ client.sendPlan(Data("{\"name\":\"x\"}".utf8))
+ client.sendConnections(["hue": ["host": "10.0.0.2", "key": "k", "updated": 5]], userCode: "u9")
+ await fulfillment(of: [shared], timeout: 10)
+ }
+
+ func testConnectionsMergeByWhoChangedLast() throws {
+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent("hc-merge-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: folder) }
+ let hub = DeviceHub(directory: folder)
+ defer { hub.disconnect(service: "hue"); hub.disconnect(service: "homeassistant") }
+
+ // Nothing set here yet: a peer's connection is taken, stamps and all.
+ XCTAssertTrue(hub.adoptConnections(["hue": ["host": "10.0.0.2", "key": "k1", "updated": 100.0]]))
+ XCTAssertEqual(hub.hue.info["host"] as? String, "10.0.0.2")
+ XCTAssertEqual((hub.shareableConnections["hue"] as? [String: Any])?["updated"] as? Double, 100)
+ // An older one is ignored, a newer one replaces it.
+ XCTAssertFalse(hub.adoptConnections(["hue": ["host": "10.0.0.3", "key": "k0", "updated": 50.0]]))
+ XCTAssertTrue(hub.adoptConnections(["hue": ["host": "10.0.0.4", "key": "k2", "updated": 200.0]]))
+ XCTAssertEqual(hub.hue.info["host"] as? String, "10.0.0.4")
+ // A platform the peer does not mention is left alone.
+ XCTAssertFalse(hub.adoptConnections([:]))
+ XCTAssertTrue(hub.hue.isConnected)
+ // A newer disconnect travels as "removed".
+ XCTAssertTrue(hub.adoptConnections(["hue": ["removed": true, "updated": 300.0]]))
+ XCTAssertFalse(hub.hue.isConnected)
+ // Disconnecting here is newer than anything the peer had, and is shared.
+ XCTAssertTrue(hub.adoptConnections(["homeassistant": ["url": "http://ha.local:8123", "token": "t", "updated": 10.0]]))
+ hub.disconnect(service: "homeassistant")
+ XCTAssertEqual((hub.shareableConnections["homeassistant"] as? [String: Any])?["removed"] as? Bool, true)
+ XCTAssertFalse(hub.adoptConnections(["homeassistant": ["url": "http://ha.local:8123", "token": "t", "updated": 10.0]]))
+ XCTAssertFalse(hub.homeAssistant.isConnected)
+ }
+
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
index d3fcd5a..3bc8575 100644
--- a/docs/connections.md
+++ b/docs/connections.md
@@ -11,12 +11,15 @@ Everything you do not link stays simulated.
| **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.
+On the Mac 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.
+On the iPhone they are in **Settings**: Smart Life, Home Assistant and Philips Hue each have their own screen, and
+**Settings → Devices** links the plan's lamps and ACs (or adds your devices to a room, already linked). No Mac is
+needed. When a Mac is paired, the Home Assistant and Hue connections travel between the two over their encrypted
+link, in whichever direction they were set up, so there is nothing to set up twice. Smart Life signs in on each
+device separately: its session cannot be shared, Tuya renews it as it is used.
## Home Assistant
@@ -108,10 +111,10 @@ emulator and a HomeKit bridge you can add to the Home app. See [tools/lab/README
## Privacy
-Credentials stay on your Mac, in `~/Library/Application Support/HouseControl/` (readable only by you):
+Credentials stay on your devices. On the Mac they are 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.
+On the iPhone they are in the Keychain. **Disconnect** deletes them, on both when they are paired. A Mac and its
+paired iPhones exchange the Home Assistant and Hue connections over their encrypted link. 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/ios/Sources/AppModel.swift b/ios/Sources/AppModel.swift
index ee06ab2..de29b56 100644
--- a/ios/Sources/AppModel.swift
+++ b/ios/Sources/AppModel.swift
@@ -18,10 +18,36 @@ enum HomeKitStatus: Equatable {
}
/// Where the settings sheet opens.
-enum SettingsRoute: Hashable {
+enum SettingsRoute: Hashable, Identifiable {
case pairing
case smartLife
case quickActions
+ case homeAssistant
+ case hue
+ case devices
+
+ var id: Self { self }
+
+ /// The screen a connection id of the web editor ("smartlife", "hue"…) stands for.
+ init?(service: String) {
+ switch service {
+ case "smartlife": self = .smartLife
+ case "homeassistant": self = .homeAssistant
+ case "hue": self = .hue
+ default: return nil
+ }
+ }
+}
+
+/// Both this iPhone and the paired Mac changed the floor plan since they last agreed:
+/// the user picks which one stays.
+struct PlanChoice: Identifiable {
+ let id = UUID()
+ let macName: String
+ let macPlanName: String
+ let phonePlanName: String
+ /// The Mac's plan, byte for byte.
+ let macPlan: Data
}
/// Everything the screens share: the floor plan, the devices, the link to the Mac.
@@ -50,6 +76,8 @@ final class AppModel {
private(set) var hasCustomPlan: Bool
private(set) var customPlanName: String?
private(set) var linkedDevices = 0
+ /// Goes up whenever the plan on disk changed, so views reading `currentPlan` redraw.
+ private(set) var planVersion = 0
// Mac sync
private(set) var syncStatus: SyncClient.Status
@@ -68,10 +96,23 @@ final class AppModel {
/// The User Code entered on the Mac, offered here so it need not be typed again.
private(set) var suggestedUserCode = ""
+ // Editing the home on this phone
+ /// The web editor, while it is open.
+ private(set) var editorWeb: HomeWeb?
+ var showEditor = false
+ /// A connection screen opened from inside the editor.
+ var editorSheet: SettingsRoute?
+ /// The editor asked for a plan file to import (`importPlan`), or to save one (`exportPlan`).
+ var editorImporting = false
+ var editorExport: PlanFile?
+ @ObservationIgnored private var editorPending: [String: Any]?
+ var planChoice: PlanChoice?
+
// Presentation
var showSettings = false
var settingsPath: [SettingsRoute] = []
var showWelcome = false
+ var showNewHome = false
private(set) var banner: Banner?
init() {
@@ -106,6 +147,8 @@ final class AppModel {
}
reloadLinks()
refreshConnections()
+ // A phone paired before plans travelled both ways holds the Mac's plan as it was sent.
+ if sync.isPaired, syncedRevision == nil { syncedRevision = plans.customPlanRevision }
sync.deviceName = UIDevice.current.name
sync.planRevision = { [plans] in plans.customPlanRevision }
@@ -131,8 +174,13 @@ final class AppModel {
case "pairing": showSettings = true; settingsPath = [.pairing]
case "smartlife": showSettings = true; settingsPath = [.smartLife]
case "quickactions": showSettings = true; settingsPath = [.quickActions]
+ case "homeassistant": showSettings = true; settingsPath = [.homeAssistant]
+ case "hue": showSettings = true; settingsPath = [.hue]
+ case "devices": showSettings = true; settingsPath = [.devices]
+ case "editor": showEditor = true; openEditor()
case "connections": showSettings = true
case "welcome": showWelcome = true
+ case "newhome": showNewHome = true
case "home": break
default: showWelcome = !sandboxed && !UserDefaults.standard.bool(forKey: "welcomed")
}
@@ -204,6 +252,8 @@ final class AppModel {
case "openSettings":
settingsPath = []
showSettings = true
+ case "openEditor":
+ openEditor()
default:
break
}
@@ -216,6 +266,7 @@ final class AppModel {
/// Re-reads everything that depends on the plan and shows it.
private func reloadHome() {
+ planVersion += 1
activePlan = plans.activePlan
hasCustomPlan = plans.hasCustomPlan
customPlanName = plans.customPlanName
@@ -247,6 +298,243 @@ final class AppModel {
reloadHome()
}
+ /// The plan the phone shows right now, as stored: the user's own, or a demo from the app.
+ var currentPlan: [String: Any]? {
+ _ = planVersion
+ if plans.activePlan == "custom", let plan = plans.customPlan() { return plan }
+ let url = HomeWeb.assetRoot.appendingPathComponent("plans/\(plans.activePlan).json")
+ return (try? Data(contentsOf: url)).flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }
+ }
+
+ /// Stores an edited plan as this phone's home (a demo becomes the user's own), shows it
+ /// and hands it to the Mac.
+ func savePlan(_ plan: [String: Any]) throws {
+ let data = try PlanStore.encode(plan)
+ _ = try PlanStore.validate(data)
+ try plans.saveCustom(data: data)
+ reloadHome()
+ sync.sendPlan(data) // when the Mac is away, the next sync sends it
+ }
+
+ /// Starts a new home on this phone: an empty one with one room, or a copy of a demo
+ /// layout. The editor opens on it.
+ func createHome(name: String, template: String?) {
+ var plan = template.flatMap { id -> [String: Any]? in
+ let url = HomeWeb.assetRoot.appendingPathComponent("plans/\(id).json")
+ return (try? Data(contentsOf: url)).flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }
+ } ?? PlanEditor.blank(name: name)
+ plan["name"] = name
+ do {
+ try savePlan(plan)
+ } catch {
+ show(Banner(symbol: "exclamationmark.triangle.fill", text: "Could not create the home", tint: Theme.red))
+ return
+ }
+ showSettings = false
+ showNewHome = false
+ Task { @MainActor in
+ try? await Task.sleep(nanoseconds: 450_000_000)
+ openEditor()
+ }
+ }
+
+ // MARK: - Editor
+
+ func openEditor() {
+ if editorWeb == nil {
+ let web = HomeWeb(persistent: (ProcessInfo.processInfo.environment["HOUSE_DATA_DIR"] ?? "").isEmpty, mode: "editor")
+ web.onMessage = { [weak self, weak web] message in
+ guard let self, let web else { return }
+ self.handleEditor(message, web)
+ }
+ web.load { [weak self] in self?.editorBoot() ?? [:] }
+ editorWeb = web
+ }
+ showSettings = false
+ showEditor = true
+ }
+
+ /// Called once the editor's screen is gone.
+ func editorClosed() {
+ editorWeb?.detach()
+ editorWeb = nil
+ editorSheet = nil
+ }
+
+ private func editorBoot() -> [String: Any] {
+ var boot = plans.bootPayload()
+ if boot["config"] == nil, let plan = currentPlan { boot["config"] = plan }
+ boot["smartLife"] = hub.smartLifeInfo
+ boot["tuya"] = hub.tuyaInfo
+ boot["services"] = hub.servicesInfo
+ if let section = ProcessInfo.processInfo.environment["HOUSE_OPEN_EDITOR"] { boot["section"] = section }
+ return boot
+ }
+
+ private func handleEditor(_ message: [String: Any], _ web: HomeWeb) {
+ switch message["type"] as? String {
+ case "close":
+ showEditor = false
+ case "haptic":
+ Haptics.shared.play(message["kind"] as? String ?? "light")
+ case "openConnection":
+ let service = message["service"] as? String ?? ""
+ if service == "homekit" {
+ // Apple Home has no screen of its own: iOS asks for access, Settings grants it.
+ switch homeKit {
+ case .off: connectHomeKit()
+ case .denied: if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) }
+ default: show(Banner(symbol: "homekit", text: "Apple Home is connected"))
+ }
+ } else {
+ editorSheet = SettingsRoute(service: service)
+ }
+ case "savePlan":
+ guard let config = message["config"] as? [String: Any] else { return }
+ do {
+ try savePlan(config)
+ Haptics.shared.play("success")
+ web.reply(to: message, ["ok": true])
+ } catch {
+ web.reply(to: message, ["error": error.localizedDescription])
+ }
+ case "importPlan":
+ editorPending = message
+ editorImporting = true
+ case "exportPlan":
+ guard let config = message["config"] as? [String: Any], let data = try? PlanStore.encode(config) else { return }
+ editorPending = message
+ editorExport = PlanFile(data: data, name: config["name"] as? String ?? "Home")
+ default:
+ handleService(message) { web.reply(to: message, $0) }
+ }
+ }
+
+ /// The file picked for the editor's "Import…" (nil: cancelled).
+ func editorImported(_ result: Result<URL, Error>?) {
+ guard let message = editorPending, let web = editorWeb else { return }
+ editorPending = nil
+ guard case .success(let url) = result else {
+ web.reply(to: message, ["cancelled": true])
+ return
+ }
+ let scoped = url.startAccessingSecurityScopedResource()
+ defer { if scoped { url.stopAccessingSecurityScopedResource() } }
+ guard let data = try? Data(contentsOf: url), let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
+ web.reply(to: message, ["error": "This file is not a floor plan."])
+ return
+ }
+ web.reply(to: message, ["config": json])
+ }
+
+ func editorExported(_ ok: Bool) {
+ guard let message = editorPending else { return }
+ editorPending = nil
+ editorExport = nil
+ editorWeb?.reply(to: message, ok ? ["ok": true] : ["cancelled": true])
+ }
+
+ /// A connection screen opened from the editor was closed: the editor's lists follow.
+ func editorSheetClosed() {
+ editorWeb?.call("servicesChanged", hub.servicesInfo)
+ }
+
+ /// What the web editor asks of the platforms; the same calls the Mac answers.
+ private func handleService(_ message: [String: Any], reply: @escaping ([String: Any]) -> Void) {
+ switch message["type"] as? String {
+ case "services.info":
+ reply(hub.servicesInfo)
+ case "devices.all":
+ Task { @MainActor in
+ let (devices, errors) = await hub.allDevices()
+ reply(["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()
+ reply(["found": found])
+ }
+ case "homeassistant.connect":
+ Task { @MainActor in
+ do {
+ try await connectHomeAssistant(url: message["url"] as? String ?? "", token: message["token"] as? String ?? "")
+ reply(hub.servicesInfo)
+ } catch {
+ reply(["error": error.localizedDescription])
+ }
+ }
+ case "hue.pair":
+ Task { @MainActor in
+ do {
+ if try await pairHue(host: message["host"] as? String ?? "", bridgeId: message["bridgeId"] as? String,
+ name: message["name"] as? String) {
+ reply(hub.servicesInfo)
+ } else {
+ reply(["waiting": true])
+ }
+ } catch {
+ reply(["error": error.localizedDescription])
+ }
+ }
+ case "service.disconnect":
+ disconnect(service: message["service"] as? String ?? "")
+ reply(hub.servicesInfo)
+ case "smartlife.begin":
+ Task { @MainActor in
+ do {
+ let login = try await beginLogin(userCode: message["userCode"] as? String ?? "")
+ let png = QRCode.png(for: login.qrContent).map { "data:image/png;base64,\($0.base64EncodedString())" }
+ reply(["token": login.token, "qr": png ?? ""])
+ } catch {
+ reply(["error": error.localizedDescription])
+ }
+ }
+ case "smartlife.poll":
+ Task { @MainActor in
+ let done = await finishLogin(token: message["token"] as? String ?? "", userCode: message["userCode"] as? String ?? "")
+ reply(["connected": done, "info": hub.smartLifeInfo])
+ }
+ case "smartlife.signOut":
+ signOut()
+ reply(hub.smartLifeInfo)
+ case "tuya.devices":
+ Task { @MainActor in
+ do { reply(["devices": try await hub.listDevices()]) } catch { reply(["error": error.localizedDescription]) }
+ }
+ case "tuya.save":
+ do {
+ try hub.saveTuya(accessId: message["accessId"] as? String ?? "", accessSecret: message["accessSecret"] as? String ?? "",
+ region: message["region"] as? String ?? "eu")
+ reply(hub.tuyaInfo)
+ } catch {
+ reply(["error": error.localizedDescription])
+ }
+ default:
+ break
+ }
+ }
+
+ // MARK: - Devices (linking without the editor)
+
+ /// Every device of every connected platform, plus what went wrong with the ones that
+ /// could not be asked.
+ func allDevices() async -> (devices: [[String: Any]], errors: [String: String]) {
+ await hub.allDevices()
+ }
+
+ /// Applies an edit to the current plan and saves it.
+ func editPlan(_ change: (inout PlanEditor) -> Void) {
+ guard let plan = currentPlan else { return }
+ var editor = PlanEditor(plan: plan)
+ change(&editor)
+ do {
+ try savePlan(editor.plan)
+ } catch {
+ show(Banner(symbol: "exclamationmark.triangle.fill", text: "Could not save the floor plan", tint: Theme.red))
+ }
+ }
+
// MARK: - Quick actions
private func runQuickAction(_ id: String, title: String) {
@@ -293,6 +581,8 @@ final class AppModel {
func unpair() {
sync.unpair()
+ syncedRevision = nil
+ planChoice = nil
macName = nil
lastSync = nil
suggestedUserCode = ""
@@ -301,17 +591,57 @@ final class AppModel {
func syncNow() { sync.refresh() }
+ /// The plan revision this phone and the Mac last agreed on: tells which side changed it.
+ private var syncedRevision: String? {
+ get { UserDefaults.standard.string(forKey: "syncedPlanRevision") }
+ set { UserDefaults.standard.set(newValue, forKey: "syncedPlanRevision") }
+ }
+
private func received(_ state: SyncState) {
macName = state.macName
lastSync = Date()
UserDefaults.standard.set(lastSync, forKey: "lastSync")
suggestedUserCode = state.userCode
- if let shared = state.connections {
- hub.adoptConnections(shared)
+ if let shared = state.connections, hub.adoptConnections(shared) {
refreshConnections()
+ reloadLinks()
startPolling()
}
+ // Whatever this phone connected (or disconnected) since goes the other way.
+ sync.sendConnections(hub.shareableConnections, userCode: hub.smartLifeUserCode)
sendCatalog()
+ reconcilePlan(with: state)
+ }
+
+ /// Decides which way the floor plan goes: to whichever side did not change it since the
+ /// two last agreed. When both did, the user chooses.
+ private func reconcilePlan(with state: SyncState) {
+ let local = plans.customPlanRevision
+ let remote = state.revision
+ if let local, local == remote {
+ syncedRevision = local
+ planChoice = nil
+ return
+ }
+ guard let local, let localData = try? Data(contentsOf: plans.customPlanURL) else {
+ // Nothing of our own: the Mac's plan, if it has one, is the home.
+ if !remote.isEmpty { adopt(state) }
+ return
+ }
+ if remote.isEmpty || remote == syncedRevision {
+ // Only this phone changed it (or the Mac has none yet): the Mac takes ours.
+ sync.sendPlan(localData)
+ } else if local == syncedRevision {
+ adopt(state)
+ } else if let macPlan = state.plan {
+ let theirs = (try? PlanStore.validate(macPlan))?["name"] as? String ?? "Home"
+ planChoice = PlanChoice(macName: state.macName, macPlanName: theirs,
+ phonePlanName: plans.customPlanName ?? "Home", macPlan: macPlan)
+ }
+ }
+
+ /// Takes the Mac's plan as this phone's home.
+ private func adopt(_ state: SyncState) {
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).
@@ -322,13 +652,34 @@ final class AppModel {
show(Banner(symbol: "exclamationmark.triangle.fill", text: "Could not save the floor plan", tint: Theme.red))
return
}
+ syncedRevision = PlanStore.revision(of: data)
reloadHome()
+ editorWeb?.call("planArrived", plans.customPlan() ?? [:], state.macName)
Haptics.shared.play("success")
show(Banner(symbol: "arrow.triangle.2.circlepath",
text: first ? "\(plans.customPlanName ?? "Your home") arrived from \(state.macName)"
: "Updated from \(state.macName)"))
}
+ /// The answer to a `PlanChoice`.
+ func resolvePlanChoice(keepPhone: Bool) {
+ guard let choice = planChoice else { return }
+ planChoice = nil
+ if keepPhone {
+ if let data = try? Data(contentsOf: plans.customPlanURL), sync.sendPlan(data) {
+ show(Banner(symbol: "arrow.up.circle.fill", text: "Sent to \(choice.macName)"))
+ } else {
+ // Next time the Mac shows this plan unchanged, ours goes over.
+ syncedRevision = PlanStore.revision(of: choice.macPlan)
+ show(Banner(symbol: "exclamationmark.triangle.fill", text: "\(choice.macName) is not connected; it gets your plan next time",
+ tint: Theme.warm))
+ }
+ } else {
+ adopt(SyncState(macName: choice.macName, revision: PlanStore.revision(of: choice.macPlan), plan: choice.macPlan,
+ userCode: suggestedUserCode, smartLifeConnected: false))
+ }
+ }
+
// MARK: - Smart Life
func beginLogin(userCode: String) async throws -> (token: String, qrContent: String) {
@@ -341,6 +692,8 @@ final class AppModel {
smartLifeConnected = hub.isSmartLifeConnected
smartLifeAccount = hub.smartLifeAccount
sync.showQR(nil)
+ sync.sendConnections(hub.shareableConnections, userCode: hub.smartLifeUserCode)
+ editorWeb?.call("servicesChanged", hub.servicesInfo)
Haptics.shared.play("success")
startPolling()
return true
@@ -359,6 +712,48 @@ final class AppModel {
// MARK: - Home Assistant, Hue, Apple Home
+ func connectHomeAssistant(url: String, token: String) async throws {
+ try await hub.connectHomeAssistant(url: url, token: token)
+ connectionsChanged()
+ Haptics.shared.play("success")
+ }
+
+ /// True once paired; false while nobody has pressed the bridge's button yet.
+ func pairHue(host: String, bridgeId: String?, name: String?) async throws -> Bool {
+ do {
+ try await hub.pairHue(host: host, bridgeId: bridgeId, name: name)
+ } catch is HueService.ButtonNotPressed {
+ return false
+ }
+ connectionsChanged()
+ Haptics.shared.play("success")
+ return true
+ }
+
+ func disconnect(service: String) {
+ hub.disconnect(service: service)
+ connectionsChanged()
+ }
+
+ /// A platform was connected or disconnected here: read the devices again, tell the Mac.
+ private func connectionsChanged() {
+ refreshConnections()
+ reloadLinks()
+ startPolling()
+ poll()
+ sync.sendConnections(hub.shareableConnections, userCode: hub.smartLifeUserCode)
+ editorWeb?.call("servicesChanged", hub.servicesInfo)
+ }
+
+ var homeAssistantInfo: [String: Any] { hub.homeAssistant.info }
+
+ /// True when at least one platform's devices can be linked.
+ var hasAnyConnection: Bool {
+ if case .ready = homeKit { return true }
+ return smartLifeConnected || homeAssistantName != nil || hueName != nil
+ }
+ var hueInfo: [String: Any] { hub.hue.info }
+
private func refreshConnections() {
let ha = hub.homeAssistant.info
homeAssistantName = ha["connected"] as? Bool == true ? (ha["name"] as? String ?? "Home Assistant") : nil
@@ -385,6 +780,7 @@ final class AppModel {
refreshConnections()
sendCatalog()
startPolling()
+ editorWeb?.call("servicesChanged", hub.servicesInfo)
if case .ready = homeKit { Haptics.shared.play("success") }
}
}
@@ -406,15 +802,17 @@ final class AppModel {
// MARK: - Welcome, banners
- func finishWelcome(pairing: Bool) {
+ enum WelcomeChoice { case setUpHere, pair, demo }
+
+ func finishWelcome(_ choice: WelcomeChoice) {
UserDefaults.standard.set(true, forKey: "welcomed")
showWelcome = false
- guard pairing else { return }
- settingsPath = [.pairing]
+ guard choice != .demo else { return }
+ if choice == .pair { settingsPath = [.pairing] }
// One sheet has to be gone before the next can come up.
Task { @MainActor in
try? await Task.sleep(nanoseconds: 450_000_000)
- showSettings = true
+ if choice == .pair { showSettings = true } else { showNewHome = true }
}
}
diff --git a/ios/Sources/ConnectionViews.swift b/ios/Sources/ConnectionViews.swift
new file mode 100644
index 0000000..c941705
--- /dev/null
+++ b/ios/Sources/ConnectionViews.swift
@@ -0,0 +1,506 @@
+import SwiftUI
+import HouseCore
+
+/// Connects this iPhone to a Home Assistant server: found on the Wi-Fi by itself or typed
+/// in, plus a long-lived access token. The paired Mac gets the connection too.
+struct HomeAssistantView: View {
+ @Environment(AppModel.self) private var model
+ @Environment(\.insideEditor) private var insideEditor
+ @State private var url = ""
+ @State private var token = ""
+ @State private var found: [[String: Any]] = []
+ @State private var scanning = false
+ @State private var busy = false
+ @State private var problem: String?
+ @State private var confirmDisconnect = false
+ @FocusState private var focus: Field?
+
+ private enum Field { case url, token }
+
+ var body: some View {
+ ScrollView {
+ VStack(spacing: 26) {
+ if let name = model.homeAssistantName {
+ connected(name)
+ } else {
+ discovery
+ form
+ }
+ }
+ .padding(.horizontal, 18)
+ .padding(.top, 8)
+ .padding(.bottom, 32)
+ .animation(.spring(response: 0.45, dampingFraction: 0.85), value: model.homeAssistantName)
+ }
+ .scrollDismissesKeyboard(.interactively)
+ .background(Theme.background)
+ .navigationTitle("Home Assistant")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbarBackground(Theme.background, for: .navigationBar)
+ .task { if model.homeAssistantName == nil { await scan() } }
+ }
+
+ // MARK: - Not connected
+
+ private var discovery: some View {
+ VStack(spacing: 10) {
+ SectionTitle("On this Wi-Fi")
+ Card {
+ if scanning {
+ HStack(spacing: 12) {
+ ProgressView().tint(Theme.muted)
+ Text("Looking for Home Assistant…").font(.system(size: 15)).foregroundStyle(Theme.muted)
+ Spacer()
+ }
+ .padding(.horizontal, 16)
+ .frame(minHeight: 60)
+ } else if found.isEmpty {
+ Text("None found by itself. Type its address below.")
+ .font(.system(size: 15)).foregroundStyle(Theme.muted)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(16)
+ } else {
+ ForEach(Array(found.enumerated()), id: \.offset) { index, server in
+ if index > 0 { RowDivider() }
+ let address = server["url"] as? String ?? ""
+ Button {
+ url = address
+ focus = .token
+ } label: {
+ HStack(spacing: 14) {
+ IconBadge(symbol: "server.rack", tint: ConnectionLook.homeAssistant)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(server["name"] as? String ?? "Home Assistant")
+ .font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ Text(address).font(.system(size: 13.5)).foregroundStyle(Theme.muted).lineLimit(1)
+ }
+ Spacer(minLength: 8)
+ Image(systemName: url == address ? "checkmark.circle.fill" : "circle")
+ .font(.system(size: 22))
+ .foregroundStyle(url == address ? Theme.accent : Theme.faint)
+ }
+ .padding(.horizontal, 14)
+ .frame(minHeight: 66)
+ }
+ .buttonStyle(RowButtonStyle())
+ }
+ }
+ }
+ if !scanning {
+ Button { Task { await scan() } } label: { Label("Look again", systemImage: "dot.radiowaves.left.and.right") }
+ .font(.system(size: 15, weight: .semibold))
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 6)
+ }
+ }
+ }
+
+ private var form: some View {
+ VStack(spacing: 10) {
+ SectionTitle("Connect")
+ Card(padding: 16) {
+ VStack(alignment: .leading, spacing: 14) {
+ InputField(title: "Address", text: $url, prompt: "http://homeassistant.local:8123", focused: focus == .url) {
+ TextField("", text: $url)
+ .keyboardType(.URL)
+ .textContentType(.URL)
+ .focused($focus, equals: .url)
+ .submitLabel(.next)
+ .onSubmit { focus = .token }
+ }
+ InputField(title: "Long-lived access token", text: $token, prompt: "Paste it here", focused: focus == .token) {
+ SecureField("", text: $token)
+ .focused($focus, equals: .token)
+ .submitLabel(.go)
+ .onSubmit(connect)
+ }
+ }
+ }
+ if let problem {
+ ProblemLabel(text: problem)
+ }
+ Button(action: connect) {
+ if busy { ProgressView().tint(.white) } else { Text("Connect") }
+ }
+ .buttonStyle(PrimaryButtonStyle())
+ .disabled(busy || url.trimmingCharacters(in: .whitespaces).isEmpty || token.trimmingCharacters(in: .whitespaces).isEmpty)
+ .padding(.top, 4)
+
+ Card(padding: 16) {
+ VStack(alignment: .leading, spacing: 10) {
+ Label("Where is the token?", systemImage: "questionmark.circle")
+ .font(.system(size: 15, weight: .semibold)).foregroundStyle(Theme.text)
+ Text("In Home Assistant open your profile (your name at the bottom of the sidebar) → **Security**. Under **Long-lived access tokens** tap **Create token**, name it “House Control” and copy it.")
+ .font(.system(size: 14)).foregroundStyle(Theme.muted)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ Footnote(text: "The token stays on this iPhone, in the Keychain, and goes to the Mac you paired, over your encrypted link. Lights, switches, climate devices and temperature sensors can then be linked to your plan.")
+ }
+ }
+
+ private func scan() async {
+ scanning = true
+ found = await ServiceDiscovery.homeAssistants()
+ scanning = false
+ if url.isEmpty, found.count == 1 { url = found[0]["url"] as? String ?? "" }
+ }
+
+ private func connect() {
+ focus = nil
+ busy = true
+ problem = nil
+ Task {
+ defer { busy = false }
+ do {
+ try await model.connectHomeAssistant(url: url, token: token)
+ token = ""
+ } catch {
+ problem = error.localizedDescription
+ Haptics.shared.play("error")
+ }
+ }
+ }
+
+ // MARK: - Connected
+
+ private func connected(_ name: String) -> some View {
+ VStack(spacing: 10) {
+ SectionTitle("Server")
+ Card {
+ HStack(spacing: 14) {
+ IconBadge(symbol: "server.rack", tint: ConnectionLook.homeAssistant)
+ VStack(alignment: .leading, spacing: 3) {
+ Text(name).font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ HStack(spacing: 7) {
+ StatusDot(color: Theme.green)
+ Text(serverLine).font(.system(size: 13.5)).foregroundStyle(Theme.muted).lineLimit(1)
+ }
+ }
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, 14)
+ .frame(minHeight: 70)
+ }
+ if !insideEditor {
+ NavigationLink(value: SettingsRoute.devices) {
+ Label("Link devices to your plan", systemImage: "link")
+ }
+ .buttonStyle(PrimaryButtonStyle())
+ .padding(.top, 6)
+ }
+ Button { confirmDisconnect = true } label: { Text("Disconnect") }
+ .buttonStyle(SecondaryButtonStyle(tint: Theme.red))
+ .confirmationDialog("Disconnect Home Assistant?", isPresented: $confirmDisconnect, titleVisibility: .visible) {
+ Button("Disconnect", role: .destructive) { model.disconnect(service: "homeassistant") }
+ } message: {
+ Text("Its devices go back to being simulated, here and on your paired Mac.")
+ }
+ Footnote(text: "Connected on this iPhone or on your Mac, it works on both: they share the connection over their encrypted link.")
+ }
+ .transition(.opacity)
+ }
+
+ private var serverLine: String {
+ let info = model.homeAssistantInfo
+ return [info["url"] as? String, (info["version"] as? String).flatMap { $0.isEmpty ? nil : "version \($0)" }]
+ .compactMap { $0 }.joined(separator: " · ")
+ }
+}
+
+/// Pairs this iPhone with a Philips Hue Bridge: pick it, press its round button.
+struct HueView: View {
+ @Environment(AppModel.self) private var model
+ @Environment(\.insideEditor) private var insideEditor
+ @State private var found: [[String: Any]] = []
+ @State private var scanning = false
+ @State private var host = ""
+ @State private var pairing: [String: Any]?
+ @State private var secondsLeft = 0
+ @State private var problem: String?
+ @State private var confirmDisconnect = false
+ @FocusState private var typing: Bool
+
+ var body: some View {
+ ScrollView {
+ VStack(spacing: 26) {
+ if let name = model.hueName {
+ connected(name)
+ } else if let pairing {
+ press(pairing)
+ } else {
+ discovery
+ manual
+ }
+ }
+ .padding(.horizontal, 18)
+ .padding(.top, 8)
+ .padding(.bottom, 32)
+ .animation(.spring(response: 0.45, dampingFraction: 0.85), value: model.hueName)
+ .animation(.spring(response: 0.45, dampingFraction: 0.85), value: pairing != nil)
+ }
+ .scrollDismissesKeyboard(.interactively)
+ .background(Theme.background)
+ .navigationTitle("Philips Hue")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbarBackground(Theme.background, for: .navigationBar)
+ .task { if model.hueName == nil { await scan() } }
+ // While waiting for the button: ask the bridge every two seconds, for a minute.
+ .task(id: pairing.map { $0["host"] as? String ?? "" }) {
+ guard let bridge = pairing else { return }
+ for left in stride(from: 60, through: 0, by: -2) {
+ secondsLeft = left
+ do {
+ if try await model.pairHue(host: bridge["host"] as? String ?? "", bridgeId: bridge["bridgeId"] as? String,
+ name: bridge["name"] as? String) {
+ pairing = nil
+ return
+ }
+ } catch {
+ problem = error.localizedDescription
+ pairing = nil
+ Haptics.shared.play("error")
+ return
+ }
+ try? await Task.sleep(nanoseconds: 2_000_000_000)
+ if Task.isCancelled { return }
+ }
+ problem = "Nobody pressed the button in time. Try again."
+ pairing = nil
+ }
+ }
+
+ private var discovery: some View {
+ VStack(spacing: 10) {
+ SectionTitle("On this Wi-Fi")
+ Card {
+ if scanning {
+ HStack(spacing: 12) {
+ ProgressView().tint(Theme.muted)
+ Text("Looking for Hue Bridges…").font(.system(size: 15)).foregroundStyle(Theme.muted)
+ Spacer()
+ }
+ .padding(.horizontal, 16)
+ .frame(minHeight: 60)
+ } else if found.isEmpty {
+ Text("No bridge found by itself. Type its address below — the Hue app shows it under Settings → My Hue System.")
+ .font(.system(size: 15)).foregroundStyle(Theme.muted)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(16)
+ } else {
+ ForEach(Array(found.enumerated()), id: \.offset) { index, bridge in
+ if index > 0 { RowDivider() }
+ HStack(spacing: 14) {
+ IconBadge(symbol: "lightbulb.led.fill", tint: ConnectionLook.hue)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(bridge["name"] as? String ?? "Hue Bridge")
+ .font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ Text(bridge["host"] as? String ?? "").font(.system(size: 13.5)).foregroundStyle(Theme.muted)
+ }
+ Spacer(minLength: 8)
+ Button("Pair") { start(bridge) }.buttonStyle(PillButtonStyle())
+ }
+ .padding(.horizontal, 14)
+ .frame(minHeight: 66)
+ }
+ }
+ }
+ if let problem { ProblemLabel(text: problem) }
+ if !scanning {
+ Button { Task { await scan() } } label: { Label("Look again", systemImage: "dot.radiowaves.left.and.right") }
+ .font(.system(size: 15, weight: .semibold))
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 6)
+ }
+ }
+ }
+
+ private var manual: some View {
+ VStack(spacing: 10) {
+ SectionTitle("Or by address")
+ Card(padding: 16) {
+ InputField(title: "Bridge address", text: $host, prompt: "e.g. 192.168.1.20", focused: typing) {
+ TextField("", text: $host)
+ .keyboardType(.numbersAndPunctuation)
+ .focused($typing)
+ .submitLabel(.go)
+ .onSubmit { start(["host": host.trimmingCharacters(in: .whitespaces), "name": "Hue Bridge"]) }
+ }
+ }
+ Button { start(["host": host.trimmingCharacters(in: .whitespaces), "name": "Hue Bridge"]) } label: { Text("Pair") }
+ .buttonStyle(SecondaryButtonStyle())
+ .disabled(host.trimmingCharacters(in: .whitespaces).isEmpty)
+ Footnote(text: "No account needed: the bridge lets one app in when its button is pressed. The key it gives stays on this iPhone and your paired Mac.")
+ }
+ }
+
+ private func press(_ bridge: [String: Any]) -> some View {
+ VStack(spacing: 22) {
+ ZStack {
+ Circle().fill(Theme.surfaceHigh).frame(width: 150, height: 150)
+ Circle().strokeBorder(ConnectionLook.hue.opacity(0.7), lineWidth: 3).frame(width: 150, height: 150)
+ .phaseAnimator([1.0, 1.12]) { view, scale in view.scaleEffect(scale).opacity(2 - scale) }
+ animation: { _ in .easeInOut(duration: 1.1) }
+ Circle().fill(Color.white.opacity(0.9)).frame(width: 56, height: 56)
+ .shadow(color: ConnectionLook.hue.opacity(0.8), radius: 18)
+ }
+ .padding(.top, 30)
+ .accessibilityHidden(true)
+ Text("Press the round button on the bridge")
+ .font(.system(size: 22, weight: .bold)).foregroundStyle(Theme.text)
+ .multilineTextAlignment(.center)
+ Text("\(bridge["name"] as? String ?? "Hue Bridge") · waiting \(secondsLeft) s")
+ .font(.system(size: 15)).foregroundStyle(Theme.muted)
+ .contentTransition(.numericText(countsDown: true))
+ .animation(.default, value: secondsLeft)
+ Button("Cancel") { pairing = nil }
+ .buttonStyle(SecondaryButtonStyle())
+ .padding(.top, 10)
+ }
+ }
+
+ private func start(_ bridge: [String: Any]) {
+ typing = false
+ problem = nil
+ pairing = bridge
+ }
+
+ private func scan() async {
+ scanning = true
+ found = await ServiceDiscovery.hueBridges()
+ scanning = false
+ }
+
+ private func connected(_ name: String) -> some View {
+ VStack(spacing: 10) {
+ SectionTitle("Bridge")
+ Card {
+ HStack(spacing: 14) {
+ IconBadge(symbol: "lightbulb.led.fill", tint: ConnectionLook.hue)
+ VStack(alignment: .leading, spacing: 3) {
+ Text(name).font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ HStack(spacing: 7) {
+ StatusDot(color: Theme.green)
+ Text(model.hueInfo["host"] as? String ?? "").font(.system(size: 13.5)).foregroundStyle(Theme.muted)
+ }
+ }
+ Spacer(minLength: 0)
+ }
+ .padding(.horizontal, 14)
+ .frame(minHeight: 70)
+ }
+ if !insideEditor {
+ NavigationLink(value: SettingsRoute.devices) {
+ Label("Link devices to your plan", systemImage: "link")
+ }
+ .buttonStyle(PrimaryButtonStyle())
+ .padding(.top, 6)
+ }
+ Button { confirmDisconnect = true } label: { Text("Disconnect") }
+ .buttonStyle(SecondaryButtonStyle(tint: Theme.red))
+ .confirmationDialog("Disconnect the Hue Bridge?", isPresented: $confirmDisconnect, titleVisibility: .visible) {
+ Button("Disconnect", role: .destructive) { model.disconnect(service: "hue") }
+ } message: {
+ Text("Its lamps go back to being simulated, here and on your paired Mac.")
+ }
+ }
+ .transition(.opacity)
+ }
+}
+
+// MARK: - Shared pieces
+
+extension EnvironmentValues {
+ /// True on the connection screens opened from inside the editor, where the plan is being
+ /// edited already (and "Devices" would change it behind the editor's back).
+ @Entry var insideEditor = false
+}
+
+enum ConnectionLook {
+ static let smartLife = Color(red: 1, green: 0.48, blue: 0.24)
+ static let homeAssistant = Color(red: 0.09, green: 0.74, blue: 0.95)
+ static let hue = Color(red: 0.76, green: 0.55, blue: 1)
+ static let homeKit = Color(red: 1, green: 0.7, blue: 0.25)
+
+ static func tint(_ service: String) -> Color {
+ switch service {
+ case "smartlife": smartLife
+ case "homeassistant": homeAssistant
+ case "hue": hue
+ default: homeKit
+ }
+ }
+
+ static func symbol(_ service: String) -> String {
+ switch service {
+ case "smartlife": "powerplug.fill"
+ case "homeassistant": "server.rack"
+ case "hue": "lightbulb.led.fill"
+ default: "homekit"
+ }
+ }
+
+ static func title(_ service: String) -> String {
+ switch service {
+ case "smartlife": "Smart Life"
+ case "homeassistant": "Home Assistant"
+ case "hue": "Philips Hue"
+ default: "Apple Home"
+ }
+ }
+}
+
+/// A labelled text field in the style of the Smart Life screen.
+struct InputField<Field: View>: View {
+ let title: String
+ @Binding var text: String
+ let prompt: String
+ let focused: Bool
+ @ViewBuilder var field: Field
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text(title).font(.system(size: 13, weight: .semibold)).foregroundStyle(Theme.muted)
+ ZStack(alignment: .leading) {
+ if text.isEmpty {
+ Text(prompt).font(.system(size: 17)).foregroundStyle(Theme.faint).allowsHitTesting(false)
+ }
+ field
+ .font(.system(size: 17))
+ .foregroundStyle(Theme.text)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ }
+ .padding(.horizontal, 14)
+ .frame(height: 50)
+ .background(Color.black.opacity(0.3), in: RoundedRectangle(cornerRadius: 14, style: .continuous))
+ .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(focused ? Theme.accent : Theme.line))
+ }
+ }
+}
+
+struct ProblemLabel: View {
+ let text: String
+
+ var body: some View {
+ Label(text, systemImage: "exclamationmark.triangle.fill")
+ .font(.system(size: 14, weight: .medium))
+ .foregroundStyle(Theme.red)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 6)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+}
+
+struct Footnote: View {
+ let text: String
+
+ var body: some View {
+ Text(text)
+ .font(.system(size: 13))
+ .foregroundStyle(Theme.faint)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 6)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+}
diff --git a/ios/Sources/DevicesView.swift b/ios/Sources/DevicesView.swift
new file mode 100644
index 0000000..b47ff5a
--- /dev/null
+++ b/ios/Sources/DevicesView.swift
@@ -0,0 +1,398 @@
+import SwiftUI
+import HouseCore
+
+/// A device of a connected platform, as `DeviceHub.allDevices` lists it.
+struct RealDevice: Identifiable, Hashable {
+ let raw: [String: Any]
+ var service: String { raw["service"] as? String ?? "" }
+ var deviceId: String { raw["id"] as? String ?? "" }
+ var id: String { "\(service)|\(deviceId)" }
+ var ref: PlanEditor.DeviceRef { .init(service: service, id: deviceId) }
+ var name: String { raw["name"] as? String ?? deviceId }
+ var kind: String { raw["kind"] as? String ?? "light" }
+ var online: Bool { raw["online"] as? Bool ?? true }
+ var room: String? { (raw["room"] as? String).flatMap { $0.isEmpty ? nil : $0 } }
+ var detail: String { [room, raw["detail"] as? String].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ") }
+
+ static func == (a: RealDevice, b: RealDevice) -> Bool { a.id == b.id }
+ func hash(into hasher: inout Hasher) { hasher.combine(id) }
+}
+
+/// Loads the devices of every connected platform once per screen.
+@MainActor
+@Observable
+final class DeviceCatalog {
+ private(set) var devices: [RealDevice] = []
+ private(set) var errors: [String: String] = [:]
+ private(set) var loading = false
+ private(set) var loaded = false
+
+ func load(_ model: AppModel) async {
+ loading = true
+ let (list, problems) = await model.allDevices()
+ devices = list.map(RealDevice.init(raw:)).sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
+ errors = problems
+ loading = false
+ loaded = true
+ }
+
+ func device(_ ref: PlanEditor.DeviceRef?) -> RealDevice? {
+ guard let ref else { return nil }
+ return devices.first { $0.ref == ref }
+ }
+}
+
+/// Every lamp and AC of the plan and the real device it is linked to; tapping one picks
+/// its device from the list of everything the connected platforms have.
+struct DevicesView: View {
+ @Environment(AppModel.self) private var model
+ @State private var catalog = DeviceCatalog()
+ @State private var picking: PlanEditor.Item?
+ @State private var pickingSensor: PlanEditor.Item?
+ @State private var adding = false
+
+ private var editor: PlanEditor? { model.currentPlan.map(PlanEditor.init(plan:)) }
+
+ var body: some View {
+ ScrollView {
+ VStack(spacing: 26) {
+ if !model.hasAnyConnection {
+ noConnections
+ } else if let errors = errorText {
+ ProblemLabel(text: errors)
+ }
+ if let editor {
+ ForEach(editor.rooms) { room in
+ let items = editor.items.filter { $0.room == room.id }
+ if !items.isEmpty { roomSection(room, items) }
+ }
+ if editor.items.isEmpty {
+ Card(padding: 16) {
+ Text("This home has no lamps or air conditioners yet. Add your devices to a room, or draw them in the editor.")
+ .font(.system(size: 15)).foregroundStyle(Theme.muted)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+ if model.hasAnyConnection {
+ Button { adding = true } label: { Label("Add devices to a room", systemImage: "plus") }
+ .buttonStyle(PrimaryButtonStyle())
+ .disabled(!catalog.loaded)
+ }
+ Footnote(text: model.activePlan != "custom"
+ ? "Linking a device turns this demo into your own home, saved on this iPhone."
+ : model.macName.map { "Changes are saved at once and reach \($0)." } ?? "Changes are saved at once.")
+ }
+ .padding(.horizontal, 18)
+ .padding(.top, 8)
+ .padding(.bottom, 32)
+ }
+ .background(Theme.background)
+ .navigationTitle("Devices")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbarBackground(Theme.background, for: .navigationBar)
+ .toolbar {
+ ToolbarItem(placement: .primaryAction) {
+ if catalog.loading { ProgressView().tint(Theme.muted) }
+ }
+ }
+ .refreshable { await catalog.load(model) }
+ .task { if !catalog.loaded { await catalog.load(model) } }
+ .sheet(item: $picking) { item in
+ DevicePicker(title: item.name, kind: item.kind == .ac ? "ac" : "light", current: item.link,
+ used: editor?.usedDevices ?? [:], catalog: catalog) { device in
+ model.editPlan { $0.link(item.id, to: device?.raw) }
+ Haptics.shared.play("success")
+ }
+ }
+ .sheet(item: $pickingSensor) { item in
+ DevicePicker(title: "\(item.name) · room temperature", kind: "sensor", current: item.sensor,
+ used: editor?.usedDevices ?? [:], catalog: catalog,
+ include: { $0.service != "smartlife" || item.link?.service == "smartlife" }) { device in
+ model.editPlan { $0.setSensor(item.id, to: device?.raw) }
+ Haptics.shared.play("success")
+ }
+ }
+ .sheet(isPresented: $adding) {
+ AddDevicesView(catalog: catalog, used: editor?.usedDevices ?? [:], rooms: editor?.rooms ?? [])
+ }
+ }
+
+ private var errorText: String? {
+ let list = catalog.errors.map { "\(ConnectionLook.title($0.key)): \($0.value)" }
+ return list.isEmpty ? nil : list.sorted().joined(separator: "\n")
+ }
+
+ private var noConnections: some View {
+ Card(padding: 16) {
+ HStack(alignment: .top, spacing: 14) {
+ IconBadge(symbol: "link", tint: Theme.warm)
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Nothing connected yet").font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ Text("Connect Smart Life, Home Assistant, Philips Hue or Apple Home in Settings first; their devices then appear here to choose from.")
+ .font(.system(size: 14)).foregroundStyle(Theme.muted)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ }
+ }
+
+ private func roomSection(_ room: PlanEditor.Room, _ items: [PlanEditor.Item]) -> some View {
+ VStack(spacing: 10) {
+ SectionTitle(room.name)
+ Card {
+ ForEach(Array(items.enumerated()), id: \.element.id) { index, item in
+ if index > 0 { RowDivider() }
+ Button { if model.hasAnyConnection { picking = item } } label: { row(item) }
+ .buttonStyle(RowButtonStyle())
+ .disabled(!model.hasAnyConnection)
+ if item.kind == .ac, model.hasAnyConnection {
+ Button { pickingSensor = item } label: { sensorRow(item) }
+ .buttonStyle(RowButtonStyle())
+ }
+ }
+ }
+ }
+ }
+
+ private func row(_ item: PlanEditor.Item) -> some View {
+ let device = catalog.device(item.link)
+ return HStack(spacing: 14) {
+ IconBadge(symbol: item.kind == .ac ? "air.conditioner.horizontal.fill" : "lightbulb.fill",
+ tint: item.link == nil ? Theme.muted : (item.kind == .ac ? Theme.accent : Theme.warm))
+ VStack(alignment: .leading, spacing: 3) {
+ Text(item.name).font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text).lineLimit(1)
+ HStack(spacing: 6) {
+ if let link = item.link {
+ Image(systemName: ConnectionLook.symbol(link.service))
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(ConnectionLook.tint(link.service))
+ Text(device?.name ?? (catalog.loaded ? "Not found right now" : ConnectionLook.title(link.service)))
+ .foregroundStyle(device == nil && catalog.loaded ? Theme.red : Theme.muted)
+ if let device, !device.online { Text("· offline").foregroundStyle(Theme.red) }
+ } else {
+ Text("Simulated").foregroundStyle(Theme.faint)
+ }
+ }
+ .font(.system(size: 13.5))
+ .lineLimit(1)
+ }
+ Spacer(minLength: 8)
+ Image(systemName: "chevron.right").font(.system(size: 14, weight: .semibold)).foregroundStyle(Theme.faint)
+ }
+ .padding(.horizontal, 14)
+ .frame(minHeight: 66)
+ .accessibilityElement(children: .combine)
+ .accessibilityHint("Choose the real device")
+ }
+
+ private func sensorRow(_ item: PlanEditor.Item) -> some View {
+ HStack(spacing: 10) {
+ Image(systemName: "thermometer.medium").font(.system(size: 13, weight: .semibold)).foregroundStyle(Theme.muted)
+ Text("Room temperature").font(.system(size: 14)).foregroundStyle(Theme.muted)
+ Spacer(minLength: 8)
+ Text(catalog.device(item.sensor)?.name ?? (item.sensor == nil ? "Estimated" : "Not found right now"))
+ .font(.system(size: 14)).foregroundStyle(Theme.faint).lineLimit(1)
+ Image(systemName: "chevron.right").font(.system(size: 12, weight: .semibold)).foregroundStyle(Theme.faint)
+ }
+ .padding(.leading, 66)
+ .padding(.trailing, 14)
+ .frame(minHeight: 40)
+ .padding(.bottom, 6)
+ }
+}
+
+/// The list of real devices of one kind to link a lamp, an AC or a thermometer to.
+struct DevicePicker: View {
+ @Environment(\.dismiss) private var dismiss
+ let title: String
+ let kind: String
+ let current: PlanEditor.DeviceRef?
+ let used: [PlanEditor.DeviceRef: String]
+ let catalog: DeviceCatalog
+ var include: (RealDevice) -> Bool = { _ in true }
+ let choose: (RealDevice?) -> Void
+ @State private var search = ""
+
+ private var candidates: [RealDevice] {
+ catalog.devices.filter { $0.kind == kind && include($0) }
+ .filter { search.isEmpty || $0.name.localizedCaseInsensitiveContains(search) || ($0.room ?? "").localizedCaseInsensitiveContains(search) }
+ }
+
+ var body: some View {
+ NavigationStack {
+ List {
+ Section {
+ option(nil, name: kind == "sensor" ? "None — estimated" : "Not linked — simulated", detail: nil, symbol: "circle.dashed")
+ }
+ ForEach(["smartlife", "homeassistant", "hue", "homekit"], id: \.self) { service in
+ let list = candidates.filter { $0.service == service }
+ if !list.isEmpty {
+ Section(ConnectionLook.title(service)) {
+ ForEach(list) { device in
+ option(device, name: device.name, detail: detailLine(device), symbol: ConnectionLook.symbol(service))
+ }
+ }
+ }
+ }
+ if catalog.loaded, candidates.isEmpty {
+ Section {
+ Text(search.isEmpty ? "None of your connected platforms has a device of this kind." : "Nothing matches “\(search)”.")
+ .foregroundStyle(Theme.muted)
+ }
+ }
+ }
+ .scrollContentBackground(.hidden)
+ .background(Theme.background)
+ .searchable(text: $search, placement: .navigationBarDrawer(displayMode: .always), prompt: "Search devices")
+ .navigationTitle(title)
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
+ }
+ .overlay { if catalog.loading && !catalog.loaded { ProgressView().tint(Theme.muted) } }
+ }
+ .presentationBackground(Theme.background)
+ .presentationDragIndicator(.visible)
+ .preferredColorScheme(.dark)
+ }
+
+ private func detailLine(_ device: RealDevice) -> String? {
+ var parts = [device.detail]
+ if !device.online { parts.append("offline") }
+ if let user = used[device.ref], device.ref != current { parts.append("used by \(user)") }
+ let line = parts.filter { !$0.isEmpty }.joined(separator: " · ")
+ return line.isEmpty ? nil : line
+ }
+
+ private func option(_ device: RealDevice?, name: String, detail: String?, symbol: String) -> some View {
+ let selected = device?.ref == current
+ return Button {
+ choose(device)
+ dismiss()
+ } label: {
+ HStack(spacing: 12) {
+ Image(systemName: symbol)
+ .font(.system(size: 15, weight: .semibold))
+ .foregroundStyle(device.map { ConnectionLook.tint($0.service) } ?? Theme.muted)
+ .frame(width: 26)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(name).foregroundStyle(device?.online == false ? Theme.muted : Theme.text)
+ if let detail { Text(detail).font(.system(size: 13)).foregroundStyle(Theme.faint).lineLimit(2) }
+ }
+ Spacer(minLength: 8)
+ if selected { Image(systemName: "checkmark").font(.system(size: 15, weight: .bold)).foregroundStyle(Theme.accent) }
+ }
+ .contentShape(Rectangle())
+ }
+ .listRowBackground(Theme.surface)
+ .accessibilityAddTraits(selected ? .isSelected : [])
+ }
+}
+
+/// Picks real devices that are not in the plan yet and puts them into a room, linked.
+struct AddDevicesView: View {
+ @Environment(AppModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+ let catalog: DeviceCatalog
+ let used: [PlanEditor.DeviceRef: String]
+ let rooms: [PlanEditor.Room]
+ @State private var chosen: Set<String> = []
+ @State private var room = ""
+ @State private var newRoom = ""
+ @State private var showAll = false
+
+ private static let newRoomTag = "\u{0}new"
+
+ private var candidates: [RealDevice] {
+ catalog.devices.filter { $0.kind != "sensor" && (showAll || used[$0.ref] == nil) }
+ }
+
+ var body: some View {
+ NavigationStack {
+ List {
+ Section {
+ Picker("Room", selection: $room) {
+ ForEach(rooms) { Text($0.name).tag($0.id) }
+ Text("New room…").tag(Self.newRoomTag)
+ }
+ .tint(Theme.accent)
+ if room == Self.newRoomTag {
+ TextField("Room name", text: $newRoom)
+ .textInputAutocapitalization(.words)
+ }
+ } footer: {
+ Text("They are spread over the room; drag them into place later in the editor.")
+ }
+ .listRowBackground(Theme.surface)
+
+ ForEach(["light", "ac"], id: \.self) { kind in
+ let list = candidates.filter { $0.kind == kind }
+ if !list.isEmpty {
+ Section(kind == "ac" ? "Air conditioners" : "Lights and plugs") {
+ ForEach(list) { device in row(device) }
+ }
+ }
+ }
+ Section {
+ Toggle("Show devices already in the plan", isOn: $showAll).tint(Theme.accent)
+ }
+ .listRowBackground(Theme.surface)
+ }
+ .scrollContentBackground(.hidden)
+ .background(Theme.background)
+ .navigationTitle("Add devices")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
+ ToolbarItem(placement: .confirmationAction) {
+ Button(chosen.isEmpty ? "Add" : "Add \(chosen.count)") { add() }
+ .fontWeight(.semibold)
+ .disabled(chosen.isEmpty || (room == Self.newRoomTag && newRoom.trimmingCharacters(in: .whitespaces).isEmpty))
+ }
+ }
+ .onAppear { if room.isEmpty { room = rooms.first?.id ?? Self.newRoomTag } }
+ }
+ .presentationBackground(Theme.background)
+ .presentationDragIndicator(.visible)
+ .preferredColorScheme(.dark)
+ }
+
+ private func row(_ device: RealDevice) -> some View {
+ let on = chosen.contains(device.id)
+ return Button {
+ if on { chosen.remove(device.id) } else { chosen.insert(device.id) }
+ Haptics.shared.play("tick")
+ } label: {
+ HStack(spacing: 12) {
+ Image(systemName: on ? "checkmark.circle.fill" : "circle")
+ .font(.system(size: 22))
+ .foregroundStyle(on ? Theme.accent : Theme.faint)
+ .contentTransition(.symbolEffect(.replace))
+ VStack(alignment: .leading, spacing: 2) {
+ Text(device.name).foregroundStyle(Theme.text)
+ Text([ConnectionLook.title(device.service), device.detail, device.online ? nil : "offline",
+ used[device.ref].map { "in the plan as \($0)" }]
+ .compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · "))
+ .font(.system(size: 13)).foregroundStyle(Theme.faint).lineLimit(2)
+ }
+ Spacer(minLength: 0)
+ }
+ .contentShape(Rectangle())
+ }
+ .listRowBackground(Theme.surface)
+ .accessibilityAddTraits(on ? .isSelected : [])
+ }
+
+ private func add() {
+ let devices = catalog.devices.filter { chosen.contains($0.id) }.map(\.raw)
+ let name = newRoom.trimmingCharacters(in: .whitespaces)
+ let target = room
+ model.editPlan { editor in
+ let id = target == Self.newRoomTag ? editor.addRoom(named: name) : target
+ editor.add(devices, to: id)
+ }
+ Haptics.shared.play("success")
+ dismiss()
+ }
+}
diff --git a/ios/Sources/EditorScreen.swift b/ios/Sources/EditorScreen.swift
new file mode 100644
index 0000000..412db70
--- /dev/null
+++ b/ios/Sources/EditorScreen.swift
@@ -0,0 +1,77 @@
+import SwiftUI
+import UniformTypeIdentifiers
+
+/// The home editor, full screen: the same web editor as the Mac's, laid out for a phone.
+/// Connections open as native sheets on top of it; files go through the system pickers.
+struct EditorScreen: View {
+ @Environment(AppModel.self) private var model
+
+ var body: some View {
+ @Bindable var model = model
+ ZStack {
+ Theme.background.ignoresSafeArea()
+ if let web = model.editorWeb {
+ HomeWebView(web: web).ignoresSafeArea()
+ }
+ }
+ .sheet(item: $model.editorSheet, onDismiss: { model.editorSheetClosed() }) { route in
+ NavigationStack {
+ Group {
+ switch route {
+ case .smartLife: SmartLifeView()
+ case .homeAssistant: HomeAssistantView()
+ case .hue: HueView()
+ default: EmptyView()
+ }
+ }
+ .toolbar {
+ ToolbarItem(placement: .confirmationAction) {
+ Button("Done") { model.editorSheet = nil }.fontWeight(.semibold)
+ }
+ }
+ }
+ .environment(\.insideEditor, true)
+ .presentationBackground(Theme.background)
+ .presentationDragIndicator(.visible)
+ .preferredColorScheme(.dark)
+ }
+ .fileImporter(isPresented: $model.editorImporting, allowedContentTypes: [.json], allowsMultipleSelection: false) { result in
+ model.editorImported(result.map { $0.first }.flatMap { url in url.map { .success($0) } ?? .failure(CocoaError(.userCancelled)) })
+ } onCancellation: {
+ model.editorImported(nil)
+ }
+ .fileExporter(isPresented: Binding(get: { model.editorExport != nil }, set: { if !$0 { model.editorExported(false) } }),
+ document: model.editorExport, contentType: .json,
+ defaultFilename: model.editorExport?.filename) { result in
+ model.editorExported((try? result.get()) != nil)
+ }
+ .preferredColorScheme(.dark)
+ .statusBarHidden(false)
+ }
+}
+
+/// A floor plan file for the system's "Save to Files".
+struct PlanFile: FileDocument {
+ static var readableContentTypes: [UTType] { [.json] }
+ let data: Data
+ let name: String
+
+ var filename: String {
+ let safe = name.lowercased().map { $0.isLetter || $0.isNumber ? String($0) : "-" }.joined()
+ return safe.split(separator: "-").joined(separator: "-").isEmpty ? "home.json" : "\(safe.split(separator: "-").joined(separator: "-")).json"
+ }
+
+ init(data: Data, name: String) {
+ self.data = data
+ self.name = name
+ }
+
+ init(configuration: ReadConfiguration) throws {
+ data = configuration.file.regularFileContents ?? Data()
+ name = "Home"
+ }
+
+ func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
+ FileWrapper(regularFileWithContents: data)
+ }
+}
diff --git a/ios/Sources/HomeWeb.swift b/ios/Sources/HomeWeb.swift
index cc9fa35..3c4da20 100644
--- a/ios/Sources/HomeWeb.swift
+++ b/ios/Sources/HomeWeb.swift
@@ -3,11 +3,13 @@ import WebKit
import OSLog
import HouseCore
-/// The WKWebView that shows the 3D home and its panel, plus the JSON bridge in both
-/// directions. It is the same web UI the Mac app shows in its menu bar popover.
+/// A WKWebView showing the web UI, plus the JSON bridge in both directions: the 3D home and
+/// its panel ("panel", the same page the Mac shows in its menu bar popover) or the home
+/// editor ("editor", the Mac's editor window laid out for a phone).
@MainActor
final class HomeWeb: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
let webView: WKWebView
+ let mode: String
var onMessage: (([String: Any]) -> Void)?
private var boot: () -> [String: Any] = { [:] }
/// Set by the page's "ready" message; a load that never gets there is retried.
@@ -20,7 +22,8 @@ final class HomeWeb: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
(Bundle.main.resourceURL ?? URL(fileURLWithPath: ".")).appendingPathComponent("dist")
}
- init(persistent: Bool) {
+ init(persistent: Bool, mode: String = "panel") {
+ self.mode = mode
let config = WKWebViewConfiguration()
config.setURLSchemeHandler(AssetSchemeHandler(root: Self.assetRoot), forURLScheme: AssetSchemeHandler.scheme)
config.allowsInlineMediaPlayback = true
@@ -34,6 +37,8 @@ final class HomeWeb: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
webView.backgroundColor = UIColor(Theme.background)
webView.scrollView.backgroundColor = UIColor(Theme.background)
webView.scrollView.isScrollEnabled = false
+ // The editor's text fields must not zoom the page in, nor drag it about.
+ webView.scrollView.pinchGestureRecognizer?.isEnabled = false
webView.scrollView.bounces = false
webView.scrollView.contentInsetAdjustmentBehavior = .never
webView.allowsLinkPreview = false
@@ -51,12 +56,12 @@ final class HomeWeb: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
let controller = webView.configuration.userContentController
controller.removeAllUserScripts()
var payload = boot()
- payload["mode"] = "panel"
+ payload["mode"] = mode
payload["platform"] = "ios"
controller.addUserScript(WKUserScript(source: "window.__HOUSE_BOOT__ = \(WebJSON.literal(payload));",
injectionTime: .atDocumentStart, forMainFrameOnly: true))
controller.addUserScript(WKUserScript(source: Self.errorReporter, injectionTime: .atDocumentStart, forMainFrameOnly: true))
- webView.load(URLRequest(url: URL(string: "\(AssetSchemeHandler.indexURL)?mode=panel")!))
+ webView.load(URLRequest(url: URL(string: "\(AssetSchemeHandler.indexURL)?mode=\(mode)")!))
// Right after a cold boot WebKit's processes can be slow enough to drop the first
// load; a page that has not reported in is loaded again, a couple of times at most.
@@ -80,6 +85,13 @@ final class HomeWeb: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
})();
"""
+ /// Stops the page from talking back (the message handler holds on to this object).
+ func detach() {
+ watchdog?.cancel()
+ webView.configuration.userContentController.removeScriptMessageHandler(forName: "house")
+ webView.stopLoading()
+ }
+
/// Calls `window.house.<function>(…args)` in the page.
func call(_ function: String, _ args: Any...) {
webView.evaluateJavaScript(WebJSON.call(function, args), completionHandler: nil)
@@ -94,7 +106,7 @@ final class HomeWeb: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
MainActor.assumeIsolated {
guard let body = message.body as? [String: Any] else { return }
if body["type"] as? String == "log" {
- Logger(subsystem: Bundle.main.bundleIdentifier ?? "HouseControl", category: "web").error("\(body["text"] as? String ?? "", privacy: .public)")
+ Logger(subsystem: Bundle.main.bundleIdentifier ?? "HouseControl", category: "web-\(mode)").error("\(body["text"] as? String ?? "", privacy: .public)")
return
}
if body["type"] as? String == "ready" {
diff --git a/ios/Sources/NewHomeView.swift b/ios/Sources/NewHomeView.swift
new file mode 100644
index 0000000..d97df7c
--- /dev/null
+++ b/ios/Sources/NewHomeView.swift
@@ -0,0 +1,95 @@
+import SwiftUI
+
+/// Starts the user's own home on this phone: a name and something to start drawing from.
+struct NewHomeView: View {
+ @Environment(AppModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+ @State private var name = "My home"
+ @State private var template: String? = nil
+ @State private var confirmReplace = false
+ @FocusState private var typing: Bool
+
+ private let templates: [(id: String?, title: String, detail: String, symbol: String)] = [
+ (nil, "One room", "Draw the rest yourself, or add your devices to it", "square.dashed"),
+ ("studio", "Studio layout", "3 rooms with furniture, to adapt", "square.split.bottomrightquarter.fill"),
+ ("home", "Apartment layout", "5 rooms with furniture, to adapt", "building.2.fill"),
+ ]
+
+ var body: some View {
+ NavigationStack {
+ ScrollView {
+ VStack(spacing: 26) {
+ VStack(spacing: 10) {
+ SectionTitle("Name")
+ Card(padding: 16) {
+ InputField(title: "What do you call it?", text: $name, prompt: "My home", focused: typing) {
+ TextField("", text: $name)
+ .textInputAutocapitalization(.words)
+ .focused($typing)
+ .submitLabel(.done)
+ }
+ }
+ }
+ VStack(spacing: 10) {
+ SectionTitle("Start from")
+ Card {
+ ForEach(Array(templates.enumerated()), id: \.offset) { index, option in
+ if index > 0 { RowDivider() }
+ Button { template = option.id } label: {
+ HStack(spacing: 14) {
+ IconBadge(symbol: option.symbol, tint: option.id == nil ? Theme.warm : Theme.accent)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(option.title).font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ Text(option.detail).font(.system(size: 13.5)).foregroundStyle(Theme.muted)
+ }
+ Spacer(minLength: 8)
+ Image(systemName: template == option.id ? "checkmark.circle.fill" : "circle")
+ .font(.system(size: 22))
+ .foregroundStyle(template == option.id ? Theme.accent : Theme.faint)
+ .contentTransition(.symbolEffect(.replace))
+ }
+ .padding(.horizontal, 14)
+ .frame(minHeight: 66)
+ }
+ .buttonStyle(RowButtonStyle())
+ .accessibilityAddTraits(template == option.id ? .isSelected : [])
+ }
+ }
+ Footnote(text: "The editor opens next: drag rooms and lamps with a finger, pinch to zoom. Lamps and air conditioners stay simulated until you link them to your real devices.")
+ }
+ Button {
+ if model.hasCustomPlan { confirmReplace = true } else { create() }
+ } label: { Label("Create and edit", systemImage: "pencil.and.ruler.fill") }
+ .buttonStyle(PrimaryButtonStyle())
+ .disabled(name.trimmingCharacters(in: .whitespaces).isEmpty)
+ .confirmationDialog("Replace \(model.customPlanName ?? "your home")?", isPresented: $confirmReplace, titleVisibility: .visible) {
+ Button("Replace", role: .destructive) { create() }
+ } message: {
+ Text(model.macName == nil
+ ? "This iPhone keeps one home of your own. Export the current one from the editor first if you want to keep it."
+ : "This iPhone keeps one home of your own, and \(model.macName ?? "your Mac") gets the new one too.")
+ }
+ }
+ .padding(.horizontal, 18)
+ .padding(.top, 8)
+ .padding(.bottom, 32)
+ }
+ .scrollDismissesKeyboard(.interactively)
+ .background(Theme.background)
+ .navigationTitle("New home")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbarBackground(Theme.background, for: .navigationBar)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
+ }
+ }
+ .presentationBackground(Theme.background)
+ .presentationDragIndicator(.visible)
+ .preferredColorScheme(.dark)
+ }
+
+ private func create() {
+ model.createHome(name: name.trimmingCharacters(in: .whitespaces), template: template)
+ dismiss()
+ }
+}
diff --git a/ios/Sources/PairingView.swift b/ios/Sources/PairingView.swift
index 95b7d0c..0925801 100644
--- a/ios/Sources/PairingView.swift
+++ b/ios/Sources/PairingView.swift
@@ -150,8 +150,8 @@ struct PairingView: View {
private var statusLine: String {
switch model.syncStatus {
case .connected:
- return model.hasCustomPlan ? "Your floor plan is here and will follow the Mac from now on."
- : "Connected. Draw your home in the Mac's editor and it appears here."
+ return model.hasCustomPlan ? "Connected. Your floor plan now stays the same on both, whichever one you edit."
+ : "Connected. Draw your home here or on the Mac; it appears on both."
case .failed(let reason): return reason
default: return "Looking for the Mac on this Wi-Fi…"
}
diff --git a/ios/Sources/RootView.swift b/ios/Sources/RootView.swift
index bd4ebbd..4ba79ae 100644
--- a/ios/Sources/RootView.swift
+++ b/ios/Sources/RootView.swift
@@ -18,6 +18,19 @@ struct RootView: View {
}
.sheet(isPresented: $model.showSettings) { SettingsView() }
.sheet(isPresented: $model.showWelcome) { WelcomeView() }
+ .sheet(isPresented: $model.showNewHome) { NewHomeView() }
+ .fullScreenCover(isPresented: $model.showEditor, onDismiss: { model.editorClosed() }) { EditorScreen() }
+ .alert("Which home do you keep?", isPresented: Binding(get: { model.planChoice != nil && !model.showEditor },
+ set: { if !$0, model.planChoice != nil { model.planChoice = nil } }),
+ presenting: model.planChoice) { choice in
+ Button("Keep this iPhone’s") { model.resolvePlanChoice(keepPhone: true) }
+ Button("Keep \(choice.macName)’s") { model.resolvePlanChoice(keepPhone: false) }
+ Button("Decide later", role: .cancel) {}
+ } message: { choice in
+ Text(choice.macPlanName == choice.phonePlanName
+ ? "“\(choice.phonePlanName)” was changed both here and on \(choice.macName) since they last synced. The one you keep replaces the other on both."
+ : "This iPhone has “\(choice.phonePlanName)”, \(choice.macName) has “\(choice.macPlanName)”. The one you keep replaces the other on both.")
+ }
.onOpenURL { model.open($0) }
.preferredColorScheme(.dark)
.tint(Theme.accent)
diff --git a/ios/Sources/SettingsView.swift b/ios/Sources/SettingsView.swift
index 4c2d378..1cb1720 100644
--- a/ios/Sources/SettingsView.swift
+++ b/ios/Sources/SettingsView.swift
@@ -10,6 +10,7 @@ struct SettingsView: View {
@State private var problem: String?
@State private var confirmUnpair = false
@State private var confirmSignOut = false
+ @State private var newHome = false
var body: some View {
@Bindable var model = model
@@ -41,12 +42,16 @@ struct SettingsView: View {
case .pairing: PairingView()
case .smartLife: SmartLifeView()
case .quickActions: QuickActionsView()
+ case .homeAssistant: HomeAssistantView()
+ case .hue: HueView()
+ case .devices: DevicesView()
}
}
}
.presentationBackground(Theme.background)
.presentationDragIndicator(.visible)
.preferredColorScheme(.dark)
+ .sheet(isPresented: $newHome) { NewHomeView() }
.fileImporter(isPresented: $importing, allowedContentTypes: [.json]) { result in
do { try model.importPlan(from: try result.get()) }
catch { problem = error.localizedDescription }
@@ -70,16 +75,47 @@ struct SettingsView: View {
RowDivider()
planRow("studio", name: "Studio", detail: "Demo · 3 rooms, simulated devices", symbol: "square.split.bottomrightquarter.fill", tint: Theme.accent)
}
- Button { importing = true } label: {
- Label("Import a floor plan file…", systemImage: "square.and.arrow.down")
+ Card {
+ Button { model.openEditor() } label: {
+ linkRow(symbol: "pencil.and.ruler.fill", tint: Theme.accent, title: "Edit floor plan",
+ detail: "Rooms, lamps, air conditioners, furniture")
+ }
+ .buttonStyle(RowButtonStyle())
+ RowDivider()
+ NavigationLink(value: SettingsRoute.devices) {
+ linkRow(symbol: "link", tint: Theme.green, title: "Devices",
+ detail: model.linkedDevices == 0 ? "Link the plan to your real devices"
+ : "\(model.linkedDevices) linked to real devices")
+ }
+ .buttonStyle(RowButtonStyle())
+ }
+ HStack(spacing: 10) {
+ Button { newHome = true } label: { Label("New home", systemImage: "plus") }
+ .buttonStyle(SecondaryButtonStyle())
+ Button { importing = true } label: { Label("Import file", systemImage: "square.and.arrow.down") }
+ .buttonStyle(SecondaryButtonStyle())
}
- .buttonStyle(SecondaryButtonStyle())
if !model.hasCustomPlan {
- footnote("Your own home is drawn in House Control on the Mac and arrives here when you pair the two.")
+ footnote("Make your own home here, or pair with House Control on a Mac and the one drawn there arrives by itself.")
}
}
}
+ private func linkRow(symbol: String, tint: Color, title: String, detail: String) -> some View {
+ HStack(spacing: 14) {
+ IconBadge(symbol: symbol, tint: tint)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(title).font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ Text(detail).font(.system(size: 13.5)).foregroundStyle(Theme.muted).lineLimit(1)
+ }
+ Spacer(minLength: 8)
+ Image(systemName: "chevron.right").font(.system(size: 14, weight: .semibold)).foregroundStyle(Theme.faint)
+ }
+ .padding(.horizontal, 14)
+ .frame(minHeight: 66)
+ .contentShape(Rectangle())
+ }
+
private var customPlanDetail: String {
let devices = model.linkedDevices == 0 ? "No real devices linked"
: "\(model.linkedDevices) real device\(model.linkedDevices == 1 ? "" : "s") linked"
@@ -178,14 +214,14 @@ struct SettingsView: View {
} message: {
Text("The floor plan stays on this iPhone but no longer follows the Mac.")
}
- footnote("Changes you save in the Mac's editor reach this iPhone while both are on the same Wi-Fi.")
+ footnote("Changes saved on either one reach the other while both are on the same Wi-Fi: the floor plan, device links, Home Assistant and Hue.")
} else {
Card(padding: 16) {
HStack(alignment: .top, spacing: 14) {
IconBadge(symbol: "laptopcomputer.and.iphone", tint: Theme.accent)
VStack(alignment: .leading, spacing: 4) {
- Text("Bring your home over").font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
- Text("Pair once and the floor plan you drew on the Mac — rooms, lamps, device links — shows up here and stays up to date.")
+ Text("Optional: a Mac").font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ Text("Pair with House Control on a Mac and your home — rooms, lamps, device links, connections — stays the same on both, whichever one you edit.")
.font(.system(size: 14))
.foregroundStyle(Theme.muted)
.fixedSize(horizontal: false, vertical: true)
@@ -282,13 +318,17 @@ struct SettingsView: 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)
+ NavigationLink(value: SettingsRoute.homeAssistant) {
+ serviceRow(symbol: "server.rack", tint: ConnectionLook.homeAssistant, title: "Home Assistant",
+ detail: model.homeAssistantName ?? "Connect your server", on: model.homeAssistantName != nil)
+ }
+ .buttonStyle(RowButtonStyle())
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)
+ NavigationLink(value: SettingsRoute.hue) {
+ serviceRow(symbol: "lightbulb.led.fill", tint: ConnectionLook.hue, title: "Philips Hue",
+ detail: model.hueName ?? "Pair your Hue Bridge", on: model.hueName != nil)
+ }
+ .buttonStyle(RowButtonStyle())
RowDivider()
homeKitRow
}
@@ -306,10 +346,12 @@ struct SettingsView: View {
Text(detail).font(.system(size: 13.5)).foregroundStyle(Theme.muted).lineLimit(2)
}
}
- Spacer(minLength: 0)
+ Spacer(minLength: 8)
+ Image(systemName: "chevron.right").font(.system(size: 14, weight: .semibold)).foregroundStyle(Theme.faint)
}
.padding(.horizontal, 14)
.frame(minHeight: 70)
+ .contentShape(Rectangle())
.accessibilityElement(children: .combine)
}
@@ -355,9 +397,9 @@ struct SettingsView: View {
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 "This iPhone switches your Apple Home devices; your Mac lists them for its editor, but 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."
+ return "Home Assistant and Hue set up here or on your paired Mac work on both, shared over your encrypted link."
}
// MARK: - About
diff --git a/ios/Sources/SmartLifeView.swift b/ios/Sources/SmartLifeView.swift
index 667e098..9f3e269 100644
--- a/ios/Sources/SmartLifeView.swift
+++ b/ios/Sources/SmartLifeView.swift
@@ -1,9 +1,10 @@
import SwiftUI
+import Photos
import HouseCore
/// Signs this iPhone in to Smart Life. The login is confirmed by scanning a QR code with
-/// the Smart Life app — which lives on this very phone, so the code has to be shown on
-/// another screen: the paired Mac puts it up by itself.
+/// the Smart Life app — which lives on this very phone. So the code goes to Photos, where
+/// Smart Life's scanner can open it, or onto another screen: a paired Mac shows it by itself.
struct SmartLifeView: View {
@Environment(AppModel.self) private var model
@Environment(\.scenePhase) private var scenePhase
@@ -12,6 +13,7 @@ struct SmartLifeView: View {
@State private var problem: String?
@State private var login: Login?
@State private var onMac = false
+ @State private var saved: Bool?
@FocusState private var typing: Bool
private struct Login: Equatable {
@@ -41,17 +43,24 @@ struct SmartLifeView: View {
.navigationTitle("Smart Life")
.navigationBarTitleDisplayMode(.inline)
.toolbarBackground(Theme.background, for: .navigationBar)
- .onAppear { if userCode.isEmpty { userCode = model.suggestedUserCode } }
+ .onAppear {
+ if userCode.isEmpty { userCode = model.suggestedUserCode }
+ // HOUSE_SMARTLIFE_QR=<text> shows the code step with that content (screenshots, UI checks);
+ // nothing is sent to Tuya for it.
+ if login == nil, let demo = ProcessInfo.processInfo.environment["HOUSE_SMARTLIFE_QR"] {
+ login = Login(token: "", content: demo)
+ }
+ }
.onChange(of: model.suggestedUserCode) { _, code in if userCode.isEmpty { userCode = code } }
.onDisappear { _ = model.showOnMac(nil) }
// Back from the Smart Life app: do not wait for the next poll to find out.
.onChange(of: scenePhase) { _, phase in
- guard phase == .active, let login, !model.smartLifeConnected else { return }
+ guard phase == .active, let login, !login.token.isEmpty, !model.smartLifeConnected else { return }
Task { _ = await model.finishLogin(token: login.token, userCode: userCode) }
}
// Ask every two seconds whether the login was confirmed, for as long as the code is up.
.task(id: login) {
- guard let login else { return }
+ guard let login, !login.token.isEmpty else { return }
for _ in 0..<150 {
try? await Task.sleep(nanoseconds: 2_000_000_000)
if Task.isCancelled { return }
@@ -151,14 +160,15 @@ struct SmartLifeView: View {
}
} else {
Card(padding: 16) {
- HStack(alignment: .top, spacing: 14) {
- IconBadge(symbol: "qrcode.viewfinder", tint: Theme.warm)
- VStack(alignment: .leading, spacing: 4) {
- Text("Scan this with Smart Life").font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
- Text("The Smart Life app on this iPhone has to scan it, so put the code on another screen: share it to a computer or tablet, or pair with your Mac and it appears there by itself.")
- .font(.system(size: 14)).foregroundStyle(Theme.muted)
- .fixedSize(horizontal: false, vertical: true)
- }
+ VStack(alignment: .leading, spacing: 14) {
+ Text("Scan it with Smart Life on this iPhone")
+ .font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)
+ step(1, "Save the code to Photos (below).")
+ step(2, "In Smart Life tap **+** → **Scan**, then the **photo** icon, and pick the code.")
+ step(3, "Confirm the login and come back here.")
+ Text("Or show it on another screen: share it to a computer or tablet, or pair a Mac and it appears there.")
+ .font(.system(size: 13.5)).foregroundStyle(Theme.faint)
+ .fixedSize(horizontal: false, vertical: true)
}
}
}
@@ -180,6 +190,18 @@ struct SmartLifeView: View {
.font(.system(size: 14)).foregroundStyle(Theme.muted)
}
+ if !onMac, let png = QRCode.png(for: login.content, scale: 16) {
+ Button { save(png) } label: {
+ Label(saved == true ? "Saved to Photos" : "Save code to Photos",
+ systemImage: saved == true ? "checkmark.circle.fill" : "photo.badge.arrow.down")
+ .contentTransition(.symbolEffect(.replace))
+ }
+ .buttonStyle(PrimaryButtonStyle())
+ if saved == false {
+ ProblemLabel(text: "House Control may not add to Photos. Allow it in Settings → Privacy & Security → Photos, or share the code instead.")
+ }
+ }
+
HStack(spacing: 10) {
if let png = QRCode.png(for: login.content, scale: 16) {
ShareLink(item: QRImage(png: png), preview: SharePreview("Smart Life sign-in code")) {
@@ -195,6 +217,7 @@ struct SmartLifeView: View {
Button("Cancel") {
_ = model.showOnMac(nil)
self.login = nil
+ saved = nil
}
.font(.system(size: 16, weight: .medium))
.foregroundStyle(Theme.muted)
@@ -202,6 +225,42 @@ struct SmartLifeView: View {
}
}
+ private func step(_ number: Int, _ text: LocalizedStringKey) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: 12) {
+ Text("\(number)")
+ .font(.system(size: 13, weight: .bold, design: .rounded))
+ .foregroundStyle(Theme.warm)
+ .frame(width: 24, height: 24)
+ .background(Theme.warm.opacity(0.16), in: Circle())
+ Text(text)
+ .font(.system(size: 15))
+ .foregroundStyle(Theme.text)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+
+ /// Adds the code to Photos (asking only for permission to add, not to read).
+ private func save(_ png: Data) {
+ Task {
+ let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly)
+ guard status == .authorized || status == .limited else {
+ saved = false
+ Haptics.shared.play("error")
+ return
+ }
+ do {
+ try await PHPhotoLibrary.shared().performChanges {
+ PHAssetCreationRequest.forAsset().addResource(with: .photo, data: png, options: nil)
+ }
+ saved = true
+ Haptics.shared.play("success")
+ } catch {
+ saved = false
+ Haptics.shared.play("error")
+ }
+ }
+ }
+
// MARK: - Done
private var connected: some View {
@@ -215,13 +274,16 @@ struct SmartLifeView: View {
.font(.system(size: 24, weight: .bold))
.foregroundStyle(Theme.text)
Text(model.linkedDevices == 0
- ? "Link lamps and air conditioners to your devices in the Mac's editor — they start working here as soon as the plan syncs."
+ ? "Now link the lamps and air conditioners of your plan to your devices: Settings → Devices, or in the editor."
: "\(model.linkedDevices) device\(model.linkedDevices == 1 ? "" : "s") in your floor plan \(model.linkedDevices == 1 ? "is" : "are") now the real thing.")
.font(.system(size: 15))
.foregroundStyle(Theme.muted)
.multilineTextAlignment(.center)
.padding(.horizontal, 20)
- Button("Done") { model.showSettings = false }
+ Button("Done") {
+ model.showSettings = false
+ model.editorSheet = nil
+ }
.buttonStyle(PrimaryButtonStyle())
.padding(.top, 14)
}
diff --git a/ios/Sources/WelcomeView.swift b/ios/Sources/WelcomeView.swift
index 3017c18..464255d 100644
--- a/ios/Sources/WelcomeView.swift
+++ b/ios/Sources/WelcomeView.swift
@@ -32,17 +32,20 @@ struct WelcomeView: View {
VStack(alignment: .leading, spacing: 26) {
feature("hand.tap.fill", Theme.warm, "Tap a lamp, drag to dim",
"Lights, colours, air conditioners and scenes, right on the floor plan.")
- feature("laptopcomputer.and.iphone", Theme.accent, "Drawn on your Mac",
- "Pair once and your own floor plan arrives here and stays in sync.")
- feature("lightbulb.2.fill", Theme.green, "Smart Life and Tuya devices",
- "Or none at all: until you sign in, everything is simulated.")
+ feature("pencil.and.ruler.fill", Theme.accent, "Draw it here or on your Mac",
+ "Rooms, lamps and ACs, on this iPhone. Pair a Mac any time: both stay in sync.")
+ feature("lightbulb.2.fill", Theme.green, "Your real devices",
+ "Smart Life, Home Assistant, Philips Hue and Apple Home. Until you connect one, everything is simulated.")
}
.padding(.horizontal, 6)
.frame(maxHeight: .infinity)
- Button { model.finishWelcome(pairing: true) } label: { Label("Pair with my Mac", systemImage: "qrcode.viewfinder") }
+ Button { model.finishWelcome(.setUpHere) } label: { Label("Set up my home", systemImage: "house.fill") }
.buttonStyle(PrimaryButtonStyle())
- Button("Explore the demo home") { model.finishWelcome(pairing: false) }
+ Button { model.finishWelcome(.pair) } label: { Label("Pair with my Mac", systemImage: "laptopcomputer.and.iphone") }
+ .buttonStyle(SecondaryButtonStyle())
+ .padding(.top, 10)
+ Button("Explore the demo home") { model.finishWelcome(.demo) }
.font(.system(size: 16, weight: .semibold))
.foregroundStyle(Theme.muted)
.frame(minHeight: 50)
diff --git a/ios/project.yml b/ios/project.yml
index be3bec1..a0a895e 100644
--- a/ios/project.yml
+++ b/ios/project.yml
@@ -48,13 +48,14 @@ 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, and talks to your Home Assistant and Hue Bridge.
- NSBonjourServices: [_housecontrol._tcp]
+ NSLocalNetworkUsageDescription: House Control finds your Home Assistant and Hue Bridge on this Wi-Fi network, and your Mac, to keep your floor plan the same on both.
+ NSBonjourServices: [_housecontrol._tcp, _hue._tcp, _home-assistant._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.
+ NSPhotoLibraryAddUsageDescription: House Control saves the Smart Life sign-in code to Photos, so the Smart Life app on this iPhone can scan it from there.
CFBundleURLTypes:
- CFBundleURLName: io.github.0xprobabillity.HouseControl.pair
CFBundleURLSchemes: [housecontrol]
diff --git a/macos/Sources/HouseControl/AppDelegate.swift b/macos/Sources/HouseControl/AppDelegate.swift
index 9dd6059..b413a36 100644
--- a/macos/Sources/HouseControl/AppDelegate.swift
+++ b/macos/Sources/HouseControl/AppDelegate.swift
@@ -31,6 +31,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
return agent
}()
private var lastSummary: [String: Any] = [:]
+ /// The Smart Life User Code a paired iPhone signed in with, to save typing it here.
+ private var phoneUserCode = ""
/// Desktop widgets and Control Center controls: what they show, what they asked for.
private let widgets = WidgetBridge()
@@ -209,7 +211,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
private func bootPayload() -> [String: Any] {
var boot = plans.bootPayload()
boot["tuya"] = hub.tuyaInfo
- boot["smartLife"] = hub.smartLifeInfo
+ var smartLife = hub.smartLifeInfo
+ // Not signed in here yet: offer the User Code a paired iPhone signed in with.
+ if !hub.isSmartLifeConnected, !phoneUserCode.isEmpty { smartLife["userCode"] = phoneUserCode }
+ boot["smartLife"] = smartLife
boot["services"] = hub.servicesInfo
switch ProcessInfo.processInfo.environment["HOUSE_OPEN_EDITOR"] {
case "smartlife": boot["section"] = "service:smartlife"
@@ -421,7 +426,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
case "homeassistant.connect":
Task { @MainActor in
do {
- try await hub.homeAssistant.connect(url: message["url"] as? String ?? "", token: message["token"] as? String ?? "")
+ try await hub.connectHomeAssistant(url: message["url"] as? String ?? "", token: message["token"] as? String ?? "")
connectionsChanged()
host.reply(to: message, hub.servicesInfo)
} catch {
@@ -431,8 +436,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
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)
+ try await hub.pairHue(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 {
@@ -442,7 +447,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
}
}
case "service.disconnect":
- hub.services.first { $0.id == message["service"] as? String }?.disconnect()
+ hub.disconnect(service: message["service"] as? String ?? "")
connectionsChanged()
host.reply(to: message, hub.servicesInfo)
default:
@@ -530,11 +535,40 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
catalog.update(devices: devices, from: phone)
self.editor?.host.call("servicesChanged", self.hub.servicesInfo)
}
+ // A home set up or edited on the iPhone becomes this Mac's home too.
+ sync.onPlan = { [weak self] data, phone in self?.receivedPlan(data, from: phone) }
+ sync.onConnections = { [weak self] shared, userCode, _ in
+ guard let self else { return }
+ if !userCode.isEmpty { self.phoneUserCode = userCode }
+ if self.hub.adoptConnections(shared) {
+ self.connectionsChanged()
+ 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) }
sync.start() // only listens once a phone has been paired
}
+ /// Stores a plan an iPhone saved. The first one becomes the active home; later ones
+ /// replace it (a Mac that switched to a demo plan stays there, like the phone does).
+ private func receivedPlan(_ data: Data, from phone: String) {
+ let first = !plans.hasCustomPlan
+ do {
+ try plans.saveCustom(data: data, select: first || plans.activePlan == "custom")
+ } catch {
+ NSLog("House Control: could not store the plan from %@: %@", phone, error.localizedDescription)
+ return
+ }
+ reloadLinks()
+ widgets.isReady = false
+ panel.host.load()
+ if island?.isShown == true { island?.host.load() }
+ sync.broadcast()
+ // An open editor takes the new plan unless it holds unsaved changes of its own.
+ if let editor, let plan = plans.customPlan() { editor.host.call("planArrived", plan, phone) }
+ }
+
/// Shows the QR code an iPhone scans once to find this Mac and receive its floor plan.
@objc private func pairPhone() {
panel.hide()
@@ -553,7 +587,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
pairingWindow?.show(code: pairing.link,
headline: "Scan with House Control on your iPhone",
detail: "On the iPhone open Settings → Pair with Mac. Both devices must be on the same Wi-Fi. "
- + "Your floor plan is sent straight from this Mac to the phone, encrypted with the key in this code.")
+ + "Your floor plan, device links and connections stay the same on both, whichever one you edit; "
+ + "they travel straight between them, encrypted with the key in this code.")
refreshPairingWindow()
}
diff --git a/web/src/editor/connections.js b/web/src/editor/connections.js
index 7e1b8bd..3ce1313 100644
--- a/web/src/editor/connections.js
+++ b/web/src/editor/connections.js
@@ -90,7 +90,7 @@ export function createConnections({ rerender, toast, usedBy, onOpen }) {
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).'),
+ isNative ? null : h('p.note.bad', 'Connecting works inside the House Control app (this is the browser preview).'),
];
}
diff --git a/web/src/editor/editor.css b/web/src/editor/editor.css
index 3e228c5..37c0ff2 100644
--- a/web/src/editor/editor.css
+++ b/web/src/editor/editor.css
@@ -265,3 +265,163 @@ html.mode-editor, html.mode-editor body { user-select: none; }
.press-button span { animation: none; box-shadow: 0 0 0 3px rgba(60, 140, 255, 0.55); }
.note.busy .icon { animation-duration: 2.4s; }
}
+
+
+/* ---------- iPhone ---------- */
+
+html.ios.mode-editor body { background: var(--bg); }
+.editor.phone {
+ --safe-top: var(--safe-top-preview, env(safe-area-inset-top, 0px));
+ --safe-bottom: var(--safe-bottom-preview, env(safe-area-inset-bottom, 0px));
+ --bar-h: calc(var(--safe-top) + 54px);
+ --tools-h: calc(var(--safe-bottom) + 62px);
+ --peek-h: min(40vh, 360px);
+ position: relative; display: block; height: 100%; overflow: hidden; font-size: 15px;
+}
+.p-bar {
+ position: absolute; left: 0; right: 0; top: 0; z-index: 5; height: var(--bar-h);
+ display: flex; align-items: center; gap: 4px; padding: var(--safe-top) 10px 0;
+ background: linear-gradient(180deg, rgba(10, 14, 26, 0.96), rgba(10, 14, 26, 0.82));
+ border-bottom: 1px solid var(--line);
+ -webkit-backdrop-filter: blur(18px); backdrop-filter: blur(18px);
+}
+.p-bar .title-input { flex: 1; min-width: 0; max-width: none; height: 40px; font-size: 17px; text-align: center; padding: 0 6px; }
+.p-icon {
+ flex: none; width: 40px; height: 40px; border-radius: 12px; display: grid; place-items: center; color: var(--text);
+ transition: background 140ms, opacity 140ms, transform 200ms var(--spring);
+}
+.p-icon:active { background: var(--glass-hi); transform: scale(0.92); }
+.p-icon:disabled { opacity: 0.3; }
+.p-icon.danger { color: #ff8a80; }
+.p-save {
+ flex: none; height: 36px; min-width: 66px; margin-left: 4px; padding: 0 14px; border-radius: 12px;
+ font-size: 15px; font-weight: 650; color: #7fb2ff; transition: background 160ms, color 160ms, transform 200ms var(--spring);
+}
+.p-save.primary { color: #fff; background: linear-gradient(180deg, #4f97ff, #2f7bf2); box-shadow: 0 6px 16px -6px rgba(61, 139, 255, 0.8); }
+.p-save:active { transform: scale(0.94); }
+.p-save:disabled { opacity: 0.4; }
+
+.editor.phone .canvas {
+ position: absolute; left: 0; right: 0; top: var(--bar-h); bottom: var(--tools-h);
+ transition: bottom 320ms var(--ease);
+}
+.editor.phone[data-sheet='peek'] .canvas { bottom: calc(var(--peek-h) + var(--tools-h) - 12px); }
+.editor.phone .plan { position: absolute; inset: 0; }
+.editor.phone .hint { bottom: 12px; font-size: 12.5px; padding: 0 20px; transition: opacity 200ms; }
+.editor.phone:not([data-sheet='closed']) .hint { opacity: 0; }
+.p-preview { position: absolute; inset: 0; display: none; background: #0a0e1a; }
+.canvas.show-3d .p-preview { display: block; }
+.canvas.show-3d .plan, .canvas.show-3d .p-float, .canvas.show-3d .hint { visibility: hidden; }
+.p-preview .chip { top: 12px; right: 12px; height: 32px; padding: 0 12px; font-size: 13px; }
+.p-float {
+ position: absolute; right: 12px; top: 12px; width: 40px; height: 40px; border-radius: 13px; display: grid; place-items: center;
+ color: var(--muted); background: rgba(16, 21, 36, 0.82); border: 1px solid var(--line);
+ -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px);
+}
+.p-float:active { color: var(--text); transform: scale(0.94); }
+.p-issue {
+ position: absolute; left: 12px; right: 60px; top: 12px; display: none; padding: 9px 12px; border-radius: 12px;
+ font-size: 13px; line-height: 1.35; color: #ffd2cc; background: rgba(80, 22, 22, 0.88); border: 1px solid rgba(255, 120, 110, 0.5);
+}
+.p-issue.show { display: block; }
+
+.editor.phone .hit { fill: transparent; stroke: none; }
+.editor.phone .p-hit { stroke: transparent; stroke-width: 0.6; }
+.editor.phone .p-room rect, .editor.phone .p-furn rect, .editor.phone .p-light, .editor.phone .p-ac rect, .editor.phone .p-open { cursor: default; }
+.editor.phone .p-room:hover rect { filter: none; }
+
+.p-tools {
+ position: absolute; left: 0; right: 0; bottom: 0; z-index: 6; height: var(--tools-h);
+ display: grid; grid-template-columns: repeat(4, 1fr); padding: 4px 8px var(--safe-bottom);
+ background: rgba(10, 14, 26, 0.94); border-top: 1px solid var(--line);
+ -webkit-backdrop-filter: blur(18px); backdrop-filter: blur(18px);
+}
+.p-tool { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; font-size: 11px; font-weight: 600; color: var(--muted); border-radius: 14px; }
+.p-tool:active { color: var(--text); background: var(--glass); }
+
+/* the details sheet */
+.p-sheet {
+ position: absolute; left: 0; right: 0; bottom: 0; z-index: 5; height: var(--peek-h);
+ display: flex; flex-direction: column;
+ background: #121828; border-top: 1px solid rgba(255, 255, 255, 0.12); border-radius: 22px 22px 0 0;
+ box-shadow: 0 -18px 50px rgba(0, 0, 0, 0.55);
+ transition: height 320ms var(--ease), transform 320ms var(--ease), bottom 320ms var(--ease);
+}
+.p-sheet[data-state='peek'] { bottom: calc(var(--tools-h) - 12px); box-shadow: 0 -12px 34px rgba(0, 0, 0, 0.45); }
+.p-sheet[data-state='peek'] .inspector { padding-bottom: 28px; }
+.p-sheet[data-state='closed'] { transform: translateY(105%); }
+.p-sheet[data-state='full'] { z-index: 7; height: calc(100% - var(--bar-h) - 6px); }
+.p-sheet.dragging { transition: none; }
+.p-grip { flex: none; height: 22px; display: grid; place-items: center; touch-action: none; }
+.p-grip span { width: 38px; height: 5px; border-radius: 3px; background: rgba(255, 255, 255, 0.25); }
+.editor.phone .inspector { flex: 1; padding: 0 18px calc(var(--safe-bottom) + 24px); -webkit-overflow-scrolling: touch; overscroll-behavior: contain; }
+.editor.phone .insp-head {
+ position: sticky; top: 0; z-index: 1; display: flex; align-items: center; gap: 6px; margin: 0 -18px; padding: 0 12px 10px 18px;
+ background: #121828; touch-action: none;
+}
+.insp-titles { flex: 1; min-width: 0; }
+.editor.phone .insp-head h2 { font-size: 19px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.editor.phone .insp-head span { font-size: 12.5px; }
+.p-head-actions { display: flex; gap: 2px; }
+.editor.phone .svc-head { position: static; margin: 0; padding: 0; }
+.editor.phone .block { margin-top: 20px; }
+.editor.phone .block h3, .editor.phone .devices-list h3 { font-size: 11.5px; margin-bottom: 10px; }
+.editor.phone .field > span { font-size: 13px; margin-bottom: 6px; }
+.editor.phone .field input:not([type='checkbox']), .editor.phone .field select { height: 44px; font-size: 16px; border-radius: 12px; padding: 0 12px; }
+.editor.phone .field select { background-position: calc(100% - 17px) 20px, calc(100% - 12px) 20px; padding-right: 30px; }
+.editor.phone .fields { gap: 10px; }
+.editor.phone .checks .field { min-height: 40px; }
+.editor.phone .checks .field > span { font-size: 15px; }
+.editor.phone .checks input { width: 22px; height: 22px; }
+.editor.phone .note { font-size: 13px; }
+.editor.phone .steps { font-size: 14px; }
+.editor.phone .btn { height: 44px; font-size: 15px; border-radius: 13px; padding: 0 16px; }
+.editor.phone .btn.wide { height: 48px; }
+.editor.phone .btn.danger { color: #ff8a80; }
+.editor.phone .back-link { font-size: 15px; padding: 6px 10px 6px 4px; margin-bottom: 12px; }
+.editor.phone .svc-card { padding: 14px; border-radius: 16px; }
+.editor.phone .svc-text b { font-size: 15.5px; }
+.editor.phone .svc-text span { font-size: 13px; }
+.editor.phone .svc-status { font-size: 12.5px; }
+.editor.phone .device { padding: 10px 12px; }
+.editor.phone .device b { font-size: 15px; }
+.editor.phone .device div span { font-size: 12.5px; }
+.editor.phone .tuya-row { height: 48px; padding: 0 12px; border-radius: 14px; background: var(--glass); border: 1px solid var(--line); font-size: 15px; }
+
+/* list, add and confirm sheets */
+.p-scrim { position: absolute; inset: 0; z-index: 7; background: rgba(0, 0, 0, 0.45); opacity: 0; pointer-events: none; transition: opacity 240ms; }
+.p-scrim.open { opacity: 1; pointer-events: auto; }
+.p-modal {
+ position: absolute; left: 0; right: 0; bottom: 0; z-index: 8; max-height: calc(100% - var(--safe-top) - 40px);
+ display: flex; flex-direction: column; padding: 0 0 var(--safe-bottom);
+ background: #141a2b; border-radius: 22px 22px 0 0; border-top: 1px solid rgba(255, 255, 255, 0.12);
+ transform: translateY(105%); transition: transform 340ms var(--ease);
+}
+.p-modal.open { transform: none; }
+.p-modal-head { flex: none; display: flex; align-items: center; justify-content: space-between; padding: 16px 18px 8px; }
+.p-modal-head b { font-size: 17px; font-weight: 650; }
+.p-text { font-size: 16px; font-weight: 600; color: #7fb2ff; padding: 6px 2px; }
+.p-list { flex: 1; overflow-y: auto; padding: 0 12px 16px; border: 0; -webkit-overflow-scrolling: touch; }
+.p-list .row { min-height: 46px; font-size: 15.5px; padding: 0 12px; }
+.p-list .row-sub { font-size: 13px; }
+.p-list .row .del { display: none !important; }
+.p-list .row:hover .row-sub { display: block; }
+.p-list .group { font-size: 12px; margin: 18px 8px 6px; }
+.p-list .group .add { width: 30px; height: 30px; border-radius: 10px; }
+.p-list .home-row, .p-list .tuya-row { height: 48px; }
+.p-add-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; padding: 8px 16px 18px; }
+.p-add-item {
+ height: 96px; border-radius: 18px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 9px;
+ font-size: 13px; font-weight: 600; color: var(--text); background: var(--glass); border: 1px solid var(--line);
+ transition: transform 200ms var(--spring), background 140ms;
+}
+.p-add-item:active { transform: scale(0.95); background: var(--glass-hi); }
+.p-add-item .icon { color: var(--warm); }
+.p-confirm .note { padding: 0 18px; font-size: 14px; }
+.p-confirm-actions { display: grid; gap: 10px; padding: 16px 18px 18px; }
+.editor.phone .toast { bottom: calc(var(--tools-h) + 14px); font-size: 14px; max-width: calc(100% - 40px); text-align: center; z-index: 9; }
+.editor.phone[data-sheet='peek'] .toast { bottom: calc(var(--peek-h) + var(--tools-h)); }
+
+@media (prefers-reduced-motion: reduce) {
+ .p-sheet, .p-modal, .editor.phone .canvas, .p-scrim { transition-duration: 1ms; }
+}
diff --git a/web/src/editor/editor.js b/web/src/editor/editor.js
index 56ecc11..d0858f0 100644
--- a/web/src/editor/editor.js
+++ b/web/src/editor/editor.js
@@ -1,12 +1,14 @@
-// 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 links to real devices.
+// Home editor (a window on the Mac, full screen on the iPhone): a top-down plan you can drag
+// things around on, an inspector for the selected item, a live 3D preview and the links to
+// real devices. On a phone the same pieces are laid out for a finger: the plan fills the
+// screen, the inspector is a sheet from the bottom, pinch zooms and drag pans.
import './editor.css';
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 { isNative, isPhone, call, post, haptic, incoming } from '../bridge.js';
import { createConnections } from './connections.js';
const SVG = 'http://www.w3.org/2000/svg';
@@ -42,6 +44,7 @@ export async function bootEditor(root) {
: startAt === 'tuya' ? { kind: 'service', service: 'smartlife' } : { kind: 'home' };
let dirty = false;
let world = null;
+ let phone = null; // the iPhone's layout and gestures, set up by buildPhoneLayout()
let previewLights = true;
const undo = [];
const redo = [];
@@ -58,7 +61,9 @@ export async function bootEditor(root) {
},
toast,
usedBy: () => links.usedMap(doc),
- onOpen: (service) => select(service ? { kind: 'service', service } : { kind: 'connections' }),
+ // On the iPhone the connection screens are native ones, shown over the editor.
+ onOpen: (service) => (isPhone && service ? post('openConnection', { 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 }));
@@ -69,6 +74,8 @@ export async function bootEditor(root) {
nameInput.addEventListener('input', () => { snapshot('name'); doc.name = nameInput.value; touch({ inspector: sel.kind === 'home' }); });
const status = h('div.status');
const saveBtn = h('button.btn.primary', { onclick: save }, icon('check', 15, 2.4), 'Save & apply');
+ const hint = h('div.hint', isPhone ? 'Tap to select · drag what is selected · pinch to zoom'
+ : 'Drag rooms, lamps and furniture · drag a room’s corner to resize · everything snaps to 5 cm');
const toastEl = h('div.toast');
const sidebar = h('aside.side');
@@ -77,7 +84,8 @@ export async function bootEditor(root) {
const previewHost = h('div.preview');
const previewToggle = h('button.chip', { onclick: () => { previewLights = !previewLights; schedulePreview(0); } });
- root.replaceChildren(h('div.editor',
+ if (isPhone) buildPhoneLayout();
+ else root.replaceChildren(h('div.editor',
h('header.bar',
h('div.bar-title', icon('home', 17), nameInput),
h('div.bar-actions',
@@ -87,7 +95,7 @@ export async function bootEditor(root) {
h('button.btn', { onclick: exportPlan }, 'Export…'),
saveBtn)),
sidebar,
- h('main.canvas', plan, h('div.hint', 'Drag rooms, lamps and furniture · drag a room’s corner to resize · everything snaps to 5 cm')),
+ h('main.canvas', plan, hint),
h('aside.right', h('div.preview-wrap', previewHost, previewToggle), inspector),
h('footer.foot', status),
toastEl));
@@ -128,6 +136,7 @@ export async function bootEditor(root) {
renderSidebar();
renderPlan();
renderInspector();
+ if (isPhone) phone.selected(next);
}
function toast(text, bad = false) {
@@ -153,6 +162,7 @@ export async function bootEditor(root) {
status.textContent = `⚠ ${e.message}`;
}
saveBtn.disabled = !valid;
+ if (isPhone) phone.refresh();
}
function previewStore(cfg) {
@@ -171,6 +181,7 @@ export async function bootEditor(root) {
function buildPreview() {
previewToggle.replaceChildren(icon(previewLights ? 'bright' : 'moon', 14), previewLights ? 'Lights on' : 'Lights off');
if (!valid) return;
+ if (isPhone && !phone.show3D) { world?.dispose(); world = null; previewHost.replaceChildren(); return; }
world?.dispose();
world = null;
const canvas = h('canvas');
@@ -184,7 +195,7 @@ export async function bootEditor(root) {
if (index >= 0) select({ kind: t.kind, index });
},
});
- world.setInsets(6, 6);
+ world.setInsets(isPhone ? 20 : 6, isPhone ? 20 : 6);
world.setRunning(true);
const w = world;
new ResizeObserver(() => { if (world === w) w.resize(); }).observe(canvas);
@@ -248,7 +259,7 @@ export async function bootEditor(root) {
list.push({ id: uniqueId('room'), name: 'New room', rect: [fix(maxX), fix(doc.rooms.length ? minZ : 0), 3, 3], floor: 'oak' });
} else if (kind === 'light') {
if (!room) return toast('Add a room first', true);
- list.push({ id: uniqueId(`${room.id}.light`), name: 'New light', room: room.id, type: 'ceiling', pos: center, capabilities: [] });
+ list.push({ id: uniqueId(`${room.id}.light`), name: 'New light', room: room.id, type: 'ceiling', pos: freeSpot(room, center), capabilities: [] });
} else if (kind === 'ac') {
if (!room) return toast('Add a room first', true);
list.push({ id: uniqueId(`${room.id}.ac`), name: `${room.name} AC`, room: room.id, wall: 'north', pos: [center[0], room.rect[1]], y: 2.2 });
@@ -265,6 +276,20 @@ export async function bootEditor(root) {
touch();
}
+ // The middle of the room, or the nearest place around it no other lamp stands on.
+ function freeSpot(room, center) {
+ const [x, z, w, d] = room.rect;
+ const taken = (p) => doc.lights.some((l) => Math.hypot(l.pos[0] - p[0], l.pos[1] - p[1]) < 0.45);
+ for (let ring = 0; ring < 4; ring++) {
+ for (let k = 0; k < Math.max(1, ring * 6); k++) {
+ const a = (k / Math.max(1, ring * 6)) * Math.PI * 2;
+ const p = [fix(round(center[0] + Math.cos(a) * ring * 0.6)), fix(round(center[1] + Math.sin(a) * ring * 0.6))];
+ if (p[0] > x + 0.2 && p[0] < x + w - 0.2 && p[1] > z + 0.2 && p[1] < z + d - 0.2 && !taken(p)) return p;
+ }
+ }
+ return center;
+ }
+
function remove(kind, index) {
snapshot();
const [gone] = doc[KEYS[kind]].splice(index, 1);
@@ -299,7 +324,10 @@ export async function bootEditor(root) {
function renderPlan() {
const b = bounds();
const m = 1.4;
- plan.setAttribute('viewBox', `${b.minX - m} ${b.minZ - m} ${b.maxX - b.minX + m * 2} ${b.maxZ - b.minZ + m * 2}`);
+ if (isPhone) phone.applyView();
+ else plan.setAttribute('viewBox', `${b.minX - m} ${b.minZ - m} ${b.maxX - b.minX + m * 2} ${b.maxZ - b.minZ + m * 2}`);
+ // Fingers are bigger than a mouse pointer: on a phone small things get a wider target.
+ const big = isPhone;
const kids = [
sv('defs', {}, sv('pattern', { id: 'grid', width: 1, height: 1, patternUnits: 'userSpaceOnUse' },
sv('path', { d: 'M1 0H0V1', fill: 'none', stroke: 'rgba(255,255,255,0.07)', 'stroke-width': 0.015 }),
@@ -329,6 +357,7 @@ export async function bootEditor(root) {
});
doc.openings.forEach((o, i) => {
+ if (big) kids.push(sv('line', { class: 'p-hit', 'data-kind': 'opening', 'data-index': i, x1: o.from[0], y1: o.from[1], x2: o.to[0], y2: o.to[1] }));
kids.push(sv('line', {
class: `p-open ${o.type || 'door'}${isSel('opening', i) ? ' sel' : ''}`, 'data-kind': 'opening', 'data-index': i,
x1: o.from[0], y1: o.from[1], x2: o.to[0], y2: o.to[1],
@@ -340,7 +369,8 @@ export async function bootEditor(root) {
kids.push(sv('g', {
class: `p-ac${isSel('ac', i) ? ' sel' : ''}`, 'data-kind': 'ac', 'data-index': i,
transform: `translate(${a.pos[0]} ${a.pos[1]}) rotate(${rot})`,
- }, sv('rect', { x: -0.47, y: 0.08, width: 0.94, height: 0.24, rx: 0.07 }),
+ }, big ? sv('rect', { x: -0.62, y: -0.12, width: 1.24, height: 0.74, class: 'hit' }) : null,
+ sv('rect', { x: -0.47, y: 0.08, width: 0.94, height: 0.24, rx: 0.07 }),
sv('path', { d: 'M-0.3 0.42v0.22M0 0.42v0.3M0.3 0.42v0.22', class: 'flow' })));
});
@@ -349,6 +379,7 @@ export async function bootEditor(root) {
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 (big) g.append(sv('circle', { r: 0.58, class: 'hit' }));
if (l.type === 'strip') {
const len = l.length || 1;
g.append(sv('rect', { x: -len / 2, y: -0.07, width: len, height: 0.14, rx: 0.07 }));
@@ -360,7 +391,8 @@ export async function bootEditor(root) {
if (sel.kind === 'room' && doc.rooms[sel.index]) {
const [x, z, w, d] = doc.rooms[sel.index].rect;
- kids.push(sv('circle', { cx: x + w, cy: z + d, r: 0.16, class: 'p-handle', 'data-kind': 'resize', 'data-index': sel.index }));
+ if (big) kids.push(sv('circle', { cx: x + w, cy: z + d, r: 0.55, class: 'hit', 'data-kind': 'resize', 'data-index': sel.index }));
+ kids.push(sv('circle', { cx: x + w, cy: z + d, r: big ? 0.24 : 0.16, class: 'p-handle', 'data-kind': 'resize', 'data-index': sel.index }));
}
plan.replaceChildren(...kids);
}
@@ -392,12 +424,17 @@ export async function bootEditor(root) {
let drag = null;
plan.addEventListener('pointerdown', (ev) => {
+ if (isPhone) return;
const el = ev.target.closest('[data-kind]');
const kind = el?.dataset.kind;
if (!kind || kind === 'none') { select({ kind: 'home' }); return; }
- const index = Number(el.dataset.index);
- const start = planPoint(ev);
plan.setPointerCapture(ev.pointerId);
+ startDrag(kind, Number(el.dataset.index), ev);
+ });
+
+ // Picks up an item (or a room's resize handle) under the pointer.
+ function startDrag(kind, index, ev) {
+ const start = planPoint(ev);
if (kind === 'resize') {
drag = { kind, index, start, rect: [...doc.rooms[index].rect] };
return;
@@ -422,15 +459,17 @@ export async function bootEditor(root) {
} else {
drag.pos = [...item.pos];
}
- });
+ }
- plan.addEventListener('pointermove', (ev) => {
+ plan.addEventListener('pointermove', (ev) => { if (!isPhone) moveDrag(ev); });
+
+ function moveDrag(ev) {
if (!drag) return;
const [px, pz] = planPoint(ev);
const dx = round(px - drag.start[0]);
const dz = round(pz - drag.start[1]);
if (!drag.moved && !dx && !dz) return;
- if (!drag.moved) { drag.moved = true; snapshot(); }
+ if (!drag.moved) { drag.moved = true; snapshot(); haptic('tick'); }
const item = drag.kind === 'resize' ? doc.rooms[drag.index] : doc[KEYS[drag.kind]][drag.index];
if (drag.kind === 'resize') {
@@ -459,11 +498,11 @@ export async function bootEditor(root) {
}
}
touch();
- });
+ }
const endDrag = () => { drag = null; lastSnapshotKey = null; };
- plan.addEventListener('pointerup', endDrag);
- plan.addEventListener('pointercancel', endDrag);
+ plan.addEventListener('pointerup', () => { if (!isPhone) endDrag(); });
+ plan.addEventListener('pointercancel', () => { if (!isPhone) endDrag(); });
/* ---------- inspector ---------- */
@@ -507,11 +546,14 @@ export async function bootEditor(root) {
const kind = sel.kind;
const item = sel.index != null ? doc[KEYS[kind]]?.[sel.index] : null;
const nodes = [];
- const head = (title, sub) => nodes.push(h('div.insp-head', h('h2', title), sub ? h('span', sub) : null));
+ const head = (title, sub) => nodes.push(isPhone
+ ? h('div.insp-head', h('div.insp-titles', h('h2', title), sub ? h('span', sub) : null), phone.headActions())
+ : h('div.insp-head', h('h2', title), sub ? h('span', sub) : null));
if (kind === 'home') {
head('Home', 'Global settings of this plan');
doc.camera ||= { azimuth: 34, elevation: 47 };
+ if (isPhone) nodes.push(section('Real devices', links.sidebarRow(false, () => select({ kind: 'connections' }))));
nodes.push(section('Building',
row(bind('Wall height, m', number(0.1), { ...prop(doc, 'wallHeight', 2.6), parse: parseNum }),
bind('Inner walls shown, m', number(0.05), { ...prop(doc, 'interiorWallHeight', 1.25), parse: parseNum })),
@@ -521,9 +563,12 @@ export async function bootEditor(root) {
bind('Elevation, °', number(1), { ...prop(doc.camera, 'elevation', 47), parse: parseNum })),
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).')));
+ h('p.note', isPhone
+ ? 'Tap anything on the plan, or find it under Items, to edit it. “Save” keeps the plan on this iPhone and sends it to your paired Mac. Coordinates are metres: x grows to the right (east), z grows downwards (south).'
+ : '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 === 'connections') {
head('Connections', 'Where your real lamps and air conditioners live');
+ if (isPhone) nodes.push(h('button.back-link', { onclick: () => select({ kind: 'home' }) }, icon('back', 14, 2.2), 'Home'));
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'));
@@ -532,6 +577,7 @@ export async function bootEditor(root) {
nodes.push(...[links.detail(sel.service, tuyaPanel)].flat());
} else if (!item) {
head('Nothing selected');
+ if (isPhone) nodes.push(h('p.note', 'Tap a room, a lamp or anything else on the plan.'));
} else if (kind === 'room') {
head(item.name || item.id, `id: ${item.id}`);
nodes.push(section('Room',
@@ -673,7 +719,7 @@ export async function bootEditor(root) {
function tuyaPanel() {
const nodes = [];
- if (!isNative) nodes.push(h('p.note.bad', 'Connecting is only available inside the macOS app (this is the browser preview).'));
+ if (!isNative) nodes.push(h('p.note.bad', 'Connecting works inside the House Control app (this is the browser preview).'));
if (tuya.account.connected) {
nodes.push(section('Smart Life account',
@@ -772,7 +818,8 @@ export async function bootEditor(root) {
await call('savePlan', { config: doc });
dirty = false;
validate();
- toast('Saved — the menu bar panel now shows this home');
+ haptic('success');
+ toast(isPhone ? 'Saved' : 'Saved — the menu bar panel now shows this home');
} catch (e) {
toast(e.message, true);
}
@@ -850,6 +897,270 @@ export async function bootEditor(root) {
}
});
+ /* ---------- iPhone ---------- */
+
+ // The plan fills the screen; a bar on top (close, name, undo, save), tools at the bottom
+ // (add, items, 3D, home) and the inspector as a sheet that rises when something is picked.
+ function buildPhoneLayout() {
+ const canvas = h('main.canvas');
+ const sheet = h('section.p-sheet', { 'aria-label': 'Details' });
+ const grip = h('div.p-grip', { role: 'button', 'aria-label': 'Resize details' }, h('span'));
+ const scrim = h('div.p-scrim');
+ const listSheet = h('section.p-modal', { 'aria-label': 'Items' });
+ const addSheet = h('section.p-modal.p-add', { 'aria-label': 'Add' });
+ const confirmSheet = h('section.p-modal.p-confirm', { 'aria-label': 'Unsaved changes' });
+ const undoBtn = h('button.p-icon', { 'aria-label': 'Undo', onclick: () => { stepHistory(undo, redo); haptic('light'); } }, icon('undo', 19, 2.1));
+ const redoBtn = h('button.p-icon', { 'aria-label': 'Redo', onclick: () => { stepHistory(redo, undo); haptic('light'); } }, icon('redo', 19, 2.1));
+ const doneBtn = h('button.p-save', { onclick: () => (dirty ? save() : close()) });
+ const issue = h('div.p-issue');
+ const fitBtn = h('button.p-float', { 'aria-label': 'Show the whole plan', onclick: () => { ui.view = null; ui.applyView(); haptic('light'); } }, icon('fit', 18, 2));
+ const tool = (name, label, onclick) => h('button.p-tool', { onclick }, icon(name, 22, 1.9), h('span', label));
+ const view3d = tool('box', '3D', () => setShow3D(!ui.show3D));
+ const tools = h('nav.p-tools',
+ tool('plus', 'Add', () => openModal(addSheet)),
+ tool('list', 'Items', () => openModal(listSheet)),
+ view3d,
+ tool('home', 'Home', () => { select({ kind: 'home' }); setSheet('full'); }));
+
+ nameInput.setAttribute('enterkeyhint', 'done');
+ nameInput.addEventListener('keydown', (ev) => { if (ev.key === 'Enter') nameInput.blur(); });
+ sidebar.classList.add('p-list');
+ listSheet.append(h('div.p-modal-head', h('b', 'Items'), h('button.p-text', { onclick: closeModals }, 'Done')), sidebar);
+ const addables = [
+ ['room', 'home', 'Room'], ['light', 'bulb', 'Lamp'], ['ac', 'ac', 'Air conditioner'],
+ ['opening', 'opening', 'Door or window'], ['furniture', 'furniture', 'Furniture'], ['scene', 'sparkles', 'Scene'],
+ ];
+ addSheet.append(h('div.p-modal-head', h('b', 'Add to the plan'), h('button.p-text', { onclick: closeModals }, 'Cancel')),
+ h('div.p-add-grid', addables.map(([kind, name, label]) => h('button.p-add-item', {
+ onclick: () => { closeModals(); add(kind); haptic('light'); ui.reveal(); },
+ }, icon(name, 24, 1.8), h('span', label)))));
+ confirmSheet.append(h('div.p-modal-head', h('b', 'Unsaved changes')),
+ h('p.note', 'Save them before closing? Saved plans reach your paired Mac too.'),
+ h('div.p-confirm-actions',
+ h('button.btn.primary.wide', { onclick: async () => { closeModals(); await save(); if (!dirty) close(); } }, 'Save and close'),
+ h('button.btn.wide.danger', { onclick: () => { closeModals(); dirty = false; close(); } }, 'Discard changes'),
+ h('button.btn.wide', { onclick: closeModals }, 'Keep editing')));
+
+ sheet.append(grip, inspector);
+ canvas.append(plan, h('div.p-preview', previewHost, previewToggle), issue, fitBtn, hint);
+ const shell = h('div.editor.phone',
+ h('header.p-bar', h('button.p-icon', { 'aria-label': 'Close', onclick: requestClose }, icon('close', 20, 2.2)),
+ nameInput, undoBtn, redoBtn, doneBtn),
+ canvas, tools, scrim, sheet, listSheet, addSheet, confirmSheet, toastEl);
+ root.replaceChildren(shell);
+
+ /* sheet: closed, peek (the bottom part of the screen) or full */
+ function setSheet(next) {
+ ui.sheet = next;
+ sheet.dataset.state = next;
+ shell.dataset.sheet = next;
+ sheet.style.height = '';
+ document.activeElement?.blur?.();
+ }
+ let gripDrag = null;
+ const startGrip = (ev) => {
+ if (ev.target.closest('button, input, select, textarea, a')) return;
+ gripDrag = { y: ev.clientY, h: sheet.getBoundingClientRect().height, id: ev.pointerId, moved: false };
+ };
+ grip.addEventListener('pointerdown', startGrip);
+ inspector.addEventListener('pointerdown', (ev) => { if (ev.target.closest('.insp-head')) startGrip(ev); });
+ window.addEventListener('pointermove', (ev) => {
+ if (!gripDrag || ev.pointerId !== gripDrag.id) return;
+ const dy = ev.clientY - gripDrag.y;
+ if (!gripDrag.moved && Math.abs(dy) < 6) return;
+ gripDrag.moved = true;
+ sheet.classList.add('dragging');
+ sheet.style.height = `${Math.max(80, gripDrag.h - dy)}px`;
+ });
+ const endGrip = (ev) => {
+ if (!gripDrag || ev.pointerId !== gripDrag.id) return;
+ const { moved, h: from } = gripDrag;
+ gripDrag = null;
+ sheet.classList.remove('dragging');
+ if (!moved) { if (ev.target.closest('.p-grip')) setSheet(ui.sheet === 'full' ? 'peek' : 'full'); return; }
+ const now = sheet.getBoundingClientRect().height;
+ const screen = window.innerHeight;
+ if (now < Math.min(from, screen * 0.42) * 0.7) closeSheet();
+ else setSheet(now > screen * 0.62 ? 'full' : 'peek');
+ };
+ window.addEventListener('pointerup', endGrip);
+ window.addEventListener('pointercancel', endGrip);
+
+ function closeSheet() {
+ setSheet('closed');
+ if (sel.kind !== 'home') { sel = { kind: 'home' }; renderSidebar(); renderPlan(); renderInspector(); }
+ }
+
+ function openModal(el) {
+ closeModals();
+ if (el === listSheet) renderSidebar();
+ el.classList.add('open');
+ scrim.classList.add('open');
+ haptic('light');
+ }
+ function closeModals() {
+ for (const el of [listSheet, addSheet, confirmSheet]) el.classList.remove('open');
+ scrim.classList.remove('open');
+ }
+ scrim.addEventListener('click', closeModals);
+
+ function requestClose() {
+ if (dirty) openModal(confirmSheet); else close();
+ }
+ function close() { post('close'); }
+
+ function setShow3D(on) {
+ ui.show3D = on;
+ canvas.classList.toggle('show-3d', on);
+ view3d.replaceChildren(icon(on ? 'map' : 'box', 22, 1.9), h('span', on ? 'Plan' : '3D'));
+ schedulePreview(0);
+ haptic('light');
+ }
+
+ /* the plan's view: a box in plan metres with the element's aspect, or null to fit */
+ function fitBox() {
+ const b = bounds();
+ const rect = plan.getBoundingClientRect();
+ const W = rect.width || 390;
+ const H = rect.height || 600;
+ // Clear of the fit button on top, a little air on the other sides.
+ const pad = { top: 64, side: 18, bottom: 18 };
+ const scale = Math.min((W - pad.side * 2) / (b.maxX - b.minX), (H - pad.top - pad.bottom) / (b.maxZ - b.minZ));
+ const w = W / scale;
+ const hh = H / scale;
+ const midY = pad.top + (H - pad.top - pad.bottom) / 2;
+ return { x: (b.minX + b.maxX) / 2 - w / 2, y: (b.minZ + b.maxZ) / 2 - midY / scale, w, h: hh };
+ }
+ new ResizeObserver(() => ui.applyView()).observe(plan);
+
+ // One finger on what is selected drags it; anywhere else it pans, and a tap picks.
+ // Two fingers pinch to zoom.
+ const fingers = new Map();
+ let gesture = null;
+ const box = () => ui.view || fitBox();
+ const spread = () => { const [a, b] = [...fingers.values()]; return Math.hypot(a.x - b.x, a.y - b.y); };
+ const middle = () => { const [a, b] = [...fingers.values()]; return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; };
+
+ plan.addEventListener('pointerdown', (ev) => {
+ plan.setPointerCapture(ev.pointerId);
+ fingers.set(ev.pointerId, { x: ev.clientX, y: ev.clientY });
+ if (fingers.size === 2) {
+ if (drag) endDrag();
+ const rect = plan.getBoundingClientRect();
+ const v = box();
+ const mid = middle();
+ gesture = { type: 'pinch', d0: spread(), v0: v, at: { x: v.x + (mid.x - rect.left) * v.w / rect.width, y: v.y + (mid.y - rect.top) * v.h / rect.height } };
+ return;
+ }
+ if (fingers.size > 2) return;
+ const el = ev.target.closest('[data-kind]');
+ const kind = el?.dataset.kind;
+ const index = Number(el?.dataset.index);
+ // A selected room is grabbed anywhere inside it, even over its furniture and lamps.
+ const room = sel.kind === 'room' && doc.rooms[sel.index];
+ const [px, pz] = planPoint(ev);
+ const inRoom = room && px >= room.rect[0] && px <= room.rect[0] + room.rect[2] && pz >= room.rect[1] && pz <= room.rect[1] + room.rect[3];
+ if (kind === 'resize' || (kind && kind !== 'none' && isSel(kind, index)) || (inRoom && kind !== 'light' && kind !== 'ac')) {
+ const what = kind === 'resize' || isSel(kind, index) ? [kind, index] : ['room', sel.index];
+ // The view holds still while something is dragged past the plan's edge.
+ if (!ui.view) ui.view = fitBox();
+ startDrag(what[0], what[1], ev);
+ gesture = { type: 'drag' };
+ return;
+ }
+ gesture = { type: 'pan', x: ev.clientX, y: ev.clientY, v0: box(), moved: false, kind, index };
+ });
+
+ plan.addEventListener('pointermove', (ev) => {
+ if (!fingers.has(ev.pointerId)) return;
+ fingers.set(ev.pointerId, { x: ev.clientX, y: ev.clientY });
+ if (!gesture) return;
+ if (gesture.type === 'drag') { moveDrag(ev); return; }
+ const rect = plan.getBoundingClientRect();
+ if (gesture.type === 'pinch' && fingers.size === 2) {
+ const fit = fitBox();
+ const w = clamp(gesture.v0.w * gesture.d0 / Math.max(1, spread()), 1.6, Math.max(fit.w * 2.5, 24));
+ const hh = w * rect.height / rect.width;
+ const mid = middle();
+ ui.view = { x: gesture.at.x - (mid.x - rect.left) * w / rect.width, y: gesture.at.y - (mid.y - rect.top) * hh / rect.height, w, h: hh };
+ ui.applyView();
+ } else if (gesture.type === 'pan') {
+ const dx = ev.clientX - gesture.x;
+ const dy = ev.clientY - gesture.y;
+ if (!gesture.moved && Math.hypot(dx, dy) < 8) return;
+ gesture.moved = true;
+ const v = gesture.v0;
+ ui.view = { ...v, x: v.x - dx * v.w / rect.width, y: v.y - dy * v.h / rect.height };
+ ui.applyView();
+ }
+ });
+
+ const lift = (ev) => {
+ if (!fingers.delete(ev.pointerId)) return;
+ if (!gesture) return;
+ if (gesture.type === 'drag') { endDrag(); gesture = null; return; }
+ if (gesture.type === 'pinch') {
+ // One finger stays down: it carries on panning from here.
+ const [rest] = [...fingers.values()];
+ gesture = rest ? { type: 'pan', x: rest.x, y: rest.y, v0: box(), moved: true } : null;
+ return;
+ }
+ if (gesture.type === 'pan' && !gesture.moved && ev.type === 'pointerup') {
+ const { kind, index } = gesture;
+ if (kind && kind !== 'none' && kind !== 'resize') { haptic('light'); select({ kind, index }); }
+ else if (ui.sheet !== 'closed') closeSheet();
+ }
+ gesture = null;
+ };
+ plan.addEventListener('pointerup', lift);
+ plan.addEventListener('pointercancel', lift);
+
+ const ui = {
+ view: null,
+ sheet: 'closed',
+ show3D: false,
+ applyView() {
+ if (ui.view) {
+ // The plan's box changed shape (the sheet came up): keep the middle and the zoom.
+ const rect = plan.getBoundingClientRect();
+ const hh = rect.width ? ui.view.w * rect.height / rect.width : ui.view.h;
+ ui.view = { ...ui.view, y: ui.view.y + (ui.view.h - hh) / 2, h: hh };
+ }
+ const v = ui.view || fitBox();
+ plan.setAttribute('viewBox', `${v.x} ${v.y} ${v.w} ${v.h}`);
+ },
+ // Something was picked (on the plan, in the list, in 3D): its details come up.
+ selected(next) {
+ closeModals();
+ if (next.kind === 'connections' || next.kind === 'service') setSheet('full');
+ else if (next.kind !== 'home' && ui.sheet === 'closed') setSheet('peek');
+ },
+ // The item just added may lie outside what is shown: show everything again.
+ reveal() { ui.view = null; ui.applyView(); },
+ headActions() {
+ const nodes = [];
+ if (sel.index != null) {
+ nodes.push(h('button.p-icon.danger', {
+ 'aria-label': 'Remove', onclick: () => { haptic('medium'); remove(sel.kind, sel.index); setSheet('closed'); },
+ }, icon('trash', 18, 2)));
+ }
+ nodes.push(h('button.p-icon', { 'aria-label': 'Close details', onclick: closeSheet }, icon('down', 20, 2.2)));
+ return h('div.p-head-actions', nodes);
+ },
+ refresh() {
+ doneBtn.textContent = dirty ? 'Save' : 'Done';
+ doneBtn.classList.toggle('primary', dirty);
+ doneBtn.disabled = dirty && !valid;
+ undoBtn.disabled = !undo.length;
+ redoBtn.disabled = !redo.length;
+ issue.textContent = valid ? '' : status.textContent;
+ issue.classList.toggle('show', !valid);
+ },
+ };
+ setSheet(sel.kind === 'connections' || sel.kind === 'service' ? 'full' : 'closed');
+ phone = ui;
+ }
+
renderSidebar();
renderPlan();
renderInspector();
@@ -857,5 +1168,22 @@ export async function bootEditor(root) {
dirty = false;
validate();
schedulePreview(0);
- window.__editor = { get doc() { return doc; }, select, tuya, links };
+ // A plan saved on the other device (the Mac, or the paired iPhone) while this editor is open.
+ incoming.planArrived = (config, from) => {
+ if (dirty) {
+ toast(`${from || 'Your other device'} saved a newer plan. Saving here replaces it.`, true);
+ return;
+ }
+ doc = structuredClone(config);
+ for (const key of Object.values(KEYS)) doc[key] ||= [];
+ nameInput.value = doc.name || 'Home';
+ if (sel.index != null && !doc[KEYS[sel.kind]]?.[sel.index]) sel = { kind: 'home' };
+ touch();
+ dirty = false;
+ validate();
+ toast(`Updated from ${from || 'your other device'}`);
+ };
+
+ window.__editor = { get doc() { return doc; }, select, tuya, links, phone };
+ post('ready');
}
diff --git a/web/src/ui/icons.js b/web/src/ui/icons.js
index 86ec3ef..6fa2817 100644
--- a/web/src/ui/icons.js
+++ b/web/src/ui/icons.js
@@ -6,6 +6,7 @@ import {
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,
+ List, Trash2, Scan, Redo2, Map as MapIcon, DoorClosed, Armchair,
} from 'lucide';
const ICONS = {
@@ -21,6 +22,7 @@ const ICONS = {
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,
+ list: List, trash: Trash2, fit: Scan, redo: Redo2, map: MapIcon, opening: DoorClosed, furniture: Armchair,
};
export function icon(name, size = 18, stroke = 1.8) {