#ifdef _WIN32
#include <conio.h>
#endif
#include <iostream>
#include "visa.h"

using namespace std;

int main()
{
	char address[192], buff[128];
	ViStatus status;
	ViSession rm, rsrc;
	ViRsrc deviceAddress;

	// Create resource manager
	status = viOpenDefaultRM(&rm);
	// Set locale for multibyte charsets
#ifdef _WIN32
	setlocale(LC_ALL, "Russian");
#endif
	// Set device address
	std::cout << "Enter device address: ";
	scanf("%s", buff);
	// Create address in SCPI-specific format
	sprintf(address, "TCPIP::%s::8888::SOCKET::GNM", buff);
	deviceAddress = address;

	// Open connection
	if ( (status = viOpen(rm, deviceAddress, VI_EXCLUSIVE_LOCK, 100000, &rsrc)) == VI_SUCCESS )
	{
		std::cout << "Connected to " << (char*)deviceAddress << std::endl;
		// Set operation timeout (ms)
		viSetAttribute(rsrc, VI_ATTR_TMO_VALUE, 3000);
		// Get identification string of device
		viQueryf(rsrc, (ViString)"*IDN?\n", (ViString)"%T", buff);
		std::cout << "IDN: " << buff << std::endl;

		// Set frequency sweep mode
		viPrintf(rsrc, (ViString)"SOURce:FREQuency:MODE SWEEp\n");
		// Set frequency range values
		viPrintf(rsrc, (ViString)"SOURce:FREQuency:STARt 10MHz;STOP 20GHz\n");
		// Set points count
		viPrintf(rsrc, (ViString)"SOURce:SWEEp:POINts 501\n");
		// Set power level value
		viPrintf(rsrc, (ViString)"SOURce:POWer:LEVel -10\n");
		// Set external trigger IN
		//viPrintf(rsrc,(ViString)"TRIGger:SEQuence:SOURce EXTernal\n");
		// Set trigger IN action (next point)
		viPrintf(rsrc, (ViString)"SOURce:LIST:MODE MANual\n");
		//	Set trigger OUT action (PLL ready)
		viPrintf(rsrc, (ViString)"TRIGger:AUXiliary:INTerval POINt\n");
		//	Enable trigger OUT
		viPrintf(rsrc, (ViString)"TRIGger:AUXiliary ON\n");
		// Set reference generator to internal source
		viPrintf(rsrc, (ViString)"ROSCillator:SOURce INTernal\n");
		// Set triggered mode
		viPrintf(rsrc, (ViString)"INITiate:CONTinuous OFF\n");
		// Turn ON RF output
		viPrintf(rsrc, (ViString)"OUTPut:STATe ON\n");
		// Check errors
		status = viQueryf(rsrc, (ViString)"SYSTem:ERRor?\n", (ViString)"%T", buff);
		std::cout << "Error: " << buff << std::endl;

		// Set trigger
		viPrintf(rsrc, (ViString)"INITiate:IMMediate\n");

		// Wait for measurement complete
		viPrintf(rsrc, (ViString) "*OPC?\n");
		status = viScanf(rsrc, (ViString)"%T", buff);
		// Waiting for user action
		std::cout << "Press any key to disconnect..." << std::endl;
#ifdef _WIN32
		_getch(stdin);
#else
		getc(stdin);
#endif

		// Turn OFF RF output
		viPrintf(rsrc, (ViString)"OUTPut:STATe OFF\n");
		// Check Errors
		status = viQueryf(rsrc, (ViString)"SYSTem:ERRor?\n", (ViString)"%T", buff);
		// Close session
		viClose(rsrc);
	}
	else
	{
		viStatusDesc(rsrc, status, buff);
		std::cout << "Connection error: " << buff << std::endl;
	}
	// Close resource manager
	viClose(rm);
}
