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

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

HANDLE m_EventHandle;

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

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

int __stdcall ErrorHandler(CPhidgetHandle TemperatureSensor, 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((CPhidgetHandle)phid, &deviceptr);
	CPhidget_getSerialNumber((CPhidgetHandle)phid, &sernum);
	CPhidget_getDeviceVersion((CPhidgetHandle)phid, &version);

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

int __stdcall TMP_TemperatureChangeHandler(CPhidgetTemperatureSensorHandle TMP, void *userptr, int Index, double Value)
{
	printf("Temperature %d is %4f\n", Index, Value);
	return 0;
}

int test_tempsensor()
{
	int result, numTempSensors;

	CPhidgetTemperatureSensorHandle TemperatureSensor = 0;

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

	CPhidgetTemperatureSensor_create(&TemperatureSensor);

	CPhidget_set_OnAttach_Handler((CPhidgetHandle)TemperatureSensor, AttachHandler, NULL);
	CPhidget_set_OnDetach_Handler((CPhidgetHandle)TemperatureSensor, DetachHandler, NULL);
	CPhidget_set_OnError_Handler((CPhidgetHandle)TemperatureSensor, ErrorHandler, NULL);
	CPhidgetTemperatureSensor_set_OnTemperatureChange_Handler(TemperatureSensor, TMP_TemperatureChangeHandler, NULL);

	result = CPhidget_open((CPhidgetHandle)TemperatureSensor, -1);
	if (result)
	{
		printf("Cannot find PhidgetTemperatureSensor\n");
		return 0;
	}
	result = WaitForSingleObject(m_EventHandle, 100000); 

	display_generic_properties((CPhidgetHandle)TemperatureSensor);


	CPhidgetTemperatureSensor_getNumTemperatureInputs(TemperatureSensor, &numTempSensors);
	printf("Number of TemperatureSensors:%d\n", numTempSensors);

	CPhidgetTemperatureSensor_setTemperatureChangeTrigger(TemperatureSensor, 0, 1);
	CPhidgetTemperatureSensor_setTemperatureChangeTrigger(TemperatureSensor, 1, 0);

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

	Sleep(2000);

	printf("And, closing\n");

	CPhidget_close((CPhidgetHandle )TemperatureSensor);
	CPhidget_delete((CPhidgetHandle )TemperatureSensor);

	return 0;
}

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

