Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ROS基本操作 #94

Open
imuncle opened this issue Nov 22, 2019 · 1 comment
Open

ROS基本操作 #94

imuncle opened this issue Nov 22, 2019 · 1 comment
Labels
ROS 向ROS发起请求

Comments

@imuncle
Copy link
Owner

imuncle commented Nov 22, 2019

新建功能包

mkdir src
cd src
catkin_create_pkg learning_communication std_msgs rospy roscpp
cd ../
catkin_make
source devel/setup.bash

创建Publisher

// ROS节点初始化
ros::init(argc, argv, "talker");

// 创建节点句柄
ros::NodeHandle n;

// 创建一个Publisher
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);

创建Subscriber

// 接收到订阅信号后,进入消息回调函数
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
    // 将接收到的消息打印出来
    ROS_INFO("I heard: [%s]", msg->data.c_str());
}

void main(int argc, char** argv)
{
    // 初始化ROS节点
    ros::init(argc, argv, "talker");
    
    // 创建节点句柄
    ros::NodeHandle n;
    
    // 创建一个Subscriber
    ros::Subscriber sub = n.subsricbe("chatter", 1000, chatterCallback);
    
    // 循环等待回调函数
    ros::spin();
    
    return 0;
}

自定义服务数据

新建.srv文件:

int64 a
int64 b
---
int64 sum

创建Server

// service回调函数,输入参数seq,输出参数res
bool add(learning_communication::AddTwoInts::Request &req, learning_communication::AddTwoInts::Response &res)
{
    // 将输入参数中的请求数据相加,结果放到应答变量中
    res.sum = req.a + req.b;
    return true;
}

int main(int argc, char **argv)
{
    // ROS节点初始化
    ros::init(argc, argv, "add_two_ints_server");
    
    // 创建节点句柄
    ros::NodeHandle n;
    
    // 创建一个名为add_two_ints的server,注册回调函数add()
    ros::ServiceServer server = n.advertiseService("add_two_ints", add);
    
    // 循环等待回调函数
    ros::spin();
    
    return 0;
}

创建Client

// 创建节点句柄
ros::NodeHandle n;

// 创建一个client,请求add_two_int service
// service消息类型是learning_communication::AddTwoInts
ros::ServiceClient = n.ServiceClient<learning_communication::AddTwoInts>("add_two_ints");

// 创建learning_communication::AddTwoInts类型的service消息
learning_communication::AddTwoInts srv;
srv.request.a = atoll(argv[1]);
srv.request.b = atoll(argv[2]);

// 发布service请求,等待加法运算的应答结果
if(client.call(srv))
{
    ROS_INFO("Sum: %d", srv.response.sum);
}
else
{
    ROS_ERROR("Failed to call service add_two_ints");
    return 1;
}

return 0;
@imuncle imuncle added the ROS 向ROS发起请求 label Nov 22, 2019
@imuncle
Copy link
Owner Author

imuncle commented Mar 2, 2020

只想编译工作空间某一个包:

$ catkin_make -DCATKIN_WHITELIST_PACKAGES="包名"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ROS 向ROS发起请求
Projects
None yet
Development

No branches or pull requests

1 participant