Skip to main content

Wireless Networks in NS2 - NS2 Tutorial 6

Wireless Networks

In this post:

·       Introduction to Wireless networks

·       Tcl scripts for various wireless networks

Unlike Wired networks, wireless networks are a little tricky in dealing with the network properties. Since wireless nodes have radio, physical layer, Mac (Medium Access Control), Antenna, etc. Every parameter of those should be addressed when configuring wireless networks.

NS provides a way to handle these properties through a construct called node-config. The node configuration in ns2 is a special task in which the number of nodes can be configured for a set of parameters. The following table tells about the node configuration parameters as defined in the ~ns-2.35/tcl/ns-lib.tcl

·       The readers are requested to refer the ns-lib.tcl file for more information.

6.1 Wireless Node Configuration

The following table shows the complete node configuration that ns supports or provides. The wireless nodes may be configured with all the parameters given here or whatever is needed can be used to configure.

Option

Available Values

Remarks

addressType

flat, hierarchical

MPLS

ON,OFF

Multi protocol Label Switching

wiredRouting

ON, OFF

llType

LL, LL/Sat

Link Layer

macType

Mac/802_11, Mac/Csma/Ca, Mac/Sat, Mac/Sat/UnslottedAloha, Mac/Tdma

Medium Access Control

ifqType

Queue/DropTail, Queue/DropTail/PriQueue

Interface Queue type

phyType

Phy/wirelessPhy, Phy/Sat

Physical Layer Type

adhocRouting

DIFFUSION/RATE, DIFFUSION/PROB, DSDV, DSR, FLOODING, OMNIMCAST,AODV,TORA,PUMA

adhoc routing protocol

propType

Propagation/TwoRayGround, Propagation/Shadowing

Propagation Type

antType

Antenna/OmniAntenna,

Antenna type

Channel

Channel/WirelessChannel, Channel/Sat

Channel to be used

mobileIP

ON,OFF

to set the IP for Mobile or not

energyModel

EnergyModel

energy model to be enabled or not

initialEnergy

in terms of joules (Ex: 3.24)

txPower

Power in terms of Watts (0.32)

rxPower

Power in terms of Watts (0.1)

idlePower

Power in terms of Watts (0.02)

agentTrace

ON, OFF

Tracing to be on or off

routerTrace

ON, OFF

Tracing to be on or off

macTrace

ON, OFF

Tracing to be on or off

movementTrace

ON, OFF

Tracing to be on or off

errProc

UniformErrorProc

toraDebug

ON, OFF

An Example

$ns node-config -addressType hierarchical \

            -adhocRouting AODV \

            -llType LL \

            -macType Mac/802_11 \

            -ifqType Queue/DropTail/PriQueue \

            -antType Antenna/OmniAntenna \

            -propType Propagation/TwoRayGround \

            -phyType Phy/WirelessPhy \

            -topologyInstance $topo \

            -energyModel “EnergyModel” \

            -initialEnergy 3.0 \

            -txPower 0.3 \

            -rxPower 0.1 \

            -sleepPower 0.05 \

            -idlePower 0.08 \

            -channel Channel/WirelessChannel \

            -agentTrace ON \

            -routerTrace OFF \

            -movementTrace ON \

            -macTrace OFF

6. 2 A Simple Wireless Configuration

For every node creation, the above node-config has to be set in the wireless networks. Now we will see a simple example related to wireless networks.

Listing 6.1 – A Two node wireless networks

# The following are the parameters to initialize the wireless properties

set val(chan)           Channel/WirelessChannel    ;# Type of channel

set val(prop)           Propagation/TwoRayGround   ;# Radio model (propagation)

set val(netif)          Phy/WirelessPhy            ;# NIC (Interface Card)

set val(mac)            Mac/802_11                 ;# Medium Access Control (MAC)

set val(ifq)            Queue/DropTail/PriQueue    ;# Type of queuing interface

set val(ll)             LL                         ;# link layer type

set val(ant)            Antenna/OmniAntenna        ;# Antenna Model

set val(ifqlen)         50                         ;# max packet in interface queue

set val(nn)             2                          ;# number of mobilenodes

set val(rp)             DSDV                       ;# routing protocol

set val(x)        500

set val(y)        500

 

# Initialize Global Variables

set ns      [new Simulator]

 

#set the tracing

set tracef [open wrls1.tr w]

$ns trace-all $tracef

 

#set the animation file

set namf [open wrls1.nam w]

$ns namtrace-all-wireless $namf $val(x) $val(y)

 

# set up topography object

set topo  [new Topography]

 

# the topography just uses the 2D flatgrid topology

$topo load_flatgrid $val(x) $val(y)

 

# Create God, GOD Means - General Operations Director, god is taken care of all the nodes in the network.

create-god $val(nn)

 

# Create two channels, if there are multiple channels, the nodes can be created either in channel 1 # or channel 2

set channel1 [new $val(chan)]

set channel2 [new $val(chan)]

 

# configure node using the initialization parameters that were declared in the beginning.

