%% 802.11 MAC and Application Throughput Measurement
% This example shows how to measure the MAC and application layer
% throughput in a multi-node 802.11a/n/ac/ax network using SimEvents(R),
% Stateflow(R), and WLAN Toolbox(TM). The system-level model presented in
% this example includes functionalities such as configuring the priority of
% the traffic at the application layer, capability to generate and decode
% waveforms of Non-HT, HT-MF, VHT, HE-SU and HE-EXT-SU formats, MPDU
% aggregation and enabling block acknowledgment of MPDUs. The application
% layer throughput calculated using this model is validated against
% published calibration results from the TGax Task Group [ <#11 4> ] for
% Box 3 scenarios (Tests 1a, 1b, and 2a) specified in TGax evaluation
% methodology [ <#11  3> ]. The obtained application layer throughput is
% within the range of minimum and maximum throughput specified in published
% calibration results [ <#11 4> ].

% Copyright 2019-2020 The MathWorks, Inc.

%% Throughput in 802.11 Networks
% The IEEE(R) 802.11(TM) working group is continually adding features to
% 802.11 specification [ <#11 1> ] to improve the throughput and
% reliability in WLAN networks. Throughput is the amount of data
% transmitted over a period of time. Medium Access Control (MAC) layer
% throughput refers to the amount of data successfully transmitted by the
% MAC layer over a period of time. MAC protocol data unit (MPDU) is the
% unit of transmission at MAC layer. In 802.11n, MPDU aggregation was
% introduced to increase the throughput. When MPDU aggregation is
% supported, MAC layer aggregates multiple MPDUs into an aggregated MPDU
% (A-MPDU) for transmission. This reduces the overhead of channel
% contention for transmitting multiple frames, resulting in enhanced
% throughput. In 802.11ac [ <#11 1> ] and 802.11ax [ <#11 2> ], the maximum
% limits for an A-MPDU length were increased resulting in even better
% throughput in WLAN networks.

%% Model 802.11 Network
% This example models a WLAN network with five nodes as shown in this
% figure. These nodes implement carrier-sense multiple access with
% collision avoidance (CSMA/CA) with physical carrier sense and virtual
% carrier sense. The physical carrier sensing uses the clear channel
% assessment (CCA) mechanism to determine whether the medium is busy before
% transmitting. Whereas, the virtual carrier sensing uses the RTS/CTS
% handshake to prevent the hidden node problem. 
%
% The model in the example displays various statistics such as the number
% of transmitted, received, and dropped packets at PHY and MAC layers.
% Moreover, the runtime figures that help in analyzing/estimating the
% node-level and network-level performance are also displayed in this
% model. This model is validated against the published calibration results
% from the TGax Task Group [ <#11 4> ] for Box 3 scenarios (Tests 1a, 1b,
% and 2a) specified in TGax evaluation methodology [ <#11 3> ].
%
% *WLAN Network*
%
% <<../wlanNetwork.png>>
%
% *Components of a WLAN Node*
%
% The components of a WLAN node are shown in this figure. The information
% is retrieved by pressing the arrow button for each node in the above
% figure.
%
% <<../wlanNode.png>>

%% Application, EDCA MAC and PHY Block Enhancements
% This example is an enhancement over
% <docid:wlan_examples#example-MultiNode80211aPhyMACExample Multi-Node
% 802.11a Network Modeling with PHY and MAC> example. Refer to the example
% documentation page for more information about each layer in a WLAN node.
% The application, the EDCA MAC and the PHY blocks used in this example has
% these enhancements over
% <docid:wlan_examples#example-MultiNode80211aPhyMACExample Multi-Node
% 802.11a Network Modeling with PHY and MAC>.
%
% *Application:* 
%
% The application layer has the capability to generate data with different
% priority levels as shown in this figure. These priority levels are configured using |Access
% Category| property in the mask parameters of the Application Traffic
% Generator block inside a WLAN node.
%
% <<../appConf.png>>
% 
% *EDCA MAC:* 
% 
% The EDCA MAC block used in this example has these enhancements over MAC
% block used in <docid:wlan_examples#example-MultiNode80211aPhyMACExample
% Multi-Node 802.11a Network Modeling with PHY and MAC> example
%
% * Generate and decode MAC frames of high efficiency single user (HE-SU),
% high efficiency extended range single user (HE-EXT-SU), very high
% throughput (VHT), high throughput mixed format (HT-MF) and Non-HT
% formats. These formats are configured using the |PHY Tx Format| property
% in the mask parameters of the MAC EDCA block inside a WLAN node as shown
% in this figure.
% * Aggregate MPDUs to form an A-MPDU. This can be configured by setting
% |PHY Tx Format| to one of |HT-MF|, |VHT|, |HE-SU|, or |HE-EXT-SU|. In
% case of |HT-MF|, |MPDU Aggregation| property must also be enabled for
% A-MPDU generation.
% * Acknowledge multiple MPDUs in an A-MPDU with a single block
% acknowledgment (BA) frame. MAC assumes a pre-configured BA session
% between the transmitter and the receiver of an A-MPDU.
% * Enable/disable acknowledgments. This can be configured using the |Ack
% Policy| property.
% * Maintain separate retry limits for shorter frames (less than RTS
% threshold) and longer frames (greater than or equal to RTS threshold).
% These limits can be configured using the |Max Short Retries| and |Max
% Long Retries| properties.
% * Transmit multiple streams of data using the multiple-input
% multiple-output (MIMO) capability. You can configure this capability
% using the |Number of Transmit Chains| property. This property is
% applicable only when the value of |PHY Tx Format| property is set to
% |VHT|, |HE-SU|, or |HE-EXT-SU|. The MIMO capability can also be used for
% |HT| format through the |MCS| property. The range of values [0, 7], [8,
% 15], [16, 23], and [24, 31] correspond to one, two, three, and four
% streams of data respectively.
% * Adapt the data rate according to the channel conditions through the
% |Rate Adaptation Algorithm| property. This is applicable only when the
% value of |PHY Tx Format| property is set to |Non-HT|. You can choose
% between |Auto Rate Fallback (ARF)| and |Minstrel| algorithms. To maintain
% a constant data rate throughout the simulation, |Fixed-Rate| option is
% available.
%
% <<../macConf.png>>
%
% *PHY:*
%
% Capability to generate and decode waveforms of Non-HT, HT-MF, VHT, HE-SU
% and HE-EXT-SU formats

%% Throughput Measurement
% Throughput varies for different configuration parameters pertaining to
% the application, MAC & PHY layers. Any change in the configuration may
% either increase or decrease the throughput. You can vary the combination
% of these parameters to measure and analyze the throughput.
%
% * |MCS|: PHY data rate
% * |PHY Tx Format|: PHY transmission format
% * |Packet Size|: Application packet size
% * |Max A-MPDU Subframes|: Maximum number of subframes in an A-MPDU
% * |Max Tx Queue Size|: MAC transmission queue size
%
% Along with above parameters, you can also vary the node positions, Tx &
% Rx gains, channel loss, number of nodes in the network, MAC contention
% parameters, number of transmit chains and rate adaptation algorithms to
% analyze MAC throughput. This example demonstrates the measurement and
% analysis of the MAC throughput by varying packet size in the |Application
% Traffic Generator| block.
%
% *Application Packet Size*
%
% Throughput is directly proportional to the application packet size.
% Smaller packet size results in greater number of packets to be
% transmitted. At the MAC layer, there is an overhead of contention time
% for each transmitted packet. This is because the MAC layer makes sure
% that the channel is idle for a specific amount of time (Refer section
% 10.3.2.3 of [ <#11 1> ]) before transmitting any packet. Therefore, as
% the packet size decreases, the contention overhead increases resulting in
% lower throughput.
%
% *Model Configuration*
%
% You can configure the application packet size using these steps:
% 
% # Open model |WLANMACThroughputMeasurementModel.slx|
% # To go inside a node subsystem, click on the downward arrow at the
% bottom left of the node
% # To open mask parameters of the application, double click on
% |Application Traffic Generator|
% # To enable application, set |App State| to 'On'
% # Configure the value of |Packet Size|
%
% Run the simulation and observe the throughput. The TGax calibration
% results for test-1a in [ <#11 4> ] are shown below:
%
% <<../test1a_MCS0.png>>
%
% The above plot compares the calibration results for WLAN Toolbox against
% the published results of other companies listed in [ <#11 4> ]. The blue
% colored curve represents the results of WLAN Toolbox, while the grey
% colored curves represent the results of other companies.

%% Simulation Results
% The simulation of the model generates:
%
% # A run-time visualization showing the time spent on channel contention,
% transmission, and reception for each node
% # An optional run-time visualization (during the simulation) showing
% the number of frames queued in MAC transmission queues for a selected
% node.
% # A bar graph showing metrics for each node such as number of
% transmitted, received, and dropped packets at PHY and MAC layers
% # A MAT file |statistics.mat| with detailed statistics obtained
%  at each layer for each node
%
% This figure shows MAC state transitions with respect to simulation time.
%
% <<../states.png>>
%
% You can also observe the live state of the MAC layer transmission buffers
% using the 'Observe MAC queue lengths' button in the above
% visualization.
%
% <<../queueLengths.png>>
%
% This figure shows the network statistics at the end of simulation.
%
% <<../networkStats.png>>
%

%% Validating Application Layer Throughput with TGax Calibration Results
% The TGax Task Group [ <#11 4> ] published application throughput results
% for different scenarios. You can observe the Layer 3 (above MAC layer)
% throughput of each node in the network in 'Throughput' column in
% 'statisticsTable' stored in 'statistics.mat'. The TGax calibration
% scenarios for MAC simulator published results of application throughput
% for a User Datagram Protocol (UDP) with Logical Link Control (LLC) layers
% overhead.
%
% To calculate application throughput from simulation results use the code
% below:

% Load statistics.mat (Output of the simulation) file
simulationResults = load('statistics', 'statisticsTable');
% Statistics
stats = simulationResults.statisticsTable;

% Successfully transmitted MAC layer bytes in the network
totalMACTxBytes = sum(stats.MACTxBytes);

% UDP & LLC overheads (bytes)
udpOverhead = 36;
llcOverhead = 8;

% UDP & LLC overhead (bytes) in the network
udpAndLLCOverhead = sum(stats.MACTxSuccess)*(udpOverhead + llcOverhead);

% Successfully transmitted application bytes
totalAppTxBytes = totalMACTxBytes - udpAndLLCOverhead;

% Time at which last transmission is completed in the network (Microseconds)
simulationTime = max(stats.MACRecentFrameStatusTimestamp);

% Application throughput (Mbps)
applicationThroughput = (totalAppTxBytes*8)/simulationTime;
disp(['Application Throughput = ' num2str(applicationThroughput) ' Mbps']);

%%
% The application throughput for different TGax calibration scenarios is
% plotted against different MAC service data unit (MSDU) sizes for a
% simulation time of 30 seconds as shown below:
%
% <<../test1a_MCS8.png>>
%
% <<../test1b_MCS0.png>>
%
% <<../test1b_MCS8.png>>
%
% <<../test2a_withoutRTS.png>>
%
% <<../test2a_withRTS.png>>

%% Further Exploration
% *Configuration options*
%
% You can change these configuration parameters to further explore this
% example:
%
% * Application layer: Access category and packet interval
% * MAC layer: RTS threshold, Tx queue size, data rate, short retry limit,
% long retry limit, transmitting frame format, MPDU aggregation, ack
% policy, number of transmit chains and the rate adaptation algorithms
% * PHY: PHY Tx gain, PHY Rx gain, and Rx
% noise figure
% * Channel modeling: Rayleigh fading, free space pathloss, range
% propagation loss and packet receive range
% * Node positions using node position allocator
% * The state of each node can be visualized during the run-time through
% the configuration available in the Visualizer block
% * By default, the PHY transmitter and the receiver blocks run in the
% |Interpreted execution| mode. For longer simulation time, configure all
% the blocks to |Code generation| mode for better performance.
%
% *Related examples*
%
% Refer these examples for further exploration:
%
% * To simulate the MAC Quality of Service (QoS) traffic scheduling in
% 802.11a/n/ac/ax networks, refer
% <docid:wlan_examples#example-WLANMACQoSSchedulingExample 802.11 MAC QoS
% Traffic Scheduling> example.
%
% * To model a multi-node IEEE 802.11ax network with abstracted PHY, refer
% <docid:wlan_examples#example-WLANMultiNodeAbstractedPHYExample 802.11ax
% System-Level Simulation with Physical Layer Abstraction> example.
%
% * To model a multi-node network using Distributed Coordination Function
% (DCF) MAC and 802.11a PHY, refer
% <docid:wlan_examples#example-MultiNode80211aPhyMACExample Multi-Node
% 802.11a Network Modeling with PHY and MAC> example.

%%
% This example enables you to create and configure a multi-node 802.11
% network using a Simulink model for analyzing the MAC and application
% layer throughput. In this model, the MAC throughput obtained through the
% simulation results is used to calculate the application layer throughput.
% This model is validated using the Box 3 scenarios (Tests 1a, 1b, and 2a)
% specified in TGax evaluation methodology [ <#11 3> ] to confirm that it
% complies with the IEEE 802.11 [ <#11 1> ]. This example concludes that
% the calculated application layer throughput is within the range of
% minimum and maximum throughput specified in published calibration results
% [ <#11 4> ].

%% Appendix
% The helper functions and objects used in this example are:
%
% # <matlab:edit('edcaFrameFormats.m') edcaFrameFormats.m>: Create an
% enumeration for PHY frame formats.
% # <matlab:edit('edcaNodeInfo.m') edcaNodeInfo.m>: Return MAC address of
% a node.
% # <matlab:edit('edcaPlotQueueLengths.m') edcaPlotQueueLengths.m>: Plot
% MAC queue lengths in the simulation.
% # <matlab:edit('edcaPlotStats.m') edcaPlotStats.m>: Plot MAC state
% transitions with respect to simulation times.
% # <matlab:edit('edcaStats.m') edcaStats.m>: Create an enumeration for
% simulation statistics.
% # <matlab:edit('edcaUpdateStats.m') edcaUpdateStats.m>: Update statistics
% of the simulation.
% # <matlab:edit('helperAggregateMPDUs.m') helperAggregateMPDUs.m>:
% Generate an A-MPDU, by creating and appending the MPDUs containing the
% MSDUs in the MSDULIST.
% # <matlab:edit('helperSubframeBoundaries.m') helperSubframeBoundaries.m>:
% Return subframes information of an A-MPDU.
% # <matlab:edit('phyRx.m') phyRx.m>: Model PHY operations related to
% packet reception.
% # <matlab:edit('phyTx.m') phyTx.m>: Model PHY operations related to
% packet transmission.
% # <matlab:edit('edcaApplyFading.m') edcaApplyFading.m>: Apply Rayleigh
% fading effect on the waveform.
% # <matlab:edit('heSIGBUserFieldDecode.m') heSIGBUserFieldDecode.m>:
% Decode HE-SIG-B user field.
% # <matlab:edit('heCPECorrection.m') heCPECorrection.m>: Estimate and
% correct common phase error.
% # <matlab:edit('heSIGBCommonFieldDecode.m') heSIGBCommonFieldDecode.m>:
% Decode HE-SIG-B common field.
% # <matlab:edit('heSIGBMergeSubchannels.m') heSIGBMergeSubchannels.m>:
% Merge 20MHz HE-SIG-B subchannels.
% # <matlab:edit('addMUPadding.m') addMUPadding.m>: Add multiuser PSDU
% padding.
% # <matlab:edit('macQueueManagement.m') macQueueManagement.m>: Create a
% WLAN MAC queue management object.
% # <matlab:edit('roundRobinScheduler.m') roundRobinScheduler.m>: Create a
% round-robin scheduler object.
% # <matlab:edit('calculateSubframesCount.m') calculateSubframesCount.m>:
% Return number of subframes to be aggregated.
% # <matlab:edit('interpretHESIGABitsFailCheck.m')
% interpretHESIGABitsFailCheck.m>: Interpret HE-SIG-A bits with failure
% check.
% # <matlab:edit('interpretVHTSIGABitsFailCheck.m')
% interpretVHTSIGABitsFailCheck.m>: Interprets the bits in VHT-SIG-A field
% # <matlab:edit('rateAdaptationARF.m') rateAdaptationARF.m>: Create an
% auto rate fallback (ARF) algorithm object.
% # <matlab:edit('rateAdaptationMinstrelNonHT.m')
% rateAdaptationMinstrelNonHT.m>: Create a minstrel algorithm object.

%% References
% # IEEE Std 802.11(TM). "Wireless LAN Medium Access Control (MAC) and
% Physical Layer (PHY) Specifications." IEEE Standard for Information
% technology-Telecommunications and information exchange between systems,
% Local and metropolitan area networks-Specific requirements.
% # IEEE P802.11ax(TM)/D4.1. "Amendment 6: Enhancements for High Efficiency
% WLAN.." Draft Standard for Information technology - Telecommunications
% and information exchange between systems Local and metropolitan area
% networks - Specific requirements -Part 11: Wireless LAN Medium Access
% Control (MAC) and Physical Layer (PHY) Specifications.
% # IEEE 802.11-14/0571r12. "11ax Evaluation Methodology." IEEE P802.11P:
% Wireless LANs.
% # Baron, Stephane., Nezou, Patrice., Guignard, Romain., and Viger,
% Pascal. "MAC Calibration Results." Presentation at the IEEE P802.11 -
% Task Group AX, September 2015.
