feat(power): 展示电池实际充放电功率并及时响应电源切换

保留电量百分比和连续趋势,按历史采样展示电池、适配器和系统功率。面板可见时读取电池实时功率,插拔电源后立即刷新并复读。
This commit is contained in:
2026-11-15 23:54:19 +08:00
parent 1595af6d13
commit 4b8deb2e48
31 changed files with 739 additions and 119 deletions
@@ -7,6 +7,14 @@ nonisolated struct SensorReadings: Sendable {
}
nonisolated enum CPUTemperatureServiceClient {
static func readBatteryPower() async -> Double? {
await ServiceRequest.perform(timeout: 2) { proxy, finish in
proxy.readBatteryPower { value in
finish(value.flatMap { abs($0.doubleValue) <= 500 ? $0.doubleValue : nil })
}
}
}
static func readSystemPower() async -> Double? {
await ServiceRequest.perform(timeout: 2) { proxy, finish in
proxy.readSystemPower { value in
+17 -2
View File
@@ -29,6 +29,7 @@ final class MetricsStore {
@ObservationIgnored private var task: Task<Void, Never>?
@ObservationIgnored private let sampler: SystemSampler
@ObservationIgnored private var scheduledInterval = 0
@ObservationIgnored private var batteryWasAsleep = false
@ObservationIgnored private var needsHistoryBoundary = true
@ObservationIgnored private var lastPublishedAt: ContinuousClock.Instant?
@@ -50,7 +51,12 @@ final class MetricsStore {
reschedule(reset: true)
}
private func reschedule(reset: Bool, sampleImmediately: Bool = true) {
func powerSourceDidChange() {
guard panelDemand, !isPaused, !isSystemSleeping else { return }
reschedule(reset: false, confirmPowerChange: true)
}
private func reschedule(reset: Bool, sampleImmediately: Bool = true, confirmPowerChange: Bool = false) {
generation += 1
task?.cancel()
task = nil
@@ -71,7 +77,12 @@ final class MetricsStore {
if initialDelay > .zero {
do { try await Task.sleep(for: initialDelay, tolerance: self?.schedulingTolerance) } catch { return }
}
if self?.batteryWasAsleep == true {
self?.batteryWasAsleep = false
await sampler.invalidateBatteryReadings()
}
if reset { await sampler.reset() }
var needsConfirmation = confirmPowerChange
while !Task.isCancelled {
let sampledAt = ContinuousClock.now
let visibleGeneration = self?.visibilityGeneration
@@ -105,7 +116,10 @@ final class MetricsStore {
self?.lastPublishedAt = .now
self?.needsHistoryBoundary = false
SamplingDiagnostics.record(next)
let interval = self?.effectiveMilliseconds ?? 5_000
let cadence = self?.effectiveMilliseconds ?? 5_000
// A source notification may arrive just before the gauge updates.
let interval = needsConfirmation ? min(cadence, 1000) : cadence
needsConfirmation = false
// Start-to-start cadence; missed deadlines do not trigger catch-up bursts.
let deadline = sampledAt.advanced(by: .milliseconds(interval))
do { try await Task.sleep(until: max(deadline, .now), tolerance: self?.schedulingTolerance, clock: .continuous) }
@@ -130,6 +144,7 @@ final class MetricsStore {
func setSystemSleeping(_ sleeping: Bool) {
guard sleeping != isSystemSleeping else { return }
if sleeping { batteryWasAsleep = true }
isSystemSleeping = sleeping
updateDemand(reset: true)
}
@@ -4,6 +4,7 @@ import Foundation
@objc protocol SMARTServiceProtocol {
nonisolated func readProcessMemory(_ request: Data, withReply reply: @escaping (Data?) -> Void)
nonisolated func readProcessEnergy(_ request: Data, withReply reply: @escaping (Data?) -> Void)
nonisolated func readBatteryPower(withReply reply: @escaping (NSNumber?) -> Void)
nonisolated func readSystemPower(withReply reply: @escaping (NSNumber?) -> Void)
nonisolated func readSensors(cpu: Bool, gpu: Bool, fans: Bool,
withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void)
+5 -1
View File
@@ -53,7 +53,11 @@ nonisolated enum SamplingDiagnostics {
payload["batteryCycles"] = snapshot.battery?.cycles
payload["batteryHealth"] = snapshot.battery?.health
payload["systemPower"] = snapshot.systemPower
payload["batteryPower"] = snapshot.battery?.power
payload["batteryPower"] = snapshot.battery?.flow.battery?.watts
payload["batteryPowerSource"] = snapshot.battery?.flow.battery.map { String(describing: $0.source) }
payload["adapterInput"] = snapshot.battery?.flow.input?.watts
payload["systemLoad"] = snapshot.battery?.flow.load?.watts
payload["powerState"] = snapshot.battery.map { String(describing: $0.flow.state) }
var info = task_vm_info_data_t()
var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size)
let status = withUnsafeMutablePointer(to: &info) { pointer in