ros2学习笔记-服务

1.创建项目包

ros2 pkg create te_test --build-type ament_cmake --dependencies rclcpp  

2.定义相关接口

        在项目目录里面创建srv目录(订阅发布是创建msg目录和 .msg 文件)并在目录下创建Test.srv文件,注意:文件名第一个字母大写。

mkdir srv
cd srv
touch Test.srv

在srv里面添加相关内容:

uint32 a
uint32 b
---
uint32 sum

3.修改CMakeLists.txt文件和package.xml

CMakeLists.txt:

cmake_minimum_required(VERSION 3.8)
project(ts_test)

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()

# find dependencies
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)
find_package(sensor_msgs REQUIRED)
find_package(rosidl_default_generators REQUIRED)
find_package(ts_test REQUIRED)

if(BUILD_TESTING)
  find_package(ament_lint_auto REQUIRED)
  # the following line skips the linter which checks for copyrights
  # comment the line when a copyright and license is added to all source files
  set(ament_cmake_copyright_FOUND TRUE)
  # the following line skips cpplint (only works in a git repo)
  # comment the line when this package is in a git repo and when
  # a copyright and license is added to all source files
  set(ament_cmake_cpplint_FOUND TRUE)
  ament_lint_auto_find_test_dependencies()
endif()

# 声明msg文件所属的工程名字, 文件位置, 依赖DEPENDENCIES
rosidl_generate_interfaces(${PROJECT_NAME}
  "srv/Test.srv"
   DEPENDENCIES sensor_msgs
)

ament_package()


add_executable(tsexe src/main.cpp src/ts.cpp)
ament_target_dependencies(tsexe "rclcpp" "std_msgs" "sensor_msgs" "ts_test")

install(TARGETS
  tsexe
  DESTINATION lib/${PROJECT_NAME}
)

package.xml: 




  ts_test
  0.0.0
  TODO: Package description
  klppc
  TODO: License declaration

  ament_cmake

  rclcpp
  std_msgs
  sensor_msgs


  rosidl_default_generators
  rosidl_default_runtime
  rosidl_interface_packages

  ament_lint_auto
  ament_lint_common

  
    ament_cmake
  

4.执行编译生成头文件

colcon build

5.在qtcreator的项目文件里添加文件

  1. 添加ros2的相关路径和新生成的接口的路径。
  2. 在src文件夹添加 main.cpp文件,ts.hpp文件,ts.cpp文件,并添加到qt的工程里面,创建qt工程时记得创建纯c++项目文件。
  3. 编写客户端和服务端代码(这里为了复习订阅发布也编写了订阅发布相关代码)。

        ros2学习笔记-服务_第1张图片

TEMPLATE = app
CONFIG += console c++11
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += \
    ../ts_test/src/main.cpp \
    ../ts_test/src/ts.cpp

HEADERS += \
    ../ts_test/src/ts.hpp
INCLUDEPATH += "/opt/ros/humble/include"
INCLUDEPATH += "/opt/ros/humble/include/rclcpp"
INCLUDEPATH += "/opt/ros/humble/include/std_msgs"
INCLUDEPATH +="/home/klppc/cache/ts_test/install/ts_test/include/ts_test"
DISTFILES += \
    ../ts_test/CMakeLists.txt \
    ../ts_test/package.xml \
    ../ts_test/srv/Test.srv
#include "ts.hpp"

int main(int argc ,char **argv)
{
    rclcpp::init(argc,argv);
    auto p = std::make_shared("ts_test");
    rclcpp::executors::MultiThreadedExecutor executor;
    executor.add_node(p);
    executor.spin();
//    rclcpp::spin(p);
    rclcpp::shutdown();
    return 0;
}
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
//#include "rclcpp/callback_group.hpp"
#include "rclcpp/client.hpp"
#include "rclcpp/service.hpp"
#include "ts_test/srv/test.hpp"


class ts:public rclcpp::Node
{
public:
    ts(std::string name);
    ~ts();
private:
    void timer_callback();
    void suber_callback(std_msgs::msg::String str);
    void seriver_callback(const std::shared_ptr request,     // CHANGE
                          std::shared_ptr       response);
    void clicent_callback(rclcpp::Client::SharedFuture s);
private:
    rclcpp::TimerBase::SharedPtr timer_;
    rclcpp::Publisher::SharedPtr puber;
    rclcpp::Subscription::SharedPtr suber;
    rclcpp::CallbackGroup::SharedPtr group_;
    rclcpp::Client::SharedPtr client_;
    rclcpp::Service::SharedPtr service_;
//    rclcpp::CallbackGroup::CallbackGroup::SharedPtr group_;
};

 

#include "ts.hpp"
using namespace std;
using std::placeholders::_1;
using std::placeholders::_2;
ts::ts(std::string name):
    rclcpp::Node(name)
{
    puber = this->create_publisher("ts",10);
    suber = this->create_subscription("ts",10,
                                                             std::bind(&ts::suber_callback,this,_1));
    group_ = this->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive);
    timer_ = this->create_wall_timer(std::chrono::milliseconds(100),
                                     std::bind(&ts::timer_callback,this),group_);


    client_ = this->create_client("ser",rmw_qos_profile_services_default,group_);
    service_ = this->create_service("ser",
                                                        std::bind(&ts::seriver_callback,this,_1,_2),
                                                        rmw_qos_profile_services_default,
                                                        group_);
    RCLCPP_INFO(this->get_logger(),"node name:%s",name.c_str());
}

ts::~ts()
{

}

void ts::timer_callback()
{
    std_msgs::msg::String str;
    static int count=1;
    std::string s = "ts"+std::string('a',count++);
    str.data = s;
    if(count>5)count = 1;
//    RCLCPP_INFO(this->get_logger(),"publish mes");
    puber->publish(str);

    while(!client_->wait_for_service(std::chrono::milliseconds(100))){};
    auto req = std::make_shared();
    req->a = count;
    req->b = count*count;
    client_->async_send_request(req,std::bind(&ts::clicent_callback,this,_1));
}

void ts::suber_callback(std_msgs::msg::String str)
{
    RCLCPP_INFO(this->get_logger(),"%s",str.data.c_str());
}

void ts::seriver_callback(const std::shared_ptr request,
                          std::shared_ptr response)
{
    response->sum = request->a+request->b;
}

void ts::clicent_callback(rclcpp::Client::SharedFuture s)
{
   auto p = s.get();
   RCLCPP_INFO(this->get_logger(),"sum = %d",p->sum);

}

更新环境变量执行编译:

source ./install/setup.bash
colcon build

6.执行程序检查结果

ros2 run ts_test tsexe

 ros2学习笔记-服务_第2张图片

  也可以新开终端打开rqt测试服务:

rqt

 ros2学习笔记-服务_第3张图片

你可能感兴趣的:(ros笔记,学习,笔记,机器人,c++,linux)