⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 asyncnetlayer.cc.bak

📁 基于omnet++开发的Mf框架下的802.11协议仿真。
💻 BAK
字号:
/* -*- mode:c++ -*- ********************************************************
 * file:        AsyncNetwLayer.cc
 *
 * author:      Yupeng.hu
 *
 * copyright:   (C) 2006 HUNAN Universtiy, ChangSha China
 *
 ***************************************************************************
 * part of:     Async Simulation
 * description: - Async Description
 *
 ***************************************************************************
 * changelog:   $Revision$
 *              last modified:   $Date: 2006-7-7 10:21 $
 *              by:              $Author: Yupeng.hu $
 ***************************************************************************/
//#include <iostream.h>
//#include <fstream.h>
#include "AsyncNetLayer.h"
#include <NetwPkt_m.h>
#include <time.h>
#include <fstream>
#include <string>
#include <map>
#include <cmath>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>
using namespace std;
map<int,vector<int> >clus_map;
int head[100];
double distToCenter[100]={10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,
	                        10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,
	                        10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,
	                        10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,
											    10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,
											    10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,
											    10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,
											    10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,
											    10000,10000,10000,10000,10000,10000,10000,10000,10000,10000,
											    10000,10000,10000,10000,10000,10000,10000,10000,10000,10000};
#define EV (ev.disabled()||!debug) ? (std::ostream&)ev : ev << logName() << "::AsyncNetLayer: "

Define_Module(AsyncNetLayer);


/**
 * Reads all parameters from the ini file. If a parameter is not
 * specified in the ini file a default value will be set.
 **/
void AsyncNetLayer::initialize(int stage)
{
	BasicNetwLayer::initialize(stage);
  
	if(stage==0)
	{       	   	
    	status=NO_CLUSTER;
    	conStatus=NO_CONNECT;
    	r=par("round");  //簇的稳定的时间,一段时间后要重新生成簇头。
    	selectHeadEvent=new cMessage("selectHeadEvent");
    	creatClusterEvent=new cMessage("creatClusterEvent");
    	topo = new cTopology("topo");
      clusterHead=0;
    	WATCH(status);
    	WATCH(conStatus);
    	
    	bbPos = blackboard()->subscribe(this, "hostPos");
    	pos=static_cast<Coord*>(bbPos->data());
  
	    int numNode = (int)par("nodenum")+6;
	    int numCluster = (int)par("numCluster"); //get the number of clusters
	    if(findHost()->index()!=0 )
	    {
	    	  double gridL =static_cast<double> (par("gridLength"))/numCluster;
    		  double gridW =static_cast<double> (par("gridWidth"))/numCluster;
  			  int id=findHost()->index();
          clu_it=numCluster*(floor(pos.y/gridW))+(floor(pos.x/gridL)+1); //floor 向下取整
          clus_map[clu_it].push_back(id);
          double x = ((clu_it-1)%numCluster)*gridL+0.5*gridL;
          double y = ((clu_it-1)/numCluster)*gridW+0.5*gridW;
          if((pow(pos.x-x,2) + pow(pos.y-y,2)) < distToCenter[clu_it-1])  //离网格中心最近的节点做簇头
          { 
          	distToCenter[clu_it-1] = (pow(pos.x-x,2) + pow(pos.y-y,2));
          	head[clu_it-1] = (findHost()->index())*8+numNode;
          }
	    }
	    
      map<int,vector<int> >::const_iterator map_it=clus_map.begin();
      while(map_it!=clus_map.end())
	    {
	      //cout<<map_it->first<<":";
	      vector<int>::const_iterator vector_it=map_it->second.begin();
	      while(vector_it!=map_it->second.end())
		    {
		//     	cout<<*vector_it<<"  ";
		      ++vector_it;
		    }
	//      cout<<endl;
	      ++map_it;
    	}
      
    	EV <<"AsyncNetLayer is loaded"<<endl;
    	scheduleAt(simTime(), selectHeadEvent);
  }
}