$ns node-config -adhocRouting $val(rp) \

            -llType $val(ll) \

            -macType $val(mac) \

            -ifqType $val(ifq) \

            -ifqLen $val(ifqlen) \

            -antType $val(ant) \

            -propType $val(prop) \

            -phyType $val(netif) \

            -topoInstance $topo \

            -agentTrace ON \

            -routerTrace ON \

            -macTrace ON \

            -movementTrace OFF \

            -channel $channel1

 

set n0 [$ns node]

 

#the node n0 is associated with the channel1 and the following node n1 created under the #channel2, if both the nodes are to be enabled to a single channel, then comment the following #two lines

#$ns node-config \

#           -channel $channel2

set n1 [$ns node]

 

#disable the random motion for the nodes, if they are mobile nodes.

$n0 random-motion 0

$n1 random-motion 0

 

#initial size of the node

$ns initial_node_pos $n1 20

$ns initial_node_pos $n0 20

 

# initial position of the node, the Z axis is 0, as the nodes are in a flatgrid

$n0 set X_ 5.0

$n0 set Y_ 2.0

$n0 set Z_ 0.0

 

$n1 set X_ 8.0

$n1 set Y_ 5.0

$n1 set Z_ 0.0

 

#some mobility of the nodes, node1 moves to 50,40 at a speed of 25m/s

$ns at 3.0 "$n1 setdest 50.0 40.0 25.0"

$ns at 3.0 "$n0 setdest 48.0 38.0 5.0"

 

#n1 is moving far away from n0 at a speed of 30m/s

$ns at 10.0 "$n1 setdest 490.0 480.0 30.0"

 

# Setup traffic flow between nodes

# TCP connections between n0 and n1

set tcp [new Agent/TCP]

$ns attach-agent $n0 $tcp

$tcp set class_ 2

 

set sink [new Agent/TCPSink]

$ns attach-agent $n1 $sink

 

$ns connect $tcp $sink

 

set ftp [new Application/FTP]

$ftp attach-agent $tcp

$ns at 3.0 "$ftp start"

 

# Tell nodes when the simulation ends

$ns at 20.0 "$n0 reset";

$ns at 20.0 "$n1 reset";

 

$ns at 20.0 "finish"

$ns at 20.01 "puts \"NS EXITING...\" ; $ns halt"

proc finish {} {

    global ns tracef namf

    $ns flush-trace

    close $tracef

    close $namf

}

 

puts "Starting Simulation..."

$ns run

The Listing 6.1 shows the wireless network with two nodes that involves in a exchange of information. This network generates two files a network animator file (wrls1.nam) and a trace file (wrls1.tr)

The output of the tracefile is, here it shows the first few lines of the wrls1.tr

s 0.029290548 _1_ RTR  --- 0 message 32 [0 0 0 0] ------- [1:255 -1:255 32 0]

s 0.029365548 _1_ MAC  --- 0 message 90 [0 ffffffff 1 800] ------- [1:255 -1:255 32 0]

r 0.030085562 _0_ MAC  --- 0 message 32 [0 ffffffff 1 800] ------- [1:255 -1:255 32 0]

r 0.030110562 _0_ RTR  --- 0 message 32 [0 ffffffff 1 800] ------- [1:255 -1:255 32 0]

s 1.119926192 _0_ RTR  --- 1 message 32 [0 0 0 0] ------- [0:255 -1:255 32 0]

s 1.120361192 _0_ MAC  --- 1 message 90 [0 ffffffff 0 800] ------- [0:255 -1:255 32 0]

r 1.121081207 _1_ MAC  --- 1 message 32 [0 ffffffff 0 800] ------- [0:255 -1:255 32 0]

r 1.121106207 _1_ RTR  --- 1 message 32 [0 ffffffff 0 800] ------- [0:255 -1:255 32 0]

Here is the analysis of the above trace file

ACTION: [s|r|D]: s -- sent, r -- received, D – dropped

WHEN: the time when the action happened

WHERE: the node where the action happened

LAYER:

AGT -- application,

RTR -- routing,

LL -- link layer (ARP is done here)

IFQ -- outgoing p’acket queue (between link and mac layer)

MAC -- mac, 

PHY – physical

flags:

SEQNO: the sequence number of the packet

TYPE: the packet type cbr -- CBR data stream packet

DSR -- DSR routing packet (control packet generated by routing)

RTS -- RTS packet generated by MAC 802.11 

ARP -- link layer ARP packet

SIZE: the size of packet at current layer, when packet goes down, size increases, goes up size decreases[a b c d]: a -- the packet duration in mac layer header  b -- the mac address of destination  c -- the mac address of source  d -- the mac type of the packet body

flags:

[......]: [  source node ip : port_number  destination node ip (-1 means broadcast) : port_number  ip header ttl   ip of next hop (0 means node 0 or broadcast)  ]

So we can interpret the below trace

r 0.010176954 _9_ RTR  --- 1 gpsr 29 [0 ffffffff 8 800] ------- [8:255 -1:255 32 0]

