Minor refactor: code clean-up & make it more readable (#695)

* Clean code

* Back

* Clean code

* Back

* Clean code

* Change arch based detection
This commit is contained in:
Angel 2024-05-12 16:16:40 +02:00 committed by GitHub
parent a79ec81709
commit cc6d98d8b1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
20 changed files with 680 additions and 1152 deletions

View File

@ -5,110 +5,76 @@
cd "$(dirname "$(readlink -f "$0")")" || exit 1 cd "$(dirname "$(readlink -f "$0")")" || exit 1
# check if lsb_release exists on the system before using it COLOUMNS="`tput cols`"
if command -v lsb_release > /dev/null MID="$((COLOUMNS / 2))"
then
distro="$(lsb_release -is)"
release="$(lsb_release -rs)"
codename="$(lsb_release -cs)"
fi
APPLICATIONS_PATH="/usr/share/applications"
VENV_PATH="/opt/auto-cpufreq"
# functions SHARE_DIR="/usr/local/share/auto-cpufreq/"
#separator AUTO_CPUFREQ_FILE="/usr/local/bin/auto-cpufreq"
function separator { AUTO_CPUFREQ_GTK_FILE=$AUTO_CPUFREQ_FILE-gtk
local COLOUMNS="`tput cols`" AUTO_CPUFREQ_GTK_DESKTOP_FILE="$(basename $AUTO_CPUFREQ_GTK_FILE).desktop"
echo -e "\n"
printf "%0.s─" $(seq $COLOUMNS)
echo -e "\n"
}
# root check IMG_FILE="/usr/share/pixmaps/auto-cpufreq.png"
function root_check { ORG_FILE="/usr/share/polkit-1/actions/org.auto-cpufreq.pkexec.policy"
if ((EUID != 0)); then
separator
echo -e "\nMust be run as root (i.e: 'sudo $0')."
separator
exit 1
fi
}
function header { function header {
local COLOUMNS="`tput cols`" echo
MID="$((COLOUMNS / 2))" printf "%0.s─" $(seq $((MID-(${#1}/2)-2)))
HEADER="$1" printf " $1 "
printf "%0.s─" $(seq $((MID-(${#HEADER}/2)- 1))) printf "%0.s─" $(seq $((MID-(${#1}/2)-2)))
echo -n " $HEADER " echo; echo
printf "%0.s─" $(seq $((MID-(${#HEADER}/2)- 1)))
echo -e "\n"
return
} }
# tool install function ask_operation {
function install { header "auto-cpufreq installer"
git config --global --add safe.directory $(pwd) echo "Welcome to auto-cpufreq tool installer."; echo
python -m pip install . read -p "Select a key [I]nstall/[R]emove or press ctrl+c to quit: " answer
mkdir -p /usr/local/share/auto-cpufreq/
cp -r scripts/ /usr/local/share/auto-cpufreq/
cp -r images/ /usr/local/share/auto-cpufreq/
cp images/icon.png /usr/share/pixmaps/auto-cpufreq.png
cp scripts/org.auto-cpufreq.pkexec.policy /usr/share/polkit-1/actions
# this is necessary since we need this script before we can run auto-cpufreq itself
cp scripts/auto-cpufreq-venv-wrapper /usr/local/bin/auto-cpufreq
cp scripts/start_app /usr/local/bin/auto-cpufreq-gtk
chmod a+x /usr/local/bin/auto-cpufreq
chmod a+x /usr/local/bin/auto-cpufreq-gtk
desktop-file-install --dir=/usr/share/applications scripts/auto-cpufreq-gtk.desktop
update-desktop-database /usr/share/applications
}
# First argument is the distro
function detected_distro {
echo -e "\nDetected $1 distribution"
separator
echo -e "\nSetting up Python environment\n"
} }
function manual_install { function manual_install {
echo -e " if command -v lsb_release > /dev/null; then
Didn't detect Debian or RedHat or Arch based distro. distro="$(lsb_release -is)"
release="$(lsb_release -rs)"
codename="$(lsb_release -cs)"
fi
To complete installation, you need to: echo "Didn't detect Debian or RedHat or Arch based distro."; echo
Install: python3, pip3, python3-setuptools, gobject-introspection, cairo (or cairo-devel), gcc, and gtk3 echo "To complete installation, you need to:"
echo "Install: python3, pip3, python3-setuptools, gobject-introspection, cairo (or cairo-devel), gcc, and gtk3"; echo
echo "Install necessary Python packages:"
echo "pip3 install psutil click distro power requests PyGObject"
echo "Run following sequence of lines:"; echo
echo "-----"; echo
echo "pip3 install ."
echo "mkdir -p $SHARE_DIR"
echo "cp -r scripts/ $SHARE_DIR"; echo
echo "-----"; echo
echo "After which tool is installed, for full list of options run:";echo
echo "auto-cpufreq --help"
Install necessary Python packages: echo; printf "%0.s─" $(seq $COLOUMNS); echo
pip3 install psutil click distro power requests PyGObject
Run following sequence of lines:
----- echo "Consider creating a feature request to add support for your distro:"
echo "https://github.com/AdnanHodzic/auto-cpufreq/issues/new"; echo
echo "Make sure to include following information:"; echo
echo "Distribution: $distro"
echo "Release: $release"
echo "Codename: $codename"
echo
pip3 install . exit 1
mkdir -p /usr/local/share/auto-cpufreq/
cp -r scripts/ /usr/local/share/auto-cpufreq/
-----
After which tool is installed, for full list of options run:
auto-cpufreq"
separator
echo -e "
Consider creating a feature request to add support for your distro:
https://github.com/AdnanHodzic/auto-cpufreq/issues/new
Make sure to include following information:
Distribution: $distro
Release: $release
Codename: $codename"
separator
} }
function tool_install { function tool_install {
separator echo
# First argument is the distro
function detected_distro {
header "Detected $1 distribution"
header "Setting up Python environment"
}
if [ -f /etc/debian_version ]; then if [ -f /etc/debian_version ]; then
detected_distro "Debian based" detected_distro "Debian based"
@ -131,8 +97,7 @@ function tool_install {
pacman -S --noconfirm --needed python python-pip python-setuptools base-devel dmidecode gobject-introspection gtk3 gcc pacman -S --noconfirm --needed python python-pip python-setuptools base-devel dmidecode gobject-introspection gtk3 gcc
elif [ -f /etc/os-release ];then elif [ -f /etc/os-release ];then
eval "$(cat /etc/os-release)" . /etc/os-release
separator
case $ID in case $ID in
opensuse-leap) opensuse-leap)
detected_distro "OpenSUSE" detected_distro "OpenSUSE"
@ -147,146 +112,113 @@ function tool_install {
xbps-install -Sy python3 python3-pip python3-devel python3-setuptools base-devel dmidecode cairo-devel gobject-introspection gcc gtk+3 xbps-install -Sy python3 python3-pip python3-devel python3-setuptools base-devel dmidecode cairo-devel gobject-introspection gcc gtk+3
;; ;;
nixos) nixos)
echo -e "NixOS detected\n" echo "NixOS detected"
echo -e "This installer is not supported on NixOS.\nPlease refer to the install instructions for NixOS at https://github.com/AdnanHodzic/auto-cpufreq#nixos" echo "This installer is not supported on NixOS."
echo "Please refer to the install instructions for NixOS at https://github.com/AdnanHodzic/auto-cpufreq#nixos"
exit 1 exit 1
;; ;;
*) manual_install;; *) manual_install;;
esac esac
else # In case /etc/os-release doesn't exist else # In case /etc/os-release doesn't exist
manual_install manual_install
exit 1
fi fi
echo -e "\nInstalling necessary Python packages\n" header "Installing necessary Python packages"
venv_dir=/opt/auto-cpufreq/venv venv_dir=$VENV_PATH/venv
mkdir -p "${venv_dir}" mkdir -p "$venv_dir"
python3 -m venv "${venv_dir}" python3 -m venv "$venv_dir"
source "${venv_dir}/bin/activate" source "$venv_dir/bin/activate"
python3 -m pip install --upgrade pip wheel python3 -m pip install --upgrade pip wheel
separator header "Installing auto-cpufreq tool"
echo -e "\ninstalling auto-cpufreq tool\n"
install
separator git config --global --add safe.directory $(pwd)
echo -e " python -m pip install .
auto-cpufreq tool successfully installed.
For list of options, run: mkdir -p $SHARE_DIR
cp -r scripts/ $SHARE_DIR
cp -r images/ $SHARE_DIR
cp images/icon.png $IMG_FILE
cp scripts/$(basename $ORG_FILE) $(dirname $ORG_FILE)
auto-cpufreq --help" # this is necessary since we need this script before we can run auto-cpufreq itself
separator cp scripts/auto-cpufreq-venv-wrapper $AUTO_CPUFREQ_FILE
chmod a+x $AUTO_CPUFREQ_FILE
cp scripts/start_app $AUTO_CPUFREQ_GTK_FILE
chmod a+x $AUTO_CPUFREQ_GTK_FILE
desktop-file-install --dir=$APPLICATIONS_PATH scripts/$AUTO_CPUFREQ_GTK_DESKTOP_FILE
update-desktop-database $APPLICATIONS_PATH
header "auto-cpufreq tool successfully installed"
echo "For list of options, run:"
echo "auto-cpufreq --help"; echo
} }
function tool_remove { function tool_remove {
# files="files.txt"
share_dir="/usr/local/share/auto-cpufreq/"
srv_install="/usr/local/bin/auto-cpufreq-install"
srv_install_old="/usr/bin/auto-cpufreq-install"
srv_remove="/usr/local/bin/auto-cpufreq-remove"
srv_remove_old="/usr/bin/auto-cpufreq-remove"
stats_file="/var/run/auto-cpufreq.stats"
tool_proc_rm="/usr/local/bin/auto-cpufreq --remove"
wrapper_script="/usr/local/bin/auto-cpufreq"
gui_wrapper_script="/usr/local/bin/auto-cpufreq-gtk"
unit_file="/etc/systemd/system/auto-cpufreq.service"
venv_path="/opt/auto-cpufreq"
cpufreqctl="/usr/local/bin/cpufreqctl.auto-cpufreq"
cpufreqctl_old="/usr/bin/cpufreqctl.auto-cpufreq"
desktop_file="/usr/share/applications/auto-cpufreq-gtk.desktop"
# stop any running auto-cpufreq argument (daemon/live/monitor) # stop any running auto-cpufreq argument (daemon/live/monitor)
tool_arg_pids=($(pgrep -f "auto-cpufreq --")) tool_arg_pids=($(pgrep -f "auto-cpufreq --"))
for pid in "${tool_arg_pids[@]}"; do for pid in "${tool_arg_pids[@]}"; do [ $pid != $$ ] && kill "$pid"; done
if [[ $tool_arg_pids != $$ ]]; then
kill "$tool_arg_pids" function remove_directory {
fi [ -d $1 ] && rm -rf $1
done }
function remove_file {
[ -f $1 ] && rm $1
}
srv_remove="$AUTO_CPUFREQ_FILE-remove"
# run uninstall in case of installed daemon # run uninstall in case of installed daemon
if [ -f $srv_remove -o -f $srv_remove_old -o $wrapper_script ]; then if [ -f $srv_remove -o -f $AUTO_CPUFREQ_FILE ]; then
eval $tool_proc_rm eval "$AUTO_CPUFREQ_FILE --remove"
else else
separator echo; echo "Couldn't remove the auto-cpufreq daemon, $srv_remove do not exist."
printf "Couldn't remove the auto-cpufreq daemon\n$srv_remove or $srv_remove_old do not exist.\n"
exit 1;
separator
fi fi
# remove auto-cpufreq and all its supporting files # remove auto-cpufreq and all its supporting files
# [ -f $files ] && cat $files | xargs sudo rm -rf && rm -f $files remove_directory $SHARE_DIR
[ -d $share_dir ] && rm -rf $share_dir
# files cleanup remove_file "$AUTO_CPUFREQ_FILE-install"
[ -f $srv_install ] && rm $srv_install remove_file $srv_remove
[ -f $srv_install_old ] && rm $srv_install_old remove_file $AUTO_CPUFREQ_FILE
remove_file $AUTO_CPUFREQ_GTK_FILE
remove_file $IMG_FILE
remove_file $ORG_FILE
remove_file "/usr/local/bin/cpufreqctl.auto-cpufreq"
remove_file "/var/run/auto-cpufreq.stats"
[ -f $srv_remove ] && rm $srv_remove remove_file "$APPLICATIONS_PATH/$AUTO_CPUFREQ_GTK_DESKTOP_FILE"
[ -f $srv_remove_old ] && rm $srv_remove_old update-desktop-database $APPLICATIONS_PATH
[ -f $stats_file ] && rm $stats_file
[ -f $unit_file ] && rm $unit_file
[ -f $wrapper_script ] && rm $wrapper_script
[ -f $gui_wrapper_script ] && rm $gui_wrapper_script
[ -f $cpufreqctl ] && rm $cpufreqctl
[ -f $cpufreqctl_old ] && rm $cpufreqctl_old
[ -f $desktop_file ] && rm $desktop_file
update-desktop-database /usr/share/applications
# remove python virtual environment # remove python virtual environment
rm -rf "${venv_path}" remove_directory $venv_path
separator echo; echo "auto-cpufreq tool and all its supporting files successfully removed"; echo
echo -e "\nauto-cpufreq tool and all its supporting files successfully removed."
separator
} }
function ask_operation { # root check
header "auto-cpufreq installer" if ((EUID != 0)); then
echo -e "Welcome to auto-cpufreq tool installer. echo; echo "Must be run as root (i.e: 'sudo $0')."; echo
\nOptions:\n" exit 1
read -p \ fi
"[I]nstall
[R]emove
[Q]uit
Select a key: [i/r/q]: " answer if [[ -z "$1" ]]; then ask_operation
}
# End of functions
root_check
if [[ -z "${1}" ]]; then ask_operation
else else
case "${1}" in case "$1" in
"--install") answer="i";; --install) answer="i";;
"--remove") answer="r";; --remove) answer="r";;
*) answer="n";; *) ask_operation;;
esac esac
fi fi
case $answer in case $answer in
I|i) tool_install;; I|i) tool_install;;
R|r) tool_remove;; R|r) tool_remove;;
Q|q)
separator
echo ""
exit 0
;;
*) *)
separator echo "Unknown key, aborting ..."; echo
echo -e "\nUnknown key, aborting ...\n"
exit 1 exit 1
;; ;;
esac esac

