├── TODO ├── .gitignore ├── smc-command_from_apple └── smcutil ├── smc-command_from_fan_control ├── smc ├── smc.o ├── Makefile ├── README ├── smc.h ├── LICENSE └── smc.c ├── test.sh ├── README.md └── main.py /TODO: -------------------------------------------------------------------------------- 1 | - Переименовать бинарник, чтобы можно было устанавливать в систему 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .pyc 2 | .idea 3 | .DS_store 4 | .vscode 5 | 6 | smc-command/*.o 7 | smc-command/smc -------------------------------------------------------------------------------- /smc-command_from_apple/smcutil: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DevNulPavel/osx_battery_charge_limit/HEAD/smc-command_from_apple/smcutil -------------------------------------------------------------------------------- /smc-command_from_fan_control/smc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DevNulPavel/osx_battery_charge_limit/HEAD/smc-command_from_fan_control/smc -------------------------------------------------------------------------------- /smc-command_from_fan_control/smc.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DevNulPavel/osx_battery_charge_limit/HEAD/smc-command_from_fan_control/smc.o -------------------------------------------------------------------------------- /smc-command_from_fan_control/Makefile: -------------------------------------------------------------------------------- 1 | # CC = gcc 2 | CC = clang 3 | CFLAGS = -mmacosx-version-min=10.4 -Wall -g -framework IOKit 4 | CPPFLAGS = -DCMD_TOOL_BUILD 5 | 6 | all: smc 7 | 8 | smc: smc.o 9 | $(CC) $(CFLAGS) -o smc smc.o 10 | 11 | smc.o: smc.h smc.c 12 | $(CC) $(CPPFLAGS) -c smc.c 13 | 14 | clean: 15 | -rm -f smc smc.o 16 | -------------------------------------------------------------------------------- /test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # SMC binary app usage example: 4 | # 5 | # All keys: 6 | # -> ./smc -l 7 | # 8 | # Current value: 9 | # -> ./smc -r -k BCLM 10 | # 11 | # Set value: 12 | # 1. convert dec value to hex using 13 | # -> python -c "print(hex(60))" 14 | # 0x3c 15 | # 2. write 3c value to SMC 16 | # -> sudo ./smc -k BCLM -w 3c 17 | 18 | python3 main.py 19 | python3 main.py -c 20 | python3 main.py -s 65 21 | sudo python3 main.py -s 65 22 | sudo python3 main.py -r 23 | 24 | 25 | -------------------------------------------------------------------------------- /smc-command_from_fan_control/README: -------------------------------------------------------------------------------- 1 | Warning 2 | ------- 3 | This tool will allow you to write values to the SMC which could irreversably damage your 4 | computer. Manipulating the fans could cause overheating and permanent damange. USE THIS 5 | PROGRAM AT YOUR OWN RISK! 6 | 7 | Background 8 | ---------- 9 | I created this program because I was unhappy with my MacBook Pro running so hot and it 10 | annoyed me that Apple didn't make any way for end users to set fan preferences. 11 | 12 | This program will allow you to read and write values to the SMC using the AppleSMC kernel 13 | extension. The purpose of this is to show how to talk to the controller. I've made no 14 | effort to make it user friendly, however I'm releasing this in hopes that someone will 15 | take the next logical step and make a nice *free* GUI. I think it's absurd that some 16 | people are trying to charge for simple programs to manipulate this type of data. 17 | 18 | In my testing I've been able to lower the average system temperature by 15C just 19 | by running the fans at a low speed like 3500 RPM, which you can barely hear. 20 | 21 | Usage 22 | ------ 23 | # smc -h 24 | 25 | Apple System Management Control (SMC) tool 0.01 26 | Usage: 27 | ./smc [options] 28 | -f : fan info decoded 29 | -h : help 30 | -k : key to manipulate 31 | -l : list all keys and values 32 | -r : read the value of a key 33 | -w : write the specified value to a key 34 | -v : version 35 | 36 | Fan control 37 | ----------- 38 | To decode: 39 | # smc -f 40 | 41 | To manually query and control: 42 | FNum - tells you how many fans are in the system 43 | 44 | To read data from each fan: 45 | F0Ac - Fan actual speed 46 | F0Mn - Fan minimum speed 47 | F0Mx - Fan maximum speed 48 | F0Sf - Fan safe speed 49 | F0Tg - Fan target speed 50 | FS! - See if fans are in automatic or forced mode 51 | 52 | [Replace 0 with fan #. In the MacBook Pro there two fans so this applies for 0 (left) 53 | and 1 (right).] 54 | 55 | To set a fan to a specific speed: 56 | FS! - Sets "force mode" to fan. Bit 0 (right to left) is fan 0, bit 1 57 | is fan 1, etc 58 | F0Tg - Sets target speed, make sure you fp78 encode it (left shift by 2) 59 | 60 | For example, to force both fans to 3500 RPM: 61 | # python -c "print hex(3500 << 2)" 62 | 0x36b0 63 | # smc -k "FS! " -w 0003 64 | # smc -k F0Tg -w 36b0 65 | # smc -k F1Tg -w 36b0 66 | 67 | ..to force fan 0 to 4000 RPM and leave fan 1 in automatic mode: 68 | # smc -k "FS! " -w 0001 69 | # smc -k F0Tg -w 3e80 70 | 71 | ..to return both fans to automatic mode: 72 | # smc -k "FS! " -w 0000 73 | 74 | Temperature sensors 75 | ------------------- 76 | TB0T 77 | TC0D 78 | TC0P 79 | TM0P 80 | TN0P 81 | Th0H 82 | Ts0P 83 | TN1P 84 | Th1H 85 | 86 | Light sensors 87 | ------------- 88 | ALV0 - Left 89 | ALV1 - Right 90 | 91 | Motion sensors 92 | -------------- 93 | MO_X 94 | MO_Y 95 | MO_Z 96 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Intel only Macbook (OSX) limit maximum battery charge. 2 | ======================== 3 | 4 | Li-ion and polymer batteries (like the one in your MacBook) last the longest when operating between 30 and 80 percent. Keeping your battery at 100% at all times can shorten the lifespan of your notebook significantly. More information can be found here: https://batteryuniversity.com/learn/article/how_to_charge_when_to_charge_table 5 | 6 | Script info 7 | ------------------------ 8 | This is script for changing maximum battery charge value on macbook by setting SMC's value. 9 | It uses *smc-command* binary from smcFanControl project for SMC keys access [smcFanControl](https://github.com/hholtmann/smcFanControl "smcFanControl"). 10 | 11 | Script changes SMC key "BCLM" (Battery control level maximum). Script sets maximum battery charge percent value from 20% to 100%. 12 | 13 | You can check real battery charge level with [coconutbattery](https://www.coconut-flavour.com/coconutbattery/). MacOS shows charge approximately 3-5% greater than real value. 14 | 15 | You can reset macbook's SMC for rollback script changes in case of some problems. 16 | 17 | Tests 18 | ------------------------ 19 | Tested on: 20 | - Macbook Pro 13 (mid 2020, 2 ports), OSX Catalina (10.15.5) 21 | - Macbook Pro 13 (mid 2019, 4 ports), OSX Catalina (10.15.5, 10.15.6) 22 | - Macbook Air 13 (mid 2011), OSX High Sierra 23 | 24 | Requirements 25 | ------------------------ 26 | All commands must be written in Terminal application step-by-step 27 | ``` 28 | # 1. Install command-line tools 29 | xcode-select --install 30 | 31 | # 2. Install Homebrew 32 | ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 33 | 34 | # 3. Install Python3 35 | brew install python3 36 | ``` 37 | 38 | Usage examples 39 | ------------------------ 40 | __Highly recomended turn off OSX Catalina 10.15.5 system battery care function before set limit value!__ Reboot is recommended after changing value. System update can reset SMC, and you will need to start script to set limit again. 41 | 42 | All commands must be called in osx_battery_charge_limit folder. Change folder example: 43 | 44 | ``` 45 | cd ~/Downloads/osx_battery_charge_limit/ 46 | ``` 47 | Usage: 48 | ``` 49 | # Get current charge limit 50 | python3 main.py 51 | python3 main.py -c 52 | 53 | # Set maximum charge level at 65% 54 | sudo python3 main.py -s 65 55 | 56 | # Reset maximum charge level to 100% 57 | sudo python3 main.py -r 58 | ``` 59 | Sometimes homebrew's folders owner need to be fixed in case of some freezing on reboot. 60 | ``` 61 | sudo chown -R "$USER":admin /usr/local/* 62 | ``` 63 | 64 | Warning! 65 | ------------------------ 66 | I do not take any responsibility for any sort of damage in result of using this tool! Alltough this had no negative side effects for me, scripts still taps in some very low level system functions that are not ment to be tampered with. Use it at your own risk! 67 | 68 | Alternatives with GUI: 69 | ------------------------ 70 | - [AlDente](https://github.com/davidwernhart/AlDente) 71 | - [BatteryStatusShow](https://github.com/sicreative/BatteryStatusShow) 72 | - [charge-limiter](https://github.com/godly-devotion/charge-limiter) 73 | - [EternalPower](https://github.com/joelucid/EternalPower) 74 | 75 | Alternatives without GUI: 76 | ------------------------ 77 | - [bclm](https://github.com/zackelia/bclm) 78 | 79 | Other references: 80 | ------------------------ 81 | - [coconutbattery](https://www.coconut-flavour.com/coconutbattery/) 82 | - [smcFanControl](https://github.com/hholtmann/smcFanControl) 83 | - [SMCKit](https://github.com/beltex/SMCKit) 84 | - [libsmc](https://github.com/beltex/libsmc) 85 | - [smcutil](https://github.com/glexey/smcutil) 86 | - [smc_util](https://github.com/alexleigh/smc_util) 87 | - [VirtualSMC](https://github.com/acidanthera/VirtualSMC) 88 | - [osx-cpu-temp](https://github.com/lavoiesl/osx-cpu-temp) 89 | 90 | -------------------------------------------------------------------------------- /smc-command_from_fan_control/smc.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Apple System Management Control (SMC) Tool 3 | * Copyright (C) 2006 devnull 4 | * Portions Copyright (C) 2013 Michael Wilber 5 | * 6 | * This program is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU General Public License 8 | * as published by the Free Software Foundation; either version 2 9 | * of the License, or (at your option) any later version. 10 | 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 19 | */ 20 | 21 | #ifndef __SMC_H__ 22 | #define __SMC_H__ 23 | #endif 24 | 25 | #define CMD_TOOL 26 | #define VERSION "0.01" 27 | 28 | #define OP_NONE 0 29 | #define OP_LIST 1 30 | #define OP_READ 2 31 | #define OP_READ_FAN 3 32 | #define OP_WRITE 4 33 | #define OP_READ_TEMPS 5 34 | 35 | #define KERNEL_INDEX_SMC 2 36 | 37 | #define SMC_CMD_READ_BYTES 5 38 | #define SMC_CMD_WRITE_BYTES 6 39 | #define SMC_CMD_READ_INDEX 8 40 | #define SMC_CMD_READ_KEYINFO 9 41 | #define SMC_CMD_READ_PLIMIT 11 42 | #define SMC_CMD_READ_VERS 12 43 | 44 | #define DATATYPE_FLT "flt " 45 | #define DATATYPE_FP1F "fp1f" 46 | #define DATATYPE_FP4C "fp4c" 47 | #define DATATYPE_FP5B "fp5b" 48 | #define DATATYPE_FP6A "fp6a" 49 | #define DATATYPE_FP79 "fp79" 50 | #define DATATYPE_FP88 "fp88" 51 | #define DATATYPE_FPA6 "fpa6" 52 | #define DATATYPE_FPC4 "fpc4" 53 | #define DATATYPE_FPE2 "fpe2" 54 | 55 | #define DATATYPE_SP1E "sp1e" 56 | #define DATATYPE_SP3C "sp3c" 57 | #define DATATYPE_SP4B "sp4b" 58 | #define DATATYPE_SP5A "sp5a" 59 | #define DATATYPE_SP69 "sp69" 60 | #define DATATYPE_SP78 "sp78" 61 | #define DATATYPE_SP87 "sp87" 62 | #define DATATYPE_SP96 "sp96" 63 | #define DATATYPE_SPB4 "spb4" 64 | #define DATATYPE_SPF0 "spf0" 65 | 66 | #define DATATYPE_UINT8 "ui8 " 67 | #define DATATYPE_UINT16 "ui16" 68 | #define DATATYPE_UINT32 "ui32" 69 | 70 | #define DATATYPE_SI8 "si8 " 71 | #define DATATYPE_SI16 "si16" 72 | 73 | #define DATATYPE_FLT "flt " 74 | 75 | #define DATATYPE_PWM "{pwm" 76 | 77 | typedef struct { 78 | char major; 79 | char minor; 80 | char build; 81 | char reserved[1]; 82 | UInt16 release; 83 | } SMCKeyData_vers_t; 84 | 85 | typedef struct { 86 | UInt16 version; 87 | UInt16 length; 88 | UInt32 cpuPLimit; 89 | UInt32 gpuPLimit; 90 | UInt32 memPLimit; 91 | } SMCKeyData_pLimitData_t; 92 | 93 | typedef struct { 94 | UInt32 dataSize; 95 | UInt32 dataType; 96 | char dataAttributes; 97 | } SMCKeyData_keyInfo_t; 98 | 99 | typedef unsigned char SMCBytes_t[32]; 100 | 101 | typedef struct { 102 | UInt32 key; 103 | SMCKeyData_vers_t vers; 104 | SMCKeyData_pLimitData_t pLimitData; 105 | SMCKeyData_keyInfo_t keyInfo; 106 | char result; 107 | char status; 108 | char data8; 109 | UInt32 data32; 110 | SMCBytes_t bytes; 111 | } SMCKeyData_t; 112 | 113 | typedef char UInt32Char_t[5]; 114 | 115 | typedef struct { 116 | UInt32Char_t key; 117 | UInt32 dataSize; 118 | UInt32Char_t dataType; 119 | SMCBytes_t bytes; 120 | } SMCVal_t; 121 | 122 | UInt32 _strtoul(char *str, int size, int base); 123 | float _strtof(unsigned char *str, int size, int e); 124 | 125 | // Exclude command-line only code from smcFanControl UI 126 | #ifdef CMD_TOOL 127 | 128 | void smc_init(); 129 | void smc_close(); 130 | kern_return_t SMCReadKey(UInt32Char_t key, SMCVal_t *val); 131 | kern_return_t SMCWriteSimple(UInt32Char_t key,char *wvalue,io_connect_t conn); 132 | 133 | #endif //#ifdef CMD_TOOL 134 | 135 | kern_return_t SMCOpen(io_connect_t *conn); 136 | kern_return_t SMCClose(io_connect_t conn); 137 | kern_return_t SMCReadKey2(UInt32Char_t key, SMCVal_t *val,io_connect_t conn); -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | import argparse 5 | import subprocess 6 | import os 7 | import os.path 8 | import re 9 | import sys 10 | import platform 11 | 12 | SMC_UTIL_FROM_APPLE = False 13 | 14 | OUTPUT_RE_SMC_FAN_CONTROL = re.compile(r" BCLM \[([a-z0-9]*)\s*\] ([0-9a-f]+) \(bytes (.+)\)") # " BCLM [ui8 ] 60 (bytes 3c)" 15 | OUTPUT_RE_FROM_APPLE = re.compile(r"[0-9]+") 16 | 17 | PMSET_RE = re.compile(r"VACTDisabled[\s]+0") 18 | 19 | def get_smc_binary_path_from_fan_control(script_directory) -> str: 20 | smc_directory = os.path.join(script_directory, "smc-command_from_fan_control") 21 | 22 | binary_path = os.path.join(smc_directory, "smc") 23 | exists = os.path.exists(binary_path) 24 | 25 | if not exists: 26 | current_dir = os.getcwd() 27 | os.chdir(smc_directory) 28 | out = subprocess.run(["make"], capture_output=True) 29 | os.chdir(current_dir) 30 | if out.returncode != 0: 31 | print("ERROR: SMC build failed!", file=sys.stderr) 32 | print(out.stderr) 33 | exit(1) 34 | 35 | exists = os.path.exists(binary_path) 36 | if not exists: 37 | print("ERROR: SMC binary does not exist at {}!".format(binary_path), file=sys.stderr) 38 | exit(1) 39 | 40 | return binary_path 41 | 42 | 43 | def get_smc_binary_path_from_apple(script_directory) -> str: 44 | smc_directory = os.path.join(script_directory, "smc-command_from_apple") 45 | 46 | binary_path = os.path.join(smc_directory, "smcutil") 47 | exists = os.path.exists(binary_path) 48 | 49 | if not exists: 50 | print("ERROR: SMC binary does not exist at {}!".format(binary_path), file=sys.stderr) 51 | exit(1) 52 | 53 | return binary_path 54 | 55 | 56 | def get_arguments(): 57 | parser = argparse.ArgumentParser(description="Macbook battery charge limit using SMC") 58 | 59 | parser.add_argument("-c", 60 | dest="current", 61 | default=False, 62 | action="store_true", 63 | help="Current limit value") 64 | 65 | parser.add_argument("-r", 66 | dest="reset", 67 | default=False, 68 | action="store_true", 69 | help="Reset on default value (100)") 70 | 71 | parser.add_argument("-s", 72 | dest="set", 73 | type=int, 74 | default=None, 75 | help="Set charge limit in percents, from 20 to 100") 76 | 77 | args = parser.parse_args() 78 | 79 | return args 80 | 81 | 82 | def get_and_check_current_battery_charge_limit(smc_binary_path) -> int: 83 | #./smc -r -k BCLM 84 | if SMC_UTIL_FROM_APPLE: 85 | get_value_out = subprocess.run([smc_binary_path, "-r", "BCLM"], capture_output=True) 86 | else: 87 | get_value_out = subprocess.run([smc_binary_path, "-k", "BCLM", "-r"], capture_output=True) 88 | # print(get_value_out) 89 | if (get_value_out.returncode != 0) or (len(get_value_out.stdout) == 0): 90 | print("ERROR: Battery limit value read failed:", file=sys.stderr) 91 | print(get_value_out.stderr, file=sys.stderr) 92 | exit(1) 93 | 94 | out_string = get_value_out.stdout.decode("utf-8").rstrip("\n") 95 | # print(out_string) 96 | 97 | if SMC_UTIL_FROM_APPLE: 98 | parse_result = OUTPUT_RE_FROM_APPLE.match(out_string) 99 | 100 | if parse_result is None: 101 | error_text = "ERROR: SMC out parse failed\nvalid \"{}\"\ncurrent \"{}\"".format("60%", out_string) 102 | print(error_text, file=sys.stderr) 103 | exit(1) 104 | 105 | current_value = int(parse_result.group(0)) 106 | 107 | current_value_valid = (current_value >= 20) and (current_value <= 100) 108 | if not current_value_valid: 109 | error_text = \ 110 | "ERROR: Invalid SMC output values value = {}\n"\ 111 | "must be: value = {}"\ 112 | .format(current_value, "20 <= val <= 100") 113 | print(error_text, file=sys.stderr) 114 | exit(1) 115 | 116 | else: 117 | parse_result = OUTPUT_RE_SMC_FAN_CONTROL.match(out_string) 118 | 119 | if parse_result is None: 120 | error_text = "ERROR: SMC out parse failed\nvalid \"{}\"\ncurrent \"{}\"".format( 121 | " BCLM [ui8 ] 60 (bytes 3c)", 122 | out_string 123 | ) 124 | print(error_text, file=sys.stderr) 125 | exit(1) 126 | 127 | #print(get_value_out.stdout) 128 | value_type = parse_result.group(1) 129 | current_value = int(parse_result.group(2)) 130 | #bytes_value = parse_result.group(3) 131 | 132 | value_type_valid = (value_type == "ui8") 133 | current_value_valid = (current_value >= 20) and (current_value <= 100) 134 | if not value_type_valid or not current_value_valid: 135 | error_text = \ 136 | "ERROR: Invalid SMC output values, type = {}, value = {}\n"\ 137 | "must be: type = {}, value = {}"\ 138 | .format(value_type, current_value, "ui8", "20 <= val <= 100") 139 | print(error_text, file=sys.stderr) 140 | exit(1) 141 | 142 | return current_value 143 | 144 | 145 | def is_root_user() -> bool: 146 | return (os.geteuid() == 0) 147 | 148 | 149 | def is_system_battery_care_activated()-> bool: 150 | pm_set_out = subprocess.run(["pmset", "-g"], capture_output=True) 151 | if (pm_set_out.returncode != 0) or (len(pm_set_out.stderr) != 0): 152 | print("ERROR: 'pmset -g' command call failed", file=sys.stderr) 153 | exit(1) 154 | 155 | out_string = pm_set_out.stdout.decode("utf-8").rstrip("\n") 156 | # print(out_string) 157 | 158 | result = PMSET_RE.findall(out_string) 159 | # print(result) 160 | 161 | if len(result) >= 1: 162 | return True 163 | else: 164 | return False 165 | 166 | 167 | def set_current_battery_charge_limit(smc_binary_path, value) -> int: 168 | # is_root = is_root_user() 169 | # if not is_root: 170 | # print("ERROR: Set limit must be run as root", file=sys.stderr) 171 | # exit(1) 172 | 173 | if (value > 100) or (value < 20) or (not isinstance(value, int)): 174 | print("ERROR: New limit integer value must be: 20 <= val <= 100", file=sys.stderr) 175 | exit(1) 176 | 177 | system_battery_care_is_active = is_system_battery_care_activated() 178 | if system_battery_care_is_active: 179 | print("ERROR: OSX Catalina 10.15.5 battery care is active. Please, turn off it and try again", file=sys.stderr) 180 | exit(1) 181 | 182 | hex_value = hex(value).replace("0x", "") 183 | if hex_value is None: 184 | print("ERROR: Value convert to hex failed", file=sys.stderr) 185 | exit(1) 186 | if len(hex_value) != 2: 187 | print("ERROR: Value convert to hex failed, too short hex: {}".format(hex_value), file=sys.stderr) 188 | exit(1) 189 | 190 | if SMC_UTIL_FROM_APPLE: 191 | # sudo ./smcutil -w BCLM 3c 192 | set_value_out = subprocess.run(["sudo", smc_binary_path, "-w", "BCLM", hex_value], capture_output=True) 193 | else: 194 | # sudo ./smc -k BCLM -w 3c 195 | set_value_out = subprocess.run(["sudo", smc_binary_path, "-k", "BCLM", "-w", hex_value], capture_output=True) 196 | 197 | # print(set_value_out) 198 | if (set_value_out.returncode != 0): 199 | print("ERROR: Battery limit value set failed:", file=sys.stderr) 200 | print(set_value_out.stderr, file=sys.stderr) 201 | exit(1) 202 | 203 | return True 204 | 205 | 206 | def change_battery_limit_value(smc_binary_path, value): 207 | current_value = get_and_check_current_battery_charge_limit(smc_binary_path) 208 | if current_value is None: 209 | print("ERROR: Battery limit previous value read failed", file=sys.stderr) 210 | exit(1) 211 | 212 | print("Current battery charge limit is {}%".format(current_value)) 213 | 214 | success = set_current_battery_charge_limit(smc_binary_path, value) 215 | if success: 216 | new_value = get_and_check_current_battery_charge_limit(smc_binary_path) 217 | print("New battery charge limit is {}%\n".format(new_value)) 218 | print('Please reboot your notebook and check applied limit value with "-c" flag!\n') 219 | else: 220 | print("ERROR: Battery limit value set failed", file=sys.stderr) 221 | exit(1) 222 | 223 | 224 | def print_current_limit(smc_binary_path): 225 | current_value = get_and_check_current_battery_charge_limit(smc_binary_path) 226 | print("Current battery charge limit is {}%".format(current_value)) 227 | 228 | 229 | def main(): 230 | current_system = platform.system() 231 | if current_system != "Darwin": 232 | print("ERROR: Script must be run using OSX platform only", file=sys.stderr) 233 | exit(1) 234 | 235 | # Script directory 236 | script_directory = os.path.dirname(os.path.realpath(__file__)) 237 | 238 | # SMC binary path 239 | if SMC_UTIL_FROM_APPLE: 240 | smc_binary_path = get_smc_binary_path_from_apple(script_directory) 241 | else: 242 | smc_binary_path = get_smc_binary_path_from_fan_control(script_directory) 243 | 244 | # Arguments 245 | args = get_arguments() 246 | 247 | # Perform command 248 | if args.current: 249 | print_current_limit(smc_binary_path) 250 | elif args.set: 251 | change_battery_limit_value(smc_binary_path, args.set) 252 | elif args.reset: 253 | change_battery_limit_value(smc_binary_path, 100) 254 | else: 255 | print_current_limit(smc_binary_path) 256 | 257 | 258 | if __name__ == "__main__": 259 | main() -------------------------------------------------------------------------------- /smc-command_from_fan_control/LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /smc-command_from_fan_control/smc.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Apple System Management Control (SMC) Tool 3 | * Copyright (C) 2006 devnull 4 | * Portions Copyright (C) 2013 Michael Wilber 5 | * 6 | * This program is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU General Public License 8 | * as published by the Free Software Foundation; either version 2 9 | * of the License, or (at your option) any later version. 10 | 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include "smc.h" 27 | #include 28 | 29 | // Cache the keyInfo to lower the energy impact of SMCReadKey() / SMCReadKey2() 30 | #define KEY_INFO_CACHE_SIZE 100 31 | struct { 32 | UInt32 key; 33 | SMCKeyData_keyInfo_t keyInfo; 34 | } g_keyInfoCache[KEY_INFO_CACHE_SIZE]; 35 | 36 | int g_keyInfoCacheCount = 0; 37 | OSSpinLock g_keyInfoSpinLock = 0; 38 | 39 | kern_return_t SMCCall2(int index, SMCKeyData_t *inputStructure, SMCKeyData_t *outputStructure, io_connect_t conn); 40 | 41 | #pragma mark C Helpers 42 | 43 | UInt32 _strtoul(char *str, int size, int base) 44 | { 45 | UInt32 total = 0; 46 | int i; 47 | 48 | for (i = 0; i < size; i++) 49 | { 50 | if (base == 16) 51 | total += str[i] << (size - 1 - i) * 8; 52 | else 53 | total += ((unsigned char) (str[i]) << (size - 1 - i) * 8); 54 | } 55 | return total; 56 | } 57 | 58 | void _ultostr(char *str, UInt32 val) 59 | { 60 | str[0] = '\0'; 61 | sprintf(str, "%c%c%c%c", 62 | (unsigned int) val >> 24, 63 | (unsigned int) val >> 16, 64 | (unsigned int) val >> 8, 65 | (unsigned int) val); 66 | } 67 | 68 | float _strtof(unsigned char *str, int size, int e) 69 | { 70 | float total = 0; 71 | int i; 72 | 73 | for (i = 0; i < size; i++) 74 | { 75 | if (i == (size - 1)) 76 | total += (str[i] & 0xff) >> e; 77 | else 78 | total += str[i] << (size - 1 - i) * (8 - e); 79 | } 80 | 81 | total += (str[size-1] & 0x03) * 0.25; 82 | 83 | return total; 84 | } 85 | 86 | void printFLT(SMCVal_t val) 87 | { 88 | float fval; 89 | memcpy(&fval,val.bytes,sizeof(float)); 90 | printf("%.0f ", fval); 91 | } 92 | 93 | void printFP1F(SMCVal_t val) 94 | { 95 | printf("%.5f ", ntohs(*(UInt16*)val.bytes) / 32768.0); 96 | } 97 | 98 | void printFP4C(SMCVal_t val) 99 | { 100 | printf("%.5f ", ntohs(*(UInt16*)val.bytes) / 4096.0); 101 | } 102 | 103 | void printFP5B(SMCVal_t val) 104 | { 105 | printf("%.5f ", ntohs(*(UInt16*)val.bytes) / 2048.0); 106 | } 107 | 108 | void printFP6A(SMCVal_t val) 109 | { 110 | printf("%.4f ", ntohs(*(UInt16*)val.bytes) / 1024.0); 111 | } 112 | 113 | void printFP79(SMCVal_t val) 114 | { 115 | printf("%.4f ", ntohs(*(UInt16*)val.bytes) / 512.0); 116 | } 117 | 118 | void printFP88(SMCVal_t val) 119 | { 120 | printf("%.3f ", ntohs(*(UInt16*)val.bytes) / 256.0); 121 | } 122 | 123 | void printFPA6(SMCVal_t val) 124 | { 125 | printf("%.2f ", ntohs(*(UInt16*)val.bytes) / 64.0); 126 | } 127 | 128 | void printFPC4(SMCVal_t val) 129 | { 130 | printf("%.2f ", ntohs(*(UInt16*)val.bytes) / 16.0); 131 | } 132 | 133 | void printFPE2(SMCVal_t val) 134 | { 135 | printf("%.2f ", ntohs(*(UInt16*)val.bytes) / 4.0); 136 | } 137 | 138 | void printUInt(SMCVal_t val) 139 | { 140 | printf("%u ", (unsigned int) _strtoul((char *)val.bytes, val.dataSize, 10)); 141 | } 142 | 143 | void printSP1E(SMCVal_t val) 144 | { 145 | printf("%.5f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 16384.0); 146 | } 147 | 148 | void printSP3C(SMCVal_t val) 149 | { 150 | printf("%.5f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 4096.0); 151 | } 152 | 153 | void printSP4B(SMCVal_t val) 154 | { 155 | printf("%.4f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 2048.0); 156 | } 157 | 158 | void printSP5A(SMCVal_t val) 159 | { 160 | printf("%.4f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 1024.0); 161 | } 162 | 163 | void printSP69(SMCVal_t val) 164 | { 165 | printf("%.3f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 512.0); 166 | } 167 | 168 | void printSP78(SMCVal_t val) 169 | { 170 | printf("%.3f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 256.0); 171 | } 172 | 173 | void printSP87(SMCVal_t val) 174 | { 175 | printf("%.3f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 128.0); 176 | } 177 | 178 | void printSP96(SMCVal_t val) 179 | { 180 | printf("%.2f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 64.0); 181 | } 182 | 183 | void printSPB4(SMCVal_t val) 184 | { 185 | printf("%.2f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 16.0); 186 | } 187 | 188 | void printSPF0(SMCVal_t val) 189 | { 190 | printf("%.0f ", (float)ntohs(*(UInt16*)val.bytes)); 191 | } 192 | 193 | void printSI8(SMCVal_t val) 194 | { 195 | printf("%d ", (signed char)*val.bytes); 196 | } 197 | 198 | void printSI16(SMCVal_t val) 199 | { 200 | printf("%d ", ntohs(*(SInt16*)val.bytes)); 201 | } 202 | 203 | void printPWM(SMCVal_t val) 204 | { 205 | printf("%.1f%% ", ntohs(*(UInt16*)val.bytes) * 100 / 65536.0); 206 | } 207 | 208 | 209 | void printBytesHex(SMCVal_t val) 210 | { 211 | int i; 212 | 213 | printf("(bytes"); 214 | for (i = 0; i < val.dataSize; i++) 215 | printf(" %02x", (unsigned char) val.bytes[i]); 216 | printf(")\n"); 217 | } 218 | 219 | void printVal(SMCVal_t val) 220 | { 221 | printf(" %-4s [%-4s] ", val.key, val.dataType); 222 | if (val.dataSize > 0) 223 | { 224 | if ((strcmp(val.dataType, DATATYPE_UINT8) == 0) || 225 | (strcmp(val.dataType, DATATYPE_UINT16) == 0) || 226 | (strcmp(val.dataType, DATATYPE_UINT32) == 0)) 227 | printUInt(val); 228 | else if (strcmp(val.dataType, DATATYPE_FLT) == 0 && val.dataSize == 4) 229 | printFLT(val); 230 | else if (strcmp(val.dataType, DATATYPE_FP1F) == 0 && val.dataSize == 2) 231 | printFP1F(val); 232 | else if (strcmp(val.dataType, DATATYPE_FP4C) == 0 && val.dataSize == 2) 233 | printFP4C(val); 234 | else if (strcmp(val.dataType, DATATYPE_FP5B) == 0 && val.dataSize == 2) 235 | printFP5B(val); 236 | else if (strcmp(val.dataType, DATATYPE_FP6A) == 0 && val.dataSize == 2) 237 | printFP6A(val); 238 | else if (strcmp(val.dataType, DATATYPE_FP79) == 0 && val.dataSize == 2) 239 | printFP79(val); 240 | else if (strcmp(val.dataType, DATATYPE_FP88) == 0 && val.dataSize == 2) 241 | printFP88(val); 242 | else if (strcmp(val.dataType, DATATYPE_FPA6) == 0 && val.dataSize == 2) 243 | printFPA6(val); 244 | else if (strcmp(val.dataType, DATATYPE_FPC4) == 0 && val.dataSize == 2) 245 | printFPC4(val); 246 | else if (strcmp(val.dataType, DATATYPE_FPE2) == 0 && val.dataSize == 2) 247 | printFPE2(val); 248 | else if (strcmp(val.dataType, DATATYPE_SP1E) == 0 && val.dataSize == 2) 249 | printSP1E(val); 250 | else if (strcmp(val.dataType, DATATYPE_SP3C) == 0 && val.dataSize == 2) 251 | printSP3C(val); 252 | else if (strcmp(val.dataType, DATATYPE_SP4B) == 0 && val.dataSize == 2) 253 | printSP4B(val); 254 | else if (strcmp(val.dataType, DATATYPE_SP5A) == 0 && val.dataSize == 2) 255 | printSP5A(val); 256 | else if (strcmp(val.dataType, DATATYPE_SP69) == 0 && val.dataSize == 2) 257 | printSP69(val); 258 | else if (strcmp(val.dataType, DATATYPE_SP78) == 0 && val.dataSize == 2) 259 | printSP78(val); 260 | else if (strcmp(val.dataType, DATATYPE_SP87) == 0 && val.dataSize == 2) 261 | printSP87(val); 262 | else if (strcmp(val.dataType, DATATYPE_SP96) == 0 && val.dataSize == 2) 263 | printSP96(val); 264 | else if (strcmp(val.dataType, DATATYPE_SPB4) == 0 && val.dataSize == 2) 265 | printSPB4(val); 266 | else if (strcmp(val.dataType, DATATYPE_SPF0) == 0 && val.dataSize == 2) 267 | printSPF0(val); 268 | else if (strcmp(val.dataType, DATATYPE_SI8) == 0 && val.dataSize == 1) 269 | printSI8(val); 270 | else if (strcmp(val.dataType, DATATYPE_SI16) == 0 && val.dataSize == 2) 271 | printSI16(val); 272 | else if (strcmp(val.dataType, DATATYPE_PWM) == 0 && val.dataSize == 2) 273 | printPWM(val); 274 | else if (strcmp(val.dataType, DATATYPE_FLT) == 0 && val.dataSize == 4) 275 | printFLT(val); 276 | 277 | printBytesHex(val); 278 | } 279 | else 280 | { 281 | printf("no data\n"); 282 | } 283 | } 284 | 285 | #pragma mark Shared SMC functions 286 | 287 | kern_return_t SMCOpen(io_connect_t *conn) 288 | { 289 | kern_return_t result; 290 | mach_port_t masterPort; 291 | io_iterator_t iterator; 292 | io_object_t device; 293 | 294 | IOMasterPort(MACH_PORT_NULL, &masterPort); 295 | 296 | CFMutableDictionaryRef matchingDictionary = IOServiceMatching("AppleSMC"); 297 | result = IOServiceGetMatchingServices(masterPort, matchingDictionary, &iterator); 298 | if (result != kIOReturnSuccess) 299 | { 300 | printf("Error: IOServiceGetMatchingServices() = %08x\n", result); 301 | return 1; 302 | } 303 | 304 | device = IOIteratorNext(iterator); 305 | IOObjectRelease(iterator); 306 | if (device == 0) 307 | { 308 | printf("Error: no SMC found\n"); 309 | return 1; 310 | } 311 | 312 | result = IOServiceOpen(device, mach_task_self(), 0, conn); 313 | IOObjectRelease(device); 314 | if (result != kIOReturnSuccess) 315 | { 316 | printf("Error: IOServiceOpen() = %08x\n", result); 317 | return 1; 318 | } 319 | 320 | return kIOReturnSuccess; 321 | } 322 | 323 | kern_return_t SMCClose(io_connect_t conn) 324 | { 325 | return IOServiceClose(conn); 326 | } 327 | 328 | kern_return_t SMCCall2(int index, SMCKeyData_t *inputStructure, SMCKeyData_t *outputStructure,io_connect_t conn) 329 | { 330 | size_t structureInputSize; 331 | size_t structureOutputSize; 332 | structureInputSize = sizeof(SMCKeyData_t); 333 | structureOutputSize = sizeof(SMCKeyData_t); 334 | 335 | return IOConnectCallStructMethod(conn, index, inputStructure, structureInputSize, outputStructure, &structureOutputSize); 336 | } 337 | 338 | // Provides key info, using a cache to dramatically improve the energy impact of smcFanControl 339 | kern_return_t SMCGetKeyInfo(UInt32 key, SMCKeyData_keyInfo_t* keyInfo, io_connect_t conn) 340 | { 341 | SMCKeyData_t inputStructure; 342 | SMCKeyData_t outputStructure; 343 | kern_return_t result = kIOReturnSuccess; 344 | int i = 0; 345 | 346 | OSSpinLockLock(&g_keyInfoSpinLock); 347 | 348 | for (; i < g_keyInfoCacheCount; ++i) 349 | { 350 | if (key == g_keyInfoCache[i].key) 351 | { 352 | *keyInfo = g_keyInfoCache[i].keyInfo; 353 | break; 354 | } 355 | } 356 | 357 | if (i == g_keyInfoCacheCount) 358 | { 359 | // Not in cache, must look it up. 360 | memset(&inputStructure, 0, sizeof(inputStructure)); 361 | memset(&outputStructure, 0, sizeof(outputStructure)); 362 | 363 | inputStructure.key = key; 364 | inputStructure.data8 = SMC_CMD_READ_KEYINFO; 365 | 366 | result = SMCCall2(KERNEL_INDEX_SMC, &inputStructure, &outputStructure, conn); 367 | if (result == kIOReturnSuccess) 368 | { 369 | *keyInfo = outputStructure.keyInfo; 370 | if (g_keyInfoCacheCount < KEY_INFO_CACHE_SIZE) 371 | { 372 | g_keyInfoCache[g_keyInfoCacheCount].key = key; 373 | g_keyInfoCache[g_keyInfoCacheCount].keyInfo = outputStructure.keyInfo; 374 | ++g_keyInfoCacheCount; 375 | } 376 | } 377 | } 378 | 379 | OSSpinLockUnlock(&g_keyInfoSpinLock); 380 | 381 | return result; 382 | } 383 | 384 | kern_return_t SMCReadKey2(UInt32Char_t key, SMCVal_t *val,io_connect_t conn) 385 | { 386 | kern_return_t result; 387 | SMCKeyData_t inputStructure; 388 | SMCKeyData_t outputStructure; 389 | 390 | memset(&inputStructure, 0, sizeof(SMCKeyData_t)); 391 | memset(&outputStructure, 0, sizeof(SMCKeyData_t)); 392 | memset(val, 0, sizeof(SMCVal_t)); 393 | 394 | inputStructure.key = _strtoul(key, 4, 16); 395 | sprintf(val->key, key); 396 | 397 | result = SMCGetKeyInfo(inputStructure.key, &outputStructure.keyInfo, conn); 398 | if (result != kIOReturnSuccess) 399 | { 400 | return result; 401 | } 402 | 403 | val->dataSize = outputStructure.keyInfo.dataSize; 404 | _ultostr(val->dataType, outputStructure.keyInfo.dataType); 405 | inputStructure.keyInfo.dataSize = val->dataSize; 406 | inputStructure.data8 = SMC_CMD_READ_BYTES; 407 | 408 | result = SMCCall2(KERNEL_INDEX_SMC, &inputStructure, &outputStructure,conn); 409 | if (result != kIOReturnSuccess) 410 | { 411 | return result; 412 | } 413 | 414 | memcpy(val->bytes, outputStructure.bytes, sizeof(outputStructure.bytes)); 415 | 416 | return kIOReturnSuccess; 417 | } 418 | 419 | #pragma mark Command line only 420 | // Exclude command-line only code from smcFanControl UI 421 | #ifdef CMD_TOOL_BUILD 422 | 423 | io_connect_t g_conn = 0; 424 | 425 | void smc_init(){ 426 | SMCOpen(&g_conn); 427 | } 428 | 429 | void smc_close(){ 430 | SMCClose(g_conn); 431 | } 432 | 433 | kern_return_t SMCCall(int index, SMCKeyData_t *inputStructure, SMCKeyData_t *outputStructure) 434 | { 435 | return SMCCall2(index, inputStructure, outputStructure, g_conn); 436 | } 437 | 438 | kern_return_t SMCReadKey(UInt32Char_t key, SMCVal_t *val) 439 | { 440 | return SMCReadKey2(key, val, g_conn); 441 | } 442 | 443 | kern_return_t SMCWriteKey2(SMCVal_t writeVal, io_connect_t conn) 444 | { 445 | kern_return_t result; 446 | SMCKeyData_t inputStructure; 447 | SMCKeyData_t outputStructure; 448 | 449 | SMCVal_t readVal; 450 | 451 | result = SMCReadKey2(writeVal.key, &readVal,conn); 452 | if (result != kIOReturnSuccess) 453 | return result; 454 | 455 | if (readVal.dataSize != writeVal.dataSize) 456 | return kIOReturnError; 457 | 458 | memset(&inputStructure, 0, sizeof(SMCKeyData_t)); 459 | memset(&outputStructure, 0, sizeof(SMCKeyData_t)); 460 | 461 | inputStructure.key = _strtoul(writeVal.key, 4, 16); 462 | inputStructure.data8 = SMC_CMD_WRITE_BYTES; 463 | inputStructure.keyInfo.dataSize = writeVal.dataSize; 464 | memcpy(inputStructure.bytes, writeVal.bytes, sizeof(writeVal.bytes)); 465 | result = SMCCall2(KERNEL_INDEX_SMC, &inputStructure, &outputStructure,conn); 466 | 467 | if (result != kIOReturnSuccess) 468 | return result; 469 | return kIOReturnSuccess; 470 | } 471 | 472 | kern_return_t SMCWriteKey(SMCVal_t writeVal) 473 | { 474 | return SMCWriteKey2(writeVal, g_conn); 475 | } 476 | 477 | UInt32 SMCReadIndexCount(void) 478 | { 479 | SMCVal_t val; 480 | 481 | SMCReadKey("#KEY", &val); 482 | return _strtoul((char *)val.bytes, val.dataSize, 10); 483 | } 484 | 485 | kern_return_t SMCPrintAll(void) 486 | { 487 | kern_return_t result; 488 | SMCKeyData_t inputStructure; 489 | SMCKeyData_t outputStructure; 490 | 491 | int totalKeys, i; 492 | UInt32Char_t key; 493 | SMCVal_t val; 494 | 495 | totalKeys = SMCReadIndexCount(); 496 | for (i = 0; i < totalKeys; i++) 497 | { 498 | memset(&inputStructure, 0, sizeof(SMCKeyData_t)); 499 | memset(&outputStructure, 0, sizeof(SMCKeyData_t)); 500 | memset(&val, 0, sizeof(SMCVal_t)); 501 | 502 | inputStructure.data8 = SMC_CMD_READ_INDEX; 503 | inputStructure.data32 = i; 504 | 505 | result = SMCCall(KERNEL_INDEX_SMC, &inputStructure, &outputStructure); 506 | if (result != kIOReturnSuccess) 507 | continue; 508 | 509 | _ultostr(key, outputStructure.key); 510 | 511 | SMCReadKey(key, &val); 512 | printVal(val); 513 | } 514 | 515 | return kIOReturnSuccess; 516 | } 517 | 518 | 519 | //Fix me with other types 520 | float getFloatFromVal(SMCVal_t val) 521 | { 522 | float fval = -1.0f; 523 | 524 | if (val.dataSize > 0) 525 | { 526 | if (strcmp(val.dataType, DATATYPE_FLT) == 0 && val.dataSize == 4) { 527 | memcpy(&fval,val.bytes,sizeof(float)); 528 | } 529 | else if (strcmp(val.dataType, DATATYPE_FPE2) == 0 && val.dataSize == 2) { 530 | fval = _strtof(val.bytes, val.dataSize, 2); 531 | } 532 | else if (strcmp(val.dataType, DATATYPE_UINT16) == 0 && val.dataSize == 2) { 533 | fval = (float)_strtoul((char *)val.bytes, val.dataSize, 10); 534 | } 535 | else if (strcmp(val.dataType, DATATYPE_UINT8) == 0 && val.dataSize == 1) { 536 | fval = (float)_strtoul((char *)val.bytes, val.dataSize, 10); 537 | } 538 | } 539 | 540 | return fval; 541 | } 542 | 543 | kern_return_t SMCPrintFans(void) 544 | { 545 | kern_return_t result; 546 | SMCVal_t val; 547 | UInt32Char_t key; 548 | int totalFans, i; 549 | 550 | result = SMCReadKey("FNum", &val); 551 | if (result != kIOReturnSuccess) 552 | return kIOReturnError; 553 | 554 | totalFans = _strtoul((char *)val.bytes, val.dataSize, 10); 555 | printf("Total fans in system: %d\n", totalFans); 556 | 557 | for (i = 0; i < totalFans; i++) 558 | { 559 | printf("\nFan #%d:\n", i); 560 | sprintf(key, "F%dID", i); 561 | SMCReadKey(key, &val); 562 | if(val.dataSize > 0) { 563 | printf(" Fan ID : %s\n", val.bytes+4); 564 | } 565 | sprintf(key, "F%dAc", i); 566 | SMCReadKey(key, &val); 567 | printf(" Actual speed : %.0f\n", getFloatFromVal(val)); 568 | sprintf(key, "F%dMn", i); 569 | SMCReadKey(key, &val); 570 | printf(" Minimum speed: %.0f\n", getFloatFromVal(val)); 571 | sprintf(key, "F%dMx", i); 572 | SMCReadKey(key, &val); 573 | printf(" Maximum speed: %.0f\n", getFloatFromVal(val)); 574 | sprintf(key, "F%dSf", i); 575 | SMCReadKey(key, &val); 576 | printf(" Safe speed : %.0f\n", getFloatFromVal(val)); 577 | sprintf(key, "F%dTg", i); 578 | SMCReadKey(key, &val); 579 | printf(" Target speed : %.0f\n", getFloatFromVal(val)); 580 | SMCReadKey("FS! ", &val); 581 | if(val.dataSize > 0) { 582 | if ((_strtoul((char *)val.bytes, 2, 16) & (1 << i)) == 0) 583 | printf(" Mode : auto\n"); 584 | else 585 | printf(" Mode : forced\n"); 586 | } 587 | else { 588 | sprintf(key, "F%dMd", i); 589 | SMCReadKey(key, &val); 590 | if (getFloatFromVal(val)) 591 | printf(" Mode : forced\n"); 592 | else 593 | printf(" Mode : auto\n"); 594 | } 595 | } 596 | 597 | return kIOReturnSuccess; 598 | } 599 | 600 | kern_return_t SMCPrintTemps(void) 601 | { 602 | kern_return_t result; 603 | SMCKeyData_t inputStructure; 604 | SMCKeyData_t outputStructure; 605 | 606 | int totalKeys, i; 607 | UInt32Char_t key; 608 | SMCVal_t val; 609 | 610 | totalKeys = SMCReadIndexCount(); 611 | for (i = 0; i < totalKeys; i++) 612 | { 613 | memset(&inputStructure, 0, sizeof(SMCKeyData_t)); 614 | memset(&outputStructure, 0, sizeof(SMCKeyData_t)); 615 | memset(&val, 0, sizeof(SMCVal_t)); 616 | 617 | inputStructure.data8 = SMC_CMD_READ_INDEX; 618 | inputStructure.data32 = i; 619 | 620 | result = SMCCall(KERNEL_INDEX_SMC, &inputStructure, &outputStructure); 621 | if (result != kIOReturnSuccess) 622 | continue; 623 | 624 | _ultostr(key, outputStructure.key); 625 | if ( key[0] != 'T' ) 626 | continue; 627 | 628 | SMCReadKey(key, &val); 629 | //printVal(val); 630 | if (strcmp(val.dataType, DATATYPE_SP78) == 0 && val.dataSize == 2) { 631 | printf("%-4s ", val.key); 632 | printSP78(val); 633 | printf("\n"); 634 | } 635 | } 636 | 637 | return kIOReturnSuccess; 638 | } 639 | 640 | void usage(char* prog) 641 | { 642 | printf("Apple System Management Control (SMC) tool %s\n", VERSION); 643 | printf("Usage:\n"); 644 | printf("%s [options]\n", prog); 645 | printf(" -f : fan info decoded\n"); 646 | printf(" -t : list all temperatures\n"); 647 | printf(" -h : help\n"); 648 | printf(" -k : key to manipulate\n"); 649 | printf(" -l : list all keys and values\n"); 650 | printf(" -r : read the value of a key\n"); 651 | printf(" -w : write the specified value to a key\n"); 652 | printf(" -v : version\n"); 653 | printf("\n"); 654 | } 655 | 656 | kern_return_t SMCWriteSimple(UInt32Char_t key, char *wvalue, io_connect_t conn) 657 | { 658 | kern_return_t result; 659 | SMCVal_t val; 660 | int i; 661 | char c[3]; 662 | for (i = 0; i < strlen(wvalue); i++) 663 | { 664 | sprintf(c, "%c%c", wvalue[i * 2], wvalue[(i * 2) + 1]); 665 | val.bytes[i] = (int) strtol(c, NULL, 16); 666 | } 667 | val.dataSize = i / 2; 668 | sprintf(val.key, key); 669 | result = SMCWriteKey2(val, conn); 670 | if (result != kIOReturnSuccess) 671 | printf("Error: SMCWriteKey() = %08x\n", result); 672 | 673 | 674 | return result; 675 | } 676 | 677 | int main(int argc, char *argv[]) 678 | { 679 | int c; 680 | extern char *optarg; 681 | 682 | kern_return_t result; 683 | int op = OP_NONE; 684 | UInt32Char_t key = { 0 }; 685 | SMCVal_t val; 686 | 687 | while ((c = getopt(argc, argv, "fthk:lrw:v")) != -1) 688 | { 689 | switch(c) 690 | { 691 | case 'f': 692 | op = OP_READ_FAN; 693 | break; 694 | case 't': 695 | op = OP_READ_TEMPS; 696 | break; 697 | case 'k': 698 | strncpy(key, optarg, sizeof(key)); //fix for buffer overflow 699 | key[sizeof(key) - 1] = '\0'; 700 | break; 701 | case 'l': 702 | op = OP_LIST; 703 | break; 704 | case 'r': 705 | op = OP_READ; 706 | break; 707 | case 'v': 708 | printf("%s\n", VERSION); 709 | return 0; 710 | break; 711 | case 'w': 712 | op = OP_WRITE; 713 | { 714 | int i; 715 | char c[3]; 716 | for (i = 0; i < strlen(optarg); i++) 717 | { 718 | sprintf(c, "%c%c", optarg[i * 2], optarg[(i * 2) + 1]); 719 | val.bytes[i] = (int) strtol(c, NULL, 16); 720 | } 721 | val.dataSize = i / 2; 722 | if ((val.dataSize * 2) != strlen(optarg)) 723 | { 724 | printf("Error: value is not valid\n"); 725 | return 1; 726 | } 727 | } 728 | break; 729 | case 'h': 730 | case '?': 731 | op = OP_NONE; 732 | break; 733 | } 734 | } 735 | 736 | if (op == OP_NONE) 737 | { 738 | usage(argv[0]); 739 | return 1; 740 | } 741 | 742 | smc_init(); 743 | 744 | switch(op) 745 | { 746 | case OP_LIST: 747 | result = SMCPrintAll(); 748 | if (result != kIOReturnSuccess) 749 | printf("Error: SMCPrintAll() = %08x\n", result); 750 | break; 751 | case OP_READ: 752 | if (strlen(key) > 0) 753 | { 754 | result = SMCReadKey(key, &val); 755 | if (result != kIOReturnSuccess) 756 | printf("Error: SMCReadKey() = %08x\n", result); 757 | else 758 | printVal(val); 759 | } 760 | else 761 | { 762 | printf("Error: specify a key to read\n"); 763 | } 764 | break; 765 | case OP_READ_FAN: 766 | result = SMCPrintFans(); 767 | if (result != kIOReturnSuccess) 768 | printf("Error: SMCPrintFans() = %08x\n", result); 769 | break; 770 | case OP_READ_TEMPS: 771 | result = SMCPrintTemps(); 772 | if (result != kIOReturnSuccess) 773 | printf("Error: SMCPrintFans() = %08x\n", result); 774 | break; 775 | case OP_WRITE: 776 | if (strlen(key) > 0) 777 | { 778 | sprintf(val.key, key); 779 | result = SMCWriteKey(val); 780 | if (result != kIOReturnSuccess) 781 | printf("Error: SMCWriteKey() = %08x\n", result); 782 | } 783 | else 784 | { 785 | printf("Error: specify a key to write\n"); 786 | } 787 | break; 788 | } 789 | 790 | smc_close(); 791 | return 0; 792 | } 793 | #endif //#ifdef CMD_TOOL --------------------------------------------------------------------------------