Can root test whether a monitor is connected

monitors

I use a script in /etc/acpi to turn off the screen (xset dpms force
off
) when I close my laptop's lid. Now I want it to act differently
when an external monitor is connected (set brightness to zero
instead). I know I can test whether it is connected with xrandr,
but the script is run by root, and xrandr depends on a certain
X-session. Is there a way for root to test whether the monitor is
connected, regardless of X-sessions? I'm using Arch Linux.

Best Answer

Method #1 - edid-decode

You can use edid-decode to see what monitors are connected. This is from an Ubuntu 16.04 system I have, but this worked in Fedora 28 & CentOS 7.x as well.

NOTE: This particular system has two video ports, I'm using the VGA one.

Here the monitor is plugged in:

$ ls /sys/class/drm/*/edid | xargs -n 1 edid-decode | grep Manufacturer:
Manufacturer: DEL Model a071 Serial Number 844247885
Manufacturer: @@@ Model 0 Serial Number 0

And here is when I unplug the VGA monitor:

$ ls /sys/class/drm/*/edid | xargs -n 1 edid-decode | grep Manufacturer:
Manufacturer: @@@ Model 0 Serial Number 0
Manufacturer: @@@ Model 0 Serial Number 0

And here it is plugged back in:

$ ls /sys/class/drm/*/edid | xargs -n 1 edid-decode | grep Manufacturer:
Manufacturer: DEL Model a071 Serial Number 844247885
Manufacturer: @@@ Model 0 Serial Number 0

Method #2 - cat sysfs

If you poke around under /sys the display ports that you have are listed here under /sys/class/drm.

$ ls /sys/class/drm
card0  card0-DP-1  card0-HDMI-A-1  controlD64  renderD128  version

The display ports for monitors will be card0-DP-1 (VGA) and the card0-HDMI-A-1 (HDMI). If you look in each of these directories, there's a file called status. If you cat this file you can see the port's status and whether a monitor is connected or not.

Same test as above, plugged in:

$ cat /sys/class/drm/card0-DP-1/status
connected

Unplugged:

$ cat /sys/class/drm/card0-DP-1/status
disconnected

References

Related Question