View File

@ -5,41 +5,16 @@ from auto_cpufreq.battery_scripts.thinkpad import thinkpad_setup, thinkpad_print
from auto_cpufreq.battery_scripts.ideapad_acpi import ideapad_acpi_setup, ideapad_acpi_print_thresholds from auto_cpufreq.battery_scripts.ideapad_acpi import ideapad_acpi_setup, ideapad_acpi_print_thresholds
from auto_cpufreq.battery_scripts.ideapad_laptop import ideapad_laptop_setup, ideapad_laptop_print_thresholds from auto_cpufreq.battery_scripts.ideapad_laptop import ideapad_laptop_setup, ideapad_laptop_print_thresholds
def lsmod(module): return module in subprocess.run(['lsmod'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout
def lsmod(module):
output = subprocess.run(
['lsmod'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
if module in output.stdout:
return True
else:
return False
def battery_setup(): def battery_setup():
if lsmod("thinkpad_acpi"): thinkpad_setup()
if lsmod("thinkpad_acpi"): elif lsmod("ideapad_acpi"): ideapad_acpi_setup()
thinkpad_setup() elif lsmod("ideapad_laptop"): ideapad_laptop_setup()
else: return
elif lsmod("ideapad_acpi"):
ideapad_acpi_setup()
elif lsmod("ideapad_laptop"):
ideapad_laptop_setup()
else:
return
def battery_get_thresholds(): def battery_get_thresholds():
if lsmod("thinkpad_acpi"): thinkpad_print_thresholds()
if lsmod("thinkpad_acpi"): elif lsmod("ideapad_acpi"): ideapad_acpi_print_thresholds()
thinkpad_print_thresholds() elif lsmod("ideapad_laptop"): ideapad_laptop_print_thresholds()
else: return
elif lsmod("ideapad_acpi"):
ideapad_acpi_print_thresholds()
elif lsmod("ideapad_laptop"):
ideapad_laptop_print_thresholds()
else:
return

View File

@ -3,62 +3,40 @@ import os
import subprocess import subprocess
from auto_cpufreq.utils.config import config from auto_cpufreq.utils.config import config
POWER_SUPPLY_DIR = "/sys/class/power_supply/"
def set_battery(value, mode, bat): def set_battery(value, mode, bat):
path = f"/sys/class/power_supply/BAT{bat}/charge_{mode}_threshold" path = f"{POWER_SUPPLY_DIR}BAT{bat}/charge_{mode}_threshold"
if os.path.isfile(path): if os.path.isfile(path): subprocess.check_output(f"echo {value} | tee {path}", shell=True, text=True)
subprocess.check_output( else: print(f"WARNING: {path} does NOT exist")
f"echo {value} | tee {path}", shell=True, text=True)
else:
print(f"WARNING: {path} does NOT exist")
def get_threshold_value(mode): def get_threshold_value(mode):
conf = config.get_config() conf = config.get_config()
if conf.has_option("battery", f"{mode}_threshold"): return conf["battery"][f"{mode}_threshold"] if conf.has_option("battery", f"{mode}_threshold") else (0 if mode == "start" else 100)
return conf["battery"][f"{mode}_threshold"]
else:
if mode == "start":
return 0
else:
return 100
def ideapad_acpi_setup(): def ideapad_acpi_setup():
conf = config.get_config() conf = config.get_config()
if not conf.has_option("battery", "enable_thresholds"): if not (conf.has_option("battery", "enable_thresholds") and conf["battery"]["enable_thresholds"] == "true"): return
return
if not conf["battery"]["enable_thresholds"] == "true":
return
if os.path.exists("/sys/class/power_supply/"): if os.path.exists(POWER_SUPPLY_DIR):
battery_count = len([name for name in os.listdir( battery_count = len([name for name in os.listdir(POWER_SUPPLY_DIR) if name.startswith('BAT')])
"/sys/class/power_supply/") if name.startswith('BAT')])
for bat in range(battery_count): for bat in range(battery_count):
set_battery(get_threshold_value("start"), "start", bat) set_battery(get_threshold_value("start"), "start", bat)
set_battery(get_threshold_value("stop"), "stop", bat) set_battery(get_threshold_value("stop"), "stop", bat)
else: else: print(f"WARNING: could NOT access {POWER_SUPPLY_DIR}")
print("WARNING: could NOT access /sys/class/power_supply")
def ideapad_acpi_print_thresholds(): def ideapad_acpi_print_thresholds():
battery_count = len([name for name in os.listdir( battery_count = len([name for name in os.listdir(POWER_SUPPLY_DIR) if name.startswith('BAT')])
"/sys/class/power_supply/") if name.startswith('BAT')])
print("\n-------------------------------- Battery Info ---------------------------------\n") print("\n-------------------------------- Battery Info ---------------------------------\n")
print(f"battery count = {battery_count}") print(f"battery count = {battery_count}")
for b in range(battery_count): for b in range(battery_count):
try: try:
with open(f'/sys/class/power_supply/BAT{b}/charge_start_threshold', 'r') as f: with open(f'{POWER_SUPPLY_DIR}BAT{b}/charge_start_threshold', 'r') as f:
print(f'battery{b} start threshold = {f.read()}', end="") print(f'battery{b} start threshold = {f.read()}', end="")
f.close()
with open(f'/sys/class/power_supply/BAT{b}/charge_stop_threshold', 'r') as f: with open(f'{POWER_SUPPLY_DIR}BAT{b}/charge_stop_threshold', 'r') as f:
print(f'battery{b} stop threshold = {f.read()}', end="") print(f'battery{b} stop threshold = {f.read()}', end="")
f.close()
except Exception: except Exception: print(f"ERROR: failed to read battery {b} thresholds")
print(f"ERROR: failed to read battery {b} thresholds")

View File

@ -3,47 +3,30 @@ import os
import subprocess import subprocess
from auto_cpufreq.utils.config import config from auto_cpufreq.utils.config import config
POWER_SUPPLY_DIR = "/sys/class/power_supply/"
def set_battery(value, mode, bat): def set_battery(value, mode, bat):
path = f"/sys/class/power_supply/BAT{bat}/charge_{mode}_threshold" path = f"{POWER_SUPPLY_DIR}BAT{bat}/charge_{mode}_threshold"
if os.path.exists(path): if os.path.exists(path):
subprocess.check_output( subprocess.check_output(f"echo {value} | tee {POWER_SUPPLY_DIR}BAT{bat}/charge_{mode}_threshold", shell=True, text=True)
f"echo {value} | tee /sys/class/power_supply/BAT{bat}/charge_{mode}_threshold", shell=True, text=True) else: print(f"WARNING: {path} does NOT exist")
else:
print(f"WARNING: {path} does NOT exist")
def get_threshold_value(mode): def get_threshold_value(mode):
conf = config.get_config() conf = config.get_config()
if conf.has_option("battery", f"{mode}_threshold"): return conf["battery"][f"{mode}_threshold"] if conf.has_option("battery", f"{mode}_threshold") else (0 if mode == "start" else 100)
return conf["battery"][f"{mode}_threshold"]
else:
if mode == "start":
return 0
else:
return 100
def conservation_mode(value): def conservation_mode(value):
try: try:
subprocess.check_output( subprocess.check_output(f"echo {value} | tee /sys/bus/platform/drivers/ideapad_acpi/VPC2004:00/conservation_mode", shell=True, text=True)
f"echo {value} | tee /sys/bus/platform/drivers/ideapad_acpi/VPC2004:00/conservation_mode", shell=True, text=True)
print(f"conservation_mode is {value}") print(f"conservation_mode is {value}")
except: print("unable to set conservation mode")
return return
except:
print("unable to set conservation mode")
return
def check_conservation_mode(): def check_conservation_mode():
try: try:
value = subprocess.check_output( value = subprocess.check_output("cat /sys/bus/platform/drivers/ideapad_acpi/VPC2004:00/conservation_mode", shell=True, text=True)
"cat /sys/bus/platform/drivers/ideapad_acpi/VPC2004:00/conservation_mode", shell=True, text=True) if value == "1": return True
if value == "1": elif value == "0": return False
return True
elif value == "0":
return False
else: else:
print("could not get value from conservation mode") print("could not get value from conservation mode")
return None return None
@ -51,51 +34,39 @@ def check_conservation_mode():
print("could not get the value from conservation mode") print("could not get the value from conservation mode")
return False return False
def ideapad_laptop_setup(): def ideapad_laptop_setup():
conf = config.get_config() conf = config.get_config()
if not conf.has_option("battery", "enable_thresholds"): if not (conf.has_option("battery", "enable_thresholds") and conf["battery"]["enable_thresholds"] == "true"): return
return
if not conf["battery"]["enable_thresholds"] == "true":
return
battery_count = len([name for name in os.listdir( battery_count = len([name for name in os.listdir(POWER_SUPPLY_DIR) if name.startswith('BAT')])
"/sys/class/power_supply/") if name.startswith('BAT')])
if conf.has_option("battery", "ideapad_laptop_conservation_mode"): if conf.has_option("battery", "ideapad_laptop_conservation_mode"):
if conf["battery"]["ideapad_laptop_conservation_mode"] == "true": if conf["battery"]["ideapad_laptop_conservation_mode"] == "true":
conservation_mode(1) conservation_mode(1)
return return
if conf["battery"]["ideapad_laptop_conservation_mode"] == "false": if conf["battery"]["ideapad_laptop_conservation_mode"] == "false": conservation_mode(0)
conservation_mode(0)
if check_conservation_mode() is False: if not check_conservation_mode():
for bat in range(battery_count): for bat in range(battery_count):
set_battery(get_threshold_value("start"), "start", bat) set_battery(get_threshold_value("start"), "start", bat)
set_battery(get_threshold_value("stop"), "stop", bat) set_battery(get_threshold_value("stop"), "stop", bat)
else: else: print("conservation mode is enabled unable to set thresholds")
print("conservation mode is enabled unable to set thresholds")
def ideapad_laptop_print_thresholds(): def ideapad_laptop_print_thresholds():
if check_conservation_mode() is True: if check_conservation_mode():
print("conservation mode is on") print("conservation mode is on")
return return
battery_count = len([name for name in os.listdir( battery_count = len([name for name in os.listdir(POWER_SUPPLY_DIR) if name.startswith('BAT')])
"/sys/class/power_supply/") if name.startswith('BAT')])
print("\n-------------------------------- Battery Info ---------------------------------\n") print("\n-------------------------------- Battery Info ---------------------------------\n")
print(f"battery count = {battery_count}") print(f"battery count = {battery_count}")
for b in range(battery_count): for b in range(battery_count):
try: try:
with open(f'/sys/class/power_supply/BAT{b}/charge_start_threshold', 'r') as f: with open(f'{POWER_SUPPLY_DIR}BAT{b}/charge_start_threshold', 'r') as f:
print(f'battery{b} start threshold = {f.read()}', end="") print(f'battery{b} start threshold = {f.read()}', end="")
f.close()
with open(f'/sys/class/power_supply/BAT{b}/charge_stop_threshold', 'r') as f: with open(f'{POWER_SUPPLY_DIR}BAT{b}/charge_stop_threshold', 'r') as f:
print(f'battery{b} stop threshold = {f.read()}', end="") print(f'battery{b} stop threshold = {f.read()}', end="")
f.close()
except Exception as e: except Exception as e: print(f"ERROR: failed to read battery {b} thresholds: {e}")
print(f"ERROR: failed to read battery thresholds: {e}")

View File

@ -3,62 +3,41 @@ import os
import subprocess import subprocess
from auto_cpufreq.utils.config import config from auto_cpufreq.utils.config import config
POWER_SUPPLY_DIR = "/sys/class/power_supply/"
def set_battery(value, mode, bat): def set_battery(value, mode, bat):
path = f"/sys/class/power_supply/BAT{bat}/charge_{mode}_threshold" path = f"{POWER_SUPPLY_DIR}BAT{bat}/charge_{mode}_threshold"
if os.path.isfile(path): if os.path.isfile(path): subprocess.check_output(f"echo {value} | tee {path}", shell=True, text=True)
subprocess.check_output( else: print(f"WARNING: {path} does NOT exist")
f"echo {value} | tee {path}", shell=True, text=True)
else:
print(f"WARNING: {path} does NOT exist")
def get_threshold_value(mode): def get_threshold_value(mode):
conf = config.get_config() conf = config.get_config()
if conf.has_option("battery", f"{mode}_threshold"): return conf["battery"][f"{mode}_threshold"] if conf.has_option("battery", f"{mode}_threshold") else (0 if mode == "start" else 100)
return conf["battery"][f"{mode}_threshold"]
else:
if mode == "start":
return 0
else:
return 100
def thinkpad_setup(): def thinkpad_setup():
conf = config.get_config() conf = config.get_config()
if not conf.has_option("battery", "enable_thresholds"): if not (conf.has_option("battery", "enable_thresholds") and conf["battery"]["enable_thresholds"] == "true"): return
return
if not conf["battery"]["enable_thresholds"] == "true":
return
if os.path.exists("/sys/class/power_supply/"): if os.path.exists(POWER_SUPPLY_DIR):
battery_count = len([name for name in os.listdir( battery_count = len([name for name in os.listdir(POWER_SUPPLY_DIR) if name.startswith('BAT')])
"/sys/class/power_supply/") if name.startswith('BAT')])
for bat in range(battery_count): for bat in range(battery_count):
set_battery(get_threshold_value("start"), "start", bat) set_battery(get_threshold_value("start"), "start", bat)
set_battery(get_threshold_value("stop"), "stop", bat) set_battery(get_threshold_value("stop"), "stop", bat)
else: else: print(f"WARNING {POWER_SUPPLY_DIR} does NOT esixt")
print("WARNING /sys/class/power_supply/ does NOT esixt")
def thinkpad_print_thresholds(): def thinkpad_print_thresholds():
battery_count = len([name for name in os.listdir( battery_count = len([name for name in os.listdir(POWER_SUPPLY_DIR) if name.startswith('BAT')])
"/sys/class/power_supply/") if name.startswith('BAT')])
print("\n-------------------------------- Battery Info ---------------------------------\n") print("\n-------------------------------- Battery Info ---------------------------------\n")
print(f"battery count = {battery_count}") print(f"battery count = {battery_count}")
for b in range(battery_count): for b in range(battery_count):
try: try:
with open(f'/sys/class/power_supply/BAT{b}/charge_start_threshold', 'r') as f: with open(f'{POWER_SUPPLY_DIR}BAT{b}/charge_start_threshold', 'r') as f:
print(f'battery{b} start threshold = {f.read()}', end="") print(f'battery{b} start threshold = {f.read()}', end="")
f.close()
with open(f'/sys/class/power_supply/BAT{b}/charge_stop_threshold', 'r') as f: with open(f'{POWER_SUPPLY_DIR}BAT{b}/charge_stop_threshold', 'r') as f:
print(f'battery{b} stop threshold = {f.read()}', end="") print(f'battery{b} stop threshold = {f.read()}', end="")
f.close()
except Exception: except Exception: print(f"ERROR: failed to read battery {b} thresholds")
print(f"ERROR: failed to read battery {b} thresholds")

View File

@ -9,6 +9,7 @@ import sys
import time import time
from click import UsageError from click import UsageError
from subprocess import call, run from subprocess import call, run
from shutil import rmtree
# sys.path.append("../") # sys.path.append("../")
from auto_cpufreq.core import * from auto_cpufreq.core import *
@ -26,12 +27,7 @@ from auto_cpufreq.utils.config import config as conf, find_config_file
@click.option("--stats", is_flag=True, help="View live stats of CPU optimizations made by daemon") @click.option("--stats", is_flag=True, help="View live stats of CPU optimizations made by daemon")
@click.option("--force", is_flag=False, help="Force use of either \"powersave\" or \"performance\" governors. Setting to \"reset\" will go back to normal mode") @click.option("--force", is_flag=False, help="Force use of either \"powersave\" or \"performance\" governors. Setting to \"reset\" will go back to normal mode")
@click.option("--get-state", is_flag=True, hidden=True) @click.option("--get-state", is_flag=True, hidden=True)
@click.option( @click.option("--config", is_flag=False, required=False, help="Use config file at defined path",)
"--config",
is_flag=False,
required=False,
help="Use config file at defined path",
)
@click.option("--debug", is_flag=True, help="Show debug info (include when submitting bugs)") @click.option("--debug", is_flag=True, help="Show debug info (include when submitting bugs)")
@click.option("--version", is_flag=True, help="Show currently installed version") @click.option("--version", is_flag=True, help="Show currently installed version")
@click.option("--donate", is_flag=True, help="Support the project") @click.option("--donate", is_flag=True, help="Support the project")
@ -39,7 +35,6 @@ from auto_cpufreq.utils.config import config as conf, find_config_file
@click.option("--log", is_flag=True, hidden=True) @click.option("--log", is_flag=True, hidden=True)
@click.option("--daemon", is_flag=True, hidden=True) @click.option("--daemon", is_flag=True, hidden=True)
def main(config, daemon, debug, update, install, remove, live, log, monitor, stats, version, donate, force, get_state, completions): def main(config, daemon, debug, update, install, remove, live, log, monitor, stats, version, donate, force, get_state, completions):
# display info if config file is used # display info if config file is used
config_path = find_config_file(config) config_path = find_config_file(config)
conf.set_path(config_path) conf.set_path(config_path)
@ -84,8 +79,7 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
sysinfo() sysinfo()
set_autofreq() set_autofreq()
countdown(2) countdown(2)
except KeyboardInterrupt: except KeyboardInterrupt: break
break;
conf.notifier.stop() conf.notifier.stop()
elif monitor: elif monitor:
config_info_dialog() config_info_dialog()
@ -111,8 +105,7 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
sysinfo() sysinfo()
mon_autofreq() mon_autofreq()
countdown(2) countdown(2)
except KeyboardInterrupt: except KeyboardInterrupt: break
break
conf.notifier.stop() conf.notifier.stop()
elif live: elif live:
root_check() root_check()
@ -141,7 +134,7 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
countdown(2) countdown(2)
except KeyboardInterrupt: except KeyboardInterrupt:
gnome_power_start_live() gnome_power_start_live()
print("") print()
break break
conf.notifier.stop() conf.notifier.stop()
elif stats: elif stats:
@ -156,8 +149,7 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
tlp_service_detect() tlp_service_detect()
battery_get_thresholds() battery_get_thresholds()
read_stats() read_stats()
elif log: elif log: deprecated_log_msg()
deprecated_log_msg()
elif get_state: elif get_state:
not_running_daemon_check() not_running_daemon_check()
override = get_override() override = get_override()
@ -171,17 +163,14 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
footer() footer()
distro_info() distro_info()
sysinfo() sysinfo()
print("") print()
app_version() app_version()
print("") print()
python_info() python_info()
print("") print()
device_info() device_info()
if charging(): print(f"Battery is: {'' if charging() else 'dis'}charging")
print("Battery is: charging") print()
else:
print("Battery is: discharging")
print("")
app_res_use() app_res_use()
display_load() display_load()
get_current_gov() get_current_gov()
@ -199,8 +188,8 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
print("https://github.com/AdnanHodzic/auto-cpufreq/#donate") print("https://github.com/AdnanHodzic/auto-cpufreq/#donate")
footer() footer()
elif install: elif install:
if os.getenv("PKG_MARKER") == "SNAP":
root_check() root_check()
if os.getenv("PKG_MARKER") == "SNAP":
running_daemon_check() running_daemon_check()
gnome_power_detect_snap() gnome_power_detect_snap()
tlp_service_detect_snap() tlp_service_detect_snap()
@ -208,16 +197,14 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
gov_check() gov_check()
run("snapctl set daemon=enabled", shell=True) run("snapctl set daemon=enabled", shell=True)
run("snapctl start --enable auto-cpufreq", shell=True) run("snapctl start --enable auto-cpufreq", shell=True)
deploy_complete_msg()
else: else:
root_check()
running_daemon_check() running_daemon_check()
gov_check() gov_check()
deploy_daemon() deploy_daemon()
deploy_complete_msg() deploy_complete_msg()
elif remove: elif remove:
if os.getenv("PKG_MARKER") == "SNAP":
root_check() root_check()
if os.getenv("PKG_MARKER") == "SNAP":
run("snapctl set daemon=disabled", shell=True) run("snapctl set daemon=disabled", shell=True)
run("snapctl stop --disable auto-cpufreq", shell=True) run("snapctl stop --disable auto-cpufreq", shell=True)
if auto_cpufreq_stats_path.exists(): if auto_cpufreq_stats_path.exists():
@ -229,10 +216,7 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
# {the following snippet also used in --update, update it there too(if required)} # {the following snippet also used in --update, update it there too(if required)}
# * undo bluetooth boot disable # * undo bluetooth boot disable
gnome_power_rm_reminder_snap() gnome_power_rm_reminder_snap()
remove_complete_msg() else: remove_daemon()
else:
root_check()
remove_daemon()
remove_complete_msg() remove_complete_msg()
elif update: elif update:
root_check() root_check()
@ -245,8 +229,7 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
if "--update" in sys.argv: if "--update" in sys.argv:
update = True update = True
sys.argv.remove("--update") sys.argv.remove("--update")
if len(sys.argv) == 2: if len(sys.argv) == 2: custom_dir = sys.argv[1]
custom_dir = sys.argv[1]
if os.getenv("PKG_MARKER") == "SNAP": if os.getenv("PKG_MARKER") == "SNAP":
print("Detected auto-cpufreq was installed using snap") print("Detected auto-cpufreq was installed using snap")
@ -259,13 +242,10 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
print("Arch-based distribution with AUR support detected. Please refresh auto-cpufreq using your AUR helper.") print("Arch-based distribution with AUR support detected. Please refresh auto-cpufreq using your AUR helper.")
else: else:
is_new_update = check_for_update() is_new_update = check_for_update()
if not is_new_update: if not is_new_update: return
return
ans = input("Do you want to update auto-cpufreq to the latest release? [Y/n]: ").strip().lower() ans = input("Do you want to update auto-cpufreq to the latest release? [Y/n]: ").strip().lower()
if not os.path.exists(custom_dir): if not os.path.exists(custom_dir): os.makedirs(custom_dir)
os.makedirs(custom_dir) if os.path.exists(os.path.join(custom_dir, "auto-cpufreq")): rmtree(os.path.join(custom_dir, "auto-cpufreq"))
if os.path.exists(os.path.join(custom_dir, "auto-cpufreq")):
shutil.rmtree(os.path.join(custom_dir, "auto-cpufreq"))
if ans in ['', 'y', 'yes']: if ans in ['', 'y', 'yes']:
remove_daemon() remove_daemon()
remove_complete_msg() remove_complete_msg()
@ -274,9 +254,7 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
run(["auto-cpufreq", "--install"]) run(["auto-cpufreq", "--install"])
print("auto-cpufreq is installed with the latest version") print("auto-cpufreq is installed with the latest version")
run(["auto-cpufreq", "--version"]) run(["auto-cpufreq", "--version"])
else: else: print("Aborted")
print("Aborted")
elif completions: elif completions:
if completions == "bash": if completions == "bash":
print("Run the below command in your current shell!\n") print("Run the below command in your current shell!\n")
@ -289,10 +267,6 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
elif completions == "fish": elif completions == "fish":
print("Run the below command in your current shell!\n") print("Run the below command in your current shell!\n")
print("echo '_AUTO_CPUFREQ_COMPLETE=fish_source auto-cpufreq | source' > ~/.config/fish/completions/auto-cpufreq.fish") print("echo '_AUTO_CPUFREQ_COMPLETE=fish_source auto-cpufreq | source' > ~/.config/fish/completions/auto-cpufreq.fish")
else: else: print("Invalid Option, try bash|zsh|fish as argument to --completions")
print("Invalid Option, try bash|zsh|fish as argument to --completions")
if __name__ == "__main__": main()
if __name__ == "__main__":
main()

View File

@ -18,5 +18,4 @@ def main():
win.handle_update() win.handle_update()
Gtk.main() Gtk.main()
if __name__ == "__main__": if __name__ == "__main__": main()
main()

View File

@ -143,7 +143,7 @@ def app_version():
if os.getenv("PKG_MARKER") == "SNAP": if os.getenv("PKG_MARKER") == "SNAP":
print(getoutput(r"echo \(Snap\) $SNAP_VERSION")) print(getoutput(r"echo \(Snap\) $SNAP_VERSION"))
# aur package # aur package
elif dist_name in ["arch", "manjaro", "garuda"]: elif os.path.exists("/etc/arch-release"):
aur_pkg_check = call("pacman -Qs auto-cpufreq > /dev/null", shell=True) aur_pkg_check = call("pacman -Qs auto-cpufreq > /dev/null", shell=True)
if aur_pkg_check == 1: if aur_pkg_check == 1:
print(get_formatted_version()) print(get_formatted_version())
@ -1308,7 +1308,7 @@ def sysinfo():
if sensor in temp_sensors: if sensor in temp_sensors:
if temp_sensors[sensor][0].current != 0: if temp_sensors[sensor][0].current != 0:
temp_per_cpu = [temp_sensors[sensor][0].current] * online_cpu_count temp_per_cpu = [temp_sensors[sensor][0].current] * online_cpu_count
break; break
except Exception as e: except Exception as e:
print(repr(e)) print(repr(e))
pass pass
@ -1346,7 +1346,7 @@ def is_running(program, argument):
# and find the one with name and args passed to the function # and find the one with name and args passed to the function
for p in psutil.process_iter(): for p in psutil.process_iter():
try: try:
cmd = p.cmdline(); cmd = p.cmdline()
except: except:
continue continue
for s in filter(lambda x: program in x, cmd): for s in filter(lambda x: program in x, cmd):

View File

@ -26,7 +26,6 @@ else:
HBOX_PADDING = 20 HBOX_PADDING = 20
PKEXEC_ERROR = "Error executing command as another user: Not authorized\n\nThis incident has been reported.\n" PKEXEC_ERROR = "Error executing command as another user: Not authorized\n\nThis incident has been reported.\n"
class ToolWindow(Gtk.Window): class ToolWindow(Gtk.Window):
def __init__(self): def __init__(self):
super().__init__(title="auto-cpufreq") super().__init__(title="auto-cpufreq")
@ -39,7 +38,6 @@ class ToolWindow(Gtk.Window):
self.build() self.build()
def main(self): def main(self):
# Main HBOX # Main HBOX
self.hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=HBOX_PADDING) self.hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=HBOX_PADDING)
@ -61,7 +59,6 @@ class ToolWindow(Gtk.Window):
self.hbox.pack_start(self.vbox_right, False, False, 0) self.hbox.pack_start(self.vbox_right, False, False, 0)
GLib.timeout_add_seconds(5, self.refresh_in_thread) GLib.timeout_add_seconds(5, self.refresh_in_thread)
def snap(self): def snap(self):
@ -81,15 +78,12 @@ class ToolWindow(Gtk.Window):
def handle_update(self): def handle_update(self):
new_stdout = StringIO() new_stdout = StringIO()
with redirect_stdout(new_stdout): with redirect_stdout(new_stdout):
is_new_update = check_for_update() if not check_for_update(): return
if not is_new_update:
return
captured_output = new_stdout.getvalue().splitlines() captured_output = new_stdout.getvalue().splitlines()
dialog = UpdateDialog(self, captured_output[1], captured_output[2]) dialog = UpdateDialog(self, captured_output[1], captured_output[2])
response = dialog.run() response = dialog.run()
dialog.destroy() dialog.destroy()
if response != Gtk.ResponseType.YES: if response != Gtk.ResponseType.YES: return
return
updater = run(["pkexec", "auto-cpufreq", "--update"], input="y\n", encoding="utf-8", stderr=PIPE) updater = run(["pkexec", "auto-cpufreq", "--update"], input="y\n", encoding="utf-8", stderr=PIPE)
if updater.stderr == PKEXEC_ERROR: if updater.stderr == PKEXEC_ERROR:
error = Gtk.MessageDialog(self, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, "Error updating") error = Gtk.MessageDialog(self, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, "Error updating")
@ -108,12 +102,9 @@ class ToolWindow(Gtk.Window):
self.add(self.box) self.add(self.box)
def build(self): def build(self):
if os.getenv("PKG_MARKER") == "SNAP": if os.getenv("PKG_MARKER") == "SNAP": self.snap()
self.snap() elif is_running("auto-cpufreq", "--daemon"): self.main()
elif is_running("auto-cpufreq", "--daemon"): else: self.daemon_not_running()
self.main()
else:
self.daemon_not_running()
def load_css(self): def load_css(self):
screen = Gdk.Screen.get_default() screen = Gdk.Screen.get_default()

View File

@ -17,38 +17,28 @@ from io import StringIO
PKEXEC_ERROR = "Error executing command as another user: Not authorized\n\nThis incident has been reported.\n" PKEXEC_ERROR = "Error executing command as another user: Not authorized\n\nThis incident has been reported.\n"
if os.getenv("PKG_MARKER") == "SNAP": auto_cpufreq_stats_path = ("/var/snap/auto-cpufreq/current" if os.getenv("PKG_MARKER") == "SNAP" else "/var/run") + "/auto-cpufreq.stats"
auto_cpufreq_stats_path = "/var/snap/auto-cpufreq/current/auto-cpufreq.stats"
else:
auto_cpufreq_stats_path = "/var/run/auto-cpufreq.stats"
def get_stats(): def get_stats():
if os.path.isfile(auto_cpufreq_stats_path): if os.path.isfile(auto_cpufreq_stats_path):
with open(auto_cpufreq_stats_path, "r") as file: with open(auto_cpufreq_stats_path, "r") as file: stats = [line for line in (file.readlines() [-50:])]
stats = [line for line in (file.readlines() [-50:])]
return "".join(stats) return "".join(stats)
def get_version(): def get_version():
# snap package # snap package
if os.getenv("PKG_MARKER") == "SNAP": if os.getenv("PKG_MARKER") == "SNAP": return getoutput(r"echo \(Snap\) $SNAP_VERSION")
return getoutput(r"echo \(Snap\) $SNAP_VERSION")
# aur package # aur package
elif dist_name in ["arch", "manjaro", "garuda"]: elif dist_name in ["arch", "manjaro", "garuda"]:
aur_pkg_check = run("pacman -Qs auto-cpufreq > /dev/null", shell=True) aur_pkg_check = run("pacman -Qs auto-cpufreq > /dev/null", shell=True)
if aur_pkg_check == 1: if aur_pkg_check == 1: return get_formatted_version()
return get_formatted_version() else: return getoutput("pacman -Qi auto-cpufreq | grep Version")
else:
return getoutput("pacman -Qi auto-cpufreq | grep Version")
else: else:
# source code (auto-cpufreq-installer) # source code (auto-cpufreq-installer)
try: try: return get_formatted_version()
return get_formatted_version()
except Exception as e: except Exception as e:
print(repr(e)) print(repr(e))
pass pass
class RadioButtonView(Gtk.Box): class RadioButtonView(Gtk.Box):
def __init__(self): def __init__(self):
super().__init__(orientation=Gtk.Orientation.HORIZONTAL) super().__init__(orientation=Gtk.Orientation.HORIZONTAL)
@ -68,7 +58,6 @@ class RadioButtonView(Gtk.Box):
self.performance.connect("toggled", self.on_button_toggled, "performance") self.performance.connect("toggled", self.on_button_toggled, "performance")
self.performance.set_halign(Gtk.Align.END) self.performance.set_halign(Gtk.Align.END)
# this keeps track of whether or not the button was toggled by the app or the user to prompt for authorization # this keeps track of whether or not the button was toggled by the app or the user to prompt for authorization
self.set_by_app = True self.set_by_app = True
self.set_selected() self.set_selected()
@ -82,24 +71,17 @@ class RadioButtonView(Gtk.Box):
if button.get_active(): if button.get_active():
if not self.set_by_app: if not self.set_by_app:
result = run(f"pkexec auto-cpufreq --force={override}", shell=True, stdout=PIPE, stderr=PIPE) result = run(f"pkexec auto-cpufreq --force={override}", shell=True, stdout=PIPE, stderr=PIPE)
if result.stderr.decode() == PKEXEC_ERROR: if result.stderr.decode() == PKEXEC_ERROR: self.set_selected()
self.set_selected() else: self.set_by_app = False
else:
self.set_by_app = False
def set_selected(self): def set_selected(self):
override = get_override() override = get_override()
match override: match override:
case "powersave": case "powersave": self.powersave.set_active(True)
self.powersave.set_active(True) case "performance": self.performance.set_active(True)
case "performance":
self.performance.set_active(True)
case "default": case "default":
# because this is the default button, it does not trigger the callback when set by the app # because this is the default button, it does not trigger the callback when set by the app
if self.set_by_app: if self.set_by_app: self.set_by_app = False
self.set_by_app = False
self.default.set_active(True) self.default.set_active(True)
class CurrentGovernorBox(Gtk.Box): class CurrentGovernorBox(Gtk.Box):
@ -117,7 +99,6 @@ class CurrentGovernorBox(Gtk.Box):
class SystemStatsLabel(Gtk.Label): class SystemStatsLabel(Gtk.Label):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
self.refresh() self.refresh()
def refresh(self): def refresh(self):
@ -130,7 +111,6 @@ class SystemStatsLabel(Gtk.Label):
self.set_label(text.getvalue()) self.set_label(text.getvalue())
sys.stdout = old_stdout sys.stdout = old_stdout
class CPUFreqStatsLabel(Gtk.Label): class CPUFreqStatsLabel(Gtk.Label):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
@ -188,8 +168,7 @@ class DropDownMenu(Gtk.MenuButton):
kwargs = {"shell": True, "stdout": PIPE, "stderr": PIPE} kwargs = {"shell": True, "stdout": PIPE, "stderr": PIPE}
future = executor.submit(run, "pkexec auto-cpufreq --remove", **kwargs) future = executor.submit(run, "pkexec auto-cpufreq --remove", **kwargs)
result = future.result() result = future.result()
if result.stderr.decode() == PKEXEC_ERROR: assert result.stderr.decode() != PKEXEC_ERROR, Exception("Authorization was cancelled")
raise Exception("Authorization was cancelled")
dialog = Gtk.MessageDialog( dialog = Gtk.MessageDialog(
transient_for=parent, transient_for=parent,
message_type=Gtk.MessageType.INFO, message_type=Gtk.MessageType.INFO,
@ -211,7 +190,6 @@ class DropDownMenu(Gtk.MenuButton):
dialog.run() dialog.run()
dialog.destroy() dialog.destroy()
class AboutDialog(Gtk.Dialog): class AboutDialog(Gtk.Dialog):
def __init__(self, parent): def __init__(self, parent):
super().__init__(title="About", transient_for=parent) super().__init__(title="About", transient_for=parent)
@ -224,7 +202,8 @@ class AboutDialog(Gtk.Dialog):
filename="/usr/local/share/auto-cpufreq/images/icon.png", filename="/usr/local/share/auto-cpufreq/images/icon.png",
width=150, width=150,
height=150, height=150,
preserve_aspect_ratio=True) preserve_aspect_ratio=True
)
self.image = Gtk.Image.new_from_pixbuf(img_buffer) self.image = Gtk.Image.new_from_pixbuf(img_buffer)
self.title = Gtk.Label(label="auto-cpufreq", name="bold") self.title = Gtk.Label(label="auto-cpufreq", name="bold")
self.version = Gtk.Label(label=app_version) self.version = Gtk.Label(label=app_version)
@ -258,7 +237,6 @@ class UpdateDialog(Gtk.Dialog):
self.show_all() self.show_all()
class ConfirmDialog(Gtk.Dialog): class ConfirmDialog(Gtk.Dialog):
def __init__(self, parent, message: str): def __init__(self, parent, message: str):
super().__init__(title="Confirmation", transient_for=parent) super().__init__(title="Confirmation", transient_for=parent)
@ -290,8 +268,7 @@ class DaemonNotRunningView(Gtk.Box):
kwargs = {"shell": True, "stdout": PIPE, "stderr": PIPE} kwargs = {"shell": True, "stdout": PIPE, "stderr": PIPE}
future = executor.submit(run, "pkexec auto-cpufreq --install", **kwargs) future = executor.submit(run, "pkexec auto-cpufreq --install", **kwargs)
result = future.result() result = future.result()
if result.stderr.decode() == PKEXEC_ERROR: assert result.stderr.decode() != PKEXEC_ERROR, Exception("Authorization was cancelled")
raise Exception("Authorization was cancelled")
# enable for debug. causes issues if kept # enable for debug. causes issues if kept
# elif result.stderr is not None: # elif result.stderr is not None:
# raise Exception(result.stderr.decode()) # raise Exception(result.stderr.decode())

View File

@ -25,8 +25,6 @@ def build_menu():
menu.show_all() menu.show_all()
return menu return menu
def open_app(MenuItem): def open_app(MenuItem): run("sudo -E python app.py", shell=True)
run("sudo -E python app.py", shell=True)
if __name__ == "__main__": if __name__ == "__main__": main()
main()

View File

@ -3,6 +3,7 @@
# * if daemon is disabled and auto-cpufreq is removed (snap) remind user to enable it back # * if daemon is disabled and auto-cpufreq is removed (snap) remind user to enable it back
from logging import root from logging import root
import os, sys, click, subprocess import os, sys, click, subprocess
from shutil import which
from subprocess import getoutput, call, run, check_output, DEVNULL from subprocess import getoutput, call, run, check_output, DEVNULL
sys.path.append("../") sys.path.append("../")
@ -10,24 +11,15 @@ from auto_cpufreq.core import *
from auto_cpufreq.tlp_stat_parser import TLPStatusParser from auto_cpufreq.tlp_stat_parser import TLPStatusParser
# app_name var # app_name var
if sys.argv[0] == "power_helper.py": app_name = "python3 power_helper.py" if sys.argv[0] == "power_helper.py" else "auto-cpufreq"
app_name = "python3 power_helper.py"
else:
app_name = "auto-cpufreq"
def header(): print("\n------------------------- auto-cpufreq: Power helper -------------------------\n")
def warning(): print("\n----------------------------------- Warning -----------------------------------\n")
def header(): def helper_opts(): print("\nFor full list of options run: python3 power_helper.py --help")
print("\n------------------------- auto-cpufreq: Power helper -------------------------\n")
def helper_opts():
print("\nFor full list of options run: python3 power_helper.py --help")
# used to check if binary exists on the system # used to check if binary exists on the system
def does_command_exists(cmd): def does_command_exists(cmd): return which(cmd) is not None
return which(cmd) is not None
systemctl_exists = does_command_exists("systemctl") systemctl_exists = does_command_exists("systemctl")
bluetoothctl_exists = does_command_exists("bluetoothctl") bluetoothctl_exists = does_command_exists("bluetoothctl")
@ -37,10 +29,7 @@ powerprofilesctl_exists = does_command_exists("powerprofilesctl")
# detect if gnome power profile service is running # detect if gnome power profile service is running
if os.getenv("PKG_MARKER") != "SNAP": if os.getenv("PKG_MARKER") != "SNAP":
if systemctl_exists: if systemctl_exists:
try: try: gnome_power_status = call(["systemctl", "is-active", "--quiet", "power-profiles-daemon"])
gnome_power_status = call(
["systemctl", "is-active", "--quiet", "power-profiles-daemon"]
)
except: except:
print("\nUnable to determine init system") print("\nUnable to determine init system")
print("If this causes any problems, please submit an issue:") print("If this causes any problems, please submit an issue:")
@ -52,33 +41,22 @@ def tlp_service_detect():
status_output = getoutput("tlp-stat -s") status_output = getoutput("tlp-stat -s")
tlp_status = TLPStatusParser(status_output) tlp_status = TLPStatusParser(status_output)
if tlp_status.is_enabled(): if tlp_status.is_enabled():
print( warning()
"\n----------------------------------- Warning -----------------------------------\n"
)
print("Detected you are running a TLP service!") print("Detected you are running a TLP service!")
print( print("This daemon might interfere with auto-cpufreq which can lead to unexpected results.")
"This daemon might interfere with auto-cpufreq which can lead to unexpected results." print("We strongly encourage you to remove TLP unless you really know what you are doing.")
)
print(
"We strongly encourage you to remove TLP unless you really know what you are doing."
)
# alert about TLP when using snap # alert about TLP when using snap
def tlp_service_detect_snap(): def tlp_service_detect_snap():
print("\n----------------------------------- Warning -----------------------------------\n") warning()
print("Unable to detect if you are using a TLP service!") print("Unable to detect if you are using a TLP service!")
print("This daemon might interfere with auto-cpufreq which can lead to unexpected results.") print("This daemon might interfere with auto-cpufreq which can lead to unexpected results.")
print("We strongly encourage you not to use TLP unless you really know what you are doing.") print("We strongly encourage you not to use TLP unless you really know what you are doing.")
# alert in case gnome power profile service is running # alert in case gnome power profile service is running
def gnome_power_detect(): def gnome_power_detect():
if systemctl_exists: if systemctl_exists and not bool(gnome_power_status):
if gnome_power_status == 0: warning()
print(
"\n----------------------------------- Warning -----------------------------------\n"
)
print("Detected running GNOME Power Profiles daemon service!") print("Detected running GNOME Power Profiles daemon service!")
print("This daemon might interfere with auto-cpufreq and should be disabled.") print("This daemon might interfere with auto-cpufreq and should be disabled.")
print("\nSteps to perform this action using auto-cpufreq: power_helper script:") print("\nSteps to perform this action using auto-cpufreq: power_helper script:")
@ -87,14 +65,10 @@ def gnome_power_detect():
print("python3 power_helper.py --gnome_power_disable") print("python3 power_helper.py --gnome_power_disable")
print("\nReference: https://github.com/AdnanHodzic/auto-cpufreq#configuring-auto-cpufreq") print("\nReference: https://github.com/AdnanHodzic/auto-cpufreq#configuring-auto-cpufreq")
# automatically disable gnome power profile service in case it's running during install # automatically disable gnome power profile service in case it's running during install
def gnome_power_detect_install(): def gnome_power_detect_install():
if systemctl_exists: if systemctl_exists and not bool(gnome_power_status):
if gnome_power_status == 0: warning()
print(
"\n----------------------------------- Warning -----------------------------------\n"
)
print("Detected running GNOME Power Profiles daemon service!") print("Detected running GNOME Power Profiles daemon service!")
print("This daemon might interfere with auto-cpufreq and has been disabled.\n") print("This daemon might interfere with auto-cpufreq and has been disabled.\n")
print('This daemon is not automatically disabled in "monitor" mode and') print('This daemon is not automatically disabled in "monitor" mode and')
@ -103,10 +77,10 @@ def gnome_power_detect_install():
# notification on snap # notification on snap
def gnome_power_detect_snap(): def gnome_power_detect_snap():
print("\n----------------------------------- Warning -----------------------------------\n") warning()
print("Due to Snap package confinement limitations please consider installing auto-cpufreq using") print("Due to Snap package confinement limitations please consider installing auto-cpufreq using")
print("auto-cpufreq-installer: https://github.com/AdnanHodzic/auto-cpufreq/#auto-cpufreq-installer") print("auto-cpufreq-installer: https://github.com/AdnanHodzic/auto-cpufreq/#auto-cpufreq-installer")
print("") print()
print("Unable to detect state of GNOME Power Profiles daemon service!") print("Unable to detect state of GNOME Power Profiles daemon service!")
print("This daemon might interfere with auto-cpufreq and should be disabled.") print("This daemon might interfere with auto-cpufreq and should be disabled.")
print("\nSteps to perform this action using auto-cpufreq: power_helper script:") print("\nSteps to perform this action using auto-cpufreq: power_helper script:")
@ -115,18 +89,15 @@ def gnome_power_detect_snap():
print("python3 power_helper.py --gnome_power_disable") print("python3 power_helper.py --gnome_power_disable")
print("\nReference: https://github.com/AdnanHodzic/auto-cpufreq#configuring-auto-cpufreq") print("\nReference: https://github.com/AdnanHodzic/auto-cpufreq#configuring-auto-cpufreq")
# stops gnome >= 40 power profiles (live) # stops gnome >= 40 power profiles (live)
def gnome_power_stop_live(): def gnome_power_stop_live():
if systemctl_exists: if systemctl_exists and not bool(gnome_power_status) and powerprofilesctl_exists:
if gnome_power_status == 0 and powerprofilesctl_exists:
call(["powerprofilesctl", "set", "balanced"]) call(["powerprofilesctl", "set", "balanced"])
call(["systemctl", "stop", "power-profiles-daemon"]) call(["systemctl", "stop", "power-profiles-daemon"])
# starts gnome >= 40 power profiles (live) # starts gnome >= 40 power profiles (live)
def gnome_power_start_live(): def gnome_power_start_live():
if systemctl_exists: if systemctl_exists: call(["systemctl", "start", "power-profiles-daemon"])
call(["systemctl", "start", "power-profiles-daemon"])
# enable gnome >= 40 power profiles (uninstall) # enable gnome >= 40 power profiles (uninstall)
def gnome_power_svc_enable(): def gnome_power_svc_enable():
@ -142,7 +113,6 @@ def gnome_power_svc_enable():
print("If this causes any problems, please submit an issue:") print("If this causes any problems, please submit an issue:")
print("https://github.com/AdnanHodzic/auto-cpufreq/issues") print("https://github.com/AdnanHodzic/auto-cpufreq/issues")
# gnome power profiles current status # gnome power profiles current status
def gnome_power_svc_status(): def gnome_power_svc_status():
if systemctl_exists: if systemctl_exists:
@ -154,11 +124,9 @@ def gnome_power_svc_status():
print("If this causes any problems, please submit an issue:") print("If this causes any problems, please submit an issue:")
print("https://github.com/AdnanHodzic/auto-cpufreq/issues") print("https://github.com/AdnanHodzic/auto-cpufreq/issues")
# disable bluetooth on boot # disable bluetooth on boot
def bluetooth_disable(): def bluetooth_disable():
if os.getenv("PKG_MARKER") == "SNAP": if os.getenv("PKG_MARKER") == "SNAP": bluetooth_notif_snap()
bluetooth_notif_snap()
elif bluetoothctl_exists: elif bluetoothctl_exists:
print("* Turn off bluetooth on boot") print("* Turn off bluetooth on boot")
btconf = Path("/etc/bluetooth/main.conf") btconf = Path("/etc/bluetooth/main.conf")
@ -170,18 +138,12 @@ def bluetooth_disable():
f.seek(0) f.seek(0)
f.truncate() f.truncate()
f.write(content.replace(orig_set, change_set)) f.write(content.replace(orig_set, change_set))
except Exception as e: except Exception as e: print(f"\nERROR:\nWas unable to turn off bluetooth on boot\n{repr(e)}")
print(f"\nERROR:\nWas unable to turn off bluetooth on boot\n{repr(e)}") else: print("* Turn off bluetooth on boot [skipping] (package providing bluetooth access is not present)")
else:
print(
"* Turn off bluetooth on boot [skipping] (package providing bluetooth access is not present)"
)
# enable bluetooth on boot # enable bluetooth on boot
def bluetooth_enable(): def bluetooth_enable():
if os.getenv("PKG_MARKER") == "SNAP": if os.getenv("PKG_MARKER") == "SNAP": bluetooth_on_notif_snap()
bluetooth_on_notif_snap()
if bluetoothctl_exists: if bluetoothctl_exists:
print("* Turn on bluetooth on boot") print("* Turn on bluetooth on boot")
btconf = "/etc/bluetooth/main.conf" btconf = "/etc/bluetooth/main.conf"
@ -193,13 +155,8 @@ def bluetooth_enable():
f.seek(0) f.seek(0)
f.truncate() f.truncate()
f.write(content.replace(change_set, orig_set)) f.write(content.replace(change_set, orig_set))
except Exception as e: except Exception as e: print(f"\nERROR:\nWas unable to turn on bluetooth on boot\n{repr(e)}")
print(f"\nERROR:\nWas unable to turn on bluetooth on boot\n{repr(e)}") else: print("* Turn on bluetooth on boot [skipping] (package providing bluetooth access is not present)")
else:
print(
"* Turn on bluetooth on boot [skipping] (package providing bluetooth access is not present)"
)
# turn off bluetooth on snap message # turn off bluetooth on snap message
def bluetooth_notif_snap(): def bluetooth_notif_snap():
@ -207,27 +164,22 @@ def bluetooth_notif_snap():
print("\nSteps to perform this action using auto-cpufreq: power_helper script:") print("\nSteps to perform this action using auto-cpufreq: power_helper script:")
print("python3 power_helper.py --bluetooth_boot_off") print("python3 power_helper.py --bluetooth_boot_off")
# turn off bluetooth on snap message # turn off bluetooth on snap message
def bluetooth_on_notif_snap(): def bluetooth_on_notif_snap():
print("\n* Unable to turn on bluetooth on boot due to Snap package restrictions!") print("\n* Unable to turn on bluetooth on boot due to Snap package restrictions!")
print("\nSteps to perform this action using auto-cpufreq: power_helper script:") print("\nSteps to perform this action using auto-cpufreq: power_helper script:")
print("python3 power_helper.py --bluetooth_boot_on") print("python3 power_helper.py --bluetooth_boot_on")
# gnome power removal reminder # gnome power removal reminder
def gnome_power_rm_reminder(): def gnome_power_rm_reminder():
if systemctl_exists: if systemctl_exists and bool(gnome_power_status):
if gnome_power_status != 0: warning()
print(
"\n----------------------------------- Warning -----------------------------------\n"
)
print("Detected GNOME Power Profiles daemon service is stopped!") print("Detected GNOME Power Profiles daemon service is stopped!")
print("This service will now be enabled and started again.") print("This service will now be enabled and started again.")
def gnome_power_rm_reminder_snap(): def gnome_power_rm_reminder_snap():
print("\n----------------------------------- Warning -----------------------------------\n") warning()
print("Unable to detect state of GNOME Power Profiles daemon service!") print("Unable to detect state of GNOME Power Profiles daemon service!")
print("Now it's recommended to enable this service.") print("Now it's recommended to enable this service.")
print("\nSteps to perform this action using auto-cpufreq: power_helper script:") print("\nSteps to perform this action using auto-cpufreq: power_helper script:")
@ -236,13 +188,10 @@ def gnome_power_rm_reminder_snap():
print("python3 power_helper.py --gnome_power_enable") print("python3 power_helper.py --gnome_power_enable")
print("\nReference: https://github.com/AdnanHodzic/auto-cpufreq#configuring-auto-cpufreq") print("\nReference: https://github.com/AdnanHodzic/auto-cpufreq#configuring-auto-cpufreq")
def valid_options(): def valid_options():
print("--gnome_power_enable\t\tEnable GNOME Power Profiles daemon") print("--gnome_power_enable\t\tEnable GNOME Power Profiles daemon")
print("--gnome_power_disable\t\tDisable GNOME Power Profiles daemon\n") print("--gnome_power_disable\t\tDisable GNOME Power Profiles daemon\n")
def disable_power_profiles_daemon(): def disable_power_profiles_daemon():
# always disable power-profiles-daemon # always disable power-profiles-daemon
try: try:
@ -256,21 +205,18 @@ def disable_power_profiles_daemon():
print("If this causes any problems, please submit an issue:") print("If this causes any problems, please submit an issue:")
print("https://github.com/AdnanHodzic/auto-cpufreq/issues") print("https://github.com/AdnanHodzic/auto-cpufreq/issues")
# default gnome_power_svc_disable func (balanced) # default gnome_power_svc_disable func (balanced)
def gnome_power_svc_disable(): def gnome_power_svc_disable():
snap_pkg_check = 0 snap_pkg_check = 0
if systemctl_exists: if systemctl_exists:
# 0 is active if bool(gnome_power_status):
if gnome_power_status != 0:
try: try:
# check if snap package installed # check if snap package installed
snap_pkg_check = call(['snap', 'list', '|', 'grep', 'auto-cpufreq'], snap_pkg_check = call(['snap', 'list', '|', 'grep', 'auto-cpufreq'],
stdout=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT) stderr=subprocess.STDOUT)
# check if snapd is present and if snap package is installed | 0 is success # check if snapd is present and if snap package is installed | 0 is success
if snap_pkg_check == 0: if not bool(snap_pkg_check):
print("GNOME Power Profiles Daemon is already disabled, it can be re-enabled by running:\n" print("GNOME Power Profiles Daemon is already disabled, it can be re-enabled by running:\n"
"sudo python3 power_helper.py --gnome_power_enable\n" "sudo python3 power_helper.py --gnome_power_enable\n"
) )
@ -278,14 +224,12 @@ def gnome_power_svc_disable():
print("auto-cpufreq snap package not installed\nGNOME Power Profiles Daemon should be enabled. run:\n\n" print("auto-cpufreq snap package not installed\nGNOME Power Profiles Daemon should be enabled. run:\n\n"
"sudo python3 power_helper.py --gnome_power_enable" "sudo python3 power_helper.py --gnome_power_enable"
) )
except: except:
# snapd not found on the system # snapd not found on the system
print("There was a problem, couldn't determine GNOME Power Profiles Daemon") print("There was a problem, couldn't determine GNOME Power Profiles Daemon")
snap_pkg_check = 0 snap_pkg_check = 0
if gnome_power_status == 0 and powerprofilesctl_exists: if not bool(gnome_power_status) and powerprofilesctl_exists:
if snap_pkg_check == 1: if snap_pkg_check == 1:
print("auto-cpufreq snap package not installed.\nGNOME Power Profiles Daemon should be enabled, run:\n\n" print("auto-cpufreq snap package not installed.\nGNOME Power Profiles Daemon should be enabled, run:\n\n"
"sudo python3 power_helper.py --gnome_power_enable" "sudo python3 power_helper.py --gnome_power_enable"
@ -305,8 +249,7 @@ def gnome_power_svc_disable():
# * update readme/docs # * update readme/docs
@click.option("--gnome_power_enable", is_flag=True, help="Enable GNOME Power profiles service") @click.option("--gnome_power_enable", is_flag=True, help="Enable GNOME Power profiles service")
@click.option("--gnome_power_status", is_flag=True, help="Get status of GNOME Power profiles service" @click.option("--gnome_power_status", is_flag=True, help="Get status of GNOME Power profiles service")
)
@click.option("--bluetooth_boot_on", is_flag=True, help="Turn on Bluetooth on boot") @click.option("--bluetooth_boot_on", is_flag=True, help="Turn on Bluetooth on boot")
@click.option("--bluetooth_boot_off", is_flag=True, help="Turn off Bluetooth on boot") @click.option("--bluetooth_boot_off", is_flag=True, help="Turn off Bluetooth on boot")
def main( def main(
@ -316,46 +259,18 @@ def main(
bluetooth_boot_off, bluetooth_boot_off,
bluetooth_boot_on, bluetooth_boot_on,
): ):
root_check() root_check()
if len(sys.argv) == 1:
header() header()
print(
'Unrecognized option!\n\nRun: "' + app_name + ' --help" for list of available options.' if len(sys.argv) == 1: print('Unrecognized option!\n\nRun: "' + app_name + ' --help" for list of available options.')
)
footer()
else: else:
if gnome_power_enable: if gnome_power_enable: gnome_power_svc_enable()
header() elif gnome_power_disable: gnome_power_svc_disable()
root_check() elif gnome_power_status: gnome_power_svc_status()
gnome_power_svc_enable() elif bluetooth_boot_off: bluetooth_disable()
helper_opts() elif bluetooth_boot_on: bluetooth_enable()
footer()
elif gnome_power_disable:
header()
root_check()
gnome_power_svc_disable()
helper_opts()
footer()
elif gnome_power_status:
header()
root_check()
gnome_power_svc_status()
helper_opts()
footer()
elif bluetooth_boot_off:
header()
root_check()
bluetooth_disable()
helper_opts()
footer()
elif bluetooth_boot_on:
header()
root_check()
bluetooth_enable()
helper_opts() helper_opts()
footer() footer()
if __name__ == "__main__": main()
if __name__ == "__main__":
main()

View File

@ -6,14 +6,8 @@ class TLPStatusParser:
def _parse(self, data): def _parse(self, data):
for line in data.split("\n"): for line in data.split("\n"):
key_val = line.split("=", 1) key_val = line.split("=", 1)
if len(key_val) > 1: if len(key_val) > 1: self.data[key_val[0].strip().lower()] = key_val[1].strip()
self.data[key_val[0].strip().lower()] = key_val[1].strip()
def _get_key(self, key): def _get_key(self, key): return self.data[key] if key in self.data else ""
if key in self.data:
return self.data[key]
else:
return ""
def is_enabled(self): def is_enabled(self): return self._get_key("state") == "enabled"
return self._get_key("state") == "enabled"

View File

@ -17,7 +17,6 @@ def find_config_file(args_config_file: str | None) -> str:
:param args_config_file: Path to the config file provided as a command line argument :param args_config_file: Path to the config file provided as a command line argument
:return: The path to the config file to use :return: The path to the config file to use
""" """
# Prepare paths # Prepare paths
# use $SUDO_USER or $USER to get home dir since sudo can't access # use $SUDO_USER or $USER to get home dir since sudo can't access
@ -25,23 +24,21 @@ def find_config_file(args_config_file: str | None) -> str:
home = run(["getent passwd ${SUDO_USER:-$USER} | cut -d: -f6"], home = run(["getent passwd ${SUDO_USER:-$USER} | cut -d: -f6"],
shell=True, shell=True,
stdout=PIPE, stdout=PIPE,
universal_newlines=True).stdout.rstrip() universal_newlines=True
).stdout.rstrip()
user_config_dir = os.getenv("XDG_CONFIG_HOME", default=os.path.join(home, ".config")) user_config_dir = os.getenv("XDG_CONFIG_HOME", default=os.path.join(home, ".config"))
user_config_file = os.path.join(user_config_dir, "auto-cpufreq/auto-cpufreq.conf") user_config_file = os.path.join(user_config_dir, "auto-cpufreq/auto-cpufreq.conf")
system_config_file = "/etc/auto-cpufreq.conf" system_config_file = "/etc/auto-cpufreq.conf"
if args_config_file is not None: # (1) Command line argument was specified if args_config_file is not None: # (1) Command line argument was specified
# Check if the config file path points to a valid file # Check if the config file path points to a valid file
if os.path.isfile(args_config_file): if os.path.isfile(args_config_file): return args_config_file
return args_config_file
else: else:
# Not a valid file # Not a valid file
print(f"Config file specified with '--config {args_config_file}' not found.") print(f"Config file specified with '--config {args_config_file}' not found.")
sys.exit(1) sys.exit(1)
elif os.path.isfile(user_config_file): # (2) User config file elif os.path.isfile(user_config_file): return user_config_file # (2) User config file
return user_config_file else: return system_config_file # (3) System config file (default if nothing else is found)
else: # (3) System config file (default if nothing else is found)
return system_config_file
class _Config: class _Config:
def __init__(self) -> None: def __init__(self) -> None:
@ -51,17 +48,13 @@ class _Config:
self.config_handler = ConfigEventHandler(self) self.config_handler = ConfigEventHandler(self)
# check for file changes using threading # check for file changes using threading
self.notifier: pyinotify.ThreadedNotifier = pyinotify.ThreadedNotifier( self.notifier: pyinotify.ThreadedNotifier = pyinotify.ThreadedNotifier(self.watch_manager, self.config_handler)
self.watch_manager, self.config_handler)
def set_path(self, path: str) -> None: def set_path(self, path: str) -> None:
self.path = path; self.path = path
mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY \ mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY | pyinotify.IN_MOVED_FROM | pyinotify.IN_MOVED_TO
| pyinotify.IN_MOVED_FROM | pyinotify.IN_MOVED_TO
self.watch_manager.add_watch(os.path.dirname(path), mask=mask) self.watch_manager.add_watch(os.path.dirname(path), mask=mask)
if os.path.isfile(path): if os.path.isfile(path): self.update_config()
self.update_config()
def has_config(self) -> bool: def has_config(self) -> bool:
return os.path.isfile(self.path) return os.path.isfile(self.path)
@ -72,9 +65,7 @@ class _Config:
def update_config(self) -> None: def update_config(self) -> None:
# create new ConfigParser to prevent old data from remaining # create new ConfigParser to prevent old data from remaining
self._config = ConfigParser() self._config = ConfigParser()
try: try: self._config.read(self.path)
self._config.read(self.path) except ParsingError as e: print(f"The following error occured while parsing the config file: \n{e}")
except ParsingError as e:
print(f"The following error occured while parsing the config file: \n{e}")
config = _Config() config = _Config()

View File

@ -3,103 +3,94 @@
# auto-cpufreq daemon install script # auto-cpufreq daemon install script
# reference: https://github.com/AdnanHodzic/auto-cpufreq # reference: https://github.com/AdnanHodzic/auto-cpufreq
# Thanks to https://github.com/errornonamer for openrc fix # Thanks to https://github.com/errornonamer for openrc fix
echo -e "\n------------------ Running auto-cpufreq daemon install script ------------------"
if [[ $EUID != 0 ]]; MID="$((`tput cols` / 2))"
then
echo -e "\nERROR\nMust be run as root (i.e: 'sudo $0')\n" echo
printf "%0.s─" $(seq $((MID-(${#1}/2)-2)))
printf " Running auto-cpufreq daemon install script "
printf "%0.s─" $(seq $((MID-(${#1}/2)-2)))
echo; echo
# root check
if ((EUID != 0)); then
echo; echo "Must be run as root (i.e: 'sudo $0')."; echo
exit 1 exit 1
fi fi
# First argument is the "sv" path, second argument is the "service" path this # First argument is the init name, second argument is the start command, third argument is the enable command
# only exist because the path between distros may vary function auto_cpufreq_install {
runit_ln() { echo -e "\n* Starting auto-cpufreq daemon ($1) service"
echo -e "\n* Deploy auto-cpufreq runit unit file" $2
echo -e "\n* Enabling auto-cpufreq daemon ($1) at boot"
$3
}
case "$(ps h -o comm 1)" in
dinit)
echo -e "\n* Deploying auto-cpufreq (dinit) unit file"
cp /usr/local/share/auto-cpufreq/scripts/auto-cpufreq-dinit /etc/dinit.d/auto-cpufreq
auto_cpufreq_install "dinit" "dinitctl start auto-cpufreq" "dinitctl enable auto-cpufreq"
;;
init)
echo -e "\n* Deploying auto-cpufreq openrc unit file"
cp /usr/local/share/auto-cpufreq/scripts/auto-cpufreq-openrc /etc/init.d/auto-cpufreq
chmod +x /etc/init.d/auto-cpufreq
auto_cpufreq_install "openrc" "rc-service auto-cpufreq start" "rc-update add auto-cpufreq"
;;
runit)
# First argument is the "sv" path, second argument is the "service" path
runit_ln() {
echo -e "\n* Deploying auto-cpufreq (runit) unit file"
mkdir "$1"/sv/auto-cpufreq mkdir "$1"/sv/auto-cpufreq
cp /usr/local/share/auto-cpufreq/scripts/auto-cpufreq-runit "$1"/sv/auto-cpufreq/run cp /usr/local/share/auto-cpufreq/scripts/auto-cpufreq-runit "$1"/sv/auto-cpufreq/run
chmod +x "$1"/sv/auto-cpufreq/run chmod +x "$1"/sv/auto-cpufreq/run
echo -e "\n* Creating symbolic link ($2/service/auto-cpufreq -> $1/sv/auto-cpufreq)" echo -e "\n* Creating symbolic link ($2/service/auto-cpufreq -> $1/sv/auto-cpufreq)"
ln -s "$1"/sv/auto-cpufreq "$2"/service ln -s "$1"/sv/auto-cpufreq "$2"/service
}
# sv commands auto_cpufreq_install "runit"
sv_cmd() {
echo -e "\n* Stopping auto-cpufreq daemon (runit) service"
sv stop auto-cpufreq
echo -e "\n* Starting auto-cpufreq daemon (runit) service"
sv start auto-cpufreq sv start auto-cpufreq
sv up auto-cpufreq sv up auto-cpufreq
} }
# Installation for runit, we still look for the distro because of the path may
# vary.
if [ "$(ps h -o comm 1)" = "runit" ];then
if [ -f /etc/os-release ];then if [ -f /etc/os-release ];then
eval "$(cat /etc/os-release)" ./etc/os-release
case $ID in case $ID in
void) void) runit_ln /etc /var;;
runit_ln /etc /var artix) runit_ln /etc/runit /run/runit;;
sv_cmd
;;
artix)
# Note: Artix supports other inits than runnit
runit_ln /etc/runit /run/runit
sv_cmd
;;
*) *)
echo -e "\n* Runit init detected but your distro is not supported\n" echo -e "\n* Runit init detected but your distro is not supported\n"
echo -e "\n* Please open an issue on https://github.com/AdnanHodzic/auto-cpufreq\n" echo -e "\n* Please open an issue on https://github.com/AdnanHodzic/auto-cpufreq\n"
esac esac
fi fi
# Install script for systemd ;;
elif [ "$(ps h -o comm 1)" = "systemd" ];then systemd)
echo -e "\n* Deploy auto-cpufreq systemd unit file" echo -e "\n* Deploying auto-cpufreq systemd unit file"
cp /usr/local/share/auto-cpufreq/scripts/auto-cpufreq.service /etc/systemd/system/auto-cpufreq.service cp /usr/local/share/auto-cpufreq/scripts/auto-cpufreq.service /etc/systemd/system/auto-cpufreq.service
echo -e "\n* Reloading systemd manager configuration" echo -e "\n* Reloading systemd manager configuration"
systemctl daemon-reload systemctl daemon-reload
echo -e "\n* Stopping auto-cpufreq daemon (systemd) service" auto_cpufreq_install "systemd" "systemctl start auto-cpufreq" "systemctl enable auto-cpufreq"
systemctl stop auto-cpufreq ;;
s6-svscan)
echo -e "\n* Starting auto-cpufreq daemon (systemd) service" echo -e "\n* Deploying auto-cpufreq (s6) unit file"
systemctl start auto-cpufreq
echo -e "\n* Enabling auto-cpufreq daemon (systemd) service at boot"
systemctl enable auto-cpufreq
# Install script for openrc
elif [ "$(ps h -o comm 1)" = "init" ];then
echo -e "\n* Deploying auto-cpufreq openrc unit file"
cp /usr/local/share/auto-cpufreq/scripts/auto-cpufreq-openrc /etc/init.d/auto-cpufreq
chmod +x /etc/init.d/auto-cpufreq
echo -e "Starting auto-cpufreq daemon (openrc) service"
rc-service auto-cpufreq start
echo -e "\n* Enabling auto-cpufreq daemon (openrc) service at boot"
rc-update add auto-cpufreq
# Install script for s6
elif [ "$(ps h -o comm 1)" = "s6-svscan" ];then
echo -e "\n* Deploying auto-cpufreq s6 unit file"
cp -r /usr/local/share/auto-cpufreq/scripts/auto-cpufreq-s6 /etc/s6/sv/auto-cpufreq cp -r /usr/local/share/auto-cpufreq/scripts/auto-cpufreq-s6 /etc/s6/sv/auto-cpufreq
echo -e "\n* Add auto-cpufreq service (s6) to default bundle" echo -e "\n* Add auto-cpufreq service (s6) to default bundle"
s6-service add default auto-cpufreq s6-service add default auto-cpufreq
echo -e "Starting auto-cpufreq daemon (s6) service"
s6-rc -u change auto-cpufreq default auto_cpufreq_install "s6" "s6-rc -u change auto-cpufreq default"
echo -e "\n* Update daemon service bundle (s6)" echo -e "\n* Update daemon service bundle (s6)"
s6-db-reload s6-db-reload
# Install script for dinit ;;
elif [ "$(ps h -o comm 1)" = "dinit" ];then *)
echo -e "\n* Deploying auto-cpufreq dinit unit file"
cp /usr/local/share/auto-cpufreq/scripts/auto-cpufreq-dinit /etc/dinit.d/auto-cpufreq
echo -e "Starting auto-cpufreq daemon (dinit) service"
dinitctl start auto-cpufreq
echo -e "\n* Enabling auto-cpufreq daemon (dinit) service at boot"
dinitctl enable auto-cpufreq
else
echo -e "\n* Unsupported init system detected, could not install the daemon\n" echo -e "\n* Unsupported init system detected, could not install the daemon\n"
echo -e "\n* Please open an issue on https://github.com/AdnanHodzic/auto-cpufreq\n" echo -e "\n* Please open an issue on https://github.com/AdnanHodzic/auto-cpufreq\n"
fi ;;
esac

View File

@ -4,83 +4,68 @@
# reference: https://github.com/AdnanHodzic/auto-cpufreq # reference: https://github.com/AdnanHodzic/auto-cpufreq
# Thanks to https://github.com/errornonamer for openrc fix # Thanks to https://github.com/errornonamer for openrc fix
echo -e "\n------------------ Running auto-cpufreq daemon removal script ------------------" MID="$((`tput cols` / 2))"
if [[ $EUID != 0 ]]; then echo
echo -e "\nERROR\nMust be run as root (i.e: 'sudo $0')\n" printf "%0.s─" $(seq $((MID-(${#1}/2)-2)))
printf " Running auto-cpufreq daemon removal script "
printf "%0.s─" $(seq $((MID-(${#1}/2)-2)))
echo; echo
# root check
if ((EUID != 0)); then
echo; echo "Must be run as root (i.e: 'sudo $0')."; echo
exit 1 exit 1
fi fi
# First argument is the "sv" path, second argument is the "service" path # First argument is the init name, second argument is the stop command, third argument is the disable command and the fourth is the "service" path
rm_sv() { function auto_cpufreq_remove {
echo -e "\n* Stopping auto-cpufreq daemon (runit) service" echo -e "\n* Stopping auto-cpufreq daemon ($1) service"
sv stop auto-cpufreq $2
echo -e "\n* Disabling auto-cpufreq daemon ($1) at boot"
echo -e "\n* Removing auto-cpufreq daemon (runit) unit files" $3
rm -rf "$1"/sv/auto-cpufreq echo -e "\n* Removing auto-cpufreq daemon ($1) unit file"
rm -rf "$2"/service/auto-cpufreq rm $4
} }
# Remove service for runit case "$(ps h -o comm 1)" in
if [ "$(ps h -o comm 1)" = "runit" ];then dinit) auto_cpufreq_remove "dinit" "dinitctl stop auto-cpufreq" "dinitctl disable auto-cpufreq" "/etc/dinit.d/auto-cpufreq";;
if [ -f /etc/os-release ];then init) auto_cpufreq_remove "openrc" "rc-service auto-cpufreq stop" "rc-update del auto-cpufreq" "/etc/init.d/auto-cpufreq";;
eval "$(cat /etc/os-release)" runit)
# First argument is the "sv" path, second argument is the "service" path
rm_sv() {
auto_cpufreq_remove "runit" "sv stop auto-cpufreq" "" "-rf $1/sv/auto-cpufreq $2/service/auto-cpufreq"
}
if [ -f /etc/os-release ]; then
. /etc/os-release
case $ID in case $ID in
void) void) rm_sv /etc /var;;
rm_sv /etc /var ;; artix) rm_sv /etc/runit /run/runit;;
artix)
rm_sv /etc/runit /run/runit ;;
*) *)
echo -e "\n* Runit init detected but your distro is not supported\n" echo -e "\n* Runit init detected but your distro is not supported\n"
echo -e "\n* Please open an issue on https://github.com/AdnanHodzic/auto-cpufreq\n" echo -e "\n* Please open an issue on https://github.com/AdnanHodzic/auto-cpufreq\n"
;;
esac esac
fi fi
# Remove service for systemd ;;
elif [ "$(ps h -o comm 1)" = "systemd" ];then systemd)
echo -e "\n* Stopping auto-cpufreq daemon (systemd) service" auto_cpufreq_remove "systemd" "systemctl stop auto-cpufreq" "systemctl disable auto-cpufreq" "/etc/systemd/system/auto-cpufreq.service"
systemctl stop auto-cpufreq
echo -e "\n* Disabling auto-cpufreq daemon (systemd) at boot"
systemctl disable auto-cpufreq
echo -e "\n* Removing auto-cpufreq daemon (systemd) unit file"
rm /etc/systemd/system/auto-cpufreq.service
echo -e "\n* Reloading systemd manager configuration" echo -e "\n* Reloading systemd manager configuration"
systemctl daemon-reload systemctl daemon-reload
echo -e "reset failed" echo "reset failed"
systemctl reset-failed systemctl reset-failed
# Remove service for openrc ;;
elif [ "$(ps h -o comm 1)" = "init" ];then s6-svscan)
echo -e "\n* Stopping auto-cpufreq daemon (openrc) service" auto_cpufreq_remove "s6" "" "s6-service delete default auto-cpufreq" "-rf /etc/s6/sv/auto-cpufreq"
rc-service auto-cpufreq stop
echo -e "\n* Disabling auto-cpufreq daemon (openrc) at boot"
rc-update del auto-cpufreq
echo -e "\n* Removing auto-cpufreq daemon (openrc) unit file"
rm /etc/init.d/auto-cpufreq
# Remove service for s6
elif [ "$(ps h -o comm 1)" = "s6-svscan" ];then
echo -e "\n* Disabling auto-cpufreq daemon (s6) at boot"
s6-service delete default auto-cpufreq
echo -e "\n* Removing auto-cpufreq daemon (s6) unit file"
rm -rf /etc/s6/sv/auto-cpufreq
echo -e "\n* Update daemon service bundle (s6)" echo -e "\n* Update daemon service bundle (s6)"
s6-db-reload s6-db-reload
# Remove service for dinit ;;
elif [ "$(ps h -o comm 1)" = "init" ];then *)
echo -e "\n* Stopping auto-cpufreq daemon (dinit) service" echo -e "\n* Unsupported init system detected, could not remove the daemon"
dinitctl stop auto-cpufreq
echo -e "\n* Disabling auto-cpufreq daemon (dinit) at boot"
dinitctl disable auto-cpufreq
echo -e "\n* Removing auto-cpufreq daemon (dinit) unit file"
rm /etc/dinit.d/auto-cpufreq
else
echo -e "\n* Unsupported init system detected, could not remove the daemon\n"
echo -e "\n* Please open an issue on https://github.com/AdnanHodzic/auto-cpufreq\n" echo -e "\n* Please open an issue on https://github.com/AdnanHodzic/auto-cpufreq\n"
fi ;;
esac

