%% End-to-End BLE PHY Simulation Using Path Loss Model, RF Impairments, and AWGN
% This example uses Communications Toolbox™ Library for the Bluetooth® Protocol to perform end-to-end Bluetooth low energy (BLE) simulation for different BLE physical layer (PHY) transmission modes in the presence of the path loss model, radio front-end (RF) impairments, and additive white Gaussian noise (AWGN). The simulation results show the estimated value of the bit error rate (BER), path loss, and distance between the transmitter and receiver.
%% Path Loss Modeling in BLE Network
% The Bluetooth Core Specifications [1] defined by the Bluetooth Special Interest Group (SIG) introduced BLE to enable low-power short-range communication. BLE devices operate in the globally unlicensed industrial, scientific, and medical (ISM) band in a frequency range from 2.4 GHz to 2.485 GHz. BLE specifies a channel spacing of 2 MHz, resulting in 40 RF channels. The prominent applications of BLE include direction finding services and building intelligent internet of things (IoT) solutions to facilitate home, commercial, and industrial automation. For more information about direction finding services in BLE, see the Bluetooth Direction Finding topic.
% In past few years, there has been a significant increase in designing BLE networks for a plethora of use case scenarios. To achieve high performance and quality in the BLE network, studying the propagation of the BLE signal along the link between the transmitter and the receiver is recommended. This example shows an end-to-end BLE simulation considering these factors that impact the propagation of BLE signals along the communication link between the transmitter and receiver.
% Receiver sensitivity
% Path loss model
% Transmit power
% Antenna gain
%% Receiver Sensitivity
% Receiver sensitivity is the measure of minimum signal strength at which the receiver can detect, demodulate, and decode the waveform. The reference sensitivity level specified in the Bluetooth Core Specifications [1] is -70 dBm. However, the actual sensitivity level for the receiver as per the Bluetooth Core Specifications [1] is defined as the receiver input level for which the BER specified in this table is achieved.
%
% This table shows the actual sensitivity level of the receiver for a given PHY transmission mode.
%
%% Path Loss Model
% Path loss or path attenuation is the decline in the power density of a given signal as it propagates from the transmitter to receiver through space. This reduction in power density occurs naturally over the distance and is impacted by the obstacles present in the environment in which the signal is being transmitted. The path loss is generally expressed in decibels (dB) and is calculated as:
%  {\textrm{PL}}_{\textrm{dB}} =P_t -P_r.
%  In this equation,
% {\textrm{PL}}_{\textrm{dB}} is the path loss in dB.
% P_t is the transmitted signal power in dB.
% P_r is the received signal power in dB.
% Path loss models describe the signal attenuation between the transmitter and receiver based on the propagation distance and other parameters such as frequency, wavelength, path loss exponent, and antenna gains. The example considers these path loss models:
% Free-space [3]
% Log-distance [3]
% Log-normal shadowing [3]
% Two-ray ground reflection [3]
% NIST PAP 02-Task 6 [4]
%% Free-Space Path Loss Model
% Free-space path loss is the attenuation of signal strength between the transmitter and receiver along the line of sight (LoS) path through free space (usually air), excluding the effect of the obstacles in the path. The free-space path loss is calculated as:
%  {\textrm{PL}}_{\textrm{dB}} =20\log \left(\frac{4\pi d}{\lambda }\right).
%  In this equation,
% d is the distance between the transmitter and receiver.
% \lambda is the signal wavelength.
%% Log-Distance Path Loss Model
% A log-distance path loss model reflects the path loss that a signal encounters in an indoor environment such as a building. It is computed as:
% {\textrm{PL}}_{\textrm{dB}} ={\textrm{PL}}_0 +10\gamma \log \left(\frac{d}{d_0 }\right).
% In this equation,
% {\textrm{PL}}_0 is the path loss at the reference distance d_0.
% d is the distance between the transmitter and receiver.
% d_0 is the reference distance.
% \gamma is the path loss exponent.
%% Log-Normal Shadowing Path Loss Model
% The log-normal shadowing model is an extension of log-distance path loss model. Unlike the log-distance model, the log-normal shadowing model considers the fact that the surrounding environment clutter can be vastly different at two different locations having the same transmitter-receiver separation. Measurements show that at any transmitter-receiver distance, d, the path loss at a particular location is random and distributed log normally (in dB) about the mean distance dependent value. The path loss is calculated as:
% {\textrm{PL}}_{\textrm{dB}} \left(d\right)={\textrm{PL}}_{\textrm{dB}} \left(d_0 \right)+10\gamma \log \left(\frac{d}{d_0 }\right)+X_{\sigma }.
% In this equation,
% {\textrm{PL}}_{\textrm{dB}} \left(d_0 \right) is the path loss at the reference distance d_0.
% d is the distance between the transmitter and receiver.
% d_0 is the reference distance.
% \gamma is the path loss exponent.
% X_{\sigma } is the normal or Gaussian random variable with zero mean, reflecting the attenuation caused by the flat fading.
%% Two-Ray Ground Reflection Model
% The two-ray ground reflection model is a radio propagation model that estimates the path loss between the transmitter and receiver by considering these two signal components: LoS and the component reflected from the ground. When the transmitter and receiver antenna heights are approximately similar and the distance between the antennas is very large relative to the height of the antennas, then the path loss is calculated as:
% {\textrm{PL}}_{\textrm{linear}\;\textrm{scale}} =\frac{G\;h_t^2 h_r^2 }{d^4 }.
% The path loss in logarithmic scale is calculated as:
% {\textrm{PL}}_{\textrm{dB}} =\;40\textrm{log10}\left(d\right)-10\textrm{log10}\left(G\;h_t^2 h_r^2 \right).
% In this equation,
% d is the distance between the transmitter and receiver.
% G is the product of antenna gains.
% h_t is the height of the transmitter.
% h_r is the height of the receiver.
%% NIST PAP02-Task 6 Model
% The National Institute of Standards and Technology (NIST) conducted studies for indoor to indoor, outdoor to outdoor, and outdoor to indoor propagation paths and derived these equations for calculating the path loss:
%   \begin{array}{l}
% {\textrm{PL}}_{d\;} ={\textrm{PL}}_0 +10\left(n_0 \right)\textrm{log10}\left(\frac{d}{d_0 }\right)\ldotp \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\textrm{for}\;d\le d_1 \\
% {\textrm{PL}}_{d\;} ={\textrm{PL}}_0 +10\left(n_0 \right)\textrm{log10}\left(\frac{d}{d_0 }\right)+10\left(n_1 \right)\textrm{log10}\left(\frac{d}{d_1 }\right)\ldotp \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\textrm{for}\;d>d_1
% \end{array}
% In these equations,
% {\textrm{PL}}_0 is the path loss at the reference distance d_0.
% n_0,n_1 are the path loss exponents.
% d is the distance between the transmitter and receiver.
% d_0 is the reference distance, assumed to be 1 meter in simulations.
% d_1 is the breakpoint where the path loss exponent adjusts from n_0 to n_1.
% The example considers these values for different environments.
%
% Most of these measurements for the NIST PAP02 Task 6 channel model were taken with transmitters and receivers located in hallways with distances ranging from 5 m to 45 m.
%% Transmit Power
% Transmit power is the power of the radio frequency signal generated by the transmitter. Increasing the transmit power increases the likelihood that the signal can be transmitted over longer distances. Bluetooth supports transmit power from -20 dBm (0.01 mW) to 20 dBm (100 mW).
%% Antenna Gain
% Antenna gain is the factor by which the antenna improves the total radiated power. Bluetooth designers can choose to implement a variety of antenna options. Bluetooth devices typically achieve an antenna gain in the range from -10 dBi to 10 dBi.
%% End-to-End BLE Simulation Procedure
% The end-to-end BLE PHY simulations estimate the BER and the distance between the transmitter and receiver by considering a specific path loss model with RF impairments and AWGN added to the transmission packets.
% For a given set of simulation parameters, obtain the signal-to-noise ratio (SNR) at the receiver by assuming a fixed noise figure. For the obtained value of SNR including the path loss, generate the BLE waveform  using bleWaveformGenerator function. Distort the generated waveform with RF impairments and AWGN. Each packet is distorted by these RF impairments:
% DC offset
% Carrier frequency offset
% Carrier phase offset
% Timing drift
% The noisy packets are processed through a practical BLE receiver that performs these operations:
% Automatic gain control (AGC)
% DC removal
% Carrier frequency offset correction
% Matched filtering
% Packet detection
% Timing error detection
% Demodulation and decoding
% De-whitening
% The end-to-end example chain is summarized in these block diagrams
%
%
% The BER is obtained by comparing the transmitted and recovered data bits.
%% Check for the Support Package Installation
% Check if the 'Communications Toolbox Library for the Bluetooth Protocol' support package is installed or not.

