summaryrefslogtreecommitdiff
path: root/armbian-envtemp-cpufreq.sh
blob: 4b88eddcb551ef756c2c45b6858ecf7d1574a28d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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."