Creating a new command

Introduction

Command (dynamicgraph::command::Command) are objects that encapsulate an action to be performed on an entity.

In this page, we define a new command that will call method InvertedPendulum::incr. The source code is in src/command-increment.hh.

Implementation

We first define the new class by deriving dynamicgraph::command::Command:

    namespace dynamicgraph {
      namespace tutorial {
        namespace command {
          class Increment : public Command
          {

The constructor takes

  • a reference to a InvertedPendulum and calls parent class,
  • a vector a types specifying the number and types of input arguments of the command and
  • a string documenting the command. In this case, there is only one argument of type double. Note the use of boost::assign::list_of to build a vector in one command line:
      Increment(InvertedPendulum& entity, const std::string& docstring) :
        Command(entity, boost::assign::list_of(Value::DOUBLE), docstring)
      {
      }
    

We then define the action of the command in virtual method doExecute. We need to get a reference to the object on which the command will act. Note that we can straightfowardly statically cast in InvertedPendulum the Entity object returned by method owner:

    virtual Value doExecute() 
    {
      Entity& entity = owner();
      InvertedPendulum& ip = static_cast<InvertedPendulum&>(entity);

We then get the parameters as a vector of dynamicgraph::command::Value objects and cast them into the appropriate types specified at construction:

      std::vector<Value> values = getParameterValues();
      double timeStep = values[0].value();

Finally, we execute the action and return a value of the appropriate type, here the command return no value:

      ip.incr(timeStep);
      return Value();
    }