macOS. How to get CPU temperature programmatically

后端 未结 1 1733
难免孤独
难免孤独 2021-02-03 15:45

I need to get CPU temperature using Swift, but I can\'t find any information except for this.

I think that I should use IOKit.framework but again there\'s no much inform

1条回答
  •  不知归路
    2021-02-03 16:02

    using https://github.com/lavoiesl/osx-cpu-temp/blob/master/smc.c I got it to work. You have to do a few things:

    Simplify main() to something else:

    double calculate()
    {
        SMCOpen();
        double temperature = SMCGetTemperature(SMC_KEY_CPU_TEMP);
        SMCClose();
        temperature = convertToFahrenheit(temperature);
        return temperature;
    }
    

    Write an ObjC wrapper:

    #import "SMCObjC.h"
    #import "smc.h"   
    @implementation SMCObjC
    
    +(double)calculateTemp {
        return calculate();
    }
    
    @end
    

    Add the header to your Swift bridging header.

    //
    //  Use this file to import your target's public headers that you would like to expose to Swift.
    //
    #import "SMCObjC.h"
    

    If the app is sandboxed, add a security exemption for AppleSMC:

    
        com.apple.security.app-sandbox
        
        com.apple.security.files.user-selected.read-only
        
        com.apple.security.temporary-exception.sbpl
        
            (allow iokit-open)
            (allow iokit-set-properties (iokit-property "AppleSMC"))
            (allow mach-lookup (global-name "com.apple.AssetCacheLocatorService"))
        
    
    
    

    Call it from Swift.

    import Cocoa
    
    class ViewController: NSViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            let temp = SMCObjC.calculateTemp()
            print("I got \(temp) in swift")
        }
    }
    

    0 讨论(0)
提交回复
热议问题