Main Content

Create and Add Custom Traffic in WLAN Network Simulation

Since R2026a

Traffic models define how data flows between nodes, providing a framework to simulate different types of network usage and application behaviors. With Wireless Network Toolbox™, you can create custom traffic models to meet your simulation needs. This example demonstrates how to create a traffic model from the wnet.Traffic base class, and how to integrate it into your WLAN simulation.

Implement Custom Traffic

To create a custom traffic model using the wnet.Traffic base class of Wireless Network Toolbox, follow these steps:

  • Inherit from the wnet.Traffic base class. The class definition must have this format, where customTraffic is the name of your custom traffic class.

  • Implement the base class public method generate. Also, implement any supporting methods and properties.

classdef customTraffic < wnet.Traffic
    properties
        ...
    end

    methods
        function obj = customTraffic(varargin)
            % Constructor
            ...
        end

        function [dt,packetSize,packet] = generate(trafficObject,elapsedTime)
            ...
        end
    end

    % Supporting methods
    ...
end
  • Save the class definition in a .m file inside your directory.

  • In a simulation script, create an object of the customTraffic class. Plug this custom traffic object into WLAN nodes by using the addTrafficSource object function of the wlanNode object.

This example implements a periodic traffic model, hTrafficPeriodic, which generates packets of a specified size at a specified interval. The model is attached to this example as a supporting file. For more information on the implementation of the model, see Supporting Files.

Simulate Network with Custom Traffic

Set the seed for the random number generator to 1 to ensure repeatability of results.

rng(1,"combRecursive")

Initialize the wireless network simulator.

networksimulator = wirelessNetworkSimulator.init;

Configure an access point (AP) by using the wlanDeviceConfig object.

deviceCfg = wlanDeviceConfig(Mode="AP");

Use the AP configuration to create a WLAN node. Specify the name and position of the node.

apNode = wlanNode(Name="AP",Position=[0 10 0],DeviceConfig=deviceCfg);

Create a station (STA) node with the default device configuration.

staNode = wlanNode(Name="STA",Position=[5 0 0]);

Associate the STA node with the AP node by using the associateStations function.

associateStations(apNode,staNode)

Create a periodic traffic pattern object using the hTrafficPeriodic helper object. Specify the period in seconds and packet size in bytes.

traffic = hTrafficPeriodic(Period=0.02,PacketSize=512);

Add application traffic from the AP to the STA.

addTrafficSource(apNode,traffic,DestinationNode=staNode)

Add the AP and STA nodes to the simulator.

addNodes(networksimulator,[apNode staNode])

If an event log file exists, delete it.

if exist("wlanEventLog.mat","file")
    delete("wlanEventLog.mat")
end

Create an event tracer object to log events to a MAT file during simulation runtime.

eventTracer = wirelessNetworkEventTracer(FileName="wlanEventLog.mat");

Add the AP and STA nodes to the event tracer.

% For both AP and STA nodes, log these events: "TransmissionStarted", "ReceptionEnded", "AppPacketGenerated", and "AppPacketReceived"
addNodes(eventTracer,apNode) 
addNodes(eventTracer,staNode)

Run the simulation for 0.3 seconds.

run(networksimulator,0.3)

Read the AppPacketGenerated events of the AP node from the event tracer.

events = read(eventTracer,EventName="AppPacketGenerated",NodeName="AP");

Obtain the timestamps for all AppPacketGenerated events of the AP node from the event log. The timestamps verify that the output is periodic, with an event occurring every 0.02 seconds.

generationTimes = [events.Timestamp]
generationTimes = 1×16

         0    0.0200    0.0400    0.0600    0.0800    0.1000    0.1200    0.1400    0.1600    0.1800    0.2000    0.2200    0.2400    0.2600    0.2800    0.3000

Supporting Files

The example uses this helper file.

hTrafficPeriodic.m — Implements a periodic traffic model.

classdef hTrafficPeriodic < wnet.Traffic
    
    properties
        % Period between generated packets, in seconds (must be a positive numeric scalar)
        Period (1,1) {mustBeNumeric,mustBePositive} = 1

        % Packet size in bytes (must be a positive integer scalar)
        PacketSize (1,1) {mustBeNumeric,mustBeInteger,mustBePositive} = 1500

        % Application data to be included in each packet (must be column vector of integers between 0 and 255)
        ApplicationData (:,1) {mustBeNumeric,mustBeInteger,mustBeInRange(ApplicationData,0,255)} = ones(1500,1)
    end

    properties (Access = private)
        % Actual packet data after adjusting for packet size (column vector)
        pAppData

        % Timer (in ms) until the generation of the next packet
        pNextInvokeTime = 0
    end

    methods
        function obj = hTrafficPeriodic(varargin)
            % hTrafficPeriodic Constructor for the periodic traffic class

            % To enable support for configurable properties through name-value arguments, 
            % call the constructor of base class by using the name-value arguments as variable inputs
            obj@wnet.Traffic(varargin{:});

            % Initialize the packet data (pAppData)
            updatePacketData(obj);
        end

        function set.PacketSize(obj,value)
            % Set method for PacketSize property

            obj.PacketSize = value;
            updatePacketData(obj);
        end

        function set.ApplicationData(obj,value)
            % Set method for ApplicationData property

            obj.ApplicationData = value;
            updatePacketData(obj);
        end

        function [dt,packetSize,packet] = generate(obj,elapsedTime)
            % generate Generate the next packet after the specified period has elapsed

            %   [dt,packetSize,packet] = generate(obj,elapsedTime)
            %   - elapsedTime: (optional) time in ms since last call (default: 0)
            %   - dt: time in ms to next packet generation
            %   - packetSize: size of the packet generated in bytes (0 if no packet)
            %   - packet: application data (empty if no packet)
            %
            % This method maintains a countdown timer. When the timer reaches
            % zero, a packet is generated and the timer is reset to the period.

            arguments
                obj
                elapsedTime (1,1) {mustBeNonnegative} = 0  % Time in ms since last call (default: 0)
            end

            if nargin == 1
                % If elapsedTime is not provided, assume this is the first call
                % and reset the timer so a packet is generated immediately.
                obj.pNextInvokeTime = 0;
            else
                % Subtract elapsed time from the internal timer
                obj.pNextInvokeTime = obj.pNextInvokeTime - elapsedTime;
                % Round to avoid numerical errors
                obj.pNextInvokeTime = round(obj.pNextInvokeTime*1e6)/1e6;
            end

            if obj.pNextInvokeTime <= 0
                % Countdown timer has elapsed, so generate the next packet
                dt = obj.Period*1000;      % Set next packet generation time (in ms)
                packetSize = obj.PacketSize; % Output the configured packet size
                obj.pNextInvokeTime = dt;    % Reset the countdown timer
                if nargout == 3
                    % Return the generated packet if requested
                    packet = obj.pAppData;
                end
            else
                % Packet generation is pending until the countdown timer expires
                dt = obj.pNextInvokeTime; % Time left until next packet (ms)
                packetSize = 0;           % No packet, so size is zero
                if nargout == 3
                    packet = [];          % No packet to return
                end
            end
        end
    end

    methods (Access = private)
        function updatePacketData(obj)
            % updatePacketData Update the size and content of application packet based on PacketSize and ApplicationData properties.

            n = obj.PacketSize;
            data = obj.ApplicationData;
            obj.pAppData = ones(n,1,"like",data); % Pre-fill with ones (default)
            m = min(n,numel(data));
            obj.pAppData(1:m) = data(1:m);        % Copy as much as fits
        end
    end
end

See Also

| | (Wireless Network Toolbox) | (Wireless Network Toolbox)