aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEvgeny Zinoviev <me@ch1p.io>2022-06-07 19:36:24 +0300
committerEvgeny Zinoviev <me@ch1p.io>2022-06-07 19:36:24 +0300
commit92d2d026ae198083108f23ba7529e12a7375b4ca (patch)
tree88134acdd6c6795e84cdcaad7427645a63e6f771
initial
-rw-r--r--README.md22
-rw-r--r--armbian-envtemp-cpufreq.sh106
2 files changed, 128 insertions, 0 deletions
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..6455b68
--- /dev/null
+++ b/README.md
@@ -0,0 +1,22 @@
+# armbian-envtemp-cpufreq
+
+Adjust maximum CPU frequency based on environment temperature.
+Works with [temphumd](https://git.ch1p.io/homekit.git/tree/src/temphumd.py) server.
+
+## Config example
+
+```
+# roof temphumd server
+192.168.1.2:8306
+
+# you can get available frequencies
+# from /sys/devices/system/cpu/cpufreq/policy0/scaling_available_frequencies
+
+# temp freq
+21 1800000
+24 1704000
+28 1608000
+32 1320000
+36 1080000
+40 888000
+```
diff --git a/armbian-envtemp-cpufreq.sh b/armbian-envtemp-cpufreq.sh
new file mode 100644
index 0000000..4b88edd
--- /dev/null
+++ b/armbian-envtemp-cpufreq.sh
@@ -0,0 +1,106 @@
+#!/bin/bash
+
+set -e
+
+PROGNAME="$0"
+
+config=
+temphumd_host=
+temphumd_port=
+
+declare -a values
+
+die() {
+ >&2 echo "error: $@"
+ exit 1
+}
+
+read_config() {
+ local config_file="$1"
+ local words
+ local temp
+ local freq
+ local line
+ local n
+
+ n=0
+ while read line; do
+ n=$(( n+1 ))
+
+ # skip empty lines or comments
+ if [ -z "$line" ] || [[ "$line" =~ ^#.* ]]; then
+ continue
+ fi
+
+ if [ -z "$temphumd_host" ] || [ -z "$temphumd_port" ]; then
+ temphumd_host=$(extract_ip "$line")
+ temphumd_port=$(extract_port "$line")
+ else
+ words=($line)
+
+ temp=${words[0]}
+ freq=${words[1]}
+
+ if [ -z "$temp" ] || [ -z "$freq" ]; then
+ die "config: line $n is invalid"
+ fi
+
+ values[$temp]=$freq
+ fi
+ done < <(cat "$config_file")
+}
+
+extract_ip() {
+ echo "$1" | sed -e 's/:.*$//g'
+}
+
+extract_port() {
+ echo "$1" | sed -e 's/^.*://g'
+}
+
+usage() {
+ cat <<-_EOF
+ usage: $PROGNAME [OPTIONS] COMMAND
+
+ Options:
+ -c|--config CONFIG
+
+ _EOF
+ exit 1
+}
+
+[[ $# -lt 1 ]] && usage
+
+while [[ $# -gt 0 ]]; do
+ case $1 in
+ -c|--config)
+ config="$2"
+ shift; shift
+ ;;
+
+ *)
+ die "unrecognized option $1"
+ exit 1
+ ;;
+ esac
+done
+
+[ -z "$config" ] && die "missing required -c or --config"
+
+read_config "$config"
+
+# reading temperature from temphumd server
+exec 3<>/dev/tcp/$temphumd_host/$temphumd_port
+echo -n "read" >&3
+read -t 5 response <&3
+
+envtemp=$(echo "$response" | jq ".temp" | awk "{print int(\$1+0.5)}")
+
+# setting corresponding cpu freq
+while read temp; do
+ freq=${values[$temp]}
+ (( envtemp >= temp )) && break
+done < <(for temp in ${!values[@]}; do echo $temp; done | sort -rn)
+
+echo -n "$freq" > /sys/devices/system/cpu/cpufreq/policy0/scaling_max_freq
+echo "Environment temperature is $envtemp C, set max CPU frequency to $freq."