in the same way, as The routing agent on node 9 received a GPSR broadcast (mac address 0xff, and ip address is -1, either of them means broadcast) routing packet whose ID is 1 and size is 19 bytes, at time 0.010176954 second, from node 8 (both mac and ip addresses are 8), port 255 (routing agent)

The output of the network animation file is

Network Animation Window
Network Animation Window

This example though it performs a little work, but the results it gives are tremendous. There are so many parameters that change during the execution of the network. Some of the performance characteristics are listed:

·       Throughput of Generating packets or sending packets

·       End to End delay between the nodes

·       Packet Delivery ratio.

·       Packet loss and packet drop calculation

·       Jitter

·       Energy used by the nodes

·       And so many other parameters.

These parameters are calculated based on the contents of the trace file. There are so many softwares available to process these trace files. Xgraph is a utility that comes with ns-allinone package and is very useful to predict the performance metrics. There are other third party software that can be used to process these trace files,

1.     Tracegraph

a.     Tracegraph is not actively maintained and it is using matlab runtime libraries.

b.     It does not process the energy values in the trace file

c.     Very easy to handle, just open the file using a GUI windows and rest taken care by the software.

d.     Its free and open source. This software can be downloaded at [5].

e.     More information about Tracegraph and GnuPlot is available at Appendix D

2.     GnuPlot

a.     This is also free and easy to handle

b.     Need to specify the axis manually and results are great looking.

3.     Matlab

a.     Its runtime libraries are responsible for processing the data.

b.     It’s a proprietary software

4.     AWK programming language

a.     Its one of the powerful programming language that can process the data column wise.

b.     Its open source and free. Refer Appendix B for more information

Analysis using Tracegraph, Listing 6.1 has two nodes that involves a TCP traffic flow and the nodes were moving. In this case, at the end of the simulation, both the nodes were away from each other and a packet drop and packet loss occurs. These results can be predicted using tracegraph as indicated below.

A 3d Graph that shows the generation of packets at all the nodes
 A 3d Graph that shows the generation of packets at all the nodes
Average End to End delay for Sending bits
Average End to End delay for Sending bits

Cumulative sum of dropped bytes of RTS packets at all nodes
Cumulative sum of dropped bytes of RTS packets at all nodes

Throughput of all generated packets at all nodes
Throughput of all generated packets at all nodes


 The above graphs, plots the various performance characteristics of the given wireless network and each graph tells some information about the network. For example, in the above graph, there are two waveforms, one refers the throughput of generating packets at all nodes and the smaller one refers the throughput of generating packets of RTS at all nodes. From the above figure, it was assumed that the RTS packets are limited in generation compared with the other packets in the network.

Also the tracegraph software will present the text based information about the network. The following figure shows 

Simulation Information
 Simulation Information
End to End delay
End to End delay

The simulation information shows the number of dropped packets is 69 and lost packets are 1427 and both the nodes (0 and 1) are dropping the packets.

 

6.3 Energy Model in Wireless networks

Real wireless nodes are equipped with battery that will last long only when the batteries are charged. In a simulator environment, implementing a battery model is always challenging as the battery has a non linear characteristics. However, ns implements a energy model for wireless nodes that uses functions based on the energy usage of the nodes during transmitting, receiving,  sleeping and even when the nodes are idle. In Listing 6.1, the nodes are not enabled with energy model, hence the nodes uses infinite amount of energy which in practice is extinct. Listing 6.2 implements energy model for the nodes as listed below:

Energy unit is given in Joules and Power consumption is calculated based on usage in Watts

As we know the energy and power relation is

Power X Time = Energy,

As per the above equation, even when the node is sleeping or idle, power is consumed as we use our real Smart Phones or Mobile phones (that consumes power or the antenna is always on to receive the signal)

Listing 6.3 – Wireless Network with Energy Model

 

# The following are the parameters to initialize the wireless properties

set val(chan)           Channel/WirelessChannel    ;# Type of channel

set val(prop)           Propagation/TwoRayGround   ;# Radio model (propagation)

set val(netif)          Phy/WirelessPhy            ;# NIC (Interface Card)

set val(mac)            Mac/802_11                 ;# Medium Access Control (MAC)

set val(ifq)            Queue/DropTail/PriQueue    ;# Type of queuing interface

set val(ll)             LL                         ;# link layer type

set val(ant)            Antenna/OmniAntenna        ;# Antenna Model

set val(ifqlen)         50                         ;# max packet in interface queue

set val(nn)             4                         ;# number of mobilenodes

set val(rp)             DSDV                       ;# routing protocol

set val(x)        500

set val(y)        500

 

# Initialize Global Variables

set ns      [new Simulator]

 

#set the tracing

set tracef [open wrls2.tr w]

$ns trace-all $tracef

 

#set the animation file

set namf [open wrls2.nam w]

$ns namtrace-all-wireless $namf $val(x) $val(y)

 

# set up topography object

set topo  [new Topography]

 

# the topography just uses the 2D flatgrid topology

$topo load_flatgrid $val(x) $val(y)

 

