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

filePath = fullfile(pwd, 'htra_api_mat');  

% Check if the folder exists, create it if not
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'); % Make sure the path to .dll and .h is correct
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'));  % Load BootProfile_TypeDef struct
load(fullfile(filePath, 'BootInfo.mat'));     % Load BootInfo_TypeDef struct

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 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\n');
else
    % Device open failed, handle based on different error status
    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
    return ;
end

% Load GNSSInfo_TypeDef struct
load(fullfile(filePath, 'GNSSInfo.mat'));  
GNSSInfo.GNSS_LockState=0;
GNSSInfo.GNSSAntennaState=0;
Status = calllib('htra_api', 'Device_SetGNSSAntennaState', Device, GNSSInfo.GNSSAntennaState);

while ~GNSSInfo.GNSS_LockState
    % Get real-time GNSS information
    Status = calllib('htra_api', 'Device_GetGNSSInfo_Realtime', Device, GNSSInfo);
    disp(['GNSS_LockState: ', num2str(GNSSInfo.GNSS_LockState)]);
    pause(1);  
end

get(GNSSInfo); % Print GNSSInfo values

% BootInfo.DeviceInfo.HardwareVersion is the hardware version number
HardwareVersion = BootInfo.DeviceInfo.HardwareVersion;

% Extract OCXO_Enable value
OCXO_Enable = bitand(bitshift(HardwareVersion, -10), 3);
% Set DOCXO work mode to disciplining mode (must be set after antenna lock)
GNSSInfo.DOCXO_WorkMode = 0;
% Check if OCXO is enabled
if OCXO_Enable 
    % Set DOCXO work mode in GNSS
    Status = calllib('htra_api', 'Device_SetDOCXOWorkMode', Device,GNSSInfo.DOCXO_WorkMode);

    % Get current time
    startTime = tic;  % Start timer
    % If DOCXO is already locked
    if GNSSInfo.DOCXO_LockState == 1
       disp(['GNSS_LockState: ', num2str(int16(GNSSInfo.GNSS_LockState))]);
       disp(['DOCXO_LockState: ', num2str(int16(GNSSInfo.DOCXO_LockState))]);
    else
        while 1
            % Get DOCXO status in GNSS
            Status = calllib('htra_api', 'Device_GetGNSSInfo_Realtime', Device, GNSSInfo);

            % Check lock state
            if GNSSInfo.DOCXO_LockState == 1 && GNSSInfo.GNSS_LockState == 1
                disp(['GNSS_LockState: ', num2str(int16(GNSSInfo.GNSS_LockState))]);
                disp(['DOCXO_LockState: ', num2str(int16(GNSSInfo.DOCXO_LockState))]);
                break;
            end

            if GNSSInfo.GNSS_LockState == 0
                GNSSInfo.DOCXO_WorkMode = 1;
                % Set DOCXO work mode in GNSS
                Status = calllib('htra_api', 'Device_SetDOCXOWorkMode', Device,GNSSInfo.DOCXO_WorkMode);
            end
            disp(['GNSS_LockState: ', num2str(int16(GNSSInfo.GNSS_LockState))]);
            % Print current status
            disp(['DOCXO_LockState: ', num2str(int16(GNSSInfo.DOCXO_LockState))]);

            % Check timeout: whether it exceeds 600 seconds
            elapsedTime = toc(startTime);  % Get elapsed time
            if elapsedTime > 600
                disp('The DOCXO is not locked, please check whether the cable connection is normal.');
                break;
            end
            pause(1);  % Wait 1 second
        end
    end
end

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

clear all;
% Unload the DLL
unloadlibrary('htra_api');   
disp('Uninstall complete')
