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

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

HANDLE m_EventHandle;

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

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

int __stdcall RFID_ErrorHandler(CPhidgetHandle RFID, 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 RFID_Handler(CPhidgetRFIDHandle RFID, void *userptr, unsigned char *buf)
{
	printf("%x%x%x%x%x%x%x%x%x%x\n", buf[0]/16,buf[0]%16,buf[1]/16,buf[1]%16, buf[2]/16,buf[2]%16, buf[3]/16,buf[3]%16, buf[4]/16,buf[4]%16);
	return 0;
}



int test_rfid()
{
	int NumOutputs, result;

	CPhidgetRFIDHandle RFID = 0;

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

	CPhidgetRFID_create(&RFID);

	CPhidget_set_OnAttach_Handler((CPhidgetHandle)RFID, RFID_AttachHandler, NULL);
	CPhidget_set_OnDetach_Handler((CPhidgetHandle)RFID, RFID_DetachHandler, NULL);
	CPhidget_set_OnError_Handler((CPhidgetHandle)RFID, RFID_ErrorHandler, NULL);
	result = CPhidgetRFID_set_OnTag_Handler(RFID, RFID_Handler, NULL);

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

	display_generic_properties((CPhidgetHandle)RFID);
	CPhidgetRFID_setAntennaOn(RFID, true);

	CPhidgetRFID_getNumOutputs(RFID, &NumOutputs);
	printf("Number of Digital Outputs = %d\n", NumOutputs);

	printf ("And we wait for it to shut down from an error, or 10 second timeout\n");
	for (int i = 0; i<100000; i++) {
		CPhidgetRFID_setLEDOn(RFID, true);
		CPhidgetRFID_setLEDOn(RFID, false);
	}

	CPhidget_close((CPhidgetHandle)RFID);
	CPhidget_delete((CPhidgetHandle)RFID);
	return 0;
}

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

