// ScpiExample.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

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

#include <string>       // std::string
#include <iostream>     // std::cout
#include <sstream>      // std::stringstream
#include <fstream>
#include <windows.h>


///
///	G7M SCPI programming sample
///
int _tmain(int argc, _TCHAR* argv[])
{
	char address[128], buff[128];
	int status;
	ViSession rm, rsrc;
	ViRsrc deviceAddress;

	using namespace std;

	// 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::5025::SOCKET", 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;
		// Get identification string of device
		viQueryf(rsrc, "*IDN?\n", "%T", buff);
		std::cout << "IDN: " << buff;

		viPrintf(rsrc, "*RST\n");
		Sleep(500);

		// Waiting for device answer
		viQueryf(rsrc, "*OPC?\n", "%T", buff);

		// Set the device settings
		viPrintf(rsrc, "SOURce:FREQuency:CW 500000000\n");

		viPrintf(rsrc, "SOURce:POWer:LEVel:ATTenuation:AUTO OFF\n");
		viPrintf(rsrc, "SOURce:POWer:LEVel:ATTenuation 10\n");
		viPrintf(rsrc, "SOURce:POWer:STARt -30\n");
		viPrintf(rsrc, "SOURce:POWer:STOP 0\n");
		viPrintf(rsrc, "SOURce:SWEep:POINts 10\n");

		viPrintf(rsrc, "SOURce:POWer:MODE SWEep\n");
		viPrintf(rsrc, "SOURce:FREQuency:MODE FIXed\n");
		viPrintf(rsrc, "SOURce:LIST:MODE AUTO\n");

		viPrintf(rsrc, "TRIGger:SEQuence:SOURce IMMediate\n");
		viPrintf(rsrc, "INITiate:CONTinuous ON\n");
		viPrintf(rsrc, "TRIGger:SEQuence:Source IMMediate\n");
		viPrintf(rsrc, "INITiate:IMMediate\n");

		// Turn ON the device output power
		viPrintf(rsrc, "OUTPut:STATe ON\n");

		viQueryf(rsrc, "SYSTem:ERRor?\n", "%T", buff);
		std::cout << "SYSTem:ERRor? " << buff;
		// Waiting for user action
		std::cout << "Press any key to close connection..." << std::endl;
		getch();

		// Close session
		viClose(rsrc);
	}
	else
	{
		viStatusDesc(rsrc, status, buff);
		std::cout << "Connection error: " << buff << std::endl;
	}
	// Close resource manager
	viClose(rm);

	// Waiting for user action
	std::cout << "Press any key to exit..." << std::endl;
	getch();

	return 0;
}
