资源描述
WSN中LEACH协议源码分析
———————————————————————————————— 作者:
———————————————————————————————— 日期:
12
个人收集整理 勿做商业用途
WSN中LEACH协议源码分析
分析(一)
首先对wireless。tcl进行分析,先对默认的脚本选项进行初始化:
set opt(chan)Channel/WirelessChannel
set opt(prop) Propagation/TwoRayGround
set opt(netif)Phy/WirelessPhy
set opt(mac) Mac/802_11
set opt(ifq) Queue/DropTail/PriQueue
set opt(ll) LL
set opt(ant) Antenna/OmniAntenna
set opt(x) 0 ;# X dimension of the topography
set opt(y) 0 ;# Y dimension of the topography
set opt(cp) "”
set opt(sc) ”。。/mobility/scene/scen-670x670—50—600—20—2” ;# scenario file
set opt(ifqlen) 50;# max packet in if
set opt(nn) 51 ;# number of nodes
set opt(seed) 0.0
set opt(stop) 10.0 ;# simulation time
set opt(tr) out。tr ;# trace file
set opt(rp) dsdv ;# routing protocol script
set opt(lm) "on” ;# log movement
在这个wireless.tcl中设置了一些全局变量:
#
# Initialize Global Variables
#
set ns_ [new Simulator]
set chan [new $opt(chan)]
set prop [new $opt(prop)]
set topo [new Topography]
set tracefd [open $opt(tr) w]
$topo load_flatgrid $opt(x) $opt(y)
$prop topography $topo
这些初始化将在后面的使用中用到,该文件最重要的是创建leach节点:创建方法如下:
} elseif { [string compare $opt(rp) "leach”] == 0} {
for {set i 0} {$i < $opt(nn) } {incr i} {
leach—create—mobile-node $i
}
如果路由协议是leach协议,则在Uamps.tcl中调用leach-create-mobile-node方法创建leach节点。将在第二小节讲如何创建leach节点。
for {set i 0} {$i 〈 $opt(nn) } {incr i} {
$ns_ at $opt(stop)。000000001 "$node_($i) reset"; //完成后,重置节点的应用
}
$ns_ at $opt(stop)。00000001 ”puts \"NS EXITING。。。\" ; $ns_ halt"
if { $opt(sc) == ”” } {
puts ”*** NOTE: no scenario file specified.”
set opt(sc) ”none”
} else {
puts "Loading scenario file。.."
source $opt(sc)
puts "Load complete。。.”
}
ns在什么时候结束simulation,并告诉ns加载sc场景文件。最后$ns_ run则ns就开始运行了。
分析(二)
上节对wireless。tcl进行了简要的分析,接下来对Uamps.tcl脚本进行分析。
set opt(Efriss_amp) [expr [expr 1。1 * $opt(RXThresh) * 16 * $PI * $PI] / \
[expr $opt(bw) * $opt(Gt) * $opt(Gr) * $l * $l]]
# Etwo_ray_amp = RXThresh / (Rb Gt Gr ht^2 hr^2)
set opt(Etwo_ray_amp) [expr 1.1 * $opt(RXThresh) / \
[expr $opt(bw) * $opt(Gt) * $opt(Gr) * \
$opt(ht) * $opt(ht) * $opt(ht) * $opt(ht)]]
set opt(EXcvr) 50e—9 ;# Energy for radio circuitry
set opt(e_bf) 5e-9 ;# Beamforming energy (J/bit)
set opt(Esense) 0 ;# Sensing energy (J/bit)
set opt(thresh_energy) 0。00 ;# Threshold for power adaptation
set opt(Pidle) 0 ;# Idle power (W)
set opt(Psleep) 0 ;# Sleep power (W)
set initialized 0
set rng_ [new RNG]#用于产生随机数
首先往opt数组里面添加一些变量,并对这些变量进行初化。opt(Psleep) ,opt(Pidle), opt(thresh_energy)在ns—leach。tcl中使用到,这个是计算单位时间空闲所消耗的能量和休眠所消耗的能量。
这个脚本主要是创建leach节点:
if {$initialized == 0} {
#remove old trace
sens_init
set initialized 1
}
# Remove old trace files.
catch ”eval exec rm [glob —nocomplain $opt(dirname)/TDMAschedule.*.txt]”
catch ”exec rm $opt(dirname)/$opt(filename).energy"
catch ”exec rm $opt(dirname)/$opt(filename).data"
catch ”exec rm $opt(dirname)/$opt(filename).alive"
catch ”exec rm $opt(dirname)/startup.energy”
catch ”exec rm $opt(dirname)/init.energy"
如果没有初始化过,则将以前的跟踪文件删除,接着回到创建leach的函数中,创建节点:
if {$id != $opt(nn_)} {
puts —nonewline "$id ”
#important
set node_($id) [new MobileNode/ResourceAwareNode]
} else {
puts "($opt(nn_) == BS)”
set node_($id) [new MobileNode/ResourceAwareNode $BS_NODE]
}
如果不是簇头节点则将$opt(nn_)-1个节点设置为一般节点,将$opt(nn_)设置为BS节点.newMobileNode/ResourceAwareNode函数是在ns—ranode.tcl中。分析完这个我们接下来分析newMobileNode/ResourceAwareNode这个函数。
set node $node_($id)
if {$id != $opt(nn_)} {
# Set initial node energy。
if {$opt(eq_energy) == 1} {
$node set-energy $opt(init_energy) $opt(thresh_energy)
} else {
由于eq-energy在leach—test中给定,将eq—energy=1;则每个节点都会对能量进行初始化,设置节点的初始能量和门槛能量(个人理解,死亡能量)。
set high_e_nodes [list 97 19 12 87 8 22 83 55 34 72]
if {[lsearch $high_e_nodes $id] == —1} {
set E 2
} else {
set E 200
}
$node set-energy $E $opt(thresh_energy)
set initf [open ”$opt(dirname)/init。energy" a]
puts $initf ”$id\t$E"
close $initf
将不属于list中的能量初始化能量设置为2,将属于list中的能量设置为200。并将初始化能量写到init.energy中,将节点id和节点初始能量写进去。
else {
# Base station has an infinite amount of energy。
$node set—energy 50000 $opt(thresh_energy)
}
节点为簇头节点,则将节点的初始化能量设置为50000,能量无限.
到此为止,创建节点完成并将每个节点的能量初始化完成。下一节将分析ns-ranode.tcl脚本。区分普通节点和簇头节点的不同。接下来是配置节点信道和跟踪文件:
$ns_ at 0.0 "$node_($id) start—app" ns在0的时候启动应用,应用在ns—ranode。tcl中分析。
分析(三)
对前面两个脚本进行分析后,已经创建好节点和设置好节点的初始能量,将opt(nn_)-1个节点设置为普通节点,而将opt(nn_)设置为bs。现在对ns—ranode。tcl进行分析。好了我们现在就开始分析这个脚本。
Class MobileNode/ResourceAwareNode —superclass Node/MobileNode
MobileNode/ResourceAwareNode instproc init args
set bs_node [lindex $args 0]
eval $self next [lreplace $args 0 0]
args由参数传递进来,若节点为簇头节点则bs_node=1,调用父类初始化函数。
set ResourceManager_ [new ResourceManager]
$ResourceManager_ Register [new Resource/NeighborResource]
set energy [new Resource/Energy]
$ResourceManager_ Register $energy
ResourceManager在ns—resouce-manager.tcl中定义的。Resource/NeighborResource在ns—neighbor—resource中对能量进行管理。
# Create a new agent and attach it to the node
if {$bs_node == 1} {
set agent [new Agent/BSAgent]
} else {
set agent [new Agent/RCAgent]
}
set rca_agent_ $agent
普通节点的应用为RCAgent,BS的应用为BSAGgent. 并将应用attch到node上。
下面两段看不明白,但是这两段不影响看程序。
set haslist [find_haslist [$self id]]
if {$bs_node == 1} {
set rca [new $opt(bsapp)]
} else {
set rca [new $opt(rcapp) $opt(mtype) $wantslist $haslist]
}
$ns_ attach—agent $self $agent
$rca attach-agent $agent
set rca_app_ $rca
将bs节点的应用设置为bsapp,普通节点的应用设置为rcaapp,并将节点的服务设置为不同的服务。bsapp在ns—app。tcl中。$opt(rcapp)定义在leach。tcl中,opt(mtype)定义在leach。tcl中。
set opt(rcapp) ”Application/LEACH" ;# Application type
set opt(ra_adv) [TxTime [expr $opt(hdr_size) + 4]]
;# Total time (s) for CH ADVs
;# Assume max 4(nn*%) CHs
set opt(ra_adv_total) [expr $opt(ra_adv)*($opt(num_clusters)*4 + 1)]
;# RA Time (s) for nodes' join reqs
set opt(ra_join) [expr 0。01 * $opt(nn_)]
;# Buffer time for join req xmittal
set opt(ra_delay) [TxTime [expr $opt(hdr_size) + 4]]
;# Maximum time required to transmit
;# a schedule (n nodes in 1 cluster)
set opt(xmit_sch) [expr 0。005 + [TxTime [expr $opt(nn_)*4+$opt(hdr_size)]]]
;# Overhead time for cluster set-up
set opt(start_xmit) [expr $opt(ra_adv_total) + $opt(ra_join) + $opt(xmit_sch)]
一般节点的应用为Application/LEACH,最终sink节点的应用为Application/BSApp。
通过前3次的分析得出,在分析1中定义变量,在分析2中创建leach节点,在分析3中将节点的应用绑定在节点上。
下面将分析leach的主要协议ns-leach.tcl脚本。
分析(四)
完成前面3个脚本的分析,最后进行ns—leach.tcl脚本的分析.首先我们看下这个脚本要使用的有哪些功能。
Application/LEACH instproc init args {} 对leach进行初始化,即构造函数。
下面是leach的一些方法
Application/LEACH instproc start {} {}
Application/LEACH instproc getRandomNumber {llim ulim} {} 得到随机数
Application/LEACH instproc node {} {}
Application/LEACH instproc nodeID {} {}
Application/LEACH instproc mac {} {}
Application/LEACH instproc getX {} {}
Application/LEACH instproc getY {} {}
Application/LEACH instproc getER {} {}
Application/LEACH instproc GoToSleep {} {} 节点进行休眠
Application/LEACH instproc WakeUp {} {}节点醒来
Application/LEACH instproc setCode code {}{}
Application/LEACH instproc checkAlive {} {} 节点是否存活
Application/LEACH instproc isClusterHead? {} {} 判断是否是簇头节点
Application/LEACH instproc hasbeenClusterHead? {} {} 判断是否成为过簇头节点
Application/LEACH instproc hasnotbeenClusterHead {} {}hasbeench=0不是簇头节点
Application/LEACH instproc setClusterHead {} {} 设置为簇头节点
Application/LEACH instproc unsetClusterHead {} {} 设置为非簇头节点
Application/LEACH instproc decideClusterHead {} {} 决定簇头节点,非常重要
Application/LEACH instproc advertiseClusterHead {} {} 广播簇头节点
Application/LEACH instproc findBestCluster {} {} 找到最佳簇
Application/LEACH instproc informClusterHead {} {} 通知簇头节点
Application/LEACH instproc createSchedule {} {} 创建TDMA调度
接收功能:
Application/LEACH instproc recv {args} {}
Application/LEACH instproc recvADV_CH {msg} {}
Application/LEACH instproc recvJOIN_REQ {nodeID} {}
Application/LEACH instproc recvADV_SCH {order} {}
Application/LEACH instproc recvDATA {msg} {}
发送功能:
Application/LEACH instproc sendData {} {}
Application/LEACH instproc send {mac_dst link_dst type msgdata_size dist code} {}
Application/LEACH instproc send_now {mac_dst link_dst type msg data_size dist code} {}
Application/LEACH instproc SendDataToBS {} {}
Application/LEACH instproc SendMyDataToBS {} {}
分析(五)
由leach 分析三可知,一般节点的应用为Application/LEACH。则现在就是如何选择簇头节点和设置门槛值.我们接下来分析leach 分析4中红色的方法。在leach 分析3中创建一个Application/LEACH对象则就会自动调用start方法。
Application/LEACH instproc start {} {
[$self mac] set node_num_ [$self nodeID]
$self decideClusterHead
$self checkAlive
}
在这个方法中会调用decideClusterHead和checkAlive方法。
Application/LEACH instproc GoToSleep {} {
global opt ns_
$self instvar begin_idle_ begin_sleep_
[[$self node] set netif_(0)] set sleep_ 1
# If node has been awake, remove idle energy (e.g。, the amount of energy
# dissipated while the node is in the idle state)。 Otherwise, the node
# has been asleep and must remove sleep energy (e.g。, the amount of
# energy dissipated while the node is in the sleep state).
if {$begin_idle_ 〉 $begin_sleep_} {
set idle_energy [expr $opt(Pidle) * [expr [$ns_ now] — $begin_idle_]]
[$self getER] remove $idle_energy
} else {
set sleep_energy [expr $opt(Psleep) * [expr [$ns_ now] - $begin_sleep_]]
[$self getER] remove $sleep_energy
}
set begin_sleep_ [$ns_ now]
set begin_idle_ 0
}
分析(六)
在start中调用下面这个方法.
Application/LEACH instproc decideClusterHead {} {
global ns_ chan opt node_
$self instvar alive_ TDMAschedule_
$self instvar begin_idle_ begin_sleep_
# Check the alive status of the node. If the node has run out of
# energy, it no longer functions in the network。
set ISalive [[[$self node] set netif_(0)] set alive_]
if {$alive_ == 1} {
if {$ISalive == 0} {
puts "Node [$self nodeID] is DEAD!!!!"
$chan removeif [[$self node] set netif_(0)]
set alive_ 0
set opt(nn_) [expr $opt(nn_) - 1]
set ISalive [[[$self node] set netif_(0)] set alive_] #从网络接口netif中查看当前节点状 况
如果节点存活,但是节点能量耗光,则$chan removeif [[$self node] set netif_(0)]将节点信道中移出,并将节点设置为死亡.节点的总数目减少一个.
if {$opt(eq_energy) == 1} {
#
# Pi(t) = k / (N — k mod(r,N/k))
# where k is the expected number of clusters per round
# N is the total number of sensor nodes in the network
# and r is the number of rounds that have already passed.
#
set nn $opt(nn_)
if {[expr $nn — $opt(num_clusters) * $round_] < 1} {
set thresh 1
} else {
set thresh [expr double($opt(num_clusters)) / \
[expr $nn - $opt(num_clusters) * $round_]]
# Whenever round_ is 0, all nodes are eligible to be cluster-head。
if {$round_ == 0} {
$self hasnotbeenClusterHead
}
}
# If node has been cluster—head in this group of rounds, it will not
# act as a cluster-head for this round.
if {[$self hasbeenClusterHead?]} {
set thresh 0
}
} else {
#
# Pi(t) = Ei(t) / Etotal(t) * k
# where k is the expected number of clusters per round,
# Ei(t) is the node’s current energy, and Etotal(t) is the total
# energy from all nodes in the network.
#
set Etotal 0
# Note! In a real network, would need a routing protocol to get this
# information. Alternatively, each node could estimate Etotal(t) from
# the energy of nodes in its cluster。
for {set id 0} {$id 〈 [expr $opt(nn)—1]} {incr id} {
set app [$node_($id) set rca_app_]
set E [[$app getER] query]
set Etotal [expr $Etotal + $E]
}
set E [[$self getER] query]
set thresh [expr double([expr $E * $opt(num_clusters)]) / $Etotal]
}
上面是对thresh的计算,当(N - k mod(r,N/k))〈1,则将thresh设置为1,否则节点thresh=k / (N — k mod(r,N/k)),每个节点在一个1/p中都要成为簇头节点一次。p=簇头节点占所有节点的比例,在r=0的时候每个节点都有机会吃呢更为簇头节点.如果节点成为过簇头节点则thresh=0,则这个节点在1/p轮后才可以成为簇头节点。
if {[$self getRandomNumber 0 1] 〈 $thresh} {
puts "$nodeID: *******************************************”
puts "$nodeID: Is a cluster head at time [$ns_ now]”
$self setClusterHead
set random_access [$self getRandomNumber 0 $opt(ra_adv)] #opt(ra_adv) in leach。tcl
$ns_ at [expr $now_ + $random_access] "$self advertiseClusterHead"
} else {
puts ”$nodeID: *******************************************"
$self unsetClusterHead
}
如果thresh〉getRandomNumber,则节点成为簇头节点。然后调用advertiseClusterHead方法。
set next_change_time_ [expr $now_ + $opt(ch_change)]
$ns_ at $next_change_time_ "$self decideClusterHead"
$ns_ at [expr $now_ + $opt(ra_adv_total)] ”$self findBestCluster"
当节点成为簇头节点,则节点调用 advertiseClusterHead方法。
set chID [$self nodeID]
set currentCH_ $chID
pp ”Cluster Head $currentCH_ broadcasting ADV at time [$ns_ now]"
set mac_dst $MAC_BROADCAST
set link_dst $LINK_BROADCAST set msg [list $currentCH_] set datasize [expr $BYTES_ID * [llength $msg]] # Send beacons opt(max_dist) meters so all nodes can hear。 $self send $mac_dst $link_dst $ADV_CH $msg $datasize $opt(max_dist) $code_
将该节点设置为簇头节点,设置当前节点所处的簇号。然后发送数据,广播该节点为簇头信息到全局网络。
在$ns_ at [expr $now_ + $opt(ra_adv_total)] "$self findBestCluster"调用findBestCluster方法。
分析(七)
当簇头发出了一个ADV类型的包时,其他的节点会接收这个包,并会将发送这个包的簇头的节点号按顺序先后记录在clusterChoices_中,还会计算每个簇头到接收节点的距离并记录在clusterDist_中。这样可以方便每个节点选簇的时候进行比较.具体的实现在ns-leach.tcl中的recvADV_CH函数中.
findBestCluster
if [$self isClusterHead?] {
# If node is CH, determine code and create a TDMA schedule。
set dist_ $opt(max_dist)
set currentCH_ $nodeID
set myADVnum_ [[$self mac] set myADVnum_]
# There are opt(spreading) - 1 codes available b/c need 1 code
# for communication with the base station.
set numCodesAvail [expr 2 * $opt(spreading) — 1]
set ClusterCode [expr int(fmod($myADVnum_, $numCodesAvail)) + 1]
$ns_ at [expr $now_ + $opt(ra_adv_total) + $opt(
展开阅读全文