71 lines
1.8 KiB
Bash
Executable File
71 lines
1.8 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
|
|
CACHE_FILE="/tmp/monitor-brightness-cache"
|
|
PID_FILE="/tmp/monitor-brightness-pid"
|
|
SCROLL_FILE="/tmp/monitor-brightness-scroll"
|
|
LOCK_FILE="/tmp/monitor-brightness-lock"
|
|
|
|
get_actual() {
|
|
# Prevent concurrent ddcutil calls
|
|
exec 9>"$LOCK_FILE"
|
|
flock -n 9 || { cat "$CACHE_FILE" 2>/dev/null || echo "50"; return; }
|
|
val=$(ddcutil getvcp 10 --display 1 2>/dev/null | grep -oP 'current value =\s*\K[0-9]+')
|
|
exec 9>&-
|
|
echo "$val"
|
|
}
|
|
|
|
# Initialize cache if missing
|
|
[ ! -f "$CACHE_FILE" ] && echo "50" > "$CACHE_FILE"
|
|
|
|
apply_brightness() {
|
|
local value=$1
|
|
[ -f "$PID_FILE" ] && kill "$(cat "$PID_FILE")" 2>/dev/null
|
|
(
|
|
echo $$ > "$PID_FILE"
|
|
sleep 0.3
|
|
exec 9>"$LOCK_FILE"
|
|
flock 9
|
|
ddcutil setvcp 10 "$value" --display 1 --noverify 2>/dev/null
|
|
exec 9>&-
|
|
rm -f "$PID_FILE"
|
|
) &
|
|
}
|
|
|
|
case "$1" in
|
|
get)
|
|
# If scrolled recently, use cache for instant feedback
|
|
if [ -f "$SCROLL_FILE" ]; then
|
|
age=$(( $(date +%s) - $(stat -c %Y "$SCROLL_FILE") ))
|
|
if [ "$age" -lt 3 ]; then
|
|
cat "$CACHE_FILE"
|
|
exit 0
|
|
fi
|
|
rm -f "$SCROLL_FILE"
|
|
fi
|
|
# Otherwise fetch actual value
|
|
val=$(get_actual)
|
|
if [ -n "$val" ]; then
|
|
echo "$val" > "$CACHE_FILE"
|
|
echo "$val"
|
|
else
|
|
cat "$CACHE_FILE"
|
|
fi
|
|
;;
|
|
up)
|
|
touch "$SCROLL_FILE"
|
|
current=$(cat "$CACHE_FILE")
|
|
new=$((current + 5))
|
|
[ "$new" -gt 100 ] && new=100
|
|
echo "$new" > "$CACHE_FILE"
|
|
apply_brightness "$new"
|
|
;;
|
|
down)
|
|
touch "$SCROLL_FILE"
|
|
current=$(cat "$CACHE_FILE")
|
|
new=$((current - 5))
|
|
[ "$new" -lt 0 ] && new=0
|
|
echo "$new" > "$CACHE_FILE"
|
|
apply_brightness "$new"
|
|
;;
|
|
esac
|