Please see "example/ros" in the YARP source code for full examples.
For simple cases, we can just use YARP Bottles whose content matches ROS types structurally. For example, to call a ROS service that adds two integers, we could do this:
namespace {
}
int main(
int argc,
char* argv[])
{
if (argc != 3) {
yCError(CLIENT_V2,
"Call as %s X Y", argv[0]);
return 1;
}
Node node("/yarp_add_int_client");
RpcClient client;
if (!client.open("add_two_ints")) {
yCError(CLIENT_V2,
"Failed to open client");
return 1;
}
Bottle msg;
Bottle reply;
msg.addInt32(atoi(argv[1]));
msg.addInt32(atoi(argv[2]));
if (!client.write(msg, reply)) {
yCError(CLIENT_V2,
"Failed to call service");
return 1;
}
yCInfo(CLIENT_V2,
"Got %d\n", reply.get(0).asInt32());
return 0;
}
An example CMakeLists.txt file to compile this and link with YARP would be:
cmake_minimum_required(VERSION 3.12)
find_package(YARP COMPONENTS os REQUIRED)
add_executable(add_int_client_v1)
target_sources(add_int_client_v1 PRIVATE add_int_client_v1.cpp)
target_link_libraries(add_int_client_v1 PRIVATE YARP::YARP_os
YARP::YARP_init)
On the ROS side we'd do:
rosrun rospy_tutorials add_two_ints_server
Then on the YARP side we can try it out (assume the above program is compiled as 'add_int_client_v1'):
yarp: Port /yarp_add_int_client active at tcp://192.168.1.2:35731
yarp: Port /add_two_ints+1@/yarp_add_int_client active at tcp://192.168.1.2:35004
Got 10