%% Multi-Node 802.11a Network Modeling with PHY and MAC
% This example shows how to model communication between multiple WLAN nodes
% containing medium access control (MAC) layer and PHY using SimEvents(R),
% Stateflow(R), and WLAN Toolbox(TM). This example models a 802.11 network
% consisting of five WLAN nodes. The distributed coordination function
% (DCF) in MAC is modeled as a Discrete Event Chart, whereas the PHY is
% modeled using MATLAB Discrete Event System block. The derived simulation
% results include a run-time plot displaying the time spent on channel
% contention, transmission, and reception for each node. A plot
% representing the per-node metrics such as number of transmitted,
% received, and dropped packets at PHY and MAC layers is also shown.

% Copyright 2019-2020 The MathWorks, Inc.

%% Background
% The IEEE(R) 802.11(TM) is a set of MAC and PHY specifications for WLAN
% implementation. A typical WLAN network will have multiple devices (nodes)
% sharing the same channel resources. Each node can have different types of
% applications transmitting or receiving packets from other nodes. As the
% nodes share the channel, their transmissions may collide or interfere
% with each other.
%
% Modeling a WLAN network with multiple nodes typically involves modeling
% the MAC layer, PHY, shared communication channel, data traffic
% pattern, and interference. This example shows how to model a multi-node
% WLAN network with 802.11a PHY and MAC using discrete event simulation.
%%
%% Multi-Node 802.11a Network Model
% This example models a WLAN network with five nodes. 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 outputs various statistics such as the number of
% transmitted, received, and dropped packets at PHY and MAC layers, and
% plots that help in analyzing/estimating the node-level and network-level
% performance.
%
% The modeling includes:
%
% * Multiple nodes, where each node contains an application, a MAC layer,
% and a PHY.
% * Packets transmitted over the channel, which is shared across multiple
% nodes.
% * A shared channel, which is simulated with these channel impairment
% options: free-space pathloss, range propagation loss and multi-path
% fading (using Rayleigh channel model).
% * A node position allocator, which is used to configure the position of
% nodes in the network.
%
% In the example, nodes 1, 2, and 3 are active participants in the
% communication, while nodes 4 and 5 passively receive the packets over the
% channel.
%
% <<../multiNodeNetwork.png>>

%%
%% Node
% Each node is modeled as a subsystem with a network stack, which includes
% application, MAC, and physical layers.
%
% <<../node.png>>
%
% * The application layer generates packets using SimEvents
% <docid:simevents_ref#bu3zmqp-1 Entity Generator> block.
% * The DCF in MAC is modeled as a Discrete Event Chart.
% * The PHY is modeled using SimEvents Discrete Event System block.
% * The shared channel is modeled inside each node in the receive path.
%%
%% Application Layer
% The application layer is implemented to generate and receive application
% traffic. It is divided into two sub-blocks:
%
% <<../application.png>>
%
% * AppTrafficGenerator &ndash; Uses SimEvents
% <docid:simevents_ref#bu3zmqp-1 Entity Generator> block to generate data
% packets with configured packet size, inter-packet interval, and
% destination node. These data packets are passed to the MAC layer.
% * AppTrafficReceiver &ndash; Uses SimEvents
% <docid:simevents_ref#bu30yzc-1 Entity Terminator> block to receive the
% data packets from MAC layer.

