feat(monitors): 为无内置电池的 Mac 采样整机即时功率
加入整机功率采样、XPC 读取和历史记录,并覆盖无电池设备的采样分支。
This commit is contained in:
@@ -3,6 +3,7 @@ import Foundation
|
||||
private actor CPUTemperatureReader {
|
||||
private let monitor = CPUTemperatureMonitor()
|
||||
private let gpuMonitor = CPUTemperatureMonitor(zone: .gpu)
|
||||
func sampleSystemPower() -> Double? { monitor.sampleSystemPower() }
|
||||
func sampleFans() -> [Double?]? { monitor.sampleFans() }
|
||||
func sampleGPU() -> Double? { gpuMonitor.sample() }
|
||||
|
||||
@@ -14,6 +15,10 @@ private actor CPUTemperatureReader {
|
||||
final class SMARTService: NSObject, SMARTServiceProtocol {
|
||||
private let temperatureReader = CPUTemperatureReader()
|
||||
|
||||
func readSystemPower(withReply reply: @escaping (NSNumber?) -> Void) {
|
||||
Task { reply(await temperatureReader.sampleSystemPower().map(NSNumber.init(value:))) }
|
||||
}
|
||||
|
||||
func readSensors(cpu: Bool, gpu: Bool, fans: Bool,
|
||||
withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void) {
|
||||
Task {
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# 资源卡片读数与趋势调整
|
||||
|
||||
目标是让文字与走势可以同时阅读、直观看出真实核心数量,并在没有内置电池时显示传感器的整机即时功率。旧面板以整卡高度绘图,每核四段,GPU 阶段只在提示中;旧版数值滚动曾在性能优化时移除。
|
||||
|
||||
1. Core / SMARTService:仅确认无内置电池且面板需要详情时请求固定只读 AppleSMC PSTR。成功按采样间隔更新,失败独立退避;未知/失败不当作无电池,功率缺失不填零。功率历史独立于电量与电池功率。不声称是插座测量。
|
||||
2. MenuBar / UI / Resources:前景按实际内容高度排版,余下区域给曲线;保留双向速率、现有控件、历史断点与提示。一核一格以连续填充显示负载,GPU 渲染器 / 分块器常显,不相加。无电池切换功率卡与 W 趋势,三语一致。
|
||||
3. UI:复用初版系统 numericText 动效;连续追加时对已有曲线图层短暂做水平变换,不设逐帧计时器。悬浮、断点和减弱动态效果时保持静态。
|
||||
4. 验证构建、逐核/高核数换行、曲线滚动与悬浮、缺失值、XPC 实际读取、不同宽度三语布局以及真实面板。保留已运行的应用。当前机器为 MacBook Pro,不能代替 Mac mini 整机验收;跨机型传感器支持、长期功耗与动效手感须分别评估。
|
||||
@@ -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,
|
||||
|
||||
@@ -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?
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -24,6 +24,8 @@ 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 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)")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,14 @@ import Foundation
|
||||
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)
|
||||
var history = MetricHistory()
|
||||
for state: BatteryAvailability in [.absent, .failed, .unknown, .present] {
|
||||
var sample = MetricsSnapshot()
|
||||
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)
|
||||
}
|
||||
let report = Data(#"{"SPPowerDataType":[{"sppower_battery_health_info":{"sppower_battery_health_maximum_capacity":"100%"}}]}"#.utf8)
|
||||
precondition(SystemBatteryHealthMonitor.parse(report) == 1)
|
||||
precondition(SystemBatteryHealthMonitor.parse(Data(String(decoding: report, as: UTF8.self).replacingOccurrences(of: "100%", with: "83%").utf8)) == 0.83)
|
||||
|
||||
Reference in New Issue
Block a user