/** 
 * Convienience function which calls sendDelayedDown with delay set to
 * 0.0.
 *
 * @sa sendDelayedDown
 **/
void AsyncNetLayer::handleUpperMsg(NetwPkt* msg)
{    
	  int id = findHost()->index();
    int numCluster = (int)par("numCluster"); //get the number of clusters
    //?
    
    /*if(find(clus_map[numCluster*(numCluster-1)+1].begin(),clus_map[numCluster*(numCluster-1)+1].end(),id) 
    	== clus_map[numCluster*(numCluster-1)+1].end())
    {
    	delete msg;
    	return ;
    }*/
    
    msg->setTimestamp();
    ev<<logName()<<"AsyncNetLayer::"<<"The timeStamp is"<<msg->timestamp()<<endl;
    delete topo;
    topo = new cTopology("topo");
    topo->extractByModuleType(findHost()->className(), NULL); 
    int dest=findHost()->submodule("appl")->par("destAddress");//topo->node 's index() is i 		  		
    topo->unweightedSingleShortestPathsTo(topo->node(dest));
    int  distance=topo->nodeFor(findHost())->distanceToTarget();
        
    ev << logName() << "::AsyncNetLayer:" <<" distance to sink node is: "<<distance<<endl;
    msg->setKind(distance);//put hops into packet
   
    Routing(msg);
    
}


/**
 * Redefine this function if you want to process messages from lower
 * layers before they are forwarded to upper layers
 *
 *
 * If you want to forward the message to upper layers please use
 * @ref sendUp which will take care of decapsulation and thelike
 **/
void AsyncNetLayer::handleLowerMsg(NetwPkt* msg) //变化了{
	//  std::cout<<"lower--"<<findHost()->index()<<":Src="<<msg->getSrcAddr()<<",Dest="<<msg->getDestAddr()<<endl;
	//  std::cout<<"myNetwAddr="<<myNetwAddr()<<endl;
	//  std::cout<<"clusterHead="<<clusterHead<<endl;
	  ev<<logName()<<"!!!!!!!!!!!!!!!!"<<endl;
    ev<<logName()<<"msg->getTag()="<<msg->getTag()<<endl;
    delete topo;
    topo = new cTopology("topo");
    topo->extractByModuleType(findHost()->className(), NULL); 
    int dest=findHost()->submodule("appl")->par("destAddress");//topo->node 's index() is i 		  		
    topo->unweightedSingleShortestPathsTo(topo->node(dest));
    int distance=topo->nodeFor(findHost())->distanceToTarget();
    //ev<<logName()<<"distance is "<<distance<<endl;
    

   	 // double t = simTime()-msg->timestamp();	
     // EV<<"pkt delay:"<<t<<"="<<simTime()<<"-"<<msg->timestamp()<<endl;
    //  delay[msg->kind()-1][0]+=t;
    //  delay[msg->kind()-1][1]+=1;
    //  ev<<"hop-"<<msg->kind()<<" delay:"<<delay[msg->kind()-1][0]<<"*****"<<delay[msg->kind()-1][1]<<endl;

    //  qstats.collect( t );
    
      
      	
     	 Routing(msg);
        
    
}


/** 
 * Convienience function which calls sendDelayedDown with delay set to
 * 0.0.
 *
 * @sa sendDelayedDown
 **/
void AsyncNetLayer::sendDown(NetwPkt *msg, int nHop, int nicGate)
{
	sendDelayedDown( msg, 0.0, nHop, nicGate );
}


