How can I play a sound when Caps Lock is toggled in Hyprland?

0
0
Asked By MellowPine42 On

I recently switched from Linux Mint to CachyOS with Hyprland and noticed that basic desktop conveniences, such as an audible indicator for Caps Lock, are not configured by default. I wrote a Bash script that watches /sys/class/leds/*::capslock/brightness every 20 milliseconds and runs pw-play when the value changes. However, the script sometimes causes very high CPU usage, forcing me to reboot. What is a better way to detect Caps Lock changes and play different sounds for turning it on and off?

3 Answers

Answered By QuartzHarbor7 On

The main issue is the tight polling loop. It repeatedly starts external commands and reads from sysfs 50 times per second, which is wasteful. If you keep this approach, use a Bash array instead of parsing ls, use Bash's read builtin instead of cat, and consider a longer sleep interval. Even better, trigger the sound from the actual keyboard event instead of polling the LED file. Also make sure the sound command is not being launched repeatedly by a loop that fails to detect or update the state correctly.

NimbleCedar18 -

Exactly. Polling should be a fallback rather than the first choice; an event-driven solution avoids unnecessary CPU usage and responds just as quickly.

Answered By BrightMango29 On

Another event-based option is to read the raw keyboard event device with od. Keyboard events are fixed-size structures, and the event type and code fields can be checked for EV_LED and LED_CAPSL. When a matching event arrives, the value field tells you whether Caps Lock is on or off. This avoids repeatedly reading the sysfs brightness file, but you need to identify the correct keyboard device and account for systems with multiple keyboards. Also remember that an LED state is not always guaranteed to represent the logical Caps Lock state in every hardware setup.

CobaltFern5 -

That distinction matters because keyboards can report or control their LEDs independently, and unplugging or adding another keyboard can change which device you are watching.

Answered By SilverKite63 On

You can monitor the keyboard's input event stream directly. Tools such as evtest can report LED changes, including LED_CAP, and then a shell pipeline can play one sound when the reported state is 1 and another when it is 0. For example, select a device under /dev/input/by-path/*-event-kbd, filter the LED_CAP events with awk, and pass each state to a loop that calls pw-play. This requires evtest and permission to read the input device, usually through membership in the input group or by running with suitable privileges.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.