%% Statistical Modeling of WLAN Interference on BLE Network
%
% This example shows how to simulate the statistical modeling of WLAN
% interference on Bluetooth(R) low energy (BLE) network using the
% Communications Toolbox(TM) Library for the Bluetooth Protocol.
% Coexistence mechanisms are used to minimize the interference of WLAN on
% BLE network. In this example, the collision probability of each WLAN
% network is used to corrupt the BLE signals. The simulation results
% generated in this example conclude that for high collision probability of
% a WLAN channel, the achieved success rate of the respective BLE channel
% is low.

% Copyright 2018-2020 The MathWorks, Inc.

%% BLE-WLAN Coexistence Mechanism
%
% 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. This interference can cause transmission
% failures in both the networks. There is no standardized algorithm to
% achieve coexistence of two different wireless networks. However, the
% IEEE(R) 802.15.2(TM) standard [ <#12 1> ] specifies some recommended
% practices to achieve the coexistence of wireless personal area networks
% (WPAN) with other wireless devices operating in unlicensed frequency
% bands.
%
% This example illustrates a statistical modeling of WLAN interference on
% BLE network. WLAN communication requires a minimum of 20 MHz bandwidth,
% while BLE devices require only 2 MHz bandwidth. WLAN uses a channel
% access mechanism called carrier-sense multiple access with collision
% avoidance (CSMA/CA), while BLE devices use frequency hopping.
% Interference occurs when the operating frequency of BLE and WLAN devices
% overlap. To minimize the interference, coexistence mechanisms are used.
%
% Coexistence mechanisms are broadly classified into these two categories [
% <#12 1> ]:
%
% * *Collaborative:* This mechanism requires a communication link between
% the BLE and WLAN networks. Since these two networks can communicate with
% each other, one of these networks pauses its transmission while the other
% is using the channel. This mechanism is used when the WLAN and BLE
% devices are embedded into the same physical device.
% * *Non-Collaborative:* This mechanism does not require any communication
% link between the BLE and WLAN networks. Since these two networks cannot
% communicate with each other, they use their own methods to detect the
% interference of the other network. This mechanism is used when the WLAN
% and BLE devices are not embedded into the same physical device.
%
% This example illustrates a non-collaborative coexistence mechanism for
% BLE devices with WLAN.

%% BLE Coexistence with WLAN - Model Description
%
% This section elaborates the data communication in BLE, WLAN interference
% and coexistence algorithm used for avoiding the interference in this
% example.
%
% *Communication in BLE:* BLE defines two major roles at the Link Layer,
% namely the Master and the Slave. Master initiates the data communication
% and Slave responds to the Master. In this example, BLE packet exchange is
% modeled between one Master and multiple (configurable up to 5) Slaves. In
% BLE [ <#12 2> ], data communication occurs only during connection events.
% A connection event is a recurring (at regular intervals called connection
% interval) sequence of data packets exchange between a Master and a Slave.
% All the packets within a connection event are transmitted on the same
% data channel. At the start of every connection event, the Master
% initiates communication with the respective Slave. Thereafter, the Slave
% responds to the Master with a data packet. If there is no data to send,
% the Slave responds with an empty packet. In this example, only one
% transaction is modeled per connection event. A new connection event uses
% a new data channel. The new channel is selected based on adaptive channel
% hopping. A channel map indicating good or bad channels is used while
% selecting a new channel, thus showing the adaptiveness in channel
% hopping.
%
% *WLAN traffic:* WLAN traffic is dynamically added to, or removed from,
% the model according to the specified start and end times. Each WLAN
% network is configured with an individual collision probability. For every
% transmission, a random number between 0 and 1 is generated. If the
% generated random number is less than the collision probability, then the
% transmitting frame is corrupted.
%
% *BLE coexistence with WLAN:* If the selected BLE channel is significantly
% impacted by the WLAN interference based on collision probability, then
% the transmitted BLE packet will undergo corruption. The Master device
% periodically classifies the Slave channels as 'good channels' or 'bad
% channels', based on packet failures in that channel. The channel
% classification information is stored in the form of a bitmap called
% channel map. The bitmap is an array of 1's and 0's defining the
% classification of the channel (either 'good' or 'bad'). The
% <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLEChannelClassification.classifyChannels')
% classifyChannels> function classifies the BLE channels and stores the
% generated bitmap. The Master maintains a different channel map for each
% Slave. The updated channel map is sent to the Slave. The periodicity of
% channel classification is configured by setting the property
% |ClassificationInterval| in
% <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLEChannelClassification')
% helperBLEChannelClassification> object. BLE devices in idle state,
% calculate channel busy time for all the 'bad channels' by performing
% energy detection (ED). If the current number of good channels is less
% than the preferred number of good channels, the bad channels are
% classified again. This classification is based on the channel busy time
% when the |BadChannelClassificationMethod| property is set to _'Using
% energy indications'_. If the |BadChannelClassificationMethod| property is
% set to _'Reset all bad channels'_, all the bad channels are reset to good
% channels.
%
% <<../BLECoexistenceModelWithWLANStatistical.png>>

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

%% BLE Configuration Parameters
%
% This section adds a BLE Master device and the specified number of Slave
% devices to the BLE network. Since the Master is responsible for updating
% channel map for each Slave in a BLE network, the channel classification
% parameters are configured at the Master device using
% <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLEChannelClassification')
% helperBLEChannelClassification>. The
% <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLEDeviceModel')
% helperBLEDeviceModel> object is used to model the BLE coexistence with
% WLAN.

% The number of BLE Slaves in connection with the Master
slavesCount = 1;

% Create the BLE Master device capable of connecting with "slavesCount"
% number of Slaves
master = helperBLEDeviceModel('Role','Master', ...
    'SlavesCount',slavesCount);

% Initialize the channel classification parameters to classify the BLE
% channels into good or bad channels. PERThreshold:                 Packet
% error rate (PER) threshold value ClassificationInterval:
% Periodicity of channel classification RxStatusCount:
% Maximum number of received packets status MinRxCountToClassify:
% Minimum number of received packets status BadChannelClassificationMethod:
% Method for bad channels classification PreferredMinimumGoodChannels:
% Preferred number of good channels
channelClassification = helperBLEChannelClassification(...
    'PERThreshold',60, ...
    'ClassificationInterval',150, ...
    'RxStatusCount',50, ...
    'MinRxCountToClassify',4, ...
    'BadChannelClassificationMethod','Using energy detections', ...
    'PreferredMinimumGoodChannels',20);

% Assign channel classification parameters to the Master device
master.ChannelClassification = channelClassification;

% Initialize "slavesCount" number of Slaves
slaves(1, slavesCount) = helperBLEDeviceModel;

% Create "slavesCount" number of Slave devices
for idx = 1:slavesCount
    slaves(idx) = helperBLEDeviceModel('Role','Slave');
end

% Create "slavesCount" connections between the "Master" and "Slaves". This
% function creates a Link Layer connection by sharing the common connection
% parameters such as connection interval, access address for each
% Master-Slave connection pair.
[master, slaves] = helperBLECreateLLConnection(master, slaves);

%% Model WLAN Traffic
%
% This section models the WLAN traffic using specified configuration.
%
% *Configuration Parameters*
%
% The configuration parameters for each WLAN network includes collision
% probability, interference start time and interference end time in the
% specified WLAN channel. The
% <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLEWLANStatisticalTrafficConfig')
% helperBLEWLANStatisticalTrafficConfig> object is used to model the WLAN
% traffic.

% Set number of WLAN networks interfering with the BLE network
wlanNetworksCount = 6;

% Set of WLAN channels (in the range [1, 14]) used by each WLAN network
wlanChannels = [1, 5, 6, 12, 9, 8];
% Probability of collisions of each WLAN network with BLE network
collisionProbabilities = [0.35, 0.48, 0.26, 0.60, 0.28, 0.34];
% Start and end times (in milliseconds) of transmission in each WLAN
% network
wlanInterferencePeriod = [0, inf; ...
    0, inf; ...
    0, 2100; ...
    0, inf; ...
    200, 2800; ...
    150, inf];

%%
% *Model WLAN Traffic*
%
% This section configures the interference to each Slave by adding WLAN
% traffic with the specified configuration. WLAN network is added in all
% specified WLAN channels using
% <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLEWLANStatisticalTrafficConfig.wlanTraffic')
% wlanTraffic> function.

% Create a configuration object for WLAN traffic
wlanTrafficConfig = helperBLEWLANStatisticalTrafficConfig();

% Configure WLAN traffic with the specified WLAN network parameters
wlanTraffic(wlanTrafficConfig, wlanNetworksCount, wlanChannels, ...
    collisionProbabilities, wlanInterferencePeriod);


%% Coexistence Simulation
%
% This section illustrates the communication between Master and Slave
% devices while the WLAN is interfering statistically.
%
% *Initialize Simulation Parameters*
%
% The simulation parameters required for the statistical modeling of WLAN
% interference on BLE network are initialized in this code.

% Initialize simulation parameters

% Reset the random number generator seed
sprev = rng('default');

% To enable the visualization of BLE coexistence with WLAN, set the
% "enableVisualization" to true. To disable the visualization of BLE
% coexistence with WLAN set the "enableVisualization" to false.
enableVisualization = true;

% To enable the visualization of channel hopping sequence, set the
% "enableHoppingVisualization" to true. To disable the visualization of
% channel hopping sequence, set the "enableHoppingVisualization" to false.
% If the "enableVisualization" is set to false, then
% "enableHoppingVisualization" is not considered.
enableHoppingVisualization = true;

% Total simulation time in milliseconds
simulationTime = 4000;

% One step time is considered as 0.025 milliseconds. All the timing
% parameters (connection interval, scan interval, advertising interval,
% etc.) in BLE specification are multiple of 0.625 milliseconds. The
% maximum packet size used in this example is 33 octets (264 bits). The
% packet transmission time in different PHY modes are: 0.264 milliseconds
% (in LE1M), 0.132 milliseconds (in LE2M), 0.528 milliseconds (in LE500K)
% and 1.056 milliseconds (in LE125K). Therefore, the step time is
% considered as 0.025 milliseconds (0.625 is multiple of 0.025) to achieve
% a trade-off between the simulation time and accuracy.
timeStep = 0.025;

% Create structure for an empty packet to initialize the output of Master
% and Slaves LLPDU:        Generated Link Layer Protocol Data Unit (PDU)
% appended with
%               Cyclic Redundancy Check (CRC)
% RateIndex:    String representing the rate at which the packet will be
%               transmitted. It contains one of 'LE2M' | 'LE1M' | 'LE500K'
%               | 'LE125K'
% AccessAddress:Unique address for each Master-Slave connection pair
% ChannelIndex: Channel on which the packet is transmitted
emptyPacket = struct('LLPDU',[], ...
    'AccessAddress','', ...
    'RateIndex','', ...
    'ChannelIndex',-1);

% Initialize the Slave output
slaveOutput = emptyPacket;

% Preallocate the buffers to store the Slave outputs
slaveOutputs = cell(1, slavesCount);

%%
% *Simulation*
%
% This section simulates the exchange of packets between a BLE Master and
% Slave devices for a specified amount of time.
%
% * *Master (Transmission or Reception)*: In each connection event, BLE
% Master initiates the communication with the respective Slave by
% transmitting a Link Layer packet on a data channel. The generated BLE
% packet is corrupted based on the WLAN collision probability of the
% respective channel. After transmission, the Master waits for the response
% from the Slave.
%
% * *Slave (Transmission or Reception)*: In each connection event, BLE
% Slave receives the interfered packet from the Master on a data channel.
% Thereafter, the Slave responds to the Master on the same data channel by
% transmitting a Link Layer packet. The generated BLE packet is corrupted
% based on the WLAN collision probability of the respective channel.
%
% The
% <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLEDeviceModel.run')
% run> function of
% <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLEDeviceModel')
% helperBLEDeviceModel> is used for communication between BLE Master and
% Slave devices. The
% <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLEWLANStatisticalTrafficConfig.getInterferenceLevel')
% getInterferenceLevel> function verifies whether or not the BLE channel is
% significantly interfered by the WLAN traffic. The
% <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLEVisualizeCoexistence')
% helperBLEVisualizeCoexistence> visualizes the simulation of BLE
% coexistence with WLAN traffic.

% Initialize figures for visualization of coexistence model for each Slave.
% This visualization shows the WLAN channels along with their collision
% probabilities and also shows the channel hopping for the communication
% between BLE Master and Slave devices. It also shows the status (good or
% bad) of each BLE channel along with the success rate in the respective
% channel.
coexistenceModel = ...
    helperBLEVisualizeCoexistence(...
    'Action','Initialize', ...
    'SlaveCount',slavesCount, ...
    'WLANChannelList',wlanChannels, ...
    'PERThreshold',master.ChannelClassification.PERThreshold, ...
    'ClassificationInterval',master.ChannelClassification.ClassificationInterval, ...
    'ChannelBusyCountThreshold',master.ChannelClassification.ChannelBusyCountThreshold, ...
    'PreferredMinimumGoodChannels',master.ChannelClassification.PreferredMinimumGoodChannels, ...
    'ConnectionInterval',master.LLConnectionConfigs(1).ConnectionInterval, ...
    'Stoptime',simulationTime, ...
    'EnableVisualization',enableVisualization, ...
    'EnableHoppingVisualization',enableHoppingVisualization);
coexistenceModel.initializeVisualization();
viewModel(coexistenceModel);
master.CoexistenceVisualization = coexistenceModel;

% Run simulation
for simulationTimer = 0:timeStep:simulationTime
    % Stop the simulation, if all the Slaves are disconnected from the
    % Master due to interference. Master and Slave are disconnected when
    % the PER of the BLE channels in which they are communicating with each
    % other is high.
    if numel(master.ActiveConnectionIdxs(master.ActiveConnectionIdxs ~= -1)) == 0
        fprintf('Simulation terminated as all Slaves are disconnected from the Master device.\n')
        break;
    end
    
    % Update WLAN traffic in visualization
    helperBLEUpdateWLANTraffic(slavesCount, wlanChannels, wlanTrafficConfig, ...
        simulationTimer, master);
    
    % MASTER: Transmitting or Receiving mode
    if (master.ActiveChannel == slaveOutput.ChannelIndex) && ...
            strcmpi(master.ActiveAccessAddress, slaveOutput.AccessAddress)
        masterOutput = run(master, slaveOutput);
    else
        masterOutput = run(master, emptyPacket);
    end
    
    if ~(isempty(masterOutput.LLPDU))
        interferenceEffect = getInterferenceLevel(wlanTrafficConfig, ...
            masterOutput.ChannelIndex, simulationTimer);
        % Corrupt the packet, if the interference effect is 1
        if (interferenceEffect == 1)
            masterOutput.LLPDU(1:2) = ~masterOutput.LLPDU(1:2);
            % Drop the packet, if the interference effect is 2
            % (interference is too high)
        elseif (interferenceEffect == 2)
            masterOutput = emptyPacket;
        end
    end
    
    % Update current simulation time
    coexistenceModel.CurrentTime = simulationTimer;
    coexistenceModel.Action = 'Simulation Progress';
    
    % SLAVE: Transmitting or Receiving mode
    for idx = 1:slavesCount
        % Pass the "MasterOutput" to the Slave listening in the same
        % frequency and matched access address
        if (slaves(idx).ActiveChannel == masterOutput.ChannelIndex) && ...
                strcmpi(slaves(idx).ActiveAccessAddress, masterOutput.AccessAddress)
            slaveOutputs{idx} = run(slaves(idx), masterOutput);
            % Pass an empty packet to all other Slaves to update the timers
        else
            slaveOutputs{idx} = run(slaves(idx), emptyPacket);
        end
        
        % Update simulation progress for each Slave
        coexistenceModel.SlaveNumber = idx;
        viewModel(coexistenceModel)
    end
    
    slaveOutput = emptyPacket;
    
    % Get the active Slave output (At any time instance only one Slave is
    % active)
    for idx = 1:slavesCount
        if ~isempty(slaveOutputs{idx}.LLPDU)
            slaveOutput = slaveOutputs{idx};
            break;
        end
    end
    
    if ~(isempty(slaveOutput.LLPDU))
        interferenceEffect = getInterferenceLevel(wlanTrafficConfig, ...
            slaveOutput.ChannelIndex, simulationTimer);
        % Corrupt the packet, if the interference effect is 1
        if (interferenceEffect == 1)
            slaveOutput.LLPDU(1:2) = ~slaveOutput.LLPDU(1:2);
            % Drop the packet, if the interference effect is 2
            % (interference is too high)
        elseif (interferenceEffect == 2)
            slaveOutput = emptyPacket;
        end
    end
end

% Update the simulation progress for each Slave
for idx = 1:slavesCount
    master.CoexistenceVisualization.SlaveNumber = idx;
    master.CoexistenceVisualization.Action = 'Simulation Progress';
    viewModel(master.CoexistenceVisualization)
end

% Log the statistics of this example to
% |bleCoexistenceWithStatisticalWLANStatistics.mat| file
helperBLELogCoexistenceStats(master, slaves, ...
    'bleCoexistenceWithStatisticalWLANStatistics.mat');

% Restore the previous setting of random number generation
rng(sprev);

%% Simulation results
%
% The simulation of this example generates:
%
% # A run-time plot for each Master-Slave connection pair depicting the
% status (good or bad) and the cumulative, recent success rates of each
% channel is displayed
% # A MAT file _bleCoexistenceWithStatisticalWLANStatistics.mat_ with
% detailed statistics such as number of packets received, number of packets
% corrupted on each channel and status (good or bad) of the channel for
% each classification interval is obtained

%%
%
% This example enables you to analyze the BLE coexistence with WLAN
% statistical interference. Collision probability of each WLAN network is
% used to corrupt the BLE packets. The BLE Master and Slave devices use
% good channels to communicate with each other to avoid packet loss. The
% success rate is calculated at each BLE channel. This example concludes
% that for high collision probability of a WLAN channel, the achieved
% success rate of the respective BLE channel is low. Therefore, these
% channels are not used for communication between BLE Master and Slave
% devices.

%% Appendix
%
% The example uses these features:
%
% * <docid:comm_ref#sysobj_bleChannelSelection bleChannelSelection>: Select
% a BLE channel index
% * <docid:comm_ref#obj_bleLLDataChannelPDUConfig
% bleLLDataChannelPDUConfig>: Create a configuration object for BLE Link
% Layer data channel PDU
% * <docid:comm_ref#mw_161d6aa9-0483-4c84-9635-deaff3f09b70
% bleLLDataChannelPDU>: Generate BLE Link Layer data channel PDU
% * <docid:comm_ref#mw_b8b55044-0492-4daa-9ce6-dfe4f355c30f
% bleLLDataChannelPDUDecode>: Decode BLE Link Layer data channel PDU
%
% The example uses these helpers:
%
% * <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLEChannelClassification')
% helperBLEChannelClassification>: Create an object BLE channel
% classification
% * <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLEWLANStatisticalTrafficConfig')
% helperBLEWLANStatisticalTrafficConfig>: Create a configuration object for
% WLAN signal traffic
% * <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLEDeviceModel')
% helperBLEDeviceModel>: Create an object for BLE device
% * <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLELLConnectionEvent')
% helperBLELLConnectionEvent>: Create an object for BLE Link Layer
% connection events
% * <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLELLConnectionEventStatus')
% helperBLELLConnectionEventStatus>: Enumeration to indicate the status of
% BLE Link Layer connection events
% * <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLEConnectionStateModel')
% helperBLEConnectionStateModel>: Create an object for a BLE Link Layer
% connection
% * <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLECreateLLConnection')
% helperBLECreateLLConnection>: Create a connection between BLE Master and
% BLE Slave devices
% * <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLEUpdateWLANTraffic')
% helperBLEUpdateWLANTraffic>: Update WLAN traffic in the visualization at
% the simulation timer
% * <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLEVisualizeCoexistence')
% helperBLEVisualizeCoexistence>: Create an object to visualization the
% coexistence model
% * <matlab:openExample('BLECoexistenceWithWLANStatisticalExample','supportingFile','helperBLELogCoexistenceStats')
% helperBLELogCoexistenceStats>: Log the coexistence statistics to MATLAB
% workspace

%% Selected Bibliography
%
% # IEEE(R) Standard 802.15.2(TM). "Coexistence of Wireless Personal Area
% Networks with Other Wireless Devices Operating in Unlicensed Frequency
% Bands". _IEEE Recommended Practice for Information technology -
% Telecommunications and information exchange between systems - Local and
% metropolitan area networks - Specific requirements; IEEE Computer
% Society_
% # Bluetooth Special Interest Group (SIG). "Bluetooth Core Specification".
% Version 5.0. https://www.bluetooth.com/