Tuesday, 18 March 2014

Simulation of IEEE 802.15.4 (WPAN) in NS-2

To simulate 802.15.4, we just need two commands.

1. $node sscs startPANCoord <txBeacon = 1> <beaconOrder = 3>  <SuperframeOrder = 3>
This command can be used to start a PAN coordinator. Generally, there will be only one coordinator in a PAN.  If some parameters are omitted, the default values shown above will be assumed.
Examples:
$node_(0) sscs startPANCoord
$node_(0) sscs startPANCoord 1 3 3
2. $node sscs startDevice <isFFD = 1> <assoPermit = 1> <txBeacon = 0> <beaconOrder = 3> <SuperframeOrder = 3>
 This Command can be used to start a device or coordinator. If some parameters are omitted, the default values shown above will be assumed.
Examples:
$node_(0) sscs startDevice // non-beacon
$node_(0) sscs startDevice 1 1 1 // beacon enabled

Following is the simple tcl script to simulate IEEE 802.15.4. It consists of only two nodes; 1 coordinator and 1 end node.

==================================Start=================================
set stopTime 100
set BO 3
set SO 3
set speed 1
#speed is in m/s

# ======================================================================
# Define options
# ======================================================================
set val(chan)        Channel/WirelessChannel    ;# Channel Type
set val(prop)        Propagation/TwoRayGround   ;# radio-propagation model
set val(netif)         Phy/WirelessPhy/802_15_4
set val(mac)         Mac/802_15_4
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)          AODV                       ;# routing protocol
set val(x)           50
set val(y)           50
set opt(err)        UniformErrorProc

set val(nam)                2nodes.nam
set val(traffic) cbr                        ;# cbr/poisson/ftp

#read command line arguments
proc getCmdArgu {argc argv} {
        global val
        for {set i 0} {$i < $argc} {incr i} {
                set arg [lindex $argv $i]
                if {[string range $arg 0 0] != "-"} continue
                set name [string range $arg 1 end]
                set val($name) [lindex $argv [expr $i+1]]
        }
}
getCmdArgu $argc $argv

##This is optional error model. you can delete it if u dont need it
proc UniformErrorProc {} {
#          puts "useing error model-"
            set err [new ErrorModel]
#          $err unit pkt
            $err set rate_ 0.05
            return $err
}

# Initialize Global Variables
set ns_             [new Simulator]
set tracefd     [open ./2nodes.tr w]
$ns_ trace-all $tracefd
if { "$val(nam)" == "2nodes.nam" } {
       set namtrace     [open ./$val(nam) w]
        $ns_ namtrace-all-wireless $namtrace $val(x) $val(y)
}

