%% Bluetooth Low Energy Waveform Generation and Visualization
% This example shows how the Communications Toolbox(TM) Library for the
% Bluetooth Protocol can be used to generate waveforms for different modes
% of Bluetooth Low Energy (BLE) physical layer (PHY) [ <#8 1> ].

% Copyright 2018-2019 The MathWorks, Inc.

%% Background
% Bluetooth special interest group (SIG) introduced BLE for low power short
% range communications. BLE devices operate in the globally unlicensed
% industrial, scientific and medical (ISM) band in the frequency range 2.4
% GHz to 2.485 GHz. BLE specifies a channel spacing of 2 MHz, which results
% in 40 RF channels as shown in the figure below. The BLE standard [ <#8 1>
% ] specifies the *Link* layer which includes both *PHY* and *MAC* layers.
% BLE finds applications in transfer of files such as images and MP3
% between mobile phones, home automation and internet of things (IoT)
% trend.
%
% <<../BLEChannels.png>>
%
% The Bluetooth standard [ <#8 1> ] specifies the following physical layer
% modes:
%
% * *LE1M* - Uncoded PHY with data rate of 1 Mbps
% * *LE2M* - Uncoded PHY with data rate of 2 Mbps
% * *LE500K* - Coded PHY with data rate of 500 Kbps
% * *LE125K* - Coded PHY with data rate of 125 Kbps
%
% The air interface packet formats for these modes include the following
% fields:
%
% * *Preamble*: The preamble depends on which PHY mode is used. LE1M mode
% uses an 8-bit sequence of alternate zeros and ones, '01010101'. LE2M uses
% a 16-bit sequence of alternate zeros and ones, '0101...'. LE500K and
% LE125K modes use an 80-bit sequence of zeros and ones obtained by
% repeating '00111100' ten times.
% * *Access Address*: Specifies the connection address shared between two
% BLE devices using a 32-bit sequence.
% * *Coding Indicator*: 2-bit sequence used for differentiating two coded
% modes (LE125K, LE500K).
% * *Payload*: Input message bits including both PDU and CRC. The maximum
% message size is 2080 bits.
% * *Termination Fields*: Two 3-bit vectors of zeros, used in Forward Error
% Correction encoding. The termination fields are present for coded modes
% (LE500K and LE125K) only.
%
% Packet format for uncoded PHY (LE1M and LE2M) modes is shown in the
% figure below:
%
% <<../BLEUncodedPhy.png>>
%
% Packet format for coded PHY (LE500K and LE125K) modes is shown in the
% figure below:
%
% <<../BLECodedPhy.png>>
%

%% Introduction
% This example shows how to generate BLE waveforms for all the physical
% layer modes as per the Bluetooth specification [ <#8 1> ]. The generated
% BLE waveforms are visualized in both time-domain and frequency-domain
% using time scope and spectrum analyzer respectively.

%% Check for Support Package Installation

% Check if the 'Communications Toolbox Library for the Bluetooth Protocol'
% support package is installed or not.
commSupportPackageCheck('BLUETOOTH');

%% Initialize Parameters for Waveform Generation

% Specify the input parameters for generating BLE waveform
numPackets = 10;    % Number of packets to generate
sps = 16;           % Samples per symbol
messageLen = 2000;  % Length of message in bits
phyMode = 'LE1M';   % Select one mode from the set {'LE1M','LE2M','LE500K','LE125K'};
channelBW = 2e6;    % Channel spacing (Hz) as per standard
% Define symbol rate based on the PHY mode
if any(strcmp(phyMode,{'LE1M','LE500K','LE125K'}))
    symbolRate = 1e6;
else
    symbolRate = 2e6;
end

%% Create Objects for Visualization

% Create a spectrum analyzer object
specAn = dsp.SpectrumAnalyzer('SpectrumType','Power density');
specAn.SampleRate = symbolRate*sps;

% Create a time scope object
timeScope = dsp.TimeScope('SampleRate', symbolRate*sps,'TimeSpanSource','Auto',...
     'ShowLegend',true);

%% Waveform Generation and Visualization

% Loop over the number of packets, generating a BLE waveform and plotting
% the waveform spectrum
rng default;
for packetIdx = 1:numPackets
    message = randi([0 1],messageLen,1);    % Message bits generation
    chanIndex = randi([0 39],1,1);          % Channel index decimal value

    if(chanIndex >=37)
        % Default access address for periodic advertising channels
        accessAdd = [0 1 1 0 1 0 1 1 0 1 1 1 1 1 0 1 1 0 0 ...
                            1 0 0 0 1 0 1 1 1 0 0 0 1]';
    else
        % Random access address for data channels
        % Ideally, this access address value should meet the requirements
        % specified in Section 2.1.2 of volume 6 of the Bluetooth Core
        % Specification.
        accessAdd = [0 0 0 0 0 0 0 1 0 0 1 0 0 ...
            0 1 1 0 1 0 0 0 1 0 1 0 1 1 0 0 1 1 1]';
    end

    waveform = bleWaveformGenerator(message,...
                                    'Mode',phyMode,...
                                    'SamplesPerSymbol',sps,...
                                    'ChannelIndex',chanIndex,...
                                    'AccessAddress',accessAdd);

    specAn.FrequencyOffset = channelBW*chanIndex;
    specAn.Title = ['Spectrum of ',phyMode,' Waveform for Channel Index = ', num2str(chanIndex)];

    tic
    while toc < 0.5 % To hold the spectrum for 0.5 seconds
        specAn(waveform);
    end

    % Plot the generated waveform
    timeScope.Title = ['BLE ',phyMode,' Waveform for Channel Index = ', num2str(chanIndex)];
    timeScope(waveform);
end

% Release objects
release(specAn);
release(timeScope);

%% Appendix
% The feature used in this example is: 
%
% * <docid:comm_ref#fcn_bleWaveformGenerator bleWaveformGenerator>:
% Generates BLE physical layer waveform

%% Selected Bibliography
% # Volume 6 of the Bluetooth Core Specification, Version 5.0 Core System 
% Package [Low Energy Controller Volume].
