Skip to content

Instantly share code, notes, and snippets.

@caioaao
Last active November 4, 2022 14:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caioaao/e23f21926d78c23d43024bee7c7f59f1 to your computer and use it in GitHub Desktop.
Save caioaao/e23f21926d78c23d43024bee7c7f59f1 to your computer and use it in GitHub Desktop.

Setup udev rule for HDMI cable

Create script that checks HDMI status and executes xrandr:

#!/usr/bin/env bash

export DISPLAY=":0.0"

USER="$(who | grep ${DISPLAY}\) | cut -f 1 -d ' ' | head -n1)"

export XAUTHORITY="/home/${USER}/.Xauthority"

HDMI_STATUS=`cat /sys/class/drm/card0-HDMI-A-1/status`

# echo "------------------------------------------------" >> /tmp/toggle_monitor.log
# echo "$(date) - DISPLAY: ${DISPLAY}, HDMI_STATUS: ${HDMI_STATUS}, USER: ${USER}" >> /tmp/toggle_monitor.log
xrandr > /dev/null # >> /tmp/toggle_monitor.log

if [[ ${HDMI_STATUS} == 'connected' ]]; then
    # echo "Turning monitor on" >> /tmp/toggle_monitor.log
    xrandr --output HDMI-1 --auto --above eDP-1
else
    # echo "Turning monitor off" >> /tmp/toggle_monitor.log
    xrandr --output HDMI-1 --off
fi

Create udev rule:

KERNEL=="card0", SUBSYSTEM=="drm", RUN+="/usr/local/bin/toggle_display"

After tangle, run this to enable the systemd unit and reload udev rules.

udevadm control --reload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment