Custom script when closing the lid of the laptop and locking the screen without sleep

Hello everyone. I use Lubuntu 18.04 on my home laptop. One fine day, I decided that I was not happy with the actions that Power Manager offers when closing the lid of a laptop. When I closed the lid of the laptop, I wanted to block the screen and after a while send the laptop to hibernation. To do this, I wrote a script and I hasten to share it with you.

I ran into two problems.

The first is that hibernation does not work in the loubunt out of the box;

Find the UUID swap, for this you need to do:

grep swap /etc/fstab

In my case, the output is as follows:

# swap was on /dev/mmcblk0p2 during installation
UUID=aebf757e-14c0-410a-b042-3d9a6044a987 none            swap    sw              0       0

Then you need to add the UUID to the kernel initialization parameters. To do this, add in the file / etc / default / grub to the line "GRUB_CMDLINE_LINUX_DEFAULT" resume = UUID =% your UUID%

...
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash resume=UUID=aebf757e-14c0-410a-b042-3d9a6044a987"
...

And execute the command:

sudo update-grub

Now hibernation should work, for verification you can do:

sudo systemctl hibernate

The second problem was how to lock the user’s screen from root without sending the laptop to sleep. I solved it using dbus-send, the command itself is in the script below. If someone knows other options, please write in the comments.

Now let's start writing the script.

The first thing we need to do in Power Manager is select Switch off display as the action when closing the lid so that there are no conflicts with our script.

image

Then create the file / etc / acpi / events / laptop-lid with the following contents:

event=button/lid.*
action=/etc/acpi/laptop-lid.sh

and create the script /etc/acpi/laptop-lid.sh with the following contents:

#!/bin/bash

#set variables
# BUS   environ   lxsession
BUS=$(grep -z DBUS_SESSION_BUS_ADDRESS \
	/proc/$(pidof -s lxsession)/environ | \
	sed 's/DBUS_SESSION_BUS_ADDRESS=//g')
#     ,    
USER=$(grep -z USER /proc/$(pidof -s lxsession)/environ | sed 's/USER=//g')
#     
LID="/proc/acpi/button/lid/LID0/state"

#Check lid state (return 0 if closed)
check_lid () {
	grep -q closed $LID
}

#Lock screen without sleep
check_lid
if [ $? = 0 ]
then
	#TODO run command as root
	sudo -u $USER -E dbus-send --bus=$BUS \
				    --type=method_call \
				    --dest="org.freedesktop.ScreenSaver" \
				    "/org/freedesktop/ScreenSaver" \
				    org.freedesktop.ScreenSaver.Lock
fi

#Wait 10 minutes and hibernate if lid is closed
sleep 600
check_lid
if [ $? = 0 ]
then
	systemctl hibernate
fi

We make the script executable:

sudo chmod a+x /etc/acpi/laptop-lid.sh

And restart the acpid daemon so that the changes apply:

sudo systemctl restart acpid.service

Everything is ready.

For Gnome in the script you need to change:

  • lxsessin => gnome-session
  • org.freedesktop.ScreenSaver => org.gnome.ScreenSaver

All Articles