feat(power): 展示电池实际充放电功率并及时响应电源切换
保留电量百分比和连续趋势,按历史采样展示电池、适配器和系统功率。面板可见时读取电池实时功率,插拔电源后立即刷新并复读。
This commit is contained in:
@@ -3,22 +3,42 @@ import IOKit.ps
|
||||
|
||||
nonisolated struct BatteryMetrics: Sendable {
|
||||
let charge: Double?
|
||||
let charging: Bool
|
||||
let externalPower: Bool
|
||||
var power: Double? = nil
|
||||
var flow = BatteryPowerFlow()
|
||||
var minutesRemaining: Int?
|
||||
var cycles: Int?
|
||||
var health: Double?
|
||||
}
|
||||
|
||||
nonisolated enum BatteryMonitor {
|
||||
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 = abs(voltageMillivolts * amperageMilliamps) / 1_000_000
|
||||
return watts.isFinite && watts <= 500 ? watts : nil
|
||||
let watts = (voltageMillivolts * amperageMilliamps) / 1_000_000
|
||||
return watts.isFinite && abs(watts) <= 500 ? watts : nil
|
||||
}
|
||||
|
||||
static func positiveMinutes(_ value: Int?) -> Int? {
|
||||
@@ -44,7 +64,7 @@ nonisolated enum BatteryMonitor {
|
||||
return .absent
|
||||
}
|
||||
|
||||
static func sample() -> BatteryMetrics? {
|
||||
mutating func sample() -> BatteryMetrics? {
|
||||
guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(),
|
||||
let sources = IOPSCopyPowerSourcesList(info)?.takeRetainedValue() as? [CFTypeRef] else { return nil }
|
||||
for source in sources {
|
||||
@@ -53,36 +73,131 @@ nonisolated enum BatteryMonitor {
|
||||
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 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())
|
||||
}
|
||||
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
|
||||
let batteryData = properties["BatteryData"] as? [String: Any] ?? [:]
|
||||
let voltage = firstNumber([properties["Voltage"], batteryData["Voltage"], batteryData["AppleRawBatteryVoltage"]])
|
||||
let amperage = firstNumber([properties["InstantAmperage"], batteryData["InstantAmperage"], properties["Amperage"], batteryData["Amperage"]])
|
||||
return BatteryMetrics(charge: charge, charging: item[kIOPSIsChargingKey] as? Bool ?? false,
|
||||
externalPower: external,
|
||||
power: normalizedPower(voltageMillivolts: voltage, amperageMilliamps: amperage),
|
||||
minutesRemaining: estimatedMinutes(charging: charging, externalPower: external, 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 firstNumber(_ values: [Any?]) -> Double? {
|
||||
for case let value? in values {
|
||||
if let number = value as? NSNumber, number.doubleValue.isFinite {
|
||||
return number.doubleValue
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user