Firmware, iOS-App und Gehäuse für den 5x5x5-LED-Würfel
ESP32-S3-Firmware mit 18 Effekten, Mikrofon (Klatschen, Beat, Spektrum) und REST-API, Testprogramme, SwiftUI-Fernbedienung und OpenSCAD-Sockel. Die WLAN-Zugangsdaten (secrets.h) sind nicht enthalten. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
55b94475a5
22 files changed
+52104
No files matched your search
@@ -0,0 +1,256 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 77;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
C0BE00000000000000000001 /* CubeRemote.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = CubeRemote.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFileSystemSynchronizedRootGroup section */
|
||||
C0BE00000000000000000002 /* CubeRemote */ = {
|
||||
isa = PBXFileSystemSynchronizedRootGroup;
|
||||
path = CubeRemote;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXFileSystemSynchronizedRootGroup section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
C0BE00000000000000000003 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
C0BE00000000000000000004 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
C0BE00000000000000000002 /* CubeRemote */,
|
||||
C0BE00000000000000000005 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
C0BE00000000000000000005 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
C0BE00000000000000000001 /* CubeRemote.app */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
C0BE00000000000000000006 /* CubeRemote */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = C0BE00000000000000000007 /* Build configuration list for PBXNativeTarget "CubeRemote" */;
|
||||
buildPhases = (
|
||||
C0BE00000000000000000008 /* Sources */,
|
||||
C0BE00000000000000000003 /* Frameworks */,
|
||||
C0BE00000000000000000009 /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
fileSystemSynchronizedGroups = (
|
||||
C0BE00000000000000000002 /* CubeRemote */,
|
||||
);
|
||||
name = CubeRemote;
|
||||
packageProductDependencies = (
|
||||
);
|
||||
productName = CubeRemote;
|
||||
productReference = C0BE00000000000000000001 /* CubeRemote.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
C0BE0000000000000000000A /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 1600;
|
||||
TargetAttributes = {
|
||||
C0BE00000000000000000006 = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = C0BE0000000000000000000B /* Build configuration list for PBXProject "CubeRemote" */;
|
||||
developmentRegion = de;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
de,
|
||||
Base,
|
||||
);
|
||||
mainGroup = C0BE00000000000000000004;
|
||||
minimizedProjectReferenceProxies = 1;
|
||||
preferredProjectObjectVersion = 77;
|
||||
productRefGroup = C0BE00000000000000000005 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
C0BE00000000000000000006 /* CubeRemote */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
C0BE00000000000000000009 /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
C0BE00000000000000000008 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
C0BE0000000000000000000C /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
|
||||
MTL_FAST_MATH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
C0BE0000000000000000000D /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
|
||||
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
|
||||
MTL_FAST_MATH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
C0BE0000000000000000000E /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEVELOPMENT_TEAM = RX5EBCNNWW;
|
||||
ENABLE_PREVIEWS = YES;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = Cube;
|
||||
INFOPLIST_KEY_NSLocalNetworkUsageDescription = "Die App steuert den LED-Würfel in deinem WLAN.";
|
||||
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
|
||||
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
|
||||
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
|
||||
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = UIInterfaceOrientationPortrait;
|
||||
INFOPLIST_KEY_UIUserInterfaceStyle = Dark;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = de.wesemann.CubeRemote;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = 1;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
C0BE0000000000000000000F /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEVELOPMENT_TEAM = RX5EBCNNWW;
|
||||
ENABLE_PREVIEWS = YES;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = Cube;
|
||||
INFOPLIST_KEY_NSLocalNetworkUsageDescription = "Die App steuert den LED-Würfel in deinem WLAN.";
|
||||
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
|
||||
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
|
||||
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
|
||||
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = UIInterfaceOrientationPortrait;
|
||||
INFOPLIST_KEY_UIUserInterfaceStyle = Dark;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = de.wesemann.CubeRemote;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = 1;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
C0BE0000000000000000000B /* Build configuration list for PBXProject "CubeRemote" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
C0BE0000000000000000000C /* Debug */,
|
||||
C0BE0000000000000000000D /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
C0BE00000000000000000007 /* Build configuration list for PBXNativeTarget "CubeRemote" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
C0BE0000000000000000000E /* Debug */,
|
||||
C0BE0000000000000000000F /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
rootObject = C0BE0000000000000000000A /* Project object */;
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 557 KiB |
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"images" : [
|
||||
{ "filename" : "AppIcon.png", "idiom" : "universal", "platform" : "ios", "size" : "1024x1024" }
|
||||
],
|
||||
"info" : { "author" : "xcode", "version" : 1 }
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"info" : { "author" : "xcode", "version" : 1 }
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import SwiftUI
|
||||
|
||||
struct ContentView: View {
|
||||
@State private var model = CubeModel()
|
||||
@State private var showSettings = false
|
||||
@State private var flashes = 0
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
// Kein Scrollen: die Effekt-Kacheln teilen sich die restliche Höhe
|
||||
VStack(spacing: 12) {
|
||||
status
|
||||
specials
|
||||
brightness
|
||||
autoToggle
|
||||
effectGrid
|
||||
}
|
||||
.padding(.horizontal)
|
||||
.padding(.vertical, 8)
|
||||
.navigationTitle("LED-Würfel")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .topBarTrailing) {
|
||||
Button("Einstellungen", systemImage: "gearshape") { showSettings = true }
|
||||
}
|
||||
}
|
||||
.sheet(isPresented: $showSettings) {
|
||||
SettingsView(host: model.host) { model.host = CubeModel.cleanHost($0) }
|
||||
}
|
||||
// Nur abfragen, solange die App im Vordergrund ist
|
||||
.task(id: scenePhase) {
|
||||
if scenePhase == .active { await model.poll() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var status: some View {
|
||||
HStack(spacing: 6) {
|
||||
Circle()
|
||||
.fill(model.isConnected ? .green : model.error == nil ? .gray : .red)
|
||||
.frame(width: 8, height: 8)
|
||||
Text(model.error ?? (model.isConnected ? "Verbunden mit \(model.host)" : "Verbinde mit \(model.host) …"))
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
/// Spezialeffekte, die kurz über dem laufenden Effekt abgespielt werden
|
||||
private var specials: some View {
|
||||
HStack(spacing: 8) {
|
||||
specialButton("blitz", "Blitz", "bolt.fill", .yellow)
|
||||
specialButton("explosion", "Explosion", "burst.fill", .orange)
|
||||
specialButton("regenbogen", "Regenbogen", "rainbow", .pink)
|
||||
}
|
||||
.sensoryFeedback(.impact(weight: .heavy), trigger: flashes)
|
||||
.disabled(!model.isConnected)
|
||||
}
|
||||
|
||||
private func specialButton(_ id: String, _ title: String, _ symbol: String, _ color: Color) -> some View {
|
||||
Button {
|
||||
flashes += 1
|
||||
Task { await model.special(id) }
|
||||
} label: {
|
||||
VStack(spacing: 4) {
|
||||
Image(systemName: symbol).font(.title2)
|
||||
Text(title)
|
||||
.font(.caption.weight(.semibold))
|
||||
.lineLimit(1)
|
||||
.minimumScaleFactor(0.7)
|
||||
}
|
||||
.foregroundStyle(.black)
|
||||
.frame(maxWidth: .infinity, minHeight: 56)
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.buttonBorderShape(.roundedRectangle(radius: 14))
|
||||
.tint(color)
|
||||
}
|
||||
|
||||
private var brightness: some View {
|
||||
HStack(spacing: 12) {
|
||||
Image(systemName: "sun.min.fill")
|
||||
.foregroundStyle(.secondary)
|
||||
Slider(value: $model.brightness, in: 0...255, step: 1) { editing in
|
||||
model.isDraggingBrightness = editing
|
||||
if !editing { Task { await model.commitBrightness() } }
|
||||
}
|
||||
.accessibilityLabel("Helligkeit")
|
||||
Image(systemName: "sun.max.fill")
|
||||
.foregroundStyle(.secondary)
|
||||
Text("\(Int(model.brightness))")
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: 36, alignment: .trailing)
|
||||
}
|
||||
.disabled(!model.isConnected)
|
||||
}
|
||||
|
||||
private var autoToggle: some View {
|
||||
Toggle("Automatisch wechseln", isOn: Binding(
|
||||
get: { model.state?.auto ?? true },
|
||||
set: { on in Task { await model.setAuto(on) } }
|
||||
))
|
||||
.disabled(!model.isConnected)
|
||||
}
|
||||
|
||||
/// Links zwei Spalten normale Effekte, rechts eine Spalte Musik-Effekte.
|
||||
/// Die Zeilen wachsen mit dem Platz (32 bis 56 Punkte hoch).
|
||||
private var effectGrid: some View {
|
||||
let normal = model.effects.filter { !$0.isMusic }
|
||||
let music = model.effects.filter(\.isMusic)
|
||||
let rowCount = max((normal.count + 1) / 2, music.count)
|
||||
return VStack(spacing: 8) {
|
||||
HStack(spacing: 8) {
|
||||
Color.clear.frame(maxWidth: .infinity)
|
||||
Color.clear.frame(maxWidth: .infinity)
|
||||
Label("Musik", systemImage: "music.note")
|
||||
.frame(maxWidth: .infinity)
|
||||
}
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
.font(.caption.weight(.semibold))
|
||||
.foregroundStyle(.secondary)
|
||||
.opacity(model.effects.isEmpty ? 0 : 1)
|
||||
ForEach(0..<rowCount, id: \.self) { row in
|
||||
HStack(spacing: 8) {
|
||||
cell(normal, 2 * row)
|
||||
cell(normal, 2 * row + 1)
|
||||
cell(music, row)
|
||||
}
|
||||
.frame(minHeight: 32, maxHeight: 56)
|
||||
}
|
||||
}
|
||||
.frame(maxHeight: .infinity, alignment: .top)
|
||||
.disabled(!model.isConnected)
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func cell(_ effects: [CubeEffect], _ index: Int) -> some View {
|
||||
if index < effects.count {
|
||||
tile(effects[index])
|
||||
} else {
|
||||
Color.clear.frame(maxWidth: .infinity)
|
||||
}
|
||||
}
|
||||
|
||||
private func tile(_ effect: CubeEffect) -> some View {
|
||||
let active = effect.id == model.state?.effect
|
||||
let idle = effect.isMusic ? Color.indigo.opacity(0.35) : Color(.secondarySystemBackground)
|
||||
return Button {
|
||||
Task { await model.select(effect) }
|
||||
} label: {
|
||||
Text(effect.name)
|
||||
.font(.subheadline)
|
||||
.fontWeight(active ? .semibold : .regular)
|
||||
.multilineTextAlignment(.center)
|
||||
// Nur an Leerzeichen umbrechen; einzelne Wörter lieber verkleinern als trennen
|
||||
.lineLimit(effect.name.contains(" ") ? 2 : 1)
|
||||
.minimumScaleFactor(0.6)
|
||||
.foregroundStyle(active ? .black : .primary)
|
||||
.padding(.horizontal, 4)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(active ? Color.green : idle, in: .rect(cornerRadius: 10))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
|
||||
struct SettingsView: View {
|
||||
let host: String
|
||||
let save: (String) -> Void
|
||||
@State private var draft = ""
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
Form {
|
||||
Section {
|
||||
TextField("cube.local", text: $draft)
|
||||
.keyboardType(.URL)
|
||||
.textInputAutocapitalization(.never)
|
||||
.autocorrectionDisabled()
|
||||
} header: {
|
||||
Text("Adresse des Würfels")
|
||||
} footer: {
|
||||
Text("Name oder IP-Adresse im WLAN, z. B. cube.local oder 10.0.1.8")
|
||||
}
|
||||
}
|
||||
.navigationTitle("Einstellungen")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .cancellationAction) {
|
||||
Button("Abbrechen") { dismiss() }
|
||||
}
|
||||
ToolbarItem(placement: .confirmationAction) {
|
||||
Button("Fertig") {
|
||||
save(draft)
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
}
|
||||
.onAppear { draft = host }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
ContentView()
|
||||
.preferredColorScheme(.dark)
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import Foundation
|
||||
|
||||
/// Zustand des Würfels, wie ihn GET/PATCH /api/state liefern.
|
||||
struct CubeState: Codable, Equatable {
|
||||
var effect: String
|
||||
var auto: Bool
|
||||
var brightness: Int
|
||||
}
|
||||
|
||||
/// Ein Eintrag aus GET /api/effects.
|
||||
struct CubeEffect: Codable, Identifiable, Hashable {
|
||||
let id: String
|
||||
let name: String
|
||||
let music: Bool?
|
||||
|
||||
/// Musik-Visualisierung (reagiert auf das Mikrofon des Würfels)
|
||||
var isMusic: Bool { music ?? false }
|
||||
}
|
||||
|
||||
/// Änderung für PATCH /api/state – nur gesetzte Felder werden gesendet.
|
||||
struct CubeStatePatch: Encodable {
|
||||
var effect: String?
|
||||
var auto: Bool?
|
||||
var brightness: Int?
|
||||
}
|
||||
|
||||
struct CubeAPIError: LocalizedError {
|
||||
let message: String
|
||||
var errorDescription: String? { message }
|
||||
}
|
||||
|
||||
/// Zugriff auf die REST-API des Würfels (siehe web.cpp in der Firmware).
|
||||
struct CubeAPI {
|
||||
let host: String
|
||||
|
||||
private static let session: URLSession = {
|
||||
let config = URLSessionConfiguration.ephemeral
|
||||
config.timeoutIntervalForRequest = 4
|
||||
return URLSession(configuration: config)
|
||||
}()
|
||||
|
||||
func state() async throws -> CubeState {
|
||||
let data = try await request("state")
|
||||
return try JSONDecoder().decode(CubeState.self, from: data)
|
||||
}
|
||||
|
||||
func effects() async throws -> [CubeEffect] {
|
||||
let data = try await request("effects")
|
||||
return try JSONDecoder().decode([CubeEffect].self, from: data)
|
||||
}
|
||||
|
||||
func update(_ patch: CubeStatePatch) async throws -> CubeState {
|
||||
let data = try await request("state", method: "PATCH", json: JSONEncoder().encode(patch))
|
||||
return try JSONDecoder().decode(CubeState.self, from: data)
|
||||
}
|
||||
|
||||
/// Spezialeffekt auslösen: "blitz", "explosion" oder "regenbogen"
|
||||
func special(_ id: String) async throws {
|
||||
_ = try await request("specials/\(id)", method: "POST")
|
||||
}
|
||||
|
||||
private func request(_ path: String, method: String = "GET", json: Data? = nil) async throws -> Data {
|
||||
guard let url = URL(string: "http://\(host)/api/\(path)") else {
|
||||
throw CubeAPIError(message: "Ungültige Adresse: \(host)")
|
||||
}
|
||||
var request = URLRequest(url: url)
|
||||
request.httpMethod = method
|
||||
if let json {
|
||||
request.httpBody = json
|
||||
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
}
|
||||
|
||||
let data: Data
|
||||
let response: URLResponse
|
||||
do {
|
||||
(data, response) = try await Self.session.data(for: request)
|
||||
} catch let error as URLError {
|
||||
throw CubeAPIError(message: Self.describe(error))
|
||||
}
|
||||
|
||||
guard let http = response as? HTTPURLResponse else {
|
||||
throw CubeAPIError(message: "Keine gültige Antwort vom Würfel")
|
||||
}
|
||||
guard (200..<300).contains(http.statusCode) else {
|
||||
let message = (try? JSONDecoder().decode([String: String].self, from: data))?["error"]
|
||||
throw CubeAPIError(message: message ?? "Fehler \(http.statusCode)")
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
private static func describe(_ error: URLError) -> String {
|
||||
switch error.code {
|
||||
case .notConnectedToInternet:
|
||||
return "Kein Netzwerk – ist das iPhone im WLAN und „Lokales Netzwerk“ für die App erlaubt?"
|
||||
case .cannotFindHost, .dnsLookupFailed:
|
||||
return "Würfel nicht gefunden – ist er eingeschaltet und im selben WLAN?"
|
||||
case .timedOut, .cannotConnectToHost, .networkConnectionLost:
|
||||
return "Würfel antwortet nicht"
|
||||
default:
|
||||
return error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import Foundation
|
||||
import Observation
|
||||
|
||||
/// Hält den Zustand des Würfels und gleicht ihn regelmäßig mit der API ab.
|
||||
@MainActor @Observable
|
||||
final class CubeModel {
|
||||
/// Name oder IP-Adresse des Würfels, wird gespeichert.
|
||||
var host: String {
|
||||
didSet {
|
||||
UserDefaults.standard.set(host, forKey: "host")
|
||||
state = nil
|
||||
effects = []
|
||||
error = nil
|
||||
}
|
||||
}
|
||||
|
||||
private(set) var state: CubeState?
|
||||
private(set) var effects: [CubeEffect] = []
|
||||
private(set) var error: String?
|
||||
|
||||
/// Wert des Helligkeitsreglers; folgt dem Würfel, solange nicht gezogen wird.
|
||||
var brightness: Double = 32
|
||||
var isDraggingBrightness = false
|
||||
|
||||
var isConnected: Bool { state != nil && error == nil }
|
||||
|
||||
private var api: CubeAPI { CubeAPI(host: host) }
|
||||
|
||||
init() {
|
||||
host = UserDefaults.standard.string(forKey: "host") ?? "cube.local"
|
||||
}
|
||||
|
||||
/// Fragt den Zustand alle 2 Sekunden ab, bis die Aufgabe abgebrochen wird.
|
||||
func poll() async {
|
||||
while !Task.isCancelled {
|
||||
await refresh()
|
||||
try? await Task.sleep(for: .seconds(2))
|
||||
}
|
||||
}
|
||||
|
||||
func refresh() async {
|
||||
do {
|
||||
if effects.isEmpty { effects = try await api.effects() }
|
||||
apply(try await api.state())
|
||||
} catch {
|
||||
self.error = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
func select(_ effect: CubeEffect) async {
|
||||
await update(CubeStatePatch(effect: effect.id))
|
||||
}
|
||||
|
||||
func setAuto(_ on: Bool) async {
|
||||
await update(CubeStatePatch(auto: on))
|
||||
}
|
||||
|
||||
func commitBrightness() async {
|
||||
await update(CubeStatePatch(brightness: Int(brightness)))
|
||||
}
|
||||
|
||||
func special(_ id: String) async {
|
||||
do {
|
||||
try await api.special(id)
|
||||
error = nil
|
||||
} catch {
|
||||
self.error = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
private func update(_ patch: CubeStatePatch) async {
|
||||
do {
|
||||
apply(try await api.update(patch))
|
||||
} catch {
|
||||
self.error = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
private func apply(_ newState: CubeState) {
|
||||
state = newState
|
||||
error = nil
|
||||
if !isDraggingBrightness { brightness = Double(newState.brightness) }
|
||||
}
|
||||
|
||||
/// Macht aus Eingaben wie "http://10.0.1.8/" ein "10.0.1.8".
|
||||
static func cleanHost(_ input: String) -> String {
|
||||
var host = input.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
for prefix in ["http://", "https://"] where host.lowercased().hasPrefix(prefix) {
|
||||
host.removeFirst(prefix.count)
|
||||
}
|
||||
while host.hasSuffix("/") { host.removeLast() }
|
||||
return host.isEmpty ? "cube.local" : host
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import SwiftUI
|
||||
|
||||
@main
|
||||
struct CubeRemoteApp: App {
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
ContentView()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user