Saturday, March 17, 2012

Automatically set Linux backlight for day/night

This is a quick PHP script to set the screen back light level at Sunrise/Sunset, like most Sat-Nav devices do. It has two dependencies, xbacklight & php-cli, and is be run from crontab. I have it every 5 minutes. 


The only changes you need to make to the script are your Longitude and Latitude (Google Earth is handy for this) and timezone. Latitude/Longitude is positive for North and East and negative for South and West. The backlight levels are percentages, be careful using 0% as it is off for some laptops.

<?php
$time=time();
//Set your Longitude, Latitude, Timezone and backlight percentages here
$latitude = -35;
$longitude = 117.9;
$tzone=8;
$daylight=70;
$nightlight=30;

// Get sunrise and Sunset 
$sunrise = date_sunrise(time(), SUNFUNCS_RET_TIMESTAMP, $latitude, $longitude, 90, $tzone);
$sunset = date_sunset(time(), SUNFUNCS_RET_TIMESTAMP, $latitude, $longitude, 90, $tzone);
night or daynight or daynight or day
//Set backlight level

if ($time > $sunset)
   system ("xbacklight -set $nightlight");
if ($time < $sunset && $time > $sunrise)
   system ("xbacklight -set $daylight");
if ($time < $sunrise)
   system ("xbacklight -set $nightlight");
?>


Save the script to somewhere that suites you, mine is in /usr/local/bin/sunset.php .

And the crontab entry for every 5 minutes,

*/5 * * * * /usr/bin/php -q /usr/local/bin/sunset.php


That's it, the script will check every five minutes to see if it's night or day depending on sunrise/sunset and set the backlight accordingly.

No comments:

Post a Comment