ROS通信模式编程

一,ROS通信编程-----话题编程
1、建立工作区的,命令如下:
打开ubuntu16.04的终端,依次输入以下3个命令创建我们的工作区
1)、创建名为ros的工作区

mkdir -p ~/ros/src

2)、进入创建工作区的src文件夹

cd ~/ros/src

3)、生成工作区

catkin_init_workspace

2、这时候工作区是空的,但是我们依然可以进行编译
1)、进入工作区

cd ~/ros/

2)、编译

catkin_make

3、接下来把工作区在bash中注册
1)、bash注册

source devel/setup.bash

2)、验证是否已经在bash中注册可以使用如下命令:

echo $ROS_PACKAGE_PATH

创建一个ROS工程包
1、切换到我们的工作区

cd ~/ros/src

2、使用catkin_create_pkg命令去创建一个叫comm(通信)的包,这个包依靠std_msgs、roscpp、rospy。

catkin_create_pkg comm std_msgs rospy roscpp

接下来在工作区编译这个工程包。
1)、进入工作区

cd ~/ros

2)、编译

catkin_make

经过以上步骤,我们的ROS工程包就建立好了

首先我们要把目录切换到我们的comm工程包中

cd ~/ros/src/comm

进入src子目录

cd src

创建一个名为talker.cpp文件

touch talker.cpp

打开talker.cpp,并且将里面的内容替换为如下:

#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
int main(int argc, char **argv)
{
  /**
   * The ros::init() function needs to see argc and argv so that it can perform
   * any ROS arguments and name remapping that were provided at the command line. For programmatic
   * remappings you can use a different version of init() which takes remappings
   * directly, but for most command-line programs, passing argc and argv is the easiest
   * way to do it.  The third argument to init() is the name of the node.
   *
   * You must call one of the versions of ros::init() before using any other
   * part of the ROS system.
   */
  ros::init(argc, argv, "talker");
 
  /**
   * NodeHandle is the main access point to communications with the ROS system.
   * The first NodeHandle constructed will fully initialize this node, and the last
   * NodeHandle destructed will close down the node.
   */
  ros::NodeHandle n;
 
  /**
   * The advertise() function is how you tell ROS that you want to
   * publish on a given topic name. This invokes a call to the ROS
   * master node, which keeps a registry of who is publishing and who
   * is subscribing. After this advertise() call is made, the master
   * node will notify anyone who is trying to subscribe to this topic name,
   * and they will in turn negotiate a peer-to-peer connection with this
   * node.  advertise() returns a Publisher object which allows you to
   * publish messages on that topic through a call to publish().  Once
   * all copies of the returned Publisher object are destroyed, the topic
   * will be automatically unadvertised.
   *
   * The second parameter to advertise() is the size of the message queue
   * used for publishing messages.  If messages are published more quickly
   * than we can send them, the number here specifies how many messages to
   * buffer up before throwing some away.
   */
  ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
 
  ros::Rate loop_rate(10);
 
  /**
   * A count of how many messages we have sent. This is used to create
   * a unique string for each message.
   */
  int count = 0;
  while (ros::ok())
  {
    /**
     * This is a message object. You stuff it with data, and then publish it.
     */
    std_msgs::String msg;
 
    std::stringstream ss;
    ss << "hello world " << count;
    msg.data = ss.str();
 
    ROS_INFO("%s", msg.data.c_str());
 
    /**
     * The publish() function is how you send messages. The parameter
     * is the message object. The type of this object must agree with the type
     * given as a template parameter to the advertise<>() call, as was done
     * in the constructor above.
     */
    chatter_pub.publish(msg);
 
    ros::spinOnce();
 
    loop_rate.sleep();
    ++count;
  }
  return 0;
}

创建一个名为listener.cpp文件

touch listener.cpp

打开listener.cpp,并且将里面的内容替换为如下:

#include "ros/ros.h"
#include "std_msgs/String.h"
 
/**
 * This tutorial demonstrates simple receipt of messages over the ROS system.
 */
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
  ROS_INFO("I heard: [%s]", msg->data.c_str());
}
 
