创建turtle_command_server.cpp文件:
/***********************************************************************
Copyright 2020 GuYueHome (www.guyuehome.com).
***********************************************************************/
/**
* 该例程将执行/turtle_command服务,服务数据类型std_srvs/Trigger
*/
#include
#include
#include
ros::Publisher turtle_vel_pub;
bool pubCommand = false;
// service回调函数,输入参数req,输出参数res
bool commandCallback(std_srvs::Trigger::Request &req,
std_srvs::Trigger::Response &res)
{
pubCommand = !pubCommand;
// 显示请求数据
ROS_INFO("Publish turtle velocity command [%s]", pubCommand==true?"Yes":"No");
// 设置反馈数据
res.success = true;
res.message = "Change turtle command state!";
return true;
}
int main(int argc, char **argv)
{
// ROS节点初始化
ros::init(argc, argv, "turtle_command_server");
// 创建节点句柄
ros::NodeHandle n;
// 创建一个名为/turtle_command的server,注册回调函数commandCallback
ros::ServiceServer command_service = n.advertiseService("/turtle_command", commandCallback);
// 创建一个Publisher,发布名为/turtle1/cmd_vel的topic,消息类型为geometry_msgs::Twist,队列长度10
turtle_vel_pub = n.advertise("/turtle1/cmd_vel", 10);
// 循环等待回调函数
ROS_INFO("Ready to receive turtle command.");
// 设置循环的频率
ros::Rate loop_rate(10);
while(ros::ok())
{
// 查看一次回调函数队列
ros::spinOnce();
// 如果标志为true,则发布速度指令
if(pubCommand)
{
geometry_msgs::Twist vel_msg;
vel_msg.linear.x = 0.5;
vel_msg.angular.z = 0.2;
turtle_vel_pub.publish(vel_msg);
}
//按照循环频率延时
loop_rate.sleep();
}
return 0;
}
随后在Cmake文件中添加如下编程规则:
add_executable(turtle_command_serversrc/turtle_command_server.cpp)
target_link_libraries(turtle_command_server$ {catkin_LIBRARIES})
随后,输入 roscore
rosrun turtlesim turtlesim_node
随后输入: rosrun learning_service turtle_command_server
再输入 rosservice call /turtle_command “{}”
效果如上。
turtle_command_server.py文件:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
########################################################################
#### Copyright 2020 GuYueHome (www.guyuehome.com). ###
########################################################################
# 该例程将执行/turtle_command服务,服务数据类型std_srvs/Trigger
import rospy
import _thread,time
from geometry_msgs.msg import Twist
from std_srvs.srv import Trigger, TriggerResponse
pubCommand = False;
turtle_vel_pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
def command_thread():
while True:
if pubCommand:
vel_msg = Twist()
vel_msg.linear.x = 0.5
vel_msg.angular.z = 0.2
turtle_vel_pub.publish(vel_msg)
time.sleep(0.1)
def commandCallback(req):
global pubCommand
pubCommand = bool(1-pubCommand)
# 显示请求数据
rospy.loginfo("Publish turtle velocity command![%d]", pubCommand)
# 反馈数据
return TriggerResponse(1, "Change turtle command state!")
def turtle_command_server():
# ROS节点初始化
rospy.init_node('turtle_command_server')
# 创建一个名为/turtle_command的server,注册回调函数commandCallback
s = rospy.Service('/turtle_command', Trigger, commandCallback)
# 循环等待回调函数
print ("Ready to receive turtle command.")
_thread.start_new_thread(command_thread, ())
rospy.spin()
if __name__ == "__main__":
turtle_command_server()
随后输入 roscore
rosrun turtlesim turtlesim_node
rosrun learning_service turtle_command_server.py
rosservice call /turtle_command “{}”
再将如下代码加到package中图示位置:
添加.srv文件
add_service_files(FILES Person.srv)
generate_messages(DEPENDENCIES std_msgs)
再加入:
记得取消注释。
随后就是 catkin_make编译了
随后加上对应的依赖:
add_executable(person_server src/person_server.cpp)
target_link_libraries(person_server ${catkin_LIBRARIES})
add_dependencies(person_server ${PROJECT_NAME}_gencpp)
add_executable(person_client src/person_client.cpp)
target_link_libraries(person_client ${catkin_LIBRARIES})
add_dependencies(person_client ${PROJECT_NAME}_gencpp)
创建对应.cpp文件
person_client.cpp
/***********************************************************************
Copyright 2020 GuYueHome (www.guyuehome.com).
***********************************************************************/
/**
* 该例程将请求/show_person服务,服务数据类型learning_service::Person
*/
#include
#include "learning_service/person.h"
int main(int argc, char** argv)
{
// 初始化ROS节点
ros::init(argc, argv, "person_client");
// 创建节点句柄
ros::NodeHandle node;
// 发现/spawn服务后,创建一个服务客户端,连接名为/spawn的service
ros::service::waitForService("/show_person");
ros::ServiceClient person_client = node.serviceClient("/show_person");
// 初始化learning_service::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);
person_server.cpp文件:
/***********************************************************************
Copyright 2020 GuYueHome (www.guyuehome.com).
***********************************************************************/
/**
* 该例程将执行/show_person服务,服务数据类型learning_service::Person
*/
#include
#include "learning_service/person.h"
// service回调函数,输入参数req,输出参数res
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节点初始化
ros::init(argc, argv, "person_server");
// 创建节点句柄
ros::NodeHandle n;
// 创建一个名为/show_person的server,注册回调函数personCallback
ros::ServiceServer person_service = n.advertiseService("/show_person", personCallback);
// 循环等待回调函数
ROS_INFO("Ready to show person informtion.");
ros::spin();
return 0;
}
输入: roscore
rosrun learning_service person_client
rosrun learning_service person_service
person_server.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
########################################################################
#### Copyright 2020 GuYueHome (www.guyuehome.com). ###
########################################################################
# 该例程将执行/show_person服务,服务数据类型learning_service::Person
import rospy
from learning_service.srv import person, personResponse
def personCallback(req):
# 显示请求数据
rospy.loginfo("Person: name:%s age:%d sex:%d", req.name, req.age, req.sex)
# 反馈数据
return PersonResponse("OK")
def person_server():
# ROS节点初始化
rospy.init_node('person_server')
# 创建一个名为/show_person的server,注册回调函数personCallback
s = rospy.Service('/show_person', person, personCallback)
# 循环等待回调函数
print ("Ready to show person informtion.")
rospy.spin()
if __name__ == "__main__":
person_server()
person_publisher.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
########################################################################
#### Copyright 2020 GuYueHome (www.guyuehome.com). ###
########################################################################
# 该例程将请求/show_person服务,服务数据类型learning_service::Person
import sys
import rospy
from learning_service.srv import person, personRequest
def person_client():
# ROS节点初始化
rospy.init_node('person_client')
# 发现/spawn服务后,创建一个服务客户端,连接名为/spawn的service
rospy.wait_for_service('/show_person')
try:
person_client = rospy.ServiceProxy('/show_person', person)
# 请求服务调用,输入请求数据
response = person_client("Tom", 20, personRequest.male)
return response.result
except rospy.ServiceException as e:
print ("Service call failed: %s"%e)
if __name__ == "__main__":
#服务调用并显示调用结果
print ("Show person result : %s" %(person_client()))
输入 roscore
rosrun learning_service person_client.py
rosrun learning_service person_server.py
如图所示。
首先输入:
catkin_create_pkg learning_parameter roscpp rospy std_srvs
创建paraneter文件。
接下来以小海龟为例为大家讲解,首先先调出小海龟(具体方法说过好多次,这里不说了。)
输入 rosparam
想看海龟进程中的所有参数:
rosparam list
想要得到某个参数的值:
rosparam get / + 上述参数名
比如: rosparam get /turtlesim/background_b
如果想要修改,则输入:
rosparam set / + 参数名 + 修改值
如下效果:
保存参数文件:
rosparam dump param.yaml
调用参数文件: rosparam load + 文件名
此时调用的参数就是保存好的参数。
使用代码实现:
/***********************************************************************
Copyright 2020 GuYueHome (www.guyuehome.com).
***********************************************************************/
/**
* 该例程设置/读取海龟例程中的参数
*/
#include
#include
#include
int main(int argc, char **argv)
{
int red, green, blue;
// ROS节点初始化
ros::init(argc, argv, "parameter_config");
// 创建节点句柄
ros::NodeHandle node;
// 读取背景颜色参数
ros::param::get("/background_r", red);
ros::param::get("/background_g", green);
ros::param::get("/background_b", blue);
ROS_INFO("Get Backgroud Color[%d, %d, %d]", red, green, blue);
// 设置背景颜色参数
ros::param::set("/background_r", 255);
ros::param::set("/background_g", 255);
ros::param::set("/background_b", 255);
ROS_INFO("Set Backgroud Color[255, 255, 255]");
// 读取背景颜色参数
ros::param::get("/background_r", red);
ros::param::get("/background_g", green);
ros::param::get("/background_b", blue);
ROS_INFO("Re-get Backgroud Color[%d, %d, %d]", red, green, blue);
// 调用服务,刷新背景颜色
ros::service::waitForService("/clear");
ros::ServiceClient clear_background = node.serviceClient("/clear");
std_srvs::Empty srv;
clear_background.call(srv);
sleep(1);
return 0;
}
Cmake添加编译条件:
add_executable(parameter_config src/parameter_config.cpp)
target_link_libraries(parameter_config ${catkin_LIBRARIES})
此时调出小海龟后,
输入: rosrun learning_parameter parameter_config
运行我们的代码:
(python实现):
因为python的操作步骤都类似,所以这里就不多介绍了。
直接给出代码:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
########################################################################
#### Copyright 2020 GuYueHome (www.guyuehome.com). ###
########################################################################
# 该例程设置/读取海龟例程中的参数
import sys
import rospy
from std_srvs.srv import Empty
def parameter_config():
# ROS节点初始化
rospy.init_node('parameter_config', anonymous=True)
# 读取背景颜色参数
red = rospy.get_param('/background_r')
green = rospy.get_param('/background_g')
blue = rospy.get_param('/background_b')
rospy.loginfo("Get Backgroud Color[%d, %d, %d]", red, green, blue)
# 设置背景颜色参数
rospy.set_param("/background_r", 255);
rospy.set_param("/background_g", 255);
rospy.set_param("/background_b", 255);
rospy.loginfo("Set Backgroud Color[255, 255, 255]");
# 读取背景颜色参数
red = rospy.get_param('/background_r')
green = rospy.get_param('/background_g')
blue = rospy.get_param('/background_b')
rospy.loginfo("Get Backgroud Color[%d, %d, %d]", red, green, blue)
# 发现/spawn服务后,创建一个服务客户端,连接名为/spawn的service
rospy.wait_for_service('/clear')
try:
clear_background = rospy.ServiceProxy('/clear', Empty)
# 请求服务调用,输入请求数据
response = clear_background()
return response
except rospy.ServiceException, e:
print "Service call failed: %s"%e
if __name__ == "__main__":
parameter_config()
Ros学习笔记(八)——各部分代码实现(三)_风声向寂的博客-CSDN博客
Ros学习笔记(六)——各部分代码实现_风声向寂的博客-CSDN博客
ROS学习笔记(五)——工作空间和功能包_风声向寂的博客-CSDN博客
ROS学习笔记(四)——ROS命令行工具使用讲解_风声向寂的博客-CSDN博客
ROS学习笔记(三)——ROS的简单了解_风声向寂的博客-CSDN博客
ROS学习笔记(二)——python、C++编译器以及ROS的安装_风声向寂的博客-CSDN博客
Ros学习笔记系列(一):_风声向寂的博客-CSDN博客