////////////////////////////////////////////////////////////////////////////
// AO "NPF Micran" 04.10.2016
// This is an example for PLS06
// Example 1.
// PLS SCPI programming Average mode
////////////////////////////////////////////////////////////////////////////

#include "stdafx.h"

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

///
///	PLS SCPI programming Average mode
///
int _tmain(int argc, _TCHAR* argv[])
{	
	char address[128], PID[64], buff[64];
	int status;
	ViSession rm, rsrc;
	ViRsrc deviceAddress;

	viOpenDefaultRM(&rm);	        //	Create resource manager
	setlocale(LC_ALL, "Russian");	//	Support Russian charset

	std::cout << "Enter PLS serial number: ";
	scanf("%s", buff);
	std::cout << "Select a model (1 - PLS-06, 2 - PLS-26, 3 - PLS-50):";
	scanf("%s", PID);
	PID[0] -= 1; // convert selected variant to last PID's digit
	sprintf(address, "USB0::0x2b70::0x002%s::%s::0::INSTR", PID, buff); // use PIDs: 0x0020 for PLS-06, 0x0021 for PLS-26, 0x0022 for PLS-50
	deviceAddress = address;

	// Open conection
	status = viOpen(rm, deviceAddress, VI_EXCLUSIVE_LOCK, 5000, &rsrc);
	if (status != VI_SUCCESS)
	{
		viStatusDesc(rm, status, buff); // Get status description
		std::cout << "Connection error: " << buff << std::endl;
		// Close resource manager
		viClose(rm);	
		std::cout << "Press any key to exit..." << std::endl;
		getch();	// Waiting for user response
		return 0;
	}

	// Set timeout
	viSetAttribute(rsrc, VI_ATTR_TMO_VALUE, 5000);

	// Send command "Reset"  (all settings to «default»)
	status = viPrintf(rsrc, "*RST\n");

	// Read ID device information
	std::cout << "IDN: ";
	status = viQueryf(rsrc, "*IDN?\n", "%T", buff);
	std::cout << buff;

	// Set to Average mode
	status = viPrintf(rsrc, "SENSe:DETector:FUNCtion AVERage\n");

	// Set manual averaging
	status = viPrintf(rsrc, "SENSe:AVERage:COUNt:AUTO ON\n");
	status = viPrintf(rsrc, "SENSe:AVERage:COUNt 10\n");

	// Set frequency
	status = viPrintf(rsrc, "SENSe:FREQuency 50MHz\n");

	// Get measurement units
	status = viQueryf(rsrc,"UNIT:POWer?\n", "%T", buff);
	std::cout << "units " << buff;

	// Set triggered measurements
	viPrintf(rsrc, ":INITiate:CONTinuous OFF\n");

	// Read error
	status = viQueryf(rsrc, "SYSTem:ERRor?\n", "%T", buff);
	std::cout << "Error: "<< buff;

	// Measure and get average result 5 times 
	for (int i = 0; i < 5; i++)
	{
		status = viPrintf(rsrc, ":INITiate:IMMediate\n");
		status = viPrintf(rsrc, "*OPC?\n");
		do
		{
			status = viScanf(rsrc, "%T", buff);
		}
		while (status == VI_ERROR_TMO);
		std::cout << "power = ";
		status = viQueryf(rsrc, "FETCh:SCALar:POWer:AC?\n", "%T", buff);
		std::cout << buff;
	}
	
	// Read error
	status = viQueryf(rsrc, "SYSTem:ERRor?\n", "%T", buff);
	std::cout << "Error: "<< buff;

	// Close session
	viClose(rsrc);
	
	// Close resource manager
	viClose(rm);
	
	std::cout << "Press any key to exit..." << std::endl;
	getch();	// Waiting for user response
	
	return 0;
}

