I have a systemd timer service which runs a script every 5 minutes to check if the monitor has been powered off. If it is powered off, it locks the screen.
But I'm having some problems with the users and permissions. It seems the script must be run as sudo to query the monitor's power state, but this causes the xsecurelock to require the root password to unlock the screen. How can I fix this?
I should say: I want to keep this approach and the use of xsecurelock since this is working on my other PCs. Needing sudo to query the power state seems peculiar to this PC.
- Systemd service
Description=Check if Monitor is switched off and run xsecurelock
After=network.target
[Service]
User=dave
Environment=XAUTHORITY=/home/dave/.Xauthority
Environment=DISPLAY=:0
Type=simple
ExecStart=/home/dave/monitor_check.sh --debug
StandardOutput=journal
StandardError=journal
Restart=no
[Install]
WantedBy=multi-user.target
- Script
XSECURELOCK_SAVER=saver_xscreensaver
export XSECURELOCK_SAVER
echo "The value of XSECURELOCK_SAVER is: $XSECURELOCK_SAVER"
state=$(ddcutil getvcp D6 2>&1)
echo "$state"
sleep 2
if [[ "$state" == *"Display not found"* ]]; then
echo "Monitor is off, executing command..."
exec xsecurelock
break
else
echo "Display is found, nothing to do."
fi
This was counterintuitive. To fix the permissions of a systemd service running a script didn't need changes to either the systemd service or the script but the creation of a udev rule:-
/etc/udev/rules.d/60-ddcutil-i2c.rules
SUBSYSTEM=="i2c-dev", KERNEL=="i2c-[0-9]*", ATTRS{class}=="0x030000", TAG+="uaccess"
SUBSYSTEM=="dri", KERNEL=="card[0-9]*", TAG+="uaccess"
Because the permissions of the command ddcutil are i2c permissions.
https://www.ddcutil.com/i2c_permissions/
Hopefully this discovery will be useful to someone, or even to people who make screensaver UIs.
The script is probably fairly portable to different monitor hardware. Where it says D6 that isn't the monitor's listing in xrandr -query but the Feature listed for the power state by the command:-
ddcutil capabilities
xrandr -query though is used to get the DISPLAY=:0 environment variable for systemd. In xrandr it is the SCREEN but in systemd it is the DISPLAY
I suppose a reason this isn't in screensaver GUIs might be that ddcutil's outputs for the Capabilities and then (if applicable) the power state varies too much between different manufacturers.