import com.phidgets.InterfaceKitPhidget;
import com.phidgets.PhidgetException;
import com.phidgets.event.AttachEvent;
import com.phidgets.event.AttachListener;
import com.phidgets.event.DetachEvent;
import com.phidgets.event.DetachListener;
import com.phidgets.event.ErrorEvent;
import com.phidgets.event.ErrorListener;
import com.phidgets.event.InputChangeEvent;
import com.phidgets.event.InputChangeListener;
import com.phidgets.event.OutputChangeEvent;
import com.phidgets.event.OutputChangeListener;
import com.phidgets.event.SensorChangeEvent;
import com.phidgets.event.SensorChangeListener;

public class IFKex1 implements SensorChangeListener, InputChangeListener,
        AttachListener, DetachListener, ErrorListener, OutputChangeListener {
    
    public static int LED_PORT=7;
    public static int INPUT_PORT=3;
    public static int ANALOG_PORT=7;
    
    public static void main(String[] args) throws PhidgetException {
        new IFKex1();
    }

    public IFKex1() throws PhidgetException {
        InterfaceKitPhidget phid = new InterfaceKitPhidget();
        try {
            phid.addAttachListener(this);
            phid.addDetachListener(this);
            phid.addSensorChangeListener(this);
            phid.addInputChangeListener(this);
            //phid.addOutputChangeListener(this);
            phid.openAny();
            phid.waitForAttachment();

            System.out.println(phid.getDeviceType());
            System.out.println("Serial Number " + phid.getSerialNumber());
            System.out.println("Device Version " + phid.getDeviceVersion());

            System.out.println("Looping...\n");
            boolean led = true;
            boolean dummy = true;
            for (; dummy;) {

                phid.setOutputState(LED_PORT, led);
                if (!phid.getInputState(INPUT_PORT))
                    led = !led;
                try {
                    // changing the output too often seems to mess up the sensor
                    // box
                    Thread.sleep(100 + phid.getSensorValue(7));
                    // Thread.sleep(1000);
                } catch (Throwable t) {
                    t.printStackTrace();
                }
            }
        } finally {
            phid.close();
            System.out.println("Closed and exiting...");
        }
    }

    public void sensorChanged(SensorChangeEvent arg0) {
        System.out.println(arg0);
    }

    public void inputChanged(InputChangeEvent arg0) {
        System.out.println(arg0);
    }

    public void attached(AttachEvent arg0) {
        System.out.println(arg0);
    }

    public void detached(DetachEvent arg0) {
        System.out.println(arg0);
    }

    public void error(ErrorEvent arg0) {
        System.out.println(arg0);
    }

    public void outputChanged(OutputChangeEvent arg0) {
        System.out.println(arg0);
    }
}
