% Copyright (c) 2023 SpinCore Technologies, Inc.
% http://www.spincore.com
% 
% This software is provided 'as-is', without any express or implied warranty. 
% In no event will the authors be held liable for any damages arising from the 
% use of this software.
% 
% Permission is granted to anyone to use this software for any purpose, 
% including commercial applications, and to alter it and redistribute it
% freely, subject to the following restrictions:
% 
% 1. The origin of this software must not be misrepresented; you must not
% claim that you wrote the original software. If you use this software in a
% product, an acknowledgment in the product documentation would be appreciated
% but is not required.
% 2. Altered source versions must be plainly marked as such, and must not be
% misrepresented as being the original software.
% 3. This notice may not be removed or altered from any source distribution.
%

%
% \file pb_read_firmware.m adapted from pb_read_firmware.c
% \brief This example program will print the firmware(s) of detected device(s).
% \ingroup genex
% 
clc; clear;

global SPINAPI_DLL_NAME

SPINAPI_DLL_NAME = 'spinapi64';

addpath('../MATLAB_SpinAPI'); % MATLAB_SpinAPI Folder path address

SpinAPI_Drive = 'C:'; % Modify to the hard drive letter that contains SpinAPI

% Loads spinapi64 library and headers
% All files are located in SpinAPI folder
if ~libisloaded('spinapi64')  % Needs the MinGW-w64 add-on
    loadlibrary([SpinAPI_Drive,'\SpinCore\SpinAPI\lib\spinapi64.dll'], ...
                 [SpinAPI_Drive,'\SpinCore\SpinAPI\include\spinapi.h'], 'addheader',...
                 [SpinAPI_Drive,'\SpinCore\SpinAPI\include\pulseblaster.h'], 'addheader',...
                 [SpinAPI_Drive,'\SpinCore\SpinAPI\include\radioprocessor.h'], 'addheader',...
                 [SpinAPI_Drive,'\SpinCore\SpinAPI\include\dds.h']);
end


% Uncommenting the line below will generate a debug log in your current
% directory that can help debug any problems that you may be experiencing   
% pb_set_debug(1);

fprintf('Copyright (c) 2023 SpinCore Technologies, Inc.\n\n');

fprintf('Using SpinAPI library version %s \n', pb_get_version());

numBoards = pb_count_boards();
fprintf('Detected %d Boards.\n', numBoards);

for i = 0:numBoards-1
    pb_select_board(i); %* Select the nth board *
    
    if pb_init() ~= 0
        error('Error initializing board: %s\n', pb_get_error());
    end

    firm_id = pb_get_firmware_id();
    dev_id = bitshift(bitand(firm_id,hex2dec('FF00')),-8);
    rev_id = bitand(firm_id,hex2dec('00FF'));
    
    fprintf('Board %d Firmware ID: %d-%d\n', i, dev_id, rev_id);

    pb_close();
end 

fprintf('\n\n');
fprintf('Press enter to continue...\n')
pause; 

% Unload library and free memory
unloadlibrary('spinapi64');