# Create God, GOD Means - General Operations Director, god is taken care of all the nodes in the network.

create-god $val(nn)

 

# Create a wireless channel

set channel1 [new $val(chan)]

 

# configure node using the initialization parameters that were declared in the beginning.

$ns node-config -adhocRouting $val(rp) \

            -llType $val(ll) \

            -macType $val(mac) \

            -ifqType $val(ifq) \

            -ifqLen $val(ifqlen) \

            -antType $val(ant) \

            -propType $val(prop) \

            -phyType $val(netif) \

            -topoInstance $topo \

            -energyModel "EnergyModel" \

            -initialEnergy 3.2 \

            -txPower 0.3 \

            -rxPower 0.1 \

            -sleepPower 0.05 \

            -idlePower 0.1 \

            -agentTrace ON \

            -routerTrace ON \

            -macTrace ON \

            -movementTrace OFF \

            -channel $channel1

 

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]

 

#disable the random motion for the nodes, if they are mobile nodes.

$n0 random-motion 0

$n1 random-motion 0

$n2 random-motion 0

 

#initial size of the node

$ns initial_node_pos $n1 20

$ns initial_node_pos $n0 20

$ns initial_node_pos $n2 20

 

# initial position of the node, the Z axis is 0, as the nodes are in a flatgrid

$n0 set X_ 5.0

$n0 set Y_ 2.0

$n0 set Z_ 0.0

 

$n1 set X_ 8.0

$n1 set Y_ 5.0

$n1 set Z_ 0.0

 

$n2 set X_ 18.0

$n2 set Y_ 15.0

$n2 set Z_ 0.0

 

#some mobility of the nodes, node1 moves to 50,40 at a speed of 25m/s

$ns at 3.0 "$n1 setdest 50.0 40.0 25.0"

$ns at 3.0 "$n0 setdest 48.0 38.0 5.0"

$ns at 4.0 "$n2 setdest 100.0 100.0 40.0"

 

#n1 is moving far away from n0 at a speed of 30m/s

$ns at 10.0 "$n1 setdest 490.0 480.0 30.0"

 

# Setup traffic flow between nodes

# TCP connections between n0 and n1

set tcp [new Agent/TCP]

$ns attach-agent $n0 $tcp

$tcp set class_ 2

 

set sink [new Agent/TCPSink]

$ns attach-agent $n1 $sink

 

$ns connect $tcp $sink

 

set ftp [new Application/FTP]

$ftp attach-agent $tcp

$ns at 3.0 "$ftp start"

 

# Tell nodes when the simulation ends

$ns at 20.0 "$n0 reset";

$ns at 20.0 "$n1 reset";

 

$ns at 20.0 "finish"

$ns at 20.01 "puts \"NS EXITING...\" ; $ns halt"

proc finish {} {

    global ns tracef namf

    $ns flush-trace

    close $tracef

    close $namf

}

 

puts "Starting Simulation..."

$ns run

 

In the Listing 6.2, the following codes are added for including energy model into the nodes

                        -energyModel "EnergyModel" \

                        -initialEnergy 3.2 \

                        -txPower 0.3 \

                        -rxPower 0.1 \

                        -sleepPower 0.05 \

                        -idlePower 0.1 \

These codes includes the energy consumption while

·       Transmitting

·       Receiving

·       Sleeping

·       Even when the node is idle

·       Transition energy also is one of the factor

The output trace file includes extra column for energy usage too.as shown below

s 0.032821055 _1_ RTR  --- 0 message 32 [0 0 0 0] [energy 3.200000 ei 0.000 es 0.000 et 0.000 er 0.000] ------- [1:255 -1:255 32 0]

The bold letters in the above line indicates the energy level trace.

energy – initial energy value which is given as 3.2 Joules

ei – idle energy

es – sleep energy

et – transmission energy

er – reception energy

following Fig shows the picture of energy level Nodes. The figure shows the nodes are in Green color and when the node’s energy comes to a threshold value, it changes to yellow and if the energy completely drained then the nodes die indicated by changing the color to red.

Wireless network with energy Model
Wireless network with energy Model
 

6.4 – Performance characteristics in Wireless Adhoc networks

Listing 6.3 – Plotting the performance characteristics in wireless adhoc networks

# Defining Node Configuration paramaters

set val(chan)           Channel/WirelessChannel    ;# channel type

set val(prop)           Propagation/TwoRayGround   ;# radio-propagation model

set val(netif)           Phy/WirelessPhy            ;# network interface type

set val(mac)            Mac/802_11                ;# MAC type

set val(ifq)            Queue/DropTail/PriQueue   ;# interface queue type

set val(ll)             LL                         ;# link layer type

set val(ant)            Antenna/OmniAntenna        ;# antenna model

set val(ifqlen)         50                         ;# max packet in ifq

set val(nn)             8                          ;# number of mobilenodes

set val(rp)             DSDV                       ;# routing protocol

set val(x)              500                        ;# X dimension of the topography

set val(y)              500                           ;# Y dimension of the topography

 

