fix(power): 完善电池卡片的共同供电判定、功率图标与预估续航

按适配器和电池的实际贡献判定共同供电,以双图标和双色柱展示两路功率。同步三语预估续航文案,在仅外接供电时隐藏估时行。
This commit is contained in:
2026-11-16 15:06:02 +08:00
parent ae448bce5c
commit 451d31682d
16 changed files with 262 additions and 147 deletions
+41 -2
View File
@@ -15,9 +15,44 @@ nonisolated struct BatteryPowerFlow: Sendable {
var load: PowerReading?
var adapterCapacity: Double?
struct JointSupply: Sendable {
let adapter: PowerReading
let discharge: PowerReading
var batteryFraction: Double { discharge.watts / (adapter.watts + discharge.watts) }
}
// Classification floor in watts, separate from the resolution of the displayed readings.
private static let minimumContribution = 0.5
private(set) var registryJointSupply: JointSupply?
var jointSupply: JointSupply? {
guard connected == true, let battery,
battery.watts <= -Self.minimumContribution else { return nil }
if battery.source == .smc { return registryJointSupply }
guard let input, input.watts >= Self.minimumContribution else { return nil }
// IOPS reports a single primary source. Override its battery-only indication
// only if all three direct telemetry channels independently support the split.
if externalSupply == false &&
(input.source != .telemetry || battery.source != .telemetry || load?.source != .telemetry) { return nil }
let discharge: PowerReading
if battery.source == .telemetry || battery.source == .balance {
discharge = PowerReading(watts: -battery.watts, source: battery.source)
} else if let load, load.source == .telemetry, input.source == .telemetry {
discharge = PowerReading(watts: load.watts - input.watts, source: .balance)
} else { return nil }
guard discharge.watts >= Self.minimumContribution else { return nil }
if let load, load.source == .telemetry, input.source == .telemetry {
// Reject conflicting measured channels rather than normalize an unexplained excess.
let residual = abs(input.watts + discharge.watts - load.watts)
guard residual <= max(1, 0.1 * load.watts) else { return nil }
}
return JointSupply(adapter: input, discharge: discharge)
}
mutating func applyBatterySensor(_ watts: Double) {
// The gauge may still report the last charging sample just after unplugging.
guard watts <= 0 || (externalSupply != false && connected != false) else { return }
if battery?.source != .smc { registryJointSupply = jointSupply }
battery = PowerReading(watts: watts, source: .smc)
// Estimates made from older registry measurements no longer share a sampling window.
if load?.source == .balance { load = nil }
@@ -37,8 +72,12 @@ nonisolated struct BatteryPowerFlow: Sendable {
let threshold = battery.source == .balance ? 0.5 : 0.05
if battery.watts >= threshold { return .charging }
if battery.watts <= -threshold {
if connected == true, let input, input.source != .balance, input.watts >= 0.05 { return .combined }
if connected == false || externalSupply == false || input?.watts == 0 { return .battery }
if jointSupply != nil { return .combined }
if connected == false || externalSupply == false { return .battery }
if let input, input.source != .balance {
if input.watts < Self.minimumContribution { return .battery }
if battery.watts > -Self.minimumContribution { return .external }
}
return .discharging
}
}
+29 -13
View File
@@ -4,7 +4,15 @@ import IOKit.ps
nonisolated struct BatteryMetrics: Sendable {
let charge: Double?
var flow = BatteryPowerFlow()
var minutesRemaining: Int?
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?
}
@@ -19,7 +27,11 @@ nonisolated struct BatteryMonitor {
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))
return isFresh(at: now)
}
func isFresh(at now: Date) -> Bool {
(0...120).contains(now.timeIntervalSince(updated))
}
}
@@ -42,7 +54,7 @@ nonisolated struct BatteryMonitor {
}
static func positiveMinutes(_ value: Int?) -> Int? {
value.flatMap { $0 > 0 ? $0 : nil }
value.flatMap { (1..<65535).contains($0) ? $0 : nil }
}
static func estimatedMinutes(charging: Bool, externalPower: Bool, sourceMinutes: Int?, systemSeconds: Double) -> Int? {
@@ -77,14 +89,15 @@ nonisolated struct BatteryMonitor {
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,
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
@@ -106,6 +119,10 @@ nonisolated struct BatteryMonitor {
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 }
@@ -141,8 +158,7 @@ nonisolated struct BatteryMonitor {
// 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 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"]