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

📄 router.cc

📁 use swarm intelligence to simulate network routings in omnet
💻 CC
📖 第 1 页 / 共 2 页
字号:
					ln = 1;
				}
				double Pnd = getProb(destination, neighbor);
				double PndFinal = Pnd + qWeightFactor * ln;
				refineProb[neighbor] = PndFinal/probSum;
			}
*/		
			// Our way of Stochastic Selection
			double incrProb = 0.0;
			double binProb = uniform(0,1);
			int maxPort = -1;
			double bestProb = 0.0;
			for( J = (*neighborPortID).begin(); J != (*neighborPortID).end(); J++)
			{
				port = (*J).first;
				int neighbor = (*((*neighborPortID)[port])).second;

				if( port != enterPort )
				{
					// uncomment the refineProb if want to do the routing in the
					// di carros way.

					double Pnd = getProb(destination, neighbor);
//					double Pnd = refineProb[neighbor];

					if( Pnd >= bestProb)
					{
						bestProb = Pnd;
						maxPort = port;
					}

					incrProb += Pnd;

					if(binProb <= incrProb)
					{
						return port;
					}
				}
			}
			return maxPort;
		}
	}


	// In case we do not want to do probabilistic routing then 
	// we simply route the packet throught highest probabilistic route

	int maxPort = -1;
	double maxPnd = 0;
	
	for( J = (*neighborPortID).begin(); J != (*neighborPortID).end(); J++)
	{
		port = (*J).first;
		int neighbor = (*((*neighborPortID)[port])).second;
		double Pnd = getProb(destination, neighbor);

		if(Pnd >= maxPnd)
		{
			maxPnd = Pnd;
			maxPort = port;
		}
	}
	return maxPort;
}



void Router::processTransmitPacket(cMessage *msg)
{
	int port = msg->kind() - TRANSMIT_PACKET;

	queueManagementForMessage(msg,port);
}

double Router::estimateTimeToNextNode(int neighbor)
{
	int nextInputNode = findInputGateIDForNeighbor(neighbor);

	Buffer *sBuff = getBufferForThisPort(nextInputNode);
	int bitsInBuffer = sBuff->getNormalQueueCapacity() + sBuff->getQuickQueueCapacity();

	// To ensure that in case of zero queue delay the txdelay of the packet will be
	// the queue delay

	int queueLength = bitsInBuffer + (dataPacketLength * BYTE);

	double bandWidth = (*((*bandWidthPdelay)[nextInputNode])).first;
	double pDelay = (*((*bandWidthPdelay)[nextInputNode])).second;
	double qDelay = static_cast<double> ( queueLength/bandWidth );

	return (pDelay + qDelay); 
}

void Router::queueManagementForMessage(cMessage *msg, int port)
{
	Buffer *sBuff = getBufferForThisPort(port);

	if(msg == (*sendControlOrDataPacket)[port])
	{
		if( sBuff->empty() )
		{
			(*msgServiced)[port] = NULL;
		}
		else
		{
			(*msgServiced)[port] = sBuff->fetchNextPacketToSend();
			simtime_t txTime = transmitPacket((*msgServiced)[port], port);
			(*sendControlOrDataPacket)[port]->setKind( TRANSMIT_PACKET + port );
			scheduleAt(simTime() + txTime, (*sendControlOrDataPacket)[port]);

		}
	}
	else if( !(*msgServiced)[port] )
	{
		(*msgServiced)[port] = msg;
		simtime_t txTime = processMessageWhenQueueIsEmpty(msg, port);
		(*sendControlOrDataPacket)[port]->setKind( TRANSMIT_PACKET + port );
		scheduleAt(simTime() + txTime, (*sendControlOrDataPacket)[port]);

	}
	else
	{
		processMessageWhenQueueIsNotEmpty(msg,port);
	}
}