# Set the Mac Parameters, for more parameters, refer the ~ns-2.35/lib/ns-default.tcl

Mac/802_11 set RTSThreshold_  3000

Mac/802_11 set basicRate_ 1Mb

Mac/802_11 set dataRate_  2Mb

 

# creation of tracefiles for various metrics

# *** Throughput Trace ***

set f0 [open thru02.tr w]

set f1 [open thru12.tr w]

set f2 [open thru22.tr w]

set f3 [open thru32.tr w]

 

# *** Packet Loss Trace ***

set f4 [open pktloss02.tr w]

set f5 [open pktloss12.tr w]

set f6 [open pktloss22.tr w]

set f7 [open pktloss32.tr w]

 

# *** Packet Delay Trace ***

set f8 [open pktdelay02.tr w]

set f9 [open pktdelay12.tr w]

set f10 [open pktdelay22.tr w]

set f11 [open pktdelay32.tr w]

 

# Simulator Object

set ns              [new Simulator]

 

# Trace file initialization

set tracef     [open wireless3.tr w]

$ns trace-all $tracef

 

# Network Animator

set namf [open wireless3.nam w]

$ns namtrace-all-wireless $namf $val(x) $val(y)

 

# Topography

set topo       [new Topography]

$topo load_flatgrid 500 500

 

#creation of god (General Operations Director) object

create-god $val(nn)

 

# configure nodes

       $ns node-config -adhocRouting $val(rp) \

                         -llType $val(ll) \

                         -macType $val(mac) \

                         -ifqType $val(ifq) \

                         -ifqLen $val(ifqlen) \

                         -antType $val(ant) \

                         -propType $val(prop) \

                         -phyType $val(netif) \

                         -channelType $val(chan) \

                         -topoInstance $topo \

                         -agentTrace ON \

                         -routerTrace ON \

                         -macTrace OFF \

                         -movementTrace OFF                   

# Creation of Nodes

        for {set i 0} {$i < $val(nn) } {incr i} {

                set node_($i) [$ns node]

                $node_($i) random-motion 0            ;# disable random motion

        }

 

 

#initial position of nodes

 

$node_(0) set X_ 5.0

$node_(0) set Y_ 5.0

$node_(0) set Z_ 0.0

 

$node_(1) set X_ 10.0

$node_(1) set Y_ 15.0

$node_(1) set Z_ 0.0

 

$node_(2) set X_ 35.0

$node_(2) set Y_ 250.0

$node_(2) set Z_ 0.0

 

$node_(3) set X_ 10.0

$node_(3) set Y_ 50.0

$node_(3) set Z_ 0.0

 

$node_(4) set X_ 235.0

$node_(4) set Y_ 10.0

$node_(4) set Z_ 0.0

 

$node_(5) set X_ 400.0

$node_(5) set Y_ 100.0

$node_(5) set Z_ 0.0

 

$node_(6) set X_ 285.0

$node_(6) set Y_ 150.0

$node_(6) set Z_ 0.0

 

$node_(7) set X_ 120.0

$node_(7) set Y_ 115.0

$node_(7) set Z_ 0.0

 

# Create traffic flow using UDP with Constant Bit Rate Application

# this includes priority and the sink is LossMonitor agent to trace the bytes received (because the Null Agent does not handle this)

set agent1 [new Agent/UDP]             

$agent1 set prio_ 0                 

set sink [new Agent/LossMonitor] 

$ns attach-agent $node_(0) $agent1

$ns attach-agent $node_(1) $sink

$ns connect $agent1 $sink       

set app1 [new Application/Traffic/CBR]

$app1 set packetSize_ 512            ; # setting the packet size

$app1 set rate_ 600Kb                ; # setting the rate at which the packets are transmitted

$app1 attach-agent $agent1           ; # attaching the agent

 

 

 

set agent2 [new Agent/UDP]           

$agent2 set prio_ 1                  

set sink2 [new Agent/LossMonitor]    

$ns attach-agent $node_(2) $agent2   

$ns attach-agent $node_(3) $sink2    

$ns connect $agent2 $sink2           

set app2 [new Application/Traffic/CBR]

$app2 set packetSize_ 512              

$app2 set rate_ 600Kb                 

$app2 attach-agent $agent2            

 

 

 

set agent3 [new Agent/UDP]            

$agent3 set prio_ 2                  

set sink3 [new Agent/LossMonitor]    

$ns attach-agent $node_(4) $agent3   

$ns attach-agent $node_(5) $sink3    

$ns connect $agent3 $sink3           

set app3 [new Application/Traffic/CBR]

$app3 set packetSize_ 512            

$app3 set rate_ 600Kb                

$app3 attach-agent $agent3

set agent4 [new Agent/UDP]

$agent4 set prio_ 3      

set sink4 [new Agent/LossMonitor]     

$ns attach-agent $node_(6) $agent4    

$ns attach-agent $node_(7) $sink4     

$ns connect $agent4 $sink4            

set app4 [new Application/Traffic/CBR]

$app4 set packetSize_ 512              

$app4 set rate_ 600Kb                 

