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.stride == 80 && MemoryLayout.offset(of: \Request.info) == 28 && MemoryLayout.offset(of: \Request.command) == 42 && MemoryLayout.offset(of: \Request.index) == 44 && MemoryLayout.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.stride let result = IOConnectCallStructMethod(connection, 2, &request, MemoryLayout.stride, &response, &size) guard result == KERN_SUCCESS, size == MemoryLayout.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..> 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..= 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 } } }