Skip to content

My custom sleep script.

Earlier I posted about a custom sleep script so that my laptop would suspend for a few hours and then automatically wake up and hibernate to disk if not woken up. I was still struggling writing it in bash, so I tried writing in python, and finally got it to work! Here's the script below. I added the command to the script in /etc/acpi/handler.sh where it responds to lid events. If it matters, releasing under GNU GPL v3.

 import os
 import sys
 import time
 import logging 
 
 def init_logger1(loggername, filename =None):
     if not filename:
         filename ='~/sleep.log'
     logger = logging.getLogger(loggername)
     logger.setLevel(logging.DEBUG)
     ch = logging.FileHandler(filename)
     ch.setLevel(logging.DEBUG)
     # create formatter
     formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
     # add formatter 
     ch.setFormatter(formatter)
     # add ch to logger
     if len(logger.handlers)==0:
         logger.addHandler(ch)
     return logger
 
 
 logger = init_logger1('smartsleep')
 pid = str(os.getpid())
 logger.info('smartsleep called, pid={0}'.format(pid))
 
 pidfile = "/tmp/smartsleep.pid"
 
 if os.path.isfile(pidfile):
     logger.info ("{0} already exists, exiting".format(pidfile))
     sys.exit()
 
 logger.info('waiting 10 seconds...'.format(pid))
 time.sleep(10)
 file1 = open('/proc/acpi/button/lid/LID/state')
 status = file1.read()
 
 logger.info(status)
 
 if 'closed' in status:
     open(pidfile, 'w').write(pid)
     logger.info('lid still closed, going to sleep')
     os.popen("rtcwake -m mem -u -v -s 10800", 'w')
     logger.info('woke up...waiting 30 seconds')
 
 
     time.sleep(30)
     file1 = open('/proc/acpi/button/lid/LID/state')
     status = file1.read()
     if 'closed' in status:
         logger.info('waited 30 seconds, lid still closed so hibernating')
         os.popen("pm-hibernate")
     else:
         logger.info('lid is open, so exiting')
 
     os.unlink(pidfile)
     sys.exit()
 else:
     logger.info('still open, quitting...')
34 points18 comments
Open on Reddit
About this post
Posted
Archived
Score
34 · 100% up
Kind
Text
ID
ppfkc

Author

30
posts
174
comments
3
media
View profile

18 comments

I have one in bash on my netbook. I'm at work right now, and I'll likely forget by the time I get home. Could someone reply to this as a reminder?

Update

The first I use is a script called lid.sh that triggers when the lid is closed (look into ACPI events to do that):

STATE=`(cat /proc/acpi/ac_adapter/AC0/state | grep on-line)`
ALLOW=`(cat /home/satoshi/.allows2ram)`

if [ -z "$STATE" ] && [ -z "$ALLOW" ]
then
  /home/satoshi/scripts/sleep-then-hibernate.sh
fi

The .allows2ram file is simply a file that contains the word "no" if I have suspend-on-lid disabled (if I'm just moving to another room or another desk, I don't want the machine to go to sleep when I close it. I have quick keybinds set up to toggle whether it suspends or not). Grepping the state of the ac-adapter is because, when the device is plugged in, I generally don't want it to sleep even with the lid closed. I like to plug it in, shove it in the corner, and then SSH into it, or VNC if I really need to.

lid.sh calls sleep-then-hibernate.sh which looks like:

TIMEOUT=14400
SLEEPTIME=`date +%s`

sudo rtcwake -m mem -s $TIMEOUT

WAKETIME=`date +%s`

if [ $(($WAKETIME - $SLEEPTIME)) -ge $TIMEOUT ]
then
  sudo s2disk
else
  echo "nobernate :("
fi

And that's it. It works flawlessly on my machine.

10 points
unknown author4 hidden

Hehe. You're sugardeath and your name is Satoshi.

1 points

I..yes.. Is there some significance? They're both aliases, actually. The only machine I use my real name as a user name is the server at work.

1 points

Thanks for sharing! I'm trying to teach myself how to write system scripts for various things and it really helps to see people's solutions to their problems. Helps give me ideas of stuff to try!

3 points

It is amazing to ponder what is possible, although I did most of this kind of script writing when setting up my arch system and have mostly been lazy since then (a year and a half).

I feel like a solution in search of a problem! At this point I love it when a pacman -Syu breaks something, my only chance to learn.

1 points

pm-utils has a command pm-suspend-hybrid, which leaves computer in sleep mode until a certain battery level gets low, at which point it hibernates. Haven't tested it out as I haven't bothered to get hibernate working, but should work fine.

3 points

As an exercise, I tried rewriting it in bash, though I don't know if it works or not since I've got trouble with hibernating as it is.

PIDFILE="/tmp/smartsleep.pid"
[[ -f $PIDFILE ]] && logger "$PIDFILE already exists, exiting"; exit 1

logger "waiting 10 seconds..."
sleep 10
STATUS=$(cat /proc/acpi/button/lid/LID/state)
logger "$STATUS"
if [[ "$STATUS" =~ "closed" ]]; then
        pidof $0 > $PIDFILE
        logger "lid still closed, going to sleep"
        rtcwake -m mem -u -v -s 10800
        logger "woke up...waiting 30 seconds"
        sleep 30
        STATUS=$(cat /proc/acpi/button/lid/LID/state)
        if [[ "$STATUS" =~ "closed" ]]; then
            logger "waited 30 seconds, lid still closed so hibernating"
            pm-hibernate
        else
            logger "lid is open, so exiting"
        fi
        unlink $PIDFILE
        exit 0
else
    logger "still open, quitting"

NOTE: I used "logger" for this, so all messages show up in syslog. You can also use the "-p" option to specify priority and facility (see man logger) or just use "echo $MSG >> $LOGFILE".

2 points

I just tested it. It appears to work!

2 points

Caveat emptor though, I'm not really sure about the pid-handling part.

For one, it should break if the filename starts with a dash, though inserting "--" after "pidof" should take care of that.

If you have any questions regarding that script (or bash in general), I'm available daily under this username.

2 points

Keyboard shortcuts

Move and act

jork
Next / previous post or comment
Enteroro
Open the post
f
Open the media viewer
s
Save
h
Hide (the toast has Undo)
Tab
Right after an action: the toast's Undo
x
Collapse the comment
v
Next layout: cards, compact, grid

Go to

/
Search
gthenh
Home
gthena
All
gthens
Subreddits
gthenl
Library
?
This list
Esc
Close a menu or this list

In the viewer

←or→
Previous / next file
↑or↓
Previous / next post
korj
Previous / next post
Space
Play / pause
m
Mute
z
Zoom
s
Save
o
Open the post (on its own page: back to it)
Esc
Close

Keys do nothing while you type in a box.