View Javadoc
1   /*
2    * Copyright 2016-2023 The OSHI Project Contributors
3    * SPDX-License-Identifier: MIT
4    */
5   package oshi.hardware.platform.mac;
6   
7   import java.util.Locale;
8   
9   import com.sun.jna.platform.mac.IOKit.IOConnect;
10  
11  import oshi.annotation.concurrent.ThreadSafe;
12  import oshi.hardware.common.AbstractSensors;
13  import oshi.util.platform.mac.SmcUtil;
14  
15  /**
16   * Sensors from SMC
17   */
18  @ThreadSafe
19  final class MacSensors extends AbstractSensors {
20  
21      // This shouldn't change once determined
22      private int numFans = 0;
23  
24      @Override
25      public double queryCpuTemperature() {
26          IOConnect conn = SmcUtil.smcOpen();
27          double temp = SmcUtil.smcGetFloat(conn, SmcUtil.SMC_KEY_CPU_TEMP);
28          SmcUtil.smcClose(conn);
29          if (temp > 0d) {
30              return temp;
31          }
32          return 0d;
33      }
34  
35      @Override
36      public int[] queryFanSpeeds() {
37          // If we don't have fan # try to get it
38          IOConnect conn = SmcUtil.smcOpen();
39          if (this.numFans == 0) {
40              this.numFans = (int) SmcUtil.smcGetLong(conn, SmcUtil.SMC_KEY_FAN_NUM);
41          }
42          int[] fanSpeeds = new int[this.numFans];
43          for (int i = 0; i < this.numFans; i++) {
44              fanSpeeds[i] = (int) SmcUtil.smcGetFloat(conn, String.format(Locale.ROOT, SmcUtil.SMC_KEY_FAN_SPEED, i));
45          }
46          SmcUtil.smcClose(conn);
47          return fanSpeeds;
48      }
49  
50      @Override
51      public double queryCpuVoltage() {
52          IOConnect conn = SmcUtil.smcOpen();
53          double volts = SmcUtil.smcGetFloat(conn, SmcUtil.SMC_KEY_CPU_VOLTAGE) / 1000d;
54          SmcUtil.smcClose(conn);
55          return volts;
56      }
57  }