$app4 attach-agent $agent4            

# defines the node size in Network Animator

for {set i 0} {$i < $val(nn)} {incr i} {

    $ns initial_node_pos $node_($i) 20

}

 

# Initialize Flags

set ht 0

set hs 0

 

set ht1 0

set hs1 0

 

set ht2 0

set hs2 0

 

set ht3 0

set hs3 0

 

set hr1 0

set hr2 0

set hr3 0

set hr4 0

 

# Function To record Statistcis (Bit Rate, Delay, Drop)

proc record {} {

        global sink sink2 sink3 sink4 f0 f1 f2 f3 f4 f5 f6 f7 ht hs ht1 hs1 ht2 hs2 ht3 hs3 f8 f9 f10 f11 hr1 hr2 hr3 hr4

set ns [Simulator instance]

set time 0.9 ;#Set Sampling Time to 0.9 Sec

 

set bw0 [$sink set bytes_]

set bw1 [$sink2 set bytes_]

set bw2 [$sink3 set bytes_]

set bw3 [$sink4 set bytes_]

set bw4 [$sink set nlost_]

set bw5 [$sink2 set nlost_]

set bw6 [$sink3 set nlost_]

set bw7 [$sink4 set nlost_]

 

set bw8 [$sink set lastPktTime_]

set bw9 [$sink set npkts_]

set bw10 [$sink2 set lastPktTime_]

set bw11 [$sink2 set npkts_]

 

set bw12 [$sink3 set lastPktTime_]

set bw13 [$sink3 set npkts_]

set bw14 [$sink4 set lastPktTime_]

set bw15 [$sink4 set npkts_]

 

set now [$ns now]

# Record the Bit Rate in Trace Files

puts $f0 "$now [expr (($bw0+$hr1)*8)/(2*$time*1000000)]"

puts $f1 "$now [expr (($bw1+$hr2)*8)/(2*$time*1000000)]"

puts $f2 "$now [expr (($bw2+$hr3)*8)/(2*$time*1000000)]"

puts $f3 "$now [expr (($bw3+$hr4)*8)/(2*$time*1000000)]"

 

# Record Packet Loss Rate in File

puts $f4 "$now [expr $bw4/$time]"

puts $f5 "$now [expr $bw5/$time]"

puts $f6 "$now [expr $bw6/$time]"

puts $f7 "$now [expr $bw7/$time]"

 

# Record Packet Delay in File

if { $bw9 > $hs } {

      puts $f8 "$now [expr ($bw8 - $ht)/($bw9 - $hs)]"

      } else {

                puts $f8 "$now [expr ($bw9 - $hs)]"

        }

        if { $bw11 > $hs1 } {

                puts $f9 "$now [expr ($bw10 - $ht1)/($bw11 - $hs1)]"

        } else {

                puts $f9 "$now [expr ($bw11 - $hs1)]"

        }

 

        if { $bw13 > $hs2 } {

                puts $f10 "$now [expr ($bw12 - $ht2)/($bw13 - $hs2)]"

        } else {

                puts $f10 "$now [expr ($bw13 - $hs2)]"

        }

 

        if { $bw15 > $hs3 } {

                puts $f11 "$now [expr ($bw14 - $ht3)/($bw15 - $hs3)]"

        } else {

                puts $f11 "$now [expr ($bw15 - $hs3)]"

        }

 

        # Reset Variables

        $sink set bytes_ 0

        $sink2 set bytes_ 0

        $sink3 set bytes_ 0

        $sink4 set bytes_ 0

 

        $sink set nlost_ 0

        $sink2 set nlost_ 0

        $sink3 set nlost_ 0

        $sink4 set nlost_ 0

 

        set ht $bw8

        set hs $bw9

        set  hr1 $bw0

        set  hr2 $bw1

        set  hr3 $bw2

        set  hr4 $bw3

    $ns at [expr $now+$time] "record"   ;# Schedule Record after $time interval sec

}

 

# Start Recording at Time 0

$ns at 0.0 "record"

$ns at 1.4 "$app1 start"                 ;# Start transmission at  2 Sec

$ns at 10.0 "$app2 start"               ;# Start transmission at 5 Sec

$ns at 20.0 "$app3 start"               ;# Start transmission at 15 Sec

$ns at 30.0 "$app4 start"               ;# Start transmission at 25 Sec

 

# Stop Simulation at Time 70 sec

$ns at 80.0 "finish"

 

# Reset Nodes at time 80 sec

for {set i 0} {$i < $val(nn) } {incr i} {

    $ns at 80.0 "$node_($i) reset";

}

 

# Exit Simulation at Time 70.01 sec

$ns at 80.01 "puts \"NS EXITING...\" ; $ns halt"

 