int main(int argc, char **argv)
{
  /**
   * The ros::init() function needs to see argc and argv so that it can perform
   * any ROS arguments and name remapping that were provided at the command line. For programmatic
   * remappings you can use a different version of init() which takes remappings
   * directly, but for most command-line programs, passing argc and argv is the easiest
   * way to do it.  The third argument to init() is the name of the node.
   *
   * You must call one of the versions of ros::init() before using any other
   * part of the ROS system.
   */
  ros::init(argc, argv, "listener");
 
  /**
   * NodeHandle is the main access point to communications with the ROS system.
   * The first NodeHandle constructed will fully initialize this node, and the last
   * NodeHandle destructed will close down the node.
   */
  ros::NodeHandle n;
 
  /**
   * The subscribe() call is how you tell ROS that you want to receive messages
   * on a given topic.  This invokes a call to the ROS
   * master node, which keeps a registry of who is publishing and who
   * is subscribing.  Messages are passed to a callback function, here
   * called chatterCallback.  subscribe() returns a Subscriber object that you
   * must hold on to until you want to unsubscribe.  When all copies of the Subscriber
   * object go out of scope, this callback will automatically be unsubscribed from
   * this topic.
   *
   * The second parameter to the subscribe() function is the size of the message
   * queue.  If messages are arriving faster than they are being processed, this
   * is the number of messages that will be buffered up before beginning to throw
   * away the oldest ones.
   */
  ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
 
  /**
   * ros::spin() will enter a loop, pumping callbacks.  With this version, all
   * callbacks will be called from within this thread (the main one).  ros::spin()
   * will exit when Ctrl-C is pressed, or the node is shutdown by the master.
   */
  ros::spin();
 
  return 0;
}

将目录切换到工作区目录,并执行catkin_make运行命令:

cd ~/ros
catkin_make

到这里呢,我们的节点创建也就完成了。
新开一个终端,启动ROS核心程序roscore。
在开始运行我们的程序之前,在原来的终端、把程序注册
1)、切换为工作区

cd ~/ros
source ./devel/setup.bash

运行talker节点:
1)、在刚刚的终端输入以下命令:

rosrun comm talker

输入完成后不要按回车
再新建一个终端想,输入以下命令:

cd ~/ros
source ./devel/setup.bash
rosrun comm listener

开始测试,在最开始的终端开始回车,切换到我们最后建立的终端,也开始回车!
测试结果
在这里插入图片描述
在这里插入图片描述
二,客户端发送一个运动目标,模拟机器人运动到目标位置
的过程,包含服务端和客户端的代码实现,要求带有实时位置反馈

创建小乌龟移动的“服务文件”turtleMove.cpp
1,新建一个终端,这里命名为终端 1,然后进入工程包 comm 下的 src 文件中
命令:cd ~/ros/src/comm/src

2,新建服务文件 turtleMove.cpp
命令:touch turtleMove.cpp

3,将如下 C++语言代码写入 turtleMove.cpp 文件中,保存后关闭!
命令:gedit turtleMove.cpp
代码:

/*
此程序通过通过动作编程实现由 client 发布一个目标位置
然后控制 Turtle 运动到目标位置的过程
*/
#include <ros/ros.h>
#include <actionlib/server/simple_action_server.h>
#include "comm/turtleMoveAction.h"
#include <turtlesim/Pose.h>
#include <turtlesim/Spawn.h>
#include <geometry_msgs/Twist.h>
typedef actionlib::SimpleActionServer<comm::turtleMoveAction> Server;
struct Myturtle
{
float x;
float y;
float theta;
}turtle_original_pose,turtle_target_pose;
ros::Publisher turtle_vel;
void posecallback(const turtlesim::PoseConstPtr& msg)
{
ROS_INFO("turtle1_position:(%f,%f,%f)",msg->x,msg->y,msg->theta);
turtle_original_pose.x=msg->x;
turtle_original_pose.y=msg->y;
turtle_original_pose.theta=msg->theta;
}
// 收到 action 的 goal 后调用该回调函数
void execute(const comm::turtleMoveGoalConstPtr& goal, Server* as)
{
comm::turtleMoveFeedback feedback;
ROS_INFO("TurtleMove is working.");
turtle_target_pose.x=goal->turtle_target_x;
turtle_target_pose.y=goal->turtle_target_y;
turtle_target_pose.theta=goal->turtle_target_theta;
geometry_msgs::Twist vel_msgs;
float break_flag;
while(1)
{
ros::Rate r(10);
vel_msgs.angular.z = 4.0 *
(atan2(turtle_target_pose.y-turtle_original_pose.y,
turtle_target_pose.x-turtle_original_pose.x)-turtle_original_pose.theta);
vel_msgs.linear.x = 0.5 *
sqrt(pow(turtle_target_pose.x-turtle_original_pose.x, 2) +
pow(turtle_target_pose.y-turtle_original_pose.y, 2));
break_flag=sqrt(pow(turtle_target_pose.x-turtle_original_pose.x, 2) +
pow(turtle_target_pose.y-turtle_original_pose.y, 2));
turtle_vel.publish(vel_msgs);
feedback.present_turtle_x=turtle_original_pose.x;
feedback.present_turtle_y=turtle_original_pose.y;
feedback.present_turtle_theta=turtle_original_pose.theta;
as->publishFeedback(feedback);
ROS_INFO("break_flag=%f",break_flag);
if(break_flag<0.1) break;
r.sleep();
}
// 当 action 完成后,向客户端返回结果
ROS_INFO("TurtleMove is finished.");
as->setSucceeded();
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "turtleMove");
ros::NodeHandle n,turtle_node;
ros::Subscriber sub =
turtle_node.subscribe("turtle1/pose",10,&posecallback); //订阅小乌龟的位置
信息
turtle_vel =
turtle_node.advertise<geometry_msgs::Twist>("turtle1/cmd_vel",10);//发布控
制小乌龟运动的速度
// 定义一个服务器
Server server(n, "turtleMove", boost::bind(&execute, _1,
&server), false);
// 服务器开始运行
server.start();
ROS_INFO("server has started.");
ros::spin();
return 0;
}

