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

#include "COM-DIO.h"


int main()
	{
	// define the port number:
	unsigned short PortNum = 0;

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

	printf ("Press 'o' to set output data, "
					"'i' to get identification data, "
					"or 'Esc' to stop\n");

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

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

		if (Result < 0) // handle a possible error
			printf ("%s\n", COM_DIO_ErrorMessage (PortNum));

		if (Result == 0) // if data is ready, print it
			printf ("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: ");
			scanf ("%X", &Data);
			if (COM_DIO_SetOutput (PortNum, Data))
				printf ("%s\n", COM_DIO_ErrorMessage (PortNum));
			}

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

			// get firmware date:
			char DateString [20];
			if (COM_DIO_FW_Date (PortNum, DateString))
				printf ("%s\n", COM_DIO_ErrorMessage (PortNum));
			else
				printf ("Firmware date: %s\n", DateString);

			// get product identification:
			char IDString [20];
			if (COM_DIO_prod_ID (PortNum, IDString))
				printf ("%s\n", COM_DIO_ErrorMessage (PortNum));
			else
				printf ("Product identification: %s\n", IDString);

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

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

	//finish the program:
	return 0;
	}