proc finish {} {

        global ns tracefd f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11

        # Close Trace Files

        close $f0

        close $f1

        close $f2

        close $f3

        close $f4

        close $f5

        close $f6

        close $f7

        close $f8

        close $f9

        close $f10

        close $f11

        # Plot the characteristics using xgrapg

        exec xgraph thru02.tr thru12.tr thru22.tr thru32.tr -geometry 800x400 &

        exec xgraph pktloss02.tr pktloss12.tr pktloss22.tr pktloss32.tr -geometry 800x400 &

        exec xgraph pktdelay02.tr pktdelay12.tr pktdelay22.tr pktdelay32.tr -geometry 800x400 &

        # Reset Trace File

        $ns flush-trace

        close $tracef

        exit 0

}

puts "Starting Simulation..."

$ns run

The Listing 6.3 uses

·       8 wireless nodes with adjusted mac parameters

·       UDP Agent for Source agent

·       LossMonitor agent to trace the received bytes

·       Each agent has a priority value from ( 0 to 3). There are four flows

·       The characteristics that were plotted are

o   Packet loss

o   Packet Delay

o   Throughput

The Network animation looks likes the following (8 nodes with packet exchange)

Nam Animation

 And the characteristics are shown below

1.     

Packet Delay for various traffic flow
Packet Delay for various traffic flow

Packet Loss for various traffic flows
Packet Loss for various traffic flows

 


Throughput for various traffic flows.

 Throughput for various traffic flows


6.5 Message Sending in Wireless Networks

Listing 6.4 – Message passing between wireless nodes

set val(chan)           Channel/WirelessChannel    ;# channel type

set val(prop)           Propagation/TwoRayGround   ;# radio-propagation model

set val(netif)          Phy/WirelessPhy            ;# network interface type

set val(mac)            Mac/802_11                 ;# MAC type

set val(ifq)            Queue/DropTail/PriQueue    ;# interface queue type

set val(ll)             LL                         ;# link layer type

set val(ant)            Antenna/OmniAntenna        ;# antenna model

set val(ifqlen)         50                         ;# max packet in ifq

set val(nn)             2                          ;# number of mobilenodes

set val(rp)             DSDV                       ;# routing protocol

 

set ns [new Simulator]

 

set f [open four.tr w]

$ns trace-all $f

set nf [open four.nam w]

$ns namtrace-all-wireless $nf 670 670

 

# set up topography object

set topo       [new Topography]

$topo load_flatgrid 700 700

 

create-god $val(nn)

 

        $ns node-config -adhocRouting $val(rp) \

             -llType $val(ll) \

             -macType $val(mac) \

             -ifqType $val(ifq) \

             -ifqLen $val(ifqlen) \

             -antType $val(ant) \

             -propType $val(prop) \

             -phyType $val(netif) \

             -channelType $val(chan) \

             -topoInstance $topo \

             -agentTrace ON \

             -routerTrace ON \

             -macTrace OFF \

             -movementTrace OFF           

           

    for {set i 0} {$i < $val(nn) } {incr i} {

        set node_($i) [$ns node]   

        $node_($i) random-motion 0        ;# disable random motion

    }

# Define node movement model

#

puts "Loading connection pattern..."

#

# Provide initial (X,Y, for now Z=0) co-ordinates for mobilenodes

#

$node_(0) set X_ 5.0

$node_(0) set Y_ 2.0

$node_(0) set Z_ 0.0

 

$node_(1) set X_ 390.0

$node_(1) set Y_ 385.0

$node_(1) set Z_ 0.0

 

#

# Now produce some simple node movements

# Node_(1) starts to move towards node_(0)

#

$ns at 50.0 "$node_(1) setdest 45.0 40.0 45.0"

 

# Define node initial position in nam

for {set i 0} {$i < $val(nn)} {incr i} {

 

    # 20 defines the node size in nam, must adjust it according to your scenario

    # The function must be called after mobility model is defined

   

    $ns initial_node_pos $node_($i) 40

}

set udp0 [new Agent/UDP]

$ns attach-agent $node_(0) $udp0

#messages that are to be sent

array set dbans {

    "Where are you" "Home"

    "Welcome to Wireless networks" "yes"

    "Good" "Welcome"       

    "" "Not Found"

}

set udp1 [new Agent/UDP]

$ns attach-agent $node_(1) $udp1

 

$ns connect $udp0 $udp1

# Setting the class allows us to color the packets in nam.

$udp0 set class_ 0

$udp1 set class_ 1

 

# The "process_data" instance procedure is what will process received data

# if no application is attached to the agent.

# In this case, we respond to messages of the form "ping(###)".

# We also print received messages to the trace file.

 

Agent/UDP instproc process_data {size data} {

    global ns

    global udp0

    global udp1

    global dbans

    $self instvar node_

   

    # note in the trace file that the packet was received

    $ns trace-annotate "[$node_ node-addr] received {$data}"

    set flag1 "0"

    set flag "0"

    foreach db [array names dbans] {

    set str3 [string equal $db $data]

   

    if {$str3 == "1"} {

    set flag "1"

   

    set str4 [$node_ node-addr]

    $ns trace-annotate "Replying correct question for recieved data:{$data}"

    $ns trace-annotate "question: $db answer: $dbans($db)"

    set ans "$dbans($db)"     

    switch $str4 {

        0 {$ns at 80 "$udp0 send 828 replied:$ans"}

        1 {$ns at 80 "$udp1 send 828 replied:$ans"}

        2 {$ns at 80 "$udp2 send 828 replied:$ans"}

        default {puts "I don't know what the number is"}

    }

    }

}

    set str5 [string equal $flag $flag1]  

    if {$str5 == "1"} {

    $ns trace-annotate "Answer not found in database"

}

 

}

 

