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.

Share the device clients as a package; add iPhone sync and the island to the Mac app

0xProbability8015b0dc3214
diff --git a/core/Package.swift b/core/Package.swift
new file mode 100644
index 0000000..8c168d8
--- /dev/null
+++ b/core/Package.swift
@@ -0,0 +1,16 @@
+// swift-tools-version:5.9
+import PackageDescription
+
+// What the macOS and iOS apps share: the Smart Life / Tuya clients, the plan store
+// and the Mac ⇄ iPhone sync.
+let package = Package(
+ name: "HouseCore",
+ platforms: [.macOS(.v13), .iOS(.v17)],
+ products: [
+ .library(name: "HouseCore", targets: ["HouseCore"])
+ ],
+ targets: [
+ .target(name: "HouseCore", path: "Sources/HouseCore"),
+ .testTarget(name: "HouseCoreTests", dependencies: ["HouseCore"], path: "Tests/HouseCoreTests"),
+ ]
+)
diff --git a/core/Sources/HouseCore/DeviceHub.swift b/core/Sources/HouseCore/DeviceHub.swift
new file mode 100644
index 0000000..2583a59
--- /dev/null
+++ b/core/Sources/HouseCore/DeviceHub.swift
@@ -0,0 +1,183 @@
+import Foundation
+
+/// Everything between the UI and the real devices, shared by the Mac and the iPhone app:
+/// which backend is connected, which device of the plan is linked to which Smart Life
+/// device, sending the changes made in the panel and reading the devices' state back.
+@MainActor
+public final class DeviceHub {
+ public let log: EventLog
+ private let tuya: TuyaService
+ private let smartLife: SmartLifeService
+ /// The backend real devices are reached through: the QR-linked Smart Life account
+ /// when there is one, otherwise a Tuya Cloud project, otherwise nothing (simulation).
+ private var cloud: DeviceCloud? {
+ smartLife.isConfigured ? smartLife : (tuya.isConfigured ? tuya : nil)
+ }
+ /// App device id -> its Smart Life link, for the devices of the active plan.
+ private var links: [String: (kind: String, link: [String: Any])] = [:]
+ /// The command in flight for each real device; the next one waits for it.
+ private var commandTails: [String: Task<Void, Never>] = [:]
+ private let infrared = InfraredRemote()
+
+ /// Called after a command failed in a way that leaves the panel out of step with the
+ /// devices, so the owner can read their state again.
+ public var onStale: (() -> Void)?
+
+ /// `session` is where the Smart Life session is kept; by default `smartlife.json` in `directory`.
+ public init(directory: URL, session: SecretStore? = nil) {
+ log = EventLog(directory: directory)
+ tuya = TuyaService(directory: directory)
+ smartLife = session.map { SmartLifeService(vault: $0) } ?? SmartLifeService(directory: directory)
+ }
+
+ // MARK: - Links
+
+ public var isConnected: Bool { cloud != nil }
+ public var hasLinks: Bool { !links.isEmpty }
+ /// True when there is something to read from the cloud at all.
+ public var canPoll: Bool { cloud != nil && !links.isEmpty }
+ public var linkedDeviceCount: Int { links.count }
+
+ /// Takes the device links from `plan`; nil (a bundled demo) means everything is simulated.
+ public func setLinks(from plan: [String: Any]?) {
+ links = [:]
+ guard let plan else { return }
+ for (kind, key) in [("light", "lights"), ("ac", "acs")] {
+ for device in plan[key] as? [[String: Any]] ?? [] {
+ guard let id = device["id"] as? String, let link = device["tuya"] as? [String: Any],
+ let deviceId = link["deviceId"] as? String, !deviceId.isEmpty else { continue }
+ links[id] = (kind, link)
+ }
+ }
+ }
+
+ // MARK: - Commands
+
+ /// Sends a change made in the panel to the real device and tells the panel how it went,
+ /// so a rejected change can be rolled back there. Commands to one device run strictly
+ /// one after another, in the order this is called.
+ public func command(_ message: [String: Any], reply: @escaping ([String: Any]) -> Void) {
+ guard let cloud, let id = message["id"] as? String, let entry = links[id],
+ let deviceId = entry.link["deviceId"] as? String else {
+ reply(["ok": true]) // simulated device: nothing to send
+ return
+ }
+ let patch = message["patch"] as? [String: Any] ?? [:]
+ let state = message["state"] as? [String: Any] ?? [:]
+ let previous = commandTails[deviceId]
+ commandTails[deviceId] = Task { @MainActor in
+ await previous?.value
+ do {
+ // The first command to a device may arrive before anything is known about it.
+ await cloud.prepare(deviceId)
+ let codes = cloud.knownCodes[deviceId] ?? []
+ if entry.kind == "light" {
+ try await send(TuyaMapper.lightCommands(patch: patch, state: state, link: entry.link, codes: codes,
+ ranges: cloud.knownRanges[deviceId] ?? [:]), to: deviceId, id, cloud)
+ } else if TuyaMapper.isInfraredAC(codes) {
+ try await infrared.apply(patch: patch, state: state, to: deviceId,
+ send: { try await self.send([$0], to: deviceId, id, cloud) },
+ note: { self.log.write("\(id) \($0)") })
+ } else {
+ try await send(TuyaMapper.acCommands(patch: patch, link: entry.link, codes: codes), to: deviceId, id, cloud)
+ }
+ reply(["ok": true])
+ } catch let rejected as InfraredRemote.Rejection {
+ reply(["error": rejected.message, "failed": rejected.fields])
+ } catch {
+ reply(["error": error.localizedDescription])
+ // The panel showed the change optimistically: pull the real state back in.
+ onStale?()
+ }
+ }
+ }
+
+ private func send(_ commands: [[String: Any]], to deviceId: String, _ id: String, _ cloud: DeviceCloud) async throws {
+ guard !commands.isEmpty else { return }
+ do {
+ try await cloud.send(commands, to: deviceId)
+ log.write("\(id) \(EventLog.describe(commands)) → ok")
+ } catch {
+ log.write("\(id) \(EventLog.describe(commands)) → \(error.localizedDescription)")
+ throw error
+ }
+ }
+
+ // MARK: - State
+
+ /// What the linked devices report right now, in the shape the panel's `applyRemote`
+ /// takes. Nil when nothing is connected or the cloud could not be reached.
+ public func poll() async -> [String: Any]? {
+ let entries = links
+ guard let cloud, !entries.isEmpty else { return nil }
+ // Devices plus the temperature sensors that stand in for an AC's room reading.
+ let ids = entries.values.flatMap { [$0.link["deviceId"] as? String, $0.link["sensorId"] as? String].compactMap { $0 } }
+ guard let status = try? await cloud.status(of: Array(Set(ids)).filter { !$0.isEmpty }) else { return nil }
+ var lights: [String: Any] = [:]
+ var acs: [String: Any] = [:]
+ var features: [String: Any] = [:]
+ for (id, entry) in entries {
+ guard let deviceId = entry.link["deviceId"] as? String else { continue }
+ if entry.kind == "ac", let known = TuyaMapper.acFeatures(codes: cloud.knownCodes[deviceId] ?? [],
+ ranges: cloud.knownRanges[deviceId] ?? [:]) {
+ features[id] = known
+ }
+ if entry.kind == "light" {
+ if let dps = status[deviceId] {
+ lights[id] = TuyaMapper.lightState(from: dps, ranges: cloud.knownRanges[deviceId] ?? [:])
+ }
+ continue
+ }
+ var state = status[deviceId].map { TuyaMapper.acState(from: $0) } ?? [:]
+ if let sensorId = entry.link["sensorId"] as? String, let dps = status[sensorId],
+ let temperature = TuyaMapper.sensorTemperature(from: dps) {
+ state["roomTemp"] = temperature
+ }
+ if !state.isEmpty { acs[id] = state }
+ }
+ return ["lights": lights, "acs": acs, "features": features]
+ }
+
+ public func listDevices() async throws -> [[String: Any]] {
+ guard let cloud else { throw SmartLifeService.Failure(message: "Connect Smart Life first") }
+ return try await cloud.listDevices()
+ }
+
+ /// Read-only snapshot of what Smart Life reports for the given devices.
+ public func diagnostics(for ids: [String]) async -> [String: Any] {
+ await smartLife.diagnostics(for: ids)
+ }
+
+ // MARK: - Smart Life account
+
+ /// What the UI may know about the session: never the tokens.
+ public var smartLifeInfo: [String: Any] { smartLife.publicInfo }
+ public var isSmartLifeConnected: Bool { smartLife.isConfigured }
+ public var smartLifeUserCode: String { smartLife.session?.userCode ?? "" }
+ public var smartLifeAccount: String { smartLife.session?.username ?? "" }
+
+ /// Asks Tuya for a login ticket; `qrContent` is what the QR code must contain.
+ public func beginLogin(userCode: String) async throws -> (token: String, qrContent: String) {
+ try await smartLife.beginLogin(userCode: userCode)
+ }
+
+ /// True once the user has confirmed the login in the Smart Life app.
+ public func finishLogin(token: String, userCode: String) async -> Bool {
+ (try? await smartLife.finishLogin(token: token, userCode: userCode)) ?? false
+ }
+
+ public func signOut() { smartLife.signOut() }
+
+ // MARK: - Tuya Cloud project ("Advanced")
+
+ public var tuyaInfo: [String: Any] { tuya.publicInfo }
+
+ /// Stores the project credentials. An empty secret keeps the one already stored;
+ /// an empty access id removes them.
+ public func saveTuya(accessId: String, accessSecret: String, region: String) throws {
+ let id = accessId.trimmingCharacters(in: .whitespacesAndNewlines)
+ let secret = accessSecret.isEmpty ? (tuya.credentials?.accessSecret ?? "")
+ : accessSecret.trimmingCharacters(in: .whitespacesAndNewlines)
+ try tuya.save(id.isEmpty ? nil : TuyaService.Credentials(accessId: id, accessSecret: secret, region: region))
+ }
+}
diff --git a/core/Sources/HouseCore/EventLog.swift b/core/Sources/HouseCore/EventLog.swift
index b25e41c..b0c9bdd 100644
--- a/core/Sources/HouseCore/EventLog.swift
+++ b/core/Sources/HouseCore/EventLog.swift
@@ -3,7 +3,7 @@ import Foundation
/// A small text log of what was sent to real devices and what the cloud answered:
/// `events.log` next to the plan. It is the first thing to look at when a device
/// does not react. Never contains tokens; it stays on this Mac.
-final class EventLog {
+public final class EventLog {
private let url: URL
private static let limit = 256 * 1024
private let stamp: ISO8601DateFormatter = {
@@ -12,11 +12,11 @@ final class EventLog {
return f
}()
- init(directory: URL) { url = directory.appendingPathComponent("events.log") }
+ public init(directory: URL) { url = directory.appendingPathComponent("events.log") }
- var fileURL: URL { url }
+ public var fileURL: URL { url }
- func write(_ line: String) {
+ public func write(_ line: String) {
let data = Data("\(stamp.string(from: Date())) \(line)\n".utf8)
guard let handle = try? FileHandle(forWritingTo: url) else {
try? data.write(to: url, options: .atomic)
@@ -33,7 +33,7 @@ final class EventLog {
try? handle.write(contentsOf: data)
}
- static func describe(_ commands: [[String: Any]]) -> String {
+ public static func describe(_ commands: [[String: Any]]) -> String {
commands.map { "\($0["code"] ?? "?")=\($0["value"] ?? "?")" }.joined(separator: " ")
}
}
diff --git a/core/Sources/HouseCore/PlanStore.swift b/core/Sources/HouseCore/PlanStore.swift
index 68d90f0..f9703d2 100644
--- a/core/Sources/HouseCore/PlanStore.swift
+++ b/core/Sources/HouseCore/PlanStore.swift
@@ -1,18 +1,19 @@
import Foundation
+import CryptoKit
/// Persists which floor plan is active and the user's own plan file.
/// Everything lives in ~/Library/Application Support/HouseControl (or HOUSE_DATA_DIR).
-final class PlanStore {
- static let bundled = ["home", "studio"]
+public final class PlanStore {
+ public static let bundled = ["home", "studio"]
- let directory: URL
- var customPlanURL: URL { directory.appendingPathComponent("plan.json") }
+ public let directory: URL
+ public var customPlanURL: URL { directory.appendingPathComponent("plan.json") }
private var settingsURL: URL { directory.appendingPathComponent("settings.json") }
/// "home" / "studio" for the bundled demos, or "custom" for plan.json.
- private(set) var activePlan = "home"
+ public private(set) var activePlan = "home"
- init() {
+ public init() {
// HOUSE_DATA_DIR points the app at another folder: a throw-away one for testing or
// screenshots leaves the real plan and the Smart Life session alone.
if let custom = ProcessInfo.processInfo.environment["HOUSE_DATA_DIR"], !custom.isEmpty {
@@ -30,14 +31,27 @@ final class PlanStore {
if activePlan == "custom", customPlan() == nil { activePlan = "home" }
}
- func customPlan() -> [String: Any]? {
+ public func customPlan() -> [String: Any]? {
guard let data = try? Data(contentsOf: customPlanURL) else { return nil }
return try? JSONSerialization.jsonObject(with: data) as? [String: Any]
}
- var hasCustomPlan: Bool { FileManager.default.fileExists(atPath: customPlanURL.path) }
+ public var hasCustomPlan: Bool { FileManager.default.fileExists(atPath: customPlanURL.path) }
- func select(_ plan: String) {
+ /// The name the user gave their home, for menus.
+ public var customPlanName: String? { customPlan()?["name"] as? String }
+
+ /// Fingerprint of the user's plan as stored; two devices holding the same revision
+ /// have nothing to exchange.
+ public var customPlanRevision: String? {
+ (try? Data(contentsOf: customPlanURL)).map(Self.revision(of:))
+ }
+
+ public static func revision(of data: Data) -> String {
+ SHA256.hash(data: data).prefix(8).map { String(format: "%02x", $0) }.joined()
+ }
+
+ public func select(_ plan: String) {
guard Self.bundled.contains(plan) || (plan == "custom" && customPlan() != nil) else { return }
activePlan = plan
let data = try? JSONSerialization.data(withJSONObject: ["plan": plan])
@@ -45,23 +59,41 @@ final class PlanStore {
}
/// Stores `plan` as the user's plan and makes it active.
- func saveCustom(_ plan: [String: Any]) throws {
- let data = try JSONSerialization.data(withJSONObject: plan, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
+ public func saveCustom(_ plan: [String: Any]) throws {
+ try saveCustom(data: Self.encode(plan))
+ }
+
+ /// Stores an already serialised plan byte for byte, so its revision matches the sender's.
+ public func saveCustom(data: Data, select: Bool = true) throws {
try data.write(to: customPlanURL, options: .atomic)
- select("custom")
+ if select { self.select("custom") }
}
- func importPlan(from url: URL) throws {
- let data = try Data(contentsOf: url)
+ public static func encode(_ plan: [String: Any]) throws -> Data {
+ try JSONSerialization.data(withJSONObject: plan, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
+ }
+
+ /// Checks that `data` is a floor plan at all before it replaces the user's one.
+ public static func validate(_ data: Data) throws -> [String: Any] {
guard let plan = try JSONSerialization.jsonObject(with: data) as? [String: Any], plan["rooms"] is [Any] else {
throw NSError(domain: "HouseControl", code: 1, userInfo: [
NSLocalizedDescriptionKey: "This file is not a House Control floor plan (no \"rooms\" list)."])
}
- try saveCustom(plan)
+ return plan
+ }
+
+ public func importPlan(from url: URL) throws {
+ try saveCustom(Self.validate(try Data(contentsOf: url)))
+ }
+
+ /// Forgets the user's plan and falls back to the bundled demo.
+ public func removeCustom() {
+ try? FileManager.default.removeItem(at: customPlanURL)
+ if activePlan == "custom" { select("home") }
}
/// The plan the UI should render: the custom JSON inline, or the name of a bundled demo.
- func bootPayload() -> [String: Any] {
+ public func bootPayload() -> [String: Any] {
var boot: [String: Any] = ["plan": activePlan, "hasCustomPlan": hasCustomPlan]
if activePlan == "custom", let plan = customPlan() { boot["config"] = plan }
return boot
diff --git a/core/Sources/HouseCore/SecretStore.swift b/core/Sources/HouseCore/SecretStore.swift
new file mode 100644
index 0000000..37fcec7
--- /dev/null
+++ b/core/Sources/HouseCore/SecretStore.swift
@@ -0,0 +1,80 @@
+import Foundation
+import Security
+
+/// Where a secret (the Smart Life session, the sync key) is kept. The Mac app uses a
+/// file only its user can read, next to the plan; the iPhone app uses the Keychain.
+public protocol SecretStore {
+ func read() -> Data?
+ /// Stores `data`; nil removes the secret.
+ func write(_ data: Data?)
+ /// Changes whenever another process rewrites the secret. Nil when that cannot happen.
+ var stamp: Date? { get }
+}
+
+public struct FileSecretStore: SecretStore {
+ public let url: URL
+
+ public init(url: URL) { self.url = url }
+
+ public func read() -> Data? { try? Data(contentsOf: url) }
+
+ public func write(_ data: Data?) {
+ guard let data else {
+ try? FileManager.default.removeItem(at: url)
+ return
+ }
+ try? data.write(to: url, options: .atomic)
+ try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path)
+ }
+
+ public var stamp: Date? {
+ (try? FileManager.default.attributesOfItem(atPath: url.path))?[.modificationDate] as? Date
+ }
+}
+
+/// A generic-password Keychain item that never leaves this device (no iCloud Keychain,
+/// not part of a backup restored to another phone).
+public struct KeychainSecretStore: SecretStore {
+ public let service: String
+ public let account: String
+
+ public init(service: String, account: String) {
+ self.service = service
+ self.account = account
+ }
+
+ private var query: [String: Any] {
+ [kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: account]
+ }
+
+ public func read() -> Data? {
+ var q = query
+ q[kSecReturnData as String] = true
+ q[kSecMatchLimit as String] = kSecMatchLimitOne
+ var out: CFTypeRef?
+ guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess else { return nil }
+ return out as? Data
+ }
+
+ public func write(_ data: Data?) {
+ SecItemDelete(query as CFDictionary)
+ guard let data else { return }
+ var q = query
+ q[kSecValueData as String] = data
+ q[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
+ SecItemAdd(q as CFDictionary, nil)
+ }
+
+ public var stamp: Date? { nil }
+}
+
+/// Keeps a secret in memory only (tests, throw-away runs).
+public final class MemorySecretStore: SecretStore {
+ private var data: Data?
+ public init(_ data: Data? = nil) { self.data = data }
+ public func read() -> Data? { data }
+ public func write(_ data: Data?) { self.data = data }
+ public var stamp: Date? { nil }
+}
diff --git a/core/Sources/HouseCore/SelfTest.swift b/core/Sources/HouseCore/SelfTest.swift
new file mode 100644
index 0000000..96dcfc1
--- /dev/null
+++ b/core/Sources/HouseCore/SelfTest.swift
@@ -0,0 +1,101 @@
+import Foundation
+
+/// Offline self-checks and the read-only diagnostic behind the Mac binary's command line
+/// flags (`--selftest-mapper`, `--selftest-infrared`, `--selftest-transport`, `--diagnose`).
+public enum SelfTest {
+ /// Runs the check named in `arguments` and exits; returns when none was asked for.
+ @MainActor
+ public static func runIfRequested(_ arguments: [String] = CommandLine.arguments) {
+ // Prints the Smart Life request envelope for fixed inputs, so the port can be
+ // compared against the reference Python implementation.
+ if arguments.contains("--selftest-transport") {
+ typealias T = SmartLifeService.Transport
+ let rid = "11111111-2222-3333-4444-555555555555"
+ let hashKey = T.md5Hex(rid + "refresh-token")
+ let secret = T.secret(requestId: rid, hashKey: hashKey)
+ let enc = try! T.encrypt("{\"homeId\":\"42\"}", secret: secret, nonce: "ABCDEFGHJKMN")
+ print(hashKey, secret, enc, try! T.decrypt(enc, secret: secret),
+ T.sign(hashKey: hashKey, headers: [("X-appKey", "app"), ("X-requestId", rid), ("X-sid", ""), ("X-time", "1700000000000"), ("X-token", "tok")], query: enc, body: ""),
+ separator: "\n")
+ exit(0)
+ }
+ // Prints the commands built for typical actions.
+ if arguments.contains("--selftest-mapper") {
+ let ir: Set<String> = ["PowerOn", "PowerOff", "T", "M", "F"]
+ let bulb: Set<String> = ["switch_led", "work_mode", "bright_value_v2", "temp_value_v2", "colour_data_v2"]
+ let ranges: TuyaMapper.Ranges = ["bright_value_v2": (10, 1000), "temp_value_v2": (0, 1000)]
+ let cases: [(String, [[String: Any]])] = [
+ ("ir on+heat+24", TuyaMapper.acCommands(patch: ["on": true, "mode": "heat", "target": 24.0], link: [:], codes: ir)),
+ ("ir off", TuyaMapper.acCommands(patch: ["on": false], link: [:], codes: ir)),
+ ("ir fan high", TuyaMapper.acCommands(patch: ["fan": "high"], link: [:], codes: ir)),
+ ("bulb on 50%", TuyaMapper.lightCommands(patch: ["on": true, "brightness": 0.5], state: [:], link: [:], codes: bulb, ranges: ranges)),
+ ("bulb 2700K", TuyaMapper.lightCommands(patch: ["temp": 2700.0], state: [:], link: [:], codes: bulb, ranges: ranges)),
+ ("bulb colour", TuyaMapper.lightCommands(patch: ["color": "#ff5a4f"], state: ["brightness": 0.8], link: [:], codes: bulb, ranges: ranges)),
+ ("plug on (nothing known)", TuyaMapper.lightCommands(patch: ["on": true], state: [:], link: [:], codes: [])),
+ ]
+ for (name, commands) in cases {
+ let data = try! JSONSerialization.data(withJSONObject: commands, options: [.sortedKeys])
+ print(name, "→", String(data: data, encoding: .utf8)!)
+ }
+ exit(0)
+ }
+ // Plays typical changes against a simulated cloud remote whose temperature is fixed
+ // in Auto mode, and prints the key presses.
+ if arguments.contains("--selftest-infrared") {
+ Task { @MainActor in
+ for line in await infraredTranscript() { print(line) }
+ exit(0)
+ }
+ RunLoop.main.run()
+ }
+ // `--diagnose <id> [<id>…]` prints what Smart Life reports for those devices
+ // (status + specification). It only reads; nothing is sent to the devices.
+ if let flag = arguments.firstIndex(of: "--diagnose") {
+ let ids = Array(arguments[(flag + 1)...])
+ let hub = DeviceHub(directory: PlanStore().directory)
+ Task { @MainActor in
+ let dump = await hub.diagnostics(for: ids)
+ let data = (try? JSONSerialization.data(withJSONObject: dump, options: [.prettyPrinted, .sortedKeys])) ?? Data()
+ print(String(data: data, encoding: .utf8) ?? "{}")
+ exit(0)
+ }
+ RunLoop.main.run()
+ }
+ }
+
+ /// One line per case: the key presses an infrared AC received and how the change ended.
+ @MainActor
+ static func infraredTranscript() async -> [String] {
+ let remote = InfraredRemote()
+ remote.spacing = 0
+ var cloud: [String: Any] = ["M": 2, "T": 24, "F": 0, "power": false] // what Tuya remembers
+ var presses: [String] = []
+ let send: ([String: Any]) async throws -> Void = { command in
+ let code = command["code"] as? String ?? "", value = command["value"]
+ if code == "T", cloud["M"] as? Int == 2 || value as? Int == 31 {
+ presses.append("\(code)=\(value ?? "") ✗")
+ throw SmartLifeService.Failure(message: "command or value not support (code 2008)", code: "2008")
+ }
+ presses.append("\(code)=\(value ?? "")")
+ if code == "PowerOn" || code == "PowerOff" { cloud["power"] = code == "PowerOn" } else { cloud[code] = value }
+ }
+ let cases: [(String, [String: Any], [String: Any])] = [
+ ("fan while off (kept)", ["fan": "high"], ["on": false, "mode": "cool", "target": 24.0, "fan": "high"]),
+ ("switch on (sends the kept fan)", ["on": true], ["on": true, "mode": "cool", "target": 24.0, "fan": "high"]),
+ ("25° while the cloud is in Auto", ["target": 25.0], ["on": true, "mode": "cool", "target": 25.0, "fan": "high"]),
+ ("26° afterwards", ["target": 26.0], ["on": true, "mode": "cool", "target": 26.0, "fan": "high"]),
+ ("a setting the remote lacks", ["target": 31.0], ["on": true, "mode": "cool", "target": 31.0, "fan": "high"]),
+ ("switch off", ["on": false], ["on": false, "mode": "cool", "target": 26.0, "fan": "high"]),
+ ]
+ var lines: [String] = []
+ for (name, patch, state) in cases {
+ presses = []
+ var outcome = "ok"
+ do { try await remote.apply(patch: patch, state: state, to: "remote", send: send, note: { presses.append("(\($0))") }) }
+ catch let rejected as InfraredRemote.Rejection { outcome = "rejected \(rejected.fields): \(rejected.message)" }
+ catch { outcome = "\(error)" }
+ lines.append("\(name) → \(presses.joined(separator: " ")) → \(outcome)")
+ }
+ return lines
+ }
+}
diff --git a/core/Sources/HouseCore/SmartLifeService.swift b/core/Sources/HouseCore/SmartLifeService.swift
index 20a4abe..f8a3c5d 100644
--- a/core/Sources/HouseCore/SmartLifeService.swift
+++ b/core/Sources/HouseCore/SmartLifeService.swift
@@ -53,30 +53,33 @@ final class SmartLifeService: DeviceCloud {
var errorDescription: String? { message }
}
- private let fileURL: URL
+ private let vault: SecretStore
private(set) var session: Session?
private var sessionStamp: Date?
+ private var loaded = false
private(set) var knownCodes: [String: Set<String>] = [:]
private(set) var knownRanges: [String: TuyaMapper.Ranges] = [:]
private var refreshing = false
- init(directory: URL) {
- fileURL = directory.appendingPathComponent("smartlife.json")
- reloadSession()
+ /// The session lives in `smartlife.json` inside `directory`.
+ convenience init(directory: URL) {
+ self.init(vault: FileSecretStore(url: directory.appendingPathComponent("smartlife.json")))
}
- private var fileStamp: Date? {
- (try? FileManager.default.attributesOfItem(atPath: fileURL.path))?[.modificationDate] as? Date
+ init(vault: SecretStore) {
+ self.vault = vault
+ reloadSession()
}
/// Refreshing rotates the refresh token, so a second process (`--diagnose` next to the
/// running app) must pick up what the other one stored instead of carrying on with a
/// token that no longer works.
private func reloadSession() {
- let stamp = fileStamp
- guard stamp != sessionStamp else { return }
+ let stamp = vault.stamp
+ guard !loaded || stamp != sessionStamp else { return }
+ loaded = true
sessionStamp = stamp
- session = (try? Data(contentsOf: fileURL)).flatMap { try? JSONDecoder().decode(Session.self, from: $0) }
+ session = vault.read().flatMap { try? JSONDecoder().decode(Session.self, from: $0) }
}
var isConfigured: Bool { session != nil }
@@ -87,19 +90,14 @@ final class SmartLifeService: DeviceCloud {
private func store(_ new: Session?) {
session = new
- guard let new else {
- try? FileManager.default.removeItem(at: fileURL)
- sessionStamp = nil
- return
- }
- try? JSONEncoder().encode(new).write(to: fileURL, options: .atomic)
- try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: fileURL.path)
- sessionStamp = fileStamp
+ vault.write(new.flatMap { try? JSONEncoder().encode($0) })
+ sessionStamp = vault.stamp
}
func signOut() {
store(nil)
knownCodes = [:]
+ knownRanges = [:]
}
// MARK: - QR login
@@ -139,12 +137,7 @@ final class SmartLifeService: DeviceCloud {
}
static func qrImageDataURL(for text: String) -> String? {
- guard let filter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
- filter.setValue(Data(text.utf8), forKey: "inputMessage")
- filter.setValue("M", forKey: "inputCorrectionLevel")
- guard let output = filter.outputImage?.transformed(by: CGAffineTransform(scaleX: 10, y: 10)),
- let cg = CIContext().createCGImage(output, from: output.extent) else { return nil }
- return PNGEncoder.data(from: cg).map { "data:image/png;base64,\($0.base64EncodedString())" }
+ QRCode.png(for: text).map { "data:image/png;base64,\($0.base64EncodedString())" }
}
// MARK: - Devices
@@ -361,8 +354,18 @@ final class SmartLifeService: DeviceCloud {
}
}
-enum PNGEncoder {
- static func data(from image: CGImage) -> Data? {
+/// QR codes for the Smart Life login and for pairing an iPhone with the Mac.
+public enum QRCode {
+ public static func image(for text: String, scale: CGFloat = 10) -> CGImage? {
+ guard let filter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
+ filter.setValue(Data(text.utf8), forKey: "inputMessage")
+ filter.setValue("M", forKey: "inputCorrectionLevel")
+ guard let output = filter.outputImage?.transformed(by: CGAffineTransform(scaleX: scale, y: scale)) else { return nil }
+ return CIContext().createCGImage(output, from: output.extent)
+ }
+
+ public static func png(for text: String, scale: CGFloat = 10) -> Data? {
+ guard let image = image(for: text, scale: scale) else { return nil }
let data = NSMutableData()
guard let dest = CGImageDestinationCreateWithData(data, "public.png" as CFString, 1, nil) else { return nil }
CGImageDestinationAddImage(dest, image, nil)
diff --git a/core/Sources/HouseCore/SyncClient.swift b/core/Sources/HouseCore/SyncClient.swift
new file mode 100644
index 0000000..b430b6a
--- /dev/null
+++ b/core/Sources/HouseCore/SyncClient.swift
@@ -0,0 +1,191 @@
+import Foundation
+import Network
+import dnssd
+
+/// The iPhone's side of the sync: finds the paired Mac on the local network, stays
+/// connected while the app is open and receives the floor plan whenever it changes.
+@MainActor
+public final class SyncClient {
+ public enum Status: Equatable {
+ /// No Mac has been paired yet.
+ case unpaired
+ /// Looking for the Mac on this network.
+ case searching
+ case connecting
+ case connected
+ /// The Mac was found but would not talk to us; the text says why.
+ case failed(String)
+ }
+
+ private let store: SecretStore
+ public private(set) var pairing: SyncPairing?
+ public private(set) var status: Status = .unpaired
+ private var running = false
+ private var browser: NWBrowser?
+ private var channel: SyncChannel?
+ private var retry: DispatchWorkItem?
+ /// Set to connect straight to a host and port instead of browsing (tests).
+ var fixedEndpoint: NWEndpoint?
+
+ /// This device's name as the Mac shows it.
+ public var deviceName = "iPhone"
+ /// The revision of the plan this device already holds, so the Mac need not resend it.
+ public var planRevision: (() -> String?)?
+ public var onStatus: (() -> Void)?
+ public var onState: ((SyncState) -> Void)?
+
+ public init(store: SecretStore) {
+ self.store = store
+ pairing = store.read().flatMap { try? JSONDecoder().decode(SyncPairing.self, from: $0) }
+ status = pairing == nil ? .unpaired : .searching
+ // HOUSE_SYNC_ENDPOINT=host:port skips the search and connects there (a simulator
+ // talking to a Mac whose Bonjour advertisement is not allowed, for instance).
+ if let fixed = ProcessInfo.processInfo.environment["HOUSE_SYNC_ENDPOINT"]?.split(separator: ":"), fixed.count == 2,
+ let port = NWEndpoint.Port(String(fixed[1])) {
+ fixedEndpoint = .hostPort(host: NWEndpoint.Host(String(fixed[0])), port: port)
+ }
+ }
+
+ public var isPaired: Bool { pairing != nil }
+ public var isConnected: Bool { status == .connected }
+
+ public func pair(_ new: SyncPairing) {
+ teardown()
+ pairing = new
+ store.write(try? JSONEncoder().encode(new))
+ set(.searching)
+ if running { search() }
+ }
+
+ public func unpair() {
+ teardown()
+ pairing = nil
+ store.write(nil)
+ set(.unpaired)
+ }
+
+ /// Call when the app comes to the foreground.
+ public func start() {
+ guard !running else { return }
+ running = true
+ if pairing != nil { search() }
+ }
+
+ /// Call when the app goes to the background.
+ public func stop() {
+ running = false
+ teardown()
+ if pairing != nil { set(.searching) }
+ }
+
+ /// Asks the Mac for its current state again.
+ public func refresh() {
+ guard running, pairing != nil else { return }
+ if let channel, status == .connected { hello(on: channel) } else { teardown(); search() }
+ }
+
+ /// Asks the Mac to display `content` as a QR code (nil takes it down again). Used for
+ /// the Smart Life login, which has to be scanned by the Smart Life app on this phone.
+ @discardableResult
+ public func showQR(_ content: String?) -> Bool {
+ guard let channel, status == .connected else { return false }
+ var message: [String: Any] = ["type": "showQR"]
+ if let content { message["content"] = content }
+ channel.send(message)
+ return true
+ }
+
+ // MARK: - Connection
+
+ private func set(_ new: Status) {
+ guard new != status else { return }
+ status = new
+ onStatus?()
+ }
+
+ private func teardown() {
+ retry?.cancel()
+ retry = nil
+ browser?.cancel()
+ browser = nil
+ channel?.onClose = nil
+ channel?.close()
+ channel = nil
+ }
+
+ private func search() {
+ guard running, let pairing, channel == nil else { return }
+ if let fixedEndpoint {
+ connect(to: fixedEndpoint, pairing)
+ return
+ }
+ guard browser == nil else { return }
+ if case .failed = status {} else { set(.searching) }
+ let browser = NWBrowser(for: .bonjourWithTXTRecord(type: SyncTransport.serviceType, domain: nil), using: NWParameters())
+ browser.browseResultsChangedHandler = { [weak self] results, _ in
+ MainActor.assumeIsolated {
+ guard let self, self.channel == nil, let pairing = self.pairing else { return }
+ let match = results.first { result in
+ if case .bonjour(let txt) = result.metadata, txt["id"] == pairing.id { return true }
+ return false
+ }
+ if let match { self.connect(to: match.endpoint, pairing) }
+ }
+ }
+ browser.stateUpdateHandler = { [weak self] state in
+ MainActor.assumeIsolated {
+ guard let self else { return }
+ if case .failed = state { self.scheduleRetry() }
+ // No permission to use the local network: say so instead of searching forever.
+ if case .waiting(let error) = state, case .dns(let code) = error, code == DNSServiceErrorType(kDNSServiceErr_PolicyDenied) {
+ self.set(.failed("Allow House Control to use the local network in Settings → Privacy & Security → Local Network."))
+ }
+ }
+ }
+ self.browser = browser
+ browser.start(queue: .main)
+ }
+
+ private func connect(to endpoint: NWEndpoint, _ pairing: SyncPairing) {
+ browser?.cancel()
+ browser = nil
+ set(.connecting)
+ let channel = SyncChannel(NWConnection(to: endpoint, using: SyncTransport.parameters(key: pairing.key)))
+ self.channel = channel
+ channel.onReady = { [weak self, weak channel] in
+ guard let self, let channel else { return }
+ self.hello(on: channel)
+ }
+ channel.onMessage = { [weak self] message in
+ guard let self, let state = SyncState(message: message) else { return }
+ self.set(.connected)
+ self.onState?(state)
+ }
+ channel.onClose = { [weak self] error in
+ guard let self else { return }
+ self.channel = nil
+ // The handshake fails when the Mac's key was reset since this phone was paired.
+ if case .some(.tls) = error {
+ self.set(.failed("\(pairing.name) did not accept this pairing. Pair again from the Mac's menu: Pair iPhone…"))
+ } else if self.running {
+ self.set(.searching)
+ }
+ self.scheduleRetry()
+ }
+ channel.start()
+ }
+
+ private func hello(on channel: SyncChannel) {
+ channel.send(["type": "hello", "device": deviceName, "rev": planRevision?() ?? ""])
+ }
+
+ private func scheduleRetry() {
+ guard running, pairing != nil else { return }
+ retry?.cancel()
+ browser?.cancel()
+ browser = nil
+ let work = DispatchWorkItem { [weak self] in self?.search() }
+ retry = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: work)
+ }
+}
diff --git a/core/Sources/HouseCore/SyncProtocol.swift b/core/Sources/HouseCore/SyncProtocol.swift
new file mode 100644
index 0000000..81eb92a
--- /dev/null
+++ b/core/Sources/HouseCore/SyncProtocol.swift
@@ -0,0 +1,203 @@
+import Foundation
+import Network
+import CryptoKit
+
+/// What an iPhone needs to find its Mac and talk to it: shown by the Mac as a QR code
+/// (or copied as a link) once, kept in the Keychain afterwards.
+public struct SyncPairing: Codable, Equatable {
+ /// Identifies the Mac among the ones advertising on the network.
+ public var id: String
+ /// The Mac's name, for display.
+ public var name: String
+ /// 32 random bytes; both sides derive the connection's pre-shared key from it.
+ public var key: Data
+
+ public init(id: String, name: String, key: Data) {
+ self.id = id
+ self.name = name
+ self.key = key
+ }
+
+ public static func generate(name: String) -> SyncPairing {
+ var bytes = [UInt8](repeating: 0, count: 32)
+ _ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
+ return SyncPairing(id: UUID().uuidString.lowercased(), name: name, key: Data(bytes))
+ }
+
+ public static let scheme = "housecontrol"
+
+ /// `housecontrol://pair?v=1&id=…&name=…&key=…` — the content of the pairing QR code.
+ public var link: String {
+ var c = URLComponents()
+ c.scheme = Self.scheme
+ c.host = "pair"
+ c.queryItems = [
+ URLQueryItem(name: "v", value: "1"),
+ URLQueryItem(name: "id", value: id),
+ URLQueryItem(name: "name", value: name),
+ URLQueryItem(name: "key", value: Self.base64URL(key)),
+ ]
+ return c.string ?? ""
+ }
+
+ /// Reads a pairing link; nil for anything that is not one.
+ public init?(link: String) {
+ guard let c = URLComponents(string: link.trimmingCharacters(in: .whitespacesAndNewlines)),
+ c.scheme == Self.scheme, c.host == "pair" else { return nil }
+ let items = Dictionary((c.queryItems ?? []).map { ($0.name, $0.value ?? "") }, uniquingKeysWith: { a, _ in a })
+ guard items["v"] == "1", let id = items["id"], !id.isEmpty,
+ let key = items["key"].flatMap(Self.data(base64URL:)), key.count == 32 else { return nil }
+ self.init(id: id, name: items["name"] ?? "Mac", key: key)
+ }
+
+ static func base64URL(_ data: Data) -> String {
+ data.base64EncodedString().replacingOccurrences(of: "+", with: "-")
+ .replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")
+ }
+
+ static func data(base64URL text: String) -> Data? {
+ var s = text.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
+ while s.count % 4 != 0 { s += "=" }
+ return Data(base64Encoded: s)
+ }
+}
+
+/// What the Mac tells a paired iPhone.
+public struct SyncState {
+ public var macName: String
+ /// Fingerprint of the Mac's own floor plan; empty when it only has the demo plans.
+ public var revision: String
+ /// The plan file byte for byte. Nil when the iPhone already holds `revision`.
+ public var plan: Data?
+ /// The Smart Life "User Code" entered on the Mac, to save typing it on the phone.
+ /// It identifies the account; it is not a credential.
+ public var userCode: String
+ public var smartLifeConnected: Bool
+
+ public init(macName: String, revision: String, plan: Data?, userCode: String, smartLifeConnected: Bool) {
+ self.macName = macName
+ self.revision = revision
+ self.plan = plan
+ self.userCode = userCode
+ self.smartLifeConnected = smartLifeConnected
+ }
+
+ func message(includingPlan: Bool) -> [String: Any] {
+ var out: [String: Any] = ["type": "state", "mac": macName, "rev": revision,
+ "userCode": userCode, "smartLife": smartLifeConnected]
+ if includingPlan, let plan, let text = String(data: plan, encoding: .utf8) { out["plan"] = text }
+ return out
+ }
+
+ init?(message: [String: Any]) {
+ guard message["type"] as? String == "state" else { return nil }
+ self.init(macName: message["mac"] as? String ?? "Mac",
+ revision: message["rev"] as? String ?? "",
+ plan: (message["plan"] as? String).map { Data($0.utf8) },
+ userCode: message["userCode"] as? String ?? "",
+ smartLifeConnected: message["smartLife"] as? Bool ?? false)
+ }
+}
+
+enum SyncTransport {
+ static let serviceType = "_housecontrol._tcp"
+ static let maxFrame = 8 * 1024 * 1024
+
+ /// TLS 1.2 with a pre-shared key and nothing else: a peer that does not hold the
+ /// pairing key cannot complete the handshake, in either direction.
+ static func parameters(key: Data) -> NWParameters {
+ let tls = NWProtocolTLS.Options()
+ let options = tls.securityProtocolOptions
+ let derived = HMAC<SHA256>.authenticationCode(for: Data("HouseControl sync v1".utf8), using: SymmetricKey(data: key))
+ let psk = derived.withUnsafeBytes { DispatchData(bytes: $0) }
+ let hint = Data("housecontrol".utf8).withUnsafeBytes { DispatchData(bytes: $0) }
+ sec_protocol_options_add_pre_shared_key(options, psk as __DispatchData, hint as __DispatchData)
+ sec_protocol_options_append_tls_ciphersuite(options, tls_ciphersuite_t(rawValue: UInt16(TLS_PSK_WITH_AES_128_GCM_SHA256))!)
+ sec_protocol_options_set_min_tls_protocol_version(options, .TLSv12)
+ sec_protocol_options_set_max_tls_protocol_version(options, .TLSv12)
+
+ let tcp = NWProtocolTCP.Options()
+ tcp.enableKeepalive = true
+ tcp.keepaliveIdle = 20
+ tcp.noDelay = true
+ return NWParameters(tls: tls, tcp: tcp)
+ }
+}
+
+/// JSON messages over one connection, each prefixed with its length (4 bytes, big endian).
+/// Everything happens on the main queue.
+@MainActor
+final class SyncChannel {
+ let connection: NWConnection
+ var onReady: (() -> Void)?
+ var onMessage: (([String: Any]) -> Void)?
+ /// Called once, with the error that ended the connection if there was one.
+ var onClose: ((NWError?) -> Void)?
+ private var closed = false
+
+ init(_ connection: NWConnection) { self.connection = connection }
+
+ func start() {
+ connection.stateUpdateHandler = { [weak self] state in
+ MainActor.assumeIsolated {
+ guard let self else { return }
+ switch state {
+ case .ready:
+ self.onReady?()
+ self.receiveHeader()
+ case .failed(let error): self.finish(error)
+ case .waiting(let error): self.finish(error) // no route / refused: let the owner retry
+ case .cancelled: self.finish(nil)
+ default: break
+ }
+ }
+ }
+ connection.start(queue: .main)
+ }
+
+ func send(_ message: [String: Any]) {
+ guard !closed, let body = try? JSONSerialization.data(withJSONObject: message, options: [.withoutEscapingSlashes]) else { return }
+ var frame = Data()
+ withUnsafeBytes(of: UInt32(body.count).bigEndian) { frame.append(contentsOf: $0) }
+ frame.append(body)
+ connection.send(content: frame, completion: .contentProcessed { _ in })
+ }
+
+ func close() {
+ guard !closed else { return }
+ connection.cancel()
+ }
+
+ private func finish(_ error: NWError?) {
+ guard !closed else { return }
+ closed = true
+ connection.stateUpdateHandler = nil
+ connection.cancel()
+ onClose?(error)
+ }
+
+ private func receiveHeader() {
+ connection.receive(minimumIncompleteLength: 4, maximumLength: 4) { [weak self] data, _, isComplete, error in
+ MainActor.assumeIsolated {
+ guard let self, !self.closed else { return }
+ guard let data, data.count == 4, error == nil else { self.finish(error); return }
+ let length = Int(data.reduce(UInt32(0)) { $0 << 8 | UInt32($1) })
+ guard length > 0, length <= SyncTransport.maxFrame, !isComplete else { self.finish(nil); return }
+ self.receiveBody(length)
+ }
+ }
+ }
+
+ private func receiveBody(_ length: Int) {
+ connection.receive(minimumIncompleteLength: length, maximumLength: length) { [weak self] data, _, _, error in
+ MainActor.assumeIsolated {
+ guard let self, !self.closed else { return }
+ guard let data, data.count == length, error == nil else { self.finish(error); return }
+ if let message = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
+ self.onMessage?(message)
+ }
+ self.receiveHeader()
+ }
+ }
+ }
+}
diff --git a/core/Sources/HouseCore/SyncServer.swift b/core/Sources/HouseCore/SyncServer.swift
new file mode 100644
index 0000000..6216d27
--- /dev/null
+++ b/core/Sources/HouseCore/SyncServer.swift
@@ -0,0 +1,167 @@
+import Foundation
+import Network
+
+/// The Mac's side of the sync: advertises itself on the local network and hands its
+/// floor plan to the iPhones that were paired with it. Nothing listens until the user
+/// pairs a phone for the first time.
+@MainActor
+public final class SyncServer {
+ private let store: SecretStore
+ private var listener: NWListener?
+ private var peers: [ObjectIdentifier: Peer] = [:]
+ private var advertise = true
+ public private(set) var pairing: SyncPairing?
+ /// True once Bonjour confirmed that phones can find this Mac. It stays false when
+ /// macOS has not been allowed to let the app use the local network.
+ public private(set) var isAdvertised = false
+
+ private final class Peer {
+ let channel: SyncChannel
+ var name = ""
+ /// The plan revision this iPhone is known to hold.
+ var revision = ""
+ init(_ channel: SyncChannel) { self.channel = channel }
+ }
+
+ /// What to send: read every time a phone connects or `broadcast()` is called.
+ public var snapshot: (() -> SyncState)?
+ /// Called when a phone connects or disconnects.
+ public var onPeersChanged: (() -> Void)?
+ /// A phone asks the Mac to display the QR code of its own Smart Life login
+ /// (`content`), or to take it down again (nil). The second argument is the phone's name.
+ public var onShowQR: ((String?, String) -> Void)?
+
+ /// `store` keeps the pairing (by default `sync.json` next to the plan, readable by its user only).
+ public init(store: SecretStore) {
+ self.store = store
+ pairing = store.read().flatMap { try? JSONDecoder().decode(SyncPairing.self, from: $0) }
+ }
+
+ public var isEnabled: Bool { pairing != nil }
+ /// Names of the iPhones connected right now.
+ public var connectedDevices: [String] { peers.values.map(\.name).filter { !$0.isEmpty }.sorted() }
+ /// The port the listener got, once it is running.
+ public var port: UInt16? { listener?.port?.rawValue }
+
+ /// Makes sure this Mac can be paired with and returns what the phone has to scan.
+ @discardableResult
+ public func enable(name: String) -> SyncPairing {
+ if let pairing {
+ start()
+ return pairing
+ }
+ return reset(name: name)
+ }
+
+ /// New key: every phone paired so far has to be paired again.
+ @discardableResult
+ public func reset(name: String) -> SyncPairing {
+ let fresh = SyncPairing.generate(name: name)
+ pairing = fresh
+ store.write(try? JSONEncoder().encode(fresh))
+ restart()
+ return fresh
+ }
+
+ public func disable() {
+ pairing = nil
+ store.write(nil)
+ stop()
+ }
+
+ /// Starts listening if this Mac has been paired with before. `advertise: false` skips
+ /// Bonjour, for tests that connect to the port directly.
+ public func start(advertise: Bool = true) {
+ self.advertise = advertise
+ guard let pairing, listener == nil else { return }
+ guard let listener = try? NWListener(using: SyncTransport.parameters(key: pairing.key)) else { return }
+ if advertise {
+ var txt = NWTXTRecord()
+ txt["id"] = pairing.id
+ listener.service = NWListener.Service(name: pairing.name, type: SyncTransport.serviceType, txtRecord: txt)
+ listener.serviceRegistrationUpdateHandler = { [weak self] change in
+ MainActor.assumeIsolated {
+ guard let self, case .add = change, !self.isAdvertised else { return }
+ self.isAdvertised = true
+ self.onPeersChanged?()
+ }
+ }
+ }
+ listener.newConnectionHandler = { [weak self] connection in
+ MainActor.assumeIsolated { self?.accept(connection) }
+ }
+ listener.stateUpdateHandler = { [weak self] state in
+ MainActor.assumeIsolated {
+ // A listener that failed (network change, port lost) is replaced.
+ guard let self, case .failed = state else { return }
+ self.listener?.cancel()
+ self.listener = nil
+ self.isAdvertised = false
+ DispatchQueue.main.asyncAfter(deadline: .now() + 2) { self.start(advertise: self.advertise) }
+ }
+ }
+ self.listener = listener
+ listener.start(queue: .main)
+ }
+
+ public func stop() {
+ listener?.cancel()
+ listener = nil
+ isAdvertised = false
+ for peer in peers.values { peer.channel.close() }
+ peers = [:]
+ onPeersChanged?()
+ }
+
+ private func restart() {
+ stop()
+ start(advertise: advertise)
+ }
+
+ /// Sends the current state to every connected phone (after the plan was saved, or the
+ /// Smart Life account changed).
+ public func broadcast() {
+ guard let state = snapshot?() else { return }
+ for peer in peers.values where !peer.name.isEmpty { send(state, to: peer) }
+ }
+
+ private func send(_ state: SyncState, to peer: Peer) {
+ peer.channel.send(state.message(includingPlan: state.revision != peer.revision))
+ peer.revision = state.revision
+ }
+
+ private func accept(_ connection: NWConnection) {
+ let channel = SyncChannel(connection)
+ let peer = Peer(channel)
+ let key = ObjectIdentifier(channel)
+ peers[key] = peer
+ channel.onMessage = { [weak self, weak peer] message in
+ guard let self, let peer else { return }
+ self.handle(message, from: peer)
+ }
+ channel.onClose = { [weak self] _ in
+ guard let self, let gone = self.peers.removeValue(forKey: key) else { return }
+ if !gone.name.isEmpty {
+ self.onShowQR?(nil, gone.name)
+ self.onPeersChanged?()
+ }
+ }
+ channel.start()
+ }
+
+ private func handle(_ message: [String: Any], from peer: Peer) {
+ switch message["type"] as? String {
+ case "hello":
+ let isNew = peer.name.isEmpty
+ peer.name = (message["device"] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? "iPhone"
+ peer.revision = message["rev"] as? String ?? ""
+ if let state = snapshot?() { send(state, to: peer) }
+ if isNew { onPeersChanged?() }
+ case "showQR":
+ guard !peer.name.isEmpty else { return }
+ onShowQR?(message["content"] as? String, peer.name)
+ default:
+ break
+ }
+ }
+}
diff --git a/core/Sources/HouseCore/WebAssets.swift b/core/Sources/HouseCore/WebAssets.swift
new file mode 100644
index 0000000..f6f395e
--- /dev/null
+++ b/core/Sources/HouseCore/WebAssets.swift
@@ -0,0 +1,66 @@
+import Foundation
+import WebKit
+
+/// Serves the bundled web UI under `house://app/…` so ES modules, fetch and
+/// localStorage behave as they would on a normal origin.
+public final class AssetSchemeHandler: NSObject, WKURLSchemeHandler {
+ public static let scheme = "house"
+ public static let indexURL = "\(scheme)://app/index.html"
+ private let root: URL
+
+ public init(root: URL) { self.root = root }
+
+ private static let mime: [String: String] = [
+ "html": "text/html", "js": "text/javascript", "mjs": "text/javascript", "css": "text/css",
+ "json": "application/json", "svg": "image/svg+xml", "png": "image/png", "jpg": "image/jpeg",
+ "woff2": "font/woff2", "map": "application/json",
+ ]
+
+ public func webView(_ webView: WKWebView, start task: WKURLSchemeTask) {
+ guard let url = task.request.url else { return }
+ var path = url.path
+ if path.isEmpty || path == "/" { path = "/index.html" }
+ let file = root.appendingPathComponent(String(path.dropFirst())).standardizedFileURL
+ guard file.path.hasPrefix(root.standardizedFileURL.path), let data = try? Data(contentsOf: file) else {
+ let response = HTTPURLResponse(url: url, statusCode: 404, httpVersion: "HTTP/1.1", headerFields: nil)!
+ task.didReceive(response)
+ task.didReceive(Data())
+ task.didFinish()
+ return
+ }
+ let type = Self.mime[file.pathExtension.lowercased()] ?? "application/octet-stream"
+ let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: [
+ "Content-Type": type.hasPrefix("text/") || type.hasSuffix("json") ? "\(type); charset=utf-8" : type,
+ "Content-Length": String(data.count),
+ "Cache-Control": "no-cache",
+ ])!
+ task.didReceive(response)
+ task.didReceive(data)
+ task.didFinish()
+ }
+
+ public func webView(_ webView: WKWebView, stop task: WKURLSchemeTask) {}
+}
+
+/// JSON literals for the bridge into the web UI.
+public enum WebJSON {
+ /// `value` as JavaScript source: an object, an array or a scalar.
+ public static func literal(_ value: Any) -> String {
+ if value is NSNull { return "null" }
+ if JSONSerialization.isValidJSONObject(value),
+ let data = try? JSONSerialization.data(withJSONObject: value, options: [.withoutEscapingSlashes]) {
+ return String(data: data, encoding: .utf8) ?? "null"
+ }
+ // Scalars are not valid top-level JSON objects: wrap, encode, unwrap.
+ if let data = try? JSONSerialization.data(withJSONObject: [value]), let s = String(data: data, encoding: .utf8) {
+ return String(s.dropFirst().dropLast())
+ }
+ return "null"
+ }
+
+ /// `window.house.<function>(…args)`, guarded so a page that is still loading ignores it.
+ public static func call(_ function: String, _ args: [Any]) -> String {
+ let list = args.map(literal).joined(separator: ",")
+ return "window.house && window.house.\(function) && window.house.\(function)(\(list));"
+ }
+}
diff --git a/core/Tests/HouseCoreTests/DeviceTests.swift b/core/Tests/HouseCoreTests/DeviceTests.swift
new file mode 100644
index 0000000..1f86506
--- /dev/null
+++ b/core/Tests/HouseCoreTests/DeviceTests.swift
@@ -0,0 +1,86 @@
+import XCTest
+@testable import HouseCore
+
+@MainActor
+final class DeviceTests: XCTestCase {
+ private func json(_ commands: [[String: Any]]) -> String {
+ String(data: try! JSONSerialization.data(withJSONObject: commands, options: [.sortedKeys]), encoding: .utf8)!
+ }
+
+ func testInfraredACCommands() {
+ let ir: Set<String> = ["PowerOn", "PowerOff", "T", "M", "F"]
+ XCTAssertEqual(json(TuyaMapper.acCommands(patch: ["on": true, "mode": "heat", "target": 24.0], link: [:], codes: ir)),
+ #"[{"code":"PowerOn","value":"PowerOn"},{"code":"M","value":1},{"code":"T","value":24}]"#)
+ XCTAssertEqual(json(TuyaMapper.acCommands(patch: ["fan": "high"], link: [:], codes: ir)), #"[{"code":"F","value":3}]"#)
+ }
+
+ func testBulbCommandsUseTheDeviceRanges() {
+ let bulb: Set<String> = ["switch_led", "work_mode", "bright_value_v2", "temp_value_v2", "colour_data_v2"]
+ let ranges: TuyaMapper.Ranges = ["bright_value_v2": (10, 1000), "temp_value_v2": (0, 1000)]
+ XCTAssertEqual(json(TuyaMapper.lightCommands(patch: ["on": true, "brightness": 0.5], state: [:], link: [:], codes: bulb, ranges: ranges)),
+ #"[{"code":"switch_led","value":true},{"code":"bright_value_v2","value":505}]"#)
+ XCTAssertEqual(json(TuyaMapper.lightCommands(patch: ["on": true], state: [:], link: [:], codes: [])),
+ #"[{"code":"switch_1","value":true}]"#)
+ let state = TuyaMapper.lightState(from: [["code": "switch_led", "value": true], ["code": "bright_value_v2", "value": 505.0]], ranges: ranges)
+ XCTAssertEqual(state["on"] as? Bool, true)
+ XCTAssertEqual(state["brightness"] as? Double ?? 0, 0.5, accuracy: 0.001)
+ }
+
+ func testInfraredRemoteReplaysStateAfterARefusedKey() async {
+ let lines = await SelfTest.infraredTranscript()
+ XCTAssertEqual(lines.count, 6)
+ XCTAssertTrue(lines[0].contains("kept for the next switch-on"), lines[0])
+ XCTAssertTrue(lines[1].hasSuffix("→ ok") && lines[1].contains("PowerOn=PowerOn") && lines[1].contains("F=3"), lines[1])
+ XCTAssertTrue(lines[2].contains("T=25 ✗") && lines[2].contains("M=0") && lines[2].hasSuffix("→ ok"), lines[2])
+ XCTAssertTrue(lines[4].contains("rejected [\"target\"]"), lines[4])
+ XCTAssertTrue(lines[5].contains("PowerOff=PowerOff"), lines[5])
+ }
+
+ func testTransportEnvelopeMatchesTheReferenceSDK() throws {
+ typealias T = SmartLifeService.Transport
+ let rid = "11111111-2222-3333-4444-555555555555"
+ let hashKey = T.md5Hex(rid + "refresh-token")
+ let secret = T.secret(requestId: rid, hashKey: hashKey)
+ let cipher = try T.encrypt("{\"homeId\":\"42\"}", secret: secret, nonce: "ABCDEFGHJKMN")
+ XCTAssertEqual(try T.decrypt(cipher, secret: secret), "{\"homeId\":\"42\"}")
+ XCTAssertEqual(secret.count, 16)
+ }
+
+ func testHubSimulatesUnlinkedDevicesAndReadsLinks() {
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let hub = DeviceHub(directory: dir, session: MemorySecretStore())
+ hub.setLinks(from: ["lights": [["id": "a", "tuya": ["deviceId": "dev1"]], ["id": "b"], ["id": "c", "tuya": ["deviceId": ""]]],
+ "acs": [["id": "ac", "tuya": ["deviceId": "dev2", "sensorId": "s1"]]]])
+ XCTAssertEqual(hub.linkedDeviceCount, 2)
+ XCTAssertFalse(hub.isConnected)
+ XCTAssertFalse(hub.canPoll)
+ var reply: [String: Any]?
+ hub.command(["id": "a", "kind": "light", "patch": ["on": true]]) { reply = $0 }
+ XCTAssertEqual(reply?["ok"] as? Bool, true) // not signed in: nothing is sent anywhere
+ hub.setLinks(from: nil)
+ XCTAssertFalse(hub.hasLinks)
+ }
+
+ func testPlanStoreKeepsSyncedBytesAndRevision() throws {
+ let data = Data("{\n \"name\": \"Synced\",\n \"rooms\": []\n}".utf8)
+ XCTAssertNoThrow(try PlanStore.validate(data))
+ XCTAssertThrowsError(try PlanStore.validate(Data("{\"name\":\"x\"}".utf8)))
+ XCTAssertEqual(PlanStore.revision(of: data).count, 16)
+ XCTAssertNotEqual(PlanStore.revision(of: data), PlanStore.revision(of: data + Data(" ".utf8)))
+ }
+
+ func testSecretStores() {
+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("\(UUID().uuidString).json")
+ let file = FileSecretStore(url: url)
+ XCTAssertNil(file.read())
+ file.write(Data("secret".utf8))
+ XCTAssertEqual(file.read(), Data("secret".utf8))
+ let mode = (try? FileManager.default.attributesOfItem(atPath: url.path))?[.posixPermissions] as? Int
+ XCTAssertEqual(mode, 0o600)
+ XCTAssertNotNil(file.stamp)
+ file.write(nil)
+ XCTAssertNil(file.read())
+ }
+}
diff --git a/core/Tests/HouseCoreTests/SyncTests.swift b/core/Tests/HouseCoreTests/SyncTests.swift
new file mode 100644
index 0000000..ef24b76
--- /dev/null
+++ b/core/Tests/HouseCoreTests/SyncTests.swift
@@ -0,0 +1,147 @@
+import XCTest
+import Network
+@testable import HouseCore
+
+@MainActor
+final class SyncTests: XCTestCase {
+ func testPairingLinkRoundTrip() throws {
+ let pairing = SyncPairing.generate(name: "Studio Mac")
+ XCTAssertEqual(pairing.key.count, 32)
+ let link = pairing.link
+ XCTAssertTrue(link.hasPrefix("housecontrol://pair?"))
+ XCTAssertEqual(SyncPairing(link: " \(link)\n"), pairing)
+ }
+
+ func testPairingLinkRejectsGarbage() {
+ XCTAssertNil(SyncPairing(link: "https://example.com/pair?v=1&id=a&key=b"))
+ XCTAssertNil(SyncPairing(link: "housecontrol://pair?v=1&id=abc&key=c2hvcnQ"))
+ XCTAssertNil(SyncPairing(link: "housecontrol://pair?v=2&id=abc&key=\(SyncPairing.base64URL(Data(count: 32)))"))
+ XCTAssertNil(SyncPairing(link: "tuyaSmart--qrLogin?token=abc"))
+ }
+
+ func testStateMessageRoundTrip() {
+ let plan = Data("{\"rooms\":[]}".utf8)
+ let state = SyncState(macName: "Mac", revision: "abc", plan: plan, userCode: "u1", smartLifeConnected: true)
+ let full = SyncState(message: state.message(includingPlan: true))
+ XCTAssertEqual(full?.plan, plan)
+ XCTAssertEqual(full?.revision, "abc")
+ XCTAssertEqual(full?.userCode, "u1")
+ XCTAssertEqual(full?.smartLifeConnected, true)
+ XCTAssertNil(SyncState(message: state.message(includingPlan: false))?.plan)
+ XCTAssertNil(SyncState(message: ["type": "hello"]))
+ }
+
+ /// A server and a client in one process, over the real TLS-PSK transport.
+ private func makePair(clientKey: Data? = nil) -> (SyncServer, SyncClient) {
+ let server = SyncServer(store: MemorySecretStore())
+ let pairing = server.reset(name: "Test Mac")
+ server.stop()
+ server.start(advertise: false)
+ var forPhone = pairing
+ if let clientKey { forPhone.key = clientKey }
+ let client = SyncClient(store: MemorySecretStore())
+ client.deviceName = "Test iPhone"
+ client.pair(forPhone)
+ return (server, client)
+ }
+
+ private func waitForPort(_ server: SyncServer) async throws -> NWEndpoint {
+ for _ in 0..<100 {
+ if let port = server.port, port != 0 { return .hostPort(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: port)!) }
+ try await Task.sleep(nanoseconds: 20_000_000)
+ }
+ throw XCTSkip("The listener did not start (no network access in this environment?)")
+ }
+
+ func testPlanTravelsFromMacToPhoneAndUpdatesArePushed() async throws {
+ let (server, client) = makePair()
+ defer { client.stop(); server.stop() }
+ var plan = Data("{\"name\":\"One\",\"rooms\":[]}".utf8)
+ server.snapshot = {
+ SyncState(macName: "Test Mac", revision: PlanStore.revision(of: plan), plan: plan, userCode: "code-1", smartLifeConnected: true)
+ }
+ var held: Data?
+ client.planRevision = { held.map(PlanStore.revision(of:)) }
+
+ let first = expectation(description: "first state")
+ var received: [SyncState] = []
+ client.onState = { state in
+ received.append(state)
+ if let data = state.plan { held = data }
+ if received.count == 1 { first.fulfill() }
+ }
+ let peerSeen = expectation(description: "server saw the phone")
+ server.onPeersChanged = { if server.connectedDevices == ["Test iPhone"] { peerSeen.fulfill() } }
+
+ client.fixedEndpoint = try await waitForPort(server)
+ client.start()
+ await fulfillment(of: [first, peerSeen], timeout: 10)
+ XCTAssertEqual(client.status, .connected)
+ XCTAssertEqual(received[0].plan, plan)
+ XCTAssertEqual(received[0].userCode, "code-1")
+
+ // Asking again with the same revision must not resend the plan.
+ let second = expectation(description: "refresh")
+ client.onState = { state in received.append(state); second.fulfill() }
+ client.refresh()
+ await fulfillment(of: [second], timeout: 10)
+ XCTAssertNil(received[1].plan)
+ XCTAssertEqual(received[1].revision, PlanStore.revision(of: plan))
+
+ // Saving a new plan on the Mac reaches the phone without it asking.
+ let third = expectation(description: "push")
+ client.onState = { state in received.append(state); third.fulfill() }
+ plan = Data("{\"name\":\"Two\",\"rooms\":[]}".utf8)
+ server.broadcast()
+ await fulfillment(of: [third], timeout: 10)
+ XCTAssertEqual(received[2].plan, plan)
+ }
+
+ func testPhoneCanPutAQRCodeOnTheMac() async throws {
+ let (server, client) = makePair()
+ defer { client.stop(); server.stop() }
+ server.snapshot = { SyncState(macName: "Test Mac", revision: "", plan: nil, userCode: "", smartLifeConnected: false) }
+ let connected = expectation(description: "connected")
+ client.onState = { _ in connected.fulfill() }
+ client.fixedEndpoint = try await waitForPort(server)
+ client.start()
+ await fulfillment(of: [connected], timeout: 10)
+
+ let shown = expectation(description: "shown")
+ let hidden = expectation(description: "hidden")
+ server.onShowQR = { content, device in
+ XCTAssertEqual(device, "Test iPhone")
+ if content == "tuyaSmart--qrLogin?token=t1" { shown.fulfill() } else if content == nil { hidden.fulfill() }
+ }
+ XCTAssertTrue(client.showQR("tuyaSmart--qrLogin?token=t1"))
+ await fulfillment(of: [shown], timeout: 10)
+ // Going away takes the code down as well.
+ client.stop()
+ await fulfillment(of: [hidden], timeout: 10)
+ }
+
+ func testAWrongKeyIsRefused() async throws {
+ let (server, client) = makePair(clientKey: Data(repeating: 7, count: 32))
+ defer { client.stop(); server.stop() }
+ var served = false
+ server.snapshot = { served = true; return SyncState(macName: "Test Mac", revision: "", plan: nil, userCode: "", smartLifeConnected: false) }
+ let refused = expectation(description: "refused")
+ refused.assertForOverFulfill = false
+ client.onStatus = { if case .failed = client.status { refused.fulfill() } }
+ client.onState = { _ in XCTFail("a phone with the wrong key must not receive anything") }
+ client.fixedEndpoint = try await waitForPort(server)
+ client.start()
+ await fulfillment(of: [refused], timeout: 10)
+ XCTAssertFalse(served)
+ XCTAssertTrue(server.connectedDevices.isEmpty)
+ }
+
+ func testPairingSurvivesARestart() {
+ let store = MemorySecretStore()
+ let pairing = SyncServer(store: store).reset(name: "Mac")
+ let again = SyncServer(store: store)
+ XCTAssertEqual(again.pairing, pairing)
+ again.disable()
+ XCTAssertNil(SyncServer(store: store).pairing)
+ }
+}
diff --git a/macos/Package.swift b/macos/Package.swift
index 21ad3c9..f3beebf 100644
--- a/macos/Package.swift
+++ b/macos/Package.swift
@@ -4,7 +4,12 @@ import PackageDescription
let package = Package(
name: "HouseControl",
platforms: [.macOS(.v13)],
+ dependencies: [
+ .package(path: "../core")
+ ],
targets: [
- .executableTarget(name: "HouseControl", path: "Sources/HouseControl")
+ .executableTarget(name: "HouseControl",
+ dependencies: [.product(name: "HouseCore", package: "core")],
+ path: "Sources/HouseControl")
]
)
diff --git a/macos/Sources/HouseControl/AppDelegate.swift b/macos/Sources/HouseControl/AppDelegate.swift
index ec67a49..efd900a 100644
--- a/macos/Sources/HouseControl/AppDelegate.swift
+++ b/macos/Sources/HouseControl/AppDelegate.swift
@@ -1,26 +1,21 @@
import AppKit
import UniformTypeIdentifiers
+import HouseCore
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate {
private let plans = PlanStore()
- private lazy var tuya = TuyaService(directory: plans.directory)
- private lazy var smartLife = SmartLifeService(directory: plans.directory)
- /// The backend real devices are reached through: the QR-linked Smart Life account
- /// when there is one, otherwise a Tuya Cloud project, otherwise nothing (simulation).
- private var cloud: DeviceCloud? {
- smartLife.isConfigured ? smartLife : (tuya.isConfigured ? tuya : nil)
- }
+ /// The Smart Life / Tuya side: device links, commands and state.
+ private lazy var hub = DeviceHub(directory: plans.directory)
+ /// Hands the floor plan to paired iPhones on the local network.
+ private lazy var sync = SyncServer(store: FileSecretStore(url: plans.directory.appendingPathComponent("sync.json")))
+ private var island: IslandController?
+ private var pairingWindow: QRWindowController?
+ private var loginWindow: QRWindowController?
private var statusItem: NSStatusItem!
private var panel: PanelController!
private var editor: EditorController?
private var pollTimer: Timer?
- private lazy var log = EventLog(directory: plans.directory)
- /// App device id -> its Smart Life link, for the devices of the active plan.
- private var links: [String: (kind: String, link: [String: Any])] = [:]
- /// The command in flight for each real device; the next one waits for it.
- private var commandTails: [String: Task<Void, Never>] = [:]
- private let infrared = InfraredRemote()
func applicationDidFinishLaunching(_ notification: Notification) {
buildMainMenu()
@@ -39,9 +34,25 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
host.onMessage = { [weak self, unowned host] message in self?.handle(message, from: host) }
panel = PanelController(host: host)
panel.onVisibilityChange = { [weak self] visible in self?.setPolling(visible) }
+ hub.onStale = { [weak self] in self?.poll() }
reloadLinks()
host.load()
-
+ startSync()
+ if islandEnabled { showIsland() }
+
+ // HOUSE_SNAPSHOT_DIR=<folder> writes panel.png and island.png there a few seconds
+ // after launch: a look at the UI without a screen (see HOUSE_RENDER_HIDDEN).
+ if let folder = ProcessInfo.processInfo.environment["HOUSE_SNAPSHOT_DIR"] {
+ let directory = URL(fileURLWithPath: folder, isDirectory: true)
+ let delay = Double(ProcessInfo.processInfo.environment["HOUSE_SNAPSHOT_DELAY"] ?? "") ?? 6
+ DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in
+ self?.panel.host.snapshot(to: directory.appendingPathComponent("panel.png"))
+ self?.island?.host.snapshot(to: directory.appendingPathComponent("island.png"))
+ }
+ }
+ if ProcessInfo.processInfo.environment["HOUSE_OPEN_PAIRING"] != nil {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [weak self] in self?.pairPhone() }
+ }
if ProcessInfo.processInfo.environment["HOUSE_OPEN_EDITOR"] != nil {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [weak self] in self?.openEditor() }
}
@@ -83,6 +94,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
menu.addItem(withTitle: "Reveal Plan File", action: #selector(revealPlan), keyEquivalent: "").target = self
menu.addItem(withTitle: "Reveal Device Log", action: #selector(revealLog), keyEquivalent: "").target = self
menu.addItem(.separator())
+ let islandItem = menu.addItem(withTitle: "Show Island", action: #selector(toggleIsland), keyEquivalent: "")
+ islandItem.target = self
+ islandItem.state = island?.isShown == true ? .on : .off
+ menu.addItem(withTitle: "Pair iPhone…", action: #selector(pairPhone), keyEquivalent: "").target = self
+ for device in sync.connectedDevices {
+ let item = menu.addItem(withTitle: "\(device) is connected", action: nil, keyEquivalent: "")
+ item.image = NSImage(systemSymbolName: "iphone", accessibilityDescription: nil)
+ }
+ menu.addItem(.separator())
menu.addItem(withTitle: "Reload", action: #selector(reloadAll), keyEquivalent: "").target = self
menu.addItem(withTitle: "Quit House Control", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
statusItem.menu = menu
@@ -102,8 +122,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
private func bootPayload() -> [String: Any] {
var boot = plans.bootPayload()
- boot["tuya"] = tuya.publicInfo
- boot["smartLife"] = smartLife.publicInfo
+ boot["tuya"] = hub.tuyaInfo
+ boot["smartLife"] = hub.smartLifeInfo
if ProcessInfo.processInfo.environment["HOUSE_OPEN_EDITOR"] == "smartlife" { boot["section"] = "tuya" }
// HOUSE_OPEN_DEVICE=<id> starts the panel on that light's or AC's detail sheet.
if let device = ProcessInfo.processInfo.environment["HOUSE_OPEN_DEVICE"] { boot["openDevice"] = device }
@@ -111,20 +131,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
}
private func reloadLinks() {
- links = [:]
- guard plans.activePlan == "custom", let plan = plans.customPlan() else { return }
- for (kind, key) in [("light", "lights"), ("ac", "acs")] {
- for device in plan[key] as? [[String: Any]] ?? [] {
- guard let id = device["id"] as? String, let link = device["tuya"] as? [String: Any],
- let deviceId = link["deviceId"] as? String, !deviceId.isEmpty else { continue }
- links[id] = (kind, link)
- }
- }
+ hub.setLinks(from: plans.activePlan == "custom" ? plans.customPlan() : nil)
}
@objc private func reloadAll() {
reloadLinks()
panel.host.load()
+ if island?.isShown == true { island?.host.load() }
+ sync.broadcast()
}
@objc private func loadPlan() {
@@ -149,8 +163,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
}
@objc private func revealLog() {
- if !FileManager.default.fileExists(atPath: log.fileURL.path) { log.write("log started") }
- NSWorkspace.shared.activateFileViewerSelecting([log.fileURL])
+ if !FileManager.default.fileExists(atPath: hub.log.fileURL.path) { hub.log.write("log started") }
+ NSWorkspace.shared.activateFileViewerSelecting([hub.log.fileURL])
}
@objc private func openEditor() {
@@ -185,8 +199,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
if let summary = (message["summary"] as? [String: Any]) ?? (message["lightsOn"] != nil ? message : nil) {
updateStatus(summary)
}
+ case "state":
+ // The panel and the island are two views of one home: what changes in one is
+ // shown by the other.
+ var state = message
+ state["type"] = nil
+ for other in [panel.host, island?.host] where other !== host { other?.call("adopt", state) }
case "command":
- forward(message, from: host)
+ hub.command(message) { [weak host] in host?.reply(to: message, $0) }
case "close":
panel.hide()
case "selectPlan":
@@ -236,23 +256,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
host.reply(to: message, ["error": error.localizedDescription])
}
case "tuya.save":
- let secret = message["accessSecret"] as? String ?? ""
- let credentials = TuyaService.Credentials(
- accessId: (message["accessId"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines),
- // An empty secret field means "keep the one already stored".
- accessSecret: secret.isEmpty ? (tuya.credentials?.accessSecret ?? "") : secret.trimmingCharacters(in: .whitespacesAndNewlines),
- region: message["region"] as? String ?? "eu")
do {
- try tuya.save(credentials.accessId.isEmpty ? nil : credentials)
- host.reply(to: message, tuya.publicInfo)
+ try hub.saveTuya(accessId: message["accessId"] as? String ?? "",
+ accessSecret: message["accessSecret"] as? String ?? "",
+ region: message["region"] as? String ?? "eu")
+ host.reply(to: message, hub.tuyaInfo)
} catch {
host.reply(to: message, ["error": error.localizedDescription])
}
case "tuya.devices":
Task { @MainActor in
do {
- guard let cloud else { throw SmartLifeService.Failure(message: "Connect Smart Life first") }
- host.reply(to: message, ["devices": try await cloud.listDevices()])
+ host.reply(to: message, ["devices": try await hub.listDevices()])
} catch {
host.reply(to: message, ["error": error.localizedDescription])
}
@@ -261,9 +276,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
let userCode = message["userCode"] as? String ?? ""
Task { @MainActor in
do {
- let login = try await smartLife.beginLogin(userCode: userCode)
- host.reply(to: message, ["token": login.token,
- "qr": SmartLifeService.qrImageDataURL(for: login.qrContent) ?? ""])
+ let login = try await hub.beginLogin(userCode: userCode)
+ let png = QRCode.png(for: login.qrContent).map { "data:image/png;base64,\($0.base64EncodedString())" }
+ host.reply(to: message, ["token": login.token, "qr": png ?? ""])
} catch {
host.reply(to: message, ["error": error.localizedDescription])
}
@@ -272,73 +287,27 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
let token = message["token"] as? String ?? ""
let userCode = message["userCode"] as? String ?? ""
Task { @MainActor in
- let done = (try? await smartLife.finishLogin(token: token, userCode: userCode)) ?? false
- host.reply(to: message, ["connected": done, "info": smartLife.publicInfo])
+ let done = await hub.finishLogin(token: token, userCode: userCode)
+ host.reply(to: message, ["connected": done, "info": hub.smartLifeInfo])
+ if done { sync.broadcast() }
}
case "smartlife.signOut":
- smartLife.signOut()
- host.reply(to: message, smartLife.publicInfo)
+ hub.signOut()
+ host.reply(to: message, hub.smartLifeInfo)
+ sync.broadcast()
default:
break
}
}
- // MARK: - Smart Life
+ // MARK: - Device state
- /// Sends a change made in the panel to the real device and tells the panel how it went,
- /// so a rejected change can be rolled back there. Commands to one device run strictly
- /// one after another.
- private func forward(_ message: [String: Any], from host: WebHost) {
- guard let cloud, let id = message["id"] as? String, let entry = links[id],
- let deviceId = entry.link["deviceId"] as? String else {
- host.reply(to: message, ["ok": true]) // simulated device: nothing to send
- return
- }
- let patch = message["patch"] as? [String: Any] ?? [:]
- let state = message["state"] as? [String: Any] ?? [:]
- let previous = commandTails[deviceId]
- commandTails[deviceId] = Task { @MainActor in
- await previous?.value
- do {
- // The first command to a device may arrive before anything is known about it.
- await cloud.prepare(deviceId)
- let codes = cloud.knownCodes[deviceId] ?? []
- if entry.kind == "light" {
- try await send(TuyaMapper.lightCommands(patch: patch, state: state, link: entry.link, codes: codes,
- ranges: cloud.knownRanges[deviceId] ?? [:]), to: deviceId, id, cloud)
- } else if TuyaMapper.isInfraredAC(codes) {
- try await infrared.apply(patch: patch, state: state, to: deviceId,
- send: { try await self.send([$0], to: deviceId, id, cloud) },
- note: { self.log.write("\(id) \($0)") })
- } else {
- try await send(TuyaMapper.acCommands(patch: patch, link: entry.link, codes: codes), to: deviceId, id, cloud)
- }
- host.reply(to: message, ["ok": true])
- } catch let rejected as InfraredRemote.Rejection {
- host.reply(to: message, ["error": rejected.message, "failed": rejected.fields])
- } catch {
- host.reply(to: message, ["error": error.localizedDescription])
- // The panel showed the change optimistically: pull the real state back in.
- poll()
- }
- }
- }
-
- private func send(_ commands: [[String: Any]], to deviceId: String, _ id: String, _ cloud: DeviceCloud) async throws {
- guard !commands.isEmpty else { return }
- do {
- try await cloud.send(commands, to: deviceId)
- log.write("\(id) \(EventLog.describe(commands)) → ok")
- } catch {
- log.write("\(id) \(EventLog.describe(commands)) → \(error.localizedDescription)")
- throw error
- }
- }
-
- private func setPolling(_ on: Bool) {
+ /// Real devices are read while there is something on screen to show them in.
+ private func setPolling(_ requested: Bool) {
+ let on = requested || panel.isVisible || island?.isExpanded == true
pollTimer?.invalidate()
pollTimer = nil
- guard on, cloud != nil, !links.isEmpty else { return }
+ guard on, hub.canPoll else { return }
poll()
pollTimer = Timer.scheduledTimer(withTimeInterval: 12, repeats: true) { [weak self] _ in
MainActor.assumeIsolated { self?.poll() }
@@ -346,36 +315,122 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
}
private func poll() {
- let entries = links
- guard let cloud else { return }
Task { @MainActor in
- // Devices plus the temperature sensors that stand in for an AC's room reading.
- let ids = entries.values.flatMap { [$0.link["deviceId"] as? String, $0.link["sensorId"] as? String].compactMap { $0 } }
- guard let status = try? await cloud.status(of: Array(Set(ids)).filter { !$0.isEmpty }) else { return }
- var lights: [String: Any] = [:]
- var acs: [String: Any] = [:]
- var features: [String: Any] = [:]
- for (id, entry) in entries {
- guard let deviceId = entry.link["deviceId"] as? String else { continue }
- if entry.kind == "ac", let known = TuyaMapper.acFeatures(codes: cloud.knownCodes[deviceId] ?? [],
- ranges: cloud.knownRanges[deviceId] ?? [:]) {
- features[id] = known
- }
- if entry.kind == "light" {
- if let dps = status[deviceId] {
- lights[id] = TuyaMapper.lightState(from: dps, ranges: cloud.knownRanges[deviceId] ?? [:])
- }
- continue
- }
- var state = status[deviceId].map { TuyaMapper.acState(from: $0) } ?? [:]
- if let sensorId = entry.link["sensorId"] as? String, let dps = status[sensorId],
- let temperature = TuyaMapper.sensorTemperature(from: dps) {
- state["roomTemp"] = temperature
- }
- if !state.isEmpty { acs[id] = state }
+ guard let update = await hub.poll() else { return }
+ panel.host.call("applyRemote", update) // the island adopts it from the panel
+ }
+ }
+
+ // MARK: - Island
+
+ /// On unless switched off in the menu (or by HOUSE_ISLAND=0 for one run).
+ private var islandEnabled: Bool {
+ if let forced = ProcessInfo.processInfo.environment["HOUSE_ISLAND"] { return forced != "0" }
+ return UserDefaults.standard.object(forKey: "island") as? Bool ?? true
+ }
+
+ private func showIsland() {
+ if island == nil {
+ let host = WebHost(mode: "island", transparent: true) { [unowned self] in
+ var boot = self.plans.bootPayload()
+ boot["island"] = self.island?.bootInfo ?? [:]
+ return boot
}
- panel.host.call("applyRemote", ["lights": lights, "acs": acs, "features": features])
+ host.onMessage = { [weak self, unowned host] message in self?.handle(message, from: host) }
+ let controller = IslandController(host: host)
+ controller.onExpandedChange = { [weak self] open in self?.setPolling(open) }
+ island = controller
+ }
+ island?.show()
+ }
+
+ @objc private func toggleIsland() {
+ let show = island?.isShown != true
+ UserDefaults.standard.set(show, forKey: "island")
+ if show { showIsland() } else { island?.hide() }
+ }
+
+ // MARK: - iPhone sync
+
+ private var computerName: String { Host.current().localizedName ?? "Mac" }
+
+ private func startSync() {
+ sync.snapshot = { [unowned self] in
+ SyncState(macName: self.computerName,
+ revision: self.plans.customPlanRevision ?? "",
+ plan: try? Data(contentsOf: self.plans.customPlanURL),
+ userCode: self.hub.smartLifeUserCode,
+ smartLifeConnected: self.hub.isSmartLifeConnected)
+ }
+ 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
+ }
+
+ /// Shows the QR code an iPhone scans once to find this Mac and receive its floor plan.
+ @objc private func pairPhone() {
+ panel.hide()
+ let pairing = sync.enable(name: computerName)
+ if pairingWindow == nil {
+ let window = QRWindowController(title: "Pair iPhone")
+ window.onClose = { [weak self] in self?.pairingWindow = nil }
+ window.addButton("Copy Pairing Link") { [weak self] in
+ guard let link = self?.sync.pairing?.link else { return }
+ NSPasteboard.general.clearContents()
+ NSPasteboard.general.setString(link, forType: .string)
+ }
+ window.addButton("Reset Pairing…") { [weak self] in self?.resetPairing() }
+ pairingWindow = window
+ }
+ 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.")
+ refreshPairingWindow()
+ }
+
+ private func resetPairing() {
+ let alert = NSAlert()
+ alert.messageText = "Reset pairing?"
+ alert.informativeText = "Every iPhone paired so far stops syncing until it scans the new code."
+ alert.addButton(withTitle: "Reset")
+ alert.addButton(withTitle: "Cancel")
+ guard alert.runModal() == .alertFirstButtonReturn else { return }
+ sync.reset(name: computerName)
+ pairPhone()
+ }
+
+ private func refreshPairingWindow() {
+ let devices = sync.connectedDevices
+ if !devices.isEmpty {
+ pairingWindow?.setStatus("Connected: \(devices.joined(separator: ", "))", active: true)
+ } else if sync.isAdvertised {
+ pairingWindow?.setStatus("Waiting for an iPhone…", active: false)
+ } else {
+ // Until macOS lets the app use the local network, no phone can find this Mac.
+ pairingWindow?.setStatus("Allow Local Network access for House Control in System Settings → Privacy & Security",
+ active: false)
+ }
+ }
+
+ /// A paired iPhone signs in to Smart Life on its own, but its login code has to be
+ /// scanned by the Smart Life app on that same phone, so it borrows this Mac's screen.
+ private func showLoginCode(_ content: String?, for device: String) {
+ guard let content, content.hasPrefix("tuyaSmart--qrLogin?token=") else {
+ loginWindow?.close()
+ loginWindow = nil
+ return
+ }
+ if loginWindow == nil {
+ let window = QRWindowController(title: "Smart Life Sign-In for \(device)")
+ window.onClose = { [weak self] in self?.loginWindow = nil }
+ loginWindow = window
}
+ loginWindow?.show(code: content,
+ headline: "Scan with the Smart Life app on \(device)",
+ detail: "Open Smart Life, tap the scanner on its Home tab and confirm the login. "
+ + "This window closes by itself once the iPhone is signed in.")
+ loginWindow?.setStatus("Requested by \(device)", active: true)
}
// MARK: - Menu (gives the editor window the usual shortcuts)
diff --git a/macos/Sources/HouseControl/IslandController.swift b/macos/Sources/HouseControl/IslandController.swift
new file mode 100644
index 0000000..62941fc
--- /dev/null
+++ b/macos/Sources/HouseControl/IslandController.swift
@@ -0,0 +1,148 @@
+import AppKit
+import WebKit
+
+private final class IslandPanel: NSPanel {
+ override var canBecomeKey: Bool { false }
+ override var canBecomeMain: Bool { false }
+}
+
+/// The island: a transparent window pinned to the top of the screen, around the MacBook's
+/// notch. The web content draws a black tab there that shows what is on, springs open
+/// under the pointer and peeks out when something changes. A display without a notch
+/// gets a drawn one in the middle of its menu bar.
+@MainActor
+final class IslandController: NSObject {
+ // Must match island.css: the open island below the notch, and room for its shadow.
+ private static let open = NSSize(width: 664, height: 292)
+ private static let canvas = NSSize(width: 820, height: 470)
+ private static let ear: CGFloat = 60
+
+ let host: WebHost
+ private let window: IslandPanel
+ private var monitors: [Any] = []
+ private var pending: DispatchWorkItem?
+ /// The notch in screen coordinates (the drawn one on a display that has none).
+ private var notch = NSRect.zero
+ private var hasNotch = false
+ private(set) var isExpanded = false
+ private(set) var isShown = false
+ /// HOUSE_ISLAND_EXPANDED=1 keeps it open (screenshots).
+ private let pinned = ProcessInfo.processInfo.environment["HOUSE_ISLAND_EXPANDED"] != nil
+ var onExpandedChange: ((Bool) -> Void)?
+
+ init(host: WebHost) {
+ self.host = host
+ window = IslandPanel(contentRect: NSRect(origin: .zero, size: Self.canvas),
+ styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
+ super.init()
+ window.isOpaque = false
+ window.backgroundColor = .clear
+ window.hasShadow = false
+ window.level = NSWindow.Level(rawValue: NSWindow.Level.mainMenu.rawValue + 2) // over the menu bar
+ window.isMovable = false
+ window.hidesOnDeactivate = false
+ window.animationBehavior = .none
+ window.ignoresMouseEvents = true
+ window.contentView = host.webView
+ NotificationCenter.default.addObserver(self, selector: #selector(screensChanged),
+ name: NSApplication.didChangeScreenParametersNotification, object: nil)
+ }
+
+ /// What the web side needs to draw itself around the notch.
+ var bootInfo: [String: Any] {
+ ["notchWidth": Double(notch.width), "notchHeight": Double(notch.height), "hasNotch": hasNotch, "expanded": pinned]
+ }
+
+ func show() {
+ guard !isShown else { return }
+ isShown = true
+ place()
+ host.load()
+ window.orderFrontRegardless()
+ // Watching the pointer needs no permission; nothing is read but its position.
+ let moved: (NSEvent) -> Void = { [weak self] _ in MainActor.assumeIsolated { self?.pointerMoved() } }
+ if let global = NSEvent.addGlobalMonitorForEvents(matching: [.mouseMoved, .leftMouseDragged], handler: moved) {
+ monitors.append(global)
+ }
+ if let local = NSEvent.addLocalMonitorForEvents(matching: [.mouseMoved, .leftMouseDragged], handler: { moved($0); return $0 }) {
+ monitors.append(local)
+ }
+ if pinned { setExpanded(true) }
+ }
+
+ func hide() {
+ guard isShown else { return }
+ isShown = false
+ monitors.forEach(NSEvent.removeMonitor)
+ monitors = []
+ pending?.cancel()
+ setExpanded(false)
+ window.orderOut(nil)
+ }
+
+ @objc private func screensChanged() {
+ guard isShown else { return }
+ let before = (notch.size, hasNotch)
+ place()
+ if before != (notch.size, hasNotch) { host.load() }
+ }
+
+ /// Picks the display (the one with a notch if there is one) and pins the window to its top.
+ private func place() {
+ let screen = NSScreen.screens.first { $0.safeAreaInsets.top > 0 } ?? NSScreen.screens.first ?? NSScreen.main
+ guard let screen else { return }
+ let frame = screen.frame
+ if screen.safeAreaInsets.top > 0, let left = screen.auxiliaryTopLeftArea, let right = screen.auxiliaryTopRightArea {
+ hasNotch = true
+ notch = NSRect(x: left.maxX, y: frame.maxY - screen.safeAreaInsets.top,
+ width: max(120, right.minX - left.maxX), height: screen.safeAreaInsets.top)
+ } else {
+ hasNotch = false
+ let bar = frame.maxY - screen.visibleFrame.maxY
+ let height = bar > 10 ? bar : 28
+ notch = NSRect(x: frame.midX - 95, y: frame.maxY - height, width: 190, height: height)
+ }
+ // A real notch is black in full-screen spaces anyway; a drawn one would cover a film.
+ window.collectionBehavior = hasNotch ? [.canJoinAllSpaces, .stationary, .fullScreenAuxiliary, .ignoresCycle]
+ : [.canJoinAllSpaces, .stationary, .ignoresCycle]
+ window.setFrame(NSRect(x: (notch.midX - Self.canvas.width / 2).rounded(), y: frame.maxY - Self.canvas.height,
+ width: Self.canvas.width, height: Self.canvas.height), display: true)
+ }
+
+ private func pointerMoved() {
+ guard isShown, !pinned else { return }
+ let point = NSEvent.mouseLocation
+ if isExpanded {
+ let zone = NSRect(x: notch.midX - Self.open.width / 2 - 14, y: notch.minY - Self.open.height - 18,
+ width: Self.open.width + 28, height: notch.height + Self.open.height + 18 + 2)
+ schedule(zone.contains(point) ? nil : false, after: 0.32)
+ } else {
+ let zone = notch.insetBy(dx: -Self.ear, dy: 0).offsetBy(dx: 0, dy: 1)
+ schedule(zone.contains(point) ? true : nil, after: 0.09)
+ }
+ }
+
+ /// Opens or closes after a short dwell, so brushing past the notch does nothing; nil cancels.
+ private func schedule(_ expand: Bool?, after delay: TimeInterval) {
+ guard let expand else {
+ pending?.cancel()
+ pending = nil
+ return
+ }
+ guard pending == nil else { return }
+ let work = DispatchWorkItem { [weak self] in
+ self?.pending = nil
+ self?.setExpanded(expand)
+ }
+ pending = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: work)
+ }
+
+ private func setExpanded(_ on: Bool) {
+ guard on != isExpanded else { return }
+ isExpanded = on
+ window.ignoresMouseEvents = !on
+ host.call("islandState", on ? "expanded" : "collapsed")
+ onExpandedChange?(on)
+ }
+}
diff --git a/macos/Sources/HouseControl/SyncWindows.swift b/macos/Sources/HouseControl/SyncWindows.swift
new file mode 100644
index 0000000..76d6624
--- /dev/null
+++ b/macos/Sources/HouseControl/SyncWindows.swift
@@ -0,0 +1,116 @@
+import AppKit
+import HouseCore
+
+/// A small window around one QR code: the pairing code for an iPhone, or the Smart Life
+/// login code a paired iPhone asked this Mac to display.
+@MainActor
+final class QRWindowController: NSObject, NSWindowDelegate {
+ private let window: NSWindow
+ private let image = NSImageView()
+ private let headline = NSTextField(labelWithString: "")
+ private let detail = NSTextField(wrappingLabelWithString: "")
+ private let status = NSTextField(wrappingLabelWithString: "")
+ private let dot = NSView()
+ private let buttons = NSStackView()
+ private var actions: [() -> Void] = []
+ var onClose: (() -> Void)?
+
+ init(title: String) {
+ window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 380, height: 560),
+ styleMask: [.titled, .closable, .fullSizeContentView], backing: .buffered, defer: false)
+ super.init()
+ window.title = title
+ window.titlebarAppearsTransparent = true
+ window.isMovableByWindowBackground = true
+ window.backgroundColor = NSColor(calibratedRed: 0.04, green: 0.055, blue: 0.1, alpha: 1)
+ window.appearance = NSAppearance(named: .darkAqua)
+ window.isReleasedWhenClosed = false
+ window.level = .floating
+ window.delegate = self
+
+ // The code itself sits on a white card: scanners need the quiet zone around it.
+ let card = NSView()
+ card.wantsLayer = true
+ card.layer?.backgroundColor = NSColor.white.cgColor
+ card.layer?.cornerRadius = 22
+ image.imageScaling = .scaleProportionallyUpOrDown
+ image.translatesAutoresizingMaskIntoConstraints = false
+ card.addSubview(image)
+
+ headline.font = .systemFont(ofSize: 17, weight: .semibold)
+ headline.alignment = .center
+ detail.font = .systemFont(ofSize: 12.5)
+ detail.textColor = .secondaryLabelColor
+ detail.alignment = .center
+ status.font = .systemFont(ofSize: 12.5, weight: .medium)
+ status.textColor = .secondaryLabelColor
+ status.alignment = .center
+ status.preferredMaxLayoutWidth = 290
+ dot.wantsLayer = true
+ dot.layer?.cornerRadius = 4
+ let statusRow = NSStackView(views: [dot, status])
+ statusRow.spacing = 7
+ statusRow.alignment = .firstBaseline
+ buttons.spacing = 10
+
+ let stack = NSStackView(views: [headline, card, detail, statusRow, buttons])
+ stack.orientation = .vertical
+ stack.alignment = .centerX
+ stack.spacing = 18
+ stack.setCustomSpacing(12, after: detail)
+ stack.edgeInsets = NSEdgeInsets(top: 46, left: 30, bottom: 26, right: 30)
+ stack.translatesAutoresizingMaskIntoConstraints = false
+ let content = NSView()
+ content.addSubview(stack)
+ window.contentView = content
+ NSLayoutConstraint.activate([
+ stack.leadingAnchor.constraint(equalTo: content.leadingAnchor),
+ stack.trailingAnchor.constraint(equalTo: content.trailingAnchor),
+ stack.topAnchor.constraint(equalTo: content.topAnchor),
+ stack.bottomAnchor.constraint(equalTo: content.bottomAnchor),
+ content.widthAnchor.constraint(equalToConstant: 380),
+ card.widthAnchor.constraint(equalToConstant: 268),
+ card.heightAnchor.constraint(equalToConstant: 268),
+ image.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 18),
+ image.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -18),
+ image.topAnchor.constraint(equalTo: card.topAnchor, constant: 18),
+ image.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -18),
+ detail.widthAnchor.constraint(equalToConstant: 320),
+ dot.widthAnchor.constraint(equalToConstant: 8),
+ dot.heightAnchor.constraint(equalToConstant: 8),
+ ])
+ setStatus("", active: false)
+ }
+
+ func addButton(_ title: String, action: @escaping () -> Void) {
+ let button = NSButton(title: title, target: self, action: #selector(pressed(_:)))
+ button.bezelStyle = .rounded
+ button.controlSize = .large
+ button.tag = actions.count
+ actions.append(action)
+ buttons.addArrangedSubview(button)
+ }
+
+ @objc private func pressed(_ sender: NSButton) { actions[sender.tag]() }
+
+ func show(code: String, headline text: String, detail more: String) {
+ if let cg = QRCode.image(for: code, scale: 12) {
+ image.image = NSImage(cgImage: cg, size: NSSize(width: 232, height: 232))
+ }
+ headline.stringValue = text
+ detail.stringValue = more
+ if !window.isVisible { window.center() }
+ NSApp.activate(ignoringOtherApps: true)
+ window.makeKeyAndOrderFront(nil)
+ }
+
+ func setStatus(_ text: String, active: Bool) {
+ status.stringValue = text
+ dot.isHidden = text.isEmpty
+ dot.layer?.backgroundColor = (active ? NSColor.systemGreen : NSColor.tertiaryLabelColor).cgColor
+ }
+
+ func close() { window.close() }
+
+ func windowWillClose(_ notification: Notification) { onClose?() }
+}
diff --git a/macos/Sources/HouseControl/WebHost.swift b/macos/Sources/HouseControl/WebHost.swift
index 9d40ee2..de419f1 100644
--- a/macos/Sources/HouseControl/WebHost.swift
+++ b/macos/Sources/HouseControl/WebHost.swift
@@ -1,47 +1,14 @@
import AppKit
import WebKit
+import HouseCore
-/// Serves the bundled web UI under `house://app/…` so ES modules, fetch and
-/// localStorage behave as they would on a normal origin.
-final class AssetSchemeHandler: NSObject, WKURLSchemeHandler {
- static let scheme = "house"
- private let root: URL
-
- init(root: URL) { self.root = root }
-
- private static let mime: [String: String] = [
- "html": "text/html", "js": "text/javascript", "mjs": "text/javascript", "css": "text/css",
- "json": "application/json", "svg": "image/svg+xml", "png": "image/png", "jpg": "image/jpeg",
- "woff2": "font/woff2", "map": "application/json",
- ]
-
- func webView(_ webView: WKWebView, start task: WKURLSchemeTask) {
- guard let url = task.request.url else { return }
- var path = url.path
- if path.isEmpty || path == "/" { path = "/index.html" }
- let file = root.appendingPathComponent(String(path.dropFirst())).standardizedFileURL
- guard file.path.hasPrefix(root.standardizedFileURL.path), let data = try? Data(contentsOf: file) else {
- let response = HTTPURLResponse(url: url, statusCode: 404, httpVersion: "HTTP/1.1", headerFields: nil)!
- task.didReceive(response)
- task.didReceive(Data())
- task.didFinish()
- return
- }
- let type = Self.mime[file.pathExtension.lowercased()] ?? "application/octet-stream"
- let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: [
- "Content-Type": type.hasPrefix("text/") || type.hasSuffix("json") ? "\(type); charset=utf-8" : type,
- "Content-Length": String(data.count),
- "Cache-Control": "no-cache",
- ])!
- task.didReceive(response)
- task.didReceive(data)
- task.didFinish()
- }
-
- func webView(_ webView: WKWebView, stop task: WKURLSchemeTask) {}
+/// Takes the click that reaches a window which is not the key one (the island never is:
+/// hovering the notch must not steal the keyboard from the app you are typing in).
+private final class FirstMouseWebView: WKWebView {
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
}
-/// A WKWebView showing the web UI in one of its modes ("panel" or "editor"),
+/// A WKWebView showing the web UI in one of its modes ("panel", "editor" or "island"),
/// plus the JSON message bridge in both directions.
final class WebHost: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
let webView: WKWebView
@@ -63,7 +30,7 @@ final class WebHost: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
config.preferences.setValue(true, forKey: "developerExtrasEnabled")
// A run against a throw-away data folder must not touch the saved panel state either.
if ProcessInfo.processInfo.environment["HOUSE_DATA_DIR"] != nil { config.websiteDataStore = .nonPersistent() }
- webView = WKWebView(frame: .zero, configuration: config)
+ webView = FirstMouseWebView(frame: .zero, configuration: config)
super.init()
config.userContentController.add(self, name: "house")
webView.navigationDelegate = self
@@ -72,6 +39,13 @@ final class WebHost: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
if #available(macOS 12.0, *) { webView.underPageBackgroundColor = .clear }
}
webView.allowsMagnification = false
+ // WebKit stops rendering into windows the system reports as hidden, which is every
+ // window while the screen is locked. HOUSE_RENDER_HIDDEN=1 keeps the page drawing
+ // there, so captures can be taken on an unattended Mac.
+ if ProcessInfo.processInfo.environment["HOUSE_RENDER_HIDDEN"] != nil,
+ webView.responds(to: Selector(("_setWindowOcclusionDetectionEnabled:"))) {
+ webView.setValue(false, forKey: "windowOcclusionDetectionEnabled")
+ }
}
func load() {
@@ -79,17 +53,35 @@ final class WebHost: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
controller.removeAllUserScripts()
var boot = bootProvider()
boot["mode"] = mode
- let json = Self.json(boot)
+ let json = WebJSON.literal(boot)
controller.addUserScript(WKUserScript(source: "window.__HOUSE_BOOT__ = \(json);",
injectionTime: .atDocumentStart, forMainFrameOnly: true))
- let base = ProcessInfo.processInfo.environment["HOUSE_DEV_URL"] ?? "\(AssetSchemeHandler.scheme)://app/index.html"
+ controller.addUserScript(WKUserScript(source: Self.errorReporter, injectionTime: .atDocumentStart, forMainFrameOnly: true))
+ let base = ProcessInfo.processInfo.environment["HOUSE_DEV_URL"] ?? AssetSchemeHandler.indexURL
webView.load(URLRequest(url: URL(string: "\(base)?mode=\(mode)")!))
}
+ /// Writes a PNG of what the page shows. Works for a window that is not on screen,
+ /// which a screen capture does not.
+ func snapshot(to url: URL) {
+ webView.takeSnapshot(with: nil) { image, _ in
+ guard let tiff = image?.tiffRepresentation, let rep = NSBitmapImageRep(data: tiff) else { return }
+ try? rep.representation(using: .png, properties: [:])?.write(to: url)
+ }
+ }
+
+ /// Script errors in the page are written to the app's log (stderr, Console.app).
+ private static let errorReporter = """
+ (() => {
+ const tell = (text) => window.webkit.messageHandlers.house.postMessage({ type: 'log', text: String(text) });
+ window.addEventListener('error', (e) => tell(`${e.message} (${(e.filename || '').split('/').pop()}:${e.lineno})`), true);
+ window.addEventListener('unhandledrejection', (e) => tell(`unhandled: ${e.reason && e.reason.message || e.reason}`));
+ })();
+ """
+
/// Calls `window.house.<function>(…args)` in the page.
func call(_ function: String, _ args: Any...) {
- let list = args.map { Self.json($0) }.joined(separator: ",")
- webView.evaluateJavaScript("window.house && window.house.\(function) && window.house.\(function)(\(list));", completionHandler: nil)
+ webView.evaluateJavaScript(WebJSON.call(function, args), completionHandler: nil)
}
func reply(to message: [String: Any], _ result: Any) {
@@ -97,21 +89,12 @@ final class WebHost: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
call("reply", id, result)
}
- static func json(_ value: Any) -> String {
- if value is NSNull { return "null" }
- if JSONSerialization.isValidJSONObject(value),
- let data = try? JSONSerialization.data(withJSONObject: value, options: [.withoutEscapingSlashes]) {
- return String(data: data, encoding: .utf8) ?? "null"
- }
- // Scalars are not valid top-level JSON objects: wrap, encode, unwrap.
- if let data = try? JSONSerialization.data(withJSONObject: [value]), let s = String(data: data, encoding: .utf8) {
- return String(s.dropFirst().dropLast())
- }
- return "null"
- }
-
func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
guard let body = message.body as? [String: Any] else { return }
+ if body["type"] as? String == "log" {
+ NSLog("House Control web (%@): %@", mode, body["text"] as? String ?? "")
+ return
+ }
onMessage?(body)
}
diff --git a/macos/Sources/HouseControl/main.swift b/macos/Sources/HouseControl/main.swift
index 774bd15..34db1db 100644
--- a/macos/Sources/HouseControl/main.swift
+++ b/macos/Sources/HouseControl/main.swift
@@ -1,89 +1,11 @@
import AppKit
+import HouseCore
MainActor.assumeIsolated {
- // `HouseControl --selftest-transport` prints the Smart Life request envelope for fixed
- // inputs, so the port can be compared against the reference Python implementation.
- if CommandLine.arguments.contains("--selftest-transport") {
- typealias T = SmartLifeService.Transport
- let rid = "11111111-2222-3333-4444-555555555555"
- let hashKey = T.md5Hex(rid + "refresh-token")
- let secret = T.secret(requestId: rid, hashKey: hashKey)
- let enc = try! T.encrypt("{\"homeId\":\"42\"}", secret: secret, nonce: "ABCDEFGHJKMN")
- print(hashKey, secret, enc, try! T.decrypt(enc, secret: secret),
- T.sign(hashKey: hashKey, headers: [("X-appKey", "app"), ("X-requestId", rid), ("X-sid", ""), ("X-time", "1700000000000"), ("X-token", "tok")], query: enc, body: ""),
- separator: "\n")
- exit(0)
- }
- // `HouseControl --selftest-mapper` prints the commands built for typical actions.
- if CommandLine.arguments.contains("--selftest-mapper") {
- let ir: Set<String> = ["PowerOn", "PowerOff", "T", "M", "F"]
- let bulb: Set<String> = ["switch_led", "work_mode", "bright_value_v2", "temp_value_v2", "colour_data_v2"]
- let ranges: TuyaMapper.Ranges = ["bright_value_v2": (10, 1000), "temp_value_v2": (0, 1000)]
- let cases: [(String, [[String: Any]])] = [
- ("ir on+heat+24", TuyaMapper.acCommands(patch: ["on": true, "mode": "heat", "target": 24.0], link: [:], codes: ir)),
- ("ir off", TuyaMapper.acCommands(patch: ["on": false], link: [:], codes: ir)),
- ("ir fan high", TuyaMapper.acCommands(patch: ["fan": "high"], link: [:], codes: ir)),
- ("bulb on 50%", TuyaMapper.lightCommands(patch: ["on": true, "brightness": 0.5], state: [:], link: [:], codes: bulb, ranges: ranges)),
- ("bulb 2700K", TuyaMapper.lightCommands(patch: ["temp": 2700.0], state: [:], link: [:], codes: bulb, ranges: ranges)),
- ("bulb colour", TuyaMapper.lightCommands(patch: ["color": "#ff5a4f"], state: ["brightness": 0.8], link: [:], codes: bulb, ranges: ranges)),
- ("plug on (nothing known)", TuyaMapper.lightCommands(patch: ["on": true], state: [:], link: [:], codes: [])),
- ]
- for (name, commands) in cases {
- let data = try! JSONSerialization.data(withJSONObject: commands, options: [.sortedKeys])
- print(name, "→", String(data: data, encoding: .utf8)!)
- }
- exit(0)
- }
- // `HouseControl --selftest-infrared` plays typical changes against a simulated cloud
- // remote whose temperature is fixed in Auto mode, and prints the key presses.
- if CommandLine.arguments.contains("--selftest-infrared") {
- Task { @MainActor in
- let remote = InfraredRemote()
- remote.spacing = 0
- var cloud: [String: Any] = ["M": 2, "T": 24, "F": 0, "power": false] // what Tuya remembers
- var presses: [String] = []
- let send: ([String: Any]) async throws -> Void = { command in
- let code = command["code"] as? String ?? "", value = command["value"]
- if code == "T", cloud["M"] as? Int == 2 || value as? Int == 31 {
- presses.append("\(code)=\(value ?? "") ✗")
- throw SmartLifeService.Failure(message: "command or value not support (code 2008)", code: "2008")
- }
- presses.append("\(code)=\(value ?? "")")
- if code == "PowerOn" || code == "PowerOff" { cloud["power"] = code == "PowerOn" } else { cloud[code] = value }
- }
- let cases: [(String, [String: Any], [String: Any])] = [
- ("fan while off (kept)", ["fan": "high"], ["on": false, "mode": "cool", "target": 24.0, "fan": "high"]),
- ("switch on (sends the kept fan)", ["on": true], ["on": true, "mode": "cool", "target": 24.0, "fan": "high"]),
- ("25° while the cloud is in Auto", ["target": 25.0], ["on": true, "mode": "cool", "target": 25.0, "fan": "high"]),
- ("26° afterwards", ["target": 26.0], ["on": true, "mode": "cool", "target": 26.0, "fan": "high"]),
- ("a setting the remote lacks", ["target": 31.0], ["on": true, "mode": "cool", "target": 31.0, "fan": "high"]),
- ("switch off", ["on": false], ["on": false, "mode": "cool", "target": 26.0, "fan": "high"]),
- ]
- for (name, patch, state) in cases {
- presses = []
- var outcome = "ok"
- do { try await remote.apply(patch: patch, state: state, to: "remote", send: send, note: { presses.append("(\($0))") }) }
- catch let rejected as InfraredRemote.Rejection { outcome = "rejected \(rejected.fields): \(rejected.message)" }
- catch { outcome = "\(error)" }
- print(name, "→", presses.joined(separator: " "), "→", outcome)
- }
- exit(0)
- }
- RunLoop.main.run()
- }
- // `HouseControl --diagnose <id> [<id>…]` prints what Smart Life reports for those devices
- // (status + specification). It only reads; nothing is sent to the devices.
- if let flag = CommandLine.arguments.firstIndex(of: "--diagnose") {
- let ids = Array(CommandLine.arguments[(flag + 1)...])
- let service = SmartLifeService(directory: PlanStore().directory)
- Task { @MainActor in
- let dump = await service.diagnostics(for: ids)
- let data = (try? JSONSerialization.data(withJSONObject: dump, options: [.prettyPrinted, .sortedKeys])) ?? Data()
- print(String(data: data, encoding: .utf8) ?? "{}")
- exit(0)
- }
- RunLoop.main.run()
- }
+ // `--selftest-mapper`, `--selftest-infrared`, `--selftest-transport` and
+ // `--diagnose <id>…` print their result and exit without starting the app.
+ SelfTest.runIfRequested()
+
let app = NSApplication.shared
let delegate = AppDelegate()
app.delegate = delegate
diff --git a/scripts/build-app.sh b/scripts/build-app.sh
index 5acd303..ee2546c 100755
--- a/scripts/build-app.sh
+++ b/scripts/build-app.sh
@@ -36,6 +36,8 @@ cat > "$APP/Contents/Info.plist" <<PLIST
<key>CFBundleVersion</key><string>1</string>
<key>LSMinimumSystemVersion</key><string>13.0</string>
<key>LSUIElement</key><true/>
+ <key>NSLocalNetworkUsageDescription</key><string>House Control lets the iPhones you paired find this Mac on your network to receive your floor plan.</string>
+ <key>NSBonjourServices</key><array><string>_housecontrol._tcp</string></array>
<key>NSHighResolutionCapable</key><true/>
</dict>
</plist>