%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  MATLAB programming example for Copper Mountain VNA
%
%  Version:  January 2016
%
%  Author:  CMT support
%           support@coppermountaintech.com
%
%  Support:  support@coppermountaintech.com
%  06/10/2015 Update syntax, validity of use_center_span
%  06/19/2015 Change into script instead of function, prompt for input.
%  07/07/2015 Change power level setting command
%  09/28/2015 Update to increase the readability of the program
%  01/11/2016 Modified to use new COM server names (RVNA, TRVNA, S2VNA, and S4VNA)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%     prompt for user's input:
% 	instrument,...            % 'S5048','S7530','Planar804','Planar304',
%     ...                     % 'S8081' (Planar808/1), 'R54', 'R140',
%     ...                     % ['TR1300'], 'TR5048', or 'TR7530'
% 	use_center_and_span,...   % [false] = use fstart/fstop, true = use center/span
%     f1_hz,...               % [fstart=400e6] or center, as per above, in Hz
%     f2_hz,...               % [fstop=600e6] or span, as per above, in Hz
%     num_points,...          % [401] number of measurement points
%     power_level_dbm,...     % [0] dBm power level (ignored for R54/140)
%     parameter,...           % ['S21'], 'S11', 'S12', etc. R54/140 must use
%     ...                     % 'S11'; TR devices must use 'S11' or 'S21';
%     ...                     % Ports 3 and 4 available for S8081 only
%     format,...              % ['mlog'] or 'phase'
%     time_per_iter_sec,...   % [1.0] seconds per measurement interval
%     num_iter,...            % [10] number of times to loop
%     num_iter_to_store...    % [2] number of function iterations to store
%

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %
    % Ask user to choose the instrument
    %
    % Default parameters to  instrument = 'S2VNA'

instrchoice = menu('Please choose your instrument','S5048','S7530','Planar804','Planar304','S8081 (Planar808/1)','R54','R140','TR1300','TR5048','TR7530');

switch instrchoice
    case 1
        instrument = 'S2VNA'; % S5048
    case 2
        instrument = 'S2VNA'; % S7530
    case 3
        instrument = 'S2VNA'; % Planar804
    case 4
        instrument = 'S2VNA'; % Planar304
    case 5
        instrument = 'S4VNA'; % S8081
    case 6
        instrument = 'RVNA';  % R54
    case 7
        instrument = 'RVNA';  % R140
    case 8
        instrument = 'TRVNA'; % TR1300
    case 9
        instrument = 'TRVNA'; % TR5048
    case 10
        instrument = 'TRVNA'; % TR7530
    otherwise
        instrument = 'S2VNA'; % Planar804
end

% ask user to choose user span type.

freqtype = menu('use_center_and_span','Start and stop frequency','Center and span frequency');
if(freqtype == 1)
    use_center_and_span = false;
else
    use_center_and_span = true;
end

%prompt for freq, num of points and power level
temp1 = inputdlg({'Enter the start/center frequency (Hz)','Enter the stop/center frequency (Hz)','Enter the number of points','Enter Power level (dbm)'},'Input',4,{'3e6','6e9','201','0'});
f1_hz = str2num(temp1{1});
f2_hz = str2num(temp1{2});
num_points = str2num(temp1{3});
power_level_dbm = str2num(temp1{4});

% prompt for measurement parameter
% default to S11
parchoice = menu('Please choose the parameter','S11','S21','S22','S12','A','B','R1','R2');

switch parchoice
    case 1
        parameter = 'S11';
    case 2
        parameter = 'S21';
    case 3
        parameter = 'S22';
    case 4
        parameter = 'S12';
    case 5
        parameter = 'A';
    case 6
        parameter = 'B';
    case 7
        parameter = 'R1';
    case 8
        parameter = 'R2';
    otherwise
        parameter = 'S11';
end

% prompt for format
% default to Log magnitude
formatchoice = menu('Please format type','Logarithmic magnitude','Phase','Smith chart format (R + jX)','Group delay time','Polar format (Real/Imag)');

switch formatchoice
    case 1
        format = 'MLOGarithmic';
    case 2
        format = 'PHASe';
    case 3
        format = 'SMITh';
    case 4
        format = 'GDELay';
    case 5
        format = 'POLar';
    otherwise
        format = 'MLOGarithmic';
end


%prompt for time per iteration, number of iteration and number of iteration to store
temp2 = inputdlg({'Enter time per iteration (sec)','Enter number of iteration','Enter number of iteration to store'},'Input',3,{'1','10','0'});
time_per_iter_sec = str2num(temp2{1});
num_iter = str2num(temp2{2});
num_iter_to_store = str2num(temp2{3});

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  Example code
%

%Instantiate COM client
try
    app=actxserver([instrument,'.application']);
catch ME
    disp('Error establishing COM server connection.');
    disp('Check that the VNA application COM server was registered');
    disp('at the time of software installation.');
    disp('This is described in the VNA programming manual.');
    return
end

%Wait up to 20 seconds for instrument to be ready
ready = 0;
count = 0;
while ~ready
    ready = app.ready;
    if count>20,
        disp('Error, instrument not ready.');
        disp('Check that VNA is powered on and connected to PC.');
        disp('The status Ready should appear in the lower right');
        disp('corner of the VNA application window.');

        return
    end;

    %Check every so often whether the instrument is ready yet
    pause(1)
    count = count + 1;
end

%Get and echo the instrument name, serial number, etc.
%
%  [This is a simple example of getting a property in MATLAB.]
%
disp(sprintf(app.name));

%Set the instrument to a Preset state
%
%  [This is an example of executing an ActiveX "method" in MATLAB.]
%
app.scpi.system.invoke('preset');

%Configure the stimulus
if use_center_and_span
    app.scpi.get('sense',1).frequency.set('center',f1_hz);
    app.scpi.get('sense',1).frequency.set('span',f2_hz);
else

    app.scpi.get('sense',1).frequency.set('start',f1_hz);
    app.scpi.get('sense',1).frequency.set('stop',f2_hz);
end

app.scpi.get('sense',1).sweep.set('points',num_points);

if(instrument(1) ~= 'R')
    app.SCPI.get('SOURce',1).POWer.LEVel.IMMediate.set('AMPLitude',power_level_dbm);
end

%Configure the measurement type

app.scpi.get('calculate',1).get('parameter',1).set('define',parameter);
app.scpi.get('calculate',1).selected.set('format',format);
app.scpi.trigger.sequence.set('source','bus');

tic;
for iter = 1:num_iter

    %Execute the measurement
    app.scpi.trigger.sequence.invoke('single');

    Y = app.scpi.get('calculate',1).selecte.data.fdata;
    Y = Y(1:2:end);

    F = app.scpi.get('sense',1).frequency.data;

    figure(1);
    plot(F,Y);

    if iter<=num_iter_to_store
        app.scpi.mmemory.store.set('image',[num2str(iter),'.png']);
        app.scpi.mmemory.store.set('fdata',[num2str(iter),'.csv']);
    end

    while(toc<iter*time_per_iter_sec)
        pause(0.01);
    end

end
