From 2327adbfc37959250f4e2b6cf13647ef079ec85d Mon Sep 17 00:00:00 2001 From: Angel-Karasu Date: Fri, 10 May 2024 13:23:45 +0200 Subject: [PATCH] Clean code --- auto-cpufreq-installer | 312 +++----- auto_cpufreq/battery_scripts/battery.py | 43 +- auto_cpufreq/battery_scripts/ideapad_acpi.py | 48 +- .../battery_scripts/ideapad_laptop.py | 71 +- auto_cpufreq/battery_scripts/thinkpad.py | 47 +- auto_cpufreq/bin/auto_cpufreq.py | 71 +- auto_cpufreq/bin/auto_cpufreq_gtk.py | 3 +- auto_cpufreq/core.py | 701 ++++-------------- auto_cpufreq/gui/app.py | 19 +- auto_cpufreq/gui/objects.py | 59 +- auto_cpufreq/gui/tray.py | 6 +- auto_cpufreq/power_helper.py | 213 ++---- auto_cpufreq/tlp_stat_parser.py | 12 +- auto_cpufreq/utils/config.py | 37 +- scripts/auto-cpufreq-install.sh | 157 ++-- scripts/auto-cpufreq-remove.sh | 121 ++- scripts/auto-cpufreq-venv-wrapper | 7 +- scripts/cpufreqctl.sh | 583 ++++++--------- scripts/start_app | 10 +- scripts/style.css | 10 +- 20 files changed, 831 insertions(+), 1699 deletions(-) diff --git a/auto-cpufreq-installer b/auto-cpufreq-installer index c3fe32ff..75cca4e3 100755 --- a/auto-cpufreq-installer +++ b/auto-cpufreq-installer @@ -5,110 +5,76 @@ cd "$(dirname "$(readlink -f "$0")")" || exit 1 -# check if lsb_release exists on the system before using it -if command -v lsb_release > /dev/null -then - distro="$(lsb_release -is)" - release="$(lsb_release -rs)" - codename="$(lsb_release -cs)" -fi +COLOUMNS="`tput cols`" +MID="$((COLOUMNS / 2))" +APPLICATIONS_PATH="/usr/share/applications" +VENV_PATH="/opt/auto-cpufreq" -# functions +SHARE_DIR="/usr/local/share/auto-cpufreq/" -#separator -function separator { - local COLOUMNS="`tput cols`" - echo -e "\n" - printf "%0.s─" $(seq $COLOUMNS) - echo -e "\n" -} +AUTO_CPUFREQ_FILE="/usr/local/bin/auto-cpufreq" +AUTO_CPUFREQ_GTK_FILE=$AUTO_CPUFREQ_FILE-gtk +AUTO_CPUFREQ_GTK_DESKTOP_FILE="$(basename $AUTO_CPUFREQ_GTK_FILE).desktop" -# root check -function root_check { - if ((EUID != 0)); then - separator - echo -e "\nMust be run as root (i.e: 'sudo $0')." - separator - exit 1 - fi -} +IMG_FILE="/usr/share/pixmaps/auto-cpufreq.png" +ORG_FILE="/usr/share/polkit-1/actions/org.auto-cpufreq.pkexec.policy" function header { - local COLOUMNS="`tput cols`" - MID="$((COLOUMNS / 2))" - HEADER="$1" - printf "%0.s─" $(seq $((MID-(${#HEADER}/2)- 1))) - echo -n " $HEADER " - printf "%0.s─" $(seq $((MID-(${#HEADER}/2)- 1))) - echo -e "\n" - return -} - -# tool install -function install { - git config --global --add safe.directory $(pwd) - python -m pip install . - 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 + echo + printf "%0.s─" $(seq $((MID-(${#1}/2)-2))) + printf " $1 " + printf "%0.s─" $(seq $((MID-(${#1}/2)-2))) + echo; echo } -# First argument is the distro -function detected_distro { - echo -e "\nDetected $1 distribution" - separator - echo -e "\nSetting up Python environment\n" +function ask_operation { + header "auto-cpufreq installer" + echo "Welcome to auto-cpufreq tool installer."; echo + read -p "Select a key [I]nstall/[R]emove or press ctrl+c to quit: " answer } function manual_install { - echo -e " - Didn't detect Debian or RedHat or Arch based distro. - - To complete installation, you need to: - Install: python3, pip3, python3-setuptools, gobject-introspection, cairo (or cairo-devel), gcc, and gtk3 - - Install necessary Python packages: - pip3 install psutil click distro power requests PyGObject - Run following sequence of lines: - - ----- - - pip3 install . - 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: + if command -v lsb_release > /dev/null; then + distro="$(lsb_release -is)" + release="$(lsb_release -rs)" + codename="$(lsb_release -cs)" + fi - Distribution: $distro - Release: $release - Codename: $codename" - separator + echo "Didn't detect Debian or RedHat or Arch based distro."; echo + 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" + + echo; printf "%0.s─" $(seq $COLOUMNS); echo + + 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 + + exit 1 } 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 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 elif [ -f /etc/os-release ];then - eval "$(cat /etc/os-release)" - separator + . /etc/os-release case $ID in opensuse-leap) 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 ;; nixos) - echo -e "NixOS detected\n" - 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 "NixOS detected" + 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 ;; *) manual_install;; esac else # In case /etc/os-release doesn't exist manual_install - exit 1 fi - echo -e "\nInstalling necessary Python packages\n" + header "Installing necessary Python packages" - venv_dir=/opt/auto-cpufreq/venv - mkdir -p "${venv_dir}" - python3 -m venv "${venv_dir}" + venv_dir=$VENV_PATH/venv + mkdir -p "$venv_dir" + python3 -m venv "$venv_dir" - source "${venv_dir}/bin/activate" + source "$venv_dir/bin/activate" python3 -m pip install --upgrade pip wheel - separator - echo -e "\ninstalling auto-cpufreq tool\n" - install + header "Installing auto-cpufreq tool" + + git config --global --add safe.directory $(pwd) + python -m pip install . - separator - echo -e " - auto-cpufreq tool successfully installed. + 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) - For list of options, run: - - auto-cpufreq --help" - separator + # this is necessary since we need this script before we can run auto-cpufreq itself + 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 { - # 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) tool_arg_pids=($(pgrep -f "auto-cpufreq --")) - for pid in "${tool_arg_pids[@]}"; do - if [[ $tool_arg_pids != $$ ]]; then - kill "$tool_arg_pids" - fi - done + for pid in "${tool_arg_pids[@]}"; do [ $pid != $$ ] && kill "$pid"; done + + function remove_directory { + [ -d $1 ] && rm -rf $1 + } + function remove_file { + [ -f $1 ] && rm $1 + } + + srv_remove="$AUTO_CPUFREQ_FILE-remove" # run uninstall in case of installed daemon - if [ -f $srv_remove -o -f $srv_remove_old -o $wrapper_script ]; then - eval $tool_proc_rm + if [ -f $srv_remove -o -f $AUTO_CPUFREQ_FILE ]; then + eval "$AUTO_CPUFREQ_FILE --remove" else - separator - printf "Couldn't remove the auto-cpufreq daemon\n$srv_remove or $srv_remove_old do not exist.\n" - exit 1; - separator + echo; echo "Couldn't remove the auto-cpufreq daemon, $srv_remove do not exist." fi # remove auto-cpufreq and all its supporting files - # [ -f $files ] && cat $files | xargs sudo rm -rf && rm -f $files - [ -d $share_dir ] && rm -rf $share_dir + remove_directory $SHARE_DIR - # files cleanup - [ -f $srv_install ] && rm $srv_install - [ -f $srv_install_old ] && rm $srv_install_old - - [ -f $srv_remove ] && rm $srv_remove - [ -f $srv_remove_old ] && rm $srv_remove_old - - [ -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 + remove_file "$AUTO_CPUFREQ_FILE-install" + remove_file $srv_remove + 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 $desktop_file ] && rm $desktop_file - update-desktop-database /usr/share/applications + remove_file "$APPLICATIONS_PATH/$AUTO_CPUFREQ_GTK_DESKTOP_FILE" + update-desktop-database $APPLICATIONS_PATH # remove python virtual environment - rm -rf "${venv_path}" + remove_directory $venv_path - separator - echo -e "\nauto-cpufreq tool and all its supporting files successfully removed." - separator + echo; echo "auto-cpufreq tool and all its supporting files successfully removed"; echo } -function ask_operation { - header "auto-cpufreq installer" - echo -e "Welcome to auto-cpufreq tool installer. - \nOptions:\n" - read -p \ -"[I]nstall -[R]emove -[Q]uit - -Select a key: [i/r/q]: " answer -} -# End of functions - -root_check +# root check +if ((EUID != 0)); then + echo; echo "Must be run as root (i.e: 'sudo $0')."; echo + exit 1 +fi -if [[ -z "${1}" ]]; then ask_operation +if [[ -z "$1" ]]; then ask_operation else - case "${1}" in - "--install") answer="i";; - "--remove") answer="r";; - *) answer="n";; + case "$1" in + --install) answer="i";; + --remove) answer="r";; + *) ask_operation;; esac fi case $answer in I|i) tool_install;; R|r) tool_remove;; - Q|q) - separator - echo "" - exit 0 - ;; *) - separator - echo -e "\nUnknown key, aborting ...\n" + echo "Unknown key, aborting ..."; echo exit 1 ;; esac diff --git a/auto_cpufreq/battery_scripts/battery.py b/auto_cpufreq/battery_scripts/battery.py index 6f7294b6..14c02970 100644 --- a/auto_cpufreq/battery_scripts/battery.py +++ b/auto_cpufreq/battery_scripts/battery.py @@ -5,41 +5,16 @@ 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 - -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 lsmod(module): return module in subprocess.run(['lsmod'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True).stdout def battery_setup(): - - if lsmod("thinkpad_acpi"): - thinkpad_setup() - - elif lsmod("ideapad_acpi"): - ideapad_acpi_setup() - - elif lsmod("ideapad_laptop"): - ideapad_laptop_setup() - - else: - return - + if lsmod("thinkpad_acpi"): thinkpad_setup() + elif lsmod("ideapad_acpi"): ideapad_acpi_setup() + elif lsmod("ideapad_laptop"): ideapad_laptop_setup() + else: return def battery_get_thresholds(): - - if lsmod("thinkpad_acpi"): - thinkpad_print_thresholds() - - elif lsmod("ideapad_acpi"): - ideapad_acpi_print_thresholds() - - elif lsmod("ideapad_laptop"): - ideapad_laptop_print_thresholds() - - else: - return + if lsmod("thinkpad_acpi"): thinkpad_print_thresholds() + elif lsmod("ideapad_acpi"): ideapad_acpi_print_thresholds() + elif lsmod("ideapad_laptop"): ideapad_laptop_print_thresholds() + else: return diff --git a/auto_cpufreq/battery_scripts/ideapad_acpi.py b/auto_cpufreq/battery_scripts/ideapad_acpi.py index 3c114ef5..0e3f91d8 100644 --- a/auto_cpufreq/battery_scripts/ideapad_acpi.py +++ b/auto_cpufreq/battery_scripts/ideapad_acpi.py @@ -3,62 +3,40 @@ import subprocess from auto_cpufreq.utils.config import config +POWER_SUPPLY_DIR = "/sys/class/power_supply/" def set_battery(value, mode, bat): - path = f"/sys/class/power_supply/BAT{bat}/charge_{mode}_threshold" - if os.path.isfile(path): - subprocess.check_output( - f"echo {value} | tee {path}", shell=True, text=True) - else: - print(f"WARNING: {path} does NOT exist") - + path = f"{POWER_SUPPLY_DIR}BAT{bat}/charge_{mode}_threshold" + if os.path.isfile(path): subprocess.check_output(f"echo {value} | tee {path}", shell=True, text=True) + else: print(f"WARNING: {path} does NOT exist") def get_threshold_value(mode): - conf = config.get_config() - if conf.has_option("battery", f"{mode}_threshold"): - return conf["battery"][f"{mode}_threshold"] - else: - if mode == "start": - - return 0 - else: - return 100 - + return conf["battery"][f"{mode}_threshold"] if conf.has_option("battery", f"{mode}_threshold") else (0 if mode == "start" else 100) def ideapad_acpi_setup(): conf = config.get_config() - if not conf.has_option("battery", "enable_thresholds"): - return - if not conf["battery"]["enable_thresholds"] == "true": - return + if not (conf.has_option("battery", "enable_thresholds") and conf["battery"]["enable_thresholds"] == "true"): return - if os.path.exists("/sys/class/power_supply/"): - battery_count = len([name for name in os.listdir( - "/sys/class/power_supply/") if name.startswith('BAT')]) + if os.path.exists(POWER_SUPPLY_DIR): + battery_count = len([name for name in os.listdir(POWER_SUPPLY_DIR) if name.startswith('BAT')]) for bat in range(battery_count): set_battery(get_threshold_value("start"), "start", bat) set_battery(get_threshold_value("stop"), "stop", bat) - else: - print("WARNING: could NOT access /sys/class/power_supply") - + else: print(f"WARNING: could NOT access {POWER_SUPPLY_DIR}") def ideapad_acpi_print_thresholds(): - battery_count = len([name for name in os.listdir( - "/sys/class/power_supply/") if name.startswith('BAT')]) + battery_count = len([name for name in os.listdir(POWER_SUPPLY_DIR) if name.startswith('BAT')]) print("\n-------------------------------- Battery Info ---------------------------------\n") print(f"battery count = {battery_count}") for b in range(battery_count): 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="") - 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="") - f.close() - except Exception: - print(f"ERROR: failed to read battery {b} thresholds") + except Exception: print(f"ERROR: failed to read battery {b} thresholds") diff --git a/auto_cpufreq/battery_scripts/ideapad_laptop.py b/auto_cpufreq/battery_scripts/ideapad_laptop.py index 7d3cce9f..025153e6 100644 --- a/auto_cpufreq/battery_scripts/ideapad_laptop.py +++ b/auto_cpufreq/battery_scripts/ideapad_laptop.py @@ -3,47 +3,30 @@ import subprocess from auto_cpufreq.utils.config import config +POWER_SUPPLY_DIR = "/sys/class/power_supply/" 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): - subprocess.check_output( - 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") - + subprocess.check_output(f"echo {value} | tee {POWER_SUPPLY_DIR}BAT{bat}/charge_{mode}_threshold", shell=True, text=True) + else: print(f"WARNING: {path} does NOT exist") def get_threshold_value(mode): - conf = config.get_config() - if conf.has_option("battery", f"{mode}_threshold"): - return conf["battery"][f"{mode}_threshold"] - else: - if mode == "start": - return 0 - else: - return 100 - + return conf["battery"][f"{mode}_threshold"] if conf.has_option("battery", f"{mode}_threshold") else (0 if mode == "start" else 100) def conservation_mode(value): try: - subprocess.check_output( - f"echo {value} | tee /sys/bus/platform/drivers/ideapad_acpi/VPC2004:00/conservation_mode", shell=True, text=True) + subprocess.check_output(f"echo {value} | tee /sys/bus/platform/drivers/ideapad_acpi/VPC2004:00/conservation_mode", shell=True, text=True) print(f"conservation_mode is {value}") - return - except: - print("unable to set conservation mode") - return - + except: print("unable to set conservation mode") + return def check_conservation_mode(): try: - value = subprocess.check_output( - "cat /sys/bus/platform/drivers/ideapad_acpi/VPC2004:00/conservation_mode", shell=True, text=True) - if value == "1": - return True - elif value == "0": - return False + value = subprocess.check_output("cat /sys/bus/platform/drivers/ideapad_acpi/VPC2004:00/conservation_mode", shell=True, text=True) + if value == "1": return True + elif value == "0": return False else: print("could not get value from conservation mode") return None @@ -51,51 +34,39 @@ def check_conservation_mode(): print("could not get the value from conservation mode") return False - def ideapad_laptop_setup(): conf = config.get_config() - if not conf.has_option("battery", "enable_thresholds"): - return - if not conf["battery"]["enable_thresholds"] == "true": - return + if not (conf.has_option("battery", "enable_thresholds") and conf["battery"]["enable_thresholds"] == "true"): return - battery_count = len([name for name in os.listdir( - "/sys/class/power_supply/") if name.startswith('BAT')]) + battery_count = len([name for name in os.listdir(POWER_SUPPLY_DIR) if name.startswith('BAT')]) if conf.has_option("battery", "ideapad_laptop_conservation_mode"): if conf["battery"]["ideapad_laptop_conservation_mode"] == "true": conservation_mode(1) return - if conf["battery"]["ideapad_laptop_conservation_mode"] == "false": - conservation_mode(0) + if conf["battery"]["ideapad_laptop_conservation_mode"] == "false": conservation_mode(0) - if check_conservation_mode() is False: + if not check_conservation_mode(): for bat in range(battery_count): set_battery(get_threshold_value("start"), "start", bat) set_battery(get_threshold_value("stop"), "stop", bat) - else: - print("conservation mode is enabled unable to set thresholds") - + else: print("conservation mode is enabled unable to set thresholds") def ideapad_laptop_print_thresholds(): - if check_conservation_mode() is True: + if check_conservation_mode(): print("conservation mode is on") return - battery_count = len([name for name in os.listdir( - "/sys/class/power_supply/") if name.startswith('BAT')]) + battery_count = len([name for name in os.listdir(POWER_SUPPLY_DIR) if name.startswith('BAT')]) print("\n-------------------------------- Battery Info ---------------------------------\n") print(f"battery count = {battery_count}") for b in range(battery_count): 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="") - 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="") - f.close() - except Exception: - print(f"ERROR: failed to read battery thresholds: {e}") + except Exception: print(f"ERROR: failed to read battery {b} thresholds") diff --git a/auto_cpufreq/battery_scripts/thinkpad.py b/auto_cpufreq/battery_scripts/thinkpad.py index 575e6121..2ee2c6d8 100644 --- a/auto_cpufreq/battery_scripts/thinkpad.py +++ b/auto_cpufreq/battery_scripts/thinkpad.py @@ -3,62 +3,41 @@ import subprocess from auto_cpufreq.utils.config import config +POWER_SUPPLY_DIR = "/sys/class/power_supply/" def set_battery(value, mode, bat): - path = f"/sys/class/power_supply/BAT{bat}/charge_{mode}_threshold" - if os.path.isfile(path): - subprocess.check_output( - f"echo {value} | tee {path}", shell=True, text=True) - else: - print(f"WARNING: {path} does NOT exist") - + path = f"{POWER_SUPPLY_DIR}BAT{bat}/charge_{mode}_threshold" + if os.path.isfile(path): subprocess.check_output(f"echo {value} | tee {path}", shell=True, text=True) + else: print(f"WARNING: {path} does NOT exist") def get_threshold_value(mode): - conf = config.get_config() - if conf.has_option("battery", f"{mode}_threshold"): - return conf["battery"][f"{mode}_threshold"] - else: - if mode == "start": - - return 0 - else: - return 100 - + return conf["battery"][f"{mode}_threshold"] if conf.has_option("battery", f"{mode}_threshold") else (0 if mode == "start" else 100) def thinkpad_setup(): conf = config.get_config() - if not conf.has_option("battery", "enable_thresholds"): - return - if not conf["battery"]["enable_thresholds"] == "true": - return + if not (conf.has_option("battery", "enable_thresholds") and conf["battery"]["enable_thresholds"] == "true"): return - if os.path.exists("/sys/class/power_supply/"): - battery_count = len([name for name in os.listdir( - "/sys/class/power_supply/") if name.startswith('BAT')]) + if os.path.exists(POWER_SUPPLY_DIR): + battery_count = len([name for name in os.listdir(POWER_SUPPLY_DIR) if name.startswith('BAT')]) for bat in range(battery_count): set_battery(get_threshold_value("start"), "start", bat) set_battery(get_threshold_value("stop"), "stop", bat) - else: - print("WARNING /sys/class/power_supply/ does NOT esixt") + else: print(f"WARNING {POWER_SUPPLY_DIR} does NOT esixt") def thinkpad_print_thresholds(): - battery_count = len([name for name in os.listdir( - "/sys/class/power_supply/") if name.startswith('BAT')]) + battery_count = len([name for name in os.listdir(POWER_SUPPLY_DIR) if name.startswith('BAT')]) print("\n-------------------------------- Battery Info ---------------------------------\n") print(f"battery count = {battery_count}") for b in range(battery_count): 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="") - 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="") - f.close() - except Exception: - print(f"ERROR: failed to read battery {b} thresholds") + except Exception: print(f"ERROR: failed to read battery {b} thresholds") diff --git a/auto_cpufreq/bin/auto_cpufreq.py b/auto_cpufreq/bin/auto_cpufreq.py index 4343b8d0..62a3b2a6 100755 --- a/auto_cpufreq/bin/auto_cpufreq.py +++ b/auto_cpufreq/bin/auto_cpufreq.py @@ -9,6 +9,7 @@ import time from click import UsageError from subprocess import call, run +from shutil import rmtree # sys.path.append("../") from auto_cpufreq.core import * @@ -26,12 +27,7 @@ @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("--get-state", is_flag=True, hidden=True) -@click.option( - "--config", - is_flag=False, - required=False, - help="Use config file at defined path", -) +@click.option("--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("--version", is_flag=True, help="Show currently installed version") @click.option("--donate", is_flag=True, help="Support the project") @@ -84,8 +80,7 @@ def config_info_dialog(): sysinfo() set_autofreq() countdown(2) - except KeyboardInterrupt: - break; + except KeyboardInterrupt: break conf.notifier.stop() elif monitor: config_info_dialog() @@ -111,8 +106,7 @@ def config_info_dialog(): sysinfo() mon_autofreq() countdown(2) - except KeyboardInterrupt: - break + except KeyboardInterrupt: break conf.notifier.stop() elif live: root_check() @@ -141,7 +135,7 @@ def config_info_dialog(): countdown(2) except KeyboardInterrupt: gnome_power_start_live() - print("") + print() break conf.notifier.stop() elif stats: @@ -156,8 +150,7 @@ def config_info_dialog(): tlp_service_detect() battery_get_thresholds() read_stats() - elif log: - deprecated_log_msg() + elif log: deprecated_log_msg() elif get_state: not_running_daemon_check() override = get_override() @@ -171,17 +164,14 @@ def config_info_dialog(): footer() distro_info() sysinfo() - print("") + print() app_version() - print("") + print() python_info() - print("") + print() device_info() - if charging(): - print("Battery is: charging") - else: - print("Battery is: discharging") - print("") + print(f"Battery is: {'' if charging() else 'dis'}charging") + print() app_res_use() display_load() get_current_gov() @@ -199,8 +189,8 @@ def config_info_dialog(): print("https://github.com/AdnanHodzic/auto-cpufreq/#donate") footer() elif install: + root_check() if os.getenv("PKG_MARKER") == "SNAP": - root_check() running_daemon_check() gnome_power_detect_snap() tlp_service_detect_snap() @@ -208,16 +198,14 @@ def config_info_dialog(): gov_check() run("snapctl set daemon=enabled", shell=True) run("snapctl start --enable auto-cpufreq", shell=True) - deploy_complete_msg() else: - root_check() running_daemon_check() gov_check() deploy_daemon() - deploy_complete_msg() + deploy_complete_msg() elif remove: + root_check() if os.getenv("PKG_MARKER") == "SNAP": - root_check() run("snapctl set daemon=disabled", shell=True) run("snapctl stop --disable auto-cpufreq", shell=True) if auto_cpufreq_stats_path.exists(): @@ -229,11 +217,8 @@ def config_info_dialog(): # {the following snippet also used in --update, update it there too(if required)} # * undo bluetooth boot disable gnome_power_rm_reminder_snap() - remove_complete_msg() - else: - root_check() - remove_daemon() - remove_complete_msg() + else: remove_daemon() + remove_complete_msg() elif update: root_check() custom_dir = "/opt/auto-cpufreq/source" @@ -245,8 +230,7 @@ def config_info_dialog(): if "--update" in sys.argv: update = True sys.argv.remove("--update") - if len(sys.argv) == 2: - custom_dir = sys.argv[1] + if len(sys.argv) == 2: custom_dir = sys.argv[1] if os.getenv("PKG_MARKER") == "SNAP": print("Detected auto-cpufreq was installed using snap") @@ -259,13 +243,10 @@ def config_info_dialog(): print("Arch-based distribution with AUR support detected. Please refresh auto-cpufreq using your AUR helper.") else: is_new_update = check_for_update() - if not is_new_update: - return + if not is_new_update: return ans = input("Do you want to update auto-cpufreq to the latest release? [Y/n]: ").strip().lower() - if not os.path.exists(custom_dir): - os.makedirs(custom_dir) - if os.path.exists(os.path.join(custom_dir, "auto-cpufreq")): - shutil.rmtree(os.path.join(custom_dir, "auto-cpufreq")) + if not os.path.exists(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 ans in ['', 'y', 'yes']: remove_daemon() remove_complete_msg() @@ -274,9 +255,7 @@ def config_info_dialog(): run(["auto-cpufreq", "--install"]) print("auto-cpufreq is installed with the latest version") run(["auto-cpufreq", "--version"]) - else: - print("Aborted") - + else: print("Aborted") elif completions: if completions == "bash": print("Run the below command in your current shell!\n") @@ -289,10 +268,6 @@ def config_info_dialog(): elif completions == "fish": 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") - else: - print("Invalid Option, try bash|zsh|fish as argument to --completions") + else: print("Invalid Option, try bash|zsh|fish as argument to --completions") - - -if __name__ == "__main__": - main() +if __name__ == "__main__": main() diff --git a/auto_cpufreq/bin/auto_cpufreq_gtk.py b/auto_cpufreq/bin/auto_cpufreq_gtk.py index 8db1dd3b..7c63663c 100644 --- a/auto_cpufreq/bin/auto_cpufreq_gtk.py +++ b/auto_cpufreq/bin/auto_cpufreq_gtk.py @@ -18,5 +18,4 @@ def main(): win.handle_update() Gtk.main() -if __name__ == "__main__": - main() \ No newline at end of file +if __name__ == "__main__": main() \ No newline at end of file diff --git a/auto_cpufreq/core.py b/auto_cpufreq/core.py index 58cedb7f..bda532f9 100755 --- a/auto_cpufreq/core.py +++ b/auto_cpufreq/core.py @@ -4,7 +4,6 @@ import os import platform as pl -import shutil import sys import psutil import distro @@ -16,7 +15,7 @@ import importlib.metadata from math import isclose from pathlib import Path -from shutil import which +from shutil import copy from subprocess import getoutput, call, run, check_output, DEVNULL import requests import re @@ -67,12 +66,9 @@ # track governor override if os.getenv("PKG_MARKER") == "SNAP": governor_override_state = Path("/var/snap/auto-cpufreq/current/override.pickle") -else: - governor_override_state = Path("/opt/auto-cpufreq/override.pickle") - -if os.getenv("PKG_MARKER") == "SNAP": auto_cpufreq_stats_path = Path("/var/snap/auto-cpufreq/current/auto-cpufreq.stats") else: + governor_override_state = Path("/opt/auto-cpufreq/override.pickle") auto_cpufreq_stats_path = Path("/var/run/auto-cpufreq.stats") # daemon check @@ -89,8 +85,7 @@ def get_override(): if os.path.isfile(governor_override_state): with open(governor_override_state, "rb") as store: return pickle.load(store) - else: - return "default" + else: return "default" def set_override(override): if override in ["powersave", "performance"]: @@ -107,52 +102,41 @@ def set_override(override): # get distro name -try: - dist_name = distro.id() +try: dist_name = distro.id() except PermissionError: # Current work-around for Pop!_OS where symlink causes permission issues print("[!] Warning: Cannot get distro name") if os.path.exists("/etc/pop-os/os-release"): # Check if using a Snap if os.getenv("PKG_MARKER") == "SNAP": - print("[!] Snap install on PopOS detected, you must manually run the following" - " commands in another terminal:\n") + print("[!] Snap install on PopOS detected, you must manually run the following commands in another terminal:\n") print("[!] Backup the /etc/os-release file:") print("sudo mv /etc/os-release /etc/os-release-backup\n") print("[!] Create hardlink to /etc/os-release:") print("sudo ln /etc/pop-os/os-release /etc/os-release\n") print("[!] Aborting. Restart auto-cpufreq when you created the hardlink") - sys.exit(1) else: # This should not be the case. But better be sure. print("[!] Check /etc/os-release permissions and make sure it is not a symbolic link") print("[!] Aborting...") - sys.exit(1) - else: print("[!] Check /etc/os-release permissions and make sure it is not a symbolic link") print("[!] Aborting...") - sys.exit(1) + sys.exit(1) # display running version of auto-cpufreq def app_version(): - print("auto-cpufreq version: ", end="") # snap package - if os.getenv("PKG_MARKER") == "SNAP": - print(getoutput(r"echo \(Snap\) $SNAP_VERSION")) + if os.getenv("PKG_MARKER") == "SNAP": print(getoutput(r"echo \(Snap\) $SNAP_VERSION")) # aur package elif dist_name in ["arch", "manjaro", "garuda"]: - aur_pkg_check = call("pacman -Qs auto-cpufreq > /dev/null", shell=True) - if aur_pkg_check == 1: - print(get_formatted_version()) - else: - print(getoutput("pacman -Qi auto-cpufreq | grep Version")) + if call("pacman -Qs auto-cpufreq > /dev/null", shell=True) == 1: print(get_formatted_version()) + else: print(getoutput("pacman -Qi auto-cpufreq | grep Version")) else: # source code (auto-cpufreq-installer) - try: - print(get_formatted_version()) + try: print(get_formatted_version()) except Exception as e: print(repr(e)) pass @@ -163,21 +147,19 @@ def check_for_update(): # Specify the repository and package name # IT IS IMPORTANT TO THAT IF THE REPOSITORY STRUCTURE IS CHANGED, THE FOLLOWING FUNCTION NEEDS TO BE UPDATED ACCORDINGLY # Fetch the latest release information from GitHub API - latest_release_url = f"https://api.github.com/repos/AdnanHodzic/auto-cpufreq/releases/latest" + latest_release_url = "https://api.github.com/repos/AdnanHodzic/auto-cpufreq/releases/latest" try: response = requests.get(latest_release_url) - if response.status_code == 200: - latest_release = response.json() + if response.ok: latest_release = response.json() else: message = response.json().get("message") print("Error fetching recent release!") if message is not None and message.startswith("API rate limit exceeded"): print("GitHub Rate limit exceeded. Please try again later within 1 hour or use different network/VPN.") - else: - print("Unexpected status code:", response.status_code) + else: print("Unexpected status code:", response.status_code) return False except (requests.exceptions.ConnectionError, requests.exceptions.Timeout, - requests.exceptions.RequestException, requests.exceptions.HTTPError) as err: + requests.exceptions.RequestException, requests.exceptions.HTTPError): print("Error Connecting to server!") return False @@ -187,21 +169,18 @@ def check_for_update(): # Get the current version of auto-cpufreq # Extract version number from the output string output = check_output(['auto-cpufreq', '--version']).decode('utf-8') - try: - version_line = next((re.search(r'\d+\.\d+\.\d+', line).group() for line in output.split('\n') if line.startswith('auto-cpufreq version')), None) + try: version_line = next((re.search(r'\d+\.\d+\.\d+', line).group() for line in output.split('\n') if line.startswith('auto-cpufreq version')), None) except AttributeError: print("Error Retrieving Current Version!") exit(1) installed_version = "v" + version_line #Check whether the same is installed or not # Compare the latest version with the installed version and perform update if necessary - if latest_version == installed_version: - print("auto-cpufreq is up to date") - return False + if latest_version == installed_version: print("auto-cpufreq is up to date") else: print(f"Updates are available,\nCurrent version: {installed_version}\nLatest version: {latest_version}") print("Note that your previous custom settings might be erased with the following update") - return True + return True else: # Handle the case where "tag_name" key doesn't exist print("Malformed Released data!\nReinstall manually or Open an issue on GitHub for help!") @@ -221,26 +200,18 @@ def get_literal_version(package_name): package_metadata = importlib.metadata.metadata(package_name) package_name = package_metadata['Name'] - metadata_version = package_metadata['Version'] - - numbered_version, _, git_version = metadata_version.partition("+") + numbered_version, _, git_version = package_metadata['Version'].partition("+") # Construct the literal version string - literal_version = f"{numbered_version}+{git_version}" - - return literal_version + return f"{numbered_version}+{git_version}" - except importlib.metadata.PackageNotFoundError: - return f"Package '{package_name}' not found" + except importlib.metadata.PackageNotFoundError: return f"Package '{package_name}' not found" # return formatted version for a better readability def get_formatted_version(): literal_version = get_literal_version("auto-cpufreq") splitted_version = literal_version.split("+") - formatted_version = splitted_version[0] - - if len(splitted_version) > 1: - formatted_version += " (git: " + splitted_version[1] + ")" + formatted_version = splitted_version[0] + " (git: " + splitted_version[1] + ")" if len(splitted_version) > 1 else '' return formatted_version @@ -268,8 +239,7 @@ def turbo(value: bool = None): inverse = False elif amd_pstate.exists(): amd_value = amd_pstate.read_text().strip() - if amd_value == "active": - print("CPU turbo is controlled by amd-pstate-epp driver") + if amd_value == "active": print("CPU turbo is controlled by amd-pstate-epp driver") # Basically, no other value should exist. return False else: @@ -277,30 +247,24 @@ def turbo(value: bool = None): return False if value is not None: - if inverse: - value = not value + if inverse: value = not value - try: - f.write_text(str(int(value)) + "\n") + try: f.write_text(str(int(value)) + "\n") except PermissionError: print("Warning: Changing CPU turbo is not supported. Skipping.") return False value = bool(int(f.read_text().strip())) - if inverse: - value = not value + if inverse: value = not value return value - # display current state of turbo -def get_turbo(): - - if turbo(): - print("Currently turbo boost is: on") - else: - print("Currently turbo boost is: off") +def get_turbo(): print(f"Currently turbo boost is: {'on' if turbo() else 'off'}") +def set_turbo(value:bool): # set turbo state + print(f"setting turbo boost: {'on' if value else 'off'}") + turbo(value) def charging(): """ @@ -313,18 +277,14 @@ def charging(): # check if we found power supplies. on a desktop these are not found # and we assume we are on a powercable. - if len(power_supplies) == 0: - # nothing found found, so nothing to check - return True + if len(power_supplies) == 0: return True # nothing found found, so nothing to check # we found some power supplies, lets check their state else: for supply in power_supplies: # Check if supply is in ignore list ignore_supply = any(item in supply for item in POWER_SUPPLY_IGNORELIST) # If found in ignore list, skip it. - if ignore_supply: - continue - + if ignore_supply: continue try: with open(Path(power_supply_path + supply + "/type")) as f: supply_type = f.read()[:-1] @@ -332,55 +292,34 @@ def charging(): # we found an AC try: with open(Path(power_supply_path + supply + "/online")) as f: - val = int(f.read()[:-1]) - if val == 1: - # we are definitely charging - return True - except FileNotFoundError: - # we could not find online, check next item - continue + if int(f.read()[:-1]) == 1: return True # we are definitely charging + except FileNotFoundError: continue # we could not find online, check next item elif supply_type == "Battery": # we found a battery, check if its being discharged try: with open(Path(power_supply_path + supply + "/status")) as f: - val = str(f.read()[:-1]) - if val == "Discharging": - # we found a discharging battery - return False - except FileNotFoundError: - # could not find status, check the next item - continue - else: - # continue to next item because current is not - # "Mains" or "Battery" - continue - except FileNotFoundError: - # could not find type, check the next item - continue + if str(f.read()[:-1]) == "Discharging": return False # we found a discharging battery + except FileNotFoundError: continue # could not find status, check the next item + else: continue # continue to next item because current is not "Mains" or "Battery" + except FileNotFoundError: continue # could not find type, check the next item # we cannot determine discharging state, assume we are on powercable return True def get_avail_gov(): - f = Path("/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors") - return f.read_text().strip().split(" ") + return Path("/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors").read_text().strip().split() - -def get_avail_powersave(): +def get_avail(reverse:bool): """ - Iterate over ALL_GOVERNORS in reverse order: from powersave to performance + Iterate over ALL_GOVERNORS: from performance to powersave (invert if reverse=True) :return: """ - for g in ALL_GOVERNORS[::-1]: - if g in get_avail_gov(): - return g - - -def get_avail_performance(): - for g in ALL_GOVERNORS: - if g in get_avail_gov(): - return g + gov = ALL_GOVERNORS[::-1] if reverse else ALL_GOVERNORS + for g in gov: + if g in get_avail_gov(): return g +def get_avail_performance(): get_avail(False) +def get_avail_powersave(): get_avail(True) def get_current_gov(): return print( @@ -389,36 +328,22 @@ def get_current_gov(): "governor", ) - def cpufreqctl(): """ deploy cpufreqctl script """ - - # detect if running on a SNAP - if os.getenv("PKG_MARKER") == "SNAP": - pass - else: - # deploy cpufreqctl.auto-cpufreq script - if not os.path.isfile("/usr/local/bin/cpufreqctl.auto-cpufreq"): - shutil.copy(SCRIPTS_DIR / "cpufreqctl.sh", "/usr/local/bin/cpufreqctl.auto-cpufreq") - + if not os.path.isfile("/usr/local/bin/cpufreqctl.auto-cpufreq"): # deploy cpufreqctl.auto-cpufreq script if not running on a SNAP + copy(SCRIPTS_DIR / "cpufreqctl.sh", "/usr/local/bin/cpufreqctl.auto-cpufreq") def cpufreqctl_restore(): """ remove cpufreqctl.auto-cpufreq script """ # detect if running on a SNAP - if os.getenv("PKG_MARKER") == "SNAP": - pass - else: - if os.path.isfile("/usr/local/bin/cpufreqctl.auto-cpufreq"): - os.remove("/usr/local/bin/cpufreqctl.auto-cpufreq") - - -def footer(l=79): - print("\n" + "-" * l + "\n") + if os.path.isfile("/usr/local/bin/cpufreqctl.auto-cpufreq"): # remove cpufreqctl.auto-cpufreq script if not running on a SNAP + os.remove("/usr/local/bin/cpufreqctl.auto-cpufreq") +def footer(l=79): print("\n" + "-" * l + "\n") def deploy_complete_msg(): print("\n" + "-" * 17 + " auto-cpufreq daemon installed and running " + "-" * 17 + "\n") @@ -426,20 +351,17 @@ def deploy_complete_msg(): print("\nTo disable and remove auto-cpufreq daemon, run:\nsudo auto-cpufreq --remove") footer() - def deprecated_log_msg(): print("\n" + "-" * 24 + " auto-cpufreq log file renamed " + "-" * 24 + "\n") print("The --log flag has been renamed to --stats\n") print("To view live stats, run:\nauto-cpufreq --stats") footer() - def remove_complete_msg(): print("\n" + "-" * 25 + " auto-cpufreq daemon removed " + "-" * 25 + "\n") print("auto-cpufreq successfully removed.") footer() - def deploy_daemon(): print("\n" + "-" * 21 + " Deploying auto-cpufreq as a daemon " + "-" * 22 + "\n") @@ -452,10 +374,10 @@ def deploy_daemon(): auto_cpufreq_stats_path.touch(exist_ok=True) print("\n* Deploy auto-cpufreq install script") - shutil.copy(SCRIPTS_DIR / "auto-cpufreq-install.sh", "/usr/local/bin/auto-cpufreq-install") + copy(SCRIPTS_DIR / "auto-cpufreq-install.sh", "/usr/local/bin/auto-cpufreq-install") print("\n* Deploy auto-cpufreq remove script") - shutil.copy(SCRIPTS_DIR / "auto-cpufreq-remove.sh", "/usr/local/bin/auto-cpufreq-remove") + copy(SCRIPTS_DIR / "auto-cpufreq-remove.sh", "/usr/local/bin/auto-cpufreq-remove") # output warning if gnome power profile is running gnome_power_detect_install() @@ -466,7 +388,6 @@ def deploy_daemon(): call("/usr/local/bin/auto-cpufreq-install", shell=True) - def deploy_daemon_performance(): print("\n" + "-" * 21 + " Deploying auto-cpufreq as a daemon (performance) " + "-" * 22 + "\n") @@ -486,10 +407,10 @@ def deploy_daemon_performance(): auto_cpufreq_stats_path.touch(exist_ok=True) print("\n* Deploy auto-cpufreq install script") - shutil.copy(SCRIPTS_DIR / "auto-cpufreq-install.sh", "/usr/local/bin/auto-cpufreq-install") + copy(SCRIPTS_DIR / "auto-cpufreq-install.sh", "/usr/local/bin/auto-cpufreq-install") print("\n* Deploy auto-cpufreq remove script") - shutil.copy(SCRIPTS_DIR / "auto-cpufreq-remove.sh", "/usr/local/bin/auto-cpufreq-remove") + copy(SCRIPTS_DIR / "auto-cpufreq-remove.sh", "/usr/local/bin/auto-cpufreq-remove") # output warning if gnome power profile is running gnome_power_detect_install() @@ -501,10 +422,8 @@ def deploy_daemon_performance(): call("/usr/local/bin/auto-cpufreq-install", shell=True) - # remove auto-cpufreq daemon def remove_daemon(): - # check if auto-cpufreq is installed if not os.path.exists("/usr/local/bin/auto-cpufreq-remove"): print("\nauto-cpufreq daemon is not installed.\n") @@ -526,27 +445,23 @@ def remove_daemon(): os.remove("/usr/local/bin/auto-cpufreq-remove") # delete override pickle if it exists - if os.path.exists(governor_override_state): - os.remove(governor_override_state) + if os.path.exists(governor_override_state): os.remove(governor_override_state) # delete stats file if auto_cpufreq_stats_path.exists(): - if auto_cpufreq_stats_file is not None: - auto_cpufreq_stats_file.close() + if auto_cpufreq_stats_file is not None: auto_cpufreq_stats_file.close() auto_cpufreq_stats_path.unlink() # restore original cpufrectl script cpufreqctl_restore() - def gov_check(): for gov in get_avail_gov(): if gov not in ALL_GOVERNORS: print("\n" + "-" * 18 + " Checking for necessary scaling governors " + "-" * 19 + "\n") sys.exit("ERROR:\n\nCouldn't find any of the necessary scaling governors.\n") - # root check func def root_check(): if not os.geteuid() == 0: @@ -555,7 +470,6 @@ def root_check(): footer() exit(1) - # refresh countdown def countdown(s): # Fix for wrong stats output and "TERM environment variable not set" @@ -572,34 +486,27 @@ def countdown(s): # auto-refresh counter for remaining in range(s, -1, -1): - - if remaining <= 3 and remaining >= 0: - print(".", end="", flush=True) + if remaining <= 3 and remaining >= 0: print(".", end="", flush=True) time.sleep(0.75) now = datetime.now() current_time = now.strftime("%B %d (%A) - %H:%M:%S") print("\n\t\tExecuted on:", current_time) - # get cpu usage + system load for (last minute) def display_load(): - - # get CPU utilization as a percentage - cpuload = psutil.cpu_percent(interval=1) - - # get system/CPU load - load1m, _, _ = os.getloadavg() + cpuload = psutil.cpu_percent(interval=1) # get CPU utilization as a percentage + load1m = os.getloadavg()[0] # get system/CPU load print("\nTotal CPU usage:", cpuload, "%") print("Total system load: {:.2f}".format(load1m)) print("Average temp. of all cores: {:.2f} °C \n".format(avg_all_core_temp)) + return cpuload, load1m + # get system load average 1m, 5m, 15m (equivalent to uptime) def display_system_load_avg(): - load1m, load5m, load15m = os.getloadavg() - print(f" (load average: {load1m:.2f}, {load5m:.2f}, {load15m:.2f})") # set minimum and maximum CPU frequencies @@ -616,10 +523,9 @@ def set_frequencies(): if ( hasattr(set_frequencies, "prev_power_supply") and power_supply == set_frequencies.prev_power_supply - ): - return - else: - set_frequencies.prev_power_supply = power_supply + ): return + + set_frequencies.prev_power_supply = power_supply frequency = { "scaling_max_freq": { @@ -648,23 +554,15 @@ def set_frequencies(): else: curr_freq = int(getoutput(f"cpufreqctl.auto-cpufreq --frequency-min")) value = set_frequencies.min_limit - if curr_freq == value: - continue + if curr_freq == value: continue - try: - frequency[freq_type]["value"] = ( - value if value else int(conf[power_supply][freq_type].strip()) - ) + try: frequency[freq_type]["value"] = (value if value else int(conf[power_supply][freq_type].strip())) except ValueError: print(f"Invalid value for '{freq_type}': {frequency[freq_type]['value']}") exit(1) - if not ( - set_frequencies.min_limit <= frequency[freq_type]["value"] <= set_frequencies.max_limit - ): - print( - f"Given value for '{freq_type}' is not within the allowed frequencies {set_frequencies.min_limit}-{set_frequencies.max_limit} kHz" - ) + if not (set_frequencies.min_limit <= frequency[freq_type]["value"] <= set_frequencies.max_limit): + print(f"Given value for '{freq_type}' is not within the allowed frequencies {set_frequencies.min_limit}-{set_frequencies.max_limit} kHz") exit(1) args = f"{frequency[freq_type]['cmdargs']} --set={frequency[freq_type]['value']}" @@ -674,32 +572,27 @@ def set_frequencies(): print(message) run(f"cpufreqctl.auto-cpufreq {args}", shell=True) +def display_average_core_temperatures(cpuload): + print(f"Optimal total CPU usage: {cpuload} %, high average core temp: {avg_all_core_temp} °C") # set powersave and enable turbo def set_powersave(): conf = config.get_config() - if conf.has_option("battery", "governor"): - gov = conf["battery"]["governor"] - else: - gov = get_avail_powersave() + if conf.has_option("battery", "governor"): gov = conf["battery"]["governor"] + else: gov = get_avail_powersave() print(f'Setting to use: "{gov}" governor') - if get_override() != "default": - print("Warning: governor overwritten using `--force` flag.") + if get_override() != "default": print("Warning: governor overwritten using `--force` flag.") run(f"cpufreqctl.auto-cpufreq --governor --set={gov}", shell=True) - if Path("/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference").exists() is False: print('Not setting EPP (not supported by system)') else: dynboost_enabled = Path("/sys/devices/system/cpu/intel_pstate/hwp_dynamic_boost").exists() if dynboost_enabled: - dynboost_enabled = bool(int( - os.popen("cat /sys/devices/system/cpu/intel_pstate/hwp_dynamic_boost").read() - )) + dynboost_enabled = bool(int(os.popen("cat /sys/devices/system/cpu/intel_pstate/hwp_dynamic_boost").read())) - if dynboost_enabled: - print('Not setting EPP (dynamic boosting is enabled)') + if dynboost_enabled: print('Not setting EPP (dynamic boosting is enabled)') else: if conf.has_option("battery", "energy_performance_preference"): epp = conf["battery"]["energy_performance_preference"] @@ -712,221 +605,77 @@ def set_powersave(): # set frequencies set_frequencies() - # get CPU utilization as a percentage - cpuload = psutil.cpu_percent(interval=1) - - # get system/CPU load - load1m, _, _ = os.getloadavg() - - print("\nTotal CPU usage:", cpuload, "%") - print("Total system load: {:.2f}".format(load1m)) - print("Average temp. of all cores: {:.2f} °C \n".format(avg_all_core_temp)) + cpuload , load1m = display_load() # conditions for setting turbo in powersave - if conf.has_option("battery", "turbo"): - auto = conf["battery"]["turbo"] - else: - auto = "auto" + auto = conf["battery"]["turbo"] if conf.has_option("battery", "turbo") else "auto" if auto == "always": print("Configuration file enforces turbo boost") - print("setting turbo boost: on") - turbo(True) + set_turbo(True) elif auto == "never": print("Configuration file disables turbo boost") - print("setting turbo boost: off") - turbo(False) + set_turbo(False) else: if psutil.cpu_percent(percpu=False, interval=0.01) >= 30.0 or isclose( max(psutil.cpu_percent(percpu=True, interval=0.01)), 100 - ): - print("High CPU load", end=""), display_system_load_avg() - - # high cpu usage trigger - if cpuload >= 20: - print("setting turbo boost: on") - turbo(True) - - # set turbo state based on average of all core temperatures - elif cpuload <= 20 and avg_all_core_temp >= 70: - print( - "Optimal total CPU usage:", - cpuload, - "%, high average core temp:", - avg_all_core_temp, - "°C", - ) - print("setting turbo boost: off") - turbo(False) - else: - print("setting turbo boost: off") - turbo(False) + ): print("High CPU load", end=""), display_system_load_avg() + elif load1m > powersave_load_threshold: print("High system load", end="") + else: print("Load optimal", end="") - elif load1m > powersave_load_threshold: - print("High system load", end=""), display_system_load_avg() - - # high cpu usage trigger - if cpuload >= 20: - print("setting turbo boost: on") - turbo(True) - - # set turbo state based on average of all core temperatures - elif cpuload <= 20 and avg_all_core_temp >= 65: - print( - "Optimal total CPU usage:", - cpuload, - "%, high average core temp:", - avg_all_core_temp, - "°C", - ) - print("setting turbo boost: off") - turbo(False) - else: - print("setting turbo boost: off") - turbo(False) + display_system_load_avg() + # high cpu usage trigger + if cpuload >= 20: set_turbo(True) + # set turbo state based on average of all core temperatures else: - print("Load optimal", end=""), display_system_load_avg() - - # high cpu usage trigger - if cpuload >= 20: - print("setting turbo boost: on") - turbo(True) - - # set turbo state based on average of all core temperatures - elif cpuload <= 20 and avg_all_core_temp >= 60: - print( - "Optimal total CPU usage:", - cpuload, - "%, high average core temp:", - avg_all_core_temp, - "°C", - ) - print("setting turbo boost: off") - turbo(False) - else: - print("setting turbo boost: off") - turbo(False) + display_average_core_temperatures(cpuload) + set_turbo(False) footer() - # make turbo suggestions in powersave def mon_powersave(): - # get CPU utilization as a percentage - cpuload = psutil.cpu_percent(interval=1) - - # get system/CPU load - load1m, _, _ = os.getloadavg() - - print("\nTotal CPU usage:", cpuload, "%") - print("Total system load: {:.2f}".format(load1m)) - print("Average temp. of all cores: {:.2f} °C \n".format(avg_all_core_temp)) + cpuload, load1m = display_load() if psutil.cpu_percent(percpu=False, interval=0.01) >= 30.0 or isclose( max(psutil.cpu_percent(percpu=True, interval=0.01)), 100 - ): - print("High CPU load", end=""), display_system_load_avg() - - # high cpu usage trigger - if cpuload >= 20: - print("suggesting to set turbo boost: on") - get_turbo() - - # set turbo state based on average of all core temperatures - elif cpuload <= 20 and avg_all_core_temp >= 70: - print( - "Optimal total CPU usage:", - cpuload, - "%, high average core temp:", - avg_all_core_temp, - "°C", - ) - print("suggesting to set turbo boost: off") - get_turbo() - else: - print("suggesting to set turbo boost: off") - get_turbo() - - elif load1m > powersave_load_threshold: - print("High system load", end=""), display_system_load_avg() + ): print("High CPU load", end=""), + elif load1m > powersave_load_threshold: print("High system load", end="") + else: print("Load optimal", end="") - # high cpu usage trigger - if cpuload >= 20: - print("suggesting to set turbo boost: on") - get_turbo() - - # set turbo state based on average of all core temperatures - elif cpuload <= 20 and avg_all_core_temp >= 65: - print( - "Optimal total CPU usage:", - cpuload, - "%, high average core temp:", - avg_all_core_temp, - "°C", - ) - print("suggesting to set turbo boost: off") - get_turbo() - else: - print("suggesting to set turbo boost: off") - get_turbo() + display_system_load_avg() + # high cpu usage trigger + if cpuload >= 20: print("suggesting to set turbo boost: on") + # set turbo state based on average of all core temperatures else: - print("Load optimal", end=""), display_system_load_avg() - - # high cpu usage trigger - if cpuload >= 20: - print("suggesting to set turbo boost: on") - get_turbo() - - # set turbo state based on average of all core temperatures - elif cpuload <= 20 and avg_all_core_temp >= 60: - print( - "Optimal total CPU usage:", - cpuload, - "%, high average core temp:", - avg_all_core_temp, - "°C", - ) - print("suggesting to set turbo boost: off") - get_turbo() - else: - print("suggesting to set turbo boost: off") - get_turbo() + display_average_core_temperatures(cpuload) + print("suggesting to set turbo boost: off") + + get_turbo() footer() - # set performance and enable turbo def set_performance(): conf = config.get_config() - if conf.has_option("charger", "governor"): - gov = conf["charger"]["governor"] - else: - gov = get_avail_performance() + gov = conf["charger"]["governor"] if conf.has_option("charger", "governor") else get_avail_performance() print(f'Setting to use: "{gov}" governor') - if get_override() != "default": - print("Warning: governor overwritten using `--force` flag.") - run( - f"cpufreqctl.auto-cpufreq --governor --set={gov}", - shell=True, - ) - + if get_override() != "default": print("Warning: governor overwritten using `--force` flag.") + run(f"cpufreqctl.auto-cpufreq --governor --set={gov}", shell=True) - if Path("/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference").exists() is False: + if not Path("/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference").exists(): print('Not setting EPP (not supported by system)') else: dynboost_enabled = Path("/sys/devices/system/cpu/intel_pstate/hwp_dynamic_boost").exists() if dynboost_enabled: - dynboost_enabled = bool(int( - os.popen("cat /sys/devices/system/cpu/intel_pstate/hwp_dynamic_boost").read() - )) + dynboost_enabled = bool(int(os.popen("cat /sys/devices/system/cpu/intel_pstate/hwp_dynamic_boost").read())) - if dynboost_enabled: - print('Not setting EPP (dynamic boosting is enabled)') + if dynboost_enabled: print('Not setting EPP (dynamic boosting is enabled)') else: intel_pstate_status_path = "/sys/devices/system/cpu/intel_pstate/status" @@ -952,28 +701,16 @@ def set_performance(): set_frequencies() # get CPU utilization as a percentage - cpuload = psutil.cpu_percent(interval=1) - - # get system/CPU load - load1m, _, _ = os.getloadavg() + cpuload, load1m = display_load() - print("\nTotal CPU usage:", cpuload, "%") - print("Total system load: {:.2f}".format(load1m)) - print("Average temp. of all cores: {:.2f} °C \n".format(avg_all_core_temp)) - - if conf.has_option("charger", "turbo"): - auto = conf["charger"]["turbo"] - else: - auto = "auto" + auto = conf["charger"]["turbo"] if conf.has_option("charger", "turbo") else "auto" if auto == "always": print("Configuration file enforces turbo boost") - print("setting turbo boost: on") - turbo(True) + set_turbo(True) elif auto == "never": print("Configuration file disables turbo boost") - print("setting turbo boost: off") - turbo(False) + set_turbo(False) else: if ( psutil.cpu_percent(percpu=False, interval=0.01) >= 20.0 @@ -982,165 +719,61 @@ def set_performance(): print("High CPU load", end=""), display_system_load_avg() # high cpu usage trigger - if cpuload >= 20: - print("setting turbo boost: on") - turbo(True) - + if cpuload >= 20: set_turbo(True) # set turbo state based on average of all core temperatures elif avg_all_core_temp >= 70: - print( - "Optimal total CPU usage:", - cpuload, - "%, high average core temp:", - avg_all_core_temp, - "°C", - ) - print("setting turbo boost: off") - turbo(False) - else: - print("setting turbo boost: on") - turbo(True) + display_average_core_temperatures(cpuload) + set_turbo(False) + else: set_turbo(True) elif load1m >= performance_load_threshold: print("High system load", end=""), display_system_load_avg() # high cpu usage trigger - if cpuload >= 20: - print("setting turbo boost: on") - turbo(True) - + if cpuload >= 20: set_turbo(True) # set turbo state based on average of all core temperatures elif avg_all_core_temp >= 65: - print( - "Optimal total CPU usage:", - cpuload, - "%, high average core temp:", - avg_all_core_temp, - "°C", - ) - print("setting turbo boost: off") - turbo(False) - else: - print("setting turbo boost: on") - turbo(True) + display_average_core_temperatures(cpuload) + set_turbo(False) + else: set_turbo(True) else: print("Load optimal", end=""), display_system_load_avg() # high cpu usage trigger - if cpuload >= 20: - print("setting turbo boost: on") - turbo(True) - + if cpuload >= 20: set_turbo(True) # set turbo state based on average of all core temperatures - elif avg_all_core_temp >= 60: - print( - "Optimal total CPU usage:", - cpuload, - "%, high average core temp:", - avg_all_core_temp, - "°C", - ) - print("setting turbo boost: off") - turbo(False) else: - print("setting turbo boost: off") - turbo(False) + display_average_core_temperatures(cpuload) + set_turbo(False) footer() - # make turbo suggestions in performance def mon_performance(): - - # get CPU utilization as a percentage - cpuload = psutil.cpu_percent(interval=1) - - # get system/CPU load - load1m, _, _ = os.getloadavg() - - print("\nTotal CPU usage:", cpuload, "%") - print("Total system load: {:.2f}".format(load1m)) - print("Average temp. of all cores: {:.2f} °C \n".format(avg_all_core_temp)) - - # get system/CPU load - load1m, _, _ = os.getloadavg() + cpuload, load1m = display_load() if ( psutil.cpu_percent(percpu=False, interval=0.01) >= 20.0 or max(psutil.cpu_percent(percpu=True, interval=0.01)) >= 75 - ): - print("High CPU load", end=""), display_system_load_avg() - - # high cpu usage trigger - if cpuload >= 20: - print("suggesting to set turbo boost: on") - get_turbo() - - # set turbo state based on average of all core temperatures - elif cpuload <= 25 and avg_all_core_temp >= 70: - print( - "Optimal total CPU usage:", - cpuload, - "%, high average core temp:", - avg_all_core_temp, - "°C", - ) - print("suggesting to set turbo boost: off") - get_turbo() - else: - print("suggesting to set turbo boost: on") - get_turbo() - - elif load1m > performance_load_threshold: - print("High system load", end=""), display_system_load_avg() + ): print("High CPU load", end="") + elif load1m > performance_load_threshold: print("High system load", end="") + else: print("Load optimal", end="") - # high cpu usage trigger - if cpuload >= 20: - print("suggesting to set turbo boost: on") - get_turbo() + display_system_load_avg() - # set turbo state based on average of all core temperatures - elif cpuload <= 25 and avg_all_core_temp >= 65: - print( - "Optimal total CPU usage:", - cpuload, - "%, high average core temp:", - avg_all_core_temp, - "°C", - ) - print("suggesting to set turbo boost: off") - get_turbo() - else: - print("suggesting to set turbo boost: on") - get_turbo() + # high cpu usage trigger + if cpuload >= 20: print("suggesting to set turbo boost: on") + # set turbo state based on average of all core temperatures + elif cpuload <= 25 and avg_all_core_temp >= 60: + display_average_core_temperatures(cpuload) + print("suggesting to set turbo boost: off") + else: print("suggesting to set turbo boost: on") - else: - print("Load optimal", end=""), display_system_load_avg() - - # high cpu usage trigger - if cpuload >= 20: - print("suggesting to set turbo boost: on") - get_turbo() - - # set turbo state based on average of all core temperatures - elif cpuload <= 25 and avg_all_core_temp >= 60: - print( - "Optimal total CPU usage:", - cpuload, - "%, high average core temp:", - avg_all_core_temp, - "°C", - ) - print("suggesting to set turbo boost: off") - get_turbo() - else: - print("suggesting to set turbo boost: on") - get_turbo() + get_turbo() footer() - def set_autofreq(): """ set cpufreq governor based if device is charging @@ -1149,10 +782,8 @@ def set_autofreq(): # determine which governor should be used override = get_override() - if override == "powersave": - set_powersave() - elif override == "performance": - set_performance() + if override == "powersave": set_powersave() + elif override == "performance": set_performance() elif charging(): print("Battery is: charging\n") set_performance() @@ -1160,7 +791,6 @@ def set_autofreq(): print("Battery is: discharging\n") set_powersave() - def mon_autofreq(): """ make cpufreq suggestions @@ -1180,7 +810,6 @@ def mon_autofreq(): print(f'Suggesting use of "{get_avail_powersave()}" governor') mon_powersave() - def python_info(): print("Python:", pl.python_version()) print("psutil package:", psutil.__version__) @@ -1188,10 +817,7 @@ def python_info(): print("click package:", click.__version__) print("distro package:", distro.__version__) - -def device_info(): - print("Computer type:", getoutput("dmidecode --string chassis-type")) - +def device_info(): print("Computer type:", getoutput("dmidecode --string chassis-type")) def distro_info(): dist = "UNKNOWN distro" @@ -1213,20 +839,17 @@ def distro_info(): pass dist = f"{dist} {version}" - else: - # get distro information + else: # get distro information fdist = distro.linux_distribution() dist = " ".join(x for x in fdist) print("Linux distro: " + dist) print("Linux kernel: " + pl.release()) - def sysinfo(): """ get system information """ - # processor_info model_name = getoutput("grep -E 'model name' /proc/cpuinfo -m 1").split(":")[-1] print(f"Processor:{model_name}") @@ -1261,19 +884,14 @@ def sysinfo(): freq_per_cpu = [] for i in range(0, len(coreid_info), 3): # ensure that indices are within the valid range, before accessing the corresponding elements - if i + 1 < len(coreid_info): - freq_per_cpu.append(float(coreid_info[i + 1].split(":")[-1])) - else: - # handle the case where the index is out of range - continue + if i + 1 < len(coreid_info): freq_per_cpu.append(float(coreid_info[i + 1].split(":")[-1])) + else: continue # handle the case where the index is out of range # ensure that indices are within the valid range, before accessing the corresponding elements cpu = int(coreid_info[i].split(":")[-1]) if i + 2 < len(coreid_info): core = int(coreid_info[i + 2].split(":")[-1]) cpu_core[cpu] = core - else: - # handle the case where the index is out of range - continue + else: continue # handle the case where the index is out of range online_cpu_count = len(cpu_core) offline_cpus = [str(cpu) for cpu in range(total_cpu_count) if cpu not in cpu_core] @@ -1300,15 +918,14 @@ def sysinfo(): if temp.current != 0: temp_per_cpu = [temp.current] * online_cpu_count break - else: - continue + else: continue break else: for sensor in ["acpitz", "k10temp", "zenpower"]: if sensor in temp_sensors: if temp_sensors[sensor][0].current != 0: temp_per_cpu = [temp_sensors[sensor][0].current] * online_cpu_count - break; + break except Exception as e: print(repr(e)) pass @@ -1317,8 +934,7 @@ def sysinfo(): for (cpu, usage, freq, temp) in zip(cpu_core, usage_per_cpu, freq_per_cpu, temp_per_cpu): print(f"CPU{cpu} {usage:>5.1f}% {temp:>3.0f} °C {freq:>5.0f} MHz") - if offline_cpus: - print(f"\nDisabled CPUs: {','.join(offline_cpus)}") + if offline_cpus: print(f"\nDisabled CPUs: {','.join(offline_cpus)}") # get average temperature of all cores avg_cores_temp = sum(temp_per_cpu) @@ -1327,45 +943,32 @@ def sysinfo(): # print current fan speed current_fans = list(psutil.sensors_fans()) - for current_fan in current_fans: - print("\nCPU fan speed:", psutil.sensors_fans()[current_fan][0].current, "RPM") - - + for current_fan in current_fans: print("\nCPU fan speed:", psutil.sensors_fans()[current_fan][0].current, "RPM") # read stats func def read_stats(): # read stats - if os.path.isfile(auto_cpufreq_stats_path): - call(["tail", "-n 50", "-f", str(auto_cpufreq_stats_path)], stderr=DEVNULL) + if os.path.isfile(auto_cpufreq_stats_path): call(["tail", "-n 50", "-f", str(auto_cpufreq_stats_path)], stderr=DEVNULL) footer() - # check if program (argument) is running def is_running(program, argument): # iterate over all processes found by psutil # and find the one with name and args passed to the function for p in psutil.process_iter(): - try: - cmd = p.cmdline(); - except: - continue - for s in filter(lambda x: program in x, cmd): - if argument in cmd: - return True - + try: cmd = p.cmdline() + except: continue + for _ in filter(lambda x: program in x, cmd): + if argument in cmd: return True def daemon_running_msg(): print("\n" + "-" * 24 + " auto-cpufreq running " + "-" * 30 + "\n") - print( - "ERROR: auto-cpufreq is running in daemon mode.\n\nMake sure to stop the daemon before running with --live or --monitor mode" - ) + print("ERROR: auto-cpufreq is running in daemon mode.\n\nMake sure to stop the daemon before running with --live or --monitor mode") footer() def daemon_not_running_msg(): print("\n" + "-" * 24 + " auto-cpufreq not running " + "-" * 30 + "\n") - print( - "ERROR: auto-cpufreq is not running in daemon mode.\n\nMake sure to run \"sudo auto-cpufreq --install\" first" - ) + print("ERROR: auto-cpufreq is not running in daemon mode.\n\nMake sure to run \"sudo auto-cpufreq --install\" first") footer() # check if auto-cpufreq --daemon is running diff --git a/auto_cpufreq/gui/app.py b/auto_cpufreq/gui/app.py index 6e91c201..e4c0ab04 100644 --- a/auto_cpufreq/gui/app.py +++ b/auto_cpufreq/gui/app.py @@ -26,7 +26,6 @@ HBOX_PADDING = 20 PKEXEC_ERROR = "Error executing command as another user: Not authorized\n\nThis incident has been reported.\n" - class ToolWindow(Gtk.Window): def __init__(self): super().__init__(title="auto-cpufreq") @@ -39,7 +38,6 @@ def __init__(self): self.build() def main(self): - # Main HBOX self.hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=HBOX_PADDING) @@ -61,7 +59,6 @@ def main(self): self.hbox.pack_start(self.vbox_right, False, False, 0) - GLib.timeout_add_seconds(5, self.refresh_in_thread) def snap(self): @@ -81,15 +78,12 @@ def snap(self): def handle_update(self): new_stdout = StringIO() with redirect_stdout(new_stdout): - is_new_update = check_for_update() - if not is_new_update: - return + if not check_for_update(): return captured_output = new_stdout.getvalue().splitlines() dialog = UpdateDialog(self, captured_output[1], captured_output[2]) response = dialog.run() dialog.destroy() - if response != Gtk.ResponseType.YES: - return + if response != Gtk.ResponseType.YES: return updater = run(["pkexec", "auto-cpufreq", "--update"], input="y\n", encoding="utf-8", stderr=PIPE) if updater.stderr == PKEXEC_ERROR: error = Gtk.MessageDialog(self, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, "Error updating") @@ -108,12 +102,9 @@ def daemon_not_running(self): self.add(self.box) def build(self): - if os.getenv("PKG_MARKER") == "SNAP": - self.snap() - elif is_running("auto-cpufreq", "--daemon"): - self.main() - else: - self.daemon_not_running() + if os.getenv("PKG_MARKER") == "SNAP": self.snap() + elif is_running("auto-cpufreq", "--daemon"): self.main() + else: self.daemon_not_running() def load_css(self): screen = Gdk.Screen.get_default() diff --git a/auto_cpufreq/gui/objects.py b/auto_cpufreq/gui/objects.py index 5e9bfd83..eb60f27b 100644 --- a/auto_cpufreq/gui/objects.py +++ b/auto_cpufreq/gui/objects.py @@ -17,38 +17,28 @@ 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/auto-cpufreq.stats" -else: - auto_cpufreq_stats_path = "/var/run/auto-cpufreq.stats" - +auto_cpufreq_stats_path = ("/var/snap/auto-cpufreq/current" if os.getenv("PKG_MARKER") == "SNAP" else "/var/run") + "/auto-cpufreq.stats" def get_stats(): if os.path.isfile(auto_cpufreq_stats_path): - with open(auto_cpufreq_stats_path, "r") as file: - stats = [line for line in (file.readlines() [-50:])] + with open(auto_cpufreq_stats_path, "r") as file: stats = [line for line in (file.readlines() [-50:])] return "".join(stats) def get_version(): # snap package - if os.getenv("PKG_MARKER") == "SNAP": - return getoutput(r"echo \(Snap\) $SNAP_VERSION") + if os.getenv("PKG_MARKER") == "SNAP": return getoutput(r"echo \(Snap\) $SNAP_VERSION") # aur package elif dist_name in ["arch", "manjaro", "garuda"]: aur_pkg_check = run("pacman -Qs auto-cpufreq > /dev/null", shell=True) - if aur_pkg_check == 1: - return get_formatted_version() - else: - return getoutput("pacman -Qi auto-cpufreq | grep Version") + if aur_pkg_check == 1: return get_formatted_version() + else: return getoutput("pacman -Qi auto-cpufreq | grep Version") else: # source code (auto-cpufreq-installer) - try: - return get_formatted_version() + try: return get_formatted_version() except Exception as e: print(repr(e)) pass - class RadioButtonView(Gtk.Box): def __init__(self): super().__init__(orientation=Gtk.Orientation.HORIZONTAL) @@ -67,7 +57,6 @@ def __init__(self): self.performance = Gtk.RadioButton.new_with_label_from_widget(self.default, "Performance") self.performance.connect("toggled", self.on_button_toggled, "performance") 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 self.set_by_app = True @@ -82,24 +71,17 @@ def on_button_toggled(self, button, override): if button.get_active(): if not self.set_by_app: result = run(f"pkexec auto-cpufreq --force={override}", shell=True, stdout=PIPE, stderr=PIPE) - if result.stderr.decode() == PKEXEC_ERROR: - self.set_selected() - else: - self.set_by_app = False - - + if result.stderr.decode() == PKEXEC_ERROR: self.set_selected() + else: self.set_by_app = False def set_selected(self): override = get_override() match override: - case "powersave": - self.powersave.set_active(True) - case "performance": - self.performance.set_active(True) + case "powersave": self.powersave.set_active(True) + case "performance": self.performance.set_active(True) case "default": # because this is the default button, it does not trigger the callback when set by the app - if self.set_by_app: - self.set_by_app = False + if self.set_by_app: self.set_by_app = False self.default.set_active(True) class CurrentGovernorBox(Gtk.Box): @@ -117,7 +99,6 @@ def refresh(self): class SystemStatsLabel(Gtk.Label): def __init__(self): super().__init__() - self.refresh() def refresh(self): @@ -130,7 +111,6 @@ def refresh(self): self.set_label(text.getvalue()) sys.stdout = old_stdout - class CPUFreqStatsLabel(Gtk.Label): def __init__(self): super().__init__() @@ -188,8 +168,7 @@ def _remove_daemon(self, MenuItem, parent): kwargs = {"shell": True, "stdout": PIPE, "stderr": PIPE} future = executor.submit(run, "pkexec auto-cpufreq --remove", **kwargs) result = future.result() - if result.stderr.decode() == PKEXEC_ERROR: - raise Exception("Authorization was cancelled") + assert result.stderr.decode() != PKEXEC_ERROR, Exception("Authorization was cancelled") dialog = Gtk.MessageDialog( transient_for=parent, message_type=Gtk.MessageType.INFO, @@ -211,7 +190,6 @@ def _remove_daemon(self, MenuItem, parent): dialog.run() dialog.destroy() - class AboutDialog(Gtk.Dialog): def __init__(self, parent): super().__init__(title="About", transient_for=parent) @@ -221,10 +199,11 @@ def __init__(self, parent): self.add_button("Close", Gtk.ResponseType.CLOSE) self.set_default_size(400, 350) img_buffer = GdkPixbuf.Pixbuf.new_from_file_at_scale( - filename="/usr/local/share/auto-cpufreq/images/icon.png", - width=150, - height=150, - preserve_aspect_ratio=True) + filename="/usr/local/share/auto-cpufreq/images/icon.png", + width=150, + height=150, + preserve_aspect_ratio=True + ) self.image = Gtk.Image.new_from_pixbuf(img_buffer) self.title = Gtk.Label(label="auto-cpufreq", name="bold") self.version = Gtk.Label(label=app_version) @@ -258,7 +237,6 @@ def __init__(self, parent, current_version: str, latest_version: str): self.show_all() - class ConfirmDialog(Gtk.Dialog): def __init__(self, parent, message: str): super().__init__(title="Confirmation", transient_for=parent) @@ -290,8 +268,7 @@ def install_daemon(self, button, parent): kwargs = {"shell": True, "stdout": PIPE, "stderr": PIPE} future = executor.submit(run, "pkexec auto-cpufreq --install", **kwargs) result = future.result() - if result.stderr.decode() == PKEXEC_ERROR: - raise Exception("Authorization was cancelled") + assert result.stderr.decode() != PKEXEC_ERROR, Exception("Authorization was cancelled") # enable for debug. causes issues if kept # elif result.stderr is not None: # raise Exception(result.stderr.decode()) diff --git a/auto_cpufreq/gui/tray.py b/auto_cpufreq/gui/tray.py index de0495d1..efd7d0d3 100644 --- a/auto_cpufreq/gui/tray.py +++ b/auto_cpufreq/gui/tray.py @@ -25,8 +25,6 @@ def build_menu(): menu.show_all() return menu -def open_app(MenuItem): - run("sudo -E python app.py", shell=True) +def open_app(MenuItem): run("sudo -E python app.py", shell=True) -if __name__ == "__main__": - main() \ No newline at end of file +if __name__ == "__main__": main() \ No newline at end of file diff --git a/auto_cpufreq/power_helper.py b/auto_cpufreq/power_helper.py index 1386e0c9..97c71aa2 100644 --- a/auto_cpufreq/power_helper.py +++ b/auto_cpufreq/power_helper.py @@ -3,6 +3,7 @@ # * if daemon is disabled and auto-cpufreq is removed (snap) remind user to enable it back from logging import root import os, sys, click, subprocess +from shutil import which from subprocess import getoutput, call, run, check_output, DEVNULL sys.path.append("../") @@ -10,24 +11,15 @@ from auto_cpufreq.tlp_stat_parser import TLPStatusParser # app_name var -if sys.argv[0] == "power_helper.py": - app_name = "python3 power_helper.py" -else: - app_name = "auto-cpufreq" +app_name = "python3 power_helper.py" if sys.argv[0] == "power_helper.py" else "auto-cpufreq" +def header(): print("\n------------------------- auto-cpufreq: Power helper -------------------------\n") +def warning(): print("\n----------------------------------- Warning -----------------------------------\n") -def header(): - print("\n------------------------- auto-cpufreq: Power helper -------------------------\n") - - -def helper_opts(): - print("\nFor full list of options run: python3 power_helper.py --help") - +def helper_opts(): print("\nFor full list of options run: python3 power_helper.py --help") # used to check if binary exists on the system -def does_command_exists(cmd): - return which(cmd) is not None - +def does_command_exists(cmd): return which(cmd) is not None systemctl_exists = does_command_exists("systemctl") bluetoothctl_exists = does_command_exists("bluetoothctl") @@ -37,10 +29,7 @@ def does_command_exists(cmd): # detect if gnome power profile service is running if os.getenv("PKG_MARKER") != "SNAP": if systemctl_exists: - try: - gnome_power_status = call( - ["systemctl", "is-active", "--quiet", "power-profiles-daemon"] - ) + try: gnome_power_status = call(["systemctl", "is-active", "--quiet", "power-profiles-daemon"]) except: print("\nUnable to determine init system") print("If this causes any problems, please submit an issue:") @@ -52,61 +41,46 @@ def tlp_service_detect(): status_output = getoutput("tlp-stat -s") tlp_status = TLPStatusParser(status_output) if tlp_status.is_enabled(): - print( - "\n----------------------------------- Warning -----------------------------------\n" - ) + warning() print("Detected you are running a TLP service!") - print( - "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("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.") # alert about TLP when using snap def tlp_service_detect_snap(): - print("\n----------------------------------- Warning -----------------------------------\n") + warning() 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("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 def gnome_power_detect(): - if systemctl_exists: - if gnome_power_status == 0: - print( - "\n----------------------------------- Warning -----------------------------------\n" - ) - print("Detected running GNOME Power Profiles daemon service!") - 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("git clone https://github.com/AdnanHodzic/auto-cpufreq.git") - print("cd auto-cpufreq/auto_cpufreq") - print("python3 power_helper.py --gnome_power_disable") - print("\nReference: https://github.com/AdnanHodzic/auto-cpufreq#configuring-auto-cpufreq") - + if systemctl_exists and not bool(gnome_power_status): + warning() + print("Detected running GNOME Power Profiles daemon service!") + 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("git clone https://github.com/AdnanHodzic/auto-cpufreq.git") + print("cd auto-cpufreq/auto_cpufreq") + print("python3 power_helper.py --gnome_power_disable") + print("\nReference: https://github.com/AdnanHodzic/auto-cpufreq#configuring-auto-cpufreq") # automatically disable gnome power profile service in case it's running during install def gnome_power_detect_install(): - if systemctl_exists: - if gnome_power_status == 0: - print( - "\n----------------------------------- Warning -----------------------------------\n" - ) - print("Detected running GNOME Power Profiles daemon service!") - 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("will be enabled after auto-cpufreq is removed.\n") + if systemctl_exists and not bool(gnome_power_status): + warning() + print("Detected running GNOME Power Profiles daemon service!") + 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("will be enabled after auto-cpufreq is removed.\n") # notification on 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("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("This daemon might interfere with auto-cpufreq and should be disabled.") 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("\nReference: https://github.com/AdnanHodzic/auto-cpufreq#configuring-auto-cpufreq") - # stops gnome >= 40 power profiles (live) def gnome_power_stop_live(): - if systemctl_exists: - if gnome_power_status == 0 and powerprofilesctl_exists: - call(["powerprofilesctl", "set", "balanced"]) - call(["systemctl", "stop", "power-profiles-daemon"]) + if systemctl_exists and not bool(gnome_power_status) and powerprofilesctl_exists: + call(["powerprofilesctl", "set", "balanced"]) + call(["systemctl", "stop", "power-profiles-daemon"]) # starts gnome >= 40 power profiles (live) def gnome_power_start_live(): - if systemctl_exists: - call(["systemctl", "start", "power-profiles-daemon"]) + if systemctl_exists: call(["systemctl", "start", "power-profiles-daemon"]) # enable gnome >= 40 power profiles (uninstall) 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("https://github.com/AdnanHodzic/auto-cpufreq/issues") - # gnome power profiles current status def gnome_power_svc_status(): if systemctl_exists: @@ -154,11 +124,9 @@ def gnome_power_svc_status(): print("If this causes any problems, please submit an issue:") print("https://github.com/AdnanHodzic/auto-cpufreq/issues") - # disable bluetooth on boot def bluetooth_disable(): - if os.getenv("PKG_MARKER") == "SNAP": - bluetooth_notif_snap() + if os.getenv("PKG_MARKER") == "SNAP": bluetooth_notif_snap() elif bluetoothctl_exists: print("* Turn off bluetooth on boot") btconf = Path("/etc/bluetooth/main.conf") @@ -170,18 +138,12 @@ def bluetooth_disable(): f.seek(0) f.truncate() f.write(content.replace(orig_set, change_set)) - except Exception as 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)" - ) - + except Exception as 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)") # enable bluetooth on boot def bluetooth_enable(): - if os.getenv("PKG_MARKER") == "SNAP": - bluetooth_on_notif_snap() + if os.getenv("PKG_MARKER") == "SNAP": bluetooth_on_notif_snap() if bluetoothctl_exists: print("* Turn on bluetooth on boot") btconf = "/etc/bluetooth/main.conf" @@ -193,13 +155,8 @@ def bluetooth_enable(): f.seek(0) f.truncate() f.write(content.replace(change_set, orig_set)) - except Exception as 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)" - ) - + except Exception as 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)") # turn off bluetooth on snap message 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("python3 power_helper.py --bluetooth_boot_off") - # turn off bluetooth on snap message def bluetooth_on_notif_snap(): 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("python3 power_helper.py --bluetooth_boot_on") - # gnome power removal reminder def gnome_power_rm_reminder(): - if systemctl_exists: - if gnome_power_status != 0: - print( - "\n----------------------------------- Warning -----------------------------------\n" - ) - print("Detected GNOME Power Profiles daemon service is stopped!") - print("This service will now be enabled and started again.") + if systemctl_exists and bool(gnome_power_status): + warning() + print("Detected GNOME Power Profiles daemon service is stopped!") + print("This service will now be enabled and started again.") def gnome_power_rm_reminder_snap(): - print("\n----------------------------------- Warning -----------------------------------\n") + warning() print("Unable to detect state of GNOME Power Profiles daemon service!") print("Now it's recommended to enable this service.") 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("\nReference: https://github.com/AdnanHodzic/auto-cpufreq#configuring-auto-cpufreq") - - def valid_options(): print("--gnome_power_enable\t\tEnable GNOME Power Profiles daemon") print("--gnome_power_disable\t\tDisable GNOME Power Profiles daemon\n") - def disable_power_profiles_daemon(): # always disable power-profiles-daemon try: @@ -256,40 +205,35 @@ def disable_power_profiles_daemon(): print("If this causes any problems, please submit an issue:") print("https://github.com/AdnanHodzic/auto-cpufreq/issues") - # default gnome_power_svc_disable func (balanced) def gnome_power_svc_disable(): snap_pkg_check = 0 if systemctl_exists: - # 0 is active - if gnome_power_status != 0: - + if bool(gnome_power_status): try: # check if snap package installed snap_pkg_check = call(['snap', 'list', '|', 'grep', 'auto-cpufreq'], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) # 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" - "sudo python3 power_helper.py --gnome_power_enable\n" + "sudo python3 power_helper.py --gnome_power_enable\n" ) elif snap_pkg_check == 1: 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: # snapd not found on the system print("There was a problem, couldn't determine GNOME Power Profiles Daemon") 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: - 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" - ) + ) else: print("auto-cpufreq snap package installed, GNOME Power Profiles Daemon should be disabled.\n") print("Using profile: ", "balanced") @@ -305,8 +249,7 @@ def gnome_power_svc_disable(): # * update readme/docs @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_off", is_flag=True, help="Turn off Bluetooth on boot") def main( @@ -316,46 +259,18 @@ def main( bluetooth_boot_off, bluetooth_boot_on, ): - root_check() - if len(sys.argv) == 1: - header() - print( - 'Unrecognized option!\n\nRun: "' + app_name + ' --help" for list of available options.' - ) - footer() + header() + + if len(sys.argv) == 1: print('Unrecognized option!\n\nRun: "' + app_name + ' --help" for list of available options.') else: - if gnome_power_enable: - header() - root_check() - gnome_power_svc_enable() - helper_opts() - 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() - footer() - - -if __name__ == "__main__": - main() \ No newline at end of file + if gnome_power_enable: gnome_power_svc_enable() + elif gnome_power_disable: gnome_power_svc_disable() + elif gnome_power_status: gnome_power_svc_status() + elif bluetooth_boot_off: bluetooth_disable() + elif bluetooth_boot_on: bluetooth_enable() + helper_opts() + + footer() + +if __name__ == "__main__": main() \ No newline at end of file diff --git a/auto_cpufreq/tlp_stat_parser.py b/auto_cpufreq/tlp_stat_parser.py index 003ac2c6..8b3a782a 100644 --- a/auto_cpufreq/tlp_stat_parser.py +++ b/auto_cpufreq/tlp_stat_parser.py @@ -6,14 +6,8 @@ def __init__(self, tlp_stat_output): def _parse(self, data): for line in data.split("\n"): key_val = line.split("=", 1) - if len(key_val) > 1: - self.data[key_val[0].strip().lower()] = key_val[1].strip() + if len(key_val) > 1: self.data[key_val[0].strip().lower()] = key_val[1].strip() - def _get_key(self, key): - if key in self.data: - return self.data[key] - else: - return "" + def _get_key(self, key): return self.data[key] if key in self.data else "" - def is_enabled(self): - return self._get_key("state") == "enabled" + def is_enabled(self): return self._get_key("state") == "enabled" diff --git a/auto_cpufreq/utils/config.py b/auto_cpufreq/utils/config.py index 650049a8..ff673a3b 100644 --- a/auto_cpufreq/utils/config.py +++ b/auto_cpufreq/utils/config.py @@ -17,31 +17,28 @@ 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 :return: The path to the config file to use """ - # Prepare paths # use $SUDO_USER or $USER to get home dir since sudo can't access # user env vars home = run(["getent passwd ${SUDO_USER:-$USER} | cut -d: -f6"], - shell=True, - stdout=PIPE, - universal_newlines=True).stdout.rstrip() + shell=True, + stdout=PIPE, + universal_newlines=True + ).stdout.rstrip() 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") 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 - if os.path.isfile(args_config_file): - return args_config_file + if os.path.isfile(args_config_file): return args_config_file else: # Not a valid file print(f"Config file specified with '--config {args_config_file}' not found.") sys.exit(1) - elif os.path.isfile(user_config_file): # (2) User config file - return user_config_file - else: # (3) System config file (default if nothing else is found) - return system_config_file + elif os.path.isfile(user_config_file): return user_config_file # (2) User config file + else: return system_config_file # (3) System config file (default if nothing else is found) class _Config: def __init__(self) -> None: @@ -51,17 +48,13 @@ def __init__(self) -> None: self.config_handler = ConfigEventHandler(self) # check for file changes using threading - self.notifier: pyinotify.ThreadedNotifier = pyinotify.ThreadedNotifier( - self.watch_manager, self.config_handler) + self.notifier: pyinotify.ThreadedNotifier = pyinotify.ThreadedNotifier(self.watch_manager, self.config_handler) def set_path(self, path: str) -> None: - self.path = path; - mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY \ - | pyinotify.IN_MOVED_FROM | pyinotify.IN_MOVED_TO + self.path = path + mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY | pyinotify.IN_MOVED_FROM | pyinotify.IN_MOVED_TO self.watch_manager.add_watch(os.path.dirname(path), mask=mask) - if os.path.isfile(path): - self.update_config() - + if os.path.isfile(path): self.update_config() def has_config(self) -> bool: return os.path.isfile(self.path) @@ -72,9 +65,7 @@ def get_config(self) -> ConfigParser: def update_config(self) -> None: # create new ConfigParser to prevent old data from remaining self._config = ConfigParser() - try: - self._config.read(self.path) - except ParsingError as e: - print(f"The following error occured while parsing the config file: \n{e}") + try: self._config.read(self.path) + except ParsingError as e: print(f"The following error occured while parsing the config file: \n{e}") config = _Config() \ No newline at end of file diff --git a/scripts/auto-cpufreq-install.sh b/scripts/auto-cpufreq-install.sh index 33e90dee..faab46ac 100755 --- a/scripts/auto-cpufreq-install.sh +++ b/scripts/auto-cpufreq-install.sh @@ -3,103 +3,94 @@ # auto-cpufreq daemon install script # reference: https://github.com/AdnanHodzic/auto-cpufreq # Thanks to https://github.com/errornonamer for openrc fix -echo -e "\n------------------ Running auto-cpufreq daemon install script ------------------" -if [[ $EUID != 0 ]]; -then - echo -e "\nERROR\nMust be run as root (i.e: 'sudo $0')\n" - exit 1 -fi +MID="$((`tput cols` / 2))" -# First argument is the "sv" path, second argument is the "service" path this -# only exist because the path between distros may vary -runit_ln() { - echo -e "\n* Deploy auto-cpufreq runit unit file" - mkdir "$1"/sv/auto-cpufreq - cp /usr/local/share/auto-cpufreq/scripts/auto-cpufreq-runit "$1"/sv/auto-cpufreq/run - chmod +x "$1"/sv/auto-cpufreq/run +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 - echo -e "\n* Creating symbolic link ($2/service/auto-cpufreq -> $1/sv/auto-cpufreq)" - ln -s "$1"/sv/auto-cpufreq "$2"/service -} +# root check +if ((EUID != 0)); then + echo; echo "Must be run as root (i.e: 'sudo $0')."; echo + exit 1 +fi -# sv commands -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 up auto-cpufreq +# First argument is the init name, second argument is the start command, third argument is the enable command +function auto_cpufreq_install { + echo -e "\n* Starting auto-cpufreq daemon ($1) service" + $2 + echo -e "\n* Enabling auto-cpufreq daemon ($1) at boot" + $3 } -# 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 - eval "$(cat /etc/os-release)" - case $ID in - void) - runit_ln /etc /var - 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* Please open an issue on https://github.com/AdnanHodzic/auto-cpufreq\n" - esac - fi -# Install script for systemd -elif [ "$(ps h -o comm 1)" = "systemd" ];then - echo -e "\n* Deploy auto-cpufreq systemd unit file" - cp /usr/local/share/auto-cpufreq/scripts/auto-cpufreq.service /etc/systemd/system/auto-cpufreq.service +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 - echo -e "\n* Reloading systemd manager configuration" - systemctl daemon-reload + 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 - echo -e "\n* Stopping auto-cpufreq daemon (systemd) service" - systemctl stop 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 + cp /usr/local/share/auto-cpufreq/scripts/auto-cpufreq-runit "$1"/sv/auto-cpufreq/run + chmod +x "$1"/sv/auto-cpufreq/run - echo -e "\n* Starting auto-cpufreq daemon (systemd) service" - systemctl start auto-cpufreq + echo -e "\n* Creating symbolic link ($2/service/auto-cpufreq -> $1/sv/auto-cpufreq)" + ln -s "$1"/sv/auto-cpufreq "$2"/service - 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 + auto_cpufreq_install "runit" - echo -e "Starting auto-cpufreq daemon (openrc) service" - rc-service auto-cpufreq start + sv start auto-cpufreq + sv up auto-cpufreq + } + + if [ -f /etc/os-release ];then + ./etc/os-release + case $ID in + void) runit_ln /etc /var;; + artix) runit_ln /etc/runit /run/runit;; + *) + 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" + esac + fi + ;; + systemd) + 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 - 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" + echo -e "\n* Reloading systemd manager configuration" + systemctl daemon-reload + + auto_cpufreq_install "systemd" "systemctl start auto-cpufreq" "systemctl enable auto-cpufreq" + ;; + s6-svscan) + 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 + echo -e "\n* Add auto-cpufreq service (s6) to default bundle" 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)" 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* Please open an issue on https://github.com/AdnanHodzic/auto-cpufreq\n" -fi + ;; + *) + 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" + ;; +esac diff --git a/scripts/auto-cpufreq-remove.sh b/scripts/auto-cpufreq-remove.sh index 8666b096..8c1f83a5 100755 --- a/scripts/auto-cpufreq-remove.sh +++ b/scripts/auto-cpufreq-remove.sh @@ -4,83 +4,68 @@ # reference: https://github.com/AdnanHodzic/auto-cpufreq # 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 -e "\nERROR\nMust be run as root (i.e: 'sudo $0')\n" - exit 1 -fi +echo +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 -# First argument is the "sv" path, second argument is the "service" path -rm_sv() { - echo -e "\n* Stopping auto-cpufreq daemon (runit) service" - sv stop auto-cpufreq +# root check +if ((EUID != 0)); then + echo; echo "Must be run as root (i.e: 'sudo $0')."; echo + exit 1 +fi - echo -e "\n* Removing auto-cpufreq daemon (runit) unit files" - rm -rf "$1"/sv/auto-cpufreq - rm -rf "$2"/service/auto-cpufreq +# 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 +function auto_cpufreq_remove { + echo -e "\n* Stopping auto-cpufreq daemon ($1) service" + $2 + echo -e "\n* Disabling auto-cpufreq daemon ($1) at boot" + $3 + echo -e "\n* Removing auto-cpufreq daemon ($1) unit file" + rm $4 } -# Remove service for runit -if [ "$(ps h -o comm 1)" = "runit" ];then - if [ -f /etc/os-release ];then - eval "$(cat /etc/os-release)" - case $ID in - void) - rm_sv /etc /var ;; - artix) - rm_sv /etc/runit /run/runit ;; - *) - 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" - - esac - fi -# Remove service for systemd -elif [ "$(ps h -o comm 1)" = "systemd" ];then - echo -e "\n* Stopping auto-cpufreq daemon (systemd) service" - systemctl stop auto-cpufreq +case "$(ps h -o comm 1)" in + dinit) auto_cpufreq_remove "dinit" "dinitctl stop auto-cpufreq" "dinitctl disable auto-cpufreq" "/etc/dinit.d/auto-cpufreq";; + init) auto_cpufreq_remove "openrc" "rc-service auto-cpufreq stop" "rc-update del auto-cpufreq" "/etc/init.d/auto-cpufreq";; + 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" + } - 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 + if [ -f /etc/os-release ]; then + . /etc/os-release + case $ID in + void) rm_sv /etc /var;; + artix) rm_sv /etc/runit /run/runit;; + *) + 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" + ;; + esac + fi + ;; + systemd) + auto_cpufreq_remove "systemd" "systemctl stop auto-cpufreq" "systemctl disable auto-cpufreq" "/etc/systemd/system/auto-cpufreq.service" echo -e "\n* Reloading systemd manager configuration" systemctl daemon-reload - echo -e "reset failed" + echo "reset failed" systemctl reset-failed -# Remove service for openrc -elif [ "$(ps h -o comm 1)" = "init" ];then - echo -e "\n* Stopping auto-cpufreq daemon (openrc) service" - 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 + ;; + s6-svscan) + auto_cpufreq_remove "s6" "" "s6-service delete default auto-cpufreq" "-rf /etc/s6/sv/auto-cpufreq" + echo -e "\n* Update daemon service bundle (s6)" - s6-db-reload -# Remove service for dinit -elif [ "$(ps h -o comm 1)" = "init" ];then - echo -e "\n* Stopping auto-cpufreq daemon (dinit) service" - 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" -fi + s6-db-reload + ;; + *) + echo -e "\n* Unsupported init system detected, could not remove the daemon" + echo -e "\n* Please open an issue on https://github.com/AdnanHodzic/auto-cpufreq\n" + ;; +esac diff --git a/scripts/auto-cpufreq-venv-wrapper b/scripts/auto-cpufreq-venv-wrapper index c3b85961..7fdc478d 100644 --- a/scripts/auto-cpufreq-venv-wrapper +++ b/scripts/auto-cpufreq-venv-wrapper @@ -16,18 +16,17 @@ err_exit() # invocation handling # - # load python virtual environment venv_dir=/opt/auto-cpufreq/venv -. "${venv_dir}/bin/activate" +. "$venv_dir/bin/activate" # run python code with venv loaded -if [[ "${#}" -ne 1 ]]; then +if [[ "$#" -ne 1 ]]; then PYTHONPATH=/opt/auto-cpufreq \ /opt/auto-cpufreq/venv/bin/python \ /opt/auto-cpufreq/venv/bin/auto-cpufreq else - param="${1}" + param="$1" PYTHONPATH=/opt/auto-cpufreq \ /opt/auto-cpufreq/venv/bin/python \ /opt/auto-cpufreq/venv/bin/auto-cpufreq \ diff --git a/scripts/cpufreqctl.sh b/scripts/cpufreqctl.sh index 67040890..363ff2fd 100755 --- a/scripts/cpufreqctl.sh +++ b/scripts/cpufreqctl.sh @@ -1,99 +1,93 @@ #!/usr/bin/env bash VERSION='20' -cpucount=`cat /proc/cpuinfo|grep processor|wc -l` +cpucount=`cat /proc/cpuinfo | grep processor | wc -l` FLROOT=/sys/devices/system/cpu DRIVER=auto VERBOSE=0 ## parse special options -for i in "$@" -do -case $i in - -v|--verbose) - VERBOSE=1 - shift - ;; - --set=*) - VALUE="${i#*=}" - shift - ;; - -c=*|--core=*) - CORE="${i#*=}" - shift - ;; - --available) - AVAILABLE=1 - shift - ;; - -*) - OPTION=$i - shift - ;; - *) # unknown - ;; -esac +for i in "$@"; do + case $i in + -v|--verbose) + VERBOSE=1 + shift + ;; + -s=*|--set=*) + VALUE="${i#*=}" + shift + ;; + -c=*|--core=*) + CORE="${i#*=}" + shift + ;; + -a|--available) + AVAILABLE=1 + shift + ;; + -*) + OPTION=$i + shift + ;; + *) exit 1;; + esac done function help () { echo "Package version: "$VERSION - echo "Usage:" - echo " cpufreqctl [OPTION[=VALUE]...]" - echo "" - echo " --help Show help options" - echo " --version Package version" - echo " --verbose, -v Verbose output" - echo "" - echo " --set=VALUE Set VALUE for selected option" - echo " --core=NUMBER Apply selected option just for the core NUMBER (0 ~ N - 1)" - echo " --available Get available values instand of default: current" - echo "" - echo " --driver Current processor driver" - echo " --governor Scaling governor's options" - echo " --epp Governor's energy_performance_preference options" - echo " --frequency Frequency options" - echo " --on Turn on --core=NUMBER" - echo " --off Turn off --core=NUMBER" - echo " --frequency-min Minimal frequency options" - echo " --frequency-max Maximum frequency options" - echo " --frequency-min-limit Get minimal frequency limit" - echo " --frequency-max-limit Get maximum frequency limit" - echo " --boost Current cpu boost value" - echo "" + echo "Usage: cpufreqctl [OPTION[=VALUE]...]" + echo + echo " -h, --help Show help options" + echo " --version Package version" + echo " -v, --verbose Verbose output" + echo + echo " -s, --set =VALUE Set VALUE for selected option" + echo " -c, --core =NUMBER Apply selected option just for the core NUMBER (0 ~ N - 1)" + echo " -a, --available Get available values instand of default: current" + echo + echo " -d, --driver Current processor driver" + echo " -g, --governor Scaling governor's options" + echo " -e, --epp Governor's energy_performance_preference options" + echo " -f, --frequency Frequency options" + echo " --on Turn on --core=NUMBER" + echo " --off Turn off --core=NUMBER" + echo " --frequency-min Minimal frequency options" + echo " --frequency-max Maximum frequency options" + echo " --frequency-min-limit Get minimal frequency limit" + echo " --frequency-max-limit Get maximum frequency limit" + echo " -b, --boost Current cpu boost value" + echo echo "intel_pstate options" - echo " --no-turbo Current no_turbo value" - echo " --min-perf Current min_perf_pct options" - echo " --max-perf Current max_perf_pct options" - echo "" + echo " --no-turbo Current no_turbo value" + echo " --min-perf Current min_perf_pct options" + echo " --max-perf Current max_perf_pct options" + echo echo "Events options" - echo " --throttle Get thermal throttle counter" - echo " --throttle-event Get kernel thermal throttle events counter" - echo " --irqbalance Get irqbalance presence" + echo " --throttle Get thermal throttle counter" + echo " --throttle-event Get kernel thermal throttle events counter" + echo " --irqbalance Get irqbalance presence" } function info () { echo "CPU driver: "`driver` - echo "Governors: "`cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors` - echo "Frequencies: "`cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies` - echo "" + echo "Governors: "`cat $FLROOT/cpu0/cpufreq/scaling_available_governors` + echo "Frequencies: "`cat $FLROOT/cpu0/cpufreq/scaling_available_frequencies` + echo echo "Usage:" echo "## list scaling governors:" echo "cpufreqctl --governor" - echo "" + echo echo "## Set all active cpu cores to the 'performance' scaling governor:" echo "cpufreqctl --governor --set=performance" - echo "" + echo echo "## Set 'performance' scaling governor for the selected core:" echo "cpufreqctl --governor --set=performance --core=0" - echo "" + echo echo "Use --help argument to see available options" } verbose () { - if [ $VERBOSE = 1 ] - then - echo $1 - fi + if [ $VERBOSE = 1 ]; then echo $1; fi } function driver () { @@ -101,9 +95,7 @@ function driver () { } function write_value () { - if [ -w $FLNM ]; then - echo $VALUE > $FLNM - fi + if [ -w $FLNM ]; then echo $VALUE > $FLNM; fi } function set_driver () { @@ -119,376 +111,267 @@ function get_governor () { then i=0 ag='' - while [ $i -ne $cpucount ] - do - if [ $i = 0 ] - then - ag=`cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor` - else - ag=$ag' '`cat /sys/devices/system/cpu/cpu$i/cpufreq/scaling_governor` + while [ $i -ne $cpucount ]; do + if [ $i = 0 ]; then ag=`cat $FLROOT/cpu0/cpufreq/scaling_governor` + else ag=$ag' '`cat $FLROOT/cpu$i/cpufreq/scaling_governor` fi i=`expr $i + 1` done echo $ag - else - cat /sys/devices/system/cpu/cpu$CORE/cpufreq/scaling_governor + else cat $FLROOT/cpu$CORE/cpufreq/scaling_governor fi } function set_governor () { - if [ -z $CORE ] - then + if [ -z $CORE ]; then i=0 - while [ $i -ne $cpucount ] - do + while [ $i -ne $cpucount ]; do FLNM="$FLROOT/cpu"$i"/cpufreq/scaling_governor" write_value i=`expr $i + 1` done - else - echo $VALUE > /sys/devices/system/cpu/cpu$CORE/cpufreq/scaling_governor + else echo $VALUE > $FLROOT/cpu$CORE/cpufreq/scaling_governor fi } function get_frequency () { - if [ -z $CORE ] - then + if [ -z $CORE ]; then i=0 V=0 - M=$(cat "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq") - while [ $i -ne $cpucount ] - do - V=$(cat "/sys/devices/system/cpu/cpu"$i"/cpufreq/scaling_cur_freq") - if [[ $V > $M ]] - then - M=$V - fi + M=$(cat "$FLROOT/cpu0/cpufreq/scaling_cur_freq") + while [ $i -ne $cpucount ]; do + V=$(cat "$FLROOT/cpu"$i"/cpufreq/scaling_cur_freq") + if [[ $V > $M ]]; then M=$V; fi i=`expr $i + 1` done echo "$M" - else - cat /sys/devices/system/cpu/cpu$CORE/cpufreq/scaling_cur_freq + else cat $FLROOT/cpu$CORE/cpufreq/scaling_cur_freq fi } function set_frequency () { set_driver - if [ $DRIVER = 'pstate'] - then + if [ $DRIVER = 'pstate' ]; then echo "Unavailable function for intel_pstate" return fi - if [ -z $CORE ] - then + if [ -z $CORE ]; then i=0 - while [ $i -ne $cpucount ] - do + while [ $i -ne $cpucount ]; do FLNM="$FLROOT/cpu"$i"/cpufreq/scaling_setspeed" write_value i=`expr $i + 1` done - else - echo $VALUE > /sys/devices/system/cpu/cpu$CORE/cpufreq/scaling_setspeed + else echo $VALUE > $FLROOT/cpu$CORE/cpufreq/scaling_setspeed fi } function get_frequency_min () { - if [ -z $CORE ] - then - CORE=0 - fi - cat /sys/devices/system/cpu/cpu$CORE/cpufreq/scaling_min_freq + if [ -z $CORE ]; then CORE=0; fi + cat $FLROOT/cpu$CORE/cpufreq/scaling_min_freq } function set_frequency_min () { - if [ -z $CORE ] - then + if [ -z $CORE ]; then i=0 - while [ $i -ne $cpucount ] - do + while [ $i -ne $cpucount ]; do FLNM="$FLROOT/cpu"$i"/cpufreq/scaling_min_freq" write_value i=`expr $i + 1` done - else - echo $VALUE > /sys/devices/system/cpu/cpu$CORE/cpufreq/scaling_min_freq + else echo $VALUE > $FLROOT/cpu$CORE/cpufreq/scaling_min_freq fi } function get_frequency_max () { - if [ -z $CORE ] - then - CORE=0 - fi - cat /sys/devices/system/cpu/cpu$CORE/cpufreq/scaling_max_freq + if [ -z $CORE ]; then CORE=0; fi + cat $FLROOT/cpu$CORE/cpufreq/scaling_max_freq } function set_frequency_max () { - if [ -z $CORE ] - then + if [ -z $CORE ]; then i=0 - while [ $i -ne $cpucount ] - do + while [ $i -ne $cpucount ]; do FLNM="$FLROOT/cpu"$i"/cpufreq/scaling_max_freq" write_value i=`expr $i + 1` done - else - echo $VALUE > /sys/devices/system/cpu/cpu$CORE/cpufreq/scaling_max_freq + else echo $VALUE > $FLROOT/cpu$CORE/cpufreq/scaling_max_freq fi } function get_frequency_min_limit () { - if [ -z $CORE ] - then - CORE=0 - fi - cat /sys/devices/system/cpu/cpu$CORE/cpufreq/cpuinfo_min_freq + if [ -z $CORE ]; then CORE=0; fi + cat $FLROOT/cpu$CORE/cpufreq/cpuinfo_min_freq } function get_frequency_max_limit () { - if [ -z $CORE ] - then - CORE=0 - fi - cat /sys/devices/system/cpu/cpu$CORE/cpufreq/cpuinfo_max_freq + if [ -z $CORE ]; then CORE=0; fi + cat $FLROOT/cpu$CORE/cpufreq/cpuinfo_max_freq } function get_energy_performance_preference () { - if [ -z $CORE ] - then + if [ -z $CORE ]; then i=0 ag='' - while [ $i -ne $cpucount ] - do - if [ $i = 0 ] - then - ag=`cat /sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference` + while [ $i -ne $cpucount ]; do + if [ $i = 0 ]; then + ag=`cat $FLROOT/cpu0/cpufreq/energy_performance_preference` 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 i=`expr $i + 1` done echo $ag - else - cat /sys/devices/system/cpu/cpu$CORE/cpufreq/energy_performance_preference + else cat $FLROOT/cpu$CORE/cpufreq/energy_performance_preference fi } function set_energy_performance_preference () { - if [ -z $CORE ] - then + if [ -z $CORE ]; then i=0 - while [ $i -ne $cpucount ] - do + while [ $i -ne $cpucount ]; do FLNM="$FLROOT/cpu"$i"/cpufreq/energy_performance_preference" write_value i=`expr $i + 1` done - else - echo $VALUE > /sys/devices/system/cpu/cpu$CORE/cpufreq/energy_performance_preference + else echo $VALUE > $FLROOT/cpu$CORE/cpufreq/energy_performance_preference fi } -if [ -z $OPTION ] # No options -then - info - exit -fi -if [ $OPTION = "--help" ] -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" - get_governor - else - verbose "Setting CPU"$CORE" governors to "$VALUE - set_governor - fi - exit -fi -if [ $OPTION = "--epp" ] -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" - get_energy_performance_preference - else - verbose "Setting CPU"$CORE" EPPs to "$VALUE - set_energy_performance_preference - fi - exit -fi -if [ $OPTION = "--frequency" ] -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" - get_frequency - else - verbose "Setting CPU"$CORE" frequency to "$VALUE - set_frequency - fi - exit -fi -if [ $OPTION = "--no-turbo" ] -then - if [ -z $VALUE ] - then - verbose "Getting no_turbo value" - cat /sys/devices/system/cpu/intel_pstate/no_turbo - else - verbose "Setting no_turbo value "$VALUE - echo $VALUE > /sys/devices/system/cpu/intel_pstate/no_turbo - fi - exit -fi -if [ $OPTION = "--boost" ] -then - if [ -z $VALUE ] - then - verbose "Getting boost value" - cat /sys/devices/system/cpu/cpufreq/boost - else - verbose "Setting boost value "$VALUE - echo $VALUE > /sys/devices/system/cpu/cpufreq/boost - fi - exit -fi -if [ $OPTION = "--frequency-min" ] -then - if [ -z $VALUE ] - then - verbose "Getting CPU"$CORE" minimal frequency" - get_frequency_min - else - verbose "Setting CPU"$CORE" minimal frequency to "$VALUE - set_frequency_min - fi - exit -fi -if [ $OPTION = "--frequency-max" ] -then - if [ -z $VALUE ] - then - verbose "Getting CPU"$CORE" maximal frequency" - get_frequency_max - else - verbose "Setting CPU"$CORE" maximal frequency to "$VALUE - set_frequency_max - fi - exit -fi -if [ $OPTION = "--frequency-min-limit" ] -then +case $OPTION in + -h|--help) help;; + --version) echo $VERSION;; + -d|--driver) driver;; + -g|--governor) + if [ ! -z $AVAILABLE ]; then cat $FLROOT/cpu0/cpufreq/scaling_available_governors + elif [ -z $VALUE ]; then + verbose "Getting CPU"$CORE" governors" + get_governor + else + verbose "Setting CPU"$CORE" governors to "$VALUE + set_governor + fi + ;; + -e|--epp) + if [ ! -z $AVAILABLE ]; then cat $FLROOT/cpu0/cpufreq/energy_performance_available_preferences + elif [ -z $VALUE ]; then + verbose "Getting CPU"$CORE" EPPs" + get_energy_performance_preference + else + verbose "Setting CPU"$CORE" EPPs to "$VALUE + set_energy_performance_preference + fi + ;; + -f|--frequency) + if [ ! -z $AVAILABLE ]; then cat $FLROOT/cpu0/cpufreq/scaling_available_frequencies + elif [ -z $VALUE ]; then + verbose "Getting CPU"$CORE" frequency" + get_frequency + else + verbose "Setting CPU"$CORE" frequency to "$VALUE + set_frequency + fi + ;; + --no-turbo) + if [ -z $VALUE ]; then + verbose "Getting no_turbo value" + cat $FLROOT/intel_pstate/no_turbo + else + verbose "Setting no_turbo value "$VALUE + echo $VALUE > $FLROOT/intel_pstate/no_turbo + fi + ;; + -b|--boost) + if [ -z $VALUE ]; then + verbose "Getting boost value" + cat $FLROOT/cpufreq/boost + else + verbose "Setting boost value "$VALUE + echo $VALUE > $FLROOT/cpufreq/boost + fi + ;; + --frequency-min) + if [ -z $VALUE ]; then + verbose "Getting CPU"$CORE" minimal frequency" + get_frequency_min + else + verbose "Setting CPU"$CORE" minimal frequency to "$VALUE + set_frequency_min + fi + ;; + --frequency-max) + if [ -z $VALUE ]; then + verbose "Getting CPU"$CORE" maximal frequency" + get_frequency_max + else + verbose "Setting CPU"$CORE" maximal frequency to "$VALUE + set_frequency_max + fi + ;; + --frequency-min-limit) verbose "Getting CPU"$CORE" minimal frequency limit" get_frequency_min_limit -fi -if [ $OPTION = "--frequency-max-limit" ] -then + ;; + --frequency-max-limit) verbose "Getting CPU"$CORE" maximum frequency limit" get_frequency_max_limit -fi -if [ $OPTION = "--min-perf" ] -then - if [ -z $VALUE ] - then - verbose "Getting min_perf_pct value" - cat /sys/devices/system/cpu/intel_pstate/min_perf_pct - else - verbose "Setting min_perf_pct value "$VALUE - echo $VALUE > /sys/devices/system/cpu/intel_pstate/min_perf_pct - fi - exit -fi -if [ $OPTION = "--max-perf" ] -then - if [ -z $VALUE ] - then - verbose "Getting max_perf_pct value" - cat /sys/devices/system/cpu/intel_pstate/max_perf_pct - else - verbose "Setting max_perf_pct value "$VALUE - echo $VALUE > /sys/devices/system/cpu/intel_pstate/max_perf_pct - fi - exit -fi -if [ $OPTION = "--on" ] -then - if [ -z $CORE ] - then - verbose "Should be specify --core=NUMBER" - else - verbose "Power on CPU Core"$CORE - echo "1" > $FLROOT/cpu"$CORE"/online - fi - exit -fi -if [ $OPTION = "--off" ] -then - if [ -z $CORE ] - then - verbose "Should be specify --core=NUMBER" - else - verbose "Power off CPU Core"$CORE - echo "0" > $FLROOT/cpu"$CORE"/online - fi - exit -fi + ;; + --min-perf) + if [ -z $VALUE ]; then + verbose "Getting min_perf_pct value" + cat $FLROOT/intel_pstate/min_perf_pct + else + verbose "Setting min_perf_pct value "$VALUE + echo $VALUE > $FLROOT/intel_pstate/min_perf_pct + fi + ;; + --max-perf) + if [ -z $VALUE ]; then + verbose "Getting max_perf_pct value" + cat $FLROOT/intel_pstate/max_perf_pct + else + verbose "Setting max_perf_pct value "$VALUE + echo $VALUE > $FLROOT/intel_pstate/max_perf_pct + fi + ;; + --on) + if [ -z $CORE ]; then verbose "Should be specify --core=NUMBER" + else + verbose "Power on CPU Core"$CORE + echo "1" > $FLROOT/cpu"$CORE"/online + fi + ;; + --off) + if [ -z $CORE ]; then verbose "Should be specify --core=NUMBER" + else + verbose "Power off CPU Core$CORE" + echo "0" > $FLROOT/cpu"$CORE"/online + fi + ;; + --throttle) + i=1 + V=0 + M=$(cat "$FLROOT/cpu0/thermal_throttle/core_throttle_count") + while [ $i -ne $cpucount ]; do + V=$(cat "$FLROOT/cpu$i/thermal_throttle/core_throttle_count") + M=`expr $M + $V` + i=`expr $i + 1` + done + echo "$M" + ;; + --throttle-events) + M=$(journalctl --dmesg --boot --since=yesterday | grep "cpu clock throttled" | wc -l) + echo "$M" + ;; + --irqbalance) + M=$(ps -A | grep irqbalance) + echo "$M" + ;; + *) + info + exit 1 + ;; +esac -if [ $OPTION = "--throttle" ] -then - i=1 - V=0 - M=$(cat "/sys/devices/system/cpu/cpu0/thermal_throttle/core_throttle_count") - while [ $i -ne $cpucount ] - do - V=$(cat "/sys/devices/system/cpu/cpu"$i"/thermal_throttle/core_throttle_count") - M=`expr $M + $V` - i=`expr $i + 1` - done - echo "$M" - exit -fi -if [ $OPTION = "--throttle-events" ] -then - M=$(journalctl --dmesg --boot --since=yesterday | grep "cpu clock throttled" | wc -l) - echo "$M" - exit -fi -if [ $OPTION = "--irqbalance" ] -then - M=$(ps -A |grep irqbalance) - echo "$M" - exit -fi +exit 0 diff --git a/scripts/start_app b/scripts/start_app index f942bbd9..2b5a9e25 100644 --- a/scripts/start_app +++ b/scripts/start_app @@ -2,17 +2,17 @@ # load python virtual environment venv_dir=/opt/auto-cpufreq/venv -. "${venv_dir}/bin/activate" -python_command="${venv_dir}/bin/auto-cpufreq-gtk" +. "$venv_dir/bin/activate" +python_command="$venv_dir/bin/auto-cpufreq-gtk" # if [ "$XDG_SESSION_TYPE" = "wayland" ] ; then # # necessary for running on wayland # xhost +SI:localuser:root -# pkexec ${python_command} +# pkexec $python_command # xhost -SI:localuser:root # xhost # else -# pkexec ${python_command} +# pkexec $python_command # fi -${python_command} \ No newline at end of file +$python_command \ No newline at end of file diff --git a/scripts/style.css b/scripts/style.css index e56f3cde..bbc4ac63 100644 --- a/scripts/style.css +++ b/scripts/style.css @@ -1,12 +1,8 @@ -label{ +label { /*font-family: Noto Sans;*/ font-size: 15px; } -#bold{ - font-weight: bold; -} +#bold { font-weight: bold; } -#small{ - font-size: 12px; -} +#small { font-size: 12px; }