%%
%% MAC Layer
% The MAC layer implements the DCF algorithm specified in section 10.3 of [
%  <#24 1> ]. Before transmitting a packet, the MAC layer senses the shared
% channel to determine the state of the channel. If the channel is idle,
% packet transmission is initiated. If the channel is busy, packet
% transmission is deferred. The packets waiting for transmission are
% queued.
%
% In the model, the MAC layer has two components: queue management and
% contention algorithm.
%
% *Queue Management*
%
% Packets received from the application layer are queued until the channel
% is available. Packets are dequeued for transmission once the channel
% becomes available. The size of the queue is configurable. The default
% queue size is 10.
%
% <<../queueManagement.png>>
% 
% *Contention Algorithm*
%
% The contention algorithm implemented in the MAC layer is the DCF
% functionality specified in section 10.3 of [ <#24 1> ]. It is implemented
% as a finite state machine with these six different states:
%
% * Idle: No active operations
% * Contend: Contends for the channel
% * Rx: Receives and processes the frame
% * WaitForRx: Waits for a response frame
% * SendingData: Transmits a frame
% * Eifs: Defers transmission for error recovery
%
% <<../contentionAlgorithm.png>>
%
% *State Level Processing in the MAC Layer*
%
% * Initially the MAC layer is in _Idle_ state. On receiving a packet from
% the application layer, the MAC layer moves to the _Contend_ state.
% * In the _Contend_ state, if the channel is sensed as idle for a period
% of DCF inter frame space (DIFS) time followed by a random back-off time,
% the MAC layer moves to the _SendingData_ state.
% * In the _SendingData_ state, a frame is transmitted, and the MAC layer
% moves to the _WaitForRx_ state.
% * In the _WaitForRx_ state, the MAC layer waits for a period of ACK/CTS
% timeout. On receiving a response frame, MAC initiates next frame
% transmission. If a response frame is not received within the timeout
% period, the frame is re-transmitted.
% * On receiving a clear channel assessment (CCA) as busy from the PHY
% layer, the MAC layer moves to the _Rx_ state. Frames are received and
% processed in the _Rx_ state. If an errored frame is received in the _Rx_
% state, the MAC layer waits for extended inter frame space (EIFS) time in
% the _Eifs_ state. If the frame is intended for other node, network
% allocation vector (NAV) is updated and transmission is deferred until NAV
% becomes zero. If the frame is intended to this node, a response frame is
% sent if needed.
%
% MAC parameters such as RTS threshold, retry limit and data rates are
% configurable for each node.
%%
%% PHY and Channel
% *Transmit Chain*:
%
% The MAC layer initiates the transmission by sending a transmission start
% request containing Tx vector information. On receiving the start request,
% the PhyTx80211aDES block configures the PHY transmission parameters with
% the given Tx vector, and sends the transmission start confirm to the MAC
% layer. The PHY parameters are configured in a non-HT format configuration
% object of type <docid:wlan_ref#buw6f2v wlanNonHTConfig>. On receiving the
% start confirm, the MAC layer sends the frame to the PhyTx80211aDES block.
%
% The PhyTx80211aDES block generates a waveform for the MAC frame using
% <docid:wlan_ref#buwv1f3 wlanWaveformGenerator> function. It also scales
% the samples of waveform with the configured Tx gain. The generated
% waveform is transmitted through the shared channel.
%
% <<../phyTx.png>>
%
% You can configure the mask properties of Tx power (dBm) and the Tx gain
% (dB) for the PhyTx80211aDES block.
%
% *Channel Impairments Modeling*:
%
% Channel impairments determined by free-space path-loss model and Rayleigh
% multipath fading are added to the transmitted PHY waveform. You can
% choose to enable or disable these impairment models. In addition to the
% impairment models, the signal reception range can also be limited by an
% optional range propagation loss model. To model any of these losses, the
% channel model must contain both the sender and receiver positions along
% with the transmitted signal strength. The channel is modeled inside each
% receiving node, before passing the waveform to the PhyRx80211aDES block.
%
% *Receiver Chain*:
%
% When the PhyRx80211aDES block receives a waveform, it scales the waveform
% with the configured Rx gain. The PhyRx80211aDES block then applies
% thermal noise and interference to the received waveform. This is done by
% calculating the expected signal to interference-plus-noise Ratio (SINR)
% at the end of preamble, header, and payload. The calculated SINR is added
% to the preamble, header, and payload of the received waveform as an
% Additive White Gaussian Noise (AWGN). The PhyRx80211aDES block then
% compares the waveform power with the energy detection (ED) threshold. If
% the waveform power is greater than the ED threshold, the PHY sends a CCA
% busy indication to the MAC layer and starts decoding the waveform.
% Otherwise, the PHY considers the waveform as noise and adds it as
% interference to the upcoming waveforms for the duration of the current
% waveform. If an error is found while decoding, the PHY stops further
% processing of the waveform and sends an error indication to the MAC
% layer. If the preamble and header are decoded successfully, the
% PhyRx80211aDES block sends a start indication to the MAC layer. If the
% payload is also decoded successfully, the payload is passed to the MAC
% layer along with a success indication.
%
% <<../phyRx.png>>
%
% The Rx gain (dB) and the noise figure (dB) can be configured for the
% PhyRx80211aDES block.
%%
%% Node Position Allocator
% Node position allocator is used to assign initial position of nodes. It
% supports linear and list position allocation strategies.
% 
% Linear Position Allocation Strategy &ndash; Places nodes uniformly in a
% straight line, on a 2D grid.
% 
% List Position Allocation Strategy &ndash; Assigns node positions from a
% list [[x1 y1 z1] [x2 y2 z2] ... [xn yn zn]] such that (xk, yk, zk) is the
% position of the kth node for all k in (1, 2, ..., n).
%
%%
%%
%% Simulation Results
% The simulation of this model generates:
%
% # A run-time plot depicting the time spent on channel contention,
% transmission, and reception for each node.
% # A plot depicting metrics for each node such as &ndash; 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.
%
% <<../timeLineGraph.png>>
%
% <<../simulationResults.png>>
%%
%% Further Exploration
% # Increase the number of nodes in the network either by copying the
% existing nodes or by creating a custom node using library blocks.
% # Vary the application parameters: packet size and packet interval.
% # Change the MAC parameters: RTS threshold, Tx queue size, data rate, and
% retry limit.
% # Change the PHY parameters: PHY Tx gain, PHY Rx gain, and Rx
% noise figure.
% # Vary the channel modeling parameters.
% # Change the node positions using node position allocator.
% # Compare the throughput by changing different parameters.
% # Enable sequence viewer and see the messages exchanged between the nodes
% and inside components of the node.
%
% This example presents a multi-node 802.11a network and show you how to
% model a communication between multiple WLAN nodes using discrete event
% simulation. DCF in MAC is modeled as a Discrete Event Chart, whereas the
% PHY is modeled using MATLAB Discrete Event System block. The run-time
% visualization display showing the time spent on channel contention,
% transmission, and reception by each node helps you to study and analyze
% the DCF functionality. The network communication performance of each node
% is analyzed based on the plot exhibiting the node-related metrics such as
% number of transmitted, received, and dropped packets at PHY and MAC
% layers.
%%
%% Limitations
% # The MAC layer retransmissions are based on a common retry counter
% instead of short retry count (SRC) and long retry count (LRC) specified
% in section 10.3.4.4 of [ <#24 1> ].
% # No management frames are exchanged.
% # The MAC layer in each node maintains a single sequence-number counter
% for all the frame transmissions, instead of a per-destination counter.
% # Data rate adaptation at the MAC layer is not implemented.
% # MAC service data unit (MSDU) fragmentation is not implemented.
% # The interference is modeled as an AWGN with SINR derived from the
% signal strength of interfering packets and thermal noise. The
% interference can also be modeled by combining the IQ samples of
% interfering signals.
%%
%% Appendix
% The example uses these helpers:
%
% # <matlab:edit('dcfApplyFading.m') dcfApplyFading.m>: Apply Rayleigh
% fading effect on the waveform.
% # <matlab:edit('dcfAssignNodeIDs.m') dcfAssignNodeIDs.m>: Assign node
% IDs.
% # <matlab:edit('dcfDisplayStats.m') dcfDisplayStats.m>: Display the
% statistics.
% # <matlab:edit('dcfNodeInfo.m') dcfGetNodeInfo.m>: Perform get or set
% operation for MAC address of the given node.
% # <matlab:edit('dcfGetNodeNamesList.m') dcfGetNodeNamesList.m>: Get the
% list of nodes in the model.
% # <matlab:edit('dcfGenerateMACFrame.m') dcfGenerateMACFrame.m>: Generate
% MAC frames.
% # <matlab:edit('dcfPlotQueueLengths.m') dcfPlotQueueLengths.m>: Plot the
% queue lengths in the simulation.
% # <matlab:edit('dcfPlotStats.m') dcfPlotStats.m>: Plot the simulation
% time-line statistics.
% # <matlab:edit('dcfStats.m') dcfStats.m>: Enumeration to indicate model
% statistics.
% # <matlab:edit('dcfUpdateStats.m') dcfUpdateStats.m>: Update the
% statistics for the given node.
% # <matlab:edit('PhyPrimitives.m') PhyPrimitives.m>:Enumeration for
% indications between the PHY and the MAC layer
% # <matlab:edit('PhyRx80211aDES.m') PhyRx80211aDES.m>: Model PHY
% operations related to packet reception.
% # <matlab:edit('PhyTx80211aDES.m') PhyTx80211aDES.m>: Model PHY
% operations related to packet transmission.
%%
%% References
% # IEEE Std 802.11(TM) &ndash; 2016 IEEE Standard for Information
% technology &ndash; Telecommunications and information exchange between
% systems &ndash; Local and metropolitan area networks &ndash; Specific
% requirements &ndash; Part 11:  Wireless LAN Medium Access Control (MAC)
% and PHY Specifications
