feat(menubar): 完善首排监控卡片与温度风扇采样
补充 GPU 渲染分块、内存与利用率统计,增加只读 SMC 温度及风扇信息和旋转动效。完善电池功率与耗电进程列表,统一首排布局并固定异步加载区域高度。同步验证用例、架构说明和 GPU 能力调研工具。
This commit is contained in:
@@ -20,5 +20,10 @@ nonisolated enum MetricFormat {
|
||||
return String(format: "%.1f %@", scaled, units[index])
|
||||
}
|
||||
|
||||
static func watts(_ value: Double?) -> String {
|
||||
guard let value, value.isFinite, value >= 0 else { return "--" }
|
||||
return String(format: "%.1f W", value)
|
||||
}
|
||||
|
||||
static func decimal(_ value: Double) -> String { String(format: "%.1f", value) }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import Foundation
|
||||
|
||||
nonisolated struct FanMetrics: Sendable, Identifiable {
|
||||
let id: Int
|
||||
let rpm: Double?
|
||||
|
||||
static func validRPM(_ value: Double?) -> Double? {
|
||||
guard let value, value.isFinite, value >= 0, value <= 30_000 else { return nil }
|
||||
return value
|
||||
}
|
||||
}
|
||||
@@ -8,11 +8,14 @@ nonisolated struct TrendSample: Sendable {
|
||||
var download: Double?
|
||||
var disk: Double?
|
||||
var battery: Double?
|
||||
var batteryPower: Double?
|
||||
var upload: Double?
|
||||
var read: Double?
|
||||
var write: Double?
|
||||
var cpuUser: Double?
|
||||
var cpuSystem: Double?
|
||||
var gpuRenderer: Double?
|
||||
var gpuTiler: Double?
|
||||
var breakBefore = false
|
||||
var expectedInterval: TimeInterval = 2
|
||||
}
|
||||
@@ -27,9 +30,10 @@ nonisolated struct MetricHistory: Sendable {
|
||||
samples.append(TrendSample(date: snapshot.date, cpu: snapshot.cpu?.usage,
|
||||
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
|
||||
download: snapshot.downloadRate, disk: snapshot.disk?.usage,
|
||||
battery: snapshot.battery?.charge, upload: snapshot.uploadRate,
|
||||
battery: snapshot.battery?.charge, batteryPower: snapshot.battery?.power,
|
||||
upload: snapshot.uploadRate,
|
||||
read: snapshot.diskIO?.read, write: snapshot.diskIO?.written,
|
||||
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, breakBefore: breakBefore, expectedInterval: expectedInterval))
|
||||
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, gpuRenderer: snapshot.gpu?.renderer, gpuTiler: snapshot.gpu?.tiler, breakBefore: breakBefore, expectedInterval: expectedInterval))
|
||||
let current = snapshot.network ?? []
|
||||
let keys = Set(current.map(\.identity))
|
||||
interfaces = interfaces.filter { keys.contains($0.key) }
|
||||
@@ -47,3 +51,30 @@ nonisolated struct InterfaceTrendSample: Sendable {
|
||||
let upload: Double?
|
||||
var expectedInterval: TimeInterval = 2
|
||||
}
|
||||
|
||||
/// Time-weighted observed utilization; never bridge failures or sleep boundaries.
|
||||
nonisolated struct GPUUtilizationSummary {
|
||||
let average: Double?
|
||||
let peak: Double?
|
||||
let coverage: TimeInterval
|
||||
|
||||
init(samples: [TrendSample], window: TimeInterval = 60) {
|
||||
guard let end = samples.last?.date else { average = nil; peak = nil; coverage = 0; return }
|
||||
let start = end.addingTimeInterval(-window)
|
||||
peak = samples.filter { $0.date >= start }.compactMap(\.gpu).max()
|
||||
var area = 0.0
|
||||
var duration = 0.0
|
||||
for (a, b) in zip(samples, samples.dropFirst()) {
|
||||
let dt = b.date.timeIntervalSince(a.date)
|
||||
guard !b.breakBefore, dt > 0, dt <= max(a.expectedInterval, b.expectedInterval) * 2.5,
|
||||
let av = a.gpu, let bv = b.gpu else { continue }
|
||||
let overlap = b.date.timeIntervalSince(max(a.date, start))
|
||||
guard overlap > 0 else { continue }
|
||||
let left = av + (bv - av) * (1 - overlap / dt)
|
||||
area += (left + bv) * 0.5 * overlap
|
||||
duration += overlap
|
||||
}
|
||||
coverage = duration
|
||||
average = duration > 0 ? area / duration : nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,9 @@ nonisolated struct MemoryMetrics: Sendable {
|
||||
nonisolated struct MetricsSnapshot: Sendable {
|
||||
var date = Date()
|
||||
var cpu: CPUMetrics?
|
||||
var cpuTemperature: Double?
|
||||
var gpuTemperature: Double?
|
||||
var fans: [FanMetrics]?
|
||||
var memory: MemoryMetrics?
|
||||
var network: [NetworkInterfaceMetrics]?
|
||||
var networkPath: NetworkPathStatus?
|
||||
|
||||
@@ -23,3 +23,21 @@ nonisolated struct ProcessSnapshot: Sendable {
|
||||
let rows: [ProcessMetrics]
|
||||
let failed: Bool
|
||||
}
|
||||
|
||||
nonisolated extension ProcessSnapshot {
|
||||
func highestCPUProcesses(limit: Int) -> [ProcessMetrics] {
|
||||
guard limit > 0 else { return [] }
|
||||
var result: [ProcessMetrics] = []
|
||||
for row in rows {
|
||||
guard let cpu = row.cpu, cpu.isFinite, cpu >= 0 else { continue }
|
||||
let index = result.firstIndex { ($0.cpu ?? 0) < cpu } ?? result.endIndex
|
||||
result.insert(row, at: index)
|
||||
if result.count > limit { result.removeLast() }
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
var highestCPUProcess: ProcessMetrics? {
|
||||
highestCPUProcesses(limit: 1).first
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,12 +5,22 @@ nonisolated struct BatteryMetrics: Sendable {
|
||||
let charge: Double?
|
||||
let charging: Bool
|
||||
let externalPower: Bool
|
||||
var power: Double? = nil
|
||||
var minutesRemaining: Int?
|
||||
var cycles: Int?
|
||||
var health: Double?
|
||||
}
|
||||
|
||||
nonisolated enum BatteryMonitor {
|
||||
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
|
||||
}
|
||||
|
||||
static func positiveMinutes(_ value: Int?) -> Int? {
|
||||
value.flatMap { $0 > 0 ? $0 : nil }
|
||||
}
|
||||
@@ -55,10 +65,24 @@ nonisolated enum BatteryMonitor {
|
||||
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, minutesRemaining: estimatedMinutes(charging: charging, externalPower: external, sourceMinutes: minutes, systemSeconds: IOPSGetTimeRemainingEstimate()),
|
||||
externalPower: external,
|
||||
power: normalizedPower(voltageMillivolts: voltage, amperageMilliamps: amperage),
|
||||
minutesRemaining: estimatedMinutes(charging: charging, externalPower: external, sourceMinutes: minutes, systemSeconds: IOPSGetTimeRemainingEstimate()),
|
||||
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
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import Foundation
|
||||
import IOKit
|
||||
|
||||
// AppleSMC is undocumented. Only read CPU/GPU temperature zones and fixed fan keys; never write keys.
|
||||
nonisolated final class CPUTemperatureMonitor {
|
||||
static let highTemperatureThreshold = 90.0
|
||||
|
||||
private struct Version { var major: UInt8 = 0; var minor: UInt8 = 0; var build: UInt8 = 0; var reserved: UInt8 = 0; var release: UInt16 = 0 }
|
||||
private struct Limits { var version: UInt16 = 0; var length: UInt16 = 0; var cpu: UInt32 = 0; var gpu: UInt32 = 0; var memory: UInt32 = 0 }
|
||||
private struct KeyInfo { var size: UInt32 = 0; var type: UInt32 = 0; var attributes: UInt8 = 0; var padding1: UInt8 = 0; var padding2: UInt8 = 0; var padding3: UInt8 = 0 }
|
||||
private struct Request {
|
||||
var key: UInt32 = 0; var version = Version(); var limits = Limits(); var info = KeyInfo()
|
||||
var result: UInt8 = 0; var status: UInt8 = 0; var command: UInt8 = 0; var index: UInt32 = 0
|
||||
var bytes: (UInt64, UInt64, UInt64, UInt64) = (0, 0, 0, 0)
|
||||
}
|
||||
static var hasExpectedLayout: Bool {
|
||||
MemoryLayout<Request>.stride == 80 && MemoryLayout<Request>.offset(of: \Request.info) == 28 &&
|
||||
MemoryLayout<Request>.offset(of: \Request.command) == 42 && MemoryLayout<Request>.offset(of: \Request.index) == 44 &&
|
||||
MemoryLayout<Request>.offset(of: \Request.bytes) == 48
|
||||
}
|
||||
static func isHighTemperature(_ value: Double?) -> Bool {
|
||||
guard let value else { return false }
|
||||
return value >= highTemperatureThreshold
|
||||
}
|
||||
enum Zone { case cpu, gpu }
|
||||
private let zone: Zone
|
||||
init(zone: Zone = .cpu) { self.zone = zone }
|
||||
|
||||
private var connection: io_connect_t = 0
|
||||
private var keys: [(UInt32, UInt32)] = []
|
||||
private var attempted = false
|
||||
|
||||
deinit { if connection != 0 { IOServiceClose(connection) } }
|
||||
|
||||
private func call(_ request: inout Request) -> Request? {
|
||||
var response = Request()
|
||||
var size = MemoryLayout<Request>.stride
|
||||
let result = IOConnectCallStructMethod(connection, 2, &request, MemoryLayout<Request>.stride, &response, &size)
|
||||
guard result == KERN_SUCCESS, size == MemoryLayout<Request>.stride, response.result == 0 else { return nil }
|
||||
return response
|
||||
}
|
||||
|
||||
private func openConnection() -> Bool {
|
||||
if connection != 0 { return true }
|
||||
guard Self.hasExpectedLayout else { return false }
|
||||
let service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSMC"))
|
||||
guard service != 0 else { return false }
|
||||
defer { IOObjectRelease(service) }
|
||||
guard IOServiceOpen(service, mach_task_self_, 0, &connection) == KERN_SUCCESS else { connection = 0; return false }
|
||||
return true
|
||||
}
|
||||
|
||||
private func discover() {
|
||||
attempted = true
|
||||
guard openConnection() else { return }
|
||||
var countRequest = Request(); countRequest.key = 0x234b4559; countRequest.info.size = 4; countRequest.command = 5
|
||||
guard let countResponse = call(&countRequest) else { return }
|
||||
let count = withUnsafeBytes(of: countResponse.bytes) { UInt32($0[0]) << 24 | UInt32($0[1]) << 16 | UInt32($0[2]) << 8 | UInt32($0[3]) }
|
||||
guard count <= 10000 else { return }
|
||||
for index in 0..<count {
|
||||
var request = Request(); request.command = 8; request.index = index
|
||||
guard let response = call(&request) else { continue }
|
||||
let prefix = response.key >> 16
|
||||
guard zone == .gpu ? prefix == 0x5467 : (prefix == 0x5470 || prefix == 0x5465) else { continue }
|
||||
var info = Request(); info.key = response.key; info.command = 9
|
||||
guard let metadata = call(&info), metadata.info.type == 0x666c7420, metadata.info.size == 4 else { continue }
|
||||
keys.append((response.key, metadata.info.size))
|
||||
}
|
||||
if keys.isEmpty {
|
||||
IOServiceClose(connection)
|
||||
connection = 0
|
||||
attempted = false
|
||||
}
|
||||
}
|
||||
|
||||
/// Highest valid selected temperature-zone sensor reading in Celsius, not an official package temperature.
|
||||
func sample() -> Double? {
|
||||
if !attempted { discover() }
|
||||
guard connection != 0 else { return nil }
|
||||
var highest: Double?
|
||||
for (key, size) in keys {
|
||||
var request = Request(); request.key = key; request.info.size = size; request.command = 5
|
||||
guard let response = call(&request) else { continue }
|
||||
let bits = withUnsafeBytes(of: response.bytes) { UInt32($0[0]) | UInt32($0[1]) << 8 | UInt32($0[2]) << 16 | UInt32($0[3]) << 24 }
|
||||
let value = Double(Float(bitPattern: bits))
|
||||
guard value.isFinite, value > 0, value < 150 else { continue }
|
||||
highest = max(highest ?? value, value)
|
||||
}
|
||||
return highest
|
||||
}
|
||||
/// Fixed read-only fan keys. nil means unavailable; [] means a fanless device.
|
||||
func sampleFans() -> [Double?]? {
|
||||
guard openConnection(), let count = readNumber(0x464e756d),
|
||||
count.isFinite, count >= 0, count <= 10, count.rounded() == count else { return nil }
|
||||
return (0..<Int(count)).map { index in
|
||||
let key = UInt32(0x46304163) + (UInt32(index) << 16) // F0Ac ... F9Ac
|
||||
guard let rpm = readNumber(key), rpm.isFinite, rpm >= 0, rpm <= 30_000 else { return nil }
|
||||
return rpm
|
||||
}
|
||||
}
|
||||
|
||||
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 }
|
||||
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))) }
|
||||
return Self.decodeSensorNumber(type: metadata.info.type, bytes: bytes)
|
||||
}
|
||||
|
||||
static func decodeSensorNumber(type: UInt32, bytes: [UInt8]) -> Double? {
|
||||
switch (type, bytes.count) {
|
||||
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))
|
||||
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 (0x75693820, 1): return Double(bytes[0]) // ui8
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,11 @@ import IOKit
|
||||
nonisolated struct GPUMetrics: Sendable {
|
||||
let usage: Double?
|
||||
let coreCount: Int?
|
||||
var renderer: Double? = nil
|
||||
var tiler: Double? = nil
|
||||
// Driver accounting, not dedicated VRAM or a capacity denominator.
|
||||
var inUseMemory: UInt64? = nil
|
||||
var allocatedMemory: UInt64? = nil
|
||||
// Independent per-core counters have not been obtained. Never split total usage.
|
||||
}
|
||||
|
||||
@@ -20,12 +25,23 @@ nonisolated enum GPUMonitor {
|
||||
let stats = IORegistryEntryCreateCFProperty(service, "PerformanceStatistics" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? [String: Any]
|
||||
let raw = (stats?["Device Utilization %"] as? NSNumber)?.doubleValue
|
||||
let cores = (IORegistryEntryCreateCFProperty(service, "gpu-core-count" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? NSNumber)?.intValue
|
||||
devices.append(GPUMetrics(usage: normalized(raw), coreCount: cores.flatMap { $0 > 0 ? $0 : nil }))
|
||||
devices.append(GPUMetrics(usage: normalized(raw), coreCount: cores.flatMap { $0 > 0 ? $0 : nil },
|
||||
renderer: normalized((stats?["Renderer Utilization %"] as? NSNumber)?.doubleValue),
|
||||
tiler: normalized((stats?["Tiler Utilization %"] as? NSNumber)?.doubleValue),
|
||||
inUseMemory: memoryBytes(stats?["In use system memory"]),
|
||||
allocatedMemory: memoryBytes(stats?["Alloc system memory"])))
|
||||
}
|
||||
// Do not average incompatible utilization counters on multi-GPU machines.
|
||||
return devices.count == 1 ? devices[0] : nil
|
||||
}
|
||||
|
||||
static func memoryBytes(_ raw: Any?) -> UInt64? {
|
||||
guard let number = raw as? NSNumber else { return nil }
|
||||
let value = number.doubleValue
|
||||
guard value.isFinite, value >= 0, value < Double(UInt64.max) else { return nil }
|
||||
return UInt64(value)
|
||||
}
|
||||
|
||||
static func normalized(_ value: Double?) -> Double? {
|
||||
value.flatMap { $0.isFinite && (0...100).contains($0) ? $0 / 100 : nil }
|
||||
}
|
||||
|
||||
@@ -4,6 +4,11 @@ import Darwin
|
||||
/// One coordinator owns baselines; slow workers have at most one in-flight call each.
|
||||
actor SystemSampler {
|
||||
private var cpu = CPUMonitor()
|
||||
private var temperatureTask: Task<Void, Never>?
|
||||
private var temperatureCache: Double?
|
||||
private var gpuTemperatureCache: Double?
|
||||
private var fanCache: [FanMetrics]?
|
||||
private var nextTemperature: TimeInterval = 0
|
||||
private var didProbe = false
|
||||
private let diskHealth = DiskHealthMonitor()
|
||||
private let batteryHealth = SystemBatteryHealthMonitor()
|
||||
@@ -56,6 +61,17 @@ actor SystemSampler {
|
||||
let start = ProcessInfo.processInfo.systemUptime
|
||||
var result = MetricsSnapshot()
|
||||
result.cpu = cpu.sample()
|
||||
if temperatureTask == nil && start >= nextTemperature {
|
||||
temperatureTask = Task { [self] in
|
||||
async let cpu = CPUTemperatureServiceClient.read()
|
||||
async let gpu = CPUTemperatureServiceClient.read(gpu: true)
|
||||
async let fans = CPUTemperatureServiceClient.readFans()
|
||||
await finishTemperature(cpu, gpu: gpu, fans: fans)
|
||||
}
|
||||
}
|
||||
result.cpuTemperature = temperatureCache
|
||||
result.gpuTemperature = gpuTemperatureCache
|
||||
result.fans = fanCache
|
||||
result.memory = MemoryMonitor.sample()
|
||||
result.network = network.sample()
|
||||
result.networkPath = networkPath.snapshot()
|
||||
@@ -95,6 +111,14 @@ actor SystemSampler {
|
||||
return result
|
||||
}
|
||||
|
||||
private func finishTemperature(_ value: Double?, gpu: Double?, fans: [FanMetrics]?) {
|
||||
fanCache = fans
|
||||
gpuTemperatureCache = gpu
|
||||
temperatureCache = value
|
||||
nextTemperature = ProcessInfo.processInfo.systemUptime + (value == nil && gpu == nil && fans == nil ? 60 : 5)
|
||||
temperatureTask = nil
|
||||
}
|
||||
|
||||
private func finishVolumes(_ value: [VolumeMetrics]?) {
|
||||
volumes = value; volumeSampleTime = ProcessInfo.processInfo.systemUptime; volumeTask = nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import Foundation
|
||||
|
||||
nonisolated enum CPUTemperatureServiceClient {
|
||||
static func read(gpu: Bool = false) async -> Double? {
|
||||
let url = Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc")
|
||||
guard let requirement = CodeIdentity.requirement(at: url) else { return nil }
|
||||
return await withCheckedContinuation { continuation in
|
||||
let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService")
|
||||
connection.setCodeSigningRequirement(requirement)
|
||||
connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self)
|
||||
let reply = Reply(connection: connection, continuation: continuation)
|
||||
connection.invalidationHandler = { reply.finish(nil) }
|
||||
connection.interruptionHandler = { reply.finish(nil) }
|
||||
connection.resume()
|
||||
guard let proxy = connection.remoteObjectProxyWithErrorHandler({ _ in reply.finish(nil) }) as? SMARTServiceProtocol else {
|
||||
reply.finish(nil)
|
||||
return
|
||||
}
|
||||
let receive: (NSNumber?) -> Void = { number in
|
||||
let value = number?.doubleValue
|
||||
reply.finish(value.flatMap { $0.isFinite && $0 > 0 && $0 < 150 ? $0 : nil })
|
||||
}
|
||||
if gpu { proxy.readGPUTemperature(withReply: receive) }
|
||||
else { proxy.readCPUTemperature(withReply: receive) }
|
||||
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) { reply.finish(nil) }
|
||||
}
|
||||
}
|
||||
|
||||
static func readFans() async -> [FanMetrics]? {
|
||||
let url = Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc")
|
||||
guard let requirement = CodeIdentity.requirement(at: url) else { return nil }
|
||||
return await withCheckedContinuation { continuation in
|
||||
let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService")
|
||||
connection.setCodeSigningRequirement(requirement)
|
||||
connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self)
|
||||
let reply = Reply(connection: connection, continuation: continuation)
|
||||
connection.invalidationHandler = { reply.finish(nil) }
|
||||
connection.interruptionHandler = { reply.finish(nil) }
|
||||
connection.resume()
|
||||
guard let proxy = connection.remoteObjectProxyWithErrorHandler({ _ in reply.finish(nil) }) as? SMARTServiceProtocol else {
|
||||
reply.finish(nil); return
|
||||
}
|
||||
proxy.readFanSpeeds { values in
|
||||
guard let values, values.count <= 10 else { reply.finish(nil); return }
|
||||
reply.finish(values.enumerated().map { FanMetrics(id: $0.offset, rpm: FanMetrics.validRPM($0.element.doubleValue)) })
|
||||
}
|
||||
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) { reply.finish(nil) }
|
||||
}
|
||||
}
|
||||
|
||||
private final class Reply<Value: Sendable>: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var continuation: CheckedContinuation<Value?, Never>?
|
||||
private let connection: NSXPCConnection
|
||||
|
||||
init(connection: NSXPCConnection, continuation: CheckedContinuation<Value?, Never>) {
|
||||
self.connection = connection
|
||||
self.continuation = continuation
|
||||
}
|
||||
|
||||
func finish(_ value: Value?) {
|
||||
lock.lock()
|
||||
let callback = continuation
|
||||
continuation = nil
|
||||
lock.unlock()
|
||||
guard let callback else { return }
|
||||
connection.invalidationHandler = nil
|
||||
connection.interruptionHandler = nil
|
||||
connection.invalidate()
|
||||
callback.resume(returning: value)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,5 +2,8 @@ import Foundation
|
||||
|
||||
/// Fixed read-only operation: no caller-supplied paths or commands.
|
||||
@objc protocol SMARTServiceProtocol {
|
||||
nonisolated func readFanSpeeds(withReply reply: @escaping ([NSNumber]?) -> Void)
|
||||
nonisolated func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void)
|
||||
nonisolated func readGPUTemperature(withReply reply: @escaping (NSNumber?) -> Void)
|
||||
nonisolated func readCPUTemperature(withReply reply: @escaping (NSNumber?) -> Void)
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ nonisolated enum SamplingDiagnostics {
|
||||
]
|
||||
payload["cpu"] = snapshot.cpu?.usage
|
||||
payload["cores"] = snapshot.cpu?.cores.count
|
||||
payload["cpuTemperature"] = snapshot.cpuTemperature
|
||||
payload["gpuUsage"] = snapshot.gpuUsage
|
||||
payload["gpuCoreCount"] = snapshot.gpu?.coreCount
|
||||
payload["processEnumerated"] = snapshot.processes?.enumerated
|
||||
@@ -32,6 +33,7 @@ nonisolated enum SamplingDiagnostics {
|
||||
payload["volumeCount"] = snapshot.volumes?.count
|
||||
payload["batteryCycles"] = snapshot.battery?.cycles
|
||||
payload["batteryHealth"] = snapshot.battery?.health
|
||||
payload["batteryPower"] = snapshot.battery?.power
|
||||
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