%% Bluetooth BR/EDR Waveform Reception by Using SDR
% This example shows how to capture and decode Bluetooth BR/EDR waveforms by using the Communications Toolbox™ Library for the Bluetooth Protocol. You can either capture the Bluetooth BR/EDR waveforms by using the ADALM-PLUTO radio or load IQ samples corresponding to the Bluetooth BR/EDR waveforms from a baseband file (*.bb). To generate and transmit the Bluetooth BR/EDR waveforms, refer to docid:comm_examples#examples-BluetoothTransmitterExample and implement any one of these setups: Two SDR platforms connected to the same host computer, which runs two MATLAB sessions or two SDR platforms connected to two host computers, which runs two separate MATLAB sessions. To configure your host computer to work with the Support Package for ADALM-PLUTO Radio, refer to docid:plutoradio_ug#bvn89q2-14.
%% Required Hardware
% To capture signals in real time, you need ADALM-PLUTO radio and the corresponding support package add-on:
% Communications Toolbox Support Package for ADALM-PLUTO Radio
% For a full list of communications toolboxes supported by SDR platforms, refer to the Supported Hardware section of the Software Defined Radio (SDR) discovery page.
%% Bluetooth BR/EDR Radio Specifications
% Bluetooth is a short-range Wireless Personal Area Network (WPAN) technology, operating in the globally unlicensed industrial, scientific, and medical (ISM) band in the frequency range of 2.4 GHz to 2.485 GHz. In Bluetooth technology, data is divided into packets and each packet is transmitted on one of the 79 designated Bluetooth channels. Each channel has a bandwidth of 1 MHz. As there are different types of wireless networks operating in the same unlicensed frequency band, it is possible for two different networks to interfere with each other. To mitigate the interference, Bluetooth implements the frequency-hopping spread spectrum (FHSS) scheme to switch a carrier between multiple frequency channels by using a pseudorandom sequence known to both transmitter and receiver.
% The Bluetooth standard specifies these physical layer (PHY) modes:
% Basic rate (BR) - Mandatory mode, uses gaussian frequency shift keying (GFSK) modulation with a data rate of 1 Mbps
% Enhanced data rate (EDR) - Optional mode, uses phase shift keying (PSK) modulation with these two variants:
% EDR2M: Uses pi/4-DQPSK with a data rate of 2 Mbps
% EDR3M: Uses 8-DPSK with a data rate of 3 Mbps
%% Bluetooth BR/EDR Packet Formats
% The air interface packet formats for PHY modes include these fields:
% Access Code: Each packet starts with an access code. If a packet header follows, the access code is 72 bits long. Otherwise, the length of the access code is 68 bits and referred to as a shortened access code. The access code consists of these fields:
% Preamble: The preamble is a fixed zero-one pattern of four symbols.
% Sync Word: The sync word is a 64-bit code word derived from the 24-bit lower address part (LAP) of the Bluetooth device address.
% Trailer: The trailer is a fixed zero-one pattern of four symbols.
%                                                Access Code Format
%
% Packet Header: The header includes link control information and consists of these fields:
% LT_ADDR: 3-bit logical transport address
% TYPE: 4-bit type code, which specifies the packet type used for transmission. The value of this field can be ID, NULL, POLL, FHS, HV1, HV2, HV3, DV, EV3, EV4, EV5, 2-EV3, 2-EV5, 3-EV3, 3-EV5, DM1, DH1, DM3, DH3, DM5, DH5, AUX1, 2-DH1, 2-DH3, 2-DH5, 3-DH1, 3-DH3 and 3-DH5. This field determines the number of slots the current packet occupies.
% FLOW: 1-bit flow control over the asynchronous connection-oriented logical (ACL) transport
% ARQN: 1-bit acknowledgement indication
% SEQN: 1-bit sequence number
% HEC: 8-bit header error check
%                                                                  Header Format
%
% Payload: Payload includes an optional payload header, a payload body, and an optional CRC.
%                                                        Payload Format
%
% Guard: For EDR packets, guard time allows the Bluetooth BR/EDR radio to prepare for the change in modulation from GFSK to DPSK. The guard time must be between 4.75 to 5.25 microseconds.
% Sync: For EDR packets, the synchronization sequence contains one reference symbol and ten DPSK symbols.
% Trailer: For EDR packets, the trailer bits must be all zero pattern of two symbols, {00,00} for pi/4-DQPSK and {000,000} for 8DPSK.
% Packet format for BR mode is shown in this figure.
%                                                                 Basic Rate Packet Format
%
% Packet format for EDR mode is shown in this figure.
%                                                             Enhanced Data Rate Packet Format
%
%% Check for Support Package Installation
% Check if the Communications Toolbox Library for the Bluetooth Protocol support package is installed.

