Listing 11. Using EVIOCGLED
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */


#include <stdlib.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <asm/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#include <string.h>

#include <linux/input.h>

/* this macro is used to tell if "bit" is set in "array"
 * it selects a byte from the array, and does a boolean AND 
 * operation with a byte that only has the relevant bit set. 
 * eg. to check for the 12th bit, we do (array[1] & 1<<4)
 */
#define test_bit(bit, array)    (array[bit/8] & (1<<(bit%8)))

int main (int argc, char **argv) {

  int fd = -1;
  uint8_t led_bitmask[LED_MAX/8 + 1];
  int yalv;

  /* ioctl() requires a file descriptor, so we check we got one, and then open it */
  if (argc != 2) {
    fprintf(stderr, "usage: %s event-device - probably /dev/input/event0\n", argv[0]);
    exit(1);
  }
  if ((fd = open(argv[1], O_RDONLY)) < 0) {
    perror("evdev open");
    exit(1);
  }

  memset(led_bitmask, 0, sizeof(led_bitmask));
  if (ioctl(fd, EVIOCGLED(sizeof(led_bitmask)), led_bitmask) < 0) {
      perror("event ioctl");
  }

  for (yalv = 0; yalv < LED_MAX; yalv++) {
      if (test_bit(yalv, led_bitmask)) {
	  /* this means that the bit is set in the LED state */
	  printf("  LED 0x%02x ", yalv);
	  switch ( yalv)
	      {
	      case LED_NUML :
		  printf(" (Num Lock)\n");
		  break;
	      case LED_CAPSL :
		  printf(" (Caps Lock)\n");
		  break;
	      case LED_SCROLLL :
		  printf(" (Scroll Lock)\n");
		  break;
	      case LED_COMPOSE :
		  printf(" (Compose)\n");
		  break;
	      case LED_KANA :
		  printf(" (Kana)\n");
		  break;
	      case LED_SLEEP :
		  printf(" (Sleep)\n");
		  break;
	      case LED_SUSPEND :
		  printf(" (Suspend)\n");
		  break;
	      case LED_MUTE :
		  printf(" (Mute)\n");
		  break;
	      case LED_MISC :
		  printf(" (Miscellaneous)\n");
		  break;
	      default:
		  printf(" (Unknown LED type: 0x%04hx)\n", yalv);
	      }
      }
  }

  close(fd);
  
  exit(0);
}
