Files
cube/ios/CubeRemote/CubeAPI.swift
T
mikeandClaude Opus 5.5 55b94475a5 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>
2026-11-13 15:00:43 +01:00

104 lines
3.5 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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
}
}
}