Skip to content

Instantly share code, notes, and snippets.

@lhw
Last active May 30, 2018 18:18
Show Gist options
  • Save lhw/6d9bd59f2af311d90fd5e628b342fe7c to your computer and use it in GitHub Desktop.
Save lhw/6d9bd59f2af311d90fd5e628b342fe7c to your computer and use it in GitHub Desktop.
Automate switch of monitor inputs via ddc in case the VM is currently running
# Example rule based on a keyboard being added/removed (In this case for a Corsair K70 keyboard)
# Note that the keyboard attaches as two keyboards + led controller
# Try to get the add/remove events down to one each by clearly defining the
# rules. As the ddcutil call can take time even if only checking the current
# output port.
KERNEL=="event1", ACTION=="add|remove", SUBSYSTEM=="input", ATTRS{idVendor}== "1b1c", ATTRS{idProduct}=="1b09", RUN+="/etc/libvirt/hooks/switch_displays.sh"
#!/bin/bash
# Based on the libvirt hook by Sebastiaan Meijer (sebastiaan@passthroughpo.st)
# https://github.com/PassthroughPOST/VFIO-Tools/blob/master/libvirt_hooks/hooks/switch_displays.sh
# Windows Domain
DOMAIN="win10"
# Example setup with two monitors
# Benq
VM_DISPLAY_1="1" # The display shown in `ddcutil detect`
VM_MON_1="0f" # The input the VM is connected to (without 0x, but with leading zeroes, if any. See `ddcutil capabilities`)
HOST_MON_1="03" # The input the host is connected to (without 0x, but with leading zeroes, if any. See `ddcutil capabilities`)
# ASUS
VM_DISPLAY_2="2"
VM_MON_2="04"
HOST_MON_2="0f"
# Do nothing if the domain is shutdown
[[ $(virsh list --all | grep "${DOMAIN}.*running" ; echo $?) -ne 0 ]] && exit 0
# Input device was removed from the host
if [[ ${ACTION} == "remove" ]]; then
INPUT_MON_1=$VM_MON_1
INPUT_MON_2=$VM_MON_2
# Input device was given back to the host
elif [[ ${ACTION} == "add" ]]; then
INPUT_MON_1=$HOST_MON_1
INPUT_MON_2=$HOST_MON_2
fi
# Check if monitor is already set to correct output. Switch displays otherwise
if [[ "$(ddcutil -d "$VM_DISPLAY_1" getvcp 60 --terse | awk '{print $4}')" != "x$INPUT_MON_1" ]]; then
ddcutil -d "$VM_DISPLAY_1" setvcp 60 "0x$INPUT_MON_1"
ddcutil -d "$VM_DISPLAY_2" setvcp 60 "0x$INPUT_MON_2"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment