aboutsummaryrefslogtreecommitdiff
path: root/rigel/.config/sway/ppd-switch.sh
blob: 4d2f496756ecaf2ebdbe96a1123c266ce02d1675 (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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#!/bin/bash
# ppd-switch.sh — auto-switch the power-profiles-daemon profile on AC↔battery.
#
# power-profiles-daemon deliberately has no "switch profile on power source"
# public policy (that's a session thing; DEs like GNOME/KDE do it). 0.30 adds
# internal battery/AC awareness (BatteryAware) — feed events into drivers and
# actions, e.g. intel_pstate switches *internally* — but nothing emits a
# user-decidable balanced↔power-saver-on-ac rule. Sway has no DE policy
# engine, so this script is the policy. Everything talks to the *system* bus
# (ppd + UPower), which means no session env is required — the supervisor can
# spawn it from a bare context.
#
# The equality gate means we never fight ppd's own native choices: if the
# daemon already sits on the state-correct profile, apply_profile no-ops.
#
# Policy (agreed 2026-10-31):
#   auto zone    {balanced, power-saver} — on every power transition it flips
#                to the state-correct profile: mains → balanced, battery →
#                power-saver (first message's mapping; the "balanced (AC)" win).
#   manual zone  {performance} — never touched, on ANY transition. Sticks
#                until the user changes it themselves (sway keybinds:
#                Ctrl+Alt+Shift+3). Setting balanced/power-saver by hand
#                re-enters auto, effective from the next transition: the
#                check below re-reads ActiveProfile at every event, so the
#                zone it lands in governs what happens next — no daemon state
#                to track, the profile *is* the zone.
#
# Events: the battery's UPower PropertiesChanged signals. They also fire on
# plain charge-level updates every ~30s; those are cheap no-ops thanks to the
# equality check in apply(), so no debounce bookkeeping beyond one short
# settle-sleep per event (the kernel isn't atomic about adapter/battery
# reveals).
#
# Supervisor: part of the daemons=() array in session-daemons.sh — singleton
# flock, crash-restart, session teardown, and stderr rolling into
# session-daemons.log. Name must be ≤15 chars (it is), because the
# supervisor resolves pids via /proc/*/comm which truncates at 15.

set -u

BUS="--system"
PPI="org.freedesktop.UPower.PowerProfiles"
PPIPATH="/org/freedesktop/UPower/PowerProfiles"
# The only battery on this machine (checked: BAT0 absent, BAT1 present).
BATTERY="/org/freedesktop/UPower/devices/battery_BAT1"

msg() { echo "$(date '+%F %T') [ppd-switch.sh] $*"; }

# --- D-Bus helpers — raw gdbus calls, no powerprofilesctl dependency -------
# (ppd 0.30: no SetProfile method on the interface; ActiveProfile is a
# readwrite property, Get/Set alongside every other property — verified by
# introspection and by flipping profiles live before writing this.)

profile_get() { # -> ActiveProfile on stdout
    gdbus call $BUS --dest "$PPI" --object-path "$PPIPATH" \
        --method org.freedesktop.DBus.Properties.Get "$PPI" ActiveProfile \
        | sed -n "s/^.*<'\([a-z][a-z-]*\)'>.*$/\1/p"   # <'balanced'> -> balanced
}

profile_set() { # $1 = profile; write is a variant "<'x'>"
    gdbus call $BUS --dest "$PPI" --object-path "$PPIPATH" \
        --method org.freedesktop.DBus.Properties.Set "$PPI" ActiveProfile \
        "<'$1'>" >/dev/null || msg "set ActiveProfile='$1' FAILED"
}

# --- power state ------------------------------------------------------------

# Any mains adapter online? Authored as a scan for type=Mains on purpose:
# the AC is ACAD but there are also four USB-C PD ports (ucsi-source-psy-*),
# and which one has the charger can vary by port.
mains_online() {
    local t online
    for d in /sys/class/power_supply/*/; do
        read -r t <"$d/type" 2>/dev/null || continue
        [ "$t" = Mains ] || continue
        read -r online <"$d/online" 2>/dev/null || continue
        [ "$online" = 1 ] && return 0
    done
    return 1
}

desired_profile() { # state-correct auto profile
    if mains_online; then echo balanced; else echo power-saver; fi
}

# --- the one decision -------------------------------------------------------

apply_profile() {
    local cur want
    # Manual zone: performance is sticky across every transition. If it's set,
    # decline entirely — including the startup one-shot.
    cur=$(profile_get)
    [ "$cur" = performance ] && return 0
    want=$(desired_profile)
    [ "$cur" = "$want" ] && return 0            # no-op: also absorbs the
                                                 # charge-update event noise
    msg "transition -> '$want' (was '$cur')"
    profile_set "$want"
}

# --- event loop ---------------------------------------------------------------

# Teardown: the supervisors TERM-kills the whole leftover stack, and our
# instance was setsid'd into its own process group (we are the group leader),
# so every child — gdbus monitor, the settle sleeps — shares the group. kill
# 0 takes them all out at once instead of leaving the monitor orphaned until
# its next battery write hits a closed pipe (SIGPIPE, ~30s later). Guard: if
# we are NOT the process-group leader (e.g. someone ran this interactively),
# kill 0 would take the caller's terminal pgrp with it — skip the group kill
# there and just exit.
cleanup() {
    # Clear the traps FIRST: leaving them active while kill 0 TERMs our own
    # group means this very shell re-enters the trap from its own group kill,
    # and the handler's exit 0 never wins the race (verified: unbounded trap
    # replay). Cleared, the self-TERM lands on default disposition and drops
    # the shell instantly — exactly probe2.sh's correct behaviour.
    trap - EXIT HUP INT TERM
    if [ "$(ps -o pgid= --no-headers -p $$ 2>/dev/null | tr -d '[:space:]')" = "$$" ]; then
        kill 0 2>/dev/null
    fi
    exit 0
}
trap cleanup EXIT HUP INT TERM

# Startup one-shot, zone-respecting: a performance pick from a previous
# session therefore also survives a full session restart. Failures here (e.g.
# ppd briefly not ready at login) are not fatal — the loop below converges on
# the first battery signal, and profiles only need one read/write.
apply_profile

while :; do
    # monitor only watches the battery device: its PropertiesChanged is the
    # trigger for "power config may have changed". If the monitor dies (bus
    # hiccup), the outer while restarts it; the supervisor's crash-restart
    # covers the script as a whole.
    # Coupling subtlety #1 — pipeline: `gdbus monitor | while read` seats the
    # main shell in do_wait on the pipeline and never services pending traps.
    # Subtlety #2 — read builtin: even with the reader as the main shell
    # (process substitution), bash defers pending traps until the read
    # *returns* (verified live: TERM was ignored for tens of seconds). The
    # pattern that works is reader-in-subshell + main shell waiting via
    # `wait $!`: wait-on-async runs deferred traps IMMEDIATELY, so the
    # supervisor's TERM -> our trap -> kill 0 teardown actually executes.
    # The reader owns no state; it is pure "event -> apply" code, so it needn't
    # handle a TERM itself — the group kill in cleanup covers it.
    reader() {
        while read -r; do
            apply_profile
            sleep 0.3   # settle: hot-trailing signals are gated in apply()
        done
    }
    reader < <(gdbus monitor $BUS --dest org.freedesktop.UPower --object-path "$BATTERY") &
    wait $!
    msg "monitor exited; restarting in 30s"
    # sleep is a builtin run to completion, and bash defers pending traps
    # until a builtin RETURNS (this file's history is one big proof of that) —
    # so the 30s restart backoff sleeps in 1s slices: a pending TERM never
    # waits longer than ~1s from here.
    for _ in $(seq 30); do
        sleep 1
    done
done