State variables
State variables are a very handy tool to track the internal state of a module: for example, to count how often we already changed the color (and then stop) or to track to which color to change (from red to blue and back).
To use a state variable, you need to define it first in the Node.h file, like this:
class Node : public cSimpleModule
{
protected:
virtual void initialize();
virtual void handleMessage(cMessage *msg);
private:
bool colorBlue;
int timesChanged;
};
Then, in the Node.cc file, you need to initialize both variables with some values, for example:
colorBlue = true;
timesChanged = 0;
This means that we started with a blue color for our node and we did not change it yet. In handleMessage, we need to check how often we already changed the color (if more than 10 - then stop) and to toggle the color itself, so that every time we change to the other color:
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, check whether we did not exceed the maximum number of changes (hard-coded to 10)
if (timesChanged > 10)
delete msg;
else {
cDisplayString& dispStr = getDisplayString();
// if the current color is blue, change to red, otherwise to blue.
if (colorBlue)
dispStr.parse("p=100,100;b=60,10,rect,red,black,2");
else
dispStr.parse("p=100,100;b=60,10,rect,blue,black,2");
// update state variables
colorBlue = !colorBlue;
timesChanged++;
// issue the debugging output
EV << "Changing the color at time " << simTime() << ", " << timesChanged << " times.\n";
// re-schedule the self message
scheduleAt(simTime()+10, msg);
}
}
Once the ten times have passed, we will not send any new self messages and the simulation will end automatically, because there will be no more events in the event queue.
Our simulation just became a little bit more useful and realistic - we change the color of the node ten times and then we stop. When you start the simulation, don't forget to go step-by-step, so that you see the toggling of the color.