#include <stdio.h>
#include <conio.h>
#include <windows.h>

#include "COM-RFID.h"

int main()
	{
	// check the DLL version:
	if ((COM_RFID_Version() & 0xFF00) != 0x0100)
		{
		printf ("Wrong DLL Version: expected 1.x, found %d.%02d\n",
			COM_RFID_Version() / 0x100, COM_RFID_Version() & 0xFF);
		return -1;
		}

	// define the port number:
	unsigned short PortNum = 0;

	// open the port, attach it to COM1:
	if (COM_RFID_Open (PortNum, 1))
		{
		// handle a possible error:
		printf ("%s\n", COM_RFID_ErrorMessage (PortNum));
		return 1;
		}

	// Set automatic transmission of digital input state:
	if (COM_RFID_AutoDigitalInput (PortNum))
		printf ("%s\n", COM_RFID_ErrorMessage (PortNum));

	// main program loop:
	while (true)
		{
		// check for automatic data:
		WORD CommandID;
		const int Result =
			COM_RFID_CheckAutoInput (PortNum, CommandID);

		if (Result < 0) // handle possible errors
			printf ("%s\n", COM_RFID_ErrorMessage (PortNum));
		if (Result == 1) printf ("Unexpected command received\n");

		if (Result == 0) // if data is ready, print it
			{
			if (CommandID & AUTO_DIN) {
				WORD Data;
				if (COM_RFID_GetLastDigitalInput (PortNum, Data))
					printf ("%s\n", COM_RFID_ErrorMessage (PortNum));
				else
					printf ("Digital input data received: "
						"%d (%02Xh)\n", Data, Data);
				}
			}

		if (kbhit() == 0) continue; // repeat if no key is pressed

		const int Key = getch(); // read the pressed key

		// set the output state:
		if (Key == 'o')
			{
			printf ("Enter new hexadecimal output state: ");
			WORD Data; scanf ("%X", &Data);
			if (COM_RFID_SetDigitalOutput (PortNum, Data))
				printf ("%s\n", COM_RFID_ErrorMessage (PortNum));
			}

		// get identification data:
		if (Key == 'i')
			{
			// get firmware version:
			WORD Version;
			if (COM_RFID_FW_Ver (PortNum, Version))
				printf ("%s\n", COM_RFID_ErrorMessage (PortNum));
			else
				printf ("Firmware version: %d.%02d\n",
					Version / 0x100, Version & 0xFF);

			// get firmware date:
			char DateString [16];
			if (COM_RFID_FW_Date (PortNum, DateString))
				printf ("%s\n", COM_RFID_ErrorMessage (PortNum));
			else
				printf ("Firmware date: %s\n", DateString);

			// get product identification:
			char IDString [81];
			if (COM_RFID_Prod_ID (PortNum, IDString))
				printf ("%s\n", COM_RFID_ErrorMessage (PortNum));
			else
				printf ("Product identification: %s\n", IDString);

			// get product number:
			DWORD Number;
			if (COM_RFID_Prod_No (PortNum, Number))
				printf ("%s\n", COM_RFID_ErrorMessage (PortNum));
			else
				printf ("Product number: %d\n", Number);
			}

		// stop on 'Esc':
		if (Key == 27)
			break;
		}

	//finish the program:
	return 0;
	}
