Files
cube/ios/CubeRemote/CubeAPI.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

182 lines
6.1 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.
/// Felder ab `allCategories` fehlen bei älterer Firmware und sind deshalb optional.
struct CubeState: Codable, Equatable {
var effect: String
var auto: Bool
/// automatisch zufällig durch alle Kategorien statt nur die laufende
var allCategories: Bool?
/// automatisch nur durch die Favoriten
var playFavorites: Bool?
/// manueller Modus: Pixel kommen per API (/api/pixels), kein Effekt läuft
var manual: Bool?
var brightness: Int
/// Effekt-ids, höchstens 12
var favorites: [String]?
/// Farbe der Lampe als "#rrggbb"
var lampColor: String?
/// Text der Laufschrift
var text: String?
/// Ort fürs Wetter, "" = keiner
var place: String?
var latitude: Double?
var longitude: Double?
}
/// Antwort von GET /api/weather; ohne Daten fehlen die Wetterfelder.
struct CubeWeather: Codable, Equatable {
var place: String
var temperature: Double?
var code: Int?
var isDay: Bool?
/// Sekunden seit dem Abruf
var age: Int?
}
/// Ein Treffer der Ortssuche (Open-Meteo Geocoding).
struct GeoPlace: Codable, Identifiable, Hashable {
let id: Int
let name: String
let latitude: Double
let longitude: Double
let admin1: String?
let country: String?
/// z. B. "Île-de-France, Frankreich"
var region: String {
[admin1, country].compactMap { $0 }.filter { $0 != name }.joined(separator: ", ")
}
}
/// Ein Eintrag aus GET /api/categories.
struct CubeCategory: Codable, Identifiable, Hashable {
let id: String
let name: String
}
/// Ein Eintrag aus GET /api/effects.
struct CubeEffect: Codable, Identifiable, Hashable {
let id: String
let name: String
/// `id` der Kategorie
let category: String
}
/// Änderung für PATCH /api/state – nur gesetzte Felder werden gesendet.
struct CubeStatePatch: Encodable {
var effect: String?
var auto: Bool?
var allCategories: Bool?
var playFavorites: Bool?
var brightness: Int?
var favorites: [String]?
var lampColor: String?
var text: String?
var place: String?
var latitude: Double?
var longitude: Double?
}
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 categories() async throws -> [CubeCategory] {
let data = try await request("categories")
return try JSONDecoder().decode([CubeCategory].self, from: data)
}
func effects() async throws -> [CubeEffect] {
let data = try await request("effects")
return try JSONDecoder().decode([CubeEffect].self, from: data)
}
func weather() async throws -> CubeWeather {
let data = try await request("weather")
return try JSONDecoder().decode(CubeWeather.self, from: data)
}
/// Orte suchen; läuft vom iPhone aus direkt bei Open-Meteo, nicht über den Würfel.
static func searchPlaces(_ name: String) async throws -> [GeoPlace] {
var components = URLComponents(string: "https://geocoding-api.open-meteo.com/v1/search")!
components.queryItems = [
URLQueryItem(name: "name", value: name),
URLQueryItem(name: "count", value: "5"),
URLQueryItem(name: "language", value: "de"),
URLQueryItem(name: "format", value: "json"),
]
struct Response: Decodable { let results: [GeoPlace]? }
let (data, _) = try await session.data(from: components.url!)
return try JSONDecoder().decode(Response.self, from: data).results ?? []
}
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
}
}
}