// Example.cpp
//
// VISA Header: visa.h (must be included)
// VISA Library: visa32.lib (must be linked with)

#include "stdafx.h"
#include "visa.h"


int main(int argc, char* argv[])
{
    ViStatus status;                        // Error checking
    ViSession defaultRM, instr;             // Communication channels
    ViUInt32 retCount;                      // Return count from string I/O
    ViByte buffer[255];                     // Buffer for string I/O
    int NOP = 21;                           // Number of measurement points
    const int maxCnt = 100;                 // Maximum reading count
    double Data[maxCnt*2];                  // Measurement data array
    double Freq[maxCnt];                    // Frequency array

    if (argc < 2)
    {
        printf("\nUsage: Example <VISA address>\n\n");
        printf("VISA address examples:\n");
        printf("       TCPIP::xxx.xxx.xxx.xxx::5025::SOCKET\n");
        printf("       TCPIP::localhost::5025::SOCKET\n");
        printf("Press ENTER");
        getc(stdin);
        return -1;
    }

    status = viOpenDefaultRM(&defaultRM);

    if (status < VI_SUCCESS)
    {
        printf("Can't initialize VISA\n");
        return -1;
    }

    status = viOpen(defaultRM, argv[1], VI_NULL, VI_NULL, &instr);

    if (status < VI_SUCCESS)
    {
        printf("Can't open VISA address: %s\n", argv[1]);
        return -1;
    }
    //
    // Set timeout 
    //
    viSetAttribute(instr, VI_ATTR_TMO_VALUE, 5000);
    // 
    // Enable terminal character
    //
    viSetAttribute(instr, VI_ATTR_TERMCHAR_EN, VI_TRUE); 	
    viSetAttribute(instr, VI_ATTR_TERMCHAR, '\n');
    //
    // Read ID string from Analyzer
    // 
    viPrintf(instr, "*IDN?\n");
    viRead(instr, buffer, sizeof(buffer), &retCount);
    printf("*IDN? Returned %d bytes: %.*s\n\n", retCount, retCount, buffer);
    //
    // Set up the Analyzer
    // 
    viPrintf(instr, "SYST:PRES\n");
    viPrintf(instr, "SENS:SWE:POIN %d\n", NOP);
    viPrintf(instr, "CALC:PAR1:DEF S21\n");
    viPrintf(instr, "CALC:PAR1:SEL\n");
    viPrintf(instr, "CALC:FORM MLOG\n");
    viPrintf(instr, "SENS:BAND 100\n");
    //
    // Trigger measurement and wait for completion
    //
    viPrintf(instr, ":TRIG:SOUR BUS\n");
    viPrintf(instr, ":TRIG:SING\n");
    viQueryf(instr, "*OPC?\n", "%*t");
    //
    // Read out measurement data
    //
    retCount = maxCnt * 2;
    viQueryf(instr, "CALC:DATA:FDAT?\n", "%,#lf", &retCount, Data);
    retCount = maxCnt;
    viQueryf(instr, "SENS:FREQ:DATA?\n", "%,#lf", &retCount, Freq);
    //
    // Display measurement data
    //
    printf("%20s %20s %20s\n", "Frequency", "Data1", "Data2");
    for (int i = 0; i < NOP; i++)
    {
        printf("%20f %20f %20f\n", Freq[i], Data[i*2], Data[i*2+1]);
    }

    status = viClose(instr);
    status = viClose(defaultRM);
    printf("Press ENTER");
    getc(stdin);
    return 0;
}