commSupportPackageCheck('BLUETOOTH');

%
%% Decode Bluetooth BR/EDR Waveforms
% This example shows how to decode Bluetooth BR/EDR waveforms either captured by using ADLAM-PLUTO or by reading IQ samples from a baseband file.
%                                                           Bluetooth BR/EDR Receiver
%
% The general structure of the Bluetooth receiver example is:
% Initialize the receiver parameters.
% Specify the signal source.
% Capture the Bluetooth BR/EDR waveforms.
% Process Bluetooth BR/EDR waveforms at receiver.
%% Initialize the Receiver Parameters
% To configure Bluetooth BR/EDR parameters, use docid:comm_ref#obj_bluetoothPhyConfig object.

cfg = bluetoothPhyConfig;
cfg.Mode = 'BR'; % Mode of transmission as one of BR, EDR2M and EDR3M
cfg.WhitenInitialization = [0;0;0;0;0;1;1]; % Whiten initialization

%
%% Specify the Signal Source
% Specify the signal source as File or ADALM-PLUTO.
% File: Uses the  comm.BasebandFileReader to read a file that contains a previously captured over-the-air signal.
% ADALM-PLUTO: Uses the  sdrrx System object to receive a live signal from the SDR hardware.
% If you assign ADALM-PLUTO as the signal source, the example searches your computer for the ADALM-PLUTO radio at radio address 'usb:0' and uses it as the signal source.

% The default signal source is 'File'
signalSource = 'File';

bbSymbolRate = 1e6; % 1 MSps
if strcmp(signalSource,'File')
    switch cfg.Mode
        case 'BR'
            bbFileName = 'bluetoothCapturesBR.bb';
        case 'EDR2M'
            bbFileName = 'bluetoothCapturesEDR2M.bb';
        case 'EDR3M'
            bbFileName = 'bluetoothCapturesEDR3M.bb';
    end
    sigSrc = comm.BasebandFileReader(bbFileName);
    sigSrcInfo = info(sigSrc);
    bbSampleRate = sigSrc.SampleRate;
    sigSrc.SamplesPerFrame = sigSrcInfo.NumSamplesInData;
    cfg.SamplesPerSymbol = bbSampleRate/bbSymbolRate;

else

    % Check if the pluto Hardware Support Package (HSP) is installed
    if isempty(which('plutoradio.internal.getRootDir'))
        error(message('comm_demos:common:NoSupportPackage', ...
                      'Communications Toolbox Support Package for ADALM-PLUTO Radio',...
                      ['<a href="https://www.mathworks.com/hardware-support/' ...
                      'adalm-pluto-radio.html">ADALM-PLUTO Radio Support From Communications Toolbox</a>']));
    end
    connectedRadios = findPlutoRadio; % Discover ADALM-PLUTO radio(s) connected to your computer
    radioID = connectedRadios(1).RadioID;    
    rxCenterFrequency = 2445000000;  % In Hz, choose between 2.402e9 to 2.480e9 with 1e6 spacing
    bbSampleRate = bbSymbolRate * cfg.SamplesPerSymbol;
    sigSrc = sdrrx('Pluto',...
        'RadioID',             radioID,...
        'CenterFrequency',     rxCenterFrequency,...
        'BasebandSampleRate',  bbSampleRate,...
        'SamplesPerFrame',     1e7,...
        'GainSource',         'Manual',...
        'Gain',                25,...
        'OutputDataType',     'double');
