import Foundation /// Uses the System Information report's own maximum-capacity field. /// Slow-changing data is cached independently of the two-second resource samples. actor SystemBatteryHealthMonitor { private var cached: Double? private var nextRead: TimeInterval = 0 private var pending: Task? 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? { await withCheckedContinuation { continuation in // Process/pipe waits use a utility queue rather than the cooperative executor. DispatchQueue.global(qos: .utility).async { let process = Process() process.executableURL = URL(fileURLWithPath: "/usr/sbin/system_profiler") process.arguments = ["SPPowerDataType", "-json", "-detailLevel", "mini", "-timeout", "5"] let pipe = Pipe() process.standardOutput = pipe process.standardError = FileHandle.nullDevice do { try process.run() } catch { continuation.resume(returning: nil); return } let deadline = DispatchWorkItem { if process.isRunning { process.terminate() } } DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 10, execute: deadline) let data = pipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() deadline.cancel() continuation.resume(returning: process.terminationStatus == 0 && data.count <= 262_144 ? parse(data) : nil) } } } }