Search code examples
c++omnet++veins

If the application has two services to send data messages, How will the messages be casted in onWSM function to obtain message content?


I tried to cast two messages in the onWSM function, one of the message is the accident message from TraCIDemo11p example see link; https://github.com/sommer/veins/blob/master/src/veins/modules/application/traci/TraCIDemo11p.cc and the other message I created myself.Simulation stops when handling of the accident message begins.

void MyClusterApp::onWSM(BaseFrame1609_4* frame)
{
    // Your application has received a data message from another car or RSU
    // code for handling the message goes here, see TraciDemo11p.cc for examples


   joinMessage* wsm = check_and_cast<joinMessage*>(frame);

            if (currentSubscribedServiceId == 7)
                    {

            if(wsm->getRecipientAddress() == myId)
        {

            mClusterMembers.insert(wsm->getSenderId());

        }
}
}

void MyClusterApp::onWSM_B(BaseFrame1609_4* frame)
{
    accident* wsm = check_and_cast<accident*>(frame);


if (currentSubscribedServiceId == 8)
                    {

    findHost()->getDisplayString().setTagArg("i", 1, "green");

    if (mobility->getRoadId()[0] != ':') traciVehicle->changeRoute(wsm->getDemoData(), 9999);
    if (!sentMessage) {
        sentMessage = true;

wsm->setSenderAddress(myId);
            wsm->setSerial(3);
for( NodeIdSetIterator it = mClusterMembers.begin(); it != mClusterMembers.end(); it++)
                   {
               wsm->setRecipientAddress((*it));
scheduleAt(simTime() + 2 + uniform(0.01, 0.2), wsm->dup());
                   }


    }
}
}

A runtime error occurred:

check_and_cast(): Cannot cast (veins::accident*) to type 'veins::joinMessage *' -- in module (veins::MyClusterApp) VANETScenario.node[1].appl (id=15), at t=74.797089255834s, event #711255

Launch a debugger with the following command?

nemiver --attach=4377 &


Solution

  • It seems that MyClusterApp::onWSM() may handle various types of messages. Therefore, I suggest use dynamic_cast to recognize the type of message - it is safe and returns nullptr when a message cannot be cast.

    An example of modification:

    void MyClusterApp::onWSM(BaseFrame1609_4* frame) {
       joinMessage* wsm = dynamic_cast<joinMessage*>(frame);
       if (wsm) {
           if (currentSubscribedServiceId == 7) {
               if(wsm->getRecipientAddress() == myId) {
                  mClusterMembers.insert(wsm->getSenderId());
               }
           }
       } else {
         // frame is not a pointer to joinMessage
       }
    }