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

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

double past_samples[10];

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 ACC_AccelChangeHandler(CPhidgetAccelerometerHandle WGT, void *userptr, int Index, double Value)
{
	past_samples[Index] = (past_samples[Index] * 0.90) + (Value * 0.10);
	
	printf("%6f  ", past_samples[Index]);
	if (Index == 1) printf("\n");
	return 0;
}


int test_accel()
{
	int result;

	/*CPhidgetInterfaceKitHandle IFK = 0;
	CPhidgetInterfaceKit_create(&IFK);*/

	CPhidgetAccelerometerHandle ACC = 0;

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

	CPhidgetAccelerometer_create(&ACC);

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

	CPhidgetAccelerometer_set_OnAccelerationChange_Handler(ACC, ACC_AccelChangeHandler, NULL);


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

	if (result) 
	{	
		for (int i = 0; i < 100000; i++)
		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) ACC);

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

	CPhidgetAccelerometer_setAccelerationChangeTrigger(ACC, 0, 0.000);
	CPhidgetAccelerometer_setAccelerationChangeTrigger(ACC, 1, 0.000);

	getchar();

	printf("And, closing\n");

	CPhidget_close((CPhidgetHandle)ACC);
	CPhidget_delete((CPhidgetHandle)ACC);

	return 0;
}



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

