Files
Kymo/kymo/Core/Monitors/BatteryMonitor.swift
wangairnan 451d31682d fix(power): 完善电池卡片的共同供电判定、功率图标与预估续航
按适配器和电池的实际贡献判定共同供电,以双图标和双色柱展示两路功率。同步三语预估续航文案,在仅外接供电时隐藏估时行。
2026-11-16 15:06:02 +08:00

220 lines
12 KiB
Swift

import Foundation
import IOKit.ps
nonisolated struct BatteryMetrics: Sendable {
let charge: Double?
var flow = BatteryPowerFlow()
var minutesToFull: Int?
var minutesToEmpty: Int?
var minutesRemaining: Int? {
switch flow.state {
case .charging: minutesToFull
case .battery, .discharging, .combined: minutesToEmpty
case .external, .unknown: nil
}
}
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 isFresh(at: now)
}
func isFresh(at now: Date) -> Bool {
(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 { (1..<65535).contains($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 flow = powerFlow(properties, externalSupply: supply, charging: charging)
let systemMinutes = Self.estimatedMinutes(charging: false, externalPower: supply != false,
sourceMinutes: item[kIOPSTimeToEmptyKey] as? Int, systemSeconds: IOPSGetTimeRemainingEstimate())
let now = Date()
let recentPack = Self.packIsRecent(properties, at: now)
let packMinutes = recentPack && packStamp.isFresh(at: now) ? Self.positiveMinutes(properties["AvgTimeToEmpty"] as? Int) : nil
return BatteryMetrics(charge: charge, flow: flow,
minutesToFull: charging == true ? Self.positiveMinutes(item[kIOPSTimeToFullChargeKey] as? Int) : nil,
minutesToEmpty: systemMinutes ?? packMinutes,
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 packIsRecent(_ properties: [String: Any], at now: Date) -> Bool {
scalar(properties["UpdateTime"]).map { (0...120).contains(now.timeIntervalSince1970 - $0) } ?? true
}
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 recent = Self.packIsRecent(properties, at: now)
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
}
}