User Tools

Site Tools


Toggle an external HDMI display using udev

Use udevadm monitor to detect udev events when connecting or disconnecting the display:

$ udevadm monitor
monitor will print the received events for:
UDEV - the event which udev sends out after rule processing
KERNEL - the kernel uevent

<connecting the display>
KERNEL[549920.709264] change   /devices/pci0000:00/0000:00:02.0/drm/card0 (drm)
UDEV  [549920.712808] change   /devices/pci0000:00/0000:00:02.0/drm/card0 (drm)

<disconnecting the display>
KERNEL[549932.063215] change   /devices/pci0000:00/0000:00:02.0/drm/card0 (drm)
UDEV  [549932.067059] change   /devices/pci0000:00/0000:00:02.0/drm/card0 (drm)

Use xrandr to automatically extend the desktop to the new display:

$ xrandr --output HDMI1 --auto --above LVDS1

Or remove the HDMI display:

$ xrandr --output HDMI1 --off

Now put all that into a udev rules:

$ sudo -s
# cat /etc/udev/rules.d/hdmi.rules
SUBSYSTEM=="drm", ACTION=="change", RUN+="/usr/local/bin/hdmi_toggle"

and create the script at /usr/local/bin/hdmi_toggle:

#!/usr/bin/env bash

# grab the display and xauthority cookie
export DISPLAY=$(w -h -s | grep ":[0-9]\W" | head -1 | awk '{print $2}')
X_USER=$(w -h -s | grep ":[0-9]\W" | head -1 | awk '{print $1}')
export XAUTHORITY=/home/$X_USER/.Xauthority

# get the status of the external display
status=$(cat /var/run/hdmi1_status)
case $status in
		/usr/bin/su $X_USER -c '/bin/xrandr --output HDMI1 --off'
		echo disconnected > /var/run/hdmi1_status
		/usr/bin/logger "disabled hdmi output"
		/usr/bin/su $X_USER -c '/bin/xrandr --output HDMI1 --auto --above LVDS1'
		echo connected > /var/run/hdmi1_status
		/usr/bin/logger "enabled hdmi output"

Make it executable:

# chmod +x /usr/local/bin/hdmi_toggle

And that's it. Enjoy connecting and disconnecting your display at will. If you want another display layout, replace the –above part of the xrandr command with {–left-of, –right-of, –below}.

en/ressources/astuces/udev_hdmi.txt · Last modified: 2024/04/17 10:19 by