View File

@ -16,18 +16,17 @@ err_exit()
# invocation handling # invocation handling
# #
# load python virtual environment # load python virtual environment
venv_dir=/opt/auto-cpufreq/venv venv_dir=/opt/auto-cpufreq/venv
. "${venv_dir}/bin/activate" . "$venv_dir/bin/activate"
# run python code with venv loaded # run python code with venv loaded
if [[ "${#}" -ne 1 ]]; then if [[ "$#" -ne 1 ]]; then
PYTHONPATH=/opt/auto-cpufreq \ PYTHONPATH=/opt/auto-cpufreq \
/opt/auto-cpufreq/venv/bin/python \ /opt/auto-cpufreq/venv/bin/python \
/opt/auto-cpufreq/venv/bin/auto-cpufreq /opt/auto-cpufreq/venv/bin/auto-cpufreq
else else
param="${1}" param="$1"
PYTHONPATH=/opt/auto-cpufreq \ PYTHONPATH=/opt/auto-cpufreq \
/opt/auto-cpufreq/venv/bin/python \ /opt/auto-cpufreq/venv/bin/python \
/opt/auto-cpufreq/venv/bin/auto-cpufreq \ /opt/auto-cpufreq/venv/bin/auto-cpufreq \

View File

@ -1,20 +1,19 @@
#!/usr/bin/env bash #!/usr/bin/env bash
VERSION='20' VERSION='20'
cpucount=`cat /proc/cpuinfo|grep processor|wc -l` cpucount=`cat /proc/cpuinfo | grep processor | wc -l`
FLROOT=/sys/devices/system/cpu FLROOT=/sys/devices/system/cpu
DRIVER=auto DRIVER=auto
VERBOSE=0 VERBOSE=0
## parse special options ## parse special options
for i in "$@" for i in "$@"; do
do case $i in
case $i in
-v|--verbose) -v|--verbose)
VERBOSE=1 VERBOSE=1
shift shift
;; ;;
--set=*) -s=*|--set=*)
VALUE="${i#*=}" VALUE="${i#*=}"
shift shift
;; ;;
@ -22,7 +21,7 @@ case $i in
CORE="${i#*=}" CORE="${i#*=}"
shift shift
;; ;;
--available) -a|--available)
AVAILABLE=1 AVAILABLE=1
shift shift
;; ;;
@ -30,41 +29,39 @@ case $i in
OPTION=$i OPTION=$i
shift shift
;; ;;
*) # unknown *) exit 1;;
;; esac
esac
done done
function help () { function help () {
echo "Package version: "$VERSION echo "Package version: "$VERSION
echo "Usage:" echo "Usage: cpufreqctl [OPTION[=VALUE]...]"
echo " cpufreqctl [OPTION[=VALUE]...]" echo
echo "" echo " -h, --help Show help options"
echo " --help Show help options"
echo " --version Package version" echo " --version Package version"
echo " --verbose, -v Verbose output" echo " -v, --verbose Verbose output"
echo "" echo
echo " --set=VALUE Set VALUE for selected option" echo " -s, --set =VALUE Set VALUE for selected option"
echo " --core=NUMBER Apply selected option just for the core NUMBER (0 ~ N - 1)" echo " -c, --core =NUMBER Apply selected option just for the core NUMBER (0 ~ N - 1)"
echo " --available Get available values instand of default: current" echo " -a, --available Get available values instand of default: current"
echo "" echo
echo " --driver Current processor driver" echo " -d, --driver Current processor driver"
echo " --governor Scaling governor's options" echo " -g, --governor Scaling governor's options"
echo " --epp Governor's energy_performance_preference options" echo " -e, --epp Governor's energy_performance_preference options"
echo " --frequency Frequency options" echo " -f, --frequency Frequency options"
echo " --on Turn on --core=NUMBER" echo " --on Turn on --core=NUMBER"
echo " --off Turn off --core=NUMBER" echo " --off Turn off --core=NUMBER"
echo " --frequency-min Minimal frequency options" echo " --frequency-min Minimal frequency options"
echo " --frequency-max Maximum frequency options" echo " --frequency-max Maximum frequency options"
echo " --frequency-min-limit Get minimal frequency limit" echo " --frequency-min-limit Get minimal frequency limit"
echo " --frequency-max-limit Get maximum frequency limit" echo " --frequency-max-limit Get maximum frequency limit"
echo " --boost Current cpu boost value" echo " -b, --boost Current cpu boost value"
echo "" echo
echo "intel_pstate options" echo "intel_pstate options"
echo " --no-turbo Current no_turbo value" echo " --no-turbo Current no_turbo value"
echo " --min-perf Current min_perf_pct options" echo " --min-perf Current min_perf_pct options"
echo " --max-perf Current max_perf_pct options" echo " --max-perf Current max_perf_pct options"
echo "" echo
echo "Events options" echo "Events options"
echo " --throttle Get thermal throttle counter" echo " --throttle Get thermal throttle counter"
echo " --throttle-event Get kernel thermal throttle events counter" echo " --throttle-event Get kernel thermal throttle events counter"
@ -73,27 +70,24 @@ function help () {
function info () { function info () {
echo "CPU driver: "`driver` echo "CPU driver: "`driver`
echo "Governors: "`cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors` echo "Governors: "`cat $FLROOT/cpu0/cpufreq/scaling_available_governors`
echo "Frequencies: "`cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies` echo "Frequencies: "`cat $FLROOT/cpu0/cpufreq/scaling_available_frequencies`
echo "" echo
echo "Usage:" echo "Usage:"
echo "## list scaling governors:" echo "## list scaling governors:"
echo "cpufreqctl --governor" echo "cpufreqctl --governor"
echo "" echo
echo "## Set all active cpu cores to the 'performance' scaling governor:" echo "## Set all active cpu cores to the 'performance' scaling governor:"
echo "cpufreqctl --governor --set=performance" echo "cpufreqctl --governor --set=performance"
echo "" echo
echo "## Set 'performance' scaling governor for the selected core:" echo "## Set 'performance' scaling governor for the selected core:"
echo "cpufreqctl --governor --set=performance --core=0" echo "cpufreqctl --governor --set=performance --core=0"
echo "" echo
echo "Use --help argument to see available options" echo "Use --help argument to see available options"
} }
verbose () { verbose () {
if [ $VERBOSE = 1 ] if [ $VERBOSE = 1 ]; then echo $1; fi
then
echo $1
fi
} }
function driver () { function driver () {
@ -101,9 +95,7 @@ function driver () {
} }
function write_value () { function write_value () {
if [ -w $FLNM ]; then if [ -w $FLNM ]; then echo $VALUE > $FLNM; fi
echo $VALUE > $FLNM
fi
} }
function set_driver () { function set_driver () {
@ -119,376 +111,267 @@ function get_governor () {
then then
i=0 i=0
ag='' ag=''
while [ $i -ne $cpucount ] while [ $i -ne $cpucount ]; do
do if [ $i = 0 ]; then ag=`cat $FLROOT/cpu0/cpufreq/scaling_governor`
if [ $i = 0 ] else ag=$ag' '`cat $FLROOT/cpu$i/cpufreq/scaling_governor`
then
ag=`cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor`
else
ag=$ag' '`cat /sys/devices/system/cpu/cpu$i/cpufreq/scaling_governor`
fi fi
i=`expr $i + 1` i=`expr $i + 1`
done done
echo $ag echo $ag
else else cat $FLROOT/cpu$CORE/cpufreq/scaling_governor
cat /sys/devices/system/cpu/cpu$CORE/cpufreq/scaling_governor
fi fi
} }
function set_governor () { function set_governor () {
if [ -z $CORE ] if [ -z $CORE ]; then
then
i=0 i=0
while [ $i -ne $cpucount ] while [ $i -ne $cpucount ]; do
do
FLNM="$FLROOT/cpu"$i"/cpufreq/scaling_governor" FLNM="$FLROOT/cpu"$i"/cpufreq/scaling_governor"
write_value write_value
i=`expr $i + 1` i=`expr $i + 1`
done done
else else echo $VALUE > $FLROOT/cpu$CORE/cpufreq/scaling_governor
echo $VALUE > /sys/devices/system/cpu/cpu$CORE/cpufreq/scaling_governor
fi fi
} }
function get_frequency () { function get_frequency () {
if [ -z $CORE ] if [ -z $CORE ]; then
then
i=0 i=0
V=0 V=0
M=$(cat "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq") M=$(cat "$FLROOT/cpu0/cpufreq/scaling_cur_freq")
while [ $i -ne $cpucount ] while [ $i -ne $cpucount ]; do
do V=$(cat "$FLROOT/cpu"$i"/cpufreq/scaling_cur_freq")
V=$(cat "/sys/devices/system/cpu/cpu"$i"/cpufreq/scaling_cur_freq") if [[ $V > $M ]]; then M=$V; fi
if [[ $V > $M ]]
then
M=$V
fi
i=`expr $i + 1` i=`expr $i + 1`
done done
echo "$M" echo "$M"
else else cat $FLROOT/cpu$CORE/cpufreq/scaling_cur_freq
cat /sys/devices/system/cpu/cpu$CORE/cpufreq/scaling_cur_freq
fi fi
} }
function set_frequency () { function set_frequency () {
set_driver set_driver
if [ $DRIVER = 'pstate'] if [ $DRIVER = 'pstate' ]; then
then
echo "Unavailable function for intel_pstate" echo "Unavailable function for intel_pstate"
return return
fi fi
if [ -z $CORE ] if [ -z $CORE ]; then
then
i=0 i=0
while [ $i -ne $cpucount ] while [ $i -ne $cpucount ]; do
do
FLNM="$FLROOT/cpu"$i"/cpufreq/scaling_setspeed" FLNM="$FLROOT/cpu"$i"/cpufreq/scaling_setspeed"
write_value write_value
i=`expr $i + 1` i=`expr $i + 1`
done done
else else echo $VALUE > $FLROOT/cpu$CORE/cpufreq/scaling_setspeed
echo $VALUE > /sys/devices/system/cpu/cpu$CORE/cpufreq/scaling_setspeed
fi fi
} }
function get_frequency_min () { function get_frequency_min () {
if [ -z $CORE ] if [ -z $CORE ]; then CORE=0; fi
then cat $FLROOT/cpu$CORE/cpufreq/scaling_min_freq
CORE=0
fi
cat /sys/devices/system/cpu/cpu$CORE/cpufreq/scaling_min_freq
} }
function set_frequency_min () { function set_frequency_min () {
if [ -z $CORE ] if [ -z $CORE ]; then
then
i=0 i=0
while [ $i -ne $cpucount ] while [ $i -ne $cpucount ]; do
do
FLNM="$FLROOT/cpu"$i"/cpufreq/scaling_min_freq" FLNM="$FLROOT/cpu"$i"/cpufreq/scaling_min_freq"
write_value write_value
i=`expr $i + 1` i=`expr $i + 1`
done done
else else echo $VALUE > $FLROOT/cpu$CORE/cpufreq/scaling_min_freq
echo $VALUE > /sys/devices/system/cpu/cpu$CORE/cpufreq/scaling_min_freq
fi fi
} }
function get_frequency_max () { function get_frequency_max () {
if [ -z $CORE ] if [ -z $CORE ]; then CORE=0; fi
then cat $FLROOT/cpu$CORE/cpufreq/scaling_max_freq
CORE=0
fi
cat /sys/devices/system/cpu/cpu$CORE/cpufreq/scaling_max_freq
} }
function set_frequency_max () { function set_frequency_max () {
if [ -z $CORE ] if [ -z $CORE ]; then
then
i=0 i=0
while [ $i -ne $cpucount ] while [ $i -ne $cpucount ]; do
do
FLNM="$FLROOT/cpu"$i"/cpufreq/scaling_max_freq" FLNM="$FLROOT/cpu"$i"/cpufreq/scaling_max_freq"
write_value write_value
i=`expr $i + 1` i=`expr $i + 1`
done done
else else echo $VALUE > $FLROOT/cpu$CORE/cpufreq/scaling_max_freq
echo $VALUE > /sys/devices/system/cpu/cpu$CORE/cpufreq/scaling_max_freq
fi fi
} }
function get_frequency_min_limit () { function get_frequency_min_limit () {
if [ -z $CORE ] if [ -z $CORE ]; then CORE=0; fi
then cat $FLROOT/cpu$CORE/cpufreq/cpuinfo_min_freq
CORE=0
fi
cat /sys/devices/system/cpu/cpu$CORE/cpufreq/cpuinfo_min_freq
} }
function get_frequency_max_limit () { function get_frequency_max_limit () {
if [ -z $CORE ] if [ -z $CORE ]; then CORE=0; fi
then cat $FLROOT/cpu$CORE/cpufreq/cpuinfo_max_freq
CORE=0
fi
cat /sys/devices/system/cpu/cpu$CORE/cpufreq/cpuinfo_max_freq
} }
function get_energy_performance_preference () { function get_energy_performance_preference () {
if [ -z $CORE ] if [ -z $CORE ]; then
then
i=0 i=0
ag='' ag=''
while [ $i -ne $cpucount ] while [ $i -ne $cpucount ]; do
do if [ $i = 0 ]; then
if [ $i = 0 ] ag=`cat $FLROOT/cpu0/cpufreq/energy_performance_preference`
then
ag=`cat /sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference`
else else
ag=$ag' '`cat /sys/devices/system/cpu/cpu$i/cpufreq/energy_performance_preference` ag=$ag' '`cat $FLROOT/cpu$i/cpufreq/energy_performance_preference`
fi fi
i=`expr $i + 1` i=`expr $i + 1`
done done
echo $ag echo $ag
else else cat $FLROOT/cpu$CORE/cpufreq/energy_performance_preference
cat /sys/devices/system/cpu/cpu$CORE/cpufreq/energy_performance_preference
fi fi
} }
function set_energy_performance_preference () { function set_energy_performance_preference () {
if [ -z $CORE ] if [ -z $CORE ]; then
then
i=0 i=0
while [ $i -ne $cpucount ] while [ $i -ne $cpucount ]; do
do
FLNM="$FLROOT/cpu"$i"/cpufreq/energy_performance_preference" FLNM="$FLROOT/cpu"$i"/cpufreq/energy_performance_preference"
write_value write_value
i=`expr $i + 1` i=`expr $i + 1`
done done
else else echo $VALUE > $FLROOT/cpu$CORE/cpufreq/energy_performance_preference
echo $VALUE > /sys/devices/system/cpu/cpu$CORE/cpufreq/energy_performance_preference
fi fi
} }
if [ -z $OPTION ] # No options case $OPTION in
then -h|--help) help;;
info --version) echo $VERSION;;
exit -d|--driver) driver;;
fi -g|--governor)
if [ $OPTION = "--help" ] if [ ! -z $AVAILABLE ]; then cat $FLROOT/cpu0/cpufreq/scaling_available_governors
then elif [ -z $VALUE ]; then
help
exit
fi
if [ $OPTION = "--version" ]
then
echo $VERSION
exit
fi
if [ $OPTION = "--driver" ]
then
driver
exit
fi
if [ $OPTION = "--governor" ]
then
if [ ! -z $AVAILABLE ]
then
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors
exit
fi
if [ -z $VALUE ]
then
verbose "Getting CPU"$CORE" governors" verbose "Getting CPU"$CORE" governors"
get_governor get_governor
else else
verbose "Setting CPU"$CORE" governors to "$VALUE verbose "Setting CPU"$CORE" governors to "$VALUE
set_governor set_governor
fi fi
exit ;;
fi -e|--epp)
if [ $OPTION = "--epp" ] if [ ! -z $AVAILABLE ]; then cat $FLROOT/cpu0/cpufreq/energy_performance_available_preferences
then elif [ -z $VALUE ]; then
if [ ! -z $AVAILABLE ]
then
cat /sys/devices/system/cpu/cpu0/cpufreq/energy_performance_available_preferences
exit
fi
if [ -z $VALUE ]
then
verbose "Getting CPU"$CORE" EPPs" verbose "Getting CPU"$CORE" EPPs"
get_energy_performance_preference get_energy_performance_preference
else else
verbose "Setting CPU"$CORE" EPPs to "$VALUE verbose "Setting CPU"$CORE" EPPs to "$VALUE
set_energy_performance_preference set_energy_performance_preference
fi fi
exit ;;
fi -f|--frequency)
if [ $OPTION = "--frequency" ] if [ ! -z $AVAILABLE ]; then cat $FLROOT/cpu0/cpufreq/scaling_available_frequencies
then elif [ -z $VALUE ]; then
if [ ! -z $AVAILABLE ]
then
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies
exit
fi
if [ -z $VALUE ]
then
verbose "Getting CPU"$CORE" frequency" verbose "Getting CPU"$CORE" frequency"
get_frequency get_frequency
else else
verbose "Setting CPU"$CORE" frequency to "$VALUE verbose "Setting CPU"$CORE" frequency to "$VALUE
set_frequency set_frequency
fi fi
exit ;;
fi --no-turbo)
if [ $OPTION = "--no-turbo" ] if [ -z $VALUE ]; then
then
if [ -z $VALUE ]
then
verbose "Getting no_turbo value" verbose "Getting no_turbo value"
cat /sys/devices/system/cpu/intel_pstate/no_turbo cat $FLROOT/intel_pstate/no_turbo
else else
verbose "Setting no_turbo value "$VALUE verbose "Setting no_turbo value "$VALUE
echo $VALUE > /sys/devices/system/cpu/intel_pstate/no_turbo echo $VALUE > $FLROOT/intel_pstate/no_turbo
fi fi
exit ;;
fi -b|--boost)
if [ $OPTION = "--boost" ] if [ -z $VALUE ]; then
then
if [ -z $VALUE ]
then
verbose "Getting boost value" verbose "Getting boost value"
cat /sys/devices/system/cpu/cpufreq/boost cat $FLROOT/cpufreq/boost
else else
verbose "Setting boost value "$VALUE verbose "Setting boost value "$VALUE
echo $VALUE > /sys/devices/system/cpu/cpufreq/boost echo $VALUE > $FLROOT/cpufreq/boost
fi fi
exit ;;
fi --frequency-min)
if [ $OPTION = "--frequency-min" ] if [ -z $VALUE ]; then
then
if [ -z $VALUE ]
then
verbose "Getting CPU"$CORE" minimal frequency" verbose "Getting CPU"$CORE" minimal frequency"
get_frequency_min get_frequency_min
else else
verbose "Setting CPU"$CORE" minimal frequency to "$VALUE verbose "Setting CPU"$CORE" minimal frequency to "$VALUE
set_frequency_min set_frequency_min
fi fi
exit ;;
fi --frequency-max)
if [ $OPTION = "--frequency-max" ] if [ -z $VALUE ]; then
then
if [ -z $VALUE ]
then
verbose "Getting CPU"$CORE" maximal frequency" verbose "Getting CPU"$CORE" maximal frequency"
get_frequency_max get_frequency_max
else else
verbose "Setting CPU"$CORE" maximal frequency to "$VALUE verbose "Setting CPU"$CORE" maximal frequency to "$VALUE
set_frequency_max set_frequency_max
fi fi
exit ;;
fi --frequency-min-limit)
if [ $OPTION = "--frequency-min-limit" ]
then
verbose "Getting CPU"$CORE" minimal frequency limit" verbose "Getting CPU"$CORE" minimal frequency limit"
get_frequency_min_limit get_frequency_min_limit
fi ;;
if [ $OPTION = "--frequency-max-limit" ] --frequency-max-limit)
then
verbose "Getting CPU"$CORE" maximum frequency limit" verbose "Getting CPU"$CORE" maximum frequency limit"
get_frequency_max_limit get_frequency_max_limit
fi ;;
if [ $OPTION = "--min-perf" ] --min-perf)
then if [ -z $VALUE ]; then
if [ -z $VALUE ]
then
verbose "Getting min_perf_pct value" verbose "Getting min_perf_pct value"
cat /sys/devices/system/cpu/intel_pstate/min_perf_pct cat $FLROOT/intel_pstate/min_perf_pct
else else
verbose "Setting min_perf_pct value "$VALUE verbose "Setting min_perf_pct value "$VALUE
echo $VALUE > /sys/devices/system/cpu/intel_pstate/min_perf_pct echo $VALUE > $FLROOT/intel_pstate/min_perf_pct
fi fi
exit ;;
fi --max-perf)
if [ $OPTION = "--max-perf" ] if [ -z $VALUE ]; then
then
if [ -z $VALUE ]
then
verbose "Getting max_perf_pct value" verbose "Getting max_perf_pct value"
cat /sys/devices/system/cpu/intel_pstate/max_perf_pct cat $FLROOT/intel_pstate/max_perf_pct
else else
verbose "Setting max_perf_pct value "$VALUE verbose "Setting max_perf_pct value "$VALUE
echo $VALUE > /sys/devices/system/cpu/intel_pstate/max_perf_pct echo $VALUE > $FLROOT/intel_pstate/max_perf_pct
fi fi
exit ;;
fi --on)
if [ $OPTION = "--on" ] if [ -z $CORE ]; then verbose "Should be specify --core=NUMBER"
then
if [ -z $CORE ]
then
verbose "Should be specify --core=NUMBER"
else else
verbose "Power on CPU Core"$CORE verbose "Power on CPU Core"$CORE
echo "1" > $FLROOT/cpu"$CORE"/online echo "1" > $FLROOT/cpu"$CORE"/online
fi fi
exit ;;
fi --off)
if [ $OPTION = "--off" ] if [ -z $CORE ]; then verbose "Should be specify --core=NUMBER"
then
if [ -z $CORE ]
then
verbose "Should be specify --core=NUMBER"
else else
verbose "Power off CPU Core"$CORE verbose "Power off CPU Core$CORE"
echo "0" > $FLROOT/cpu"$CORE"/online echo "0" > $FLROOT/cpu"$CORE"/online
fi fi
exit ;;
fi --throttle)
if [ $OPTION = "--throttle" ]
then
i=1 i=1
V=0 V=0
M=$(cat "/sys/devices/system/cpu/cpu0/thermal_throttle/core_throttle_count") M=$(cat "$FLROOT/cpu0/thermal_throttle/core_throttle_count")
while [ $i -ne $cpucount ] while [ $i -ne $cpucount ]; do
do V=$(cat "$FLROOT/cpu$i/thermal_throttle/core_throttle_count")
V=$(cat "/sys/devices/system/cpu/cpu"$i"/thermal_throttle/core_throttle_count")
M=`expr $M + $V` M=`expr $M + $V`
i=`expr $i + 1` i=`expr $i + 1`
done done
echo "$M" echo "$M"
exit ;;
fi --throttle-events)
if [ $OPTION = "--throttle-events" ]
then
M=$(journalctl --dmesg --boot --since=yesterday | grep "cpu clock throttled" | wc -l) M=$(journalctl --dmesg --boot --since=yesterday | grep "cpu clock throttled" | wc -l)
echo "$M" echo "$M"
exit ;;
fi --irqbalance)
if [ $OPTION = "--irqbalance" ] M=$(ps -A | grep irqbalance)
then
M=$(ps -A |grep irqbalance)
echo "$M" echo "$M"
exit ;;
fi *)
info
exit 1
;;
esac
exit 0

