// 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 WeightSensor, void *userptr)
{
	SetEvent(m_EventHandle);
	printf("Attach handler ran!\n");
	return 0;
}

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

int __stdcall ErrorHandler(CPhidgetHandle WeightSensor, 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_WeightChangeHandler(CPhidgetWeightSensorHandle TMP, void *userptr, double Value)
{
	printf("Weight is %4f\n", Value);
	return 0;
}

int test_tempsensor()
{
	int result;

	CPhidgetWeightSensorHandle WeightSensor = 0;

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

	CPhidgetWeightSensor_create(&WeightSensor);

	CPhidget_set_OnAttach_Handler((CPhidgetHandle)WeightSensor, AttachHandler, NULL);
	CPhidget_set_OnDetach_Handler((CPhidgetHandle)WeightSensor, DetachHandler, NULL);
	CPhidget_set_OnError_Handler((CPhidgetHandle)WeightSensor, ErrorHandler, NULL);
	CPhidgetWeightSensor_set_OnWeightChange_Handler(WeightSensor, TMP_WeightChangeHandler, NULL);

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

	display_generic_properties((CPhidgetHandle)WeightSensor);

	CPhidgetWeightSensor_setWeightChangeTrigger(WeightSensor, 0.1);

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

	Sleep(2000);

	printf("And, closing\n");

	CPhidget_close((CPhidgetHandle )WeightSensor);
	CPhidget_delete((CPhidgetHandle )WeightSensor);

	return 0;
}

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