commSupportPackageCheck('BLUETOOTH');

%% Configure Simulation Parameters
% In this example, the distance between the transmitter and receiver is estimated based on the environment and the power levels of the signal at the transmitter and receiver.
%% Configure parameters related to the communication link between the transmitter and receiver

pathLossModel = 'Free space';          % Path loss model
rxSensitivity = -70 ; % Receiver sensitivity in dBm
txPower = 0;          % Transmit power in dBm
txAntennaGain = 0;    % Transmitter antenna gain in dB
rxAntennaGain = 0;    % Receiver antenna gain in dB
linkMargin = 15;                              % Link margin(dB) assumed in the simulation

%% Configure parameters for waveform generation

samplesPerSymbol = 8;                 % Samples per symbol
dataLen = 254;  % Data length in bytes
phyMode = 'LE1M';       % PHY transmission mode

% 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]';

% Random data bits generation
txBits = randi([0 1],dataLen*8,1,'int8');

% Random channel index
chanIndex =37;
fc = (2*chanIndex+2402)*1e6; % Center frequency in Hz

% Generate BLE waveform
txWaveform = bleWaveformGenerator(txBits,'Mode',phyMode,...
                    'SamplesPerSymbol',samplesPerSymbol,...
                    'ChannelIndex',chanIndex,...
                    'AccessAddress',accessAdd);

