function [crcFail,pdu] = helperBLETestPacketValidate(rcvBits,accessAddress)
%helperBLETestPacketValidate Validates BLE test packets
%   [CRCFAIL,PDU] = helperBLETestPacketValidate(RCVBITS,ACCESSADDRESS)
%   validates the BLE packet, RCVBITS based on access address
%   information, ACCESSADDRESS and CRC check.
%
%   CRCFAIL is a logical value, where zero represents CRC pass and one
%   represents CRC fail.
%
%   PDU is a binary column vector containing the information bits.

%   Copyright 2019 The MathWorks, Inc.

% Create a CRC detector System object
crcPolynomial = 'x^24 + x^10 + x^9 + x^6 + x^4 + x^3 + x + 1';
crcInitValue = '555555';
persistent crcDetect
if isempty(crcDetect)
    crcDetect = comm.CRCDetector(crcPolynomial, 'InitialConditions', ...
        comm.internal.utilities.de2biBase2LeftMSB(hex2dec(crcInitValue), 24), ...
        'DirectMethod', true);
end

% Initialize the variables
crcLength = 24;
pduHeaderLength = 16;
pdu = [];
crcFail = 1;

% Access address for test packet
testPacketAA = flip([1 0 0 1 0 1 0 0 1 0 0 0 0 0 1 0 0 1 1 0 1 1 1 0 1 0 0 0 1 1 1 0].');

% Check for the decoded access address, if the decoded access address does
% not match with the test packet access address then the packet is
% considered as a lost packet.
if isequal(accessAddress,testPacketAA)

    % Perform data dewhitening on PDU and CRC bits in order to remove
    % whitening effect, because whitening must be turned off for the test
    % measurements.
    chanIdx = 37;
    chanIdxBin = comm.internal.utilities.de2biBase2LeftMSB(chanIdx,6);
    initState = [1 chanIdxBin];
    dewhitenedBits = ble.internal.whiten(rcvBits,initState);

    % Extract PDU length
    pduLenField = double(dewhitenedBits(9:16)); % Second byte of PDU header
    pduByteLen = comm.internal.utilities.bi2deRightMSB(pduLenField',2);
    pduBitLen = pduByteLen*8;

    % Check for the length of decoded data. If the length of
    % decoded data is greater than or equal to (PDU length +
    % CRC length + Header length) then CRC check is performed.
    if length(dewhitenedBits) >= pduBitLen+crcLength+pduHeaderLength
        pduBitsWithCRC = double(dewhitenedBits(1:pduBitLen+crcLength+pduHeaderLength));
        [pdu,crcFail] = crcDetect(pduBitsWithCRC); % Perform CRC
    end
end
end