Your home as a live 3D model in the Mac menu bar and on iPhone — lights and ACs via Smart Life, Home Assistant, Philips Hue and Apple Home.
iPhone app in two editions: App Store without Smart Life, TestFlight with it
0xProbability450f6bfc3abe
diff --git a/README.md b/README.mdindex fa699f7..463dc24 100644--- a/README.md+++ b/README.md@@ -205,8 +205,21 @@ Try it in the simulator:```To put it on a phone, write your Apple developer team into `ios/Config/Local.xcconfig`-(`DEVELOPMENT_TEAM = ABCDE12345`), run `cd ios && xcodegen generate`, open `ios/HouseControl.xcodeproj` and run it-on your device. `./scripts/build-ios.sh --upload` archives it and sends it to TestFlight; the script lists what it needs.+(`DEVELOPMENT_TEAM = ABCDE12345`), run `cd ios && xcodegen generate --spec project-smartlife.yml`, open+`ios/HouseControl.xcodeproj` and run it on your device. `./scripts/build-ios.sh --upload` archives it and sends it to+TestFlight; the script lists what it needs.++The iPhone app comes in two editions, built from the same code:++| Edition | What it has | Built from |+| --- | --- | --- |+| **App Store** | Home Assistant, Philips Hue, Apple Home | `ios/project.yml` · `EDITION=appstore` |+| **Smart Life** | all of the above plus Smart Life / Tuya, for TestFlight and your own phone | `ios/project-smartlife.yml` (the scripts' default) |++Smart Life is reached through the sign-in Home Assistant's Tuya integration uses, not through an API Tuya offers to+apps, so it stays out of the App Store edition entirely: its code lives in its own module (`core/Sources/HouseSmartLife`)+that only the Smart Life edition and the Mac app link, and `build-ios.sh` refuses an App Store archive that contains it.+The two editions are separate apps (bundle id and App Group), so both can sit on one phone.### Sync with the Mac@@ -229,7 +242,7 @@ pre-shared key that only the QR code carries, so a device that never saw the cod### Real devices on the iPhone-The phone signs in to Smart Life on its own: **Settings → Connect Smart Life**. The User Code is filled in from the+In the Smart Life edition the phone signs in to Smart Life on its own: **Settings → Connect Smart Life**. The User Code is filled in from theMac if you are signed in there. The sign-in code has to be scanned by the Smart Life app, which is on the very phoneyou are holding. So **Save code to Photos**, then in Smart Life tap **+ → Scan** and open the picture from its photobutton. A paired Mac also puts the code on its screen for you, and **Share code** sends it to any other screen.@@ -330,7 +343,8 @@ Home Assistant and Hue connections the Mac shared in the Keychain.```web/ the UI: Three.js scene, panel, island, editor, AI Access window and the AI tools (Vite, plain ES modules)-core/ what both apps share: Smart Life and Tuya clients, plan store, Mac ⇄ iPhone sync, the AI gateway (SwiftPM, with tests)+core/ what both apps share: plan store, device platforms, Mac ⇄ iPhone sync, the AI gateway, and the Smart Life+ and Tuya clients as a separate module (SwiftPM, with tests)macos/ the Mac shell: menu bar item, panel, island and editor windows (SwiftPM)ios/ the iPhone shell: SwiftUI, generated into an Xcode project by XcodeGenscripts/ build-app.sh, build-ios.sh and ios-sim.sh build the apps, release-mac.sh makes the .dmg,diff --git a/core/Package.swift b/core/Package.swiftindex 8c168d8..d2a7109 100644--- a/core/Package.swift+++ b/core/Package.swift@@ -1,16 +1,20 @@// swift-tools-version:5.9import PackageDescription-// What the macOS and iOS apps share: the Smart Life / Tuya clients, the plan store-// and the Mac ⇄ iPhone sync.+// What the macOS and iOS apps share: the plan store, the device platforms and the+// Mac ⇄ iPhone sync. Smart Life / Tuya is a separate module (HouseSmartLife), so a build+// can leave it out: the App Store edition of the iPhone app does.let package = Package(name: "HouseCore",platforms: [.macOS(.v13), .iOS(.v17)],products: [- .library(name: "HouseCore", targets: ["HouseCore"])+ .library(name: "HouseCore", targets: ["HouseCore"]),+ .library(name: "HouseSmartLife", targets: ["HouseSmartLife"]),],targets: [.target(name: "HouseCore", path: "Sources/HouseCore"),+ .target(name: "HouseSmartLife", dependencies: ["HouseCore"], path: "Sources/HouseSmartLife"),.testTarget(name: "HouseCoreTests", dependencies: ["HouseCore"], path: "Tests/HouseCoreTests"),+ .testTarget(name: "HouseSmartLifeTests", dependencies: ["HouseSmartLife"], path: "Tests/HouseSmartLifeTests"),])diff --git a/core/Sources/HouseCore/About.swift b/core/Sources/HouseCore/About.swiftnew file mode 100644index 0000000..dfd2211--- /dev/null+++ b/core/Sources/HouseCore/About.swift@@ -0,0 +1,12 @@+import Foundation++/// Who makes House Control and where to find it, for the About screens of both apps.+public enum About {+ public static let developer = "0xProbability"+ public static let website = URL(string: "https://house-control-3d.vercel.app")!+ public static let privacy = URL(string: "https://house-control-3d.vercel.app/privacy")!+ public static let support = URL(string: "https://house-control-3d.vercel.app/support")!+ public static let x = URL(string: "https://x.com/0xProbabillity")!+ public static let github = URL(string: "https://github.com/0xProbabillity")!+ public static let source = URL(string: "https://github.com/0xProbabillity/house-control")!+}diff --git a/core/Sources/HouseCore/DeviceHub.swift b/core/Sources/HouseCore/DeviceHub.swiftindex 27b35a4..da096f8 100644--- a/core/Sources/HouseCore/DeviceHub.swift+++ b/core/Sources/HouseCore/DeviceHub.swift@@ -7,8 +7,8 @@ import Foundation@MainActorpublic final class DeviceHub {public let log: EventLog- private let tuya: TuyaService- private let smartLife: SmartLifeService+ /// Smart Life, in the builds that include it (HouseSmartLife); nil elsewhere.+ public let cloud: LinkedCloud?public let homeAssistant: HomeAssistantServicepublic let hue: HueService/// Apple Home: HomeKit itself on the iPhone, the iPhone's catalog on the Mac.@@ -16,11 +16,8 @@ public final class DeviceHub {/// The platforms other than Smart Life, by the id a plan's `link.service` uses.public var services: [DeviceService] { [homeAssistant, hue, homeKit] }private func service(_ id: String) -> DeviceService? { services.first { $0.id == id } }- /// The backend real devices are reached through: the QR-linked Smart Life account- /// when there is one, otherwise a Tuya Cloud project, otherwise nothing (simulation).- private var cloud: DeviceCloud? {- smartLife.isConfigured ? smartLife : (tuya.isConfigured ? tuya : nil)- }+ /// Smart Life when it is part of this build and signed in.+ private var connectedCloud: LinkedCloud? { cloud?.isConnected == true ? cloud : nil }/// App device id -> its Smart Life link, for the devices of the active plan.private var links: [String: (kind: String, link: [String: Any])] = [:]/// App device id -> its link to another platform.@@ -37,7 +34,6 @@ public final class DeviceHub {private var refresh: Task<Void, Never>?/// The command in flight for each real device; the next one waits for it.private var commandTails: [String: Task<Void, Never>] = [:]- private let infrared = InfraredRemote()/// 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.@@ -46,12 +42,13 @@ public final class DeviceHub {/// `secret(name)` is where a platform's credentials are kept ("smartlife", "homeassistant",/// "hue"); by default `<name>.json` in `directory`, readable by its user only. `homeKit`/// is HomeKit on the iPhone; without one, Apple Home is the catalog a paired iPhone sent.- public init(directory: URL, secret: ((String) -> SecretStore)? = nil, homeKit: DeviceService? = nil) {+ /// `cloud` makes the Smart Life client (`SmartLifePlatform.init` where it is built in).+ public init(directory: URL, secret: ((String) -> SecretStore)? = nil, homeKit: DeviceService? = nil,+ cloud: (@MainActor (URL, (String) -> SecretStore) -> LinkedCloud)? = nil) {let vault = secret ?? { FileSecretStore(url: directory.appendingPathComponent("\($0).json")) }log = EventLog(directory: directory)stampsURL = directory.appendingPathComponent("connections-sync.json")- tuya = TuyaService(directory: directory)- smartLife = SmartLifeService(vault: vault("smartlife"))+ self.cloud = cloud?(directory, vault)homeAssistant = HomeAssistantService(vault: vault("homeassistant"))hue = HueService(vault: vault("hue"))self.homeKit = homeKit ?? RemoteCatalogService(id: "homekit", title: "Apple Home",@@ -73,11 +70,11 @@ public final class DeviceHub {// MARK: - Links- public var isConnected: Bool { cloud != nil || services.contains { $0.isConnected && $0.controlsDevices } }+ public var isConnected: Bool { connectedCloud != nil || services.contains { $0.isConnected && $0.controlsDevices } }public var hasLinks: Bool { !links.isEmpty || !serviceLinks.isEmpty }/// True when there is something to read at all.public var canPoll: Bool {- (cloud != nil && !links.isEmpty)+ (connectedCloud != nil && !links.isEmpty)|| serviceLinks.values.contains { service($0.service).map { $0.isConnected && $0.controlsDevices } ?? false }}public var linkedDeviceCount: Int { links.count + serviceLinks.values.filter { !$0.id.isEmpty }.count }@@ -96,7 +93,8 @@ public final class DeviceHub {if let link = device["link"] as? [String: Any], let service = link["service"] as? String,let target = link["id"] as? String, !target.isEmpty {serviceLinks[id] = Link(kind: DeviceKind(rawValue: kind) ?? .light, service: service, id: target, sensor: sensor)- } else if let link = device["tuya"] as? [String: Any], let deviceId = link["deviceId"] as? String, !deviceId.isEmpty {+ } else if cloud != nil, let link = device["tuya"] as? [String: Any],+ let deviceId = link["deviceId"] as? String, !deviceId.isEmpty {links[id] = (kind, link)if let sensor { tuyaSensors[id] = sensor }} else if let sensor, kind == "ac" {@@ -135,7 +133,7 @@ public final class DeviceHub {commandService(link, appId: id, message, reply: reply)return}- guard let cloud, let id = message["id"] as? String, let entry = links[id],+ guard let cloud = connectedCloud, 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 sendreturn@@ -146,21 +144,9 @@ public final class DeviceHub {commandTails[deviceId] = Task { @MainActor inawait previous?.valuedo {- // 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)- }+ try await cloud.command(appId: id, kind: entry.kind, link: entry.link, patch: patch, state: state, log: log)reply(["ok": true])- } catch let rejected as InfraredRemote.Rejection {+ } catch let rejected as CommandRejection {reply(["error": rejected.message, "failed": rejected.fields])} catch {reply(["error": error.localizedDescription])@@ -194,23 +180,12 @@ public final class DeviceHub {}}- 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]? {- async let tuyaPart = pollSmartLife()+ async let tuyaPart = pollCloud()async let servicePart = pollServices()let (fromTuya, fromServices) = await (tuyaPart, servicePart)guard fromTuya != nil || fromServices != nil else { return nil }@@ -264,40 +239,9 @@ public final class DeviceHub {return ["lights": lights, "acs": acs, "features": features]}- private func pollSmartLife() async -> [String: Any]? {- let entries = links- guard let cloud, !entries.isEmpty else { return nil }- // Devices plus the temperature sensors that stand in for an AC's room reading.- 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()+ private func pollCloud() async -> [String: Any]? {+ guard let cloud = connectedCloud, !links.isEmpty else { return nil }+ return await cloud.poll(links)}/// Every device of every connected platform, in the editor's terms, plus what went@@ -305,9 +249,9 @@ public final class DeviceHub {public func allDevices() async -> (devices: [[String: Any]], errors: [String: String]) {var devices: [[String: Any]] = []var errors: [String: String] = [:]- if cloud != nil {+ if let cloud = connectedCloud {do {- devices += try await listDevices().map(Self.smartLifeDevice)+ devices += try await cloud.devices()} catch {errors["smartlife"] = error.localizedDescription}@@ -322,34 +266,10 @@ public final class DeviceHub {return (devices, errors)}- /// A Smart Life device in the same shape as the other platforms' (plus its Tuya codes).- static func smartLifeDevice(_ d: [String: Any]) -> [String: Any] {- let codes = Set(d["codes"] as? [String] ?? [])- let category = d["category"] as? String ?? ""- let kind: DeviceKind- if ["kt", "ktkzq", "infrared_ac"].contains(category) || TuyaMapper.isInfraredAC(codes) || codes.contains("temp_set") {- kind = .ac- } else if ["wsdcg", "wk", "wnykq"].contains(category) || (codes.contains("temp_current") && !codes.contains("switch_led")) {- kind = .sensor- } else {- kind = .light- }- var caps: [String] = []- if codes.contains("bright_value") || codes.contains("bright_value_v2") { caps.append("brightness") }- if codes.contains("temp_value") || codes.contains("temp_value_v2") { caps.append("temp") }- if codes.contains("colour_data") || codes.contains("colour_data_v2") { caps.append("color") }- var out = d- out["service"] = "smartlife"- out["kind"] = kind.rawValue- out["capabilities"] = caps- out["room"] = nil- out["detail"] = [d["product"] as? String, category].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")- return out- }-/// What the editor and the settings show for each platform.public var servicesInfo: [String: Any] {- var out: [String: Any] = ["smartlife": smartLifeInfo.merging(["connected": isSmartLifeConnected || tuya.isConfigured]) { $1 }]+ var out: [String: Any] = [:]+ if let cloud { out["smartlife"] = cloud.info }for service in services { out[service.id] = service.info }return out}@@ -445,42 +365,4 @@ public final class DeviceHub {stamps = knownreturn changed}-- /// 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/LinkedCloud.swift b/core/Sources/HouseCore/LinkedCloud.swiftnew file mode 100644index 0000000..3a85de2--- /dev/null+++ b/core/Sources/HouseCore/LinkedCloud.swift@@ -0,0 +1,33 @@+import Foundation++/// The cloud behind the plan's `tuya` links (Smart Life). It is an optional part of the+/// apps, the HouseSmartLife module: a build without it keeps such links in the plan but+/// shows those devices as simulated.+@MainActor+public protocol LinkedCloud: AnyObject {+ /// True when an account is connected and commands can be sent.+ var isConnected: Bool { get }+ /// What the editor and the settings show for it, under "smartlife".+ var info: [String: Any] { get }+ /// Sends the panel's change (`patch`; `state` is the device with it applied) to the+ /// device a plan's `tuya` link names. Throws `CommandRejection` when part of it did not+ /// reach the device.+ func command(appId: String, kind: String, link: [String: Any], patch: [String: Any],+ state: [String: Any], log: EventLog) async throws+ /// What the linked devices report (app device id -> its `tuya` link), in the shape the+ /// panel's `applyRemote` takes; nil when the cloud could not be reached.+ func poll(_ links: [String: (kind: String, link: [String: Any])]) async -> [String: Any]?+ /// Every device of the account, in the editor's terms.+ func devices() async throws -> [[String: Any]]+}++/// The parts of a change that did not reach the device; the panel rolls back only those.+public struct CommandRejection: Error {+ public let message: String+ public let fields: [String]++ public init(message: String, fields: [String]) {+ self.message = message+ self.fields = fields+ }+}diff --git a/core/Sources/HouseCore/QRCode.swift b/core/Sources/HouseCore/QRCode.swiftnew file mode 100644index 0000000..af0920f--- /dev/null+++ b/core/Sources/HouseCore/QRCode.swift@@ -0,0 +1,22 @@+import Foundation+import CoreImage+import ImageIO++/// QR codes for pairing an iPhone with the Mac (and the Smart Life login, where it is built in).+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)+ return CGImageDestinationFinalize(dest) ? data as Data : nil+ }+}diff --git a/core/Sources/HouseCore/InfraredRemote.swift b/core/Sources/HouseSmartLife/InfraredRemote.swiftsimilarity index 99%rename from core/Sources/HouseCore/InfraredRemote.swiftrename to core/Sources/HouseSmartLife/InfraredRemote.swiftindex de22b20..454762c 100644--- a/core/Sources/HouseCore/InfraredRemote.swift+++ b/core/Sources/HouseSmartLife/InfraredRemote.swift@@ -1,4 +1,5 @@import Foundation+import HouseCore/// Drives air conditioners that are a remote control learned by an infrared blaster.///diff --git a/core/Sources/HouseCore/SelfTest.swift b/core/Sources/HouseSmartLife/SelfTest.swiftsimilarity index 95%rename from core/Sources/HouseCore/SelfTest.swiftrename to core/Sources/HouseSmartLife/SelfTest.swiftindex 96dcfc1..7ff00bf 100644--- a/core/Sources/HouseCore/SelfTest.swift+++ b/core/Sources/HouseSmartLife/SelfTest.swift@@ -1,4 +1,5 @@import Foundation+import HouseCore/// Offline self-checks and the read-only diagnostic behind the Mac binary's command line/// flags (`--selftest-mapper`, `--selftest-infrared`, `--selftest-transport`, `--diagnose`).@@ -52,9 +53,10 @@ public enum SelfTest {// (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)+ let directory = PlanStore().directory+ let cloud = SmartLifePlatform(directory: directory) { FileSecretStore(url: directory.appendingPathComponent("\($0).json")) }Task { @MainActor in- let dump = await hub.diagnostics(for: ids)+ let dump = await cloud.diagnostics(for: ids)let data = (try? JSONSerialization.data(withJSONObject: dump, options: [.prettyPrinted, .sortedKeys])) ?? Data()print(String(data: data, encoding: .utf8) ?? "{}")exit(0)diff --git a/core/Sources/HouseSmartLife/SmartLifePlatform.swift b/core/Sources/HouseSmartLife/SmartLifePlatform.swiftnew file mode 100644index 0000000..8df1915--- /dev/null+++ b/core/Sources/HouseSmartLife/SmartLifePlatform.swift@@ -0,0 +1,172 @@+import Foundation+import HouseCore++/// Smart Life for the device hub: the QR-linked account when there is one, otherwise a+/// Tuya Cloud project ("Advanced"). Builds that include this module pass+/// `SmartLifePlatform.init` to `DeviceHub(cloud:)`; the App Store build of the iPhone app+/// leaves it out.+@MainActor+public final class SmartLifePlatform: LinkedCloud {+ private let tuya: TuyaService+ private let smartLife: SmartLifeService+ private let infrared = InfraredRemote()++ /// `secret("smartlife")` keeps the session; the Tuya Cloud project lives in `directory`.+ public init(directory: URL, secret: (String) -> SecretStore) {+ tuya = TuyaService(directory: directory)+ smartLife = SmartLifeService(vault: secret("smartlife"))+ }++ /// 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 active: DeviceCloud? {+ smartLife.isConfigured ? smartLife : (tuya.isConfigured ? tuya : nil)+ }++ public var isConnected: Bool { active != nil }++ public var info: [String: Any] {+ smartLife.publicInfo.merging(["connected": isConnected]) { $1 }+ }++ // MARK: - LinkedCloud++ public func command(appId id: String, kind: String, link: [String: Any], patch: [String: Any],+ state: [String: Any], log: EventLog) async throws {+ guard let cloud = active, let deviceId = link["deviceId"] as? String else { return }+ // The first command to a device may arrive before anything is known about it.+ await cloud.prepare(deviceId)+ let codes = cloud.knownCodes[deviceId] ?? []+ let send: ([[String: Any]]) async throws -> Void = { commands in+ 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+ }+ }+ if kind == "light" {+ try await send(TuyaMapper.lightCommands(patch: patch, state: state, link: link, codes: codes,+ ranges: cloud.knownRanges[deviceId] ?? [:]))+ } else if TuyaMapper.isInfraredAC(codes) {+ do {+ try await infrared.apply(patch: patch, state: state, to: deviceId,+ send: { try await send([$0]) }, note: { log.write("\(id) \($0)") })+ } catch let rejected as InfraredRemote.Rejection {+ throw CommandRejection(message: rejected.message, fields: rejected.fields)+ }+ } else {+ try await send(TuyaMapper.acCommands(patch: patch, link: link, codes: codes))+ }+ }++ public func poll(_ entries: [String: (kind: String, link: [String: Any])]) async -> [String: Any]? {+ guard let cloud = active, !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 devices() async throws -> [[String: Any]] {+ try await listDevices().map(Self.device)+ }++ /// The account's devices as Tuya reports them (with their data point codes).+ public func listDevices() async throws -> [[String: Any]] {+ guard let cloud = active else { throw SmartLifeService.Failure(message: "Connect Smart Life first") }+ return try await cloud.listDevices()+ }++ /// A Smart Life device in the same shape as the other platforms' (plus its Tuya codes).+ static func device(_ d: [String: Any]) -> [String: Any] {+ let codes = Set(d["codes"] as? [String] ?? [])+ let category = d["category"] as? String ?? ""+ let kind: DeviceKind+ if ["kt", "ktkzq", "infrared_ac"].contains(category) || TuyaMapper.isInfraredAC(codes) || codes.contains("temp_set") {+ kind = .ac+ } else if ["wsdcg", "wk", "wnykq"].contains(category) || (codes.contains("temp_current") && !codes.contains("switch_led")) {+ kind = .sensor+ } else {+ kind = .light+ }+ var caps: [String] = []+ if codes.contains("bright_value") || codes.contains("bright_value_v2") { caps.append("brightness") }+ if codes.contains("temp_value") || codes.contains("temp_value_v2") { caps.append("temp") }+ if codes.contains("colour_data") || codes.contains("colour_data_v2") { caps.append("color") }+ var out = d+ out["service"] = "smartlife"+ out["kind"] = kind.rawValue+ out["capabilities"] = caps+ out["room"] = nil+ out["detail"] = [d["product"] as? String, category].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")+ return out+ }++ /// 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 userCode: String { smartLife.session?.userCode ?? "" }+ public var account: 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))+ }+}++public extension DeviceHub {+ /// The Smart Life side of this hub, when it was made with one.+ var smartLife: SmartLifePlatform? { cloud as? SmartLifePlatform }+}diff --git a/core/Sources/HouseCore/SmartLifeService.swift b/core/Sources/HouseSmartLife/SmartLifeService.swiftsimilarity index 94%rename from core/Sources/HouseCore/SmartLifeService.swiftrename to core/Sources/HouseSmartLife/SmartLifeService.swiftindex f8a3c5d..cf45da3 100644--- a/core/Sources/HouseCore/SmartLifeService.swift+++ b/core/Sources/HouseSmartLife/SmartLifeService.swift@@ -1,7 +1,6 @@import Foundationimport CryptoKit-import CoreImage-import ImageIO+import HouseCore/// What the app needs from a device backend, whichever way the account is connected.@MainActor@@ -353,22 +352,3 @@ final class SmartLifeService: DeviceCloud {}}}--/// 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)- return CGImageDestinationFinalize(dest) ? data as Data : nil- }-}diff --git a/core/Sources/HouseCore/TuyaService.swift b/core/Sources/HouseSmartLife/TuyaService.swiftsimilarity index 99%rename from core/Sources/HouseCore/TuyaService.swiftrename to core/Sources/HouseSmartLife/TuyaService.swiftindex 0bf3ba6..40ba7a4 100644--- a/core/Sources/HouseCore/TuyaService.swift+++ b/core/Sources/HouseSmartLife/TuyaService.swift@@ -1,4 +1,5 @@import Foundation+import HouseCoreimport CryptoKit/// Minimal client for the Tuya Cloud OpenAPI ("Smart Home" project with the Smart Lifediff --git a/core/Tests/HouseCoreTests/DeviceTests.swift b/core/Tests/HouseCoreTests/DeviceTests.swiftindex 5dcf1a2..65fa826 100644--- a/core/Tests/HouseCoreTests/DeviceTests.swift+++ b/core/Tests/HouseCoreTests/DeviceTests.swift@@ -7,60 +7,18 @@ final class DeviceTests: XCTestCase {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() {+ func testHubWithoutSmartLifeSimulatesItsLinks() {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, secret: { _ in MemorySecretStore() })- hub.setLinks(from: ["lights": [["id": "a", "tuya": ["deviceId": "dev1"]], ["id": "b"], ["id": "c", "tuya": ["deviceId": ""]]],- "acs": [["id": "ac", "tuya": ["deviceId": "dev2", "sensorId": "s1"]]]])- XCTAssertEqual(hub.linkedDeviceCount, 2)- XCTAssertFalse(hub.isConnected)- XCTAssertFalse(hub.canPoll)+ hub.setLinks(from: ["lights": [["id": "a", "tuya": ["deviceId": "dev1"]]]])+ XCTAssertNil(hub.cloud)+ XCTAssertEqual(hub.linkedDeviceCount, 0)+ XCTAssertNil(hub.servicesInfo["smartlife"])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)+ XCTAssertEqual(reply?["ok"] as? Bool, true)}func testPlanStoreKeepsSyncedBytesAndRevision() throws {diff --git a/core/Tests/HouseCoreTests/ServiceTests.swift b/core/Tests/HouseCoreTests/ServiceTests.swiftindex 4d9fdd8..fbac9c1 100644--- a/core/Tests/HouseCoreTests/ServiceTests.swift+++ b/core/Tests/HouseCoreTests/ServiceTests.swift@@ -248,13 +248,6 @@ final class ServiceTests: XCTestCase {XCTAssertTrue(fake.sent.count == 1)}- func testSmartLifeDevicesGetAKind() {- XCTAssertEqual(DeviceHub.smartLifeDevice(["id": "1", "category": "dj", "codes": ["switch_led", "bright_value_v2", "temp_value_v2"]])["kind"] as? String, "light")- XCTAssertEqual(DeviceHub.smartLifeDevice(["id": "2", "category": "infrared_ac", "codes": ["PowerOn", "T"]])["kind"] as? String, "ac")- XCTAssertEqual(DeviceHub.smartLifeDevice(["id": "3", "category": "wsdcg", "codes": ["temp_current"]])["kind"] as? String, "sensor")- XCTAssertEqual(DeviceHub.smartLifeDevice(["id": "1", "category": "dj", "codes": ["switch_led", "bright_value_v2"]])["capabilities"] as? [String], ["brightness"])- }-// MARK: - A real Home Assistant (opt-in)func testLiveHomeAssistant() async throws {diff --git a/core/Tests/HouseSmartLifeTests/SmartLifeTests.swift b/core/Tests/HouseSmartLifeTests/SmartLifeTests.swiftnew file mode 100644index 0000000..2e8ab0c--- /dev/null+++ b/core/Tests/HouseSmartLifeTests/SmartLifeTests.swift@@ -0,0 +1,75 @@+import XCTest+import HouseCore+@testable import HouseSmartLife++/// The Smart Life / Tuya module: command building, the infrared remote, the transport and+/// the hub routing plan links through it.+@MainActor+final class SmartLifeTests: 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, secret: { _ in MemorySecretStore() }, cloud: SmartLifePlatform.init)+ 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 testSmartLifeDevicesGetAKind() {+ XCTAssertEqual(SmartLifePlatform.device(["id": "1", "category": "dj", "codes": ["switch_led", "bright_value_v2", "temp_value_v2"]])["kind"] as? String, "light")+ XCTAssertEqual(SmartLifePlatform.device(["id": "2", "category": "infrared_ac", "codes": ["PowerOn", "T"]])["kind"] as? String, "ac")+ XCTAssertEqual(SmartLifePlatform.device(["id": "3", "category": "wsdcg", "codes": ["temp_current"]])["kind"] as? String, "sensor")+ XCTAssertEqual(SmartLifePlatform.device(["id": "1", "category": "dj", "codes": ["switch_led", "bright_value_v2"]])["capabilities"] as? [String], ["brightness"])+ }+}diff --git a/ios/Config/Base.xcconfig b/ios/Config/Base.xcconfigindex 42a0e2e..016b73f 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 = 5+MARKETING_VERSION = 1.0.0+CURRENT_PROJECT_VERSION = 6CODE_SIGN_STYLE = Automaticdiff --git a/ios/Sources/AppModel.swift b/ios/Sources/AppModel.swiftindex de29b56..bcc7767 100644--- a/ios/Sources/AppModel.swift+++ b/ios/Sources/AppModel.swift@@ -1,5 +1,8 @@import SwiftUIimport HouseCore+#if SMART_LIFE+import HouseSmartLife+#endif/// A short message that slides in under the status bar.struct Banner: Equatable, Identifiable {@@ -31,7 +34,7 @@ enum SettingsRoute: Hashable, Identifiable {/// The screen a connection id of the web editor ("smartlife", "hue"…) stands for.init?(service: String) {switch service {- case "smartlife": self = .smartLife+ case "smartlife" where AppModel.includesSmartLife: self = .smartLifecase "homeassistant": self = .homeAssistantcase "hue": self = .huedefault: return nil@@ -90,9 +93,15 @@ final class AppModel {private(set) var homeKit: HomeKitStatus = .off@ObservationIgnored let homeKitService = HomeKitService()- // Smart Life- private(set) var smartLifeConnected: Bool- private(set) var smartLifeAccount: String+ // Smart Life: only in the builds that include it (TestFlight). The App Store edition is+ // built without the HouseSmartLife module, so none of its code is in that app.+ #if SMART_LIFE+ nonisolated static let includesSmartLife = true+ #else+ nonisolated static let includesSmartLife = false+ #endif+ private(set) var smartLifeConnected = false+ private(set) var smartLifeAccount = ""/// The User Code entered on the Mac, offered here so it need not be typed again.private(set) var suggestedUserCode = ""@@ -125,7 +134,11 @@ final class AppModel {sandboxed ? FileSecretStore(url: directory.appendingPathComponent("\(name).json")): KeychainSecretStore(service: Bundle.main.bundleIdentifier ?? "HouseControl", account: name)}+ #if SMART_LIFE+ hub = DeviceHub(directory: directory, secret: secret, homeKit: homeKitService, cloud: SmartLifePlatform.init)+ #elsehub = DeviceHub(directory: directory, secret: secret, homeKit: homeKitService)+ #endifsync = SyncClient(store: secret("sync"))web = HomeWeb(persistent: !sandboxed)@@ -134,8 +147,10 @@ final class AppModel {customPlanName = plans.customPlanNamesyncStatus = sync.statusmacName = sync.pairing?.name- smartLifeConnected = hub.isSmartLifeConnected- smartLifeAccount = hub.smartLifeAccount+ #if SMART_LIFE+ smartLifeConnected = hub.smartLife?.isSmartLifeConnected ?? false+ smartLifeAccount = hub.smartLife?.account ?? ""+ #endiflastSync = UserDefaults.standard.object(forKey: "lastSync") as? Datehub.onStale = { [weak self] in self?.poll() }@@ -224,7 +239,9 @@ final class AppModel {private func bootPayload() -> [String: Any] {var boot = plans.bootPayload()- boot["smartLife"] = hub.smartLifeInfo+ #if SMART_LIFE+ boot["smartLife"] = hub.smartLife?.smartLifeInfo+ #endifif let device = ProcessInfo.processInfo.environment["HOUSE_OPEN_DEVICE"] { boot["openDevice"] = device }return boot}@@ -364,8 +381,10 @@ final class AppModel {private func editorBoot() -> [String: Any] {var boot = plans.bootPayload()if boot["config"] == nil, let plan = currentPlan { boot["config"] = plan }- boot["smartLife"] = hub.smartLifeInfo- boot["tuya"] = hub.tuyaInfo+ #if SMART_LIFE+ boot["smartLife"] = hub.smartLife?.smartLifeInfo+ boot["tuya"] = hub.smartLife?.tuyaInfo+ #endifboot["services"] = hub.servicesInfoif let section = ProcessInfo.processInfo.environment["HOUSE_OPEN_EDITOR"] { boot["section"] = section }return boot@@ -480,6 +499,7 @@ final class AppModel {case "service.disconnect":disconnect(service: message["service"] as? String ?? "")reply(hub.servicesInfo)+ #if SMART_LIFEcase "smartlife.begin":Task { @MainActor indo {@@ -493,23 +513,24 @@ final class AppModel {case "smartlife.poll":Task { @MainActor inlet done = await finishLogin(token: message["token"] as? String ?? "", userCode: message["userCode"] as? String ?? "")- reply(["connected": done, "info": hub.smartLifeInfo])+ reply(["connected": done, "info": smartLife.smartLifeInfo])}case "smartlife.signOut":signOut()- reply(hub.smartLifeInfo)+ reply(smartLife.smartLifeInfo)case "tuya.devices":Task { @MainActor in- do { reply(["devices": try await hub.listDevices()]) } catch { reply(["error": error.localizedDescription]) }+ do { reply(["devices": try await smartLife.listDevices()]) } catch { reply(["error": error.localizedDescription]) }}case "tuya.save":do {- try hub.saveTuya(accessId: message["accessId"] as? String ?? "", accessSecret: message["accessSecret"] as? String ?? "",+ try smartLife.saveTuya(accessId: message["accessId"] as? String ?? "", accessSecret: message["accessSecret"] as? String ?? "",region: message["region"] as? String ?? "eu")- reply(hub.tuyaInfo)+ reply(smartLife.tuyaInfo)} catch {reply(["error": error.localizedDescription])}+ #endifdefault:break}@@ -608,7 +629,7 @@ final class AppModel {startPolling()}// Whatever this phone connected (or disconnected) since goes the other way.- sync.sendConnections(hub.shareableConnections, userCode: hub.smartLifeUserCode)+ sync.sendConnections(hub.shareableConnections, userCode: smartLifeUserCode)sendCatalog()reconcilePlan(with: state)}@@ -682,17 +703,30 @@ final class AppModel {// MARK: - Smart Life+ /// The User Code of the Smart Life account, for the Mac (empty without Smart Life).+ private var smartLifeUserCode: String {+ #if SMART_LIFE+ hub.smartLife?.userCode ?? ""+ #else+ ""+ #endif+ }++ #if SMART_LIFE+ /// Always there in the builds that include Smart Life.+ private var smartLife: SmartLifePlatform { hub.smartLife! }+func beginLogin(userCode: String) async throws -> (token: String, qrContent: String) {- try await hub.beginLogin(userCode: userCode)+ try await smartLife.beginLogin(userCode: userCode)}/// True once the login was confirmed in the Smart Life app.func finishLogin(token: String, userCode: String) async -> Bool {- guard await hub.finishLogin(token: token, userCode: userCode) else { return false }- smartLifeConnected = hub.isSmartLifeConnected- smartLifeAccount = hub.smartLifeAccount+ guard await smartLife.finishLogin(token: token, userCode: userCode) else { return false }+ smartLifeConnected = smartLife.isSmartLifeConnected+ smartLifeAccount = smartLife.accountsync.showQR(nil)- sync.sendConnections(hub.shareableConnections, userCode: hub.smartLifeUserCode)+ sync.sendConnections(hub.shareableConnections, userCode: smartLifeUserCode)editorWeb?.call("servicesChanged", hub.servicesInfo)Haptics.shared.play("success")startPolling()@@ -703,12 +737,13 @@ final class AppModel {func showOnMac(_ qrContent: String?) -> Bool { sync.showQR(qrContent) }func signOut() {- hub.signOut()+ smartLife.signOut()smartLifeConnected = falsesmartLifeAccount = ""pollTimer?.invalidate()pollTimer = nil}+ #endif// MARK: - Home Assistant, Hue, Apple Home@@ -741,7 +776,7 @@ final class AppModel {reloadLinks()startPolling()poll()- sync.sendConnections(hub.shareableConnections, userCode: hub.smartLifeUserCode)+ sync.sendConnections(hub.shareableConnections, userCode: smartLifeUserCode)editorWeb?.call("servicesChanged", hub.servicesInfo)}diff --git a/ios/Sources/EditorScreen.swift b/ios/Sources/EditorScreen.swiftindex 412db70..c0b22a1 100644--- a/ios/Sources/EditorScreen.swift+++ b/ios/Sources/EditorScreen.swift@@ -18,7 +18,9 @@ struct EditorScreen: View {NavigationStack {Group {switch route {+ #if SMART_LIFEcase .smartLife: SmartLifeView()+ #endifcase .homeAssistant: HomeAssistantView()case .hue: HueView()default: EmptyView()diff --git a/ios/Sources/SettingsView.swift b/ios/Sources/SettingsView.swiftindex 1cb1720..6380d8b 100644--- a/ios/Sources/SettingsView.swift+++ b/ios/Sources/SettingsView.swift@@ -20,7 +20,9 @@ struct SettingsView: View {homeSectionshortcutsSectionmacSection+ #if SMART_LIFEsmartLifeSection+ #endifconnectionsSectionaboutSection}@@ -40,7 +42,11 @@ struct SettingsView: View {.navigationDestination(for: SettingsRoute.self) { route inswitch route {case .pairing: PairingView()+ #if SMART_LIFEcase .smartLife: SmartLifeView()+ #else+ case .smartLife: EmptyView()+ #endifcase .quickActions: QuickActionsView()case .homeAssistant: HomeAssistantView()case .hue: HueView()@@ -264,6 +270,7 @@ struct SettingsView: View {// MARK: - Smart Life+ #if SMART_LIFEprivate var smartLifeSection: some View {VStack(spacing: 10) {SectionTitle("Smart Life")@@ -311,12 +318,13 @@ struct SettingsView: View {}}}+ #endif// MARK: - Home Assistant, Hue, Apple Homeprivate var connectionsSection: some View {VStack(spacing: 10) {- SectionTitle("More connections")+ SectionTitle(AppModel.includesSmartLife ? "More connections" : "Connections")Card {NavigationLink(value: SettingsRoute.homeAssistant) {serviceRow(symbol: "server.rack", tint: ConnectionLook.homeAssistant, title: "Home Assistant",@@ -412,7 +420,25 @@ struct SettingsView: View {RowDivider().padding(.leading, -52)infoRow("Privacy", value: "No account, no analytics")}- footnote("House Control talks to your own devices: Tuya's servers for Smart Life, your Home Assistant, your Hue Bridge, Apple Home, and your Mac. Nothing else leaves this iPhone.")+ footnote(AppModel.includesSmartLife+ ? "House Control talks to your own devices: Tuya's servers for Smart Life, your Home Assistant, your Hue Bridge, Apple Home, and your Mac. Nothing else leaves this iPhone."+ : "House Control talks to your own devices: your Home Assistant, your Hue Bridge, Apple Home, and your Mac. Nothing else leaves this iPhone.")+ Card {+ webRow(About.website, symbol: "globe", tint: Theme.accent, title: "Website", detail: "Features, help and the Mac app")+ RowDivider()+ webRow(About.privacy, symbol: "hand.raised.fill", tint: Theme.green, title: "Privacy Policy", detail: "Nothing is collected")+ RowDivider()+ webRow(About.support, symbol: "questionmark.circle.fill", tint: Theme.warm, title: "Support", detail: "Questions and problems")+ }+ SectionTitle("Developer").padding(.top, 20)+ Card {+ webRow(About.x, symbol: "at", tint: Theme.text, title: "\(About.developer) on X", detail: "@0xProbabillity")+ RowDivider()+ webRow(About.github, symbol: "chevron.left.forwardslash.chevron.right", tint: Theme.text,+ title: "\(About.developer) on GitHub", detail: "github.com/0xProbabillity")+ RowDivider()+ webRow(About.source, symbol: "shippingbox.fill", tint: Theme.text, title: "Source code", detail: "House Control is open source")+ }}}@@ -431,6 +457,26 @@ struct SettingsView: View {.frame(minHeight: 52)}+ /// A row that opens a web page in the browser.+ private func webRow(_ url: URL, symbol: String, tint: Color, title: String, detail: String) -> some View {+ Link(destination: url) {+ HStack(spacing: 14) {+ IconBadge(symbol: symbol, tint: tint)+ VStack(alignment: .leading, spacing: 2) {+ Text(title).font(.system(size: 16.5, weight: .semibold)).foregroundStyle(Theme.text)+ Text(detail).font(.system(size: 13.5)).foregroundStyle(Theme.muted).lineLimit(1)+ }+ Spacer(minLength: 8)+ Image(systemName: "arrow.up.right").font(.system(size: 13, weight: .semibold)).foregroundStyle(Theme.faint)+ }+ .padding(.horizontal, 14)+ .frame(minHeight: 66)+ .contentShape(Rectangle())+ }+ .buttonStyle(RowButtonStyle())+ .accessibilityHint("Opens in Safari")+ }+private func footnote(_ text: String) -> some View {Text(text).font(.system(size: 13))diff --git a/ios/Sources/SmartLifeView.swift b/ios/Sources/SmartLifeView.swiftindex 9f3e269..4018a87 100644--- a/ios/Sources/SmartLifeView.swift+++ b/ios/Sources/SmartLifeView.swift@@ -1,3 +1,4 @@+#if SMART_LIFEimport SwiftUIimport Photosimport HouseCore@@ -300,3 +301,4 @@ private struct QRImage: Transferable {.suggestedFileName("Smart Life sign-in code.png")}}+#endifdiff --git a/ios/Sources/WelcomeView.swift b/ios/Sources/WelcomeView.swiftindex 464255d..8ac2a83 100644--- a/ios/Sources/WelcomeView.swift+++ b/ios/Sources/WelcomeView.swift@@ -35,7 +35,9 @@ struct WelcomeView: View {feature("pencil.and.ruler.fill", Theme.accent, "Draw it here or on your Mac","Rooms, lamps and ACs, on this iPhone. Pair a Mac any time: both stay in sync.")feature("lightbulb.2.fill", Theme.green, "Your real devices",- "Smart Life, Home Assistant, Philips Hue and Apple Home. Until you connect one, everything is simulated.")+ AppModel.includesSmartLife+ ? "Smart Life, Home Assistant, Philips Hue and Apple Home. Until you connect one, everything is simulated."+ : "Home Assistant, Philips Hue and Apple Home. Until you connect one, everything is simulated.")}.padding(.horizontal, 6).frame(maxHeight: .infinity)diff --git a/ios/project-smartlife.yml b/ios/project-smartlife.ymlnew file mode 100644index 0000000..e6ead82--- /dev/null+++ b/ios/project-smartlife.yml@@ -0,0 +1,30 @@+# The Smart Life edition of the iPhone app: everything in project.yml plus the Smart Life /+# Tuya module (HouseSmartLife). Smart Life is reached through the sign-in Home Assistant's+# Tuya integration uses, not through an API Tuya offers to apps, so this edition is for+# TestFlight and own use only, never the App Store. It is its own app (bundle id and App+# Group), so both editions can sit on one iPhone without mixing their widgets:+# xcodegen generate --spec project-smartlife.yml+# scripts/build-ios.sh and scripts/ios-sim.sh build it unless EDITION=appstore.+include: [project.yml]+targets:+ HouseControl:+ dependencies:+ - package: HouseCore+ product: HouseSmartLife+ info:+ properties:+ NSPhotoLibraryAddUsageDescription: House Control saves the Smart Life sign-in code to Photos, so the Smart Life app on this iPhone can scan it from there.+ settings:+ base:+ SWIFT_ACTIVE_COMPILATION_CONDITIONS: $(inherited) SMART_LIFE+ PRODUCT_BUNDLE_IDENTIFIER: io.github.0xprobabillity.HouseControl+ HOUSE_APP_GROUP: group.io.github.0xprobabillity.HouseControl+ HouseWidgets:+ dependencies:+ - package: HouseCore+ product: HouseSmartLife+ settings:+ base:+ SWIFT_ACTIVE_COMPILATION_CONDITIONS: $(inherited) SMART_LIFE+ PRODUCT_BUNDLE_IDENTIFIER: io.github.0xprobabillity.HouseControl.Widgets+ HOUSE_APP_GROUP: group.io.github.0xprobabillity.HouseControldiff --git a/ios/project.yml b/ios/project.ymlindex a0a895e..4dad694 100644--- a/ios/project.yml+++ b/ios/project.yml@@ -1,4 +1,6 @@# The Xcode project is generated from this file: `xcodegen generate` (scripts/build-ios.sh does it).+# This is the App Store edition: Home Assistant, Philips Hue and Apple Home. The edition with+# Smart Life on top (TestFlight, own use) is project-smartlife.yml, which includes this file.name: HouseControloptions:bundleIdPrefix: io.github.0xprobabillity@@ -32,13 +34,13 @@ targets:properties:com.apple.developer.homekit: true# Shared with the widgets: the home they draw, and the connections they use.- com.apple.security.application-groups: [group.io.github.0xprobabillity.HouseControl]+ com.apple.security.application-groups: [$(HOUSE_APP_GROUP)]keychain-access-groups: [$(AppIdentifierPrefix)io.github.0xprobabillity.HouseControl]info:path: Config/Info.plistproperties:CFBundleDisplayName: House Control- HouseAppGroup: group.io.github.0xprobabillity.HouseControl+ HouseAppGroup: $(HOUSE_APP_GROUP)CFBundleShortVersionString: $(MARKETING_VERSION)CFBundleVersion: $(CURRENT_PROJECT_VERSION)LSApplicationCategoryType: public.app-category.lifestyle@@ -55,13 +57,14 @@ targets:NSAppTransportSecurity:NSAllowsLocalNetworking: trueNSCameraUsageDescription: The camera reads the pairing code shown by House Control on your Mac.- NSPhotoLibraryAddUsageDescription: House Control saves the Smart Life sign-in code to Photos, so the Smart Life app on this iPhone can scan it from there.CFBundleURLTypes:- CFBundleURLName: io.github.0xprobabillity.HouseControl.pairCFBundleURLSchemes: [housecontrol]settings:base:- PRODUCT_BUNDLE_IDENTIFIER: io.github.0xprobabillity.HouseControl+ PRODUCT_BUNDLE_IDENTIFIER: io.github.0xprobabillity.HouseControl3D+ # Shared with the widgets: the home they draw, and the actions they queue.+ HOUSE_APP_GROUP: group.io.github.0xprobabillity.HouseControl3DPRODUCT_NAME: HouseControlTARGETED_DEVICE_FAMILY: "1"ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon@@ -84,7 +87,7 @@ targets:entitlements:path: ../widgets/Config/iOS.entitlementsproperties:- com.apple.security.application-groups: [group.io.github.0xprobabillity.HouseControl]+ com.apple.security.application-groups: [$(HOUSE_APP_GROUP)]keychain-access-groups: [$(AppIdentifierPrefix)io.github.0xprobabillity.HouseControl]info:path: ../widgets/Config/Info-iOS.plist@@ -92,12 +95,13 @@ targets:CFBundleDisplayName: House ControlCFBundleShortVersionString: $(MARKETING_VERSION)CFBundleVersion: $(CURRENT_PROJECT_VERSION)- HouseAppGroup: group.io.github.0xprobabillity.HouseControl+ HouseAppGroup: $(HOUSE_APP_GROUP)NSExtension:NSExtensionPointIdentifier: com.apple.widgetkit-extensionsettings:base:- PRODUCT_BUNDLE_IDENTIFIER: io.github.0xprobabillity.HouseControl.Widgets+ PRODUCT_BUNDLE_IDENTIFIER: io.github.0xprobabillity.HouseControl3D.Widgets+ HOUSE_APP_GROUP: group.io.github.0xprobabillity.HouseControl3DPRODUCT_NAME: HouseWidgetsTARGETED_DEVICE_FAMILY: "1"SWIFT_VERSION: "5.0"diff --git a/macos/Package.swift b/macos/Package.swiftindex f3beebf..fd22885 100644--- a/macos/Package.swift+++ b/macos/Package.swift@@ -9,7 +9,8 @@ let package = Package(],targets: [.executableTarget(name: "HouseControl",- dependencies: [.product(name: "HouseCore", package: "core")],+ dependencies: [.product(name: "HouseCore", package: "core"),+ .product(name: "HouseSmartLife", package: "core")],path: "Sources/HouseControl")])diff --git a/macos/Sources/HouseControl/AppDelegate.swift b/macos/Sources/HouseControl/AppDelegate.swiftindex b413a36..d8debd3 100644--- a/macos/Sources/HouseControl/AppDelegate.swift+++ b/macos/Sources/HouseControl/AppDelegate.swift@@ -1,12 +1,15 @@import AppKitimport UniformTypeIdentifiersimport HouseCore+import HouseSmartLife@MainActorfinal class AppDelegate: NSObject, NSApplicationDelegate {private let plans = PlanStore()/// The Smart Life / Tuya side: device links, commands and state.- private lazy var hub = DeviceHub(directory: plans.directory)+ private lazy var hub = DeviceHub(directory: plans.directory, cloud: SmartLifePlatform.init)+ /// Smart Life is always part of the Mac app.+ private var smartLife: SmartLifePlatform { hub.smartLife! }/// 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?@@ -191,6 +194,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {item.image = NSImage(systemSymbolName: "iphone", accessibilityDescription: nil)}menu.addItem(.separator())+ menu.addItem(aboutMenuItem())menu.addItem(withTitle: "Reload", action: #selector(reloadAll), keyEquivalent: "").target = selfmenu.addItem(withTitle: "Quit House Control", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")statusItem.menu = menu@@ -210,11 +214,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate {private func bootPayload() -> [String: Any] {var boot = plans.bootPayload()- boot["tuya"] = hub.tuyaInfo- var smartLife = hub.smartLifeInfo+ boot["tuya"] = smartLife.tuyaInfo+ var account = smartLife.smartLifeInfo// Not signed in here yet: offer the User Code a paired iPhone signed in with.- if !hub.isSmartLifeConnected, !phoneUserCode.isEmpty { smartLife["userCode"] = phoneUserCode }- boot["smartLife"] = smartLife+ if !smartLife.isSmartLifeConnected, !phoneUserCode.isEmpty { account["userCode"] = phoneUserCode }+ boot["smartLife"] = accountboot["services"] = hub.servicesInfoswitch ProcessInfo.processInfo.environment["HOUSE_OPEN_EDITOR"] {case "smartlife": boot["section"] = "service:smartlife"@@ -269,6 +273,37 @@ final class AppDelegate: NSObject, NSApplicationDelegate {NSWorkspace.shared.activateFileViewerSelecting([url])}+ /// "About House Control": the version, the website and where to find the developer.+ private func aboutMenuItem() -> NSMenuItem {+ let about = NSMenu()+ let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String+ about.addItem(withTitle: "House Control\(version.map { " \($0)" } ?? "")", action: nil, keyEquivalent: "")+ about.addItem(.separator())+ let links: [(String, String, URL)] = [+ ("Website", "globe", About.website),+ ("Privacy Policy", "hand.raised", About.privacy),+ ("Support", "questionmark.circle", About.support),+ ("", "", About.website),+ ("\(About.developer) on X", "at", About.x),+ ("\(About.developer) on GitHub", "chevron.left.forwardslash.chevron.right", About.github),+ ("Source Code", "shippingbox", About.source),+ ]+ for (title, symbol, url) in links {+ guard !title.isEmpty else { about.addItem(.separator()); continue }+ let item = about.addItem(withTitle: title, action: #selector(openLink(_:)), keyEquivalent: "")+ item.target = self+ item.representedObject = url+ item.image = NSImage(systemSymbolName: symbol, accessibilityDescription: nil)+ }+ let item = NSMenuItem(title: "About House Control", action: nil, keyEquivalent: "")+ item.submenu = about+ return item+ }++ @objc private func openLink(_ sender: NSMenuItem) {+ if let url = sender.representedObject as? URL { NSWorkspace.shared.open(url) }+ }+@objc private func revealLog() {if !FileManager.default.fileExists(atPath: hub.log.fileURL.path) { hub.log.write("log started") }NSWorkspace.shared.activateFileViewerSelecting([hub.log.fileURL])@@ -370,17 +405,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate {}case "tuya.save":do {- try hub.saveTuya(accessId: message["accessId"] as? String ?? "",+ try smartLife.saveTuya(accessId: message["accessId"] as? String ?? "",accessSecret: message["accessSecret"] as? String ?? "",region: message["region"] as? String ?? "eu")- host.reply(to: message, hub.tuyaInfo)+ host.reply(to: message, smartLife.tuyaInfo)} catch {host.reply(to: message, ["error": error.localizedDescription])}case "tuya.devices":Task { @MainActor indo {- host.reply(to: message, ["devices": try await hub.listDevices()])+ host.reply(to: message, ["devices": try await smartLife.listDevices()])} catch {host.reply(to: message, ["error": error.localizedDescription])}@@ -389,7 +424,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {let userCode = message["userCode"] as? String ?? ""Task { @MainActor indo {- let login = try await hub.beginLogin(userCode: userCode)+ let login = try await smartLife.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 {@@ -400,13 +435,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate {let token = message["token"] as? String ?? ""let userCode = message["userCode"] as? String ?? ""Task { @MainActor in- let done = await hub.finishLogin(token: token, userCode: userCode)- host.reply(to: message, ["connected": done, "info": hub.smartLifeInfo])+ let done = await smartLife.finishLogin(token: token, userCode: userCode)+ host.reply(to: message, ["connected": done, "info": smartLife.smartLifeInfo])if done { sync.broadcast() }}case "smartlife.signOut":- hub.signOut()- host.reply(to: message, hub.smartLifeInfo)+ smartLife.signOut()+ host.reply(to: message, smartLife.smartLifeInfo)sync.broadcast()// Home Assistant, Philips Hue, Apple Home@@ -526,8 +561,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {SyncState(macName: self.computerName,revision: self.plans.customPlanRevision ?? "",plan: try? Data(contentsOf: self.plans.customPlanURL),- userCode: self.hub.smartLifeUserCode,- smartLifeConnected: self.hub.isSmartLifeConnected,+ userCode: self.smartLife.userCode,+ smartLifeConnected: self.smartLife.isSmartLifeConnected,connections: self.hub.shareableConnections)}sync.onCatalog = { [weak self] devices, phone indiff --git a/macos/Sources/HouseControl/main.swift b/macos/Sources/HouseControl/main.swiftindex 34db1db..782aaa3 100644--- a/macos/Sources/HouseControl/main.swift+++ b/macos/Sources/HouseControl/main.swift@@ -1,5 +1,6 @@import AppKitimport HouseCore+import HouseSmartLifeMainActor.assumeIsolated {// `--selftest-mapper`, `--selftest-infrared`, `--selftest-transport` anddiff --git a/scripts/build-ios.sh b/scripts/build-ios.shindex b21a38f..9270fdd 100755--- a/scripts/build-ios.sh+++ b/scripts/build-ios.sh@@ -8,10 +8,29 @@# ASC_KEY_ID the key's ID; its file AuthKey_<id>.p8 lives in ~/.appstoreconnect/private_keys# ASC_ISSUER_ID the issuer ID shown above the key list in App Store Connect# The build number is CURRENT_PROJECT_VERSION in ios/Config/Base.xcconfig: raise it for every upload.-# BUNDLE_ID=… build under another bundle id (and <id>.Widgets for the widgets), e.g. the one an-# existing App Store Connect record was created with; the project files are not changed.+# EDITION=… smartlife (default): with Smart Life, for TestFlight and own use (ios/project-smartlife.yml)+# appstore: without it, the app that goes to App Review (ios/project.yml,+# io.github.0xprobabillity.HouseControl3D)+# BUNDLE_ID=… the Smart Life edition's bundle id (and <id>.Widgets for the widgets): the one+# your own App Store Connect record was created with; the project files are not+# changed. Required to upload that edition, which never goes to the App Store app.set -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"+EDITION="${EDITION:-smartlife}"+case "$EDITION" in+ appstore) SPEC=project.yml ;;+ smartlife) SPEC=project-smartlife.yml ;;+ *) echo "EDITION is appstore or smartlife"; exit 1 ;;+esac+if [ "$EDITION" = smartlife ] && [ "${1:-}" = "--upload" ] && [ -z "${BUNDLE_ID:-}" ]; then+ echo "The Smart Life edition goes to your own TestFlight app: set BUNDLE_ID to its bundle id,"+ echo "or EDITION=appstore for the App Store app."+ exit 1+fi+if [ "$EDITION" = appstore ] && [ -n "${BUNDLE_ID:-}" ]; then+ echo "The App Store edition keeps the bundle id in ios/project.yml; unset BUNDLE_ID."+ exit 1+fi: "${ASC_KEY_ID:?Set ASC_KEY_ID to your App Store Connect API key ID}": "${ASC_ISSUER_ID:?Set ASC_ISSUER_ID to your App Store Connect issuer ID}"KEY_FILE="${ASC_KEY_FILE:-$HOME/.appstoreconnect/private_keys/AuthKey_$ASC_KEY_ID.p8}"@@ -24,12 +43,12 @@ cd "$ROOT/web"[ -d node_modules ] || npm installnpm run build --silent-echo "▸ Archiving"+echo "▸ Archiving the $EDITION edition"cd "$ROOT/ios"[ -f Config/Local.xcconfig ] || { echo "Create ios/Config/Local.xcconfig with: DEVELOPMENT_TEAM = <your team id>"; exit 1; }-xcodegen generate --quiet+xcodegen generate --spec "$SPEC" --quietif [ -n "${BUNDLE_ID:-}" ]; then- sed -i '' "s/PRODUCT_BUNDLE_IDENTIFIER = io\.github\.0xprobabillity\.HouseControl/PRODUCT_BUNDLE_IDENTIFIER = $BUNDLE_ID/" \+ sed -i '' "s/PRODUCT_BUNDLE_IDENTIFIER = io\.github\.0xprobabillity\.HouseControl\([.;]\)/PRODUCT_BUNDLE_IDENTIFIER = $BUNDLE_ID\1/" \HouseControl.xcodeproj/project.pbxprojfirm -rf build/HouseControl.xcarchive build/export@@ -37,6 +56,13 @@ xcodebuild archive -project HouseControl.xcodeproj -scheme HouseControl -configu-destination 'generic/platform=iOS' -archivePath build/HouseControl.xcarchive \-derivedDataPath build/DerivedData "${AUTH[@]}" 2>&1 | grep -E "error|ARCHIVE" || true[ -d build/HouseControl.xcarchive ] || { echo "Archive failed"; exit 1; }+# The App Store edition must not contain the Smart Life client at all, not even unused.+APP_DIR=build/HouseControl.xcarchive/Products/Applications/HouseControl.app+if grep -rlq -e "iotbing" -e "SmartLifePlatform" "$APP_DIR"; then+ [ "$EDITION" = smartlife ] || { echo "Smart Life code found in the App Store edition"; exit 1; }+else+ [ "$EDITION" = appstore ] || { echo "Smart Life is missing from the Smart Life edition"; exit 1; }+fiecho "▸ Exporting"xcodebuild -exportArchive -archivePath build/HouseControl.xcarchive -exportPath build/export \diff --git a/scripts/ios-sim.sh b/scripts/ios-sim.shindex d071c90..9dee998 100755--- a/scripts/ios-sim.sh+++ b/scripts/ios-sim.sh@@ -2,10 +2,12 @@# Builds the iPhone app for the simulator and launches it there.# ./scripts/ios-sim.sh build + install + launch on the booted simulator# HOUSE_SCREEN=settings ./scripts/ios-sim.sh …opening on a given screen (settings, pairing, smartlife, welcome, home)+# EDITION=appstore ./scripts/ios-sim.sh …the App Store edition, without Smart Life# Any HOUSE_* variable set here is passed on to the app.set -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"-DEVICE="${DEVICE:-iPhone 17 Pro}"+DEVICE="${DEVICE:-iPhone 17 Pro}" # a simulator's name or UDID+[[ "$DEVICE" =~ ^[0-9A-F-]{36}$ ]] && DEST="id=$DEVICE" || DEST="name=$DEVICE"if [ -z "${SKIP_WEB:-}" ]; thencd "$ROOT/web"@@ -14,9 +16,10 @@ if [ -z "${SKIP_WEB:-}" ]; thenficd "$ROOT/ios"-xcodegen generate --quiet+[ "${EDITION:-smartlife}" = appstore ] && SPEC=project.yml || SPEC=project-smartlife.yml+xcodegen generate --spec "$SPEC" --quietxcodebuild -project HouseControl.xcodeproj -scheme HouseControl -configuration Debug \- -destination "platform=iOS Simulator,name=$DEVICE" -derivedDataPath build/DerivedData \+ -destination "platform=iOS Simulator,$DEST" -derivedDataPath build/DerivedData \CODE_SIGN_IDENTITY=- build 2>&1 | grep -E "error|warning: |BUILD" | grep -v appintentsmetadataprocessor || trueAPP="build/DerivedData/Build/Products/Debug-iphonesimulator/HouseControl.app"[ -d "$APP" ] || { echo "Build failed"; exit 1; }@@ -33,4 +36,4 @@ fixcrun simctl bootstatus "$DEVICE" -b >/dev/nullxcrun simctl install "$DEVICE" "$APP"for name in $(compgen -v | grep '^HOUSE_' || true); do export "SIMCTL_CHILD_$name=${!name}"; done-xcrun simctl launch --terminate-running-process "$DEVICE" io.github.0xprobabillity.HouseControl+xcrun simctl launch --terminate-running-process "$DEVICE" "$(/usr/libexec/PlistBuddy -c "Print CFBundleIdentifier" "$APP/Info.plist")"diff --git a/web/src/editor/connections.js b/web/src/editor/connections.jsindex 3ce1313..b3a79f2 100644--- a/web/src/editor/connections.js+++ b/web/src/editor/connections.js@@ -27,8 +27,11 @@ export function createConnections({ rerender, toast, usedBy, onOpen }) {pairing: null, // { host, until } while waiting for the Hue button};+ // The platforms this app offers: the native side lists them (the iPhone's App Store+ // edition has no Smart Life). A plain browser shows them all.+ const offered = () => (isNative && boot.services ? ORDER.filter((id) => id in state.info) : ORDER);const connected = (id) => Boolean(state.info[id]?.connected);- const anyConnected = () => ORDER.some(connected);+ const anyConnected = () => offered().some(connected);const devicesOf = (id) => (state.devices || []).filter((d) => d.service === id);async function refreshInfo() {@@ -58,7 +61,7 @@ export function createConnections({ rerender, toast, usedBy, onOpen }) {/* ---------- sidebar ---------- */function sidebarRow(active, select) {- const n = ORDER.filter(connected).length;+ const n = offered().filter(connected).length;return h(`button.row.tuya-row${active ? '.active' : ''}`, { onclick: select },icon('link', 15), h('span.row-name', 'Connections'),h(`span.pill${n ? '.on' : ''}`, n ? `${n} connected` : 'Demo mode'));@@ -84,12 +87,12 @@ export function createConnections({ rerender, toast, usedBy, onOpen }) {function overview() {if (anyConnected() && !state.devices && !state.loading) setTimeout(() => load(), 0);return [- h('div.svc-cards', ORDER.map((id) => h('button.svc-card', { onclick: () => onOpen(id) },+ h('div.svc-cards', offered().map((id) => h('button.svc-card', { onclick: () => onOpen(id) },tile(id),h('div.svc-text', h('b', SERVICES[id].name), h('span', LOOK[id].blurb)),h(`span.svc-status${connected(id) ? '.on' : ''}`, connected(id) ? icon('ok', 13, 2.4) : null, statusText(id)),icon('next', 16)))),- h('p.note', 'Lamps and ACs stay simulated until you link them: pick one on the plan, then choose its device under “Real device”. One home can mix all four.'),+ h('p.note', 'Lamps and ACs stay simulated until you link them: pick one on the plan, then choose its device under “Real device”. One home can mix them all.'),isNative ? null : h('p.note.bad', 'Connecting works inside the House Control app (this is the browser preview).'),];}@@ -307,7 +310,7 @@ export function createConnections({ rerender, toast, usedBy, onOpen }) {const select = h('select');select.append(h('option', { value: '' }, kind === 'sensor' ? 'None — estimated' : 'Not linked — simulated'));let found = false;- for (const id of ORDER) {+ for (const id of offered()) {const list = devicesOf(id).filter((d) => d.kind === kind && include(d));if (!list.length) continue;select.append(h('optgroup', { label: SERVICES[id].name }, list.map((d) => {diff --git a/widgets/Resources/PrivacyInfo.xcprivacy b/widgets/Resources/PrivacyInfo.xcprivacynew file mode 100644index 0000000..e87b65d--- /dev/null+++ b/widgets/Resources/PrivacyInfo.xcprivacy@@ -0,0 +1,20 @@+<?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>NSPrivacyTracking</key><false/>+ <key>NSPrivacyTrackingDomains</key><array/>+ <key>NSPrivacyCollectedDataTypes</key><array/>+ <key>NSPrivacyAccessedAPITypes</key>+ <array>+ <dict>+ <key>NSPrivacyAccessedAPIType</key><string>NSPrivacyAccessedAPICategoryUserDefaults</string>+ <key>NSPrivacyAccessedAPITypeReasons</key><array><string>CA92.1</string></array>+ </dict>+ <dict>+ <key>NSPrivacyAccessedAPIType</key><string>NSPrivacyAccessedAPICategoryFileTimestamp</string>+ <key>NSPrivacyAccessedAPITypeReasons</key><array><string>C617.1</string></array>+ </dict>+ </array>+</dict>+</plist>diff --git a/widgets/Sources/Actions.swift b/widgets/Sources/Actions.swiftindex e21a39e..4696b5d 100644--- a/widgets/Sources/Actions.swift+++ b/widgets/Sources/Actions.swift@@ -1,6 +1,9 @@import Foundationimport WidgetKitimport HouseCore+#if SMART_LIFE+import HouseSmartLife+#endif/// Carries out what a widget or a control asked for.///@@ -8,8 +11,8 @@ import HouseCore/// at once) and queued for the app. On the Mac the app is running in the menu bar: it takes/// the queue straight away and sends the change through the panel, like a click there./// On the iPhone the app is usually not running, so the widget reaches Home Assistant, Hue-/// and Smart Life itself, with the connections the app keeps in the shared Keychain group;-/// what it cannot reach from here (Apple Home) waits for the app to open.+/// and Smart Life (where it is built in) itself, with the connections the app keeps in the+/// shared Keychain group; what it cannot reach from here (Apple Home) waits for the app to open.enum WidgetActions {/// Returns false when the action could not be applied (no home yet, or nothing changed).@discardableResult@@ -39,7 +42,11 @@ enum WidgetActions {#if os(iOS)/// The platforms a widget can reach without the app.+ #if SMART_LIFEprivate static let reachable: Set<String> = ["smartlife", "homeassistant", "hue"]+ #else+ private static let reachable: Set<String> = ["homeassistant", "hue"]+ #endif/// True when every change reached its device (simulated devices always do).@MainActor@@ -49,8 +56,13 @@ enum WidgetActions {guard !real.isEmpty else { return true }if real.contains(where: { !reachable.contains((services[$0.id] ?? nil) ?? "") }) { return false }let app = appBundleIdentifier- let hub = DeviceHub(directory: shared.directory.appendingPathComponent("Hub", isDirectory: true),- secret: { KeychainSecretStore(service: app, account: $0) })+ let directory = shared.directory.appendingPathComponent("Hub", isDirectory: true)+ let secret: (String) -> SecretStore = { KeychainSecretStore(service: app, account: $0) }+ #if SMART_LIFE+ let hub = DeviceHub(directory: directory, secret: secret, cloud: SmartLifePlatform.init)+ #else+ let hub = DeviceHub(directory: directory, secret: secret)+ #endifhub.setLinks(from: home.linksPlan)var ok = truefor change in real {