% IMPORTANT!
% Before running this script,
% The socket must be turned on by going to "system" -> "misc setup" 
% -> "network remote control settings" -> "socket server (on)" in the
% VNA software

nl = 10; % this is the decimal value of a new line character ('\n')

% Connect to VNA
try
    vna = tcpclient("127.0.0.1", 5025, "Timeout", 20, "ConnectTimeout", 5);
catch ME
    disp('Error establishing TCP connection.');
    disp('Check that the TCP server is on.');
    return
end

% Get and display the instrument name, serial number, etc.
write(vna, [uint8('*IDN?'), nl]);
disp(char(VNAread(vna)));

% Preset the VNA
write(vna, [uint8('SYSTem:PRESet'), nl]);

% Set VNA trigger to BUS trigger
write(vna, [uint8('TRIG:SOUR BUS'), nl]);
write(vna, [uint8('*OPC?'), nl]); % use *OPC? command to wait for the VNA settings to finish
opc_response = VNAread(vna); % *OPC? response must be read

% Trigger the VNA once
write(vna, [uint8('TRIG:SING'), nl]);
write(vna, [uint8('*OPC?'), nl]); % use *OPC? command to wait for the sweep to finish
opc_response = VNAread(vna);

% Read frequency data into array
write(vna, [uint8('SENSe1:FREQuency:DATA?'), nl]);
Freq = VNAread(vna);
write(vna, [uint8('*OPC?'), nl]); % use *OPC? command to wait for the sweep to finish
opc_response = VNAread(vna);
Freq = char(Freq);
Freq = str2num(Freq);
disp(Freq);

% Read measurement data into array
write(vna, [uint8('CALC1:DATA:FDAT?'), nl]);
data = VNAread(vna);
data = char(data);
data = str2num(data);
data = data(1:2:end); % skip every other element in the array
                      % for example, if measurement data is in logmag
                      % format, every other element in the array will be 0
disp(data);

% Save trace data into a csv file
% User should change test1.csv into desired file name
write(vna, [uint8(char("MMEMory:STORe:FDATa "+ pwd + "\test1.csv")),nl]);

% return to internal trigger
write(vna, [uint8('TRIG:SOUR INT'), nl]);

% read from VNA through TCP connection
% blocks until data read is not empty
% reads until new line character is received
function query_response = VNAread(app_vna)
    query_response = '';
    while true
        partial_query_response = read(app_vna);
        if(isempty(partial_query_response)~=1)
            last_index = length(partial_query_response);
            query_response = strcat(query_response, partial_query_response);
            if (partial_query_response(last_index) == 10) % 10 is newline
                break;
            end
        end
    end
end

