% Configure compilation environment
% setenv('MW_MINGW64_LOC','D:\msys64\ucrt64');
% mex -setup C++

filePath = fullfile(pwd, 'htra_api_mat');  

% Check if the folder exists; if not, create it
if ~exist(filePath, 'dir')
    run('htra_api.m');
    filePath = fullfile(pwd, 'htra_api_mat');  
end

% Load htra_api.dll
if not(libisloaded('htra_api.dll'))   
    loadlibrary('.\htra_api\htra_api.dll','.\htra_api\htra_api.h'); % Ensure correct paths for .dll and .h files
end

libfunctions('htra_api'); % View all functions in the API

% Open device
Device = libpointer; % Create Device pointer
DevNum = 0;
Status = 0;

load(fullfile(filePath, 'BootProfile.mat'));  % Directly load BootProfile_TypeDef structure
load(fullfile(filePath, 'BootInfo.mat'));  % Directly load BootInfo_TypeDef structure

BootProfile.DevicePowerSupply = 0;

IS_USB = 1;  % Default to USB device; set to 0 for Ethernet device

if IS_USB == 1
    % Configure USB interface
    BootProfile.PhysicalInterface = 0;
else
    % Configure Ethernet interface
    BootProfile.PhysicalInterface = 3;
    BootProfile.ETH_IPVersion = 0;
    BootProfile.ETH_RemotePort = 5000;
    BootProfile.ETH_ReadTimeOut = 5000;
    BootProfile.ETH_IPAddress = [192, 168, 1, 100];
end

% Call Device_Open function
Status = calllib('htra_api', 'Device_Open', Device, DevNum, BootProfile, BootInfo);

if Status == 0
    get(BootProfile); % Print BootProfile values
    get(BootInfo); % Print BootInfo values    
    fprintf('Device successfully opened\n');
else
    % Device opening failed; handle different error statuses
    switch Status
        case -1
            fprintf('Error - Check the power supply of the device, the connection of the data cable, and ensure the driver is installed correctly\n');
        case -3
            fprintf('Error - RF calibration file is missing; please copy the RF calibration file to the CalFile folder\n');
        case -4
            fprintf('Error - IF calibration file is missing; please copy the IF calibration file to the CalFile folder\n');
        case -5
            fprintf('Error - Profile is missing; please copy the profile to the CalFile folder\n');
        case -6
            fprintf('Error - The device spec file is missing; please copy the device spec file to the CalFile folder\n');
        otherwise
            fprintf('Device turn on failed: Returns another error Status = %d', Status);
    end

    % Return error status value
    return;
end

load(fullfile(filePath, 'SWP_Profile.mat'));  % Directly load SWP_Profile_TypeDef structure

% Define SWP_ProfileIn and SWP_ProfileOut pointers
SWP_ProfileIn = SWP_Profile;
SWP_ProfileOut = SWP_Profile;

% Call SWP_ProfileDeInit function
Status = calllib('htra_api', 'SWP_ProfileDeInit', Device, SWP_ProfileIn);
get(SWP_ProfileIn); % Print SWP_ProfileIn_p values

% Modify certain parameters of the SWP_ProfileIn structure
SWP_ProfileIn.StartFreq_Hz = 9e3; % Configure start frequency
SWP_ProfileIn.StopFreq_Hz = 6.3e9;  % Configure stop frequency
SWP_ProfileIn.RefLevel_dBm = 0;	  % Configure reference level
SWP_ProfileIn.RBWMode = 0;        % Configure RBWMode
SWP_ProfileIn.RBW_Hz = 300e3;     % Configure RBW

load(fullfile(filePath, 'TraceInfo.mat'));   % Directly load SWP_TraceInfo_TypeDef structure

% Call SWP_Configuration function
Status = calllib('htra_api', 'SWP_Configuration', Device, SWP_ProfileIn, SWP_ProfileOut, TraceInfo);

% If configuration is successful (Status == 0)
if Status == 0
    get(SWP_ProfileOut); % Print SWP_ProfileOut values
    get(TraceInfo); % Print TraceInfo values
    fprintf('Configuration successfully\n');
else
    % If call fails, print error message and close device
    fprintf('SWP_Configuration Call error Status = %d\n', Status);
    Device_Close(Device); 
    
    % Return 0 to end function execution
    return;
end

% Create Frequency array to store SWP spectrum data
% Create PowerSpec_dBm array to store SWP amplitude data
Frequency = double(1:TraceInfo.FullsweepTracePoints);
PowerSpec_dBm = single(1:TraceInfo.FullsweepTracePoints);

% Convert C language parameters to MATLAB types
Frequency_p = libpointer('doublePtr', Frequency);
PowerSpec_dBm_p = libpointer('singlePtr', PowerSpec_dBm);

% The device's entire spectrum is assembled from multiple frames; 
% this parameter returns the current frame's index in the assembly process.
HopIndex = int32(0);
% Indicates the current frame's index among all frames, 
% used to identify the position of the current frame among all frames.
FrameIndex = int32(0);
% Create pointer HopIndex_p.
HopIndex_p = libpointer('int32Ptr', HopIndex);
% Create pointer FrameIndex_p.
FrameIndex_p = libpointer('int32Ptr', FrameIndex);

load(fullfile(filePath, 'MeasAuxInfo.mat'));  % Directly load MeasAuxInfo_TypeDef structure

% Acquire n SWP data sets
n = 10000; 
for t = 1:n
    % TraceInfo.TotalHops represents the number of frames under the current configuration;
    % therefore, loop TraceInfo.TotalHops times calling SWP_GetPartialSweep to obtain a complete trace.
    for i = 1:TraceInfo.TotalHops 
        Status = calllib('htra_api', 'SWP_GetPartialSweep', Device, Frequency_p + (i-1) * TraceInfo.PartialsweepTracePoints, PowerSpec_dBm_p + (i-1) * TraceInfo.PartialsweepTracePoints, HopIndex_p, FrameIndex_p, MeasAuxInfo);     
        if Status ~= 0
           % If call fails, print error message and close device
           fprintf('SWP_GetPartialSweep Call error Status = %d\n', Status);
           % Return 0 to end function execution
           return;
        end
    end
    
    % Plot SWP spectrum
    plot(Frequency_p.Value, PowerSpec_dBm_p.Value);
    ylim([-130, SWP_ProfileOut.RefLevel_dBm]);
    xlim([min(Frequency_p.Value), max(Frequency_p.Value)]);
    pause(0.01);
end

% Call Device_Close function
Status = calllib('htra_api', 'Device_Close', Device);

clear all;

% Unload the library file
unloadlibrary('htra_api');   
disp('Uninstall complete'); 
 







