Created
October 20, 2024 16:33
-
-
Save helje5/06191b8e6cc5ece8dd33d41b06789a9f to your computer and use it in GitHub Desktop.
GridApp.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import Charts | |
// Required entitlement: | |
// <key>com.apple.security.network.client</key><true/> | |
enum Signal: Int { case red, yellow, green } | |
struct Value { | |
let date : Date | |
let percentage : Float | |
let signal : Signal? | |
} | |
struct ChartView: View { | |
let values : [ Value ] | |
let currentSignal : Signal? | |
var body: some View { | |
Chart { | |
LinePlot( | |
values, | |
x: .value("Date", \.date), | |
y: .value("Percentage", \.percentage) | |
) | |
} | |
.chartYScale(domain: 0.0...100.0) | |
} | |
} | |
struct ContentView: View { | |
@State var values = [ Value ]() | |
@State var currentValue : Value? | |
func fetchIt() async { | |
do { | |
let url = | |
URL(string: "https://api.energy-charts.info/signal?country=de")! | |
let (data,_) = try await URLSession.shared.data(from: url) | |
struct Result: Decodable { | |
var unix_seconds : [ Int ] // in 15min steps, starting at day | |
var share : [ Float ] // Anteil EE an Last | |
var signal : [ Int ] | |
} | |
let result = try JSONDecoder().decode(Result.self, from: data) | |
values = result.unix_seconds.enumerated().map { idx, ts in | |
Value(date: Date(timeIntervalSince1970: TimeInterval(ts)), | |
percentage: idx < result.share.count ? result.share[idx] : 0, | |
signal: idx < result.signal.count | |
? Signal(rawValue: result.signal[idx]) : nil) | |
} | |
let now = Date() | |
currentValue = values.firstIndex(where: { $0.date > now }) | |
.flatMap { $0 - 1 } | |
.flatMap { $0 >= 0 ? values[$0] : nil } | |
} | |
catch { currentValue = nil } | |
} | |
var body: some View { | |
VStack { | |
if let currentValue { | |
ChartView(values: values, currentSignal: currentValue.signal) | |
} | |
else { | |
Button("Retry") { Task { await fetchIt()} } | |
.foregroundStyle(.red) | |
} | |
} | |
.padding() | |
.task { | |
await fetchIt() | |
} | |
} | |
} | |
@main | |
struct GridApp: App { | |
var body: some Scene { | |
MenuBarExtra { | |
ContentView() | |
} | |
label: { | |
Label("Grid", systemImage: "chandelier") | |
} | |
.menuBarExtraStyle(.window) | |
} | |
} |
Author
helje5
commented
Oct 20, 2024

Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment