////////////////////////////////////////////////////////////////////////////
// ZAO "NPF Micran" 28.10.2011
// This is an example for G7M generator with SCPI commands
// C++ example.
// Frequency sweep with fixed power
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"

#include "visa.h"
#include <conio.h>
#include <iostream>
#include <stdio.h>
#include <locale>

///
///	G7M SCPI programming sample
///
int _tmain(int argc, _TCHAR* argv[])
{	
	char address[128], buff[128];
	ViStatus status;
	ViSession rm, rsrc;
	ViRsrc deviceAddress;
	
	// Create resource manager
	viOpenDefaultRM(&rm);	
	// Set locale for multibyte charsets
	setlocale(LC_ALL, "Russian");
	// 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, 5000, &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, "*IDN?\n", "%T", buff);
		std::cout << "IDN: " << buff << std::endl;

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

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

