% 配置编译环境
% setenv('MW_MINGW64_LOC','D:\msys64\ucrt64');
% mex -setup C++

filePath = fullfile(pwd, 'htra_api_mat');  

% 检查文件夹是否存在，如果不存在，创建文件夹
if ~exist(filePath, 'dir')
    run('htra_api.m');
    filePath = fullfile(pwd, 'htra_api_mat');  
end

%加载htra_api.dll
if not(libisloaded('htra_api.dll'))   
    loadlibrary('.\htra_api\htra_api.dll','.\htra_api\htra_api.h'); %.dll和.h的文件路径一定要注意
end

libfunctions('htra_api'); %查看API中的所有函数

%打开设备
Device = libpointer; %创建Device指针
DevNum = 0;
Status = 0;

load(fullfile(filePath, 'BootProfile.mat'));  % 直接加载BootProfile_TypeDef结构体
load(fullfile(filePath, 'BootInfo.mat'));  % 直接加载BootInfo_TypeDef结构体

IS_USB = 1;  % 默认为 USB 设备，如果使用网口型设备则设置为 0

if IS_USB == 1
    % 配置 USB 接口
    BootProfile.PhysicalInterface = 0;
else
    % 配置 ETH 接口
    BootProfile.PhysicalInterface = 3;
    BootProfile.ETH_IPVersion = 0;
    BootProfile.ETH_RemotePort = 5000;
    BootProfile.ETH_ReadTimeOut = 5000;
    BootProfile.ETH_IPAddress = [192, 168, 1, 100];
end

%调用Device_Open函数
Status = calllib('htra_api', 'Device_Open', Device, DevNum, BootProfile, BootInfo);

if Status == 0
    get(BootProfile);%打印BootInfo的值
    get(BootInfo);%打印BootInfo的值    
    fprintf('Device successfully\n');
else
    % 设备打开失败，根据不同的错误状态进行处理
    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 ;
end

load(fullfile(filePath, 'DET_Profile.mat'));  % 直接加载DET_Profile_TypeDef结构体

%定义DET_ProfileIn指针和SWP_ProfileOut指针
DET_ProfileIn = DET_Profile;
DET_ProfileOut = DET_Profile;

%调用DET_ProfileIn函数
Status = calllib('htra_api', 'DET_ProfileDeInit', Device, DET_ProfileIn);
get(DET_ProfileIn); %打印SWP_ProfileIn_p的值

DET_ProfileIn.CenterFreq_Hz = 1e9;   %配置中心频率。
DET_ProfileIn.RefLevel_dBm = 0;      %配置参考电平。
DET_ProfileIn.DecimateFactor = 2;    %配置抽取倍数。
DET_ProfileIn.TriggerLength = 16242; %配置单次触发采集的点数。仅当TriggerMode设置为FixedPoints时生效。

load(fullfile(filePath, 'DET_StreamInfo.mat'));    % 直接加载DET_StreamInfo_TypeDef结构体

%调用DET_Configuration函数
Status = calllib('htra_api', 'DET_Configuration', Device, DET_ProfileIn, DET_ProfileOut,DET_StreamInfo);

% 如果配置下发成功（Status == 0）
if Status == 0
    get(DET_ProfileOut); %打印IQS_ProfileOut的值
    get(DET_StreamInfo); %打印StreamInfo的值
    fprintf('Configuration successfully\n');
else
    % 如果调用出错，打印错误信息并关闭设备
    fprintf('DET_Configuration Call error Status = %d\n', Status);
    
    % 关闭设备的函数（Device_Close）。
    Device_Close(Device);  
    
    % 返回 0，结束函数执行
    return;
end

load(fullfile(filePath, 'TriggerInfo.mat'));% 直接加载IQS_TriggerInfo_TypeDef结构体

load(fullfile(filePath, 'MeasAuxInfo.mat'));% 直接加载MeasAuxInfo_TypeDef结构体

%创建NormalizedPowerStream，存放DET的数据
NormalizedPowerStream=1:DET_StreamInfo.StreamSamples;
NormalizedPowerStream_p = libpointer('singlePtr',NormalizedPowerStream);
disp(DET_StreamInfo.StreamSamples);

%此参数为绝对幅度（V单位）的比例因子。
ScaleToV = single(0);                                           
ScaleToV_p=libpointer('singlePtr',ScaleToV);

% 获取n次IQ数据
n = 10000;
 % 当 TriggerMode == Adaptive 时，先执行一次 DET_BusTriggerStart
if strcmp(DET_ProfileOut.TriggerMode, 'Adaptive')
    Status = calllib('htra_api', 'DET_BusTriggerStart', Device);
end

for j = 1:n
    % 如果 TriggerMode == FixedPoints，则每次循环时执行 DET_BusTriggerStart
    if strcmp(DET_ProfileOut.TriggerMode, 'FixedPoints')
        Status = calllib('htra_api', 'DET_BusTriggerStart', Device);
    end
    for i = 1:DET_StreamInfo.PacketCount
        Status = calllib('htra_api', 'DET_GetPowerStream', Device, NormalizedPowerStream_p,ScaleToV_p,TriggerInfo,MeasAuxInfo);
        if Status ~= 0
            % 如果调用出错，打印错误信息并关闭设备
           fprintf('DET_GetPowerStream Call error Status = %d\n', Status);

            % 返回 0，结束函数执行
           return;
        end
    end 

    %将DET数据中的单位转换为dBm
    for i=1:DET_StreamInfo.StreamSamples
        NormalizedPowerStream(i)=10 * log10(20 * power(NormalizedPowerStream_p.Value(i) * ScaleToV_p.Value, 2));
    end

    %画出DET的频谱图
    plot(1:DET_StreamInfo.StreamSamples,NormalizedPowerStream);
    ylim([-130, DET_ProfileOut.RefLevel_dBm]);
    xlim([0, DET_StreamInfo.StreamSamples]);
    pause(0.01);
end

%调用 DET_BusTriggerStop 函数
Status = calllib('htra_api', 'DET_BusTriggerStop', Device);

%调用Device_Close函数
Status = calllib('htra_api', 'Device_Close', Device);

clear all;

%卸载库文件
unloadlibrary('htra_api');   
disp('Uninstall complete')










