Skip to content

Instantly share code, notes, and snippets.

@chrillep
Forked from bahamas10/cec-keypresses.sh
Last active September 29, 2025 14:46
Show Gist options
  • Select an option

  • Save chrillep/1beb3714cadf8aa4e585271ea1c7ead1 to your computer and use it in GitHub Desktop.

Select an option

Save chrillep/1beb3714cadf8aa4e585271ea1c7ead1 to your computer and use it in GitHub Desktop.
use `cec-client` to fire events when keys are pressed
#!/usr/bin/env bash
#
# react to cec keypresses and inject Wayland key events via wtype
#
# Author: Dave Eddy <[email protected]>
# License: MIT
# Modified: dedup filter + wtype mapping
#
onright() {
echo 'right button pressed'
wtype -k Right
}
onleft() {
echo 'left button pressed'
wtype -k Left
}
ondown() {
echo 'down button pressed'
wtype -k Down
}
onup() {
echo 'up button pressed'
wtype -k Up
}
onselect() {
echo 'select button pressed'
wtype -k Return
}
onexit() {
echo 'exit button pressed'
wtype -k Escape
}
onplay() {
echo 'play button pressed'
wtype -k space
}
onpause() {
echo 'pause button pressed'
wtype -k space
}
onforward() {
echo 'forward button pressed'
wtype -k F
}
onbackward() {
echo 'backward button pressed'
wtype -k R
}
filter() {
perl -nle '
BEGIN { $|=1 }
if (/key pressed: (.*) \(/) {
$key=$1;
if ($key ne $last) {
print $key;
$last=$key;
}
}
if (/key released: (.*) \(/) {
$last="";
}
'
}
echo as | cec-client | filter | \
while read cmd; do
case "$cmd" in
right) onright;;
left) onleft;;
down) ondown;;
up) onup;;
select) onselect;;
exit) onexit;;
play) onplay;;
pause) onpause;;
forward) onforward;;
backward) onbackward;;
*) echo "unrecognized button ($cmd)";;
esac
done

install libcec on raspbian

sudo apt-get update
sudo apt-get install build-essential autoconf liblockdev1-dev libudev-dev git libtool pkg-config
git clone https://github.com/Pulse-Eight/libcec
cd libcec
./bootstrap
./configure --with-rpi-include-path=/opt/vc/include --with-rpi-lib-path=/opt/vc/lib --enable-rpi
make
sudo make install
sudo ln -s /usr/local/lib/libcec.so /usr/lib/
sudo ln -s /usr/local/lib/libcec.so.2 /usr/lib/

run cec-keypresses.sh

~$ ./cec-keypresses.sh 
right button pressed
right button pressed
left button pressed
up button pressed
down button pressed
select button pressed
select button pressed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment