iCub-main
Loading...
Searching...
No Matches
The RFModule Class

In this tutorial we show more details of how to write an iCub module using the module helper class.

Introduction

In a previous tutorial we showed how to use the ResourceFinder to organize modules parameters in $YARP_DATA_HOME/contexts.

The RFModule helper class simplify writing an iCub module that uses the ResourceFinder class.

This is how a module will look like:

#include <iostream>
#include <iomanip>
#include <yarp/os/Network.h>
#include <yarp/os/RFModule.h>
using namespace std;
using namespace yarp::os;
class MyModule:public RFModule
{
Port handlerPort; // a port to handle messages
int count;
public:
double getPeriod()
{
/* module periodicity (seconds), called implicitly by the module. */
return 1.0;
}
/* This is our main function. Will be called periodically every getPeriod() seconds */
bool updateModule()
{
count++;
cout<<"["<<count<<"]"<< " updateModule... "<<endl;
return true;
}
/* Message handler. Just echo all received messages. */
bool respond(const Bottle& command, Bottle& reply)
{
cout<<"Got something, echo is on"<<endl;
if (command.get(0).asString()=="quit")
return false;
else
reply=command;
return true;
}
/* Configure function. Receive a previously initialized
resource finder object. Use it to configure your module.
If you are migrating from the old module, this is the function
equivalent to the "open" method. */
bool configure(yarp::os::ResourceFinder &rf)
{
count=0;
/* optional, attach a port to the module
so that messages received from the port are redirected
to the respond method */
handlerPort.open("/myModule");
attach(handlerPort);
return true;
}
// Interrupt function.
bool interruptModule()
{
cout<<"Interrupting your module, for port cleanup"<<endl;
return true;
}
/* Close function, to perform cleanup. */
bool close()
{
/* optional, close port explicitly */
cout<<"Calling close function\n";
handlerPort.close();
return true;
}
};

and this is the main function to instantiate it.

int main(int argc, char * argv[])
{
/* initialize yarp network */
Network yarp;
/* create your module */
MyModule module;
/* prepare and configure the resource finder */
ResourceFinder rf;
rf.configure(argc, argv);
rf.setVerbose(true);
cout << "Configuring and starting module. \n";
module.runModule(rf); // This calls configure(rf) and, upon success, the module execution begins with a call to updateModule()
cout<<"Main returning..."<<endl;
return 0;
}
int main()
Definition main.cpp:67
Copyright (C) 2008 RobotCub Consortium.

Code

See code in: src/module/tutorial_module.cpp