#include <stdio.h>
#include <conio.h>
#include <windows.h>
#include "COM-HVPSU6.h"

// handle a possible error:
static int Error (int code)
	{
	printf ("%s\n", COM_HVPSU6_ErrorMessage());
	return code;
	}

static char * MakeLED (bool active)
	{
	return active ? "On" : "Off";
	}

int main (int argc, char * argv[])
	{
	if (argc != 2)
		{
		printf ("The number of the COM port must be specified!\n");
		return -1;
		}
	// check the DLL version:
	const WORD DLL_Version = COM_HVPSU6_SW_Version();
	if ((DLL_Version & 0xFF00) != 0x0100)
		{
		printf ("Wrong DLL Version: expected 1.x, found %d.%02d\n",
			DLL_Version / 0x100, DLL_Version & 0xFF);
		return 1;
		}

	// open the port:
	WORD COMNumber;
	sscanf (argv[1], "%hu", &COMNumber);
	if (COM_HVPSU6_Open (COMNumber))
		return Error (2); // handle a possible error

	// get the product number:
	DWORD Number;
	if (COM_HVPSU6_Product_No (Number))
		return Error (10); // handle a possible error
	printf ("Product number: %u\n", Number);

	// get the device state:
	unsigned int DeviceState;
	if (COM_HVPSU6_GetDeviceState (DeviceState))
		return Error (11); // handle a possible error
	printf ("Device state: %04Xh\n", DeviceState);
	printf ("LED Failure: %s\n",
		MakeLED (DeviceState & COM_HVPSU6_LED_FAIL));
	printf ("LED Activated: %s\n",
		MakeLED (DeviceState & COM_HVPSU6_LED_ACT));
	printf ("LED Interlock: %s\n",
		MakeLED (DeviceState & COM_HVPSU6_LED_ILOCK));

	// activate the device:
	if (DeviceState & COM_HVPSU6_ENB_PSU)
		printf ("Device already activated\n");
	else
		{
		if (COM_HVPSU6_SetDeviceState (true, DeviceState))
			return Error (12); // handle a possible error
		if (DeviceState & COM_HVPSU6_ENB_PSU)
			printf ("Device activated\n");
		else
			printf ("Device could not be activated!\n");
		}

	// set the output voltage V1
	double Voltage = -10.23; // V1 = -10.23V
	if (COM_HVPSU6_SetVoltage (COM_HVPSU6_CH_V1, Voltage))
		return Error (13); // handle a possible error
	printf ("V1 set to %.3fV\n", Voltage);

	// get the measured high-voltage values
	printf ("Reading measured voltages...\n");
	printf ("Press any key to stop\n");
	while (true) {
		double Voltage [COM_HVPSU6_VOLT_NUM];
		if (COM_HVPSU6_GetMeasuredVoltages (Voltage))
			return Error (14); // handle a possible error
		printf ("Measured V1: %.3fV\n", Voltage[COM_HVPSU6_CH_V1]);
		if (kbhit()) break;
		Sleep (500);
		}
	getch();
		
	// close the port:
	if (COM_HVPSU6_Close())
		return Error (2); // handle a possible error

	//finish the program:
	return 0;
	}