创建小乌龟“发布目标位置文件”turtleMoveClient.cpp

  1. 、在相同的目录下,创建“发布目标位置”文件 turtleMoveClient.cpp
    命令:touch turtleMoveClient.cpp
    2)、将如下 C++代码写入目标位置文件 turtleMoveClient.cpp 中,如下:
    命令:gedit turtleMoveClient.cpp
    代码:
#include <actionlib/client/simple_action_client.h>
#include "comm/turtleMoveAction.h"
#include <turtlesim/Pose.h>
#include <turtlesim/Spawn.h>
#include <geometry_msgs/Twist.h>
typedef actionlib::SimpleActionClient<comm::turtleMoveAction>
Client;
struct Myturtle
{
float x;
float y;
float theta;
}turtle_present_pose;
// 当 action 完成后会调用该回调函数一次
void doneCb(const actionlib::SimpleClientGoalState& state,
const comm::turtleMoveResultConstPtr& result)
{
ROS_INFO("Yay! The turtleMove is finished!");
ros::shutdown();
}
// 当 action 激活后会调用该回调函数一次
void activeCb()
{
ROS_INFO("Goal just went active");
}
// 收到 feedback 后调用该回调函数
void feedbackCb(const comm::turtleMoveFeedbackConstPtr& feedback)
{
ROS_INFO(" present_pose : %f %f %f",
feedback->present_turtle_x,
feedback->present_turtle_y,feedback->present_turtle_theta);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "turtleMoveClient");
// 定义一个客户端
Client client("turtleMove", true);
// 等待服务器端
ROS_INFO("Waiting for action server to start.");
client.waitForServer();
ROS_INFO("Action server started, sending goal.");
// 创建一个 action 的 goal
comm::turtleMoveGoal goal;
goal.turtle_target_x = 1;
goal.turtle_target_y = 1;
goal.turtle_target_theta = 0;
// 发送 action 的 goal 给服务器端,并且设置回调函数
client.sendGoal(goal, &doneCb, &activeCb, &feedbackCb);
ros::spin();
return 0;
}

在功能包目录下创建 action 文件夹

  1. 、进入工程包目录
    命令:cd ~/ros/src/comm
  2. 、创建 action 文件夹
    命令:mkdir action

在 action 文件夹下创建 turtleMove.action 文件

  1. 、进入 action 文件夹
    命令:cd action
  2. 、创建 turtleMove.action 文件
    命令:touch turtleMove.action
  3. 、将如下代码写入 turtleMove.action 文件中,如下:
    命令:gedit turtleMove.action
    代码:
# Define the goal
float64 turtle_target_x # Specify Turtle's target position
float64 turtle_target_y
float64 turtle_target_theta
---
# Define the result
float64 turtle_final_x
float64 turtle_final_y
float64 turtle_final_theta
---
# Define a feedback message
float64 present_turtle_x
float64 present_turtle_y
float64 present_turtle_theta

修改 CMakeLists.txt 文件内容
1 进入工程包 comm 目录下
命令:cd ~/ros/src/comm
2 打开 CMakeLists.txt 文件
命令:sudo gedit CMakeLists.txt
3 将如下代码添加到 CMakeLists.txt 文件末尾

  1. 、在 CMakeLists.txt 文件末尾添加如下代码:
add_executable(turtleMoveClient src/turtleMoveClient.cpp)
target_link_libraries(turtleMoveClient ${catkin_LIBRARIES})
add_dependencies(turtleMoveClient ${PROJECT_NAME}_gencpp)
add_executable(turtleMove src/turtleMove.cpp)
target_link_libraries(turtleMove ${catkin_LIBRARIES})
add_dependencies(turtleMove ${PROJECT_NAME}_gencpp)
  1. 、在该文件中找到 find_package 函数方法,修改为如下:
    代码:
find_package(catkin REQUIRED COMPONENTS
roscpp
rospy
std_msgs
message_generation
actionlib_msgs
actionlib
)
  1. 、继续在该文件中找到 add_action_files 函数一项,默认是用#注释掉了的,这
    里我们找到后修改为如下代码:
    代码:
add_action_files(
FILES
turtleMove.action
)
  1. 、继续在该文件中找到 generate_messages 函数一项,默认也是#注释,这里修改
    为如下代码:
    代码:
generate_messages(
DEPENDENCIES
std_msgs
actionlib_msgs
)
  1. 、找到 catkin_package 函数一项,修改为如下代码:
    代码:
# INCLUDE_DIRS include
# LIBRARIES comm
# CATKIN_DEPENDS roscpp rospy std_msgs
# DEPENDS system_lib
CATKIN_DEPENDS roscpp rospy std_msgs
message_runtime

(3) 、修改 package.xml 文件内容
1 打开 package.xml 文件
命令:gedit package.xml
2 将文件中 build_depend 一栏、替换为如下代码:
代码:

<buildtool_depend>catkin</buildtool_depend>
<build_depend>roscpp</build_depend>
<build_depend>rospy</build_depend>
<build_depend>std_msgs</build_depend>
<build_depend>message_generation</build_depend>
<build_depend>actionlib</build_depend>
<build_depend>actionlib_msgs</build_depend>
<build_export_depend>roscpp</build_export_depend>
<build_export_depend>rospy</build_export_depend>
<build_export_depend>std_msgs</build_export_depend>

3 将文件中 exec_depend 一栏、替换为如下代码:
代码:

<exec_depend>roscpp</exec_depend>
<exec_depend>rospy</exec_depend>
<exec_depend>std_msgs</exec_depend>
<exec_depend>message_runtime</exec_depend>
<exec_depend>actionlib</exec_depend>
<exec_depend>actionlib_msgs</exec_depend>

点击保存关闭,我们的 package.xml 文件就修改好了!
(4) 、运行程序进行测试
1 编译我们的测试文件

  1. 、进入我们的项目工程空间
    命令:cd ~/ros
  2. 、编译文件
    命令:catkin_make
    成功注册图
    在这里插入图片描述

2 注册程序
命令: source ./devel/setup.bash
3 新建一个终端,命令为终端 2,启动 ros
命令:roscore

再新建一个终端,命名为终端 3,运行我们的小海龟,出现小海龟窗口,我们命名为 窗口 3

在新建一个终端,命名为终端 4,运行我们的目标位置程序代码:

  1. 、进入 ros 工作空间
    命令:cd ~/ros
  2. 、程序注册
    命令:source ./devel/setup.bash
  3. 、运行 turtleMoveClient.cpp,记住,输入该命令,但不忙按回车
    命令:rosrun comm turtleMoveClient

6 进行测试
在终端 1 运行 turtleMove,记住,输入如下命令,也不忙按回车
命令:rosrun comm turtleMove
3) 、开始测试,终端 1 回车、终端 4 回车,出现如下画面,则我们动作编程的实验
完美成功
在这里插入图片描述
三,主从机通信连接测试
ip查看指令ifconfig
查看各自的hostname,在终端里输入hostname
再打开hosts文件和hashrc文件
分别修改主从机的.bashrc文件
主机A添加:

export ROS_HOSTNAME=hostA
export ROS_MASTER_URI=http://192.168.0.1:11311 ##主机的ip
export ROS_IP=192.168.0.1  ##主机的ip

从机B添加:

export ROS_HOSTNAME=hostB ##这个不设置,可能出现主机无法打印从机信息
export ROS_MASTER_URI=http://192.168.0.1:11311 ##主机的ip
export ROS_IP=192.168.0.1 ##我的测试里主机的ip和从机的ip都可以,去掉也可以

在这里插入图片描述
在这里插入图片描述
要实现双向的通信测试,不止要通过 rostopic list 指令查看是否有接收调对方的topic,还要通过rostopic echo /“topicname” 打印一下,(有时候列表有显示,但所打印不了,同样无法实现双向的控制)
测试方法:1、主从机各自发送topic,互相显示topic内容;2、使用小乌龟教程,互相作为控制和显示端,进行测试。
测试成功事例
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值