feat(power): 展示电池实际充放电功率并及时响应电源切换
保留电量百分比和连续趋势,按历史采样展示电池、适配器和系统功率。面板可见时读取电池实时功率,插拔电源后立即刷新并复读。
This commit is contained in:
@@ -26,6 +26,12 @@ nonisolated enum MetricFormat {
|
||||
return String(format: "%.1f %@", scaled, units[index])
|
||||
}
|
||||
|
||||
static func signedWatts(_ value: Double?) -> String {
|
||||
guard let value, value.isFinite else { return "--" }
|
||||
if abs(value) < 0.05 { return "0 W" }
|
||||
return (value < 0 ? "−" : "+") + watts(abs(value))
|
||||
}
|
||||
|
||||
static func watts(_ value: Double?) -> String {
|
||||
guard let value, value.isFinite, value >= 0 else { return "--" }
|
||||
return String(format: "%.1f W", value)
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import Foundation
|
||||
|
||||
nonisolated struct PowerReading: Sendable, Equatable {
|
||||
enum Source: Sendable { case smc, telemetry, instantaneous, average, balance }
|
||||
let watts: Double
|
||||
var source: Source = .telemetry
|
||||
}
|
||||
|
||||
nonisolated struct BatteryPowerFlow: Sendable {
|
||||
var connected: Bool?
|
||||
var externalSupply: Bool?
|
||||
var charging: Bool?
|
||||
var battery: PowerReading?
|
||||
var input: PowerReading?
|
||||
var load: PowerReading?
|
||||
var adapterCapacity: Double?
|
||||
|
||||
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 }
|
||||
battery = PowerReading(watts: watts, source: .smc)
|
||||
// Estimates made from older registry measurements no longer share a sampling window.
|
||||
if load?.source == .balance { load = nil }
|
||||
if input?.source == .balance { input = nil }
|
||||
if connected == false, load == nil, watts < 0 {
|
||||
load = PowerReading(watts: -watts, source: .balance)
|
||||
}
|
||||
}
|
||||
|
||||
enum State: Sendable {
|
||||
case charging, combined, battery, discharging, external, unknown
|
||||
}
|
||||
|
||||
var state: State {
|
||||
if let battery {
|
||||
// Differences of two sensors are less precise than a battery-terminal reading.
|
||||
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 }
|
||||
return .discharging
|
||||
}
|
||||
}
|
||||
if battery == nil, charging == true, connected != false, externalSupply != false { return .charging }
|
||||
if externalSupply == false { return .battery }
|
||||
if externalSupply == true || (input?.watts ?? 0) > 0 { return .external }
|
||||
if connected == false { return .battery }
|
||||
return .unknown
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,9 @@ nonisolated struct TrendSample: Sendable {
|
||||
let memory: Double?
|
||||
var download: Double?
|
||||
var battery: Double?
|
||||
var batteryPower: Double?
|
||||
var powerFlow: BatteryPowerFlow?
|
||||
var systemPower: Double?
|
||||
var desktopInput: Double?
|
||||
var upload: Double?
|
||||
var read: Double?
|
||||
var write: Double?
|
||||
@@ -46,9 +47,9 @@ nonisolated struct MetricHistory: Sendable {
|
||||
samples.append(TrendSample(date: snapshot.date, cpu: snapshot.cpu?.usage,
|
||||
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
|
||||
download: snapshot.downloadRate,
|
||||
battery: snapshot.battery?.charge, batteryPower: snapshot.battery?.power,
|
||||
battery: snapshot.battery?.charge, powerFlow: snapshot.battery?.flow,
|
||||
systemPower: snapshot.batteryState == .absent ? snapshot.systemPower : nil,
|
||||
upload: snapshot.uploadRate,
|
||||
desktopInput: snapshot.desktopInput, upload: snapshot.uploadRate,
|
||||
read: snapshot.diskIO?.read, write: snapshot.diskIO?.written,
|
||||
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, gpuRenderer: snapshot.gpu?.renderer, gpuTiler: snapshot.gpu?.tiler,
|
||||
memoryApp: snapshot.memory.map { Double($0.app) },
|
||||
|
||||
@@ -35,6 +35,7 @@ nonisolated struct MetricsSnapshot: Sendable {
|
||||
var diskIO: DiskIOMetrics?
|
||||
var volumes: [VolumeMetrics]?
|
||||
var systemPower: Double?
|
||||
var desktopInput: Double?
|
||||
var battery: BatteryMetrics?
|
||||
var uptime: TimeInterval = 0
|
||||
var gpu: GPUMetrics?
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
import IOKit
|
||||
|
||||
// AppleSMC is undocumented. Only read CPU/GPU temperature zones and fixed fan / system power keys; never write keys.
|
||||
// AppleSMC is undocumented. Only read CPU/GPU temperature zones and fixed fan / system and battery power keys; never write keys.
|
||||
nonisolated final class CPUTemperatureMonitor {
|
||||
static let highTemperatureThreshold = 90.0
|
||||
|
||||
@@ -105,9 +105,21 @@ nonisolated final class CPUTemperatureMonitor {
|
||||
return watts
|
||||
}
|
||||
|
||||
private func readNumber(_ key: UInt32) -> Double? {
|
||||
/// B0AP on Apple Silicon is a signed, little-endian milliwatt reading at the battery.
|
||||
func sampleBatteryPower() -> Double? {
|
||||
#if arch(arm64)
|
||||
guard openConnection(), let milliwatts = readNumber(0x42304150, expectedType: 0x73693332),
|
||||
abs(milliwatts) <= 500_000 else { return nil }
|
||||
return milliwatts / 1000
|
||||
#else
|
||||
return nil
|
||||
#endif
|
||||
}
|
||||
|
||||
private func readNumber(_ key: UInt32, expectedType: UInt32? = nil) -> Double? {
|
||||
var request = Request(); request.key = key; request.command = 9
|
||||
guard let metadata = call(&request), metadata.info.size <= 32 else { return nil }
|
||||
guard let metadata = call(&request), metadata.info.size <= 32,
|
||||
expectedType == nil || metadata.info.type == expectedType else { return nil }
|
||||
request.command = 5; request.info.size = metadata.info.size
|
||||
guard let response = call(&request) else { return nil }
|
||||
let bytes = withUnsafeBytes(of: response.bytes) { Array($0.prefix(Int(metadata.info.size))) }
|
||||
@@ -116,6 +128,8 @@ nonisolated final class CPUTemperatureMonitor {
|
||||
|
||||
static func decodeSensorNumber(type: UInt32, bytes: [UInt8]) -> Double? {
|
||||
switch (type, bytes.count) {
|
||||
case (0x73693332, 4): // si32, little-endian signed integer
|
||||
return Double(bytes.withUnsafeBytes { Int32(littleEndian: $0.loadUnaligned(as: Int32.self)) })
|
||||
case (0x666c7420, 4): // flt, little-endian IEEE754
|
||||
let bits = UInt32(bytes[0]) | UInt32(bytes[1]) << 8 | UInt32(bytes[2]) << 16 | UInt32(bytes[3]) << 24
|
||||
let value = Double(Float(bitPattern: bits))
|
||||
|
||||
@@ -10,11 +10,14 @@ actor SystemSampler {
|
||||
private var fanCache: [FanMetrics]?
|
||||
private var powerSchedule = SensorSchedule(successInterval: 0)
|
||||
private var readingPower = false
|
||||
private var batteryPowerSchedule = SensorSchedule(successInterval: 0)
|
||||
private var readingBatteryPower = false
|
||||
private var cpuSchedule = SensorSchedule()
|
||||
private var gpuSchedule = SensorSchedule()
|
||||
private var fanSchedule = SensorSchedule()
|
||||
private var didProbe = false
|
||||
private let diskHealth = DiskHealthMonitor()
|
||||
private var batteryMonitor = BatteryMonitor()
|
||||
private let batteryHealth = SystemBatteryHealthMonitor()
|
||||
private var network = NetworkMonitor()
|
||||
private let networkPath = NetworkPathObserver()
|
||||
@@ -48,6 +51,8 @@ actor SystemSampler {
|
||||
|
||||
func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() }
|
||||
|
||||
func invalidateBatteryReadings() { batteryMonitor.invalidate() }
|
||||
|
||||
func setProcessVisible(_ visible: Bool, revision: Int? = nil) {
|
||||
var changedRevision = false
|
||||
if let revision {
|
||||
@@ -101,7 +106,7 @@ actor SystemSampler {
|
||||
result.defaultNetworkInterface = networkPath.defaultInterface()
|
||||
result.disk = DiskMonitor.sample()
|
||||
result.diskIO = diskIO.sample()
|
||||
result.battery = BatteryMonitor.sample()
|
||||
result.battery = batteryMonitor.sample()
|
||||
result.batteryState = result.battery == nil ? BatteryMonitor.availability() : .present
|
||||
result.gpu = GPUMonitor.sample()
|
||||
if includeSlowMetrics && volumeTask == nil && start - volumeSampleTime >= 30 {
|
||||
@@ -122,8 +127,20 @@ actor SystemSampler {
|
||||
result.battery?.health = batteryCache
|
||||
result.volumes = volumes
|
||||
result.uptime = ProcessInfo.processInfo.systemUptime
|
||||
if includeSlowMetrics && result.battery != nil && !readingBatteryPower && batteryPowerSchedule.isDue(at: start) {
|
||||
readingBatteryPower = true
|
||||
let watts = await CPUTemperatureServiceClient.readBatteryPower()
|
||||
readingBatteryPower = false
|
||||
if !Task.isCancelled {
|
||||
if let watts { result.battery?.flow.applyBatterySensor(watts) }
|
||||
batteryPowerSchedule.complete(available: watts != nil, at: ProcessInfo.processInfo.systemUptime)
|
||||
}
|
||||
}
|
||||
// Only a confirmed batteryless machine requests the fixed system-total key.
|
||||
// Use this sample's reply directly: a missing reading never repeats the last wattage.
|
||||
if includeSlowMetrics && result.batteryState == .absent {
|
||||
result.desktopInput = batteryMonitor.desktopInput()
|
||||
}
|
||||
if includeSlowMetrics && result.batteryState == .absent && !readingPower && powerSchedule.isDue(at: start) {
|
||||
readingPower = true
|
||||
result.systemPower = await CPUTemperatureServiceClient.readSystemPower()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user