%% Link Layer State Machine for BLE Devices using Stateflow
%
% This example shows how to model link layer state machine to establish a
% connection between Bluetooth(R) low energy (BLE) devices using the
% Communications Toolbox(TM) Library for the Bluetooth Protocol and
% Stateflow(R). The working mechanism of the link layer is described in
% terms of a state machine consisting of these five states: Standby,
% Advertising, Scanning, Initiating, and Connection. Based on these states,
% the Bluetooth devices can either be Advertisers, Scanners, Initiators,
% Master or Slave. This example presents a model to demonstrate the
% connection establishment process between a Master and a Slave through
% transitions between different states of the link layer state machine. The
% simulation results display the time taken to establish a connection
% between a Master and a Slave. Moreover, this example also provides plots
% showing the variation in connection establishment time as a function of
% configuration parameters such as advertising interval and interference.

% Copyright 2018-2020 The MathWorks, Inc.

%% BLE Stack
%
% The Bluetooth core specification [ <#11 1> ] includes a low energy (LE)
% version for low-rate wireless personal area networks, referred as BLE or
% Bluetooth Smart. The BLE stack consists of: Generic Attribute Profile
% (GATT), Attribute Protocol (ATT), Security Manager Protocol (SMP),
% Logical Link Control and Adaptation Protocol (L2CAP), Link Layer (LL) and
% Physical layer (PHY). BLE was added to the Bluetooth Special Interest
% Group (SIG) [ <#11 1> ] standard for low energy devices generating small
% amount of data such as notification alerts used in applications like home
% automation, health-care, fitness, and Internet of Things (IoT).
%
% <<../BLEProtocolStack.png>>
%
% BLE operates in the 2.4 GHz ISM band at 2400 - 2483.5 MHz. It uses 40 RF
% channels and each channel is 2 MHz wide.
%
% BLE classifies these 40 RF channels into three advertising channels
% (channel indices: 37, 38, 39) and 37 data channels (channel indices: 0 -
% 36). Advertising channels are mainly used for creating connection between
% the BLE devices by transmitting advertising packets, scan
% request/response packets and connection indication packets. Data channels
% are mainly used after connection establishment for exchanging data
% packets.

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

%% BLE Link Layer State Machine Model
%
% The model in this example demonstrates the connection establishment
% process between two BLE devices, where one device acts as a Master and
% the other acts as a Slave. The Master device starts scanning for the
% advertising packets on the advertising channels. The Slave device starts
% sending advertising packets on advertising channels. After selecting an
% advertiser, the Master initiates a connection with it using the
% 'Connection indication' packet. The connection is established when the
% Slave receives this packet. Thereafter, the Master and Slave devices can
% exchange the data packets.

modelName = 'BLELinkLayerStateMachineModel';
open_system(modelName);
set_param(modelName,'Open','on');
set_param([modelName '/Channel Hopping'],'Open','off');

%% Link Layer States
%
% The link layer state machine is implemented using Stateflow(R) as shown
% below.
%
% <<../BLELLStatemachineLibrary.png>>
%
% The link layer maintains a state machine consisting of these five states:
%
% # *Standby* : This is the default state in the link layer. The device
% does not send or receive packets in this state. It may leave the Standby
% state to enter one of the Advertising, Scanning or Initiating states.
% # *Advertising* : In this state, the device transmits advertising packets
% in periodic intervals called advertising events. These devices are called
% advertisers.
% # *Scanning* : In this state, the device listens for advertisers on the
% advertising channels and transits to the Standby state for selecting an
% advertiser to initiate a connection.
% # *Initiating* : In this state, the device listens for a specific
% advertiser and initiates a connection with it. The device will move to
% Connection state after receiving the advertising packet from the selected
% advertiser. These devices are called initiators.
% # *Connection* : In this state, the device transmits data packets in
% periodic intervals called connection events.
%
% After the connection is established, the initiator becomes the Master
% (Central) device and the advertiser becomes the Slave (Peripheral)
% device.
%
% <<../BLELLStateMachine.png>>

%% Link Layer Events
%
% An advertising device transmits advertising packets on the three
% advertising channels in a cyclic manner (starting from channel index 37).
% Each cycle of advertising is called an advertising event. The same
% procedure is used by the scanning or the initiating device that listens
% on the three advertising channels in a cyclic manner called scan event.
%
% A connected device changes to a new data channel for every connection
% event. A connection event is a time frame for exchanging a sequence of
% data packets between two connected devices, which repeats at regular
% intervals. All the packets within a connection event are transmitted on
% the same data channel. A new connection event uses a new data channel.
% Two alternate channel selection algorithms are specified by the Bluetooth
% core specification (refer Section 4.5.8, Part-B, Vol-6 of [ <#11 1> ]).
% These algorithms are used to select the data channel for each connection
% event.
%
% This figure illustrates the connection establishment process between two
% BLE devices using link layer events:
%
% <<../BLELinkLayerEvents.png>>

%% Model Configuration
%
% The link layer state machine model demonstrated in this example use these
% two library blocks: Device and Wireless Medium.
%
% You can update the device configuration through the mask parameters of
% the Device block in the model. Based on the selected GAP role (Central/
% Peripheral), the mask will be updated with relevant properties.
%
% You can also configure the interference statistically for each
% advertising channel (37, 38 and 39) in the Wireless Medium block.

%% Simulation Results
%
% The results obtained in this simulation are:
%
% * *Connection establishment time*:
%
% This model outputs the time taken, in milliseconds, for establishing the
% connection. This time value is saved to a base workspace variable
% |timeTakenToEstablishConnection|.
%
% * *Channel hopping sequence*:
%
% The sequence of channel hops used by the Master and Slave devices is
% separately shown in a scope diagram.
%
% <<../BLEChannelHoppingStatistics.png>>
%
% * *Packet exchange between devices*
% 
% The packets exchanged between the Master and the Slave are captured in a
% PCAP format file with the name *BLEPacketExchange.pcap*. This PCAP file
% can be opened with any third-party packet analyzing software.
%
% <<../BLEPacketExchange.png>>
%
% * *Diagnostic log for device operations*
%
% You can enable or disable the message log using the settings of the
% Device block.
%
% <<../BLECommunicationModelDiagnostics.png>>

bdclose(modelName);
clear modelName;

%% Further Exploration
%
% In the simulation, you can vary the intervals and the interference to
% observe the variation of the connection establishment time. The
% simulation results are shown below:
%
% * *Simulation results without interference*:
%
% This plot shows how the connection establishment time varies with the
% advertising interval. Here, scan window is 10 milliseconds with a scan
% interval of 100 milliseconds i.e. 10% of the active period in scanning.
%
% <<../BLEConnectionTimeWithoutInterference.png>>
%
% Run <matlab:edit('helperBLEPlotConnectionTimeWithoutInterference')
% helperBLEPlotConnectionTimeWithoutInterference> script (long run
% simulation) for generating the above results.
%
% * *Simulation results with interference*:
%
% This plot shows how the average connection establishment time varies with
% different levels of interference. The plot also shows the variation for
% multiple values of advertising intervals. Here, scan window is 100
% milliseconds with a scan interval of 100 milliseconds i.e. 100% of active
% period in scanning. These connection establishment time values are
% averaged over 100 simulation runs for different values of advertising
% intervals and interference levels.
%
% <<../BLEConnectionTimeWithInterference.png>>
%
% Run <matlab:edit('helperBLEPlotConnectionTimeWithInterference')
% helperBLEPlotConnectionTimeWithInterference> script (long run simulation)
% for generating the above results.
%
% Apart from advertising interval, the connection establishment time varies
% with respect to multiple parameters such as scan interval, scan window,
% scan duration, advertising duration and interference. You can further
% explore by varying any of these parameters. Both the above simulations
% are run with scan and advertising duration of 1 and 10 seconds
% respectively.

%% Conclusion
%
% This example illustrates a link layer state machine model to establish a
% connection between two BLE devices namely: Master and Slave. This model
% gives detailed information about different link layer states and events.
% The state transition diagrams presented in this example clearly explain
% the process of connection establishment between the Master and the Slave.
% The derived simulation results display the time taken to establish a
% connection between the BLE devices. Furthermore, the derived plots also
% show that the connection establishment time varies with the configuration
% parameters such as advertising interval and interference.

%% Appendix
%
% The example uses these features:
%
% * <docid:comm_ref#mw_fccd1d53-97fd-42f0-bc75-3dcc8a93ca5e
% bleLLAdvertisingChannelPDU>: Generate LL advertising channel PDU
% * <docid:comm_ref#mw_0309e66e-dc52-4189-872e-2523a76669de
% bleLLAdvertisingChannelPDUDecode>: Decode LL advertising channel
% PDU
% * <docid:comm_ref#obj_bleLLAdvertisingChannelPDUConfig
% bleLLAdvertisingChannelPDUConfig>: Create a configuration object for
% generation and decoding of LL advertising channel PDU
% * <docid:comm_ref#mw_161d6aa9-0483-4c84-9635-deaff3f09b70
% bleLLDataChannelPDU>: Generate LL data channel PDU
% * <docid:comm_ref#mw_b8b55044-0492-4daa-9ce6-dfe4f355c30f
% bleLLDataChannelPDUDecode>: Decode LL data channel PDU
% * <docid:comm_ref#obj_bleLLDataChannelPDUConfig
% bleLLDataChannelPDUConfig>: Create a configuration object for generation
% and decoding of LL data channel PDU
% * <docid:comm_ref#obj_bleLLControlPDUConfig bleLLControlPDUConfig>:
% Create a sub-configuration object used in generation and decoding of data
% channel PDU
% * <docid:comm_ref#fcn_bleGAPDataBlock bleGAPDataBlock>: Generate GAP
% advertising and scan response data
% * <docid:comm_ref#fcn_bleGAPDataBlockDecode bleGAPDataBlockDecode>:
% Decode GAP advertising and scan response data
% * <docid:comm_ref#obj_bleGAPDataBlockConfig bleGAPDataBlockConfig>:
% Create a configuration object for generation and decoding of GAP data
% block
% * <docid:comm_ref#sysobj_bleChannelSelection bleChannelSelection>: Create
% a System object used for selecting a new data channel to transmit the
% data packet
% * <docid:comm_ref#mw_28e190f2-8546-4ccd-b1d9-a84bb841307a blePCAPWriter>:
%  Create BLE PCAP or PCAPNG file writer object
%
% The example uses these helpers:
%
% * <matlab:edit('helperBLELLConnectionEvent') helperBLELLConnectionEvent>:
% Create an object for BLE LL connection events
% * <matlab:edit('helperBLELLConnectionEventStatus')
% helperBLELLConnectionEventStatus>: Enumeration to indicate the status of
% BLE LL connection events
% * <matlab:edit('helperBLELLStateMachineEnumeration')
% helperBLELLStateMachineEnumeration>: Enumeration to indicate strings used
% in BLE LL state machine model
% * <matlab:edit('helperBLEGenerateRandomDeviceAddress')
% helperBLEGenerateRandomDeviceAddress>: Generate random device address for
% a Bluetooth device
% * <matlab:edit('helperBLEGetDurationInSteps')
% helperBLEGetDurationInSteps>: Calculate the number of steps required for
% timing parameters in the model based on stepunit
% * <matlab:edit('helperBLEPlotConnectionTimeWithoutInterference')
% helperBLEPlotConnectionTimeWithoutInterference>: Run multiple simulations
% varying advertising interval without interference
% * <matlab:edit('helperBLEPlotConnectionTimeWithInterference')
% helperBLEPlotConnectionTimeWithInterference>: Run multiple simulations
% varying advertising interval with interference

%% Selected Bibliography
%
% # Bluetooth(R) Technology Website. "Bluetooth Technology Website | The
% Official Website of Bluetooth Technology." Accessed July 8, 2020.
% https://www.bluetooth.com/.
% # "Development/LibpcapFileFormat - The Wireshark Wiki." Accessed July 8,
% 2020. https://wiki.wireshark.org/Development/LibpcapFileFormat.
