////////////////////////////////////////////////////////////////////////////
// AO "NPF Micran" 26.04.2021
// This is an example for P2M 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::SNM", 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, "SENSe:FREQuency:MODE SWEEp\n");
		// Set frequency range values
		viPrintf(rsrc, "SENSe:FREQuency:STARt 10MHz;STOP 20GHz\n");
		// Set points count
		viPrintf(rsrc, "SENSe:SWEEp:POINts 501\n");
		// Set power level value
		viPrintf(rsrc, "SOURce:POWer:LEVel -10\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;
		status = viQueryf(rsrc, "*ESR?\n", "%T", buff);
		std::cout << "Status Register (ESR): " << buff << std::endl;
		
		// Set trigger
		viPrintf(rsrc, "INITiate:IMMediate\n");
	
		// Wait for measurement complete
		viPrintf(rsrc, "*OPC?\n");
		status = viScanf(rsrc, "%T", buff);	
		status = viQueryf(rsrc, "*ESR?\n", "%T", buff);
		std::cout << "Status Register (ESR): " << buff << std::endl;
		// 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;
}

