YARP  2.3.68+272-20170522.1+git50f0ae7
Yet Another Robot Platform
The RFModule Class

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

Introduction

The RFModule helper class simplify writing a generic module. It provides support for:

  • Perform periodic activities
  • Handle signals, catch termination and perform smooth shutdown
  • Parses messages from a port to monitor module activity and set/get parameters
  • Use the ResourceFinder class to handle parameters

You do not need to understand the details of the ResourceFinder to proceed with this tutorial. However it may be useful: Resource Finder Tutorials.

This is how a module will look like:

#include <iostream>
#include <iomanip>
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;
}

Code

See code in: examples/rfmodule/main.cpp