$ns at 50.3 "$udp0 send 500 {how are you}"

$ns at 70.5 "$udp1 send 828 hi"

 

#

# Tell nodes when the simulation ends

#

for {set i 0} {$i < $val(nn) } {incr i} {

    $ns at 150.0 "$node_($i) reset";

}

$ns at 150.0 "stop"

$ns at 150.01 "puts \"NS EXITING...\" ; $ns halt"

proc stop {} {

       global ns f nf

    $ns flush-trace

    close $f

    close $nf

 

}

puts "Starting Simulation..."

$ns run


Conclusion:

This chapter deals with the basics of wireless adhoc networks and its simulation in ns2. This chapter shows the wireless networks with two nodes, energy model enablement and message sending between the nodes. For most of the 802.11 mac protocols, the same set of node configuration, GOD object setting, Agent creation, etc will be common. Using this chapter, one can able to design most of the wireless adhoc networks in ns2.

Comments

Popular posts from this blog

Installing ns-3.34 in Ubuntu 20.04

This post shows how to install ns 3.34 in Ubuntu 20.04 LTS Prerequisites: Fresh installation of Ubuntu Version 20.04 LTS  ns3.34 can be downloaded from here Follow the video link for complete step by step instructions on the installation.  This version fixes the compilation issues of vanet-routing-compare.cc (bug in ns3.33)  Issue the following commands after opening a terminal  $ sudo apt update $ sudo apt install g++ python3 python3-dev python-dev pkg-config sqlite3 python3-setuptools git qt5-default gir1.2-goocanvas-2.0 python3-gi python3-gi-cairo python3-pygraphviz gir1.2-gtk-3.0 ipython3 openmpi-bin openmpi-common openmpi-doc libopenmpi-dev autoconf cvs bzr unrar openmpi-bin openmpi-common openmpi-doc libopenmpi-dev tcpdump wireshark libxml2 libxml2-dev Unzip or untar the ns-allinone-3.34.tar.bz2 in the home folder (in my case its /home/pradeepkumar) $ cd ns-allinone-3.34/ $ ./build.py --enable-examples --enable-tests  Once the installation is completed, you may get an output show

Installation of NS2 (ns-2.35) in Ubuntu 20.04

Installation of NS2 (ns-2.35) in Ubuntu 20.04 LTS Step 1: Install the basic libraries like      $] sudo apt install build-essential autoconf automake libxmu-dev Step 2: install gcc-4.8 and g++-4.8 open the file using sudo mode $] sudo nano /etc/apt/sources.list Include the following line deb http://in.archive.ubuntu.com/ubuntu bionic main universe $] sudo apt update $] sudo apt install gcc-4.8 g++-4.8 Step 3:  Unzip the ns2 packages to home folder $] tar zxvf ns-allinone-2.35.tar.gz $] cd ns-allinone-2.35/ns-2.35 Modify the following make files. ~ns-2.35/Makefile.in Change @CC@ to gcc-4.8 change @CXX@ to g++-4.8 ~nam-1.15/Makefile.in ~xgraph-12.2/Makefile.in ~otcl-1.14/Makefile.in Change in all places  @CC@ to gcc-4.8 @CPP@ or @CXX@ to g++-4.8 open the file: ~ns-2.35/linkstate/ls.h Change at the Line no 137  void eraseAll() { erase(baseMap::begin(), baseMap::end()); } to This void eraseAll() { this->erase(baseMap::begin(), baseMap::end()); } All changes made Step 4: Open a new termi

Installation of ns3 in Windows 10 and Windows 11 OS using WSL (Windows Subsystem for Linux)

This post shows how to install ns-3.33 in Windows 10 through WSL (Windows Subsystem for Linux) This posts works for Windows 11 also (I have tested it on a Windows 11 ISO and it works the Same way as mentioned in the following post.) This post will work for ns-3.3x version. Prerequisites : Install Windows Subsystem for Linux with GUI: Please refer the following video  System Information: OS used: Windows 10 and WSL (Ubuntu 20.04) GUI: XServer for Windows NS3 Version: ns-3.33 See the following complete video on how to install ns3 in Windows 10 Step 0 : Open XLaunch Step 1 :  Open WSL using PowerShell and open it as Administrator Command:/  wsl $ xfce4-session The GUI of Ubuntu Opens within Windows 10 OS. Step 2 : Download ns3 from nsnam.org website through Mozilla Firefox browser Step 3: Open a Terminal  $ sudo apt update $ sudo apt install build-essential autoconf automake libxmu-dev python3-pygraphviz cvs mercurial bzr git cmake p7zip-full python3-matplotlib python-tk python3-dev qt5-q