end

%
%% Capture the Bluetooth BR/EDR Waveforms
% Capture the IQ samples corresponding to Bluetooth BR/EDR waveforms either by using ADLAM-PLUTO or baseband file as signal source. Visualize the spectrum of the received Bluetooth waveforms by using a spectrum analyzer.

% The transmitted waveforms are captured as a burst
dataCaptures = sigSrc();

% Setup spectrum viewer
spectrumScope = dsp.SpectrumAnalyzer( ...
    'SampleRate',       bbSampleRate,...
    'SpectrumType',     'Power density', ...
    'SpectralAverages', 10, ...
    'YLimits',          [-130 -30], ...
    'Title',            'Received Baseband Bluetooth Signal Spectrum', ...
    'YLabel',           'Power spectral density');

% Show power spectral density of the received waveform
spectrumScope(dataCaptures);

%
%% Process Bluetooth BR/EDR Waveforms at Receiver
% To decode the packet header, payload header information, and raw message bits, the receiver processess the baseband samples received from the signal source. This figure shows the receiver processing.
%                                                            Bluetooth Practical Receiver
%
% The Bluetooth practical receiver performs these functions:
% Remove DC offset
% Detect the signal bursts
% Perform matched filtering
% Estimate and correct the timing offset
% Estimate and correct the carrier frequency offset
% Demodulate BR/EDR waveform
% Perform forward error correction (FEC) decoding
% Perform data dewhitening
% Perform header error check (HEC) and cyclic redundancy check (CRC)
% Outputs decoded bits and decoded packet statistics based on decoded lower address part (LAP), HEC and CRC

% Bluetooth practical receiver
[decBits,decodedInfo,pktStatus] = helperBluetoothPracticalReceiver(dataCaptures,cfg);

% Get the number of detected packets
pktCount = length(pktStatus);
disp(['Number of Bluetooth packets detected: ' num2str(pktCount)])

% Get the decoded packet statistics
displayFlag = true; % set true, to display the decoded packet statistics  
if(displayFlag && (pktCount~=0))
    decodedInfoPrint = decodedInfo;
    for ii = 1:pktCount
        if(pktStatus(ii))
            decodedInfoPrint(ii).PacketStatus = 'Success';
        else
            decodedInfoPrint(ii).PacketStatus = 'Fail';
        end
    end
    packetInfo = struct2table(decodedInfoPrint,'AsArray',1);
    fprintf('Decoded Bluetooth packet(s) information: \n \n')
    disp(packetInfo);
end

% Get the packet error rate performance metrics
if(pktCount)
    pktErrCount = sum(~pktStatus);
    pktErrRate = pktErrCount/pktCount;
    disp(['Simulated Mode: ' cfg.Mode ', '...
        'Packet error rate: ',num2str(pktErrRate)])
end

% Release the signal source
release(sigSrc);

%
% This example enables you to decode Bluetooth BR/EDR waveforms either captured by using ADLAM-PLUTO or by reading IQ samples from a baseband file. Visualize the spectrum of the received Bluetooth waveforms by using a spectrum analyzer. The packet error rate is computed based on the decoded packet information.
%% Further Exploration
% You can use this example to receive EDR packets by changing the PHY transmission mode. To generate the Bluetooth waveforms in this example, refer to docid:comm_examples#examples-BluetoothTransmitterExample.
%% Troubleshooting
% General tips for troubleshooting SDR hardware and the Communications Toolbox Support Package for ADALM-PLUTO Radio can be found in docid:plutoradio_ug#bvn89q2-68.
%% Appendix
% This example uses this helper function:
% helperBluetoothPracticalReceiver.m: Practical receiver for Bluetooth physical layer
%% Selected Bibliography
% Bluetooth Special Interest Group (SIG). "Core System Package [BR/EDR Controller Volume]". Bluetooth Core Specification. Version 5.1, Volume 2 <https://www.bluetooth.com/>
% Copyright 2019 The MathWorks, Inc.