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
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