feat(monitors): 实现 C 阶段网络存储电池监控与三语详情
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
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<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? {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user