Skip to main content

Different self messages

We can of course define and use also different self messages, for example, to switch to blue or to switch to red. For this, we can use the attribute kind of messages. In our ongoing example, we will define the kind of the first message we created in the initialize() method with CHANGE_TO_RED, a constant we define in the node.h file:

In Node.h:

#define CHANGE_TO_BLUE 100
#define CHANGE_TO_RED 101

In initialize(), we would need to add the attribute to the message. Then, in handleMessage(), instead of using the state variable colorBlue (which we don't need anymore), we will check which type we receive and act accordingly. Every time we receive a RED message, we will schedule a BLUE one and vice versa:

void Node::initialize()
{
    // create a simple message and send it to ourselves at simulation time 10.
    cMessage *msg = new cMessage("changeColor");
    msg->setKind(CHANGE_TO_RED);
    scheduleAt(10, msg);
    timesChanged = 0;
}

void Node::handleMessage(cMessage *msg)
{
    if (timesChanged >= 10)
        delete msg;
    else {
        cDisplayString& dispStr = getDisplayString();
        // if the current color is blue, change to red, otherwise to blue.
        if (msg->getKind() == CHANGE_TO_RED) {
            dispStr.parse("p=100,100;b=60,10,rect,red,black,2");
            msg->setKind(CHANGE_TO_BLUE);
        }
        else if (msg->getKind() == CHANGE_TO_BLUE) {
            dispStr.parse("p=100,100;b=60,10,rect,blue,black,2");
            msg->setKind(CHANGE_TO_RED);
        }
        // update state variables
        timesChanged++;
        // issue the debugging output
        EV << "Changing the color at time " << simTime() << ", " << timesChanged << " times.\n";
        // re-schedule the self message
        scheduleAt(simTime()+10, msg);
    }
}

I am sure most of your got it by now, but let's stress it again. Note how all of the messages that we need to treat all land in the same handleMessages() function. Every time the kernel has a message for this node, it will call handleMessage with that message as a parameter. We need to check what it is (like opening a newly arrived letter) and decide what to do with it.