Skip to content

Instantly share code, notes, and snippets.

@AntonioND
Created March 26, 2018 23:16
Show Gist options
  • Select an option

  • Save AntonioND/22da68aa34cd1babb1457f76cad706c8 to your computer and use it in GitHub Desktop.

Select an option

Save AntonioND/22da68aa34cd1babb1457f76cad706c8 to your computer and use it in GitHub Desktop.
Automatically turn off and on the monitor of a Raspberry Pi
#!/usr/bin/env python3
#
# energy-saver.py
#
# Copyright (c) 2018, Antonio Niño Díaz
#
# SPDX-License-Identifier: MIT
#
# Author: Antonio Niño Díaz
# Email: antonio_nd at outlook dot com
# Date: 2018-03-26
# Version: 1.1
#
# This script turns on and off the monitor connected to a Raspberry Pi. It turns
# it on every day at 7:00 except during the weekends. It turns it off at 19:00.
# The file /home/pi/monitor-status holds the last status (on or off) set by this
# script to the monitor (which may not be the actual status, it can be turned on
# or off from outside the script!).
#
# Note: To query status of the monitor over ssh run:
#
# export DISPLAY=":0"
# xset q | grep Monitor
import datetime
import subprocess
import time
def monitor_should_be_on():
now = datetime.datetime.now()
# At 7:00 turn screen on
if now.hour >= 7:
# At 19:00 turn screen off
if now.hour < 19:
# Only Monday to Friday
if now.isoweekday() < 6:
return True
return False
def monitor_turn_on():
subprocess.call('export DISPLAY=":0"\n' +
# Turn monitor on
'xset dpms force on\n' +
# Disable screen saving to prevent it from going to sleep
'xset s off\n' +
'xset s noblank\n' +
'xset -dpms', shell=True)
# Set status to on
subprocess.call('echo "on" > ~/monitor-status', shell=True)
return
def monitor_turn_off():
subprocess.call('export DISPLAY=":0"\n' +
# Turn monitor on
'xset dpms force off', shell=True)
# Set status to off
subprocess.call('echo "off" > ~/monitor-status', shell=True)
return
# Make sure that the status of the monitor is consistent when the script starts
monitor_is_on = monitor_should_be_on()
if monitor_is_on:
monitor_turn_on()
else:
monitor_turn_off()
# Loop forever
while True:
monitor_desired_on = monitor_should_be_on()
if monitor_desired_on and not monitor_is_on:
monitor_turn_on()
elif not monitor_desired_on and monitor_is_on:
monitor_turn_off()
monitor_is_on = monitor_desired_on
# Sleep for 1 minute
time.sleep(60)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment