exampleCommModule.cpp
This is an example of how to use the CommModule class. More details about this example.
#include <CommModule.h>
#include <IPCommModule.h>
#include <TaskDict.h>
#include <CommonOptions.h>
using namespace MipResources;
using namespace MipTasks;
CommModule *commModule;
int myRobId;
int myTaskPlate;
int receivedPackets = 0;
void receiveCommPackets(){
CommBox entPackets;
commModule->receive(myTaskPlate, entPackets);
int size = entPackets.size();
for (int i=0; i<size; i++) {
CommPacket rP = *entPackets[i];
if (rP.sender().getIdsSize()<=0) {
cout << "MIP-warning: Message without sender received" << endl;
continue;
}
int otherId = rP.sender().getId(0);
if (otherId<0) {
cout << "MIP-warning: Message with invalid sender received: " << otherId << endl;
continue;
}
receivedPackets ++;
if (rP.messageType()=="MYPOSE") {
Serialization<Pose> srl(rP.message());
Pose otherPose = srl.getObj();
cout << receivedPackets << ". " << otherId << " MYPOSE " << otherPose.print() << ", " << rP.time().print() << endl;
}else if(rP.messageType()=="MYANGVEL"){
Serialization<Decimal> srl(rP.message());
Decimal otherAngVel = srl.getObj();
cout << receivedPackets << ". " << otherId << " MYANGVEL " << otherAngVel << ", " << rP.time().print() << endl;
}else{
cout << "MIP-warning: Message with unused type received: " << otherId << endl;
}
}
commModule->receiveAck(ENT_TASK, entPackets);
}
void sendCommPackets(){
CommNode sender(myRobId,myTaskPlate);
CommNode recipient;
if(myRobId==2) while(!recipient.addId(0)){};
if(myRobId==0) while(!recipient.addId(2)){};
while(!recipient.addTask(ENT_TASK)){};
while(!recipient.addTask(DRV_TASK)){};
Pose myPose(((Decimal)myRobId)+0.12,-78.45,Angle(0.33*M_PI));
Serialization<Pose> srlP(myPose);
CommPacket pP(srlP.getStr(),"MYPOSE",sender,recipient);
Decimal myAngVel(0.11);
Serialization<Decimal> srlA(myAngVel);
CommPacket pA(srlA.getStr(),"MYANGVEL",sender,recipient);
CommPacket pC(srlA.getStr(),"MYANGVEL",sender,recipient);
commModule->send(pP);
commModule->send(pA);
commModule->send(pC);
}
int main(int argc, const char* argv[]){
CommonOptions::init(argc,(char* const *)argv);
commonOptions->updateValues();
commModule = new IPCommModule(argc,argv);
commModule->requestBox(ENT_TASK);
commModule->requestBox(DRV_TASK);
myRobId = commonOptions->robotId->getValue();
cout << "[ROBOT ID " << myRobId << "]" << endl;
Timer timer;
while(1){
if(timer.get() > Time(1,0)){
myTaskPlate = ENT_TASK;
sendCommPackets();
timer.reset();
}
#ifdef EXAMPLE_CM_DEBUG
cout << "[COMMUNICATION MODULE STATUS]" << endl;
cout << commModule->print() << endl;
#endif
myTaskPlate = ENT_TASK;
receiveCommPackets();
#ifdef EXAMPLE_CM_DEBUG
cout << "[COMMUNICATION MODULE STATUS]" << endl;
cout << commModule->print() << endl;
#endif
myTaskPlate = DRV_TASK;
receiveCommPackets();
usleep(1000000);
}
}