Files
cube/ios/CubeRemote/CubeModel.swift
T
mikeandClaude Opus 5.5 ffac7d6ff2 Manueller Modus: einzelne Pixel per API setzen (/api/pixels)
- PUT /api/pixels: alle 125 Pixel, Index x + 5*y + 25*z
- PATCH /api/pixels: optional fill, dann einzelne Pixel mit x, y, z
- GET /api/pixels: aktuelles Bild
- Schreiben schaltet den manuellen Modus ein: Farben unverändert (nur die
  Strombegrenzung dimmt), kein Autowechsel, keine Klatsch-Blitze; ein
  Effektstart oder {"manual": false} in /api/state beendet ihn
- Nicht im Flash gespeichert, damit Skripte viele Bilder schicken können
- App zeigt den manuellen Modus in der Statuszeile

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:56:23 +01:00

202 lines
6.7 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
import Observation
import SwiftUI
/// 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
categories = []
effects = []
shownCategory = nil
error = nil
}
}
private(set) var state: CubeState?
private(set) var categories: [CubeCategory] = []
private(set) var effects: [CubeEffect] = []
private(set) var error: String?
private(set) var weather: CubeWeather?
/// Kennung der Favoriten in der Kategorie-Spalte (keine Kategorie der Firmware)
static let favoritesID = "favoriten"
static let maxFavorites = 12
/// In der App gewählte Kategorie; anfangs die des laufenden Effekts.
var shownCategory: String?
/// Kategorie des Effekts, der gerade auf dem Würfel läuft – oder die Favoriten,
/// wenn der Würfel durch sie wechselt
var runningCategory: String? {
guard let state, state.manual != true else { return nil }
if state.playFavorites == true && !favorites.isEmpty { return Self.favoritesID }
return effects.first { $0.id == state.effect }?.category
}
/// Favoriten in ihrer Reihenfolge
var favorites: [CubeEffect] {
(state?.favorites ?? []).compactMap { id in effects.first { $0.id == id } }
}
func isFavorite(_ effect: CubeEffect) -> Bool {
state?.favorites?.contains(effect.id) ?? false
}
/// 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 {
categories = try await api.categories()
effects = try await api.effects()
}
apply(try await api.state())
} catch {
self.error = error.localizedDescription
}
}
/// Aus den Favoriten gestartet, wechselt der Würfel danach nur durch die Favoriten.
func select(_ effect: CubeEffect, fromFavorites: Bool) async {
await update(fromFavorites
? CubeStatePatch(effect: effect.id, allCategories: false, playFavorites: true)
: CubeStatePatch(effect: effect.id, playFavorites: false))
}
func toggleFavorite(_ effect: CubeEffect) async {
var ids = state?.favorites ?? []
if let i = ids.firstIndex(of: effect.id) {
ids.remove(at: i)
} else if ids.count < Self.maxFavorites {
ids.append(effect.id)
}
await update(CubeStatePatch(favorites: ids))
}
func setAuto(_ on: Bool) async {
await update(CubeStatePatch(auto: on))
}
func setAllCategories(_ on: Bool) async {
await update(on ? CubeStatePatch(allCategories: true, playFavorites: false) : CubeStatePatch(allCategories: false))
}
private var lampTask: Task<Void, Never>?
/// Neue Farbe für die Lampe und die Lampe einschalten; beim Ziehen im
/// Farbwähler wird nur alle 0,15 s gesendet.
func setLampColor(_ color: Color) {
lampTask?.cancel()
lampTask = Task {
try? await Task.sleep(for: .milliseconds(150))
guard !Task.isCancelled else { return }
await update(CubeStatePatch(effect: "lampe", lampColor: color.hexString))
}
}
func setText(_ text: String) async {
await update(CubeStatePatch(effect: "laufschrift", text: text))
}
/// Ort fürs Wetter setzen (nil = entfernen) und das Wetter zeigen
func setPlace(_ place: GeoPlace?) async {
if let place {
await update(CubeStatePatch(effect: "wetter", place: Self.shortened(place.name, bytes: 47),
latitude: place.latitude, longitude: place.longitude))
} else {
await update(CubeStatePatch(place: ""))
}
weather = nil
}
func loadWeather() async {
weather = try? await api.weather()
}
/// Kürzt einen Text auf höchstens so viele UTF-8-Bytes (Grenze der Firmware).
static func shortened(_ text: String, bytes: Int) -> String {
var result = ""
for character in text where result.utf8.count + String(character).utf8.count <= bytes {
result.append(character)
}
return result
}
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) }
if shownCategory == nil { shownCategory = runningCategory }
}
/// 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
}
}
extension Color {
/// "#rrggbb" -> Farbe
init?(hex: String?) {
guard let hex, hex.count == 7, hex.hasPrefix("#"), let v = Int(hex.dropFirst(), radix: 16) else { return nil }
self.init(red: Double(v >> 16 & 0xFF) / 255, green: Double(v >> 8 & 0xFF) / 255, blue: Double(v & 0xFF) / 255)
}
/// Farbe -> "#rrggbb"
var hexString: String {
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
UIColor(self).getRed(&r, green: &g, blue: &b, alpha: &a)
func byte(_ c: CGFloat) -> Int { Int((min(max(c, 0), 1) * 255).rounded()) }
return String(format: "#%02x%02x%02x", byte(r), byte(g), byte(b))
}
}