$ns_ puts-nam-traceall {# nam4wpan #}                   ;# inform nam that this is a trace file for wpan (special handling needed)

#Mac/802_15_4 wpanNam macType $para1  # added by pranesh
Mac/802_15_4 wpanCmd verbose on
Mac/802_15_4 wpanNam namStatus on                   ;# default = off (should be turned on before other 'wpanNam' commands can work)
#Mac/802_15_4 wpanNam ColFlashClr gold             ;# default = gold

# For model 'TwoRayGround'
set dist(5m)  7.69113e-06
set dist(9m)  2.37381e-06
set dist(10m) 1.92278e-06
set dist(11m) 1.58908e-06
set dist(12m) 1.33527e-06
set dist(13m) 1.13774e-06
set dist(14m) 9.81011e-07
set dist(15m) 8.54570e-07
set dist(16m) 7.51087e-07
set dist(20m) 4.80696e-07
set dist(25m) 3.07645e-07
set dist(30m) 2.13643e-07
set dist(35m) 1.56962e-07
set dist(40m) 1.20174e-07
Phy/WirelessPhy set CSThresh_ $dist(15m)
Phy/WirelessPhy set RXThresh_ $dist(15m)

# set up topography object
set topo       [new Topography]
$topo load_flatgrid $val(x) $val(y)
#ns-random 1  gives same result in trace file everytime simulation is done
#ns-random 0 gives different result in trace file when simulated
ns-random 0
# Create God
set god_ [create-god $val(nn)]
set chan_1_ [new $val(chan)]

# configure node
$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 OFF \
                        -macTrace ON \
                        -movementTrace OFF \
                        -energyModel "EnergyModel" \
                        -initialEnergy 10 \
                        -idlePower 0.00279 \
                        -rxPower 0.0565 \
                        -txPower 0.048 \
                        -sleepPower 0.000030 \
                        -transitionPower 0.002 \
                        -transitionTime 0.0002 \
                        -IncomingErrProc $opt(err) \
                        -channel $chan_1_ 

for {set i 0} {$i < $val(nn) } {incr i} {
            set node_($i) [$ns_ node]      
            $node_($i) random-motion 0             ;# disable random motion
}
##initial postion of node 0 and node 1
$node_(0) set X_ 25.0
$node_(0) set Y_ 25.0
$node_(0) set Z_ 0.0
$node_(1) set X_ 10.0
$node_(1) set Y_ 25.0
$node_(1) set Z_ 0.0


$ns_ at 0.0  "$node_(0) NodeLabel PAN Coor"
$ns_ at 0.0  "$node_(0) sscs startPANCoord 1 $BO $SO"  ;# startPANCoord <txBeacon=1> <BO=3> <SO=3>
$ns_ at 5  "$node_(1) sscs startDevice 0 0 0 $BO $SO"

Mac/802_15_4 wpanNam PlaybackRate 3ms
$ns_ at 50 "puts \"\nTransmitting data ...\n\""

##define traffic type and date rate 
set udp_(0) [new Agent/UDP]
$ns_ attach-agent $node_(1) $udp_(0)
set null_(0) [new Agent/Null]
$ns_ attach-agent $node_(0) $null_(0)
set cbr_ [new Application/Traffic/CBR]
$cbr_ set packetSize_ 100
$cbr_ set interval_ 0.2
$cbr_ set random_ 1
$cbr_ attach-agent $udp_(0)
$ns_ connect $udp_(0) $null_(0)
$ns_ at 50 "$cbr_ start"

# the following command is for moving the node 1. you can disable it if you dont need it.
#node 1 will start to meet at time 70 towards the cordinate(42,25) at the speed of $speed. $speed is defined at top.
$ns_ at 70 "$node_(1) setdest 42.00 25 $speed"

# defines the node size in nam
for {set i 0} {$i < $val(nn)} {incr i} {
            $ns_ initial_node_pos $node_($i) 2
}

# Tell nodes when the simulation ends
for {set i 0} {$i < $val(nn) } {incr i} {
    $ns_ at $stopTime "$node_($i) reset";
}

##to stop simulation
$ns_ at $stopTime "stop"
$ns_ at $stopTime "puts \"\nNS EXITING...\n\""
$ns_ at $stopTime "$ns_ halt"

proc stop {} {
    global ns_ tracefd appTime val env
    $ns_ flush-trace
    close $tracefd
    set hasDISPLAY 0
    foreach index [array names env] {

        if { ("$index" == "DISPLAY") && ("$env($index)" != "") } {
                set hasDISPLAY 1
        }
    }
}
puts "\nStarting Simulation..."
$ns_ run

===========================End====================

Extra Features in the TCL


In the above two extra features have been added as bonus. 
  1. Error model
Error model has been added in the tcl file. UniformErrorProc defines the error mode and error rate. The error rate is set to 5%. If someone don’t need error model you can delete the UniformErrorProc. But make sure you delete “-IncomingErrProc $opt(err) \”  from node-config function also.
  1. Setdest
Setdest has been used in the tcl file. Setdest function is use for node mobility. Setdest is used to move node from current position to new position.
The syntax is:
 $node_(1) setdest  newXpos newYpos speed

for example: setdest 50 50 2 ;  will move node 1 from current location to 50,50 at the speed of 2 m/s.
You can disable the node movement by just delete the setdest line.


P.S. Queries are welcome. I will try to answer to my earliest convince. Thank you.


23 comments:

  1. Sir Pranesh,

    I tried your code and I am getting the following trace format:
    s 0.000960000 _0_ MAC --- 0 CM7 8 [0 ffffffff 0 0] [energy 9.999981 ei 0.000 es 0.000 et 0.000 er 0.000]
    N -t 0.000960 -n 1 -e 9.999972
    r 0.001408050 _1_ MAC --- 0 CM7 8 [0 ffffffff 0 0] [energy 9.999972 ei 0.000 es 0.000 et 0.000 er 0.000]

    How to analyse it? This is old trace format. Can you refer some awk script for calculating throughtput in this case?

    Thank you

    ReplyDelete
    Replies
    1. use this awk script..it will work...

      http://www.ifn.et.tu-dresden.de/~marandin/ZigBee/avg_throughput.awk

      Delete
  2. Sir thank you the link you provided helped much. Kindly answer this question:

    In this code or any demo code of wpan available in NS2, where are we defining the radio range of the nodes? Is it 15m as defined under Two ray ground model?

    ReplyDelete
  3. yes, as seen in the tcl, you can vary the radio range from 5m to 40m.
    for eg. if you want to change the range to 40m, do it as follows
    Phy/WirelessPhy set CSThresh_ $dist(40m)<-
    Phy/WirelessPhy set RXThresh_ $dist(40m)<-

    ReplyDelete
  4. Sir if I want to change the value of macminBE (backoff exponential) in 802.15.4 in ns2 can you please tell how is it possible? I am changing in p805_15_4const.h file but no changes are being reflected in the results.

    Thank you.

    ReplyDelete
    Replies
    1. try looking at this code in the file p802_15_4csmaca.cc on line 87 ...it may be reason...try changing code in this part...

      void CsmaCA802_15_4::reset(void)
      {
      if (beaconEnabled)
      {
      NB = 0;
      CW = 2;
      BE = mac->mpib.macMinBE;
      if ((mac->mpib.macBattLifeExt)&&(BE > 2))
      BE = 2;
      }
      else
      {
      NB = 0;
      BE = mac->mpib.macMinBE;
      }
      }

      Delete
    2. could u please explain me the basic flow of this program what we are doing..

      Delete
  5. How to make automatic start NAM file of the above code ?

    ReplyDelete
  6. Sir, your tutorial just only for starting PanCoordinator and for device. Would you please to explain me how to activate the router? Because in 802.15.4 (zigbee), has 3 type of nodes; end device, router, and coordinator.

    ReplyDelete
  7. I want to add another node which will transmit data to node-0 , so will you tell me, what will be the changes in the below syntax? i.e., which parameters should i change.

    $ns_ at 0.0 "$node_(0) NodeLabel PAN Coor"
    $ns_ at 0.0 "$node_(0) sscs startPANCoord 1 $BO $SO" ;# startPANCoord
    $ns_ at 5 "$node_(1) sscs startDevice 0 0 0 $BO $SO"

    Thank you in advance

    ReplyDelete
  8. Hi,
    please, if it's possible, tell me how to implement GTS (CFP) of IEEE 802.15.4 in tcl file.
    i found the implementation of the modification in WPAN for taking account of the GTS but i don't know how to implement in tcl file.
    thanks in advance

    ReplyDelete
    Replies
    1. as far as i know, there is no gts in default wpan of ns-2

      Delete
  9. hi sir plese if it's possible i need to patch my ns2.35 on 802.15.4 .what should i do ? thanks in advance

    ReplyDelete
  10. hi sir plese if it's possible i need to patch my ns2.35 on 802.15.4 .what should i do ? thanks in advance

    ReplyDelete
    Replies
    1. Just Download WPAN_ZBR from internet and use it in ns2.35 directly. no need to change anything in this code. just download it and run simulation.
      faseekhan@yahoo.com is my email for further assistance...

      Delete
  11. Just Download WPAN_ZBR from internet and use it in ns2.35 directly. no need to change anything in this code. just download it and run simulation.
    faseekhan@yahoo.com is my email for further assistance....

    ReplyDelete
  12. Hi Sir, how can i add more source nodes into the network to transmit data to the sink, what will be the changes to be made? Thank you

    ReplyDelete
  13. I tried with above tcl, its not affecting on throughput/ delivery ratio/ delay due to error model.
    There is no effect on addition/ removal of error model.

    ReplyDelete
  14. No need to download WPAN_ZBR from internet.
    step 1:
    just download ns-2.35 from the official website.
    step 2:
    open up the file "/ns-allinone-2.35/ns-
    2.35/linkstate/ls.h" in an editor. You can do it either from the terminal or from the file
    explorer (Nautilus). We have to make some changes in the ls.h file else it will show an error
    while installing the NS. Once you have opened the file move to the line 137 and replace the
    erase (image 1) with this—>erase (image 2) and save the file.
    step 3:
    install ns-2.35
    step 4:
    setup paths for directories as mentioned by installation process

    ReplyDelete
  15. Dear Sir,
    I have run this code, but i can't get some output parameters from the trace file like throughput, jitter, delay etc. plz guide me to change the code for such parameters.
    Thank you sir.

    ReplyDelete
  16. You have to insert individual codes for throughput, delay and loss calculation inside your program. You can get those files from other .tcl files from Internet. After inserting those codes, you will get those parameters in your trace files. All the best.

    ReplyDelete
  17. Dear Sir if i need to make the BO and SO variable according to the network traffic for mitigating the delay and energy consumption of the 802.15.4, so only TCL file should be changed or any other files are also to be modified?
    and how I can make BO and SO dynamic???
    Thank you.

    ReplyDelete