void Router::processMessageWhenQueueIsNotEmpty(cMessage * msg, int port)
{
	int kind = msg->kind();

#ifdef __FLYINGANTS
	if ( kind == NETLAYER_FORWARD_ANT || kind == NETLAYER_BACKWARD_ANT ||
#else
	if ( kind == NETLAYER_BACKWARD_ANT ||
#endif
		kind == NETLAYER_HELLO_PACKET || kind == NETLAYER_HELLO_REPLY_PACKET)
	{
		Buffer *sBuff = getBufferForThisPort(port);
		bool success = sBuff->enqueueInQuickQueue(msg);
#ifdef __FLYINGANTS
		if( (kind == NETLAYER_FORWARD_ANT || kind == NETLAYER_BACKWARD_ANT) && !success)
#else
		if( (kind == NETLAYER_BACKWARD_ANT) && !success)
#endif
		{
			sPtr->incrTotalAntsDeleted();
			delete msg;
		}

		else if ( !success )
		{
			delete msg;
		}
	}
#ifdef __FLYINGANTS
	else if ( kind == NETLAYER_DATA_PACKET)
#else
	else if ( kind == NETLAYER_FORWARD_ANT || kind == NETLAYER_DATA_PACKET)
#endif
	{
		Buffer *sBuff = getBufferForThisPort(port);
		bool success = sBuff->enqueueInNormalQueue(msg);
#ifdef __FLYINGANTS
		if( !success )
		{
			delete msg;
			sPtr->incrTotalBitsLost();
		}
#else
		if( kind == NETLAYER_FORWARD_ANT && !success )
		{
			delete msg;
			sPtr->incrTotalAntsDeleted();
		}
		else if( kind == NETLAYER_DATA_PACKET && !success)
		{
			delete msg;
			sPtr->incrTotalBitsLost();
		}
#endif
	}
	else
	{
		throw new cException("Unknown Message in processMessageWhenQueueIsNotEmpty() %d", kind);

	}
}

double Router::processMessageWhenQueueIsEmpty(cMessage * msg, int port)
{
	double txTime = transmitPacket(msg,port);
	return txTime;
}

double Router::transmitPacket(cMessage * msg, int port)
{
	int kind = msg->kind();
	int length = msg->length();
	int outPort = -1;

	simtime_t txTime = 0.000001;

	//Locat and output gate id from this input gate id

	map<int,pair<int,int>*>::const_iterator P = (*neighborPortID).find(port);
	

	if( P != (*neighborPortID).end())
	{
		pair<int,int>& thePair = *((*P).second);
		outPort = thePair.first;
	}

	else
	{
		throw new cException("Could not locate for %d port an output port", port);
	}


	//1. The Hello Packet has been generated to estimate the bandwidth
	// and Propagation Delay
	if( kind == NETLAYER_HELLO_PACKET)
	{
		helloPacket *hPacket = dynamic_cast<helloPacket*> (msg);
		simtime_t startTime = simTime();
		hPacket->setTxTime( startTime );
	
		send(hPacket, outPort);

		if ( gate(outPort)->toGate()->isBusy())
		{
			simtime_t endTime = gate(outPort)->toGate()->transmissionFinishes();

			txTime = endTime - startTime;

			//Estimate the bandwidth of the channel

			double bandWidth = static_cast<double> ( length / txTime );

			if(debug)
			{
				ev<<"Bandwidth is: " << bandWidth <<endl;
			}

			map<int,pair<double,double>*>::const_iterator I = (*bandWidthPdelay).find(port);

			if( I != (*bandWidthPdelay).end() )
			{
				(*((*bandWidthPdelay)[port])).first = bandWidth;
			}
			else
			{
				pair<double,double> *p = new pair<double,double>(bandWidth,0.0);

				(*bandWidthPdelay)[port] = p;
			}

		}
		else
		{
			send(msg,outPort);
		}

	}
	else
	{
		if( kind == NETLAYER_HELLO_REPLY_PACKET)
		{
			simtime_t inTime = msg->timestamp();
			simtime_t qTime = simTime() - inTime;
			helloPacket *hPacket = dynamic_cast<helloPacket*>(msg);
			hPacket->setQDelayAtNeighbor(qTime);
		}
		else if( kind == NETLAYER_DATA_PACKET)
		{
			simtime_t qTime = simTime() - msg->timestamp();
			sPtr->insertQueueDelay( qTime );
		}
		else if( kind == NETLAYER_FORWARD_ANT || kind == NETLAYER_BACKWARD_ANT)
		{
			Ant *ant = dynamic_cast<Ant*>(msg);
			ant->setSourceModule((int) ROUTER);
			if(simTime() >= converganceTime)
			{
				sPtr->incrTotalAntBits( ant->forwardAntSize() );
			}
		}

		send(msg,outPort);
	}
	double bandWidth = (*((*bandWidthPdelay)[port])).first;
	txTime = static_cast<double> ( length/bandWidth );
	return txTime;
}

Buffer* Router::getBufferForThisPort(int port)
{
	map<int,Buffer*>::const_iterator I = (*qBuffer).find(port);

	if( I != (*qBuffer).end() )
	{
		return (*I).second;
	}
	else
	{
		return NULL;
	}
}

void Router::buildGateIDToNeighborMap()
{
	cGate *outTempGate = gate("out");
	int vectorSize = outTempGate->size();

	for(int i=0; i<vectorSize; i++)
	{
		cGate *outRouterGate = gate("out", i); //access each gate of router
		int gateIDtoNode = outRouterGate->id();
		if(outRouterGate->isConnected())
		{
			
			//get the gate of networkNode to which this gate is connected

			cGate *networkNodeGate = outRouterGate->toGate();
			
			// get the address of the neighbor and then build the map

			if(networkNodeGate->isConnected())
			{
				cModule *neighborNetworkNode = networkNodeGate->toGate()->ownerModule();
				int neighborAddress = neighborNetworkNode->par("address");

				if(debug)
				{
					ev << "Neighbor: " << neighborAddress << "connected to: "<< 
						IPAddress << "at Port: " << gateIDtoNode<<endl;
				}

				int gateIDfromNode = findInputGateIDForNeighbor(neighborAddress);

				pair<int,int> *p = new pair<int,int>(gateIDtoNode,neighborAddress);
				
				(*neighborPortID)[gateIDfromNode] = p; //this is gateID
			}
		}
	}
}

int Router::findInputGateIDForNeighbor(int node)
{
	cGate *inTempGate = gate("in");
	int vectorSize = inTempGate->size();

	for(int i=0; i<vectorSize; i++)
	{
		cGate *inRouterGate = gate("in", i); //access each gate of router
		int gateIDfromNode = inRouterGate->id();
		if(inRouterGate->isConnected())
		{
			
			//get the gate of networkNode to which this gate is connected

			cGate *networkNodeGate = inRouterGate->fromGate();
			
			// get the address of the neighbor and then build the map

			if(networkNodeGate->isConnected())
			{
				cModule *neighborNetworkNode = networkNodeGate->fromGate()->ownerModule();
				int neighborAddress = neighborNetworkNode->par("address");

				if(node == neighborAddress)
				{
					if(debug)
					{
						ev << "Neighbor: " << neighborAddress << "connected to: "<< 
							IPAddress << "at Port: " << gateIDfromNode <<endl;
					}
					return gateIDfromNode;
				}

			}
		}
	}
	throw new cException("Could not locate gate to router %d from %d in findInputGateForNeighbor",
	node, IPAddress);
}


void Router::clearAllBuffersOfRouter()
{
	map<int,Buffer*>::const_iterator I;

	for( I = (*qBuffer).begin(); I != (*qBuffer).end(); I++)
	{
		Buffer *sBuff = (*I).second;
		int bCount = 0, dCount = 0;
		sBuff->clear(bCount,dCount);
		sPtr->incrPacketInQueue( dCount );
		(*msgServiced)[(*I).first] = NULL;
	}
}

void Router::findSourceForAnt(Ant *msg)
{
	int source = msg->getSourceModule();

	if( source == ANT_NEST)
	{
		tcb.source = ANT_NEST;
	}

	else if (source == ROUTER)
	{
		tcb.source = ROUTER;
	}
}

int Router::getNumNeighbors() 
{ 
	return numNeighbors; 
}

double Router::getProb(int destination, int neighbor) 
{ 
	int port = findInputGateIDForNeighbor(neighbor);
	return rTable->getDestViaThisNeighborProb(destination, port);
}

void Router::setProb(int destination, int neighbor, double prob) 
{
	int port = findInputGateIDForNeighbor(neighbor);
	rTable->setDestViaThisNeighborProb(destination, port, prob);
}

int Router::getNumNodes()
{
	return numNodes;
}

int Router::getMyAddress()
{
	return IPAddress;
}

// This function has now become redundant as the queueLength function
// does the same thing, however, we are keeping it to make sure that
// it remains backward compatible with the function in AntNest:)

double Router::bitsInQueue(int neighbor)
{
	int nextInputNode = findInputGateIDForNeighbor(neighbor);
	Buffer *sBuff = getBufferForThisPort(nextInputNode);
	int bitsInBuffer = sBuff->getNormalQueueCapacity() + sBuff->getQuickQueueCapacity();
	return bitsInBuffer;
}

int Router::queueLength(int neighbor)
{
	int nextInputNode = findInputGateIDForNeighbor(neighbor);

	Buffer *sBuff = getBufferForThisPort(nextInputNode);
	int bitsInBuffer = sBuff->getNormalQueueCapacity() + sBuff->getQuickQueueCapacity();
	return bitsInBuffer;

}

int Router::totalQueueLength()
{
	int totalQ = 0;

	map<int,Buffer*>::const_iterator I;
	for( I = (*qBuffer).begin(); I != (*qBuffer).end(); I++)
	{
		Buffer *sBuff = (*I).second;
		totalQ += sBuff->getNormalQueueCapacity() + sBuff->getQuickQueueCapacity();
	}
	return totalQ;
}


int Router::getQueueMaxLen()
{
	return queueSize;
}

double Router::getBandwidth(int neighbor)
{
	int enterPort = findInputGateIDForNeighbor(neighbor);
	double bandWidth = (*((*bandWidthPdelay)[enterPort])).first;
	return bandWidth;
}

void Router::initAntRoutingTable(double initial)
{
	map<int,pair<int,int>*>::const_iterator I;

	for(int i = 0; i < numNodes; i++)
	{
		if( i != IPAddress)
		{
			for(I = (*neighborPortID).begin(); I != (*neighborPortID).end() ; I++)
			{
				int port = (*I).first;
				rTable->setDestViaThisNeighborProb(i, port, initial);
			}
		}
	}
}

int Router::findNeighborAtIndex(int index)
{
	if( index < numNeighbors)
	{
		return neighborAtIndex[index];
	}
	else
	{
		throw new cException("Index %d in Router %d is out of bound", index, IPAddress);
	}
}

int Router::findIndexForNeighbor(int neighbor)
{
	for(int i = 0; i < numNeighbors ; i++)
	{
		if( neighborAtIndex[i] == neighbor)
		{
			return i;			
		}
	}
	throw new cException("Router %d Index not found for Neighbor %d ", IPAddress, neighbor);
}


void Router::finish()
{
	ev << "Module: " << fullPath() << endl;

	map<int,Buffer*>::const_iterator I;

	for( I = (*qBuffer).begin(); I != (*qBuffer).end(); I++)
	{
		Buffer *sBuff = (*I).second;
		int bCount = 0, dCount = 0;
		sBuff->clear(bCount,dCount);
		sPtr->incrPacketInQueue( dCount );
	}

	sPtr->incrEntriesInRoutingTable( numNodes * numNeighbors);

	map<int,pair<int,int>*>::const_iterator J;

	for( J = (*neighborPortID).begin(); J != (*neighborPortID).end(); J++)
	{
		int port = (*J).first;
		double bandWidth = (*((*bandWidthPdelay)[port])).first;
		sPtr->incrTotalBandWidthInNetwork( bandWidth );
	}
}

⌨️ 快捷键说明

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