diff --git a/README.md b/README.md index ddb52c6..ce9639c 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,8 @@ # cutiepi-button-handler -Simple button handling service for the CutiePi button events + +This script handles button press events on a CutiePi tablet and toggles the display on/off upon pressure. + +## Installation + +Just copy `bin/cutiepi-button-handler` somewhere in your `PATH` (default: `~/bin`) and start it. Button support should work out of the box. + diff --git a/bin/cutiepi-button-handler b/bin/cutiepi-button-handler new file mode 100755 index 0000000..c0ff48b --- /dev/null +++ b/bin/cutiepi-button-handler @@ -0,0 +1,64 @@ +#!/usr/bin/env python + +import os +import re +import subprocess + +from gi.repository import GLib +from dbus import SessionBus +from dbus.mainloop.glib import DBusGMainLoop + +previous_xrandr = 'xrandr --output DSI-1 --auto' + + +def get_current_xrandr() -> str: + proc = subprocess.Popen(['unxrandr'], stdout=subprocess.PIPE) + return proc.communicate()[0].decode().strip() + + +def is_display_on() -> bool: + proc = subprocess.Popen(['xrandr', '-q'], stdout=subprocess.PIPE) + out = proc.communicate()[0].decode().strip() + lines = [ + line for line in out.split('\n') + if line.startswith('DSI-1 ') + ] + + assert lines, 'Display DSI-1 not found' + m = re.search(r'^DSI-1\s+(connected\s+)?(primary\s+)?\d+x\d+\+\d+\+\d+', lines[0]) + return m is not None + + +def signal_handler(name, value): + global previous_xrandr + if name != 'button': + return + + is_on = is_display_on() + if is_on: + previous_xrandr = get_current_xrandr() + os.system('xrandr --output DSI-1 --off') + else: + os.system(previous_xrandr) + + +def main(): + xrandr = get_current_xrandr() + + loop = DBusGMainLoop() + bus = SessionBus(mainloop=loop) + bus.add_signal_receiver( + signal_handler, 'updateEvent', + 'io.cutiepi.interface', path='/mcu' + ) + + loop = GLib.MainLoop() + + try: + loop.run() + finally: + loop.quit() + + +if __name__ == '__main__': + main() diff --git a/systemd/cutiepi-button-handler.service b/systemd/cutiepi-button-handler.service new file mode 100644 index 0000000..ae38621 --- /dev/null +++ b/systemd/cutiepi-button-handler.service @@ -0,0 +1,19 @@ +# Copy or symlink this systemd service to ~/.config/systemd/user +# (create the folder if it doesn't exist). +# Start with: systemctl --user start cutiepi-button-handler +# Stop with: systemctl --user stop cutiepi-button-handler +# Enable at startup with: systemctl --user cutiepi-button-handler +# Disable at startup with: systemctl --user cutiepi-button-handler + +[Unit] +Description=Manage screen on/off logic upon button press on the CutiePi +After=graphical.target + +[Service] +ExecStart=/home/pi/bin/cutiepi-button-handler +Restart=always +RestartSec=5 + +[Install] +WantedBy=default.target +