feat(power): 展示电池实际充放电功率并及时响应电源切换
保留电量百分比和连续趋势,按历史采样展示电池、适配器和系统功率。面板可见时读取电池实时功率,插拔电源后立即刷新并复读。
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
import Foundation
|
||||
|
||||
@main struct BatteryPowerChecks {
|
||||
static func main() {
|
||||
func read(_ telemetry: [String: Any], extra: [String: Any] = [:], connected: Bool = true) -> BatteryPowerFlow {
|
||||
var monitor = BatteryMonitor()
|
||||
var raw = extra
|
||||
raw["ExternalConnected"] = connected
|
||||
raw["PowerTelemetryData"] = telemetry
|
||||
return monitor.powerFlow(raw, externalSupply: connected)
|
||||
}
|
||||
let adapter = ["AdapterDetails": ["Watts": 65]]
|
||||
let charging = read(["BatteryPower": 6_000], extra: adapter)
|
||||
precondition(charging.battery == PowerReading(watts: 6) && charging.state == .charging)
|
||||
precondition(charging.adapterCapacity == 65 && charging.input == nil)
|
||||
precondition(read([:], extra: adapter).battery == nil)
|
||||
let combined = read(["BatteryPower": NSNumber(value: UInt64(bitPattern: -8000)), "SystemPowerIn": 30_000])
|
||||
precondition(combined.battery?.watts == -8 && combined.state == .combined)
|
||||
precondition(combined.load == PowerReading(watts: 38, source: .balance))
|
||||
let staleCharge = read(["BatteryPower": 6_000], extra: ["Voltage": 12_000, "InstantAmperage": 0, "IsCharging": false])
|
||||
precondition(staleCharge.battery?.watts == 0 && staleCharge.state == .external)
|
||||
let unknownWatts = read([:], extra: ["IsCharging": true])
|
||||
precondition(unknownWatts.battery == nil && unknownWatts.state == .charging)
|
||||
let idle = read(["SystemPowerIn": 17_453, "BatteryPower": 0])
|
||||
precondition(idle.battery?.watts == 0 && idle.state == .external)
|
||||
let estimated = read(["SystemPowerIn": 65_000, "SystemLoad": 59_000])
|
||||
precondition(estimated.battery == PowerReading(watts: 6, source: .balance))
|
||||
precondition(read(["SystemPowerIn": 30_000, "SystemLoad": 38_000]).state == .combined)
|
||||
precondition(read(["SystemPowerIn": 30_000, "SystemLoad": 30_200]).state == .external)
|
||||
precondition(read(["BatteryPower": 6_000, "SystemLoad": 0]).input == PowerReading(watts: 6, source: .balance))
|
||||
precondition(read(["SystemVoltageIn": 20_000, "SystemCurrentIn": 300]).input?.watts == 6)
|
||||
let pack = ["Voltage": NSNumber(value: 12_000), "InstantAmperage": NSNumber(value: UInt32(bitPattern: -1500))]
|
||||
let discharge = read(["SystemPowerIn": 0, "BatteryPower": 0], extra: pack, connected: false)
|
||||
precondition(discharge.battery == PowerReading(watts: -18, source: .instantaneous) && discharge.state == .battery)
|
||||
let unplugged = read(["SystemLoad": 18_000], connected: false)
|
||||
precondition(unplugged.battery == PowerReading(watts: -18, source: .balance))
|
||||
precondition(read(["SystemLoad": 18_000, "SystemPowerIn": 17_000], connected: false).battery == nil)
|
||||
precondition(read(["BatteryPower": Double.nan]).battery == nil)
|
||||
precondition(read(["BatteryPower": NSNumber(value: true)]).battery == nil)
|
||||
precondition(read([:], extra: ["Voltage": 12_000, "Amperage": -1000]).battery == PowerReading(watts: -12, source: .average))
|
||||
precondition(MetricFormat.signedWatts(-0.02) == "0 W" && MetricFormat.signedWatts(6) == "+6.0 W")
|
||||
precondition(MetricFormat.signedWatts(-18) == "−18.0 W" && MetricFormat.signedWatts(nil) == "--")
|
||||
|
||||
var monitor = BatteryMonitor()
|
||||
let now = Date()
|
||||
var raw: [String: Any] = ["ExternalConnected": true, "PowerTelemetryData": ["BatteryPower": 6_000]]
|
||||
precondition(monitor.powerFlow(raw, externalSupply: true, now: now).battery?.watts == 6)
|
||||
monitor.invalidate()
|
||||
precondition(monitor.powerFlow(raw, externalSupply: true, now: now).battery == nil)
|
||||
raw["ExternalConnected"] = false
|
||||
precondition(monitor.powerFlow(raw, externalSupply: false, now: now).battery == nil)
|
||||
raw["PowerTelemetryData"] = ["BatteryPower": -18_000]
|
||||
precondition(monitor.powerFlow(raw, externalSupply: false, now: now).battery?.watts == -18)
|
||||
precondition(monitor.powerFlow(raw, externalSupply: false, now: now.addingTimeInterval(121)).battery == nil)
|
||||
// Physical disconnection can precede an IOPS update, while both cached power registers still show AC.
|
||||
let unplug = monitor.powerFlow(["ExternalConnected": false, "PowerTelemetryData": ["SystemPowerIn": 30_000, "BatteryPower": 6_000]], externalSupply: true)
|
||||
precondition(unplug.state == .battery && unplug.battery == nil)
|
||||
var live = unplug
|
||||
live.applyBatterySensor(6)
|
||||
precondition(live.battery == nil)
|
||||
live.applyBatterySensor(-12.6)
|
||||
precondition(live.battery == PowerReading(watts: -12.6, source: .smc) && live.state == .battery)
|
||||
let delayedRegistry = BatteryPowerFlow(connected: true, externalSupply: false, charging: true, input: PowerReading(watts: 20))
|
||||
precondition(delayedRegistry.state == .battery)
|
||||
var joint = combined
|
||||
joint.applyBatterySensor(-10)
|
||||
precondition(joint.battery?.watts == -10 && joint.state == .combined && joint.load == nil)
|
||||
print("PASS: signed battery watts, adapter limits, joint supply, measured and derived values, stale telemetry")
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import Foundation
|
||||
precondition(!CPUTemperatureMonitor.isHighTemperature(nil))
|
||||
precondition(!CPUTemperatureMonitor.isHighTemperature(89.9))
|
||||
precondition(CPUTemperatureMonitor.isHighTemperature(90))
|
||||
precondition(CPUTemperatureMonitor.decodeSensorNumber(type: 0x73693332, bytes: [0x80, 0xc1, 0xff, 0xff]) == -16_000)
|
||||
precondition(CPUTemperatureMonitor.decodeSensorNumber(type: 0x73693332, bytes: [0x70, 0x17, 0, 0]) == 6_000)
|
||||
if let temperature = CPUTemperatureMonitor().sample() {
|
||||
precondition(temperature > 0 && temperature < 150)
|
||||
}
|
||||
|
||||
@@ -19,6 +19,16 @@ import QuartzCore
|
||||
func input(_ values: [Double?]) -> NativePanelCurve.Input {
|
||||
NativePanelCurve.Input(frame: PanelCurveFrame(dates: dates, series: [values], intervals: [2,2,2,2], boundaryDates: []), colors: [.red], scales: [1], maximumGap: 5)
|
||||
}
|
||||
var signed = input([-1, 0, 0.5, 1])
|
||||
signed.projection = .signed
|
||||
signed.hoveredIndex = 0
|
||||
plot.configure(signed)
|
||||
let dischargeDot = plot.layer!.sublayers!.last as! CAShapeLayer
|
||||
precondition(dischargeDot.path!.boundingBoxOfPath.midY == 60)
|
||||
precondition(plot.baseline.path!.boundingBoxOfPath.midY == 30)
|
||||
signed.hoveredIndex = 3
|
||||
plot.configure(signed)
|
||||
precondition(dischargeDot.path!.boundingBoxOfPath.midY == 0)
|
||||
let continuous = input([0.8,0.8,0.8,0.8])
|
||||
plot.configure(continuous)
|
||||
let image = bitmap(plot)
|
||||
|
||||
@@ -24,6 +24,9 @@ import Darwin
|
||||
print("FAIL: hardened sandbox to packaged XPC sensor RPC"); exit(1)
|
||||
}
|
||||
print("PASS: hardened sandbox host authenticates packaged XPC; footprint, CPU energy and sensor RPCs")
|
||||
let battery = await CPUTemperatureServiceClient.readBatteryPower()
|
||||
precondition(battery.map { abs($0) <= 500 } ?? true)
|
||||
print("Live battery gauge (W):", battery.map(String.init(describing:)) ?? "unavailable")
|
||||
let power = await CPUTemperatureServiceClient.readSystemPower()
|
||||
print("System-total sensor (W):", power.map(String.init(describing:)) ?? "unavailable")
|
||||
print("Sensor coverage: CPU=\(sensors.cpu != nil), GPU=\(sensors.gpu != nil), fans=\(sensors.fans?.count ?? 0)")
|
||||
|
||||
@@ -59,20 +59,34 @@ import SwiftUI
|
||||
var sample = MetricsSnapshot()
|
||||
sample.batteryState = state
|
||||
sample.systemPower = state == .absent ? 32.5 : nil
|
||||
if state == .present { sample.battery = BatteryMetrics(charge: 0.8, charging: false, externalPower: true, power: 0) }
|
||||
if state == .present { sample.battery = BatteryMetrics(charge: 0.77, flow: BatteryPowerFlow(connected: true, externalSupply: true, battery: PowerReading(watts: 0))) }
|
||||
var history = MetricHistory()
|
||||
history.append(sample)
|
||||
sample.date = sample.date.addingTimeInterval(2); sample.systemPower = nil
|
||||
sample.battery?.flow = BatteryPowerFlow(connected: false, externalSupply: false, battery: PowerReading(watts: -18))
|
||||
history.append(sample)
|
||||
if state == .present {
|
||||
sample.date = sample.date.addingTimeInterval(2)
|
||||
sample.battery?.flow = BatteryPowerFlow(connected: true, externalSupply: true, battery: PowerReading(watts: 34.8))
|
||||
history.append(sample)
|
||||
}
|
||||
host.rootView = AnyView(PowerResourceCard(snapshot: sample, samples: history.samples,
|
||||
chartInterval: 2, chartBoundaries: [], chartIntervals: [2,2]))
|
||||
chartInterval: 2, chartBoundaries: [], chartIntervals: history.samples.map(\.expectedInterval)))
|
||||
try? await Task.sleep(for: .milliseconds(80)); host.layoutSubtreeIfNeeded()
|
||||
let plot = descendants(host).compactMap { $0 as? NativePanelCurve.PlotView }.first!
|
||||
let first = plot.input?.frame.series.first
|
||||
switch state {
|
||||
case .absent: precondition(first == [32.5, nil] && plot.input?.scales.first == 32.5)
|
||||
case .present: precondition(first == [0.8, 0.8] && plot.input?.scales.first == 1 && topRect(plot, in: host) == host.bounds)
|
||||
default: precondition(first == [nil, nil] && plot.input?.scales.first == 1)
|
||||
case .present:
|
||||
precondition(first == [0.77, 0.77, 0.77] && plot.input?.scales.first == 1)
|
||||
precondition(plot.input?.projection == .fullHeight && plot.baseline.isHidden)
|
||||
let area = (plot.curves.sublayers!.first!.sublayers!.first as! CAShapeLayer).path!
|
||||
for fraction: CGFloat in [0.25, 0.75] {
|
||||
precondition(area.contains(CGPoint(x: plot.bounds.width * fraction, y: plot.bounds.midY)),
|
||||
"Battery charge fill must span both unplugging and reconnecting")
|
||||
}
|
||||
precondition(topRect(plot, in: host) == host.bounds)
|
||||
default: precondition(first == [nil, nil] && plot.input?.projection == .fullHeight)
|
||||
}
|
||||
}
|
||||
host.rootView = AnyView(EmptyView())
|
||||
|
||||
@@ -29,15 +29,15 @@ import Foundation
|
||||
precondition(MetricFormat.watts(12.34) == "12.3 W")
|
||||
var extended = MetricsSnapshot()
|
||||
extended.network = [NetworkInterfaceMetrics(name: "en0", received: 100, sent: 50, download: 20, upload: 10)]
|
||||
extended.battery = BatteryMetrics(charge: 0.8, charging: false, externalPower: true, power: 0)
|
||||
extended.battery = BatteryMetrics(charge: 0.8, flow: BatteryPowerFlow(connected: true, externalSupply: true, battery: PowerReading(watts: 0)))
|
||||
var extendedHistory = MetricHistory()
|
||||
extendedHistory.append(extended)
|
||||
precondition(extendedHistory.samples.last?.download == 20)
|
||||
precondition(extendedHistory.samples.last?.battery == 0.8)
|
||||
precondition(extendedHistory.samples.last?.batteryPower == 0)
|
||||
extended.battery?.power = 12.5
|
||||
precondition(extendedHistory.samples.last?.powerFlow?.battery?.watts == 0)
|
||||
extended.battery?.flow.battery = PowerReading(watts: -12.5)
|
||||
extendedHistory.append(extended)
|
||||
precondition(extendedHistory.samples.last?.batteryPower == 12.5)
|
||||
precondition(extendedHistory.samples.last?.powerFlow?.battery?.watts == -12.5)
|
||||
extended.network = [NetworkInterfaceMetrics(name: "en0", received: 100, sent: 50, download: nil, upload: nil)]
|
||||
extendedHistory.append(extended)
|
||||
precondition(extendedHistory.samples.last?.download == nil)
|
||||
|
||||
@@ -56,6 +56,17 @@ import Observation
|
||||
precondition(store.effectiveMilliseconds == 1_800_000)
|
||||
precondition(store.history.samples.last?.breakBefore == true)
|
||||
store.togglePause()
|
||||
let pausedCount = store.history.samples.count
|
||||
store.powerSourceDidChange()
|
||||
try await Task.sleep(for: .milliseconds(100))
|
||||
precondition(store.history.samples.count == pausedCount)
|
||||
store.togglePause()
|
||||
try await until { store.history.samples.count > pausedCount }
|
||||
let beforeEvent = store.history.samples.count
|
||||
store.powerSourceDidChange()
|
||||
try await until { store.history.samples.count >= beforeEvent + 2 }
|
||||
precondition(store.effectiveMilliseconds == 1_800_000)
|
||||
store.togglePause()
|
||||
let probe = DelayedProcessRead()
|
||||
let deferred = SystemSampler(processRead: { probe.read(&$0) })
|
||||
await deferred.setProcessVisible(true)
|
||||
|
||||
@@ -19,7 +19,7 @@ import Foundation
|
||||
precondition(BatteryMonitor.estimatedMinutes(charging: true, externalPower: true, sourceMinutes: nil, systemSeconds: 5400) == nil)
|
||||
precondition(BatteryMonitor.estimatedMinutes(charging: false, externalPower: false, sourceMinutes: nil, systemSeconds: .infinity) == nil)
|
||||
precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 12_000, amperageMilliamps: 2_500) == 30)
|
||||
precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 12_000, amperageMilliamps: -2_500) == 30)
|
||||
precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 12_000, amperageMilliamps: -2_500) == -30)
|
||||
precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 0, amperageMilliamps: 2_500) == nil)
|
||||
precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 12_000, amperageMilliamps: .nan) == nil)
|
||||
precondition(BatteryMonitor.normalizedPower(voltageMillivolts: 50_000, amperageMilliamps: 2_500) == nil)
|
||||
@@ -29,7 +29,7 @@ import Foundation
|
||||
sample.batteryState = state; sample.systemPower = 29.5
|
||||
history.append(sample)
|
||||
precondition(history.samples.last?.systemPower == (state == .absent ? 29.5 : nil))
|
||||
precondition(history.samples.last?.batteryPower == nil && history.samples.last?.battery == nil)
|
||||
precondition(history.samples.last?.powerFlow?.battery?.watts == nil && history.samples.last?.battery == nil)
|
||||
}
|
||||
let report = Data(#"{"SPPowerDataType":[{"sppower_battery_health_info":{"sppower_battery_health_maximum_capacity":"100%"}}]}"#.utf8)
|
||||
precondition(SystemBatteryHealthMonitor.parse(report) == 1)
|
||||
@@ -55,10 +55,11 @@ import Foundation
|
||||
precondition(disk.total > 0 && (0...1).contains(disk.usage))
|
||||
print("Volume bytes:", disk.total, "available:", disk.available)
|
||||
}
|
||||
if let battery = BatteryMonitor.sample() {
|
||||
var monitor = BatteryMonitor()
|
||||
if let battery = monitor.sample() {
|
||||
precondition(battery.charge.map { (0...1).contains($0) } ?? true)
|
||||
precondition(battery.power.map { $0.isFinite && (0...500).contains($0) } ?? true)
|
||||
print("Battery:", battery.charge as Any, "charging:", battery.charging, "cycles:", battery.cycles as Any, "health:", battery.health as Any, "powerW:", battery.power as Any, "minutes:", battery.minutesRemaining as Any)
|
||||
precondition(battery.flow.battery.map { $0.watts.isFinite && abs($0.watts) <= 500 } ?? true)
|
||||
print("Battery:", battery.charge as Any, "state:", battery.flow.state, "cycles:", battery.cycles as Any, "health:", battery.health as Any, "powerW:", battery.flow.battery as Any, "minutes:", battery.minutesRemaining as Any)
|
||||
} else { print("Battery unavailable or absent") }
|
||||
print("Stage C checks passed")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user