41 lines
1.9 KiB
Swift
41 lines
1.9 KiB
Swift
import Foundation
|
|
|
|
/// Uses the System Information report's own maximum-capacity field.
|
|
/// Slow-changing data has its own cache, independent of the configurable resource interval.
|
|
actor SystemBatteryHealthMonitor {
|
|
private var cached: Double?
|
|
private var nextRead: TimeInterval = 0
|
|
private var pending: Task<Double?, Never>?
|
|
|
|
func sample() async -> Double? {
|
|
if let pending { return await pending.value }
|
|
guard ProcessInfo.processInfo.systemUptime >= nextRead else { return cached }
|
|
let task = Task { await Self.readReport() }
|
|
pending = task
|
|
cached = await task.value
|
|
pending = nil
|
|
nextRead = ProcessInfo.processInfo.systemUptime + (cached == nil ? 600 : 3600)
|
|
return cached
|
|
}
|
|
|
|
nonisolated static func parse(_ data: Data) -> Double? {
|
|
guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
let reports = root["SPPowerDataType"] as? [[String: Any]] else { return nil }
|
|
for report in reports {
|
|
guard let health = report["sppower_battery_health_info"] as? [String: Any],
|
|
let text = health["sppower_battery_health_maximum_capacity"] as? String,
|
|
text.trimmingCharacters(in: .whitespacesAndNewlines).hasSuffix("%"),
|
|
let percent = Double(text.trimmingCharacters(in: .whitespacesAndNewlines).dropLast().trimmingCharacters(in: .whitespaces)),
|
|
percent.isFinite, (0...100).contains(percent) else { continue }
|
|
return percent / 100
|
|
}
|
|
return nil
|
|
}
|
|
|
|
nonisolated private static func readReport() async -> Double? {
|
|
guard let data = await BoundedProcess.read(executable: URL(fileURLWithPath: "/usr/sbin/system_profiler"),
|
|
arguments: ["SPPowerDataType", "-json", "-detailLevel", "mini", "-timeout", "5"]) else { return nil }
|
|
return parse(data)
|
|
}
|
|
}
|