參考
話題(topic)
釋出者(publisher)
#include <ros/ros.h>
#include "learning_topic/Person.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "person_publisher");
ros::NodeHandle n;
ros::Publisher person_info_pub = n.advertise<learning_topic::Person>("/person_info", 10);
ros::Rate loop_rate(1);
int count = 0;
while (ros::ok())
{
learning_topic::Person person_msg;
person_msg.name = "Tom";
person_msg.age = 18;
person_msg.sex = learning_topic::Person::male;
person_info_pub.publish(person_msg);
ROS_INFO("Publish Person Info: name:%s age:%d sex:%d",
person_msg.name.c_str(), person_msg.age, person_msg.sex);
loop_rate.sleep();
}
return 0;
}
訂閱者(subscriber)
#include <ros/ros.h>
#include "learning_topic/Person.h"
void personInfoCallback(const learning_topic::Person::ConstPtr& msg)
{
ROS_INFO("Subcribe Person Info: name:%s age:%d sex:%d",
msg->name.c_str(), msg->age, msg->sex);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "person_subscriber");
ros::NodeHandle n;
ros::Subscriber person_info_sub = n.subscribe("/person_info", 10, personInfoCallback);
ros::spin();
return 0;
}
服務(service)
服務端(server)
#include <ros/ros.h>
#include "learning_service/Person.h"
bool personCallback(learning_service::Person::Request &req,
learning_service::Person::Response &res)
{
ROS_INFO("Person: name:%s age:%d sex:%d", req.name.c_str(), req.age, req.sex);
res.result = "OK";
return true;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "person_server");
ros::NodeHandle n;
ros::ServiceServer person_service = n.advertiseService("/show_person", personCallback);
ROS_INFO("Ready to show person informtion.");
ros::spin();
return 0;
}
客戶端(client)
#include <ros/ros.h>
#include "learning_service/Person.h"
int main(int argc, char** argv)
{
ros::init(argc, argv, "person_client");
ros::NodeHandle node;
ros::service::waitForService("/show_person");
ros::ServiceClient person_client = node.serviceClient<learning_service::Person>("/show_person");
learning_service::Person srv;
srv.request.name = "Tom";
srv.request.age = 20;
srv.request.sex = learning_service::Person::Request::male;
ROS_INFO("Call service to show person[name:%s, age:%d, sex:%d]",
srv.request.name.c_str(), srv.request.age, srv.request.sex);
person_client.call(srv);
ROS_INFO("Show person result : %s", srv.response.result.c_str());
return 0;
};
動作(action)