204 lines
11 KiB
Swift
204 lines
11 KiB
Swift
import Foundation
|
|
import IOKit.ps
|
|
|
|
nonisolated struct BatteryMetrics: Sendable {
|
|
let charge: Double?
|
|
var flow = BatteryPowerFlow()
|
|
var minutesRemaining: Int?
|
|
var cycles: Int?
|
|
var health: Double?
|
|
}
|
|
|
|
nonisolated struct BatteryMonitor {
|
|
// The controller publishes less frequently than the panel. After a source change or
|
|
// wake, wait for each register group to advance before using it again.
|
|
private struct Freshness {
|
|
var stamp: [NSNumber?]?
|
|
var updated = Date.distantPast
|
|
|
|
mutating func accepts(_ next: [NSNumber?], at now: Date, invalidate: Bool) -> Bool {
|
|
if next != stamp { updated = now; stamp = next }
|
|
else if invalidate { updated = .distantPast }
|
|
return (0...120).contains(now.timeIntervalSince(updated))
|
|
}
|
|
}
|
|
|
|
private var telemetryStamp = Freshness()
|
|
private var packStamp = Freshness()
|
|
private var previousConnection: Bool?
|
|
private var previousSupply: Bool?
|
|
private var sampled = false
|
|
private var invalidated = false
|
|
|
|
mutating func invalidate() { invalidated = true }
|
|
|
|
static func normalizedPower(voltageMillivolts: Double?, amperageMilliamps: Double?) -> Double? {
|
|
guard let voltageMillivolts, let amperageMilliamps,
|
|
voltageMillivolts.isFinite, amperageMilliamps.isFinite,
|
|
voltageMillivolts > 0, voltageMillivolts <= 30_000,
|
|
abs(amperageMilliamps) <= 20_000 else { return nil }
|
|
let watts = (voltageMillivolts * amperageMilliamps) / 1_000_000
|
|
return watts.isFinite && abs(watts) <= 500 ? watts : nil
|
|
}
|
|
|
|
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 availability() -> BatteryAvailability {
|
|
guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(),
|
|
let sources = IOPSCopyPowerSourcesList(info)?.takeRetainedValue() as? [CFTypeRef] else { return .failed }
|
|
for source in sources {
|
|
guard let item = IOPSGetPowerSourceDescription(info, source)?.takeUnretainedValue() as? [String: Any] else { return .failed }
|
|
if item[kIOPSTypeKey] as? String == kIOPSInternalBatteryType { return .present }
|
|
}
|
|
return .absent
|
|
}
|
|
|
|
mutating 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 properties = Self.registryProperties() ?? [:]
|
|
let state = item[kIOPSPowerSourceStateKey] as? String
|
|
let supply: Bool? = state == kIOPSACPowerValue ? true : state == kIOPSBatteryPowerValue ? false : nil
|
|
let charging = item[kIOPSIsChargingKey] as? Bool
|
|
let minutes = charging == true ? item[kIOPSTimeToFullChargeKey] as? Int : item[kIOPSTimeToEmptyKey] as? Int
|
|
var estimate: Int?
|
|
if let supply, let charging {
|
|
estimate = Self.estimatedMinutes(charging: charging, externalPower: supply, sourceMinutes: minutes,
|
|
systemSeconds: IOPSGetTimeRemainingEstimate())
|
|
}
|
|
return BatteryMetrics(charge: charge, flow: powerFlow(properties, externalSupply: supply, charging: charging),
|
|
minutesRemaining: estimate,
|
|
cycles: (properties["CycleCount"] as? Int).flatMap { $0 >= 0 ? $0 : nil })
|
|
}
|
|
return nil
|
|
}
|
|
|
|
private static func registryProperties() -> [String: Any]? {
|
|
let service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSmartBattery"))
|
|
guard service != 0 else { return nil }
|
|
defer { IOObjectRelease(service) }
|
|
var raw: Unmanaged<CFMutableDictionary>?
|
|
guard IORegistryEntryCreateCFProperties(service, &raw, kCFAllocatorDefault, 0) == KERN_SUCCESS else { return nil }
|
|
return raw?.takeRetainedValue() as? [String: Any]
|
|
}
|
|
|
|
/// A machine without a pack can still publish an independent DC input reading.
|
|
mutating func desktopInput() -> Double? {
|
|
guard let properties = Self.registryProperties() else { return nil }
|
|
let input = powerFlow(properties, externalSupply: true).input
|
|
return input?.source == .telemetry ? input?.watts : nil
|
|
}
|
|
|
|
private static func scalar(_ raw: Any?) -> Double? {
|
|
guard let number = raw as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(),
|
|
number.doubleValue.isFinite else { return nil }
|
|
return number.doubleValue
|
|
}
|
|
|
|
/// IORegistry can expose signed telemetry as an unsigned 32- or 64-bit register.
|
|
private static func signed(_ raw: Any?, limit: Double) -> Double? {
|
|
guard let number = raw as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() else { return nil }
|
|
var value = number.doubleValue
|
|
if value > limit, !CFNumberIsFloatType(number) {
|
|
let bits = number.uint64Value
|
|
if bits <= UInt32.max { value = Double(Int32(bitPattern: UInt32(bits))) }
|
|
else { value = Double(Int64(bitPattern: bits)) }
|
|
}
|
|
return value.isFinite && abs(value) <= limit ? value : nil
|
|
}
|
|
|
|
mutating func powerFlow(_ properties: [String: Any], externalSupply: Bool?, charging: Bool? = nil, now: Date = Date()) -> BatteryPowerFlow {
|
|
let connected = properties["ExternalConnected"] as? Bool ?? (externalSupply == true ? true : nil)
|
|
let changed = invalidated || (sampled && (previousConnection != connected || previousSupply != externalSupply))
|
|
previousConnection = connected
|
|
previousSupply = externalSupply
|
|
sampled = true
|
|
invalidated = false
|
|
let telemetry = properties["PowerTelemetryData"] as? [String: Any] ?? [:]
|
|
let pack = properties["BatteryData"] as? [String: Any] ?? [:]
|
|
let adapter = properties["AdapterDetails"] as? [String: Any]
|
|
var flow = BatteryPowerFlow(connected: connected, externalSupply: externalSupply, charging: charging ?? properties["IsCharging"] as? Bool)
|
|
if connected != false, let capacity = Self.scalar(adapter?["Watts"]), (0.1...500).contains(capacity) {
|
|
flow.adapterCapacity = capacity
|
|
}
|
|
|
|
// IORegistry can observe physical disconnection before IOPowerSources catches up.
|
|
if connected == false { flow.externalSupply = false; flow.charging = false }
|
|
let packDate = Self.scalar(properties["UpdateTime"])
|
|
let recent = packDate.map { (0...120).contains(now.timeIntervalSince1970 - $0) } ?? true
|
|
let voltage = properties["Voltage"] ?? pack["Voltage"] ?? pack["AppleRawBatteryVoltage"]
|
|
let instant = properties["InstantAmperage"] ?? pack["InstantAmperage"]
|
|
let average = properties["Amperage"] ?? pack["Amperage"]
|
|
let packFresh = packStamp.accepts([properties["UpdateTime"], voltage, instant, average].map { $0 as? NSNumber }, at: now, invalidate: changed)
|
|
let counters = ["SystemLoadAccumulatorCount", "SystemPowerInAccumulatorCount", "SystemPowerIn",
|
|
"BatteryPower", "SystemLoad", "SystemVoltageIn", "SystemCurrentIn"]
|
|
let telemetryFresh = telemetryStamp.accepts(counters.map { telemetry[$0] as? NSNumber }, at: now, invalidate: changed)
|
|
let disconnected = connected == false
|
|
func compatible(_ watts: Double) -> Bool { watts <= 0 || (!disconnected && externalSupply != false) }
|
|
|
|
if packFresh && recent {
|
|
for (raw, source) in [(instant, PowerReading.Source.instantaneous), (average, .average)] {
|
|
if let watts = Self.normalizedPower(voltageMillivolts: Self.scalar(voltage),
|
|
amperageMilliamps: Self.signed(raw, limit: 20_000)), compatible(watts) {
|
|
flow.battery = PowerReading(watts: watts, source: source)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
if disconnected { flow.input = PowerReading(watts: 0) }
|
|
guard telemetryFresh, recent else { return flow }
|
|
func measured(_ key: String) -> Double? {
|
|
guard let value = Self.scalar(telemetry[key]), (0...500_000).contains(value) else { return nil }
|
|
return value / 1000
|
|
}
|
|
var input = measured("SystemPowerIn")
|
|
if input == nil, let mv = Self.scalar(telemetry["SystemVoltageIn"]), (1...50_000).contains(mv),
|
|
let ma = Self.scalar(telemetry["SystemCurrentIn"]), (0...10_000).contains(ma) {
|
|
input = mv * ma / 1_000_000
|
|
}
|
|
// A positive adapter reading after unplugging belongs to the previous supply.
|
|
if disconnected && (input ?? 0) > 0 { return flow }
|
|
if !disconnected { flow.input = input.map { PowerReading(watts: $0) } }
|
|
flow.load = measured("SystemLoad").map { PowerReading(watts: $0) }
|
|
if let mw = Self.signed(telemetry["BatteryPower"], limit: 500_000), compatible(mw / 1000) {
|
|
let watts = mw / 1000
|
|
// Some controllers retain zero/old-direction battery telemetry while the
|
|
// pack already reports discharge. Prefer the instantaneous pack in that case.
|
|
if let pack = flow.battery, pack.source == .instantaneous {
|
|
if abs(pack.watts) >= 0.05 && watts * pack.watts <= 0 { return flow }
|
|
if watts > 0 && pack.watts == 0 && flow.charging == false { return flow }
|
|
}
|
|
flow.battery = PowerReading(watts: watts)
|
|
}
|
|
if flow.battery == nil, connected != nil || externalSupply != nil, let input = flow.input, let load = flow.load, compatible(input.watts - load.watts) {
|
|
flow.battery = PowerReading(watts: input.watts - load.watts, source: .balance)
|
|
} else if let battery = flow.battery, battery.source == .telemetry {
|
|
// Reverse estimates use only quantities published in the same telemetry group.
|
|
if flow.load == nil, let input = flow.input, (0...500).contains(input.watts - battery.watts) {
|
|
flow.load = PowerReading(watts: input.watts - battery.watts, source: .balance)
|
|
} else if flow.input == nil, connected == true, let load = flow.load, (0...500).contains(load.watts + battery.watts) {
|
|
flow.input = PowerReading(watts: load.watts + battery.watts, source: .balance)
|
|
}
|
|
}
|
|
return flow
|
|
}
|
|
}
|