% 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 the folder
if ~exist(filePath, 'dir')
    mkdir(filePath);  % Create the target folder
    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 the correct paths for .dll and .h files
end

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

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

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

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

if IS_USB == 1
    % Configure USB interface
    BootProfile.PhysicalInterface = 0;
else
    % Configure ETH 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\n');
else
    % Device open 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 check that 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

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

% Define SWP_ProfileIn pointer and SWP_ProfileOut pointer
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 values

% Modify some parameters of the SWP_ProfileIn structure
SWP_ProfileIn.StartFreq_Hz = 9e3; % Configure start frequency
SWP_ProfileIn.StopFreq_Hz = 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

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

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

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

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

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

% The entire spectrum of the device is made by stitching multiple frames, 
% this parameter returns the sequence number of the current frame in the stitching process.
HopIndex = int32(0);
% Indicates the index of the current frame among all frames.
FrameIndex = int32(0);
% Create HopIndex pointer
HopIndex_p = libpointer('int32Ptr', HopIndex);
% Create FrameIndex pointer
FrameIndex_p = libpointer('int32Ptr', FrameIndex);

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

% Get n times SWP data
n = 100; 
for t = 1:n
    % TraceInfo.TotalHops represents the number of frames under the current configuration,
    % so call SWP_GetPartialSweep TraceInfo.TotalHops times to get the full 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 the call fails, print error info and close the device
            fprintf('SWP_GetPartialSweep Call error Status = %d\n', Status);
            % Return 0, end function execution
            return;
        end
    end
    
    % Find the maximum value and its index in the current array
    [maxPowerValue, maxIndex] = max(PowerSpec_dBm_p.Value);  
    
    % Plot the 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);
    
    % Print the frequency and power corresponding to the maximum power
    fprintf('Maximum frequency: %.2f Hz, maximum power: %.2f dBm\n', Frequency_p.Value(maxIndex), maxPowerValue);

    % Delay for five minutes
    pause(300); % 300 seconds
end

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

clear all;

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