aboutsummaryrefslogtreecommitdiff
path: root/sleepwalk
blob: 03e139d612c50c3c916c4a334d742e356897c92a (plain) (blame)
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
#! /bin/sh

set -eu

THRESHOLD=15.00

is_charging() {
        [ "$(cat /sys/class/power_supply/axp20x-usb/online)" = "1" ]
}

is_inhibitor_active() {
	#dbus-send --print-reply --dest=org.gnome.SessionManager /org/gnome/SessionManager org.gnome.SessionManager.GetInhibitors | tail -n+2 | grep object
        #INHIBITORS=$(sudo -u "$(cat /proc/$(pidof -s gnome-session-ctl)/environ | grep -z USER | sed 's,\x0,,;s,USER=,,')" DBUS_SESSION_BUS_ADDRESS=$(cat /proc/$(pidof -s gnome-session-ctl)/environ | grep -z DBUS_SESSION_BUS_ADDRESS | sed "s,\x0,,;s,DBUS_SESSION_BUS_ADDRESS=,,") gnome-session-inhibit --list)
        # printf "%s\n" "$INHIBITORS"
        INHIBITORS=$(systemd-inhibit --list --what=sleep --mode=block --no-legend \
               | grep -e 'sleep')

        [ -n "$INHIBITORS" ]
        # if [ "$INHIBITORS" = "No inhibitors" ]; then
        #       return 1
        # fi

        # return 0
}

is_screen_on() {
        return "$(cat /sys/class/backlight/backlight/bl_power)"
}

network_activity() {
        for n in $(seq 2)
        do
                for i in wwan0 wlan0
                do
                        A=$(ifstat -i $i 1 1 | tail -n1)
                        RX=$(echo $A | awk '{print $1}')
                        TX=$(echo $A | awk '{print $2}')

                        if [ "$RX" = "n/a" ] || [ "$TX" = "n/a" ]
                        then
                                return 1
                        fi

                        for v in $RX $TX
                        do
                                C=$(echo $v $THRESHOLD |
                                        awk '{if ($1 > $2) print "y"; else print "n"}')

                                if [ "$C" = "y" ]
                                then
					echo Ongoing network activity >&2
                                        return 0
                                fi
                        done
                done
        done

        return 1
}

bluetooth_connected() {
	test "$(bluetoothctl devices Connected)" != ""
	return
}

hotspot_active() {
	nmcli c show --active | grep -e 'Hotspot'
	return
}

can_suspend() {
	! ( is_inhibitor_active || is_screen_on || is_charging || bluetooth_connected|| hotspot_active || network_activity  )
}

cpufreq-set -g powersave

while :
do
	if can_suspend
	then
		(rtcwake -m no -s 600 && systemctl suspend) || :

		if can_suspend
		then
			sleep 30
		fi
	else
		sleep 5
	fi
done