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

* Clean code

* Back

* Clean code

* Back

* Clean code

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

View File

@ -5,110 +5,76 @@
cd "$(dirname "$(readlink -f "$0")")" || exit 1
# 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
echo
printf "%0.s─" $(seq $((MID-(${#1}/2)-2)))
printf " $1 "
printf "%0.s─" $(seq $((MID-(${#1}/2)-2)))
echo; echo
}
# 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
}
# 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.
if command -v lsb_release > /dev/null; then
distro="$(lsb_release -is)"
release="$(lsb_release -rs)"
codename="$(lsb_release -cs)"
fi
To complete installation, you need to:
Install: python3, pip3, python3-setuptools, gobject-introspection, cairo (or cairo-devel), gcc, and gtk3
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"
Install necessary Python packages:
pip3 install psutil click distro power requests PyGObject
Run following sequence of lines:
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
-----
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:
Distribution: $distro
Release: $release
Codename: $codename"
separator
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
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 $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
[ -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
# root check
if ((EUID != 0)); then
echo; echo "Must be run as root (i.e: 'sudo $0')."; echo
exit 1
fi
Select a key: [i/r/q]: " answer
}
# End of functions
root_check
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

View File

@ -5,41 +5,16 @@ from auto_cpufreq.battery_scripts.thinkpad import thinkpad_setup, thinkpad_print
from auto_cpufreq.battery_scripts.ideapad_acpi import ideapad_acpi_setup, ideapad_acpi_print_thresholds
from auto_cpufreq.battery_scripts.ideapad_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

View File

@ -3,62 +3,40 @@ import os
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")

View File

@ -3,47 +3,30 @@ import os
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 as e:
print(f"ERROR: failed to read battery thresholds: {e}")
except Exception as e: print(f"ERROR: failed to read battery {b} thresholds: {e}")

View File

@ -3,62 +3,41 @@ import os
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")

View File

@ -9,6 +9,7 @@ import sys
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 @@ from auto_cpufreq.utils.config import config as conf, find_config_file
@click.option("--stats", is_flag=True, help="View live stats of CPU optimizations made by daemon")
@click.option("--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")
@ -39,7 +35,6 @@ from auto_cpufreq.utils.config import config as conf, find_config_file
@click.option("--log", is_flag=True, hidden=True)
@click.option("--daemon", is_flag=True, hidden=True)
def main(config, daemon, debug, update, install, remove, live, log, monitor, stats, version, donate, force, get_state, completions):
# display info if config file is used
config_path = find_config_file(config)
conf.set_path(config_path)
@ -84,8 +79,7 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
sysinfo()
set_autofreq()
countdown(2)
except KeyboardInterrupt:
break;
except KeyboardInterrupt: break
conf.notifier.stop()
elif monitor:
config_info_dialog()
@ -111,8 +105,7 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
sysinfo()
mon_autofreq()
countdown(2)
except KeyboardInterrupt:
break
except KeyboardInterrupt: break
conf.notifier.stop()
elif live:
root_check()
@ -141,7 +134,7 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
countdown(2)
except KeyboardInterrupt:
gnome_power_start_live()
print("")
print()
break
conf.notifier.stop()
elif stats:
@ -156,8 +149,7 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
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 +163,14 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
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 +188,8 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
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 +197,14 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
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 +216,8 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
# {the following snippet also used in --update, update it there too(if required)}
# * 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 +229,7 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
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 +242,10 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
print("Arch-based distribution with AUR support detected. Please refresh auto-cpufreq using your AUR helper.")
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 +254,7 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
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 +267,6 @@ def main(config, daemon, debug, update, install, remove, live, log, monitor, sta
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()

View File

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

View File

@ -143,7 +143,7 @@ def app_version():
if os.getenv("PKG_MARKER") == "SNAP":
print(getoutput(r"echo \(Snap\) $SNAP_VERSION"))
# aur package
elif dist_name in ["arch", "manjaro", "garuda"]:
elif os.path.exists("/etc/arch-release"):
aur_pkg_check = call("pacman -Qs auto-cpufreq > /dev/null", shell=True)
if aur_pkg_check == 1:
print(get_formatted_version())
@ -1308,7 +1308,7 @@ def sysinfo():
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
@ -1346,7 +1346,7 @@ def is_running(program, argument):
# and find the one with name and args passed to the function
for p in psutil.process_iter():
try:
cmd = p.cmdline();
cmd = p.cmdline()
except:
continue
for s in filter(lambda x: program in x, cmd):
@ -1384,4 +1384,4 @@ def not_running_daemon_check():
exit(1)
elif os.getenv("PKG_MARKER") == "SNAP" and dcheck == "disabled":
daemon_not_running_msg()
exit(1)
exit(1)

View File

@ -26,7 +26,6 @@ else:
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 @@ class ToolWindow(Gtk.Window):
self.build()
def main(self):
# Main HBOX
self.hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=HBOX_PADDING)
@ -61,7 +59,6 @@ class ToolWindow(Gtk.Window):
self.hbox.pack_start(self.vbox_right, False, False, 0)
GLib.timeout_add_seconds(5, self.refresh_in_thread)
def snap(self):
@ -81,15 +78,12 @@ class ToolWindow(Gtk.Window):
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 @@ class ToolWindow(Gtk.Window):
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()

View File

@ -17,38 +17,28 @@ from io import StringIO
PKEXEC_ERROR = "Error executing command as another user: Not authorized\n\nThis incident has been reported.\n"
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 @@ class RadioButtonView(Gtk.Box):
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 @@ class RadioButtonView(Gtk.Box):
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 @@ class CurrentGovernorBox(Gtk.Box):
class SystemStatsLabel(Gtk.Label):
def __init__(self):
super().__init__()
self.refresh()
def refresh(self):
@ -130,7 +111,6 @@ class SystemStatsLabel(Gtk.Label):
self.set_label(text.getvalue())
sys.stdout = old_stdout
class CPUFreqStatsLabel(Gtk.Label):
def __init__(self):
super().__init__()
@ -188,8 +168,7 @@ class DropDownMenu(Gtk.MenuButton):
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 @@ class DropDownMenu(Gtk.MenuButton):
dialog.run()
dialog.destroy()
class AboutDialog(Gtk.Dialog):
def __init__(self, parent):
super().__init__(title="About", transient_for=parent)
@ -221,10 +199,11 @@ class AboutDialog(Gtk.Dialog):
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 @@ class UpdateDialog(Gtk.Dialog):
self.show_all()
class ConfirmDialog(Gtk.Dialog):
def __init__(self, parent, message: str):
super().__init__(title="Confirmation", transient_for=parent)
@ -290,8 +268,7 @@ class DaemonNotRunningView(Gtk.Box):
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())

View File

@ -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()
if __name__ == "__main__": main()

View File

@ -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.core import *
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 @@ powerprofilesctl_exists = does_command_exists("powerprofilesctl")
# 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 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()
if __name__ == "__main__": main()

View File

@ -6,14 +6,8 @@ class TLPStatusParser:
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"

View File

@ -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 @@ class _Config:
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 @@ class _Config:
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()

View File

@ -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
MID="$((`tput cols` / 2))"
echo
printf "%0.s─" $(seq $((MID-(${#1}/2)-2)))
printf " Running auto-cpufreq daemon install script "
printf "%0.s─" $(seq $((MID-(${#1}/2)-2)))
echo; echo
# root check
if ((EUID != 0)); then
echo; echo "Must be run as root (i.e: 'sudo $0')."; echo
exit 1
fi
# 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 -e "\n* Creating symbolic link ($2/service/auto-cpufreq -> $1/sv/auto-cpufreq)"
ln -s "$1"/sv/auto-cpufreq "$2"/service
# 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
}
# 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
}
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
# 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"
auto_cpufreq_install "dinit" "dinitctl start auto-cpufreq" "dinitctl enable auto-cpufreq"
;;
init)
echo -e "\n* Deploying auto-cpufreq openrc unit file"
cp /usr/local/share/auto-cpufreq/scripts/auto-cpufreq-openrc /etc/init.d/auto-cpufreq
chmod +x /etc/init.d/auto-cpufreq
auto_cpufreq_install "openrc" "rc-service auto-cpufreq start" "rc-update add auto-cpufreq"
;;
runit)
# First argument is the "sv" path, second argument is the "service" path
runit_ln() {
echo -e "\n* Deploying auto-cpufreq (runit) unit file"
mkdir "$1"/sv/auto-cpufreq
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* Creating symbolic link ($2/service/auto-cpufreq -> $1/sv/auto-cpufreq)"
ln -s "$1"/sv/auto-cpufreq "$2"/service
auto_cpufreq_install "runit"
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* Reloading systemd manager configuration"
systemctl daemon-reload
echo -e "\n* Stopping auto-cpufreq daemon (systemd) service"
systemctl stop auto-cpufreq
echo -e "\n* Starting auto-cpufreq daemon (systemd) service"
systemctl start auto-cpufreq
echo -e "\n* Enabling auto-cpufreq daemon (systemd) service at boot"
systemctl enable auto-cpufreq
# Install script for openrc
elif [ "$(ps h -o comm 1)" = "init" ];then
echo -e "\n* Deploying auto-cpufreq openrc unit file"
cp /usr/local/share/auto-cpufreq/scripts/auto-cpufreq-openrc /etc/init.d/auto-cpufreq
chmod +x /etc/init.d/auto-cpufreq
echo -e "Starting auto-cpufreq daemon (openrc) service"
rc-service auto-cpufreq start
echo -e "\n* Enabling auto-cpufreq daemon (openrc) service at boot"
rc-update add auto-cpufreq
# Install script for s6
elif [ "$(ps h -o comm 1)" = "s6-svscan" ];then
echo -e "\n* Deploying auto-cpufreq s6 unit file"
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

View File

@ -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
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
# root check
if ((EUID != 0)); then
echo; echo "Must be run as root (i.e: 'sudo $0')."; echo
exit 1
fi
# 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
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"
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"
}
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
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

View File

@ -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 \

View File

@ -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

View File

@ -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}
$python_command

View File

@ -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; }