View File

@ -2,17 +2,17 @@
# load python virtual environment # load python virtual environment
venv_dir=/opt/auto-cpufreq/venv venv_dir=/opt/auto-cpufreq/venv
. "${venv_dir}/bin/activate" . "$venv_dir/bin/activate"
python_command="${venv_dir}/bin/auto-cpufreq-gtk" python_command="$venv_dir/bin/auto-cpufreq-gtk"
# if [ "$XDG_SESSION_TYPE" = "wayland" ] ; then # if [ "$XDG_SESSION_TYPE" = "wayland" ] ; then
# # necessary for running on wayland # # necessary for running on wayland
# xhost +SI:localuser:root # xhost +SI:localuser:root
# pkexec ${python_command} # pkexec $python_command
# xhost -SI:localuser:root # xhost -SI:localuser:root
# xhost # xhost
# else # else
# pkexec ${python_command} # pkexec $python_command
# fi # fi
${python_command} $python_command

View File

@ -1,12 +1,8 @@
label{ label {
/*font-family: Noto Sans;*/ /*font-family: Noto Sans;*/
font-size: 15px; font-size: 15px;
} }
#bold{ #bold { font-weight: bold; }
font-weight: bold;
}
#small{ #small { font-size: 12px; }
font-size: 12px;
}