/**
 * Call this function to hand your message to layer n-1
 *
 * It just calls the OMNeT++ sendDelayed function.
 *
 * In the case of the network layer we also have to provide a nextHop (nHop)
 * network address the msg has to be send to. nHop may be read
 * from a static table or the result of a routing query or whatever
 * else you want to implement.
 *
 * Additionally the network layer has to provide a mapping of the nHop
 * network address to the corresponding mac address (if the message is
 * no broadcast message). getMacAddr() is called to achive this task.
 *
 * The returned mac address is attached to the netwPkt within the
 * ControlInfo object MacControlInfo used to pass control information
 * from the network to the mac layer.
 * @todo update as soon as Andras updated the ControlInfo stuff in omnet
 * 
 * This function is only for convenience so that the programmer does
 * not have to take care about the details of message sending
 * 
 * @param msg msg to send
 * @param delay Delay (in seconds) to wait before sending the message
 * @param nHop next hop netw address to forward the msg to
 * @param nicGate gate of the nic to send the packet out on
 * @sa getMacAddr()
 *
 * to be called within @ref handleUpperMsg
 **/
void AsyncNetLayer::sendDelayedDown(NetwPkt* msg, double delay, int nHop, int nicGate)
{
	int macAddr;
  	/*if( nHop == -1 )
  	{
    	EV <<"sendDown: nHop=-1 -> message has to be broadcasted -> set destMac=-1\n";
    	macAddr=-2;
    }
    else if(nHop==-2)
    {
       EV <<"sendDown: nHop=-2 -> message has to sent to clusterHead -> set destMac="<<clusterHead<<endl;
	     macAddr=clusterHead;
    }
    **/
  //  else{
    	EV <<"sendDown: get the MAC address\n";//?
    	macAddr = getMacAddr( nHop );
//    	std::cout<<"getMacAddr( nHop )"<<getMacAddr( nHop )<<endl;
 // 	}
//    std::cout<<"dest="<<msg->getDestAddr()<<endl;
  	MacControlInfo* cInfo = new MacControlInfo;
  	cInfo->setNextHopMac( macAddr );
  	msg->setControlInfo( cInfo );
//  	std::cout<<"dest="<<msg->getDestAddr()<<endl;
  	EV <<"ControlInfo set; sending down msg\n";
  	sendDelayed((cMessage*) msg, delay, nicGate);
}


/** 
 * map the net module id to parent host's index
 * @param id to map
 **/
int AsyncNetLayer::NetModuleID2Index(int id)
{
  	int index=-1;
  	for (int i=0; i<topo->nodes(); i++)
  	{
  		if( topo->node(i)->module()->findSubmodule("net")==id)
    	{
    		index=topo->node(i)->module()->index();   			
   			return index;
    	}    		
  	}			
	  return index;	
}


/** 
 * find the next hop to all other nodes
 * @param topo the topology
 **/
void AsyncNetLayer::findNextHop(cTopology *topo)
{	
  	topo->extractByModuleType(parentModule()->className(), NULL); 	  	
  	cTopology::Node *thisNode = topo->nodeFor(parentModule());
  	for (int i=0; i<topo->nodes(); i++)
  	{
  		if (topo->node(i)==thisNode)
  			 continue; // skip ourselves
    	topo->unweightedSingleShortestPathsTo(topo->node(i));//find route to node(i) for this host	    	
    	if (thisNode->paths()==0) continue; // not connected		
    	
    	int address = topo->node(i)->module()->findSubmodule("net");
    	int nHop = thisNode->path(0)->remoteNode()->module()->findSubmodule("net");    	
  		rtable[address] = nHop;
   		EV << "  towards address " << NetModuleID2Index(address) << " next hop is: " << NetModuleID2Index(nHop) <<endl;
  	}	
}


/** 
 * handle all packets
 * @param msg msg to send
 **/
