summaryrefslogtreecommitdiff
path: root/power_control.sh
blob: a3d9d88d23982ab6df4335d945e3eb384907aa81 (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
107
108
109
#!/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
		set -- $(cat "/dev/power$i")

		# Convert to JSON booleans
		state="false"; [ "$1" = "on" ] && state="true"

		echo -e "\t{"
		echo -e "\t\t\"output\": $i,"
		echo -e "\t\t\"engaged\": $state,"
		echo -e "\t\t\"active_power\": $2,"
		echo -e "\t\t\"energy_sum\": $6,"
		echo -e "\t\t\"current_rms\": $3,"
		echo -e "\t\t\"voltage_rms\": $4,"
		echo -e "\t\t\"power_factor\": $5"
		echo -en "\t}"

		[ $i -ne $NUM_OUTPUTS ] && echo -e ","
	done
	echo "]"
}

disable_junk_processes() {
    # Otherwise init will continue to respawn them
    sed -i \
        -e '/ubnt-websockets/s/^/#/' \
        -e '/telnetd/s/^/#/' \
        -e '/mca[-d]/s/^/#/' \
        -e '/lighttpd/s/^/#/' \
        /etc/inittab

    kill -HUP 1

    # Most of these kill cleanly but a few are stubborn so don't ask, tell.
    pkill -9 ubnt-websockets
    pkill -9 lighttpd
    pkill upnpd
    pkill telnetd
    pkill mca-monitor
    pkill mcad
    pkill avahi-daemon
}

disable_blinking() {
    echo 0 > /proc/led/freq
    echo 1 > /proc/led/status
}

if ! grep -E '^#.*mcad$' /etc/inittab 2>&1 > /dev/null; then
    disable_junk_processes
    disable_blinking
fi

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
		;;
    disable_blinking)
        disable_blinking
        ;;
	*)
		error "Invalid command"
		;;
esac