55 lines
2.9 KiB
Swift
55 lines
2.9 KiB
Swift
import Foundation
|
|
import IOKit.ps
|
|
|
|
nonisolated struct BatteryMetrics: Sendable {
|
|
let charge: Double?
|
|
let charging: Bool
|
|
let externalPower: Bool
|
|
var minutesRemaining: Int?
|
|
var cycles: Int?
|
|
var health: Double?
|
|
}
|
|
|
|
nonisolated enum BatteryMonitor {
|
|
static func positiveMinutes(_ value: Int?) -> Int? {
|
|
value.flatMap { $0 > 0 ? $0 : nil }
|
|
}
|
|
|
|
static func estimatedMinutes(charging: Bool, externalPower: Bool, sourceMinutes: Int?, systemSeconds: Double) -> Int? {
|
|
guard charging || !externalPower else { return nil }
|
|
if let minutes = positiveMinutes(sourceMinutes) { return minutes }
|
|
// The global estimate applies to discharge only and reports seconds.
|
|
guard !charging, !externalPower, systemSeconds.isFinite,
|
|
systemSeconds > 0, systemSeconds < Double(Int.max) else { return nil }
|
|
return max(1, Int((systemSeconds / 60).rounded(.up)))
|
|
}
|
|
|
|
static func sample() -> BatteryMetrics? {
|
|
guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(),
|
|
let sources = IOPSCopyPowerSourcesList(info)?.takeRetainedValue() as? [CFTypeRef] else { return nil }
|
|
for source in sources {
|
|
guard let item = IOPSGetPowerSourceDescription(info, source)?.takeUnretainedValue() as? [String: Any],
|
|
item[kIOPSTypeKey] as? String == kIOPSInternalBatteryType else { continue }
|
|
let current = item[kIOPSCurrentCapacityKey] as? Double
|
|
let maximum = item[kIOPSMaxCapacityKey] as? Double
|
|
let charge = current.flatMap { c in maximum.flatMap { $0 > 0 ? min(1, max(0, c / $0)) : nil } }
|
|
let service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSmartBattery"))
|
|
var properties: [String: Any] = [:]
|
|
if service != 0 {
|
|
defer { IOObjectRelease(service) }
|
|
var raw: Unmanaged<CFMutableDictionary>?
|
|
if IORegistryEntryCreateCFProperties(service, &raw, kCFAllocatorDefault, 0) == KERN_SUCCESS {
|
|
properties = raw?.takeRetainedValue() as? [String: Any] ?? [:]
|
|
}
|
|
}
|
|
let charging = item[kIOPSIsChargingKey] as? Bool ?? false
|
|
let external = item[kIOPSPowerSourceStateKey] as? String == kIOPSACPowerValue
|
|
let minutes = charging ? item[kIOPSTimeToFullChargeKey] as? Int : external ? nil : item[kIOPSTimeToEmptyKey] as? Int
|
|
return BatteryMetrics(charge: charge, charging: item[kIOPSIsChargingKey] as? Bool ?? false,
|
|
externalPower: external, minutesRemaining: estimatedMinutes(charging: charging, externalPower: external, sourceMinutes: minutes, systemSeconds: IOPSGetTimeRemainingEstimate()),
|
|
cycles: (properties["CycleCount"] as? Int).flatMap { $0 >= 0 ? $0 : nil })
|
|
}
|
|
return nil
|
|
}
|
|
}
|