Creating and handling a self message
Creating and handling a self message
In the last section, we have explored the code of our simple module Node and have noticed some code lines, that look like creating a message. Let's revisit them:
#include "Node.h"
Define_Module(Node);
void Node::initialize()
{
// create a simple message and send it to ourselves at simulation time 10.
cMessage *msg = new cMessage("changeColorToRed");
scheduleAt(10, msg);
}
void Node::handleMessage(cMessage *msg)
{
// In this scenario, we can only receive one possible message - the one
// we created in initialize()
// when we receive it, simply change the color of the node from blue to red
cDisplayString& dispStr = getDisplayString();
dispStr.parse("p=100,100;b=60,10,rect,red,black,2");
delete msg;
}
We already know that the method initialize() is run before the simulation starts. Here, we simply create a single message to ourselves (a little bit like scheduling a tea timer) by instantiating a pointer to an object (msg) and giving it the name changeColorToRed. Note that this is the internal name of the message, not of the pointer!
Next, we schedule the message to fire at simulation time 10 (seconds) by passing it to the kernel's event queue by the function scheduleAt(). This function can only schedule self messages, as it does not take any destination as a parameter.
From now on, we should not make any changes to this message, as it is "gone" into the event queue of the kernel. The initialize() method is over and once all other nodes (we have only one...) are initialized, the simulation will start. We already know how discrete events work - we need at least one event in the queue so that the simulation continues running. In our case, we have exactly one, scheduled for time 10. Since it is only one, the simulation will jump directly there and send us the message back into the handleMessage() method of our Node module. All messages (self and others) end up here.
In handleMessage(), we expect only one type of message and we do not currently plan to send any more messages anywhere. Thus, we simply change the color of the node with that cryptic line of code marked above and delete the message. Again, you created the message, you must delete it too.
That's it, folks. Next: play!