【ACCESS精品源码栏目提醒】:网学会员,鉴于大家对ACCESS精品源码十分关注,论文会员在此为大家搜集整理了“WSN中LEACH协议源码分析 - 网络与通信”一文,供大家参考学习!
WSN 中 LEACH 协议
源码分析 分析(一)首先对 wireless.tcl 进行分析,先对默认的脚本选项进行初始化:set optchanChannel/WirelessChannelset optprop Propagation/TwoRayGroundset optnetifPhy/WirelessPhyset optmac Mac/802_11set optifq Queue/DropTail/PriQueueset optll LLset optant Antenna/OmniAntennaset optx 0 X dimension of the topographyset opty 0 Y dimension of the topographyset optcp quotquotset optsc quot../mobility/scene/scen-670x670-50-600-20-2quot scenario fileset optifqlen 50 max packet in ifset optnn 51 number of nodesset optseed 0.0set optstop 10.0 simulation timeset opttr out.tr trace file set opt rp dsdv o cript r uting protocol s set opt lm quotonquot o l g movement在这个 wireless.tcl 中设置了一些全局变量: Initialize Global Variablesset ns_ new Simulatorset c han new optchan oset pr p new o ptprop oset t po new Topographyset tracefd open opttr wtopo load_flatgrid optx optyprop topography topo这些初始化将在后面的使用中用到,该文件最重要的是创建 leach 节点:创建方法如下: elseif string compare optrp quotleachquot 0 for set i 0 i lt optnn incr i leach-create-mobile-node i 如果路由协议是 leach 协议,则在 Uamps.tcl 中调用 leach-create-mobile-node 方法创建leach 节点。
将在第二小节讲如何创建 leach 节点。
for set i 0 i lt optnn incr i ns_ at optstop.000000001 quotnode_i resetquot //完成后,重置节点的应用ns_ at optstop.00000001 quotputs quotNS EXITING...quot ns_ haltquotif optsc quotquot puts quot NOTE: no scenario file specified.quot set optsc quotnonequot else puts quotLoading scenario file...quotsource optscputs quotLoad complete...quotns 在什么时候结束 simulation,并告诉 ns 加载 sc 场景文件。
最后ns_ run 则 ns 就开始运行了。
分析(二) 上节对 wireless.tcl 进行了简要的分析,接下来对 Uamps.tcl 脚本进行分析。
eset opt Efriss_amp expr xpr 1.1 optRXThresh 16 PI PI / expr optbw optGt optGr l l Etwo_ray_amp RXThresh / Rb Gt Gr ht2 hr2set optEtwo_ray_amp expr 1.1 optRXThresh / expr optbw optGt optGr optht optht optht optht set opt EXcvr 50e-9 E a nergy for r dio circuitry set opt e_bf 5e-9 Beamforming e J nergy /bitset optEsense 0 Sensing e J nergy /bitset optthresh_energy 0.00 o Threshold f r pow a er daptation set opt Pidle 0 er W Idle pow set opt Psleep 0 S leep power Wset initialized 0set rng_ new RNG用于产生随机数 首先往 opt 数组里面添加一些变量, 并对这些变量进行初化。
optPsleep ,optPidle,optthresh_energy在 ns-leach.tcl 中使用到,这个是计算单位时间空闲所消耗的能量和休眠所消耗的能量。
这个脚本主要是创建 leach 节点:if initialized 0 remove old trace sens_init set initialized 1 Remove old trace files. catch quoteval exec rm glob -nocomplain optdirname/TDMAschedule..txtquot catch quotexec rm optdirname/optfilename.energyquot catch quotexec rm optdirname/optfilename.dataquot catch quotexec rm optdirname/optfilename.alivequot catch quotexec rm optdirname/startup.energyquot catch quotexec rm optdirname/init.energyquot 如果没有初始化过,则将以前的跟踪文件删除,接着回到创建 leach 的函数中,创建节点:if id optnn_ puts -nonewline quotid quot important set node_id new MobileNode/ResourceAwareNode else puts quotoptnn_ BSquot set node_id new MobileNode/ResourceAwareNode BS_NODE 如果不是簇头节点则将optnn_-1 个节点设置为一般节点, 将optnn_设置为 BS 节点。
newMobileNode/ResourceAwareNode 函数是在 ns-ranode.tcl 中。
分析完这个我们接下来分析newMobileNode/ResourceAwareNode 这个函数。
set node node_id if id optnn_ Set initial node energy. if opteq_energy 1 node set-energy optinit_energy optthresh_energy else 由于 eq-energy 在 leach-test 中给定,将 eq-energy1;则每个节点都会对能量进行初始化,设置节点的初始能量和门槛能量(个人理解,死亡能量) 。
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 optthresh_energy set initf open quotoptdirname/init.energyquot a puts initf quotidtEquot close initf将不属于 list 中的能量初始化能量设置为 2,将属于 list 中的能量设置为 200.并将初始化能量写到 init.energy 中,将节点 id 和节点初始能量写进去。
else Base station has an infinite amount of energy. node set-energy 50000 optthresh_energy 节点为簇头节点,则将节点的初始化能量设置为 50000,能量无限。
到此为止, 创建节点完成并将每个节点的能量初始化完成。
下一节将分析 ns-ranode.tcl 脚本。
区分普通节点和簇头节点的不同。
接下来是配置节点信道和跟踪文件:ns_ at 0.0 quotnode_id start-appquot ns 在 0 的时候启动应用,应用在 ns-ranode.tcl 中分析。
分析(三) 对前面两个脚本进行分析后,已经创建好节点和设置好节点的初始能量,将 optnn_-1个节点设置为普通节点,而将 optnn_设置为 bs。
现在对 ns-ranode.tcl 进行分析。
好了我们现在就开始分析这个脚本。
Class MobileNode/ResourceAwareNode -superclass Node/MobileNodeMobileNode/ResourceAwareNode instproc init argsset bs_node lindex args 0 eval self next lreplace args 0 0args 由参数传递进来,若节点为簇头节点则 bs_node1,调用父类初始化函数。
set ResourceManager_ new ResourceManager ResourceManager_ Register new Resource/NeighborResource set energy new Resource/Energy ResourceManager_ Register energyResourceManager 在 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 optbsapp else set rca new optrcapp optmtype wantslist haslist ns_ attach-agent self agent rca attach-agent agent set rca_app_ rca 将 bs 节点的应用设置为 bsapp,普通节点的应用设置为 rcaapp,并将节点的服务设置为不同的服务。
bsapp 在 ns-app.tcl 中。
optrcapp定义在 leach.tcl 中, optmtype定义在 leach.tcl中。
set opt rcapp quotApplication/LEACHquot y Application t pe set opt ra_adv TxTime expr opthdr_size 4 Total time s for CH ADVs Assume max 4nn CHsset optra_adv_total expr optra_advoptnum_clusters4 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 e TxTime xpr opt hdr_size 4 Maximum time required to transmit a schedule n nodes in 1 clusterset optxmit_sch expr 0.005 TxTime expr optnn_4opthdr_size Overhead time for cluster set-upset optstart_xmit expr optra_adv_total optra_join optxmit_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 hasbeench0 不是簇头节点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_ gt begin_sleep_ set idle_energy expr optPidle expr ns_ now - begin_idle_ self getER remove idle_energy else set sleep_energy expr optPsleep 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 quotNode self nodeID is DEADquot chan removeif self node set netif_0 set alive_ 0 set optnn_ expr optnn_ - 1 set ISalive self node set netif_0 set alive_ 从网络接口 netif 中查看当前节点状 况 如果节点存活,但是节点能量耗光,则chan removeif self node set netif_0将节点信道中移出,并将节点设置为死亡。
节点的总数目减少一个。
if opteq_energy 1 Pit k / N - k modrN/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 optnn_ if expr nn - optnum_clusters round_ lt 1 set thresh 1 else set thresh expr doubleoptnum_clusters / expr nn - optnum_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 Pit Eit / Etotalt k where k is the expected number of clusters per round Eit is the nodes current energy and Etotalt 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 Etotalt from the energy of nodes in its cluster. for set id 0 id lt expr optnn-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 doubleexpr E optnum_clusters / Etotal 上面是对 thresh 的计算, 当N - k modrN/klt1, 则将 thresh 设置为 1,否则节点 threshk / N- k modrN/k, 每个节点在一个 1/p 中都要成为簇头节点一次。
p簇头节点占所有节点的比例,在 r0 的时候每个节点都有机会吃呢更为簇头节点。
如果节点成为过簇头节点则thresh0,则这个节点在 1/p 轮后才可以成为簇头节点。
if self getRandomNumber 0 1 lt thresh puts quotnodeID: quot puts quotnodeID: Is a cluster head at time ns_ nowquot self setClusterHead set random_
access self getRandomNumber 0 optra_adv optra_adv in leach.tcl ns_ at expr now_ random_
access quotself advertiseClusterHeadquot else puts quotnodeID: quot self unsetClusterHead 如果 threshgtgetRandomNumber,则节点成为簇头节点。
然后调用 advertiseClusterHead 方法。
set next_change_time_ expr now_ optch_change ns_ at next_change_time_ quotself decideClusterHeadquot ns_ at expr now_ optra_adv_total quotself findBestClusterquot当节点成为簇头节点,则节点调用 advertiseClusterHead 方法。
set chID self nodeID set currentCH_ chID pp quotCluster Head currentCH_ broadcasting ADV at time ns_ nowquot set mac_dst MAC_BROADCAST set link_dst LINK_BROADCAST set msg list currentCH_ set datasize exprBYTES_ID llength msg .