ROS- create packages and feature node

 Personal blog: http://www.chenjianqu.com/

Original link: http://www.chenjianqu.com/show-72.html

 This article is my learning ROS notes, explains how to create a command line feature pack from zero: Service-based communication roscpp and based rospy the topic of communication.

 

A. Service based on the communication roscpp

1. First, create a workspace

    Catkin workspace to create, modify, compile directory catkin package.

(Base) chenjianqu chen @: ~ $ cd ROS 
(Base) chenjianqu chen @: ~ / ROS $ cd Project 
(Base) chenjianqu chen @: ~ / ROS / Project ws2 $ mkdir -p / src 
(Base) chenjianqu @ chen: ~ / ROS / Project $ cd ws2 
(Base) chenjianqu chen @: ~ / ROS / Project / ws2 $ catkin_make # initialize workspace

    catkin workspace includes src, build, devel three folders:

    src /: ROS catkin of packages (source package)

    build /: catkin (CMake) and intermediate file cache information

    devel /: the resulting object files (including header files, dynamic link libraries, statically linked libraries, executables, etc.), environment variables

 

2. Create a Package

(base) chenjianqu@chen:~/ros/project/ws2$ cd src
(base) chenjianqu@chen:~/ros/project/ws2/src$ catkin_create_pkg serve_test std_msgs rospy roscpp

    Need to create a package in the catkin_ws / src, used catkin_create_pkg command usage is: catkin_create_pkg package depends, where package is the package name, depends is dependent package name, you can rely on more than one package. The above command creates a serve_test packages, depending on the roscpp rospy std_msgs.

     A package under common file paths are:

    CMakeLists.txt: definition of package package name, dependence, source files, object files compiled rules are essential components package

    package.xml: description of the package name, version number, author, etc. dependent package, the package is the essential ingredient

    src /: storing ROS source code, including source code, and C ++ (.cpp) Python and the module (.py)

    include /: C ++ source code corresponding to the stored headers

    scripts /: for executable scripts, such as shell scripts (.sh), Python scripts (.py)

    msg /: storing custom format message (a .msg)

    srv /: self-storage service definition format (.srv)

    models /: store the 3D model of the robot or a simulation scenario (.sda, .stl, .dae etc.)

    urdf /: storage model describes the robot (.urdf or .xacro)

    launch /: store launch file (.launch or .xml)

    Which is defined package of CMakeLists.txt and package.xml, these two files in the package is essential. catkin before compiling build system, we must first resolve these two files. These two documents on the definition of a package. ROS are usually organized in accordance with the above file the form, which is the convention of naming conventions, guidelines are recommended. More than one path, only CMakeLists.txt and package.xml is a must, the rest of the path is required to decide according to the package.

 

3. Create a service message file

(base) chenjianqu@chen:~/ros/project/ws2/src$ ls
(base) chenjianqu@chen:~/ros/project/ws2/src$ cd serve_test
(base) chenjianqu@chen:~/ros/project/ws2/src/serve_test$ mkdir -p srv
(base) chenjianqu@chen:~/ros/project/ws2/src/serve_test$ cd srv

(base) chenjianqu@chen:~/ros/project/ws2/src/serve_test/srv$ vim Greeting.srv

Written message content Greeting.srv in:

string name
int32 age
---
string feedback

    srv file is used to describe the service (service data format definition data type, the communication service in the * .srv. declares a service, comprising a two-part request (request) and response (Reply).

 

4. Modify CMakeLists.txt and package.xml, compiling news service

(base) chenjianqu@chen:~/ros/project/ws2/src/serve_test/srv$ cd ..
(base) chenjianqu@chen:~/ros/project/ws2/src/serve_test$ ls
(base) chenjianqu@chen:~/ros/project/ws2/src/serve_test$ vim CMakeLists.txt #修改CMakeLists文件

Modifications are as follows:

find_package (catkin REQUIRED COMPONENTS  
    roscpp 
    std_msgs 
    place message_generation # want to add 
) 
#catkin over cmake new command, specify the file from which the message is generated 
add_service_files (FILES Greeting.srv) # add this one 
#catkin new command, for generating a message #DEPENDENCIES specified later generation relies on any other message msg, since gps.msg uses standard ROS flaot32 this message, then it is necessary std_msgs as dependent 
generate_messages (DEPENDENCIES std_msgs) # Add this to a

 

(Base) chenjianqu @ chen: ~ / ros / project / ws2 / src / serve_test $ vim package.xml # modified file package.xml

Modify the content added:

<build_depend> message_generation </ build_depend> # add this one 
<exec_depend> message_runtime </ exec_depend> # Add this one

 

Finally compile news service

(base) chenjianqu@chen:~/ros/project/ws2/src/serve_test$ cd ..
(base) chenjianqu@chen:~/ros/project/ws2/src$ cd ..
(base) chenjianqu@chen:~/ros/project/ws2$ catkin_make

    After completion of the translation will generate a corresponding Greeting.srv path at devel header files, header files define serve_test :: Greeting :: Request and serve_test :: Greeting :: Response types of data according to the rules of syntax of C ++.

 

5. Preparation of Server and Client two source nodes

(Base) chenjianqu @ chen: ~ / ROS / Project / ws2 $ cd src 
(Base) chenjianqu @ chen: ~ / ROS / Project / ws2 / src $ cd serve_test 
(Base) chenjianqu @ chen: ~ / ROS / Project / ws2 / src / serve_test $ LS 
(base) chenjianqu @ chen: ~ / ros / project / ws2 / src / serve_test $ cd src 
# create the source code for server node 
(base) chenjianqu @ chen: ~ / ros / project / ws2 / src / serve_test / src $ vim server.cpp

Code reads as follows:

#include <ROS / ros.h> 
#include <serve_test / Greeting.h> 
BOOL handle_function (serve_test the Request :: :: the Greeting & REQ, the Greeting :: :: serve_test the Response & RES) { 
    // display request information 
    ROS_INFO ( "Request from Age% S with D% ", req.name.c_str (), req.age); 
    // process the request, write result Response 
    res.feedback =" the Hi "+ + req.name" the I'm Server. "! ; 
    // returns true, correctly processed the request 
    return to true; 
} 
int main (int argc, char ** the argv) { 
    ros :: the init (argc, the argv, "greetings_server"); // resolution parameters, unnamed node 
    ros :: NodeHandle nh; // create the handle, instantiate the Node 
    ROS :: ServiceServer service = nh.advertiseService ( "Greetings", handle_function); // handler stated services 
    ROS :: Spin (); 
    return 0;
}

    Then creates the source code of the client node

(base) chenjianqu@chen:~/ros/project/ws2/src/serve_test/src$ vim client.cpp

code show as below:

#include <ROS / ros.h> 
#include <serve_test / Greeting.h> 

int main (int argc, char ** the argv) 
{ 
    ROS :: the init (argc, the argv, "greetings_client"); // initialization, node naming It is "greetings_client" 
    ROS :: NodeHandle NH; 
    ROS client :: = nh.serviceClient the ServiceClient <serve_test the Greeting ::> ( "Greetings"); 
    // define the service client, service named "greetings", service type serve_test 

    / / SRV instantiation, provided that the content request message, where the request contains two variables, name and Age, see Greeting.srv 
    serve_test the Greeting :: SRV; 
    srv.request.name = "HAN"; 
    srv.request.age = 20 is ; 

    IF (the Client.call (SRV)) 
    {  
        // we note the contents of the response portion contains only a variable response, another note was converted to a string
        ROS_INFO ( "the Response from Server:% S", srv.response.feedback.c_str ());
    }
    else
    {
        ROS_ERROR("Failed to call service serve_test");
        return 1;
    }
    return 0;
}

 

5. Configure CMakeLists.txt, compiler workspace

(base) chenjianqu@chen:~/ros/project/ws2/src/serve_test/src$ cd ..
(base) chenjianqu@chen:~/ros/project/ws2/src/serve_test$ vim CMakeLists.txt

In CMakeLists.txt file to add:

# Server to generate the executable file needed to compile source files and src / server.cpp, if desired a plurality of code files can be listed once in the back, separated by a space intermediate 
add_executable (server the src / server.cpp) 
# Set dependencies, this must be added add_dependencies, otherwise it can not find the custom headers srv generated 
add_dependencies (Server serve_test_generate_messages_cpp)  
# set link libraries, many processes need to use third-party libraries, where you can configure the default link library 
target_link_libraries (server $ catkin_LIBRARIES} {)  

add_executable (Client the src / client.cpp) 
add_dependencies (Client serve_test_generate_messages_cpp) 
target_link_libraries (Client catkin_LIBRARIES $ {})

Then compile Workspace

(base) chenjianqu@chen:~/ros/project/ws2/src/serve_test$ cd ..
(base) chenjianqu@chen:~/ros/project/ws2/src$ cd ..
(base) chenjianqu@chen:~/ros/project/ws2$ catkin_make

 

6. Test

    A. Open a new terminal and run roscore

    B. then open a new terminal, the server runs node

(base) chenjianqu@chen:~/ros/project/ws2$ source devel/setup.bash
(base) chenjianqu@chen:~/ros/project/ws2$ rosrun serve_test server

    C. and then open a new terminal, run client node

(base) chenjianqu@chen:~/ros/project/ws2$ source devel/setup.bash
(base) chenjianqu@chen:~/ros/project/ws2$ rosrun serve_test client

    Then the server node will receive the message client node: [INFO] [1575818511.403724893]: Request from HAN with age 20.

    Then the client node receives the message returned from the server node: [INFO] [1575818511.403884222]: Response from server:. Hi HAN I ??? m server !.

    After compilation environment must refresh the workspace, or it may not find a job space. Many times we have to open the terminal will be able to run the workspace compiled ROS program, we used the "source workspace path /devel/setup.bash" command added to the ~ / .bashrc file so that every time you open a terminal, the system it will refresh the workspace environment. By "echo" source workspace path /devel/setup.bash ">> ~ / .bashrc" command to append.

 

 

II. Topic on the communication rospy

    Created above the basic work on the space, create another package.

(base) chenjianqu@chen:~/ros/project/ws2/src$ catkin_create_pkg topic_test std_msgs rospy

    Then create a directory for storing message msg topic in the package directory, create topic communication format gps.msg

(base) chenjianqu@chen:~/ros/project/ws2/src/topic_test/msg$ vim gps.msg

    The following code is written, the different format of the communication service, topic communication is one-way communication:

string state
float32 x
float32 y

    Then as service example above, modify CMakeLists.txt and package.xml, and compile service messages.

    Then you can start writing rospy program here create scripts folder under the package directory for storing simple python script code,

(base) chenjianqu@chen:~/ros/project/ws2/src/topic_test/scripts$ vim pytalker.py

code show as below:

! # / usr / bin / Python the env 
# = UTF-Coding. 8 
Import rospy 
from topic_test.msg # Import GPS import the custom data type 

DEF Talker (): 
    Pub rospy.Publisher = ( 'gps_info', GPS, the queue_size = 10 ) 
    rospy.init_node ( 'pytalker', Anonymous = True) 
    # update frequency is 1Hz 
    Rate rospy.Rate = (. 1)  
    X = 1.0 
    Y = 2.0 
    State = 'Working' 
    the while Not rospy.is_shutdown (): 
    # calculates the distance 
    rospy. the loginfo ( 'Talker: the GPS:% X = F, Y = F%', X, Y) 
    pub.publish (GPS (State, X, Y)) 
    X * X = 1.03 
    Y = 1.01 * Y 
    rate.sleep () 

the __name__ == IF '__main__': 
    Talker ()
 
the first parameter #Publisher function is a topic name, and the second parameter data types, now is the msg we define the last one is the size of the buffer
#queue_size: None (not recommended) # This will set the transceiver to block synchronous mode! 
#queue_size: 0 (not recommended) # This buffer is set to infinity mode, very dangerous! 
#queue_size: 10 or more # In general, to 10. queue_size too much can cause data latency is not synchronized.

After writing the file as an executable file:

(base) chenjianqu@chen:~/ros/project/ws2/src/topic_test/scripts$ chmod +x pytalker.py

 

Then create a new node script file:

(base) chenjianqu@chen:~/ros/project/ws2/src/topic_test/scripts$ vim pylistener.py

Code:

! # / usr / bin / Python the env 
# = UTF-Coding. 8 
Import rospy 
Import Math 
from GPS Import topic_test.msg 

# callback should be entered MSG 
DEF the callback (GPS): 
    Distance = Math.sqrt (Math.pow (GPS .x, 2) + Math.pow (gps.y, 2))  
    rospy.loginfo ( 'The listener: the GPS: Distance =% F,% S = State', Distance, gps.state) 
DEF listener (): 
    rospy. init_node ( 'pylistener', anonymous = True) 
    the first argument is the function #Subscriber topic name, the second parameter is the data type of the third parameter is received callback function name 
    rospy.Subscriber ( 'gps_info', gps, the callback) 
    rospy.spin () 
IF the __name__ == '__main__': 
    listener ()
(base) chenjianqu@chen:~/ros/project/ws2/src/topic_test/scripts$ chmod +x pylistener.py

 

    python code is a dynamic language, so no need to modify cmakelists.txt file, catkin_make directly in the workspace, another refresh environment variables to run.

 

    The first line of code #! / Usr / bin / env python This usage is intended to prevent the operating system the user will not have python installed in the default / usr / bin path inside. When the system sees this line, the first thing will be to find the installation path settings in the env python, and then calls the interpreter program under the corresponding path to complete the operation.

 

 

 

 

 

 

references

[0] CAS software, heavy German intelligence company. China University of MOOC --- "Android OS Getting Started" course notes. Https://sychaichangkun.gitbooks.io/ros-tutorial-icourse163/content/

 

 

Published 74 original articles · won praise 33 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_37394634/article/details/104430077