%% Configure noise and signal power at the receiver
% The noise floor of the receiver is simulated with thermal noise. The height of the noise floor determines the SNR at the receiver. The noise figure of the receiver determines the level of noise floor.

NF = 6;            % Noise figure (dB)
T = 290;           % Ambient temperature (K)
dBm2dBFactor = 30; % Factor for converting dBm to dB

% Symbol rate based on the PHY transmission mode
symbolRate = 1e6; 
if strcmp(phyMode,'LE2M')
    symbolRate = 2e6;
end
BW = samplesPerSymbol*symbolRate; % Bandwidth (Hz)
k = 1.3806e-23;                   % Boltzmann constant (J/K)
noiseFloor = 10*log10(k*T*BW)+NF; % Nosie floor in dB

% Measure signal power at the receiver based on the receiver sensitivity and
% assumed link margin
measuredPowerVector = rxSensitivity - dBm2dBFactor+linkMargin;
snrdB = measuredPowerVector - noiseFloor; % SNR in dB

%% Distort BLE Waveform
% Distort the generated BLE waveform using RF impairments, path loss, and AWGN.
%% Add RF Impairments
% The RF impairments are generated randomly and added to the BLE waveform.

% Create and configure the System objects for impairments
initImp = helperBLEImpairmentsInit(phyMode,samplesPerSymbol);

% Configure RF impairments
initImp.pfo.FrequencyOffset = 5800; % Frequency offset in Hz
initImp.pfo.PhaseOffset = 5;         % Phase offset in degrees
initoff = 0.15*samplesPerSymbol; % Static timing offset
stepsize = 20*1e-6;              % Timing drift in ppm, Max range is +/- 50 ppm
initImp.vdelay = (initoff:stepsize:initoff+stepsize*(length(txWaveform)-1))';
initImp.dc = 20; % Percentage related to maximum amplitude value

% Pass generated BLE waveform through RF impairments
txImpairedWfm = helperBLEImpairmentsAddition(txWaveform,initImp);

%% Attenuate Impaired BLE Waveform
% Obtain the path loss value and attenuate the impaired BLE waveform.

% Obtain the path loss value in dB
pldB = txPower-dBm2dBFactor+rxAntennaGain+txAntennaGain-measuredPowerVector;
plLinear = 10^(pldB/20); % Convert from dB to linear scale