void AsyncNetLayer::Routing(NetwPkt* msg)
{  	    
  	
  	findNextHop(topo);
  	
  	int destAddr = msg->getDestAddr();    
  	if (destAddr == myNetwAddr())
  	{        
     	EV << "local delivery of packet--- " << endl;
     	sendUp(msg);
//     	std::cout<<"sendUp the msg"<<endl;
     	return;
  	}
  	
  	ShortestNetwLayerTable::iterator it = rtable.find(destAddr);
    if (it==rtable.end())
   	{
    	EV << "address " << NetModuleID2Index(destAddr) << " unreachable, discarding packet " <<msg->name()<< endl;
       	delete msg;
//      std::cout<<"delete the msg"<<endl;
       	return;
   	}
   	
    int nHop = (*it).second;
    EV<< "forwarding packet " << msg->name()<<" to next hop: " <<NetModuleID2Index(nHop) <<" to dest "<<NetModuleID2Index(destAddr)<< endl;
    sendDown(msg, nHop,lowergateOut);   
//    std::cout<<"sendDown the msg"<<endl;
      
        
    	
}
/**
 * 利用时钟调度,周期性的建立拓扑结构。 *(1)调用该函数,通过门限判断该节点是否能成为簇头: *(2)是,则生成一个簇头广播报; *(3)否,检查队列,是否有可通信邻居节点已经成为簇头: *(4)是,与该节点建立连接,将其作为数据报的目的节点; *(5)否,等待一段时间后,再进入步骤(1)。**/

void AsyncNetLayer::handleSelfMsg(cMessage* msg)
{
	if(msg==selectHeadEvent)
	{       
	
		status=NO_CLUSTER;
		conStatus=NO_CONNECT;
	//	double a=1.0*rand()/(RAND_MAX+1.0);
		//ev<<logName()<<"::AsyncNetLayer: "<<" a is "<<a<<endl;
		//if(a<(double)par("minLine")&&findHost()->index()!=(int)findHost()->submodule("appl")->par("destAddress"))//在ned文件中添加minLine变量
		
		
	//	if(a<(double)par("minLine")&&findHost()->index()!=(int)findHost()->submodule("appl")->par("destAddress"))
	//	{
			int numNode = (int)par("nodenum")+6;
			if(head[clu_it-1] == (findHost()->index())*8+numNode)  //confirm the grid has a clusterhead whether or not   2007-9-7
			{
				//head[clu_it-1] = (findHost()->index())*8+206;
				status=IS_CLUSTER;
				//std::cout<<"node "<<findHost()->index()<<" is the clusterHead"<<endl;
				findHost()->displayString().setTagArg("i",1, "red");								
		  }
	//	}
		
		scheduleAt(simTime()+1, creatClusterEvent);	
		
	}
	else if(msg==creatClusterEvent)
	{
			//std::cout<<"node "<<findHost()->index()<<" belong to grid:"<<clu_it;

			if(status==IS_CLUSTER)
				{
				 	clu = clus_map[clu_it];
				 	conStatus=IS_CONNECT;
				}
			else
				{
					if((clu_it%2)!=0)
					{
						findHost()->displayString().setTagArg("i",1, "green");
					}
				  else
					{
						findHost()->displayString().setTagArg("i",1, "yellow");
					}
					clusterHead=head[clu_it-1];	
					//std::cout<<",clusterHead="<<clusterHead<<endl;
					conStatus=IS_CONNECT;
					}	
			scheduleAt(simTime()+r, selectHeadEvent);
	}
	
}



void AsyncNetLayer::finish()
{    
  //  EV << " node ID: " << findHost()->index()<<endl;
  //  EV << " Total jobs processed: " << qstats.samples() << endl;    
  //  EV << " Max transmission:         " << qstats.max() << " sec" << endl;
  //  EV << " Min transmission:         " << qstats.min() << " sec" << endl;
  //  EV << " Avg transmission:         " << qstats.mean() << " sec" << endl;
  //  EV << " Standard deviation:   " << qstats.stddev() << " sec" << endl;
    
  //  if(findHost()->index()==0){
  //  	for(int i=0;i<maxHops;i++)
  //  	{   
  //  		mean[i]=(delay[i][0]/delay[i][1]);
   //  	 	EV<<mean[i]<<endl;
    	
   // 	} 
    
  //  }    
  //  recordScalar("node id",findHost()->index());
  //  recordScalar("avg trans time",qstats.mean());
  //  recordScalar("max trans time",qstats.max());
  //  recordScalar("min trans time",qstats.min());
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -