在ROS中实现C++两个节点相互通信以及向python节点请求service

  • Post author:
  • Post category:python


首先新建工作空间文件夹drone_ws,在工作空间中创建文件夹src,返回工作空间文件夹,编译工作空间

cd ~/drone_ws
catkin_make

在src文件夹中创建程序包

catkin_create_pkg my_pkg std_msgs rospy roscpp

在程序包中建立msg和srv文件夹,在msg文件夹中建立msg1.msg文件(空的即可,本例中不需要message类型),在srv文件夹中建立文件:srv1.srv  并输入以下代码:

float64 powerConsumption
---
float64 etaD

在程序包中的include/my_pkg文件夹中创建头文件 controller.h

#ifndef CONTROLLER_H
#define CONTROLLER_H

#include"std_msgs/Float64.h"

class Controller{
public:
    double f;
    double eta_d = 5;
    double kp = 3;
    double p = 0; //power consumption
    
    Controller(){};
    void CalF(double &eta);
    void ChangeEtaD(double &etad);
    void CalP();
    void ResetPowerConsumption();
};

#endif

controller_node.h

#ifndef CONTROLLERNO_NODE_H
#define CONTROLLER_NODE_H

#include"controller.h"
#include"ros/ros.h"
#include"my_pkg/srv1.h"
#include<cstdlib>
#include<sstream>
#include<iostream>

class ControllerNode{
public:
    ros::NodeHandle n_;
    ros::Publisher pub_;
    ros::Subscriber sub_;
    ros::Publisher pub_2;
    ros::Subscriber sub_2;
    ros::ServiceClient client_;
    my_pkg::srv1 srv1;
    Controller *controller_;
    int count = 0;

    ControllerNode(Controller *controller){
        controller_ = controller;  
        sub_ = n_.subscribe("vessel_position", 1, &ControllerNode::callback, this); 
        pub_ = n_.advertise<std_msgs::Float64>("control_force", 1);
        client_ = n_.serviceClient<my_pkg::srv1>("call_for_etaD");
        
    }

    void PublishControlForce();

    void callback(const std_msgs::Float64::ConstPtr& msg){
        count += 1;
	    double eta = msg->data;
        controller_->CalF(eta);
        controller_->CalP();
        std_msgs::Float64 output;
	    output.data = controller_->f;
        pub_.publish(output);
        std::cout << "step:" << count << ";" << "eta_d:" << controller_->eta_d << ";" << "force:" << output.data << std::endl;
        if(count > 50){
            srv1.request.powerConsumption = controller_->p;
            client_.call(srv1);
            std::cout<< "call service!" << std::endl;
            controller_->eta_d = srv1.response.etaD;
            controller_->ResetPowerConsumption();
            count = 0;
        }
    }

};

#endif

vessel.h

#ifndef VESSEL_H
#define VESSEL_H


#include"std_msgs/Float64.h"

class Vessel{
public:
    double m;
    double eta;

    Vessel(double m_, double eta_){
        m = m_;
        eta = eta_;
    }
    void Motion(double &f);
};

#endif

vessel_node.h

#ifndef VESSEL_NODE_H
#define VESSEL_NODE_H

#include"vessel.h"
#include"ros/ros.h"
#include<sstream>
#include<iostream>

class VesselNode{
public:
    ros::NodeHandle n_;
    ros::Publisher pub_;
    ros::Subscriber sub_;
    Vessel *vessel_;


    VesselNode(Vessel *vessel){
        vessel_ = vessel;   
        sub_ = n_.subscribe("control_force", 1, &VesselNode::callback, this); 
        pub_ = n_.advertise<std_msgs::Float64>("vessel_position", 1);
    }
    void PublishPosition();
    void callback(const std_msgs::Float64::ConstPtr& msg){
	    double f = msg->data;
        vessel_->Motion(f);
        std_msgs::Float64 output;
	    output.data = vessel_->eta;
        pub_.publish(output);
        std::cout << output.data << std::endl;
    }
};

#endif

在程序包的src文件夹中创建以下cpp文件和py文件,controller.cpp

#include"my_pkg/controller.h"

void Controller::CalF(double &eta){
    this->f = kp * (eta_d - eta);
}

void Controller::ChangeEtaD(double &etad){
    this->eta_d = etad;
}

void Controller::CalP(){
    this->p = f * f;
}

void Controller::ResetPowerConsumption(){
    this->p = 0;
}

controller_node.cpp

#include"my_pkg/controller_node.h"


void ControllerNode::PublishControlForce(){
    std_msgs::Float64 output;
    output.data = controller_->f;
    pub_.publish(output);
    std::cout << output.data << std::endl;
}

controller_interface.cpp

#include"my_pkg/controller_node.h"
#include"ros/ros.h"


int main(int argc, char **argv){
    ros::init(argc, argv, "controller_interface");
    Controller pidController;
    ControllerNode node_controller(&pidController);
    ros::spin();
    

    return 0;
}

vessel.cpp

#include"my_pkg/vessel.h"


void Vessel::Motion(double &f){
    this->eta = eta + f / m;
}

vessel_node.cpp

#include"my_pkg/vessel_node.h"


void VesselNode::PublishPosition(){
    std_msgs::Float64 output;
    output.data = vessel_->eta;
    pub_.publish(output);
    std::cout << output.data << std::endl;
}

vessel_interface.cpp

#include"my_pkg/vessel_node.h"


int main(int argc, char** argv){
    ros::init(argc, argv, "vessel_interface");
    Vessel v1(10, 0);
    VesselNode node_vessel(&v1);
    ros::Rate loop_rate(10);
    while(ros::ok()){
        node_vessel.PublishPosition();
        ros::spinOnce();
        loop_rate.sleep();
    }

    

    return 0;    
}

brain.py

#!/usr/bin/env python

NAME = 'call_for_etaD'

import rospy
from std_msgs.msg import Float64
from my_pkg.srv import *
import random


def ChangeEtaD(req):
    reward = req.powerConsumption
    etaD = random.randint(1,10)
    print("send new etaD")
    return etaD

def rossrv_creat():
    rospy.init_node(NAME , anonymous=True)
    s = rospy.Service('call_for_etaD', srv1, ChangeEtaD)
    print("server is waiting!")
    rospy.spin()

if __name__ == '__main__':
    print('Brain is waiting')
    rossrv_creat()

之后,将程序包中的CMakeList.txt文件与pacakge.xml文件改成如下内容:

cmake_minimum_required(VERSION 2.8.3)
project(my_pkg)

## Compile as C++11, supported in ROS Kinetic and newer
# add_compile_options(-std=c++11)

## Find catkin macros and libraries
## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)
## is used, also find other catkin packages
find_package(catkin REQUIRED COMPONENTS
  roscpp
  rospy
  std_msgs
  message_generation
)

## System dependencies are found with CMake's conventions
# find_package(Boost REQUIRED COMPONENTS system)


## Uncomment this if the package has a setup.py. This macro ensures
## modules and global scripts declared therein get installed
## See http://ros.org/doc/api/catkin/html/user_guide/setup_dot_py.html
# catkin_python_setup()

################################################
## Declare ROS messages, services and actions ##
################################################

## To declare and build messages, services or actions from within this
## package, follow these steps:
## * Let MSG_DEP_SET be the set of packages whose message types you use in
##   your messages/services/actions (e.g. std_msgs, actionlib_msgs, ...).
## * In the file package.xml:
##   * add a build_depend tag for "message_generation"
##   * add a build_depend and a run_depend tag for each package in MSG_DEP_SET
##   * If MSG_DEP_SET isn't empty the following dependency has been pulled in
##     but can be declared for certainty nonetheless:
##     * add a run_depend tag for "message_runtime"
## * In this file (CMakeLists.txt):
##   * add "message_generation" and every package in MSG_DEP_SET to
##     find_package(catkin REQUIRED COMPONENTS ...)
##   * add "message_runtime" and every package in MSG_DEP_SET to
##     catkin_package(CATKIN_DEPENDS ...)
##   * uncomment the add_*_files sections below as needed
##     and list every .msg/.srv/.action file to be processed
##   * uncomment the generate_messages entry below
##   * add every package in MSG_DEP_SET to generate_messages(DEPENDENCIES ...)

## Generate messages in the 'msg' folder
 add_message_files(
   FILES
   msg1.msg
#   Message2.msg
 )

## Generate services in the 'srv' folder
 add_service_files(
   FILES
   srv1.srv
#   Service2.srv
 )

## Generate actions in the 'action' folder
# add_action_files(
#   FILES
#   Action1.action
#   Action2.action
# )

## Generate added messages and services with any dependencies listed here
 generate_messages(
   DEPENDENCIES
   std_msgs
 )

################################################
## Declare ROS dynamic reconfigure parameters ##
################################################

## To declare and build dynamic reconfigure parameters within this
## package, follow these steps:
## * In the file package.xml:
##   * add a build_depend and a run_depend tag for "dynamic_reconfigure"
## * In this file (CMakeLists.txt):
##   * add "dynamic_reconfigure" to
##     find_package(catkin REQUIRED COMPONENTS ...)
##   * uncomment the "generate_dynamic_reconfigure_options" section below
##     and list every .cfg file to be processed

## Generate dynamic reconfigure parameters in the 'cfg' folder
# generate_dynamic_reconfigure_options(
#   cfg/DynReconf1.cfg
#   cfg/DynReconf2.cfg
# )

###################################
## catkin specific configuration ##
###################################
## The catkin_package macro generates cmake config files for your package
## Declare things to be passed to dependent projects
## INCLUDE_DIRS: uncomment this if your package contains header files
## LIBRARIES: libraries you create in this project that dependent projects also need
## CATKIN_DEPENDS: catkin_packages dependent projects also need
## DEPENDS: system dependencies of this project that dependent projects also need
catkin_package(
#  INCLUDE_DIRS include
#  LIBRARIES my_pkg
  CATKIN_DEPENDS roscpp rospy std_msgs
#  DEPENDS system_lib
)

###########
## Build ##
###########

## Specify additional locations of header files
## Your package locations should be listed before other locations
include_directories(
 include
  ${catkin_INCLUDE_DIRS}
)

## Declare a C++ library
#   include/my_pkg/controller.h
#   include/my_pkg/controller_node.h
#   include/my_pkg/vessel.h
#   include/my_pkg/vessel_node.h
 add_library(simulation
   include/my_pkg/controller.h
   include/my_pkg/controller_node.h
   include/my_pkg/vessel.h
   include/my_pkg/vessel_node.h
   src/controller.cpp
   src/controller_node.cpp
   src/vessel.cpp
   src/vessel_node.cpp
 )

## Add cmake target dependencies of the library
## as an example, code may need to be generated before libraries
## either from message generation or dynamic reconfigure
# add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})

## Declare a C++ executable
## With catkin_make all packages are built within a single CMake context
## The recommended prefix ensures that target names across packages don't collide
add_executable(controller_interface src/controller_interface.cpp)
add_executable(vessel_interface src/vessel_interface.cpp)

## Rename C++ executable without prefix
## The above recommended prefix causes long target names, the following renames the
## target back to the shorter version for ease of user use
## e.g. "rosrun someones_pkg node" instead of "rosrun someones_pkg someones_pkg_node"
# set_target_properties(${PROJECT_NAME}_node PROPERTIES OUTPUT_NAME node PREFIX "")

## Add cmake target dependencies of the executable
## same as for the library above
add_dependencies(controller_interface my_pkg_generate_messages_cpp)
add_dependencies(vessel_interface my_pkg_generate_messages_cpp)

## Specify libraries to link a library or executable target against
target_link_libraries(controller_interface  simulation  ${catkin_LIBRARIES})
target_link_libraries(vessel_interface  simulation  ${catkin_LIBRARIES})


#############
## Install ##
#############

# all install targets should use catkin DESTINATION variables
# See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html

## Mark executable scripts (Python etc.) for installation
## in contrast to setup.py, you can choose the destination
# install(PROGRAMS
#   scripts/my_python_script
#   DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
# )

## Mark executables and/or libraries for installation
# install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_node
#   ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
#   LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
#   RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
# )

## Mark cpp header files for installation
# install(DIRECTORY include/${PROJECT_NAME}/
#   DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
#   FILES_MATCHING PATTERN "*.h"
#   PATTERN ".svn" EXCLUDE
# )

## Mark other files for installation (e.g. launch and bag files, etc.)
# install(FILES
#   # myfile1
#   # myfile2
#   DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
# )

#############
## Testing ##
#############

## Add gtest based cpp test target and link libraries
# catkin_add_gtest(${PROJECT_NAME}-test test/test_my_pkg.cpp)
# if(TARGET ${PROJECT_NAME}-test)
#   target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME})
# endif()

## Add folders to be run by python nosetests
# catkin_add_nosetests(test)
<?xml version="1.0"?>
<package format="2">
  <name>my_pkg</name>
  <version>0.0.0</version>
  <description>The my_pkg package</description>

  <!-- One maintainer tag required, multiple allowed, one person per tag -->
  <!-- Example:  -->
  <!-- <maintainer email="jane.doe@example.com">Jane Doe</maintainer> -->
  <maintainer email="ivan@todo.todo">ivan</maintainer>


  <!-- One license tag required, multiple allowed, one license per tag -->
  <!-- Commonly used license strings: -->
  <!--   BSD, MIT, Boost Software License, GPLv2, GPLv3, LGPLv2.1, LGPLv3 -->
  <license>TODO</license>


  <!-- Url tags are optional, but multiple are allowed, one per tag -->
  <!-- Optional attribute type can be: website, bugtracker, or repository -->
  <!-- Example: -->
  <!-- <url type="website">http://wiki.ros.org/my_pkg</url> -->


  <!-- Author tags are optional, multiple are allowed, one per tag -->
  <!-- Authors do not have to be maintainers, but could be -->
  <!-- Example: -->
  <!-- <author email="jane.doe@example.com">Jane Doe</author> -->


  <!-- The *depend tags are used to specify dependencies -->
  <!-- Dependencies can be catkin packages or system dependencies -->
  <!-- Examples: -->
  <!-- Use depend as a shortcut for packages that are both build and exec dependencies -->
  <!--   <depend>roscpp</depend> -->
  <!--   Note that this is equivalent to the following: -->
  <!--   <build_depend>roscpp</build_depend> -->
  <!--   <exec_depend>roscpp</exec_depend> -->
  <!-- Use build_depend for packages you need at compile time: -->
  <!--   <build_depend>message_generation</build_depend> -->
  <!-- Use build_export_depend for packages you need in order to build against this package: -->
  <!--   <build_export_depend>message_generation</build_export_depend> -->
  <!-- Use buildtool_depend for build tool packages: -->
  <!--   <buildtool_depend>catkin</buildtool_depend> -->
  <!-- Use exec_depend for packages you need at runtime: -->
  <!--   <exec_depend>message_runtime</exec_depend> -->
  <!-- Use test_depend for packages you need only for testing: -->
  <!--   <test_depend>gtest</test_depend> -->
  <!-- Use doc_depend for packages you need only for building documentation: -->
  <!--   <doc_depend>doxygen</doc_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_export_depend>roscpp</build_export_depend>
  <build_export_depend>rospy</build_export_depend>
  <build_export_depend>std_msgs</build_export_depend>
  <build_export_depend>message_generation</build_export_depend>
  <exec_depend>roscpp</exec_depend>
  <exec_depend>rospy</exec_depend>
  <exec_depend>std_msgs</exec_depend>
  <exec_depend>message_generation</exec_depend>


  <!-- The export tag contains other, unspecified, tags -->
  <export>
    <!-- Other tools can request additional information be placed here -->

  </export>
</package>

返回工作空间编译即可。

本例所实现的功能是一个极简化版vessel一维运动控制,brain.py文件类似指挥官,为控制器controller.h类提供运动的目标点,控制器计算出运动到该目标点所需的控制力,vessel.h类在控制器的作用下移动,移动过程中将自己的位置不断反馈给控制器,使控制器调整控制力,控制器与vessel之间为topic通信。当vessel运动一段时间后,控制器通过ROS的service通信方式,向brain.py发送信息,brain.py作为服务器为控制器客户端发送新的目标点。



版权声明:本文为qq_41816368原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。