% Attenuate BLE waveform
attenWaveform  = txImpairedWfm./plLinear;

%% Add AWGN
% Add AWGN to the attenuated BLE waveform.

% Add WGN to the attenuated BLE waveform
rxWaveform = awgn(attenWaveform,snrdB,'measured');

%% Simulation Results
% Estimate and display the BER and the distance between the transmitter and the receiver by processing the distorted BLE waveform through the practical receiver.
%% Receiver Processing
% To retrieve the data bits, pass the attenuated, AWGN-distorted BLE waveform through the practical receiver.

% Create and configure the receiver System objects 
initRxParams = helperBLEReceiverInit(phyMode,samplesPerSymbol,accessAdd);

% Recover data bits using practical receiver
[rxBits,accessAddress] = helperBLEPracticalReceiver(rxWaveform,initRxParams,chanIndex);

%% Estimate BER
% Estimate value of the BER based on the retrieved and the transmitted data bits.

% Obtain BER by comparing the transmitted and recovered bits
ber = [];
if(length(txBits) == length(rxBits))
    ber = (sum(xor(txBits,rxBits))/length(txBits));
end

%% Estimate Distance
% Estimate the distance between the transmitter and the receiver.

% Estimate the distance between the transmitter and the receiver based on the path loss value and the environment
if any(strcmp(pathLossModel,{'Free space','Log distance','Log normal shadowing'})) 
    
    % Center frequency is required only for these path loss models
    distance = helperBluetoothEstimateDistance(pathLossModel,pldB,fc);
else
    distance = helperBluetoothEstimateDistance(pathLossModel,pldB);  
end

%% Display Results
% Display the estimated results and plot the spectrum of the transmitted and received BLE waveform.

% Display estimated BER and distance between the transmitter and the receiver.
disp(['Input configuration: ', newline , '    PHY transmission mode: ', phyMode,....
    newline,'    Path loss model: ', pathLossModel]);
disp(['Estimated outputs: ', newline , '    Path loss : ', num2str(pldB), ' dB'....
    newline,'    Distance between the transmitter and receiver: ', num2str(distance), ' m', newline, ...
    '    BER: ', num2str(ber)]);
% Plot the spectrum of the transmitted and received BLE waveform
specAnalyzer = dsp.SpectrumAnalyzer('NumInputPorts',2,'SampleRate',symbolRate*samplesPerSymbol,...
    'Title','Spectrum of Transmitted and Received BLE Signals',...
   'ShowLegend',true,'ChannelNames',{'Transmitted BLE signal','Received BLE signal'});
specAnalyzer(txWaveform,rxWaveform);
release(specAnalyzer);

% This example demonstrates an end-to-end BLE simulation for different PHY transmission modes by considering the path loss model, RF impairments, and AWGN. The obtained simulation results display the path loss, estimated distance between the transmitter and receiver, and BER. The spectrum of the transmitted and received BLE waveform is visualized by using a spectrum analyzer.
%% Appendix
% The example uses these helper functions:
% helperBluetoothEstimateDistance.m: Calculates the distance between the transmitter and receiver based on the obtained path loss and the assumed environment.
% helperBLEImpairmentsAddition.m: Adds RF impairments to the BLE waveform.
% helperBLEPracticalReceiver.m: Demodulates and decodes the received BLE waveform.
% helperBLEReceiverInit.m: Initializes BLE receiver parameters.
% helperBLEImpairmentsInit.m: Initializes RF impairment parameters.
%% Selected Bibliography
% [1] Bluetooth Special Interest Group (SIG). "Bluetooth Core Specification". Version 5.2. https://www.bluetooth.com.
% [2] Path Loss Models Used in Bluetooth Range Estimator. Bluetooth Special Interest Group (SIG). https://www.bluetooth.com.
% [3] Rappaport, Theodore. Wireless Communication – Principles and Practice. Prentice Hall, 1996.
% [4] NIST Smart Grid Interoperability Panel Priority Action Plan 2: Guidelines for Assessing Wireless Standards for Smart Grid Applications. National Institute of Standards and Technology, U.S. Department of Commerce, 2014, https://nvlpubs.nist.gov/.
% Copyright 2020 The MathWorks, Inc.