#!/usr/bin/php
<?php
  // (c) 2009 plugdev @ sub.noloop.net - http://plug.noloop.net
  // See /usr/src/linux/Documentation/input/input.txt and include/linux/input.h
  define('STRUCT_INPUT_EVENT_LEN', 8+2+2+4);

  $fp = fopen('/dev/input/event0', 'rb') or die('Could not open event0');
  while(true) {
    $evdata = fread($fp, STRUCT_INPUT_EVENT_LEN);
    if (strlen($evdata) != STRUCT_INPUT_EVENT_LEN) {
      die('Unexpected read len '.strlen($evdata).' expected '.STRUCT_INPUT_EVENT_LEN);
    }
    $ev = unpack('Ltv_sec/Ltv_usec/Stype/Scode/ivalue', $evdata);
    if ($ev['type'] == 1) { // #define EV_KEY 0x01
      if ($ev['value'] == 1) { // 0 for EV_KEY for release, 1 for keypress and 2 for autorepeat.
        switch ($ev['code']) {
          case 114: // KEY_VOLUMEDOWN
            system("mpc volume -10");
            break;
          case 115: // KEY_VOLUMEUP
            system("mpc volume +10");
            break;
          case 163: // KEY_NEXTSONG
            system("mpc next");
            break;
          case 165: // KEY_PREVIOUSSONG
            system("mpc prev");
            break;
          case 164: // KEY_PLAYPAUSE
            system("mpc toggle");
            break;
          case 256: // BTN_MISC (the "music" key)
            system("/home/user/imap-to-speech/imap-to-speech.php > /dev/null &");
            break;
          case 113: // KEY_MUTE (the "power" key)
            break;
        }
      }
    }
  }