2008-06-08 y0shi dimmer.c

GPL
/*  file dimmer.c
    
    compile with gcc -o dimmer dimmer.c -lXss
    
    should run as NON-root !
    run chown you_user.users /sys/class/backlight/thinkpad_screen/brightness
    on system startup (i.e. for slackware users put this
    command in your /etc/rc.d/rc.local)
    
    you might need to replace /thinkpad_screen/ with /ibm/
    
    tested on thinkpad x30 with linux-2.6.24.3
    tested on thinkpad t30 with linux-2.6.21.5
    
*/

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <X11/extensions/scrnsaver.h>

int dimmed;

void dim_down() {
  int i;
  FILE *fp;
  
  fp=fopen("/sys/class/backlight/thinkpad_screen/brightness","w");

  if (fp==NULL){
    printf("Problem beim Oeffnen des files brightness\n");
    fflush(stdout);
    exit(1);
  }
  
  for (i=6; i>=0; i--) {
    fprintf(fp,"%i\n",i);
    usleep(50000);
    fflush(fp);
  }
  fclose(fp);
  dimmed = 1;
}

void dim_up() {
  int i;
  FILE *fp;

  fp=fopen("/sys/class/backlight/thinkpad_screen/brightness","w");

  if (fp==NULL){
    printf("Problem beim Oeffnen des files brightness\n");
    fflush(stdout);
    exit(1);
  }

  for (i=1; i<8; i++) {
    fprintf(fp,"%i\n",i);
    usleep(20000);
    fflush(fp);
  }
  fclose(fp);
  dimmed = 0;
}

main(int argc, char *argv[])
{
  int idle_new, idle_max=7000;
  int idle_old=0;
  int opt;
  XScreenSaverInfo *info = XScreenSaverAllocInfo();
  Display *display = XOpenDisplay(0);
  
  while ((opt = getopt(argc, argv, "ht:")) != -1) {
    switch (opt) {
    case 'h':
      fprintf(stderr, "Usage: [-t max_idle_time_secs] [-h] this help\n",argv[1]);
      fprintf(stderr, "with no argument max_idle_time_secs is set to 7 secs\n",argv[1]);
      exit(EXIT_FAILURE);
    case 't':
      idle_max = 1000 * atoi(optarg);
      break;
    default/* '?' */
      fprintf(stderr, "Usage: [-t max_idle_time_secs] [-h] this help\n",argv[1]);
      fprintf(stderr, "with no argument max_idle_time_secs is set to 7 secs\n",argv[1]);
      exit(EXIT_FAILURE);
    }
  }
  dimmed = 0;
  if (idle_max < 6000) idle_max = 6000;
  printf("Idle timeout is set to %i secs\n",idle_max/1000);
  
  while (1) {
    if (dimmed == 1) {
      if (idle_new > 10*idle_max) sleep(1);
      else usleep(900000);
    } else {
      sleep(3);
    }
    XScreenSaverQueryInfo(display, DefaultRootWindow(display), info);  
    idle_new = info->idle;
    if ((idle_new > idle_max) && (dimmed == 0))
      dim_down();
    if ((idle_new < idle_old) && (dimmed == 1))
      dim_up();
    idle_old = idle_new;
  }
}