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.

Add the native macOS shell and the Smart Life / Tuya clients

0xProbability3313e3928bc1
diff --git a/macos/Package.swift b/macos/Package.swift
new file mode 100644
index 0000000..21ad3c9
--- /dev/null
+++ b/macos/Package.swift
@@ -0,0 +1,10 @@
+// swift-tools-version:5.9
+import PackageDescription
+
+let package = Package(
+ name: "HouseControl",
+ platforms: [.macOS(.v13)],
+ targets: [
+ .executableTarget(name: "HouseControl", path: "Sources/HouseControl")
+ ]
+)
diff --git a/macos/Sources/HouseControl/AppDelegate.swift b/macos/Sources/HouseControl/AppDelegate.swift
new file mode 100644
index 0000000..ec67a49
--- /dev/null
+++ b/macos/Sources/HouseControl/AppDelegate.swift
@@ -0,0 +1,411 @@
+import AppKit
+import UniformTypeIdentifiers
+
+@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)
+ }
+ 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()
+
+ statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
+ if let button = statusItem.button {
+ button.image = symbol("house.fill")
+ button.imagePosition = .imageLeading
+ button.target = self
+ button.action = #selector(statusItemClicked)
+ button.sendAction(on: [.leftMouseUp, .rightMouseUp])
+ button.toolTip = "House Control"
+ }
+
+ let host = WebHost(mode: "panel", transparent: true) { [unowned self] in self.bootPayload() }
+ 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) }
+ reloadLinks()
+ host.load()
+
+ if ProcessInfo.processInfo.environment["HOUSE_OPEN_EDITOR"] != nil {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [weak self] in self?.openEditor() }
+ }
+ if ProcessInfo.processInfo.environment["HOUSE_OPEN_ON_LAUNCH"] != nil {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { [weak self] in self?.togglePanel() }
+ }
+ }
+
+ func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }
+
+ // MARK: - Status item
+
+ private func symbol(_ name: String) -> NSImage? {
+ let image = NSImage(systemSymbolName: name, accessibilityDescription: "House Control")?
+ .withSymbolConfiguration(NSImage.SymbolConfiguration(pointSize: 14, weight: .medium))
+ image?.isTemplate = true
+ return image
+ }
+
+ private func updateStatus(_ summary: [String: Any]) {
+ guard let button = statusItem.button else { return }
+ let lights = summary["lightsOn"] as? Int ?? 0
+ let acOn = summary["acOn"] as? Int ?? 0
+ var parts: [String] = []
+ if lights > 0 { parts.append("\(lights)") }
+ if acOn > 0, let target = summary["acTarget"] as? Int { parts.append("\(target)°") }
+ button.image = symbol(lights > 0 || acOn > 0 ? "house.fill" : "house")
+ button.attributedTitle = NSAttributedString(
+ string: parts.isEmpty ? "" : " " + parts.joined(separator: " · "),
+ attributes: [.font: NSFont.monospacedDigitSystemFont(ofSize: 13, weight: .medium)])
+ }
+
+ @objc private func statusItemClicked() {
+ if NSApp.currentEvent?.type == .rightMouseUp {
+ panel.hide()
+ let menu = NSMenu()
+ menu.addItem(withTitle: "Edit Home…", action: #selector(openEditor), keyEquivalent: "").target = self
+ menu.addItem(withTitle: "Load Floor Plan…", action: #selector(loadPlan), keyEquivalent: "").target = self
+ 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())
+ 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
+ statusItem.button?.performClick(nil)
+ statusItem.menu = nil
+ return
+ }
+ togglePanel()
+ }
+
+ private func togglePanel() {
+ guard let button = statusItem.button else { return }
+ panel.toggle(below: button)
+ }
+
+ // MARK: - Plans
+
+ private func bootPayload() -> [String: Any] {
+ var boot = plans.bootPayload()
+ boot["tuya"] = tuya.publicInfo
+ boot["smartLife"] = smartLife.publicInfo
+ 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 }
+ return boot
+ }
+
+ 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)
+ }
+ }
+ }
+
+ @objc private func reloadAll() {
+ reloadLinks()
+ panel.host.load()
+ }
+
+ @objc private func loadPlan() {
+ panel.hide()
+ NSApp.activate(ignoringOtherApps: true)
+ let open = NSOpenPanel()
+ open.title = "Choose a floor plan"
+ open.allowedContentTypes = [.json]
+ guard open.runModal() == .OK, let url = open.url else { return }
+ do {
+ try plans.importPlan(from: url)
+ reloadAll()
+ editor?.host.load()
+ } catch {
+ alert("Could not load this floor plan", error.localizedDescription)
+ }
+ }
+
+ @objc private func revealPlan() {
+ let url = plans.hasCustomPlan ? plans.customPlanURL : WebHost.assetRoot.appendingPathComponent("plans/\(plans.activePlan).json")
+ NSWorkspace.shared.activateFileViewerSelecting([url])
+ }
+
+ @objc private func revealLog() {
+ if !FileManager.default.fileExists(atPath: log.fileURL.path) { log.write("log started") }
+ NSWorkspace.shared.activateFileViewerSelecting([log.fileURL])
+ }
+
+ @objc private func openEditor() {
+ panel.hide()
+ if editor == nil {
+ let host = WebHost(mode: "editor", transparent: false) { [unowned self] in self.bootPayload() }
+ host.onMessage = { [weak self, unowned host] message in self?.handle(message, from: host) }
+ let controller = EditorController(host: host)
+ controller.onClose = { [weak self, unowned host] in
+ host.webView.configuration.userContentController.removeScriptMessageHandler(forName: "house")
+ self?.editor = nil
+ }
+ editor = controller
+ host.load()
+ }
+ editor?.show()
+ }
+
+ private func alert(_ title: String, _ text: String) {
+ NSApp.activate(ignoringOtherApps: true)
+ let alert = NSAlert()
+ alert.messageText = title
+ alert.informativeText = text
+ alert.runModal()
+ }
+
+ // MARK: - Messages from the web UI
+
+ private func handle(_ message: [String: Any], from host: WebHost) {
+ switch message["type"] as? String {
+ case "ready", "summary":
+ if let summary = (message["summary"] as? [String: Any]) ?? (message["lightsOn"] != nil ? message : nil) {
+ updateStatus(summary)
+ }
+ case "command":
+ forward(message, from: host)
+ case "close":
+ panel.hide()
+ case "selectPlan":
+ if let plan = message["plan"] as? String {
+ plans.select(plan)
+ reloadAll()
+ editor?.host.load()
+ }
+ case "loadPlan": loadPlan()
+ case "revealPlan": revealPlan()
+ case "openEditor": openEditor()
+ case "quit": NSApp.terminate(nil)
+
+ // Editor
+ case "savePlan":
+ guard let config = message["config"] as? [String: Any] else { return }
+ do {
+ try plans.saveCustom(config)
+ reloadAll()
+ host.reply(to: message, ["ok": true, "path": plans.customPlanURL.path])
+ } catch {
+ host.reply(to: message, ["error": error.localizedDescription])
+ }
+ case "importPlan":
+ let open = NSOpenPanel()
+ open.allowedContentTypes = [.json]
+ guard open.runModal() == .OK, let url = open.url,
+ let data = try? Data(contentsOf: url),
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
+ host.reply(to: message, ["cancelled": true])
+ return
+ }
+ host.reply(to: message, ["config": json])
+ case "exportPlan":
+ guard let config = message["config"] as? [String: Any] else { return }
+ let save = NSSavePanel()
+ save.allowedContentTypes = [.json]
+ save.nameFieldStringValue = "\((config["name"] as? String ?? "home").lowercased()).json"
+ guard save.runModal() == .OK, let url = save.url else {
+ host.reply(to: message, ["cancelled": true])
+ return
+ }
+ do {
+ try JSONSerialization.data(withJSONObject: config, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]).write(to: url)
+ host.reply(to: message, ["ok": true])
+ } catch {
+ 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)
+ } 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()])
+ } catch {
+ host.reply(to: message, ["error": error.localizedDescription])
+ }
+ }
+ case "smartlife.begin":
+ 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) ?? ""])
+ } catch {
+ host.reply(to: message, ["error": error.localizedDescription])
+ }
+ }
+ case "smartlife.poll":
+ 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])
+ }
+ case "smartlife.signOut":
+ smartLife.signOut()
+ host.reply(to: message, smartLife.publicInfo)
+ default:
+ break
+ }
+ }
+
+ // MARK: - Smart Life
+
+ /// 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) {
+ pollTimer?.invalidate()
+ pollTimer = nil
+ guard on, cloud != nil, !links.isEmpty else { return }
+ poll()
+ pollTimer = Timer.scheduledTimer(withTimeInterval: 12, repeats: true) { [weak self] _ in
+ MainActor.assumeIsolated { self?.poll() }
+ }
+ }
+
+ 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 }
+ }
+ panel.host.call("applyRemote", ["lights": lights, "acs": acs, "features": features])
+ }
+ }
+
+ // MARK: - Menu (gives the editor window the usual shortcuts)
+
+ private func buildMainMenu() {
+ let main = NSMenu()
+ let appItem = NSMenuItem()
+ let appMenu = NSMenu()
+ appMenu.addItem(withTitle: "Quit House Control", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
+ appItem.submenu = appMenu
+ main.addItem(appItem)
+
+ let editItem = NSMenuItem()
+ let edit = NSMenu(title: "Edit")
+ edit.addItem(withTitle: "Undo", action: Selector(("undo:")), keyEquivalent: "z")
+ edit.addItem(withTitle: "Redo", action: Selector(("redo:")), keyEquivalent: "Z")
+ edit.addItem(.separator())
+ edit.addItem(withTitle: "Cut", action: #selector(NSText.cut(_:)), keyEquivalent: "x")
+ edit.addItem(withTitle: "Copy", action: #selector(NSText.copy(_:)), keyEquivalent: "c")
+ edit.addItem(withTitle: "Paste", action: #selector(NSText.paste(_:)), keyEquivalent: "v")
+ edit.addItem(withTitle: "Select All", action: #selector(NSText.selectAll(_:)), keyEquivalent: "a")
+ editItem.submenu = edit
+ main.addItem(editItem)
+
+ let windowItem = NSMenuItem()
+ let window = NSMenu(title: "Window")
+ window.addItem(withTitle: "Close", action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w")
+ window.addItem(withTitle: "Minimize", action: #selector(NSWindow.performMiniaturize(_:)), keyEquivalent: "m")
+ windowItem.submenu = window
+ main.addItem(windowItem)
+ NSApp.mainMenu = main
+ }
+}
diff --git a/macos/Sources/HouseControl/EditorController.swift b/macos/Sources/HouseControl/EditorController.swift
new file mode 100644
index 0000000..d15e73d
--- /dev/null
+++ b/macos/Sources/HouseControl/EditorController.swift
@@ -0,0 +1,36 @@
+import AppKit
+import WebKit
+
+/// Regular window hosting the home editor (rooms, devices, Smart Life links).
+final class EditorController: NSObject, NSWindowDelegate {
+ let host: WebHost
+ private let window: NSWindow
+ var onClose: (() -> Void)?
+
+ init(host: WebHost) {
+ self.host = host
+ window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1240, height: 800),
+ styleMask: [.titled, .closable, .miniaturizable, .resizable],
+ backing: .buffered, defer: false)
+ super.init()
+ window.title = "House Control — Edit Home"
+ window.titlebarAppearsTransparent = true
+ window.backgroundColor = NSColor(calibratedRed: 0.04, green: 0.055, blue: 0.1, alpha: 1)
+ window.appearance = NSAppearance(named: .darkAqua)
+ window.minSize = NSSize(width: 980, height: 640)
+ window.isReleasedWhenClosed = false
+ window.delegate = self
+ window.contentView = host.webView
+ window.center()
+ window.setFrameAutosaveName("HouseControlEditor")
+ }
+
+ func show() {
+ NSApp.activate(ignoringOtherApps: true)
+ window.makeKeyAndOrderFront(nil)
+ }
+
+ func windowWillClose(_ notification: Notification) {
+ onClose?()
+ }
+}
diff --git a/macos/Sources/HouseControl/EventLog.swift b/macos/Sources/HouseControl/EventLog.swift
new file mode 100644
index 0000000..b25e41c
--- /dev/null
+++ b/macos/Sources/HouseControl/EventLog.swift
@@ -0,0 +1,39 @@
+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 {
+ private let url: URL
+ private static let limit = 256 * 1024
+ private let stamp: ISO8601DateFormatter = {
+ let f = ISO8601DateFormatter()
+ f.timeZone = .current
+ return f
+ }()
+
+ init(directory: URL) { url = directory.appendingPathComponent("events.log") }
+
+ var fileURL: URL { url }
+
+ 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)
+ return
+ }
+ defer { try? handle.close() }
+ // Keep the newer half once the file has grown past the limit.
+ if let size = try? handle.seekToEnd(), size > Self.limit, let old = try? Data(contentsOf: url) {
+ let tail = old.suffix(Self.limit / 2)
+ let cut = tail.firstIndex(of: 0x0A).map { tail.suffix(from: tail.index(after: $0)) } ?? tail
+ try? (cut + data).write(to: url, options: .atomic)
+ return
+ }
+ try? handle.write(contentsOf: data)
+ }
+
+ static func describe(_ commands: [[String: Any]]) -> String {
+ commands.map { "\($0["code"] ?? "?")=\($0["value"] ?? "?")" }.joined(separator: " ")
+ }
+}
diff --git a/macos/Sources/HouseControl/InfraredRemote.swift b/macos/Sources/HouseControl/InfraredRemote.swift
new file mode 100644
index 0000000..de22b20
--- /dev/null
+++ b/macos/Sources/HouseControl/InfraredRemote.swift
@@ -0,0 +1,81 @@
+import Foundation
+
+/// Drives air conditioners that are a remote control learned by an infrared blaster.
+///
+/// Such an AC is not a device with a state of its own. Tuya keeps a virtual remote in
+/// the cloud; every change is one key press (`PowerOn`, `PowerOff`, `M`, `T`, `F`) that
+/// the blaster transmits, and the cloud works out the infrared code from the state it
+/// remembers for that remote. Three things follow:
+/// - keys go out one at a time, a second apart (several in one request are refused);
+/// - nothing is transmitted while the AC is off: what changed is sent when it is switched on;
+/// - when a key is refused (code 2008) the cloud's idea of the remote usually differs
+/// from ours, e.g. it is in a mode with a fixed temperature. The rest of our state is
+/// replayed once and the key retried.
+@MainActor
+final class InfraredRemote {
+ struct Rejection: Error {
+ let message: String
+ /// The parts of the change that did not reach the AC.
+ let fields: [String]
+ }
+
+ /// Seconds between two key presses of the same remote.
+ var spacing: TimeInterval = 1.0
+ private static let fields = ["on", "mode", "target", "fan"]
+ private var lastKey: [String: Date] = [:]
+ /// Settings changed while the AC was off, to be sent along when it is switched on.
+ private var deferred: [String: Set<String>] = [:]
+
+ /// Brings the remote `deviceId` from where it was to `state` (the app's state with
+ /// `patch` already applied). `send` transmits one command; `note` receives log lines.
+ func apply(patch: [String: Any], state: [String: Any], to deviceId: String,
+ send: ([String: Any]) async throws -> Void, note: (String) -> Void) async throws {
+ let isOn = state["on"] as? Bool ?? false
+ var wanted = patch.filter { Self.fields.contains($0.key) }
+ if !isOn, wanted["on"] == nil {
+ guard !wanted.isEmpty else { return }
+ deferred[deviceId, default: []].formUnion(wanted.keys)
+ note("off: \(wanted.keys.sorted().joined(separator: ", ")) kept for the next switch-on")
+ return
+ }
+ if wanted["on"] as? Bool == true, let kept = deferred.removeValue(forKey: deviceId) {
+ for field in kept where wanted[field] == nil { wanted[field] = state[field] }
+ }
+ if wanted["on"] as? Bool == false { deferred[deviceId] = nil }
+
+ let keys = TuyaMapper.infraredKeys(patch: wanted)
+ var index = 0
+ var replayed = false
+ while index < keys.count {
+ let key = keys[index]
+ do {
+ try await press(key, on: deviceId, send)
+ index += 1
+ } catch {
+ let pending = keys[index...].map(\.field)
+ if tuyaCode(of: error) == "2008", !replayed, isOn, key.field != "on" {
+ replayed = true
+ var rest = state.filter { Self.fields.contains($0.key) }
+ for field in pending + keys[..<index].map(\.field) { rest[field] = nil }
+ note("\(key.field) refused (2008): replaying \(rest.keys.sorted().joined(separator: ", "))")
+ for other in TuyaMapper.infraredKeys(patch: rest) { try? await press(other, on: deviceId, send) }
+ continue
+ }
+ let reason = tuyaCode(of: error) == "2008"
+ ? "this remote has no infrared code for that setting (Tuya code 2008)"
+ : error.localizedDescription
+ throw Rejection(message: reason, fields: pending)
+ }
+ }
+ }
+
+ private func press(_ key: TuyaMapper.InfraredKey, on deviceId: String,
+ _ send: ([String: Any]) async throws -> Void) async throws {
+ if let last = lastKey[deviceId] {
+ let wait = spacing - Date().timeIntervalSince(last)
+ if wait > 0 { try? await Task.sleep(nanoseconds: UInt64(wait * 1_000_000_000)) }
+ }
+ defer { lastKey[deviceId] = Date() }
+ try await send(key.command)
+ }
+}
diff --git a/macos/Sources/HouseControl/PanelController.swift b/macos/Sources/HouseControl/PanelController.swift
new file mode 100644
index 0000000..0e799a1
--- /dev/null
+++ b/macos/Sources/HouseControl/PanelController.swift
@@ -0,0 +1,103 @@
+import AppKit
+import WebKit
+
+private final class FloatingPanel: NSPanel {
+ override var canBecomeKey: Bool { true }
+ override var canBecomeMain: Bool { false }
+}
+
+/// The borderless popover under the menu bar icon. The web content draws the card
+/// (rounded corners, notch, shadow) itself on a fully transparent window.
+final class PanelController: NSObject, NSWindowDelegate {
+ private static let card = NSSize(width: 440, height: 800)
+ // Transparent margin around the card, matching `html.native #app` padding in style.css.
+ private static let padTop: CGFloat = 13, padSide: CGFloat = 24, padBottom: CGFloat = 34
+
+ let host: WebHost
+ private let window: FloatingPanel
+ private var outsideClickMonitor: Any?
+ private(set) var isVisible = false
+ private var lastHide = Date.distantPast
+ var onVisibilityChange: ((Bool) -> Void)?
+ /// Keeps the panel open when it loses focus (HOUSE_PIN=1, for UI automation and screenshots).
+ private let pinned = ProcessInfo.processInfo.environment["HOUSE_PIN"] != nil
+
+ init(host: WebHost) {
+ self.host = host
+ let size = NSSize(width: Self.card.width + Self.padSide * 2, height: Self.card.height + Self.padTop + Self.padBottom)
+ window = FloatingPanel(contentRect: NSRect(origin: .zero, size: size),
+ styleMask: [.borderless, .nonactivatingPanel, .fullSizeContentView],
+ backing: .buffered, defer: false)
+ super.init()
+ window.isOpaque = false
+ window.backgroundColor = .clear
+ window.hasShadow = false
+ window.level = .popUpMenu
+ window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .transient, .ignoresCycle]
+ window.isMovable = false
+ window.hidesOnDeactivate = false
+ window.animationBehavior = .none
+ window.delegate = self
+ window.contentView = host.webView
+ window.alphaValue = 0
+ }
+
+ func toggle(below button: NSStatusBarButton) {
+ if isVisible { hide(); return }
+ // The click that dismissed the panel (resign key) must not immediately reopen it.
+ if Date().timeIntervalSince(lastHide) < 0.25 { return }
+ show(below: button)
+ }
+
+ func show(below button: NSStatusBarButton) {
+ guard let buttonWindow = button.window else { return }
+ let anchor = buttonWindow.convertToScreen(button.convert(button.bounds, to: nil))
+ let screen = buttonWindow.screen ?? NSScreen.main
+ let visible = screen?.visibleFrame ?? NSRect(x: 0, y: 0, width: 1440, height: 900)
+
+ var size = window.frame.size
+ size.height = min(Self.card.height + Self.padTop + Self.padBottom, visible.height - 4)
+ var x = anchor.midX - size.width / 2
+ x = max(visible.minX + 4 - Self.padSide, min(x, visible.maxX - size.width - 4 + Self.padSide))
+ let y = anchor.minY - size.height + 3
+ window.setFrame(NSRect(x: x.rounded(), y: y.rounded(), width: size.width, height: size.height), display: true)
+
+ host.call("setNotch", Double(anchor.midX - x - Self.padSide))
+ host.call("shown")
+
+ isVisible = true
+ window.alphaValue = 0
+ window.makeKeyAndOrderFront(nil)
+ NSAnimationContext.runAnimationGroup { ctx in
+ ctx.duration = 0.16
+ window.animator().alphaValue = 1
+ }
+ if !pinned {
+ outsideClickMonitor = NSEvent.addGlobalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown]) { [weak self] _ in
+ self?.hide()
+ }
+ }
+ onVisibilityChange?(true)
+ }
+
+ func hide() {
+ guard isVisible else { return }
+ isVisible = false
+ lastHide = Date()
+ if let monitor = outsideClickMonitor { NSEvent.removeMonitor(monitor) }
+ outsideClickMonitor = nil
+ NSAnimationContext.runAnimationGroup({ ctx in
+ ctx.duration = 0.12
+ window.animator().alphaValue = 0
+ }, completionHandler: { [weak self] in
+ guard let self, !self.isVisible else { return }
+ self.window.orderOut(nil)
+ self.host.call("hidden")
+ })
+ onVisibilityChange?(false)
+ }
+
+ func windowDidResignKey(_ notification: Notification) {
+ if !pinned { hide() }
+ }
+}
diff --git a/macos/Sources/HouseControl/PlanStore.swift b/macos/Sources/HouseControl/PlanStore.swift
new file mode 100644
index 0000000..68d90f0
--- /dev/null
+++ b/macos/Sources/HouseControl/PlanStore.swift
@@ -0,0 +1,69 @@
+import Foundation
+
+/// 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"]
+
+ let directory: URL
+ 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"
+
+ 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 {
+ directory = URL(fileURLWithPath: (custom as NSString).expandingTildeInPath, isDirectory: true)
+ } else {
+ let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
+ directory = base.appendingPathComponent("HouseControl", isDirectory: true)
+ }
+ try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
+ if let data = try? Data(contentsOf: settingsURL),
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let plan = json["plan"] as? String {
+ activePlan = plan
+ }
+ if activePlan == "custom", customPlan() == nil { activePlan = "home" }
+ }
+
+ 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) }
+
+ 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])
+ try? data?.write(to: settingsURL, options: .atomic)
+ }
+
+ /// 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])
+ try data.write(to: customPlanURL, options: .atomic)
+ select("custom")
+ }
+
+ func importPlan(from url: URL) throws {
+ let data = try Data(contentsOf: url)
+ 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)
+ }
+
+ /// The plan the UI should render: the custom JSON inline, or the name of a bundled demo.
+ 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/macos/Sources/HouseControl/SmartLifeService.swift b/macos/Sources/HouseControl/SmartLifeService.swift
new file mode 100644
index 0000000..20a4abe
--- /dev/null
+++ b/macos/Sources/HouseControl/SmartLifeService.swift
@@ -0,0 +1,371 @@
+import Foundation
+import CryptoKit
+import CoreImage
+import ImageIO
+
+/// What the app needs from a device backend, whichever way the account is connected.
+@MainActor
+protocol DeviceCloud: AnyObject {
+ var isConfigured: Bool { get }
+ var knownCodes: [String: Set<String>] { get }
+ /// Numeric ranges of each device's data points (brightness scales differ per model).
+ var knownRanges: [String: TuyaMapper.Ranges] { get }
+ func listDevices() async throws -> [[String: Any]]
+ func status(of ids: [String]) async throws -> [String: [[String: Any]]]
+ func send(_ commands: [[String: Any]], to deviceId: String) async throws
+ /// Makes sure the device's functions are known before the first command is built.
+ func prepare(_ deviceId: String) async
+}
+
+extension TuyaService: DeviceCloud {
+ func prepare(_ deviceId: String) async {}
+}
+
+/// Tuya's error code behind a failed request, whichever backend raised it.
+func tuyaCode(of error: Error) -> String {
+ (error as? SmartLifeService.Failure)?.code ?? (error as? TuyaService.Failure)?.code ?? ""
+}
+
+/// Smart Life account access without a Tuya developer project: the user approves a QR
+/// login in the Smart Life app and the app talks to Tuya's "device sharing" gateway.
+/// This is a Swift port of the open-source `tuya-device-sharing-sdk` that the Home
+/// Assistant Tuya integration is built on, and it identifies itself the same way.
+@MainActor
+final class SmartLifeService: DeviceCloud {
+ private static let clientId = "HA_3y9q4ak7g4ephrvke"
+ private static let schema = "haauthorize"
+ private static let loginHost = "https://apigw.iotbing.com"
+
+ struct Session: Codable {
+ var userCode: String
+ var accessToken: String
+ var refreshToken: String
+ var expiresAt: Double // ms since 1970
+ var uid: String
+ var endpoint: String
+ var username: String
+ }
+
+ struct Failure: LocalizedError {
+ let message: String
+ /// Tuya's error code when the cloud answered with one ("2008", "1109", …).
+ var code = ""
+ var errorDescription: String? { message }
+ }
+
+ private let fileURL: URL
+ private(set) var session: Session?
+ private var sessionStamp: Date?
+ 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()
+ }
+
+ private var fileStamp: Date? {
+ (try? FileManager.default.attributesOfItem(atPath: fileURL.path))?[.modificationDate] as? Date
+ }
+
+ /// 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 }
+ sessionStamp = stamp
+ session = (try? Data(contentsOf: fileURL)).flatMap { try? JSONDecoder().decode(Session.self, from: $0) }
+ }
+
+ var isConfigured: Bool { session != nil }
+
+ var publicInfo: [String: Any] {
+ ["connected": isConfigured, "userCode": session?.userCode ?? "", "account": session?.username ?? ""]
+ }
+
+ 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
+ }
+
+ func signOut() {
+ store(nil)
+ knownCodes = [:]
+ }
+
+ // MARK: - QR login
+
+ /// Asks Tuya for a login ticket; the returned string is what the QR code must contain.
+ func beginLogin(userCode: String) async throws -> (token: String, qrContent: String) {
+ let code = userCode.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !code.isEmpty, let encoded = code.addingPercentEncoding(withAllowedCharacters: .alphanumerics) else {
+ throw Failure(message: "Enter the User Code from the Smart Life app first.")
+ }
+ let url = URL(string: "\(Self.loginHost)/v1.0/m/life/home-assistant/qrcode/tokens?clientid=\(Self.clientId)&usercode=\(encoded)&schema=\(Self.schema)")!
+ var request = URLRequest(url: url, timeoutInterval: 12)
+ request.httpMethod = "POST"
+ let json = try await Self.json(for: request)
+ guard json["success"] as? Bool == true, let result = json["result"] as? [String: Any],
+ let token = result["qrcode"] as? String else {
+ throw Failure(message: Self.explain(json, fallback: "Tuya did not accept this User Code."))
+ }
+ return (token, "tuyaSmart--qrLogin?token=\(token)")
+ }
+
+ /// True once the user has confirmed the login in the Smart Life app.
+ func finishLogin(token: String, userCode: String) async throws -> Bool {
+ let code = userCode.trimmingCharacters(in: .whitespacesAndNewlines)
+ let encoded = code.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? code
+ let url = URL(string: "\(Self.loginHost)/v1.0/m/life/home-assistant/qrcode/tokens/\(token)?clientid=\(Self.clientId)&usercode=\(encoded)")!
+ let json = try await Self.json(for: URLRequest(url: url, timeoutInterval: 12))
+ guard json["success"] as? Bool == true, let r = json["result"] as? [String: Any],
+ let access = r["access_token"] as? String, let refresh = r["refresh_token"] as? String,
+ let endpoint = r["endpoint"] as? String else { return false }
+ let now = (json["t"] as? Double) ?? Date().timeIntervalSince1970 * 1000
+ store(Session(userCode: code, accessToken: access, refreshToken: refresh,
+ expiresAt: now + ((r["expire_time"] as? Double) ?? 7200) * 1000,
+ uid: r["uid"] as? String ?? "", endpoint: endpoint,
+ username: r["username"] as? String ?? ""))
+ return true
+ }
+
+ 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())" }
+ }
+
+ // MARK: - Devices
+
+ func listDevices() async throws -> [[String: Any]] {
+ var devices: [[String: Any]] = []
+ let homes = try await request("GET", "/v1.0/m/life/users/homes") as? [[String: Any]] ?? []
+ for home in homes {
+ // ownerId arrives as a number or a string depending on the account.
+ guard let homeId = (home["ownerId"] as? String) ?? (home["ownerId"] as? NSNumber)?.stringValue else { continue }
+ let list = try await request("GET", "/v1.0/m/life/ha/home/devices", query: ["homeId": homeId]) as? [[String: Any]] ?? []
+ for d in list {
+ guard let id = d["id"] as? String else { continue }
+ let status = d["status"] as? [[String: Any]] ?? []
+ let codes = status.compactMap { $0["code"] as? String }
+ knownCodes[id] = Set(codes)
+ devices.append([
+ "id": id,
+ "name": d["name"] as? String ?? id,
+ "category": d["category"] as? String ?? "",
+ "product": d["product_name"] as? String ?? "",
+ "online": d["online"] as? Bool ?? false,
+ "codes": codes,
+ "home": home["name"] as? String ?? "",
+ ])
+ }
+ }
+ return devices
+ }
+
+ func status(of ids: [String]) async throws -> [String: [[String: Any]]] {
+ var out: [String: [[String: Any]]] = [:]
+ for chunk in stride(from: 0, to: ids.count, by: 20).map({ Array(ids[$0..<min($0 + 20, ids.count)]) }) {
+ let list = try await request("GET", "/v1.0/m/life/ha/devices/detail", query: ["devIds": chunk.joined(separator: ",")]) as? [[String: Any]] ?? []
+ for d in list {
+ guard let id = d["id"] as? String, let status = d["status"] as? [[String: Any]] else { continue }
+ out[id] = status
+ knownCodes[id, default: []].formUnion(status.compactMap { $0["code"] as? String })
+ }
+ }
+ for id in ids where knownRanges[id] == nil { await loadSpecification(of: id) }
+ return out
+ }
+
+ func send(_ commands: [[String: Any]], to deviceId: String) async throws {
+ guard !commands.isEmpty else { return }
+ _ = try await request("POST", "/v1.1/m/thing/\(deviceId)/commands", body: ["commands": commands])
+ }
+
+ /// Read-only snapshot for diagnostics: raw status and specification of the given devices.
+ func diagnostics(for ids: [String]) async -> [String: Any] {
+ var out: [String: Any] = [:]
+ let details = (try? await request("GET", "/v1.0/m/life/ha/devices/detail", query: ["devIds": ids.joined(separator: ",")])) as? [[String: Any]] ?? []
+ for d in details {
+ guard let id = d["id"] as? String else { continue }
+ var entry: [String: Any] = [:]
+ for key in ["name", "category", "product_name", "online", "status", "sub"] { entry[key] = d[key] ?? NSNull() }
+ do { entry["specification"] = try await request("GET", "/v1.1/m/life/\(id)/specifications") }
+ catch { entry["specification_error"] = error.localizedDescription }
+ // How the cloud maps raw data points to status codes; also shows what it last knew.
+ do { entry["strategy"] = try await request("GET", "/v1.0/m/life/devices/\(id)/status") }
+ catch { entry["strategy_error"] = error.localizedDescription }
+ out[id] = entry
+ }
+ return out
+ }
+
+ func prepare(_ deviceId: String) async {
+ if knownRanges[deviceId] == nil { await loadSpecification(of: deviceId) }
+ }
+
+ /// Functions and value ranges of a device; fetched once. Some devices (Zigbee bulbs,
+ /// infrared remotes) report no status at all, so the specification is the only place
+ /// that says which commands they understand.
+ private func loadSpecification(of id: String) async {
+ knownRanges[id] = [:] // remembered even on failure so it is not retried on every poll
+ guard let spec = try? await request("GET", "/v1.1/m/life/\(id)/specifications") as? [String: Any] else { return }
+ var ranges: TuyaMapper.Ranges = [:]
+ var codes = knownCodes[id] ?? []
+ for key in ["status", "functions"] {
+ for item in spec[key] as? [[String: Any]] ?? [] {
+ guard let code = item["code"] as? String else { continue }
+ codes.insert(code)
+ guard let raw = item["values"] as? String,
+ let values = try? JSONSerialization.jsonObject(with: Data(raw.utf8)) as? [String: Any],
+ let lo = values["min"] as? Double, let hi = values["max"] as? Double else { continue }
+ ranges[code] = (lo, hi)
+ }
+ }
+ knownCodes[id] = codes
+ knownRanges[id] = ranges
+ }
+
+ // MARK: - Encrypted, signed transport
+
+ private func refreshIfNeeded() async {
+ guard let s = session, !refreshing, s.expiresAt - 60_000 < Date().timeIntervalSince1970 * 1000 else { return }
+ refreshing = true
+ defer { refreshing = false }
+ guard let result = try? await request("GET", "/v1.0/m/token/\(s.refreshToken)", refresh: false) as? [String: Any],
+ let access = result["accessToken"] as? String, let refresh = result["refreshToken"] as? String else { return }
+ var next = s
+ next.accessToken = access
+ next.refreshToken = refresh
+ next.expiresAt = Date().timeIntervalSince1970 * 1000 + ((result["expireTime"] as? Double) ?? 7200) * 1000
+ if let uid = result["uid"] as? String { next.uid = uid }
+ store(next)
+ }
+
+ private func request(_ method: String, _ path: String, query: [String: Any] = [:],
+ body: [String: Any] = [:], refresh: Bool = true) async throws -> Any {
+ reloadSession()
+ if refresh { await refreshIfNeeded() }
+ guard let s = session else { throw Failure(message: "Not signed in to Smart Life") }
+
+ let rid = UUID().uuidString.lowercased()
+ let hashKey = Transport.md5Hex(rid + s.refreshToken)
+ let secret = Transport.secret(requestId: rid, hashKey: hashKey)
+
+ var queryEnc = ""
+ var urlString = s.endpoint + path
+ if !query.isEmpty {
+ queryEnc = try Transport.encrypt(Transport.compactJSON(query), secret: secret)
+ var allowed = CharacterSet.alphanumerics
+ allowed.insert(charactersIn: "-._~")
+ urlString += "?encdata=" + (queryEnc.addingPercentEncoding(withAllowedCharacters: allowed) ?? queryEnc)
+ }
+ var bodyEnc = ""
+ if !body.isEmpty { bodyEnc = try Transport.encrypt(Transport.compactJSON(body), secret: secret) }
+ guard let url = URL(string: urlString) else { throw Failure(message: "Bad request URL") }
+
+ let t = String(Int(Date().timeIntervalSince1970 * 1000))
+ let headers = [("X-appKey", Self.clientId), ("X-requestId", rid), ("X-sid", ""), ("X-time", t), ("X-token", s.accessToken)]
+
+ var req = URLRequest(url: url, timeoutInterval: 12)
+ req.httpMethod = method
+ for (name, value) in headers { req.setValue(value, forHTTPHeaderField: name) }
+ req.setValue(Transport.sign(hashKey: hashKey, headers: headers, query: queryEnc, body: bodyEnc), forHTTPHeaderField: "X-sign")
+ if !bodyEnc.isEmpty {
+ req.httpBody = try JSONSerialization.data(withJSONObject: ["encdata": bodyEnc])
+ req.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ }
+
+ let json = try await Self.json(for: req)
+ guard json["success"] as? Bool == true else {
+ throw Failure(message: Self.explain(json, fallback: "Smart Life request failed"), code: Self.code(of: json))
+ }
+ guard let cipher = json["result"] as? String else { return json["result"] ?? NSNull() }
+ let plain = try Transport.decrypt(cipher, secret: secret)
+ return (try? JSONSerialization.jsonObject(with: Data(plain.utf8), options: [.fragmentsAllowed])) ?? plain
+ }
+
+ private static func json(for request: URLRequest) async throws -> [String: Any] {
+ let (data, _) = try await URLSession.shared.data(for: request)
+ guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
+ throw Failure(message: "Unexpected response from Tuya")
+ }
+ return json
+ }
+
+ private static func code(of json: [String: Any]) -> String {
+ (json["code"] as? String) ?? (json["code"] as? NSNumber)?.stringValue ?? ""
+ }
+
+ private static func explain(_ json: [String: Any], fallback: String) -> String {
+ let code = code(of: json)
+ // 2001: the cloud cannot reach the device (unplugged, or only paired over Bluetooth).
+ if code == "2001" { return "device is offline — Smart Life cannot reach it over Wi-Fi (code 2001)" }
+ let msg = json["msg"] as? String ?? fallback
+ return code.isEmpty ? msg : "\(msg) (code \(code))"
+ }
+
+ /// The gateway's request envelope: per-request AES-GCM key derived from the request id
+ /// and the refresh token, payloads sent as `encdata`, HMAC over headers + payloads.
+ enum Transport {
+ private static let alphabet = Array("ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678")
+
+ static func md5Hex(_ text: String) -> String {
+ Insecure.MD5.hash(data: Data(text.utf8)).map { String(format: "%02x", $0) }.joined()
+ }
+
+ static func secret(requestId: String, hashKey: String) -> String {
+ let mac = HMAC<SHA256>.authenticationCode(for: Data(hashKey.utf8), using: SymmetricKey(data: Data(requestId.utf8)))
+ return String(mac.map { String(format: "%02x", $0) }.joined().prefix(16))
+ }
+
+ static func sign(hashKey: String, headers: [(String, String)], query: String, body: String) -> String {
+ let text = headers.filter { !$0.1.isEmpty }.map { "\($0.0)=\($0.1)" }.joined(separator: "||") + query + body
+ let mac = HMAC<SHA256>.authenticationCode(for: Data(text.utf8), using: SymmetricKey(data: Data(hashKey.utf8)))
+ return mac.map { String(format: "%02x", $0) }.joined()
+ }
+
+ static func compactJSON(_ object: [String: Any]) throws -> String {
+ let data = try JSONSerialization.data(withJSONObject: object, options: [.withoutEscapingSlashes])
+ return String(data: data, encoding: .utf8) ?? "{}"
+ }
+
+ static func encrypt(_ plain: String, secret: String, nonce fixed: String? = nil) throws -> String {
+ let nonceText = fixed ?? String((0..<12).map { _ in alphabet.randomElement()! })
+ let nonce = try AES.GCM.Nonce(data: Data(nonceText.utf8))
+ let box = try AES.GCM.seal(Data(plain.utf8), using: SymmetricKey(data: Data(secret.utf8)), nonce: nonce)
+ return Data(nonceText.utf8).base64EncodedString() + (box.ciphertext + box.tag).base64EncodedString()
+ }
+
+ static func decrypt(_ cipher: String, secret: String) throws -> String {
+ guard let data = Data(base64Encoded: cipher), data.count > 28 else {
+ throw Failure(message: "Could not decode the response from Smart Life")
+ }
+ let box = try AES.GCM.SealedBox(nonce: AES.GCM.Nonce(data: data.prefix(12)),
+ ciphertext: data.dropFirst(12).dropLast(16), tag: data.suffix(16))
+ let plain = try AES.GCM.open(box, using: SymmetricKey(data: Data(secret.utf8)))
+ return String(data: plain, encoding: .utf8) ?? ""
+ }
+ }
+}
+
+enum PNGEncoder {
+ static func data(from image: CGImage) -> Data? {
+ let data = NSMutableData()
+ guard let dest = CGImageDestinationCreateWithData(data, "public.png" as CFString, 1, nil) else { return nil }
+ CGImageDestinationAddImage(dest, image, nil)
+ return CGImageDestinationFinalize(dest) ? data as Data : nil
+ }
+}
diff --git a/macos/Sources/HouseControl/TuyaService.swift b/macos/Sources/HouseControl/TuyaService.swift
new file mode 100644
index 0000000..0bf3ba6
--- /dev/null
+++ b/macos/Sources/HouseControl/TuyaService.swift
@@ -0,0 +1,374 @@
+import Foundation
+import CryptoKit
+
+/// Minimal client for the Tuya Cloud OpenAPI ("Smart Home" project with the Smart Life
+/// app account linked to it). Covers exactly what the app needs: list devices, read
+/// their status, send commands.
+@MainActor
+final class TuyaService {
+ struct Credentials: Codable {
+ var accessId: String
+ var accessSecret: String
+ var region: String
+ }
+
+ struct Failure: LocalizedError {
+ let message: String
+ var code = ""
+ var errorDescription: String? { message }
+ }
+
+ static let hosts: [String: String] = [
+ "eu": "openapi.tuyaeu.com", // Central Europe
+ "eu-w": "openapi-weaz.tuyaeu.com", // Western Europe
+ "us": "openapi.tuyaus.com", // Western America
+ "us-e": "openapi-ueaz.tuyaus.com", // Eastern America
+ "cn": "openapi.tuyacn.com",
+ "in": "openapi.tuyain.com",
+ "sg": "openapi-sg.iotbing.com",
+ ]
+
+ private let fileURL: URL
+ private(set) var credentials: Credentials?
+ private var token: String?
+ private var tokenExpiry = Date.distantPast
+ /// Data-point codes each device reported, used to pick the right command dialect.
+ private(set) var knownCodes: [String: Set<String>] = [:]
+ private(set) var knownRanges: [String: TuyaMapper.Ranges] = [:]
+
+ init(directory: URL) {
+ fileURL = directory.appendingPathComponent("tuya.json")
+ if let data = try? Data(contentsOf: fileURL) {
+ credentials = try? JSONDecoder().decode(Credentials.self, from: data)
+ }
+ }
+
+ var isConfigured: Bool {
+ guard let c = credentials else { return false }
+ return !c.accessId.isEmpty && !c.accessSecret.isEmpty && Self.hosts[c.region] != nil
+ }
+
+ /// What the UI may know: never the secret itself.
+ var publicInfo: [String: Any] {
+ ["configured": isConfigured, "accessId": credentials?.accessId ?? "", "region": credentials?.region ?? "eu",
+ "hasSecret": !(credentials?.accessSecret.isEmpty ?? true)]
+ }
+
+ func save(_ new: Credentials?) throws {
+ credentials = new
+ token = nil
+ tokenExpiry = .distantPast
+ guard let new else {
+ try? FileManager.default.removeItem(at: fileURL)
+ return
+ }
+ try JSONEncoder().encode(new).write(to: fileURL, options: .atomic)
+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: fileURL.path)
+ }
+
+ // MARK: - API
+
+ /// Every device of the linked Smart Life account, with the DP codes it supports.
+ func listDevices() async throws -> [[String: Any]] {
+ var devices: [[String: Any]] = []
+ var lastKey: String?
+ repeat {
+ var query = ["size": "50"]
+ if let lastKey { query["last_row_key"] = lastKey }
+ let result = try await request("GET", "/v1.0/iot-01/associated-users/devices", query: query)
+ guard let page = result as? [String: Any] else { break }
+ for d in page["devices"] as? [[String: Any]] ?? [] {
+ guard let id = d["id"] as? String else { continue }
+ let status = d["status"] as? [[String: Any]] ?? []
+ let codes = status.compactMap { $0["code"] as? String }
+ knownCodes[id] = Set(codes)
+ devices.append([
+ "id": id,
+ "name": d["name"] as? String ?? id,
+ "category": d["category"] as? String ?? "",
+ "product": d["product_name"] as? String ?? "",
+ "online": d["online"] as? Bool ?? false,
+ "codes": codes,
+ ])
+ }
+ lastKey = (page["has_more"] as? Bool ?? false) ? page["last_row_key"] as? String : nil
+ } while lastKey != nil
+ return devices
+ }
+
+ /// Current data points for the given devices, keyed by device id.
+ func status(of ids: [String]) async throws -> [String: [[String: Any]]] {
+ var out: [String: [[String: Any]]] = [:]
+ for chunk in stride(from: 0, to: ids.count, by: 20).map({ Array(ids[$0..<min($0 + 20, ids.count)]) }) {
+ let result = try await request("GET", "/v1.0/iot-03/devices/status", query: ["device_ids": chunk.joined(separator: ",")])
+ for entry in result as? [[String: Any]] ?? [] {
+ guard let id = entry["id"] as? String, let status = entry["status"] as? [[String: Any]] else { continue }
+ out[id] = status
+ knownCodes[id] = Set(status.compactMap { $0["code"] as? String })
+ }
+ }
+ return out
+ }
+
+ func send(_ commands: [[String: Any]], to deviceId: String) async throws {
+ guard !commands.isEmpty else { return }
+ let body = try JSONSerialization.data(withJSONObject: ["commands": commands])
+ _ = try await request("POST", "/v1.0/iot-03/devices/\(deviceId)/commands", body: body)
+ }
+
+ // MARK: - Signing
+
+ private func accessToken() async throws -> String {
+ if let token, tokenExpiry > Date().addingTimeInterval(60) { return token }
+ let result = try await request("GET", "/v1.0/token", query: ["grant_type": "1"], authorized: false)
+ guard let dict = result as? [String: Any], let value = dict["access_token"] as? String else {
+ throw Failure(message: "Tuya did not return an access token")
+ }
+ token = value
+ tokenExpiry = Date().addingTimeInterval(TimeInterval(dict["expire_time"] as? Int ?? 3600))
+ return value
+ }
+
+ private func request(_ method: String, _ path: String, query: [String: String] = [:],
+ body: Data? = nil, authorized: Bool = true, retry: Bool = true) async throws -> Any {
+ guard let c = credentials, isConfigured, let host = Self.hosts[c.region] else {
+ throw Failure(message: "Tuya credentials are not set")
+ }
+ let sorted = query.sorted { $0.key < $1.key }
+ let queryString = sorted.map { "\($0.key)=\($0.value)" }.joined(separator: "&")
+ let signedURL = queryString.isEmpty ? path : "\(path)?\(queryString)"
+ guard let url = URL(string: "https://\(host)\(signedURL)") else { throw Failure(message: "Bad request URL") }
+
+ let bodyHash = SHA256.hash(data: body ?? Data()).map { String(format: "%02x", $0) }.joined()
+ let t = String(Int(Date().timeIntervalSince1970 * 1000))
+ let token = authorized ? try await accessToken() : ""
+ let payload = c.accessId + token + t + "\(method)\n\(bodyHash)\n\n\(signedURL)"
+ let mac = HMAC<SHA256>.authenticationCode(for: Data(payload.utf8), using: SymmetricKey(data: Data(c.accessSecret.utf8)))
+ let sign = mac.map { String(format: "%02X", $0) }.joined()
+
+ var req = URLRequest(url: url, timeoutInterval: 12)
+ req.httpMethod = method
+ req.httpBody = body
+ req.setValue(c.accessId, forHTTPHeaderField: "client_id")
+ req.setValue(sign, forHTTPHeaderField: "sign")
+ req.setValue(t, forHTTPHeaderField: "t")
+ req.setValue("HMAC-SHA256", forHTTPHeaderField: "sign_method")
+ if authorized { req.setValue(token, forHTTPHeaderField: "access_token") }
+ if body != nil { req.setValue("application/json", forHTTPHeaderField: "Content-Type") }
+
+ let (data, _) = try await URLSession.shared.data(for: req)
+ guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
+ throw Failure(message: "Unexpected response from Tuya")
+ }
+ if json["success"] as? Bool == true { return json["result"] ?? NSNull() }
+ let code = json["code"] as? Int ?? 0
+ // 1010 / 1011: token expired or invalid. Fetch a fresh one once.
+ if authorized, retry, code == 1010 || code == 1011 {
+ self.token = nil
+ return try await request(method, path, query: query, body: body, authorized: true, retry: false)
+ }
+ throw Failure(message: "\(json["msg"] as? String ?? "Tuya request failed") (code \(code))", code: String(code))
+ }
+}
+
+/// Translates between the app's device state and Tuya's "standard instruction set".
+/// Devices differ in which data points they expose and in their value ranges, so every
+/// mapping checks the codes the device actually reported and silently skips what it cannot do.
+enum TuyaMapper {
+ /// (min, max) of a numeric data point, from the device specification when known.
+ typealias Ranges = [String: (Double, Double)]
+
+ private static let acModes = ["cool": "cold", "heat": "hot", "dry": "wet", "fan": "wind", "auto": "auto"]
+ private static let acFans = ["auto": "auto", "low": "low", "medium": "mid", "high": "high", "turbo": "strong"]
+ // Infrared ACs (a remote learned by an IR blaster) number their modes and fan speeds.
+ private static let irModes = ["cool": 0, "heat": 1, "auto": 2, "fan": 3, "dry": 4]
+ private static let irFans = ["auto": 0, "low": 1, "medium": 2, "high": 3, "turbo": 3]
+
+ private static func pick(_ candidates: [String], in codes: Set<String>, override: Any?) -> String? {
+ if let o = override as? String, !o.isEmpty { return o }
+ return candidates.first { codes.contains($0) }
+ }
+
+ /// Range of a brightness / temperature point: the specification wins; otherwise the
+ /// `_v2` points are 0…1000 and the legacy ones 0…255.
+ private static func range(_ code: String, _ ranges: Ranges, floor: Double = 0) -> (Double, Double) {
+ if let r = ranges[code], r.1 > r.0 { return r }
+ return code.hasSuffix("_v2") ? (floor > 0 ? 10 : 0, 1000) : (floor, 255)
+ }
+
+ static func lightCommands(patch: [String: Any], state: [String: Any], link: [String: Any],
+ codes: Set<String>, ranges: Ranges = [:]) -> [[String: Any]] {
+ let custom = link["codes"] as? [String: Any] ?? [:]
+ var out: [[String: Any]] = []
+ if let on = patch["on"] as? Bool {
+ // A plain plug only has a switch; assume switch_1 when the device has not reported yet.
+ let code = pick(["switch_led", "switch_1", "switch"], in: codes, override: custom["switch"]) ?? "switch_1"
+ out.append(["code": code, "value": on])
+ }
+ if let b = patch["brightness"] as? Double, let code = pick(["bright_value_v2", "bright_value"], in: codes, override: nil) {
+ let (lo, hi) = range(code, ranges, floor: 25)
+ out.append(["code": code, "value": Int((lo + b * (hi - lo)).rounded())])
+ }
+ if let k = patch["temp"] as? Double, let code = pick(["temp_value_v2", "temp_value"], in: codes, override: nil) {
+ let t = max(0, min(1, (k - 2200) / (6500 - 2200)))
+ let (lo, hi) = range(code, ranges)
+ if codes.contains("work_mode") { out.append(["code": "work_mode", "value": "white"]) }
+ out.append(["code": code, "value": Int((lo + t * (hi - lo)).rounded())])
+ }
+ if let hex = patch["color"] as? String, let (h, s, _) = hsv(hex),
+ let code = pick(["colour_data_v2", "colour_data"], in: codes, override: nil) {
+ // Saturation and value share the brightness scale of the same generation.
+ let scale = range(code == "colour_data_v2" ? "bright_value_v2" : "bright_value", ranges).1 > 255 ? 1000.0 : 255.0
+ let v = max(0.01, state["brightness"] as? Double ?? 1)
+ if codes.contains("work_mode") { out.append(["code": "work_mode", "value": "colour"]) }
+ // Sent as a JSON string, which is also how the device reports it.
+ out.append(["code": code, "value": "{\"h\":\(Int(h)),\"s\":\(Int(s * scale)),\"v\":\(Int(v * scale))}"])
+ }
+ return out
+ }
+
+ static func lightState(from status: [[String: Any]], ranges: Ranges = [:]) -> [String: Any] {
+ var out: [String: Any] = [:]
+ for dp in status {
+ guard let code = dp["code"] as? String, let value = dp["value"] else { continue }
+ switch code {
+ case "switch_led", "switch_1", "switch":
+ if out["on"] == nil, let v = value as? Bool { out["on"] = v }
+ case "bright_value_v2", "bright_value":
+ if let v = value as? Double {
+ let (lo, hi) = range(code, ranges, floor: 25)
+ out["brightness"] = max(0.05, min(1, (v - lo) / (hi - lo)))
+ }
+ case "temp_value_v2", "temp_value":
+ if let v = value as? Double {
+ let (lo, hi) = range(code, ranges)
+ out["temp"] = 2200 + max(0, min(1, (v - lo) / (hi - lo))) * 4300
+ }
+ default: break
+ }
+ }
+ return out
+ }
+
+ /// True for an AC that is a remote learned by an infrared blaster. Those take the
+ /// "PowerOn / PowerOff / T / M / F" key set and never report their state back.
+ static func isInfraredAC(_ codes: Set<String>) -> Bool {
+ codes.contains("PowerOn") || codes.contains("PowerOff")
+ }
+
+ /// One key press of an infrared remote, and the piece of app state it carries.
+ struct InfraredKey {
+ let field: String
+ let command: [String: Any]
+ }
+
+ /// The key presses that bring an infrared AC to `patch`. Order matters for a remote:
+ /// power first, then mode, then the set-point and fan.
+ static func infraredKeys(patch: [String: Any]) -> [InfraredKey] {
+ var out: [InfraredKey] = []
+ if let on = patch["on"] as? Bool {
+ let key = on ? "PowerOn" : "PowerOff"
+ out.append(InfraredKey(field: "on", command: ["code": key, "value": key]))
+ }
+ if let m = patch["mode"] as? String, let v = irModes[m] {
+ out.append(InfraredKey(field: "mode", command: ["code": "M", "value": v]))
+ }
+ if let t = patch["target"] as? Double {
+ out.append(InfraredKey(field: "target", command: ["code": "T", "value": Int(t)]))
+ }
+ if let f = patch["fan"] as? String, let v = irFans[f] {
+ out.append(InfraredKey(field: "fan", command: ["code": "F", "value": v]))
+ }
+ return out
+ }
+
+ /// What the panel may offer for a linked AC. Controls the device has no function for
+ /// are hidden instead of pretending to work. Nil until the functions are known.
+ static func acFeatures(codes: Set<String>, ranges: Ranges) -> [String: Any]? {
+ guard !codes.isEmpty else { return nil }
+ let allModes = ["cool", "heat", "dry", "fan", "auto"]
+ if isInfraredAC(codes) {
+ let m = ranges["M"] ?? (0, 4), f = ranges["F"] ?? (0, 3)
+ return [
+ "infrared": true,
+ "modes": allModes.filter { Double(irModes[$0] ?? 99) >= m.0 && Double(irModes[$0] ?? 99) <= m.1 },
+ // Turbo shares the top speed with High on a remote, so it is not offered twice.
+ "fans": ["auto", "low", "medium", "high"].filter { Double(irFans[$0] ?? 99) >= f.0 && Double(irFans[$0] ?? 99) <= f.1 },
+ "sleep": false, "eco": false, "swing": false,
+ ]
+ }
+ return [
+ "infrared": false,
+ "modes": codes.contains("mode") ? allModes : [],
+ "fans": codes.contains("fan_speed_enum") || codes.contains("windspeed") ? ["auto", "low", "medium", "high", "turbo"] : [],
+ "sleep": codes.contains("sleep"), "eco": codes.contains("eco"), "swing": false,
+ ]
+ }
+
+ static func acCommands(patch: [String: Any], link: [String: Any], codes: Set<String>) -> [[String: Any]] {
+ let custom = link["codes"] as? [String: Any] ?? [:]
+ var out: [[String: Any]] = []
+
+ if isInfraredAC(codes) { return infraredKeys(patch: patch).map(\.command) }
+
+ if let on = patch["on"] as? Bool {
+ out.append(["code": pick(["switch", "power", "switch_1"], in: codes, override: custom["switch"]) ?? "switch", "value": on])
+ }
+ if let t = patch["target"] as? Double {
+ out.append(["code": pick(["temp_set"], in: codes, override: custom["target"]) ?? "temp_set", "value": Int(t)])
+ }
+ if let m = patch["mode"] as? String, let v = acModes[m] {
+ out.append(["code": pick(["mode"], in: codes, override: custom["mode"]) ?? "mode", "value": v])
+ }
+ if let f = patch["fan"] as? String, let v = acFans[f],
+ let code = pick(["fan_speed_enum", "windspeed"], in: codes, override: custom["fan"]) {
+ out.append(["code": code, "value": v])
+ }
+ if let s = patch["sleep"] as? Bool, codes.contains("sleep") { out.append(["code": "sleep", "value": s]) }
+ if let e = patch["eco"] as? Bool, codes.contains("eco") { out.append(["code": "eco", "value": e]) }
+ return out
+ }
+
+ static func acState(from status: [[String: Any]]) -> [String: Any] {
+ var out: [String: Any] = [:]
+ for dp in status {
+ guard let code = dp["code"] as? String, let value = dp["value"] else { continue }
+ switch code {
+ case "switch", "power": if let v = value as? Bool { out["on"] = v }
+ case "temp_set": if let v = value as? Double { out["target"] = v }
+ case "temp_current": if let v = value as? Double { out["roomTemp"] = v }
+ case "mode": if let v = value as? String, let m = acModes.first(where: { $0.value == v })?.key { out["mode"] = m }
+ case "fan_speed_enum", "windspeed": if let v = value as? String, let f = acFans.first(where: { $0.value == v })?.key { out["fan"] = f }
+ default: break
+ }
+ }
+ return out
+ }
+
+ /// Reading of a temperature sensor in °C (Tuya reports tenths of a degree).
+ static func sensorTemperature(from status: [[String: Any]]) -> Double? {
+ for dp in status {
+ guard let code = dp["code"] as? String, ["temp_current", "va_temperature"].contains(code),
+ let v = dp["value"] as? Double else { continue }
+ return abs(v) > 60 ? v / 10 : v
+ }
+ return nil
+ }
+
+ private static func hsv(_ hex: String) -> (Double, Double, Double)? {
+ var s = hex.trimmingCharacters(in: .whitespaces)
+ if s.hasPrefix("#") { s.removeFirst() }
+ guard s.count == 6, let n = Int(s, radix: 16) else { return nil }
+ let r = Double((n >> 16) & 255) / 255, g = Double((n >> 8) & 255) / 255, b = Double(n & 255) / 255
+ let mx = max(r, g, b), mn = min(r, g, b), d = mx - mn
+ var h = 0.0
+ if d > 0 {
+ if mx == r { h = ((g - b) / d).truncatingRemainder(dividingBy: 6) }
+ else if mx == g { h = (b - r) / d + 2 }
+ else { h = (r - g) / d + 4 }
+ h *= 60
+ if h < 0 { h += 360 }
+ }
+ return (h, mx == 0 ? 0 : d / mx, mx)
+ }
+}
diff --git a/macos/Sources/HouseControl/WebHost.swift b/macos/Sources/HouseControl/WebHost.swift
new file mode 100644
index 0000000..9d40ee2
--- /dev/null
+++ b/macos/Sources/HouseControl/WebHost.swift
@@ -0,0 +1,129 @@
+import AppKit
+import WebKit
+
+/// 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) {}
+}
+
+/// A WKWebView showing the web UI in one of its modes ("panel" or "editor"),
+/// plus the JSON message bridge in both directions.
+final class WebHost: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
+ let webView: WKWebView
+ let mode: String
+ var onMessage: (([String: Any]) -> Void)?
+ private var bootProvider: () -> [String: Any]
+
+ /// Where the web UI lives: the app bundle, or a directory / dev server given by the environment.
+ static var assetRoot: URL {
+ if let dir = ProcessInfo.processInfo.environment["HOUSE_WEB_DIR"] { return URL(fileURLWithPath: dir) }
+ return (Bundle.main.resourceURL ?? URL(fileURLWithPath: ".")).appendingPathComponent("web")
+ }
+
+ init(mode: String, transparent: Bool, boot: @escaping () -> [String: Any]) {
+ self.mode = mode
+ self.bootProvider = boot
+ let config = WKWebViewConfiguration()
+ config.setURLSchemeHandler(AssetSchemeHandler(root: Self.assetRoot), forURLScheme: AssetSchemeHandler.scheme)
+ 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)
+ super.init()
+ config.userContentController.add(self, name: "house")
+ webView.navigationDelegate = self
+ if transparent {
+ webView.setValue(false, forKey: "drawsBackground")
+ if #available(macOS 12.0, *) { webView.underPageBackgroundColor = .clear }
+ }
+ webView.allowsMagnification = false
+ }
+
+ func load() {
+ let controller = webView.configuration.userContentController
+ controller.removeAllUserScripts()
+ var boot = bootProvider()
+ boot["mode"] = mode
+ let json = Self.json(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"
+ webView.load(URLRequest(url: URL(string: "\(base)?mode=\(mode)")!))
+ }
+
+ /// 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)
+ }
+
+ func reply(to message: [String: Any], _ result: Any) {
+ guard let id = message["callId"] as? Int else { return }
+ 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 }
+ onMessage?(body)
+ }
+
+ func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction,
+ decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
+ // The UI never navigates away; anything external opens in the default browser.
+ if let url = action.request.url, let scheme = url.scheme,
+ ["http", "https"].contains(scheme), url.host != "localhost", action.navigationType == .linkActivated {
+ NSWorkspace.shared.open(url)
+ decisionHandler(.cancel)
+ return
+ }
+ decisionHandler(.allow)
+ }
+}
diff --git a/macos/Sources/HouseControl/main.swift b/macos/Sources/HouseControl/main.swift
new file mode 100644
index 0000000..774bd15
--- /dev/null
+++ b/macos/Sources/HouseControl/main.swift
@@ -0,0 +1,93 @@
+import AppKit
+
+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()
+ }
+ let app = NSApplication.shared
+ let delegate = AppDelegate()
+ app.delegate = delegate
+ // Menu bar only: no Dock icon (HOUSE_DOCK=1 shows one, handy for UI automation).
+ app.setActivationPolicy(ProcessInfo.processInfo.environment["HOUSE_DOCK"] != nil ? .regular : .accessory)
+ app.run()
+}
diff --git a/scripts/build-app.sh b/scripts/build-app.sh
new file mode 100755
index 0000000..5acd303
--- /dev/null
+++ b/scripts/build-app.sh
@@ -0,0 +1,44 @@
+#!/bin/bash
+# Builds HouseControl.app: web UI (Vite) + native shell (SwiftPM), assembled into build/.
+set -euo pipefail
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+APP="$ROOT/build/HouseControl.app"
+
+echo "▸ Building web UI"
+cd "$ROOT/web"
+[ -d node_modules ] || npm install
+npm run build --silent
+
+echo "▸ Building native shell"
+cd "$ROOT/macos"
+swift build -c release 2>&1 | grep -E "error|warning: unused|Build complete" || true
+BIN="$(swift build -c release --show-bin-path)/HouseControl"
+[ -x "$BIN" ] || { echo "Swift build failed"; exit 1; }
+
+echo "▸ Assembling $APP"
+rm -rf "$APP"
+mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
+cp "$BIN" "$APP/Contents/MacOS/HouseControl"
+cp -R "$ROOT/web/dist" "$APP/Contents/Resources/web"
+[ -f "$ROOT/macos/AppIcon.icns" ] && cp "$ROOT/macos/AppIcon.icns" "$APP/Contents/Resources/AppIcon.icns"
+cat > "$APP/Contents/Info.plist" <<PLIST
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleName</key><string>House Control</string>
+ <key>CFBundleDisplayName</key><string>House Control</string>
+ <key>CFBundleIdentifier</key><string>io.github.0xprobabillity.HouseControl</string>
+ <key>CFBundleExecutable</key><string>HouseControl</string>
+ <key>CFBundleIconFile</key><string>AppIcon</string>
+ <key>CFBundlePackageType</key><string>APPL</string>
+ <key>CFBundleShortVersionString</key><string>0.1.0</string>
+ <key>CFBundleVersion</key><string>1</string>
+ <key>LSMinimumSystemVersion</key><string>13.0</string>
+ <key>LSUIElement</key><true/>
+ <key>NSHighResolutionCapable</key><true/>
+</dict>
+</plist>
+PLIST
+codesign --force --sign - "$APP" >/dev/null 2>&1 || echo " (ad-hoc signing skipped)"
+echo "✓ Done: $APP"