feat(monitors): 为无内置电池的 Mac 采样整机即时功率

加入整机功率采样、XPC 读取和历史记录,并覆盖无电池设备的采样分支。
This commit is contained in:
2026-11-15 22:03:46 +08:00
parent e2f88023d6
commit c886c4227d
10 changed files with 58 additions and 2 deletions
+2
View File
@@ -8,6 +8,7 @@ nonisolated struct TrendSample: Sendable {
var download: Double?
var battery: Double?
var batteryPower: Double?
var systemPower: Double?
var upload: Double?
var read: Double?
var write: Double?
@@ -46,6 +47,7 @@ nonisolated struct MetricHistory: Sendable {
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
download: snapshot.downloadRate,
battery: snapshot.battery?.charge, batteryPower: snapshot.battery?.power,
systemPower: snapshot.batteryState == .absent ? snapshot.systemPower : nil,
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,
+1
View File
@@ -34,6 +34,7 @@ nonisolated struct MetricsSnapshot: Sendable {
var diskHealth: DiskHealthMetrics?
var diskIO: DiskIOMetrics?
var volumes: [VolumeMetrics]?
var systemPower: Double?
var battery: BatteryMetrics?
var uptime: TimeInterval = 0
var gpu: GPUMetrics?
+10 -1
View File
@@ -1,7 +1,7 @@
import Foundation
import IOKit
// AppleSMC is undocumented. Only read CPU/GPU temperature zones and fixed fan keys; never write keys.
// AppleSMC is undocumented. Only read CPU/GPU temperature zones and fixed fan / system power keys; never write keys.
nonisolated final class CPUTemperatureMonitor {
static let highTemperatureThreshold = 90.0
@@ -99,6 +99,12 @@ nonisolated final class CPUTemperatureMonitor {
}
}
/// PSTR is the SMC system-total sensor, not battery flow or wall-outlet power.
func sampleSystemPower() -> Double? {
guard openConnection(), let watts = readNumber(0x50535452), watts > 0 else { return nil }
return watts
}
private func readNumber(_ key: UInt32) -> Double? {
var request = Request(); request.key = key; request.command = 9
guard let metadata = call(&request), metadata.info.size <= 32 else { return nil }
@@ -116,6 +122,9 @@ nonisolated final class CPUTemperatureMonitor {
return value.isFinite ? value : nil
case (0x66706532, 2): // fpe2, big-endian unsigned 14.2 fixed point
return Double(UInt16(bytes[0]) << 8 | UInt16(bytes[1])) / 4
case (0x73703738, 2): // sp78, signed 8.8 (SMC sign-magnitude)
let magnitude = Double(UInt16(bytes[0] & 0x7f) << 8 | UInt16(bytes[1])) / 256
return bytes[0] & 0x80 == 0 ? magnitude : -magnitude
case (0x75693820, 1): return Double(bytes[0]) // ui8
default: return nil
}
+13 -1
View File
@@ -8,6 +8,8 @@ actor SystemSampler {
private var temperatureCache: Double?
private var gpuTemperatureCache: Double?
private var fanCache: [FanMetrics]?
private var powerSchedule = SensorSchedule(successInterval: 0)
private var readingPower = false
private var cpuSchedule = SensorSchedule()
private var gpuSchedule = SensorSchedule()
private var fanSchedule = SensorSchedule()
@@ -67,7 +69,7 @@ actor SystemSampler {
func sample(includeProcesses: Bool? = nil, includeSlowMetrics: Bool = true, maximumEnergyInterval: TimeInterval = 30, demandRevision: Int? = nil,
processUpdate: (@Sendable (ProcessSnapshot) -> Void)? = nil,
energyUpdate: (@Sendable (ProcessEnergySnapshot) -> Void)? = nil) -> MetricsSnapshot {
energyUpdate: (@Sendable (ProcessEnergySnapshot) -> Void)? = nil) async -> MetricsSnapshot {
guard !Task.isCancelled else { return MetricsSnapshot() }
if let demandRevision, demandRevision < self.demandRevision { return MetricsSnapshot() }
setProcessVisible(includeProcesses ?? processVisible, revision: demandRevision)
@@ -120,6 +122,16 @@ actor SystemSampler {
result.battery?.health = batteryCache
result.volumes = volumes
result.uptime = 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 && !readingPower && powerSchedule.isDue(at: start) {
readingPower = true
result.systemPower = await CPUTemperatureServiceClient.readSystemPower()
readingPower = false
if !Task.isCancelled {
powerSchedule.complete(available: result.systemPower != nil, at: ProcessInfo.processInfo.systemUptime)
}
}
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" {
let line = "{\"event\":\"sampleDuration\",\"milliseconds\":\((ProcessInfo.processInfo.systemUptime - start) * 1000)}\n"
try? FileHandle.standardOutput.write(contentsOf: Data(line.utf8))
@@ -7,6 +7,14 @@ nonisolated struct SensorReadings: Sendable {
}
nonisolated enum CPUTemperatureServiceClient {
static func readSystemPower() async -> Double? {
await ServiceRequest.perform(timeout: 2) { proxy, finish in
proxy.readSystemPower { value in
finish(value.flatMap { $0.doubleValue.isFinite && $0.doubleValue > 0 ? $0.doubleValue : nil })
}
}
}
static func readSensors(cpu: Bool, gpu: Bool, fans: Bool) async -> SensorReadings? {
await ServiceRequest.perform(timeout: 2) { proxy, finish in
proxy.readSensors(cpu: cpu, gpu: gpu, fans: fans) { cpu, gpu, fans in
@@ -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 readSystemPower(withReply reply: @escaping (NSNumber?) -> Void)
nonisolated func readSensors(cpu: Bool, gpu: Bool, fans: Bool,
withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void)
nonisolated func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void)