www.pudn.com > 3.rar > application.cc, change:2004-03-23,size:2102b


//-------------------------------------------------------------------
//  file name: application.cpp
// 
//    - contains the implementation of application class
//
//-------------------------------------------------------------------


#include "application.h"


void application::initialize()
{
	// initialization for this node
	last_seen_id = -1;
	msgcount = 0;

	// node 0 periodically broadcasts messages in the network
	// self timer each 10 seconds
	if (ID==0)
	{
		cMessage *msg = new cMessage("selfmessage");
		msg->setKind(M_SELF);
		scheduleAt(10,msg);
	}
}


void application::finish()
{
	ev << "Node " << ID << " generated/forwarded: " << msgcount << " messages\n";
}


void application::handleMessage(cMessage *msg)
{
	switch(msg->kind())
	{
	case M_LOWHIGH:
		{
			if (strcmp(msg->name(),"FLOOD")==0)
			{
				// process the flood message
				processFlood(msg);

				return;
			}

			ev << "unknown message received from another node.\n";
			endSimulation();
		}

	case M_SELF:
		{
			// send a new message in the network
			cMessage *msgnew = new cMessage("FLOOD");
			msgnew->setKind(M_HIGHLOW);
			msgnew->addPar("flood_id") = ++last_seen_id;
			send(msgnew,"lowergate_out");
			
			// change the color
			UPDATECOLOR(msgcount+2);

			// update the message counter
			msgcount++;
			
			// set the timer again
			scheduleAt(simTime()+GENERATIONDELAY,msg);
			break;
		}

	default:
		ev << "unknown message received\n";
		endSimulation();
	}
}

void application::processFlood(cMessage *msg)
{
	// are we the source? 
	// (the source does not forward flood messages, it only generates them)
	if (ID==0)
	{
		delete msg;
		return;
	}


	// have we seen this message before?
	int flood_id = (int)msg->par("flood_id");
	if (flood_id <= last_seen_id)
	{
		// yes, discard this message
		delete msg;
		return;
	}
	
	// no, forward the message after small delay
	msg->setKind(M_HIGHLOW);
	sendDelayed(msg,RETRANSMITDELAY,"lowergate_out");

	// change the color
	UPDATECOLOR(flood_id+2);
	
	// update the message counter
	msgcount++;

	// update the last_seen_id
	last_seen_id = flood_id;
}