//
// Copyright (C) Dave Roberts G8KBB 2004
//
// This is a simple demonstration of using
// the VNADevice class via vnadll.dll
// to performa raw write to ports A and B

#include "stdio.h"

#include "stdafx.h"
#include "objbase.h"
#include "iostream.h"

#include "vnaio.h"


void print_last_error_message(void);

// Command needs to be able to find the DLL!!!!!
// Program is a win32 CONSOLE application that
// takes 2 parameters - hex values for ports A and B
// Typical usage 'vnaraw 5A A5'
// writes 0x5A (01011010 binary) to port A
// and 0xA5 (10100101 binary) to port B
// Reading the VNA will show this (read twice due to comms buffering)
// with the exception of the input port bits (bit 7)

int main( int argc, char *argv[])
{
	VNA_TXBUFFER tx_data;
	VNADevice* VNA;				// Vector Network Analyzer hardware object
	long ltemp;
	char *tmpptr;

	if( argc != 3 )
	{
		printf("Error: Usage is 'vnaraw portA portB' where Port values are 2 hex digits\n");
		return false;
	}

	VNA = new VNADevice;

	if (VNA->get_State() != 1 )
	{
		printf("Sorry - cannot open VNA interface: ");
		print_last_error_message();
		delete VNA;
		return true;
	}

	ltemp = strtol( argv[1], &tmpptr, 16);
	tx_data.raw.portA = unsigned char(ltemp);
	ltemp = strtol( argv[2], &tmpptr, 16);
	tx_data.raw.portB = unsigned char(ltemp);

	printf("Setting Port A to 0x%02x, Port B to 0x%02x\n", tx_data.raw.portA, tx_data.raw.portB);
	tx_data.raw.command_code = 0x5A;
	tx_data.raw.flags = 0xC0;

	if( VNA->Write( &tx_data, sizeof(tx_data.raw) ) == false )
	{
		print_last_error_message();
	}
	delete VNA;
	return true;
}

// print error message if it fails

void print_last_error_message()
{
	LPVOID lpMsgBuf;
	DWORD LastError;

	LastError = GetLastError();
	printf("IO Error code %ld\n", LastError );
	FormatMessage( 
		FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
	    NULL,
		LastError,
	    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
		(LPTSTR) &lpMsgBuf,
		0,
		NULL 
	);
	printf("IO Error message: %s\n",lpMsgBuf);
	// Free the buffer.
	LocalFree( lpMsgBuf );
}
