// EncoderTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "..\phidget21.h"
#include <windows.h>


HANDLE m_EventHandle;

int __stdcall AttachHandler(CPhidgetHandle IFK, void *userptr)
{
	SetEvent(m_EventHandle);
	printf("Attach handler ran!\n");
	return 0;
}

int __stdcall DetachHandler(CPhidgetHandle IFK, void *userptr)
{
	printf("Detach handler ran!\n");
	return 0;
}

int __stdcall ErrorHandler(CPhidgetHandle IFK, void *userptr, long ErrorCode, void *unknown)
{
	printf("Error handler ran!\n");
	return 0;
}

void display_generic_properties(CPhidgetHandle phid)
{
	long sernum, version;
	const char *deviceptr;
	CPhidget_getDeviceType(phid, &deviceptr);
	CPhidget_getSerialNumber(phid, &sernum);
	CPhidget_getDeviceVersion(phid, &version);

	printf("%s\n", deviceptr);
	printf("Version: %8d SerialNumber: %10d\n", version, sernum);
	return;
}

int __stdcall Enc_InputChangeHandler(CPhidgetEncoderHandle IFK, void *userptr, int Index, int Value)
{
	printf("Encoder Button %d Input is %d\n", Index, Value);
	return 0;
}

int __stdcall Enc_PositionChangeHandler(CPhidgetEncoderHandle IFK, void *userptr, int Index, int Time, int Position)
{
	printf("Encoder # %d Position %d at Time %d\n", Index, Position, Time);
	return 0;
}

int test_encoder()
{
	int result;
	char *err;

	CPhidgetEncoderHandle Enc = 0;

	m_EventHandle = CreateEvent(NULL, FALSE, FALSE, NULL);

	result = CPhidgetEncoder_create(&Enc);
	CPhidget_getErrorDescription(result, &err);
	printf("CPhidgetEncoder_create returns: %d: \"%s\"", result, err);

	CPhidget_set_OnAttach_Handler((CPhidgetHandle)Enc, AttachHandler, NULL);
	CPhidget_set_OnDetach_Handler((CPhidgetHandle)Enc, DetachHandler, NULL);
	CPhidget_set_OnError_Handler((CPhidgetHandle)Enc, ErrorHandler, NULL);

	CPhidgetEncoder_set_OnInputChange_Handler(Enc, Enc_InputChangeHandler, NULL);
	CPhidgetEncoder_set_OnPositionChange_Handler(Enc, Enc_PositionChangeHandler, NULL);

	result = CPhidget_open((CPhidgetHandle)Enc, -1);

	if (result) 
	{
		printf ("No Accelerometer found...\n");	
		return 0;
	}

	result = WaitForSingleObject(m_EventHandle, 10000); 
	// We wait for up to 1000 milliseconds to get the device

	display_generic_properties((CPhidgetHandle) Enc);

	printf("And reading ...\n");

	getchar();

	printf("And, closing\n");

	CPhidget_close((CPhidgetHandle)Enc);
	CPhidget_delete((CPhidgetHandle)Enc);

	return 0;
}


int main(int argc, char* argv[])
{
	test_encoder();
	return 0;
}

