summaryrefslogtreecommitdiff
path: root/power_control.sh
blob: 8e995bd83c3e3452c84506c6f51f32bc84543227 (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
#!/bin/sh

POWER_PATH="/proc/power"
NUM_OUTPUTS=$(find $POWER_PATH -name 'output*' | wc -l)

valid_output() {
	[ "$1" -gt "$NUM_OUTPUTS" ] && return 1
	[ "$1" -lt "1" ] && return 1
	return 0
}

check_output() {
	! valid_output $1 &&  error "Invalid output number"
}


error() {
	echo "{\"error\":\"$1\"}"
	exit 1
}

set_output() {
	echo $2 > $POWER_PATH/relay$1
}

clear_all() {
	for i in $(seq 1 $NUM_OUTPUTS); do
		echo 1 > $POWER_PATH/clear_ae$i
	done
}

report() {
	echo "["
	for i in $(seq 1 $NUM_OUTPUTS); do
		relay_state=$(cat $POWER_PATH/relay$i)
		if [ $relay_state -eq 1 ]; then
			state="true"
		else
			state="false"
		fi

		echo -e "\t{"
		echo -e "\t\t\"output\": $i,"
		echo -e "\t\t\"engaged\": $state,"
		echo -e "\t\t\"active_power\": $(cat $POWER_PATH/active_pwr$i),"
		echo -e "\t\t\"energy_sum\": $(cat $POWER_PATH/energy_sum$i),"
		echo -e "\t\t\"current_rms\": $(cat $POWER_PATH/i_rms$i),"
		echo -e "\t\t\"voltage_rms\": $(cat $POWER_PATH/v_rms$i),"
		echo -e "\t\t\"power_factor\": $(cat $POWER_PATH/pf$i)"

		if [ $i -eq $NUM_OUTPUTS ]; then
			echo -e "\t}"
		else
			echo -e "\t},"
		fi
	done
	echo "]"
}


case $1 in
	on)
		check_output $2
		set_output $2 1
		report
		;;
	off)
		check_output $2
		set_output $2 0
		report
		;;
	report)
		report
		;;
	clear)
		clear_all
		;;
	*)
		error "Invalid command"
		;;
esac