147 lines
7.5 KiB
Swift
147 lines
7.5 KiB
Swift
import Foundation
|
|
import IOKit
|
|
|
|
// 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
|
|
|
|
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
|
|
}
|
|
}
|
|
|
|
/// 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
|
|
}
|
|
|
|
/// 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,
|
|
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))) }
|
|
return Self.decodeSensorNumber(type: metadata.info.type, bytes: bytes)
|
|
}
|
|
|
|
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))
|
|
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
|
|
}
|
|
}
|
|
}
|