Tuesday, 16 October 2012

LEACH in NS2 using Mannasim Frame-work

The code in the editor below shows how to simulate LEACH protocol
using MannaSim patch with ns2. A summary of the simulation settings is
given below:

Area: 500 m X 500m
Duration: 550 sec
# of nodes: 11
# of clusters: 4
New cluster formation interval: 100 sec (fixed)
Initial energy: 10 joules
Disseminating interval: 10 sec
Transmission range: 50 m
Channel type: Wireless
Transport protocol: UDP
Layer: Physical
Antenna: OmniAntenna
Radio Propagation:TwoRayGround
Sensing interval: 5 sec
Data generator type: Temperature
Sensing type: Programmed

The no. of access points has been set to be 0 for our simulation and
all the nodes are static.

The ratio P that has been referred to while describing LEACH in the
theory section is obtained in our case as k/N, where k is the # of
desired cluster heads, and N is the total # of nodes in the network.

Now, answer the following and verify them from the simulation results:

For the given simulation time, how many rounds of cluster formation take place?
What is the number of cluster heads per round?
Does the average number of cluster heads per round equal the desired
number of cluster heads (line #475)? (See the discussion on LEACH in
Theory section)
Vary the number of nodes (line #474) and expected number of cluster
heads (line #475), and once again verify the output


# Generated by MannaSim


puts "Initializing MannaSim Script..."

#Consumo de energia do sensor node - Dados do Mica Motes
set mica(sensing_power) 0.015 ;# i = 5mA, V = 3 --> P = ixV = 15 mW = 0.015 W
set mica(processing_power) 0.024 ;# i = 8mA, V = 3 --> P = ixV = 24 mW = 0.024 W
set mica(instructions_per_second) 8000000 ;# Atmel 128L 8MHZ --> 8MIPS

#Consumo de energia do sensor node - Dados do WINS
set wins(sensing_power) 0.064 ;# 64 mW = 0.064 W
set wins(processing_power) 0.360 ;# 360 mW = 0.360 W
set wins(instructions_per_second) 150000000 ;# Intel StrongArm 1100 133 MHZ --> 150 MIPS

#Seta valores para consumo de energia com o radio
set mica(consumo_transmissao) 0.036 ;#i = 12mA, V = 3 --> P = ixV = 36mW = 0.036W
set mica(consumo_recepcao) 0.024 ;#i = 8mA, V = 3 --> P = ixV = 24mW = 0.024W

set wins(consumo_transmissao)   3.75 ;# 3.75 250m, 0.6 600 mW - 100m
set wins(consumo_recepcao) 1.875 ;# 1.875 250m,  0.3 300 mW

#seta a taxa de transmissao
#Phy/WirelessPhy set  bandwidth_
set mica(taxa_transmissao) 28.8*10e3 ;#28.8 kbps
set wins(taxa_transmissao) 100*10e3 ;#100 kbps

proc setup_mica2 { antenna range }  {
        puts "Setting up mica 2 mote with $antenna and range = $range"      

        Phy/WirelessPhy set Pt_ 0.281838
        Phy/WirelessPhy set freq_ 2.4e09
        Phy/WirelessPhy set L_ 1.0
        Phy/WirelessPhy set lambda_ 0.125
        Phy/WirelessPhy set RXThresh_ [TwoRay 0.281838 [$antenna set Gt_] [$antenna set Gr_] 0.8 0.8 1.0 $range 0.125]
        Phy/WirelessPhy set bandwidth_ 28.8*10e3        ;#28.8 kbps

        Node/MobileNode/SensorNode set sensingPower_ 0.015
        Node/MobileNode/SensorNode set processingPower 0.024
        Node/MobileNode/SensorNode set instructionsPerSecond_ 8000000

}

##########################################
# CONSTANTES
#########################################
# Continuo: 0
# Programada: 1
# Sob Demanda: 2
########################################

proc create_common_app {destination_id disseminating_type disseminating_interval} {
    global val
    #puts "executing create_common_app\n"
    if { $val(commonApp) == "Application/SensorBaseApp/CommonNodeApp/LeachApp" } {
          if { $val(n_ch) == 0 } {
                   puts "NO CLUSTER HEADS HAS BEEN DEFINED! Assuming 20% of common nodes."
                   set val(n_ch) [expr int($val(n_common) * 2 / 10)]
          }
          #puts "Debug: val(n_ch): $val(n_ch)\n";
          set app_ [new $val(commonApp) $val(nn) $val(n_ch) [expr sqrt($val(x) * $val(x) + $val(y) * $val(y))]]
    } else {
          set app_ [new $val(commonApp)]
          $app_ set destination_id_ $destination_id
    }
    $app_ set disseminating_type_ $disseminating_type
    $app_ set disseminating_interval_ $disseminating_interval
    return $app_
}

set val(commonApp) "Application/SensorBaseApp/CommonNodeApp"
set val(chApp)     "Application/SensorBaseApp/ClusterHeadApp"
set val(apApp)     "Application/AccessPointApp"

proc create_cluster_head_app {destination_id disseminating_type disseminating_interval} {
    global val
    set app_ [new $val(chApp)]
    $app_ set destination_id_ $destination_id
    $app_ set disseminating_type_ $disseminating_type
    $app_ set disseminating_interval_ $disseminating_interval
    return $app_
}

proc create_access_point_app {outside_network} {
    global val
    set app_ [new $val(apApp)]
    $app_ set outside_network_ $outside_network
    return $app_
}

proc create_temp_data_generator {sensing_interval sensing_type avg_measure std_deviation maximumTemperatureAllowedValue} {
    set temp_gen_ [new DataGenerator/TemperatureDataGenerator]
    $temp_gen_ set sensing_interval_ $sensing_interval
    $temp_gen_ set sensing_type_ $sensing_type
    $temp_gen_ set avg_measure $avg_measure
    $temp_gen_ set std_deviation $std_deviation
    $temp_gen_ set maximumTemperatureAllowedValue_ $maximumTemperatureAllowedValue
    return $temp_gen_
}

proc create_data_generator {generator sensing_interval sensing_type avg_measure std_deviation maximumTemperatureAllowedValue} {
    set temp_gen_ [new DataGenerator/$generator]
    $temp_gen_ set sensing_interval_ $sensing_interval

    if {$sensing_type=="continuous"} {
          $temp_gen_ set sensing_type_ 0
    } elseif {$sensing_type=="programmed"} {
          $temp_gen_ set sensing_type_ 1
    } elseif {$sensing_type=="on demand"} {
          $temp_gen_ set sensing_type_ 2
    } else {          
          $temp_gen_ set sensing_type_ $sensing_type
    }
    $temp_gen_ set avg_measure $avg_measure
    $temp_gen_ set std_deviation $std_deviation
    $temp_gen_ set maximumTemperatureAllowedValue_ $maximumTemperatureAllowedValue
    return $temp_gen_
}

proc create_common_node { iniEnergy x y z father_addr start stop } {
    global val ns_ node_ topo udp_ app_ gen_ contador_nodos rng trace

    if { [llength $start] == 0 }  {
            set start [expr $val(start) + [$rng uniform 0 1]]
            set stop $val(stop)
    }

    $ns_ node-config -sensorNode ON \
        -adhocRouting $val(rp) \
        -llType $val(ll) \
        -macType $val(mac) \
        -ifqType $val(ifq) \
        -ifqLen $val(ifqlen) \
        -antType $val(antenna) \
        -propType $val(prop) \
        -energyModel $val(en) \
        -phyType $val(netif) \
        -channelType $val(chan) \
        -topoInstance $topo \
        -agentTrace $trace(agent) \
        -routerTrace $trace(router) \
        -macTrace $trace(mac) \
        -rxPower 0.024 \
        -txPower 0.036 \
        -initialEnergy $iniEnergy \
        -movementTrace $trace(movement)

        set node_($contador_nodos) [$ns_ node]
        $node_($contador_nodos) random-motion 0

        $node_($contador_nodos) set X_ $x
        $node_($contador_nodos) set Y_ $y
        $node_($contador_nodos) set Z_ $z

        puts "* Node [$node_($contador_nodos) node-addr] = $contador_nodos created in ($x, $y, $z)"

        set app_($contador_nodos) [create_common_app $father_addr $val(disseminating_type) $val(disseminating_interval)]

        if { $val(leach) == 1 } {
              set agent [new Agent/RCAgent]

              $agent set sport_ 0
              $agent set dport_ 0

              $node_($contador_nodos) attach $agent 0
              $app_($contador_nodos) attach-agent $agent

              $agent add-ll [$node_($contador_nodos) set ll_(0)] [$node_($contador_nodos) set mac_(0)]
        } else {
                set udp_($contador_nodos) [new Agent/UDP]
                $node_($contador_nodos) attach $udp_($contador_nodos) $val(port)
        }
        $node_($contador_nodos) add-app $app_($contador_nodos)

        set processing_($contador_nodos) [new $val(processing)]

        $app_($contador_nodos) node $node_($contador_nodos)

        if { $val(leach) != 1 } {
                $app_($contador_nodos) attach-agent $udp_($contador_nodos)
        }

        $app_($contador_nodos) attach-processing $processing_($contador_nodos)
        $processing_($contador_nodos) node $node_($contador_nodos)

        for { set i 0 } { $i < [llength $start] } { incr i } {
                $ns_ at $start "$app_($contador_nodos) start"
        }

        for { set i 0 } { $i < [llength $stop] } { incr i } {
                $ns_ at $stop "$app_($contador_nodos) stop"
        }

        #[create_temp_data_generator  5.0 0 27.0 10.0 50]
        set gen_($contador_nodos) $val(data_generator)

        $app_($contador_nodos) attach_data_generator $gen_($contador_nodos)

        incr contador_nodos

}

proc create_cluster_head_node { iniEnergy x y z father_addr start stop } {

        global val ns_ node_ topo udp_ app_ gen_ contador_nodos rng trace

        if { [llength $start] == 0 }  {
                set start [expr $val(start) + [$rng uniform 0 1]]
                set stop $val(stop)
        }

        $ns_ node-config -sensorNode ON \
            -adhocRouting $val(rp) \
            -llType $val(ll) \
            -macType $val(mac) \
            -ifqType $val(ifq) \
            -ifqLen $val(ifqlen) \
            -antType $val(antenna) \
            -propType $val(prop) \
            -energyModel $val(en) \
            -phyType $val(netif) \
            -channelType $val(chan) \
            -topoInstance $topo \
             -agentTrace $trace(agent) \
            -routerTrace $trace(router) \
            -macTrace $trace(mac) \
            -rxPower 0.024 \
            -txPower 0.036 \
            -initialEnergy $iniEnergy \
            -movementTrace $trace(movement)

        #puts "Debug Cluster head iniEnergy: $iniEnergy\n";

        set node_($contador_nodos) [$ns_ node]
        $node_($contador_nodos) random-motion 0


        $node_($contador_nodos) set X_ $x
        $node_($contador_nodos) set Y_ $y
        $node_($contador_nodos) set Z_ $z

        puts "* Cluster head [$node_($contador_nodos) node-addr] = $contador_nodos created in ($x, $y, $z)"

        set udp_($contador_nodos) [new Agent/UDP]
        set app_($contador_nodos) [create_cluster_head_app $father_addr $val(disseminating_type) $val(disseminating_interval)]

        $node_($contador_nodos) attach $udp_($contador_nodos) $val(port)
        $node_($contador_nodos) add-app $app_($contador_nodos)

#CN#        set processing_($contador_nodos) [new $val(processing)]

        $app_($contador_nodos) node $node_($contador_nodos)
        $app_($contador_nodos) attach-agent $udp_($contador_nodos)

#CN#        $app_($contador_nodos) attach-processing $processing_($contador_nodos)
        $processing_($contador_nodos) node $node_($contador_nodos)

        for { set i 0 } { $i < [llength $start] } { incr i } {
                $ns_ at $start "$app_($contador_nodos) start"
        }

        for { set i 0 } { $i < [llength $stop] } { incr i } {
                $ns_ at $stop "$app_($contador_nodos) stop"
        }

#CN#        set gen_($contador_nodos) $val(data_generator)
#CN#        $app_($contador_nodos) attach_data_generator $gen_($contador_nodos)

        incr contador_nodos

}

proc create_access_point { iniEnergy x y z start stop} {
        global ns_ val node_ app_ udp_ contador_nodos topo trace rng

        if { [llength $start] == 0 }  {
                set start [expr $val(start) + [$rng uniform 0 1]]
                set stop $val(stop)
        }

        $ns_ node-config -sensorNode ON \
            -adhocRouting $val(rp) \
            -llType $val(ll) \
            -macType $val(mac) \
            -ifqType $val(ifq) \
            -ifqLen $val(ifqlen) \
            -antType $val(antenna) \
            -propType $val(prop) \
            -energyModel $val(en) \
            -phyType $val(netif) \
            -channelType $val(chan) \
            -topoInstance $topo \
             -agentTrace $trace(agent) \
            -routerTrace $trace(router) \
            -macTrace $trace(mac) \
            -rxPower 0.5 \
            -txPower 0.5 \
            -initialEnergy $iniEnergy \
            -movementTrace $trace(movement)

        #puts "Debug AP iniEnergy: $iniEnergy\n";

        set node_($contador_nodos) [$ns_ node]
        $node_($contador_nodos) random-motion 0
        set app_($contador_nodos) [create_access_point_app [$node_(0) node-addr]]

        if { $val(leach) == 1 } {
              set agent [new Agent/RCAgent/LeachAgent]

              $agent set sport_ 0
              $agent set dport_ 0

              $node_($contador_nodos) attach $agent 0
              $app_($contador_nodos) attach-agent $agent

              $agent add-ll [$node_($contador_nodos) set ll_(0)] [$node_($contador_nodos) set mac_(0)]
        } else {
              set  udp_($contador_nodos) [new Agent/UDP]
              $node_($contador_nodos) attach $udp_($contador_nodos) $val(port)
              $app_($contador_nodos) attach-agent $udp_($contador_nodos)
        }
        $node_($contador_nodos) set X_ $x
        $node_($contador_nodos) set Y_ $y
        $node_($contador_nodos) set Z_ $z

        puts "* Access point [$node_($contador_nodos) node-addr] = $contador_nodos created in ($x, $y, $z)"

        for { set i 0 } { $i < [llength $start] } { incr i } {
                $ns_ at $start "$app_($contador_nodos) start"
        }

        for { set i 0 } { $i < [llength $stop] } { incr i } {
                $ns_ at $stop "$app_($contador_nodos) stop"
        }

        incr contador_nodos

}

###
# Grid distribution.

proc get_next_x {} {

        global val
        set aux [expr int(sqrt($val(nn)))]
        return [expr (($contador_nodos) % $aux) * $val(x) / ($aux - 1)]

}

proc get_next_y {} {

        global val
        set aux [expr int(sqrt($val(nn)))]
        return [expr (($contador_nodos) / $aux) * $val(y) / ($aux - 1)]

}

####
# Calculating the receiving threshold (RXThresh_ for Phy/Wireless)
# Wei Ye, weiye@isi.edu, 2000

proc Friis { Pt Gt Gr lambda L d} {
  set M [expr $lambda / (4 * 3.14159265359 * $d)]
  return [expr ($Pt * $Gt * $Gr * ($M * $M)) / $L]
}

proc TwoRay { Pt Gt Gr ht hr L d lambda } {
        set crossover_dist [expr (4 * 3.14159265359 * $ht * $hr) / $lambda]

        if { $d < $crossover_dist } {
                return [Friis $Pt $Gt $Gr $lambda $L $d]
        } else {
                return [expr $Pt * $Gt * $Gr * ($hr * $hr * $ht * $ht) / ($d * $d * $d * $d * $L)]
       }
}

###

proc set_default_settings {} {

        global val

        ####
        # Default network settings
        set val(antenna) "Antenna/OmniAntenna"
        Antenna/OmniAntenna set X_ 0 ;
        Antenna/OmniAntenna set Y_ 0 ;
        Antenna/OmniAntenna set Z_ 1.5 ;
        Antenna/OmniAntenna set Gt_ 1.0 ;
        Antenna/OmniAntenna set Gr_ 1.0 ;

        ###

        # Using Mica 2 Mote settings


        set val(range) 100
        setup_mica2 $val(antenna) $val(range)
        set val(bandwidth) [Phy/WirelessPhy set bandwidth_]
        set val(mac)    Mac/802_11
        set val(ifq)    Queue/DropTail
        set val(ifqlen) 200
        set val(ll) LL
        set val(rp) "LEACH"


        # Configuration adjustment

        if { $val(rp) == "LEACH" } {

                set val(rp) DumbAgent
                set val(leach) 1

                if { $val(ll) != "RCALinkLayer" } {
                        puts "LEACH requires RCALinkLayer! Forcing it!!!"                   
                        set val(ll) RCALinkLayer
                }

                if { $val(netif) != "Phy/WirelessPhy/LeachWirelessPhy" } {
                        puts "LEACH requires LeachWirelessPhy! Forcing it!!!"
                        set val(netif) Phy/WirelessPhy/LeachWirelessPhy
                }

                if { $val(mac) != "Mac/Sensor" } {
                        puts "LEACH requires Mac/Sensor! Forcing it!!!"
                        set val(mac) Mac/Sensor
                }

                set val(port) 0

                Agent/RCAgent set sport_           $val(port)
                Agent/RCAgent set dport_           $val(port)
                Agent/RCAgent set packetMsg_       0
                Agent/RCAgent set distEst_         0
                Agent/RCAgent set packetSize_      0

                RCALinkLayer set delay_            25us
                RCALinkLayer set bandwidth_        [Phy/WirelessPhy set bandwidth_]
                RCALinkLayer set off_prune_        0
                RCALinkLayer set off_CtrMcast_     0
                RCALinkLayer set macDA_            0
                RCALinkLayer set debug_            0
        } else {
                set val(leach) 0
        }
        if { $val(rp) == "DIRECTED DIFFUSION" } {
                set val(rp) "Directed_Diffusion"
        }       
}

set val(father_addr) 0 
set val(port)   2020

set val(netif)  Phy/WirelessPhy

set_default_settings

# Global network settings
set contador_nodos 0
set val(chan)   Channel/WirelessChannel

# Propagation
set val(prop)   Propagation/TwoRayGround

# Energy model
set val(en) EnergyModel/Battery

# Nodes
set val(n_pas)  0
set val(n_common) 11
set val(n_ch) 4
set val(nn) [expr $val(n_pas) + $val(n_common) + $val(n_ch)]

puts "\nNodes count:"
puts " - $val(n_pas) access points"
puts " - $val(n_common) common nodes"
puts " - $val(n_ch) cluster heads"
puts " - $val(nn) nodes"
puts " - $val(rp) routing protocol"
puts " - $val(ll) link layer"
puts " - $val(netif) network interface"

# Scenario size
set val(x)  500.0
set val(y)  500.0

puts "\nScenario size: $val(x) x $val(y)"

set val(start)  0.0
set val(stop)   [expr $val(start) + 550.0]

set ns_     [new Simulator]


# Trace
puts "\nUsing trace.tr as trace file"
set traceFile   [open trace.tr w]
$ns_ trace-all $traceFile
$ns_ use-newtrace

set trace(mac) ON
set trace(router) ON
set trace(agent) ON
set trace(movement) ON


set topo    [new Topography]
$topo load_flatgrid $val(x) $val(y)
create-god $val(nn)
set rng [new RNG]
$rng seed [clock seconds]

#-------------------------------------------------------------------------------------------



# Creating an access point
puts "Creating an access point..."

set_default_settings


# Using Mica 2 Mote settings

puts "Using mica 2 mote settings"
set val(range) 100
setup_mica2 $val(antenna) $val(range)
set local(x) 50.0
set local(y) 50.0
set local(z) 0.0
set local(start) ""
set local(stop) ""
set local(energy) 100.0
set val(apApp) Application/AccessPointApp/AccessPointLeachApp

create_access_point $local(energy) $local(x) $local(y) $local(z) $local(start) $local(stop)



# Creating common node
puts "Creating common node..."

set_default_settings


# Using Mica 2 Mote settings
puts "Using mica 2 mote settings"

set val(range) 100
setup_mica2 $val(antenna) $val(range)

# Disseminating settings
set val(disseminating_type) 0       ;# Programmed
puts "Setting disseminating type to programmed"
set val(disseminating_interval) 10.0
puts "Setting disseminating interval: $val(disseminating_interval)"

set local(start) ""
set local(stop) ""
set local(energy) 10.0
set local(father_addr) $val(father_addr)

set val(processing) Processing/AggregateProcessing
set val(data_generator) "[create_data_generator {TemperatureDataGenerator} {5.0} {programmed} {25.0} {5.0} {30.0}]"


for { set common_node_i 0 } { $common_node_i < 10 } { incr common_node_i } {
    set local(x) [$rng uniform 0.0 $val(x)]
    set local(y) [$rng uniform 0.0 $val(y)]
    set local(z) 0.0

    set val(commonApp) Application/SensorBaseApp/CommonNodeApp/LeachApp
    create_common_node $local(energy) $local(x) $local(y) $local(z) $local(father_addr) $local(start) $local(stop)
}


$ns_ at [expr $val(stop)] "flush stdout"
$ns_ at [expr $val(stop)+0.0001] "finish"


proc finish {} {
    global ns_ traceFile namtrace tempoInicio val

    $ns_ flush-trace
    #    close $namtrace
    $ns_ halt
    $ns_ flush-trace
    #$ns_ nam-end-wireless $val(stop)
    close $traceFile
    #close $namtrace
    flush stdout

    exit 0
}

puts "Starting Simulation..."
$ns_ run