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

filePath = fullfile(pwd, 'htra_api_mat');  

% Check whether the folder exists. If it does not exist, 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'); % Pay attention to the file paths of the .dll and .h files.
end

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

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

APIVersion = uint32(calllib('htra_api', 'Get_APIVersion'));  % Ensure that apiVersion is of uint32 type.

% Extract the version number using the provided bitwise operation method.
major = bitshift(APIVersion, -16);                  % Extract the high 16 bits (major version number).
minor = bitshift(bitand(APIVersion, 65535), -8);    % Extract the middle 8 bits (minor version number).
rev = bitand(APIVersion, 255);                      % Extract the low 8 bits (revision number).

% Print the API version information.
fprintf('htra_api version: %d.%d.%d\n', major, minor, rev);

load(fullfile(filePath, 'BootProfile.mat'));  % Directly load the file.
load(fullfile(filePath, 'BootInfo.mat'));     % Directly load the file.

IS_USB = 1;  % USB device by default. Set this value to 0 if a network-port device is used.

if IS_USB == 1
    % Configure the USB interface.
    BootProfile.PhysicalInterface = 0;
else
    % Configure the 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 the Device_Open function.
Status = calllib('htra_api', 'Device_Open', Device, DevNum, BootProfile, BootInfo);

if Status == 0
    get(BootProfile); % Print the value of BootProfile.
    get(BootInfo);    % Print the value of BootInfo.
    fprintf('Device successfully\n');
else
    % Device opening failed. Handle different error status values.
    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 the error status value.
    return;
end

% Display the device UID.
fprintf('DeviceInfo.DeviceUID: %s\n', sprintf('0x%016X\n', uint64(vpa(BootInfo.DeviceInfo.DeviceUID))));
% disp(uint64(BootInfo.DeviceInfo.DeviceUID));

if BootInfo.DeviceInfo.Model == 11
    str = 'E90_R1';
elseif BootInfo.DeviceInfo.Model == 12
    str = 'E90_R2';
elseif BootInfo.DeviceInfo.Model == 13
    str = 'E90_R3';
elseif BootInfo.DeviceInfo.Model == 22
    str = 'E200_R2';
elseif BootInfo.DeviceInfo.Model == 23
    str = 'E200_R3';
elseif BootInfo.DeviceInfo.Model == 53
    str = 'N60_R4';
elseif BootInfo.DeviceInfo.Model == 54
    str = 'M60_R4';
elseif BootInfo.DeviceInfo.Model == 55
    str = 'N45_R4';
elseif BootInfo.DeviceInfo.Model == 56
    str = 'M80_R5';
elseif BootInfo.DeviceInfo.Model == 57
    str = 'M60_R5';
elseif BootInfo.DeviceInfo.Model == 58
    str = 'N60_R5';
elseif BootInfo.DeviceInfo.Model == 59
    str = 'N45_R5';
elseif BootInfo.DeviceInfo.Model == 91
    str = 'N400_R1';
elseif BootInfo.DeviceInfo.Model == 94
    str = 'N400_R2';
else
    str = 'Unknown_Model';
end

% Display the device model.
disp(['The device model is ', str]);

fprintf('BusSpeed:  %d.\n',BootInfo.BusSpeed);

% Display the device MCU version and FPGA version.
MFM = uint32(BootInfo.DeviceInfo.MFWVersion);    % Convert to uint32 type.
FPGA = uint32(BootInfo.DeviceInfo.FFWVersion);   % Convert to uint32 type.

x1 = bitshift(MFM, -16);                  % Extract the high 16 bits.
y1 = bitshift(bitand(MFM, 65535), -8);    % Extract the middle 8 bits.
z1 = bitand(MFM, 255);                    % Extract the low 8 bits.

x2 = bitshift(FPGA, -16);                 % Extract the high 16 bits.
y2 = bitshift(bitand(FPGA, 65535), -8);   % Extract the middle 8 bits.
z2 = bitand(FPGA, 255);                   % Extract the low 8 bits.

fprintf('The MFM version of the device is %d.%d.%d\n', x1, y1, z1);
fprintf('The FPGA version of the device is %d.%d.%d\n', x2, y2, z2);

% Display the device temperature.
load(fullfile(filePath, 'DeviceState.mat'));  % Directly load the DeviceState.mat file.
Status = calllib('htra_api', 'Device_QueryDeviceState_Realtime', Device,DeviceState);
fprintf('Device Temperature: %2f\n',DeviceState.Temperature * 0.01);

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

clear all;

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