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.
Keep the Smart Life sign-in code on the Mac while the iPhone is away
0xProbability6a412c7aecbf
diff --git a/README.md b/README.mdindex 3165e53..31bc2de 100644--- a/README.md+++ b/README.md@@ -53,6 +53,10 @@ open build/HouseControl.appThe script builds the web UI with Vite, the native shell with SwiftPM, and assembles an ad-hoc signed`build/HouseControl.app`. The first build downloads the npm packages; later builds take a few seconds.+The app is signed ad hoc. If you rebuild often and use iPhone sync, sign it with your own certificate instead, so+macOS does not ask for the Local Network permission after every build:+`CODESIGN_IDENTITY="Apple Development: [email protected] (ABCDE12345)" ./scripts/build-app.sh`.+To keep it, drag `build/HouseControl.app` into `/Applications`. To start it with your Mac, add it under**System Settings → General → Login Items**.diff --git a/core/Sources/HouseCore/SyncClient.swift b/core/Sources/HouseCore/SyncClient.swiftindex b430b6a..5daa8bd 100644--- a/core/Sources/HouseCore/SyncClient.swift+++ b/core/Sources/HouseCore/SyncClient.swift@@ -24,6 +24,9 @@ public final class SyncClient {private var browser: NWBrowser?private var channel: SyncChannel?private var retry: DispatchWorkItem?+ /// What the Mac should be showing for this phone, and whether it has been told yet.+ private var qrContent: String?+ private var qrUnsent = false/// Set to connect straight to a host and port instead of browsing (tests).var fixedEndpoint: NWEndpoint?@@ -58,6 +61,8 @@ public final class SyncClient {}public func unpair() {+ qrContent = nil+ qrUnsent = falseteardown()pairing = nilstore.write(nil)@@ -86,12 +91,22 @@ public final class SyncClient {/// 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.+ /// Returns false when the Mac is not connected right now; the request is then delivered+ /// as soon as it is. (The code is scanned from another app, so this one is in the+ /// background, and disconnected, for most of the time the code is up.)@discardableResultpublic func showQR(_ content: String?) -> Bool {- guard let channel, status == .connected else { return false }+ qrContent = content+ qrUnsent = true+ return flushQR()+ }++ private func flushQR() -> Bool {+ guard qrUnsent, let channel, status == .connected else { return false }var message: [String: Any] = ["type": "showQR"]- if let content { message["content"] = content }+ if let qrContent { message["content"] = qrContent }channel.send(message)+ qrUnsent = falsereturn true}@@ -159,6 +174,7 @@ public final class SyncClient {channel.onMessage = { [weak self] message inguard let self, let state = SyncState(message: message) else { return }self.set(.connected)+ _ = self.flushQR()self.onState?(state)}channel.onClose = { [weak self] error indiff --git a/core/Sources/HouseCore/SyncServer.swift b/core/Sources/HouseCore/SyncServer.swiftindex f1fcae0..0b0b3d4 100644--- a/core/Sources/HouseCore/SyncServer.swift+++ b/core/Sources/HouseCore/SyncServer.swift@@ -29,6 +29,8 @@ public final class SyncServer {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.+ /// A phone that disconnects does not take its code down: it is scanned from another+ /// app on that phone, and iOS cuts the connection as soon as ours leaves the screen.public var onShowQR: ((String?, String) -> Void)?/// `store` keeps the pairing (by default `sync.json` next to the plan, readable by its user only).@@ -147,10 +149,7 @@ public final class SyncServer {}channel.onClose = { [weak self] _ inguard let self, let gone = self.peers.removeValue(forKey: key) else { return }- if !gone.name.isEmpty {- self.onShowQR?(nil, gone.name)- self.onPeersChanged?()- }+ if !gone.name.isEmpty { self.onPeersChanged?() }}channel.start()}diff --git a/core/Tests/HouseCoreTests/SyncTests.swift b/core/Tests/HouseCoreTests/SyncTests.swiftindex dc6b2d1..658b836 100644--- a/core/Tests/HouseCoreTests/SyncTests.swift+++ b/core/Tests/HouseCoreTests/SyncTests.swift@@ -2,6 +2,8 @@ import XCTestimport Network@testable import HouseCore+private final class Flag { var isSet = false }+@MainActorfinal class SyncTests: XCTestCase {func testPairingLinkRoundTrip() throws {@@ -108,16 +110,35 @@ final class SyncTests: XCTestCase {await fulfillment(of: [connected], timeout: 10)let shown = expectation(description: "shown")+ let hiddenWhileAway = expectation(description: "hidden while the phone was away")+ hiddenWhileAway.isInverted = truelet hidden = expectation(description: "hidden")+ let away = Flag()server.onShowQR = { content, device inXCTAssertEqual(device, "Test iPhone")- if content == "tuyaSmart--qrLogin?token=t1" { shown.fulfill() } else if content == nil { hidden.fulfill() }+ if content == "tuyaSmart--qrLogin?token=t1" { shown.fulfill() }+ else if content == nil { (away.isSet ? hiddenWhileAway : hidden).fulfill() }}XCTAssertTrue(client.showQR("tuyaSmart--qrLogin?token=t1"))await fulfillment(of: [shown], timeout: 10)- // Going away takes the code down as well.++ // The code is scanned from another app: ours goes to the background and iOS cuts+ // the connection. The code must stay up on the Mac.+ let gone = expectation(description: "phone disconnected")+ server.onPeersChanged = { if server.connectedDevices.isEmpty { gone.fulfill() } }+ away.isSet = trueclient.stop()- await fulfillment(of: [hidden], timeout: 10)+ await fulfillment(of: [gone], timeout: 10)+ server.onPeersChanged = nil+ await fulfillment(of: [hiddenWhileAway], timeout: 0.4)++ // Signed in while away: the Mac is told to take the code down once the phone is back.+ XCTAssertFalse(client.showQR(nil))+ away.isSet = false+ let back = expectation(description: "reconnected")+ client.onState = { _ in back.fulfill() }+ client.start()+ await fulfillment(of: [back, hidden], timeout: 10)}func testAWrongKeyIsRefused() async throws {diff --git a/ios/Config/Base.xcconfig b/ios/Config/Base.xcconfigindex 5c941b2..7947f58 100644--- a/ios/Config/Base.xcconfig+++ b/ios/Config/Base.xcconfig@@ -1,6 +1,6 @@// Version of the iPhone app. CURRENT_PROJECT_VERSION is the build number TestFlight sees.MARKETING_VERSION = 0.1.0-CURRENT_PROJECT_VERSION = 2+CURRENT_PROJECT_VERSION = 3CODE_SIGN_STYLE = Automaticdiff --git a/ios/Sources/SmartLifeView.swift b/ios/Sources/SmartLifeView.swiftindex bf33b8a..667e098 100644--- a/ios/Sources/SmartLifeView.swift+++ b/ios/Sources/SmartLifeView.swift@@ -6,6 +6,7 @@ import HouseCore/// another screen: the paired Mac puts it up by itself.struct SmartLifeView: View {@Environment(AppModel.self) private var model+ @Environment(\.scenePhase) private var scenePhase@State private var userCode = ""@State private var busy = false@State private var problem: String?@@ -43,6 +44,11 @@ struct SmartLifeView: View {.onAppear { if userCode.isEmpty { userCode = model.suggestedUserCode } }.onChange(of: model.suggestedUserCode) { _, code in if userCode.isEmpty { userCode = code } }.onDisappear { _ = model.showOnMac(nil) }+ // Back from the Smart Life app: do not wait for the next poll to find out.+ .onChange(of: scenePhase) { _, phase in+ guard phase == .active, let login, !model.smartLifeConnected else { return }+ Task { _ = await model.finishLogin(token: login.token, userCode: userCode) }+ }// Ask every two seconds whether the login was confirmed, for as long as the code is up..task(id: login) {guard let login else { return }@@ -137,7 +143,7 @@ struct SmartLifeView: View {IconBadge(symbol: "laptopcomputer", tint: Theme.green)VStack(alignment: .leading, spacing: 4) {Text("The code is on \(mac)").font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)- Text("Open Smart Life on this iPhone, tap the scanner on its Home tab and point it at the Mac's screen.")+ Text("Switch to Smart Life on this iPhone, tap the scanner on its Home tab and point it at the Mac's screen. The code stays there while you are away; come back here when you have confirmed.").font(.system(size: 14)).foregroundStyle(Theme.muted).fixedSize(horizontal: false, vertical: true)}diff --git a/macos/Sources/HouseControl/AppDelegate.swift b/macos/Sources/HouseControl/AppDelegate.swiftindex 724d2d3..9742b7f 100644--- a/macos/Sources/HouseControl/AppDelegate.swift+++ b/macos/Sources/HouseControl/AppDelegate.swift@@ -12,6 +12,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {private var island: IslandController?private var pairingWindow: QRWindowController?private var loginWindow: QRWindowController?+ private var loginWindowExpiry: DispatchWorkItem?private var statusItem: NSStatusItem!private var panel: PanelController!private var editor: EditorController?@@ -420,12 +421,25 @@ final class AppDelegate: NSObject, NSApplicationDelegate {/// 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.+ ///+ /// The window does not follow the phone's connection: to scan the code the user switches+ /// to Smart Life, our app goes to the background and iOS disconnects it. It closes when+ /// the phone says it is signed in (or gave up), when the user closes it, or after ten+ /// minutes, by which time the login ticket is long dead.private func showLoginCode(_ content: String?, for device: String) {+ loginWindowExpiry?.cancel()+ loginWindowExpiry = nilguard let content, content.hasPrefix("tuyaSmart--qrLogin?token=") else {loginWindow?.close()loginWindow = nilreturn}+ let expiry = DispatchWorkItem { [weak self] in+ self?.loginWindow?.close()+ self?.loginWindow = nil+ }+ loginWindowExpiry = expiry+ DispatchQueue.main.asyncAfter(deadline: .now() + 600, execute: expiry)if loginWindow == nil {let window = QRWindowController(title: "Smart Life Sign-In for \(device)")window.onClose = { [weak self] in self?.loginWindow = nil }@@ -433,8 +447,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {}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.")+ detail: "Switch to Smart Life on the iPhone, tap the scanner on its Home tab and confirm the login. "+ + "Then return to House Control: this window closes once the iPhone is signed in.")loginWindow?.setStatus("Requested by \(device)", active: true)}diff --git a/scripts/build-app.sh b/scripts/build-app.shindex ee2546c..f3c684d 100755--- a/scripts/build-app.sh+++ b/scripts/build-app.sh@@ -42,5 +42,9 @@ cat > "$APP/Contents/Info.plist" <<PLIST</dict></plist>PLIST-codesign --force --sign - "$APP" >/dev/null 2>&1 || echo " (ad-hoc signing skipped)"+# Ad-hoc by default. macOS ties permissions (the Local Network one that iPhone sync needs)+# to the signature, and an ad-hoc one changes with every build, so it asks again each time.+# CODESIGN_IDENTITY="Apple Development: …" (see `security find-identity -v -p codesigning`)+# signs with your own certificate and the permission sticks.+codesign --force --sign "${CODESIGN_IDENTITY:--}" "$APP" >/dev/null 2>&1 || echo " (signing skipped)"echo "✓ Done: $APP"