当前位置:网站首页>2021-07-18 ROS notes - basics and communication

2021-07-18 ROS notes - basics and communication

2022-06-11 01:48:00 Captain xiaoyifeng

my ROS yes noetic edition , Language is Python,Ubuntu yes 20.04
Here are some of the pits we have encountered , And some experience

About Linux Simple use

create a file

This is more convenient

>>1.py
echo "int a">>1.py

You can also use vim etc.

Create folder

mkdir <name>

Move

mv [option]  <source>  <target>

among [option] -f It's compulsory
-i I will ask you if you want to

Delete

rm [option] <name>

among [option] -f It's compulsory
-i I will ask you if you want to
-r Is to recursively delete all sub files

Copy

cp <source> <target>

Line break

\

About configuring the environment

Create Feature Pack

Because the structure of the function pack is relatively fixed , So it is troublesome to build , You need to call system commands directly

cd ~/catkin_ws/src
catkin_create_pkg <name> [depend1] [depend2] [depend3]

Compile workspace and set environment variables

cd ~/catkin_ws
catkin_make
. ./devel/setup.bash or source ./devel/setup.bash

Be careful : The environment variables here are only valid on the current terminal , If you want the environment variable to be valid on all terminals

echo "source /WORKSPACE/devel/setup.bash">>~/.bashrc

WORKSPACE Represents the workspace path

Little knowledge : stay linux in ,~ Express home,/ Represents the root directory

View the working position

echo $ROS_PACKAGE_PATH

Little knowledge :$ Variables are usually represented in programs

About Python Script

There are some python Script without suffix .py Of , And some are with , When you use it, you should see clearly Otherwise, it will report a mistake

Change the default Python edition

ROS Related libraries are installed in by default Python3 below , and Ubuntu The default open version is python2, The following modifications are required

echo alias python=python3 >> ~/.bashrc

And execute immediately

. ~/.bashrc

among alias Is an equivalent command
.bashrc Is the hidden file of the system , Custom commands for users , For all command line windows

About where the code in the package is and roscp Instructions for use

Written in the package directory scripts Folder customization file Can be run directly like this

rosrun beginner_tutorials talker.py

The files included in the package are, for example /opt/ros/noetic/share/rospy_tutorials/005_add_two_ints in
It cannot be run directly like this

rosrun beginner_tutorials add_two_ints_server.py( wrong )

It needs to be copied out

roscd beginner_tutorials/
roscp rospy_tutorials add_two_ints_server scripts/add_two_ints_server.py
roscp rospy_tutorials add_two_ints_client scripts/add_two_ints_client.py

roscp You can recursively traverse all the files under a folder
roscd Can directly cd Into a bag , No absolute directory is required

Use custom messages

CMakeList This command is written at the beginning
find_package(catkin REQUIRED COMPONENTS
roscpp
rospy
std_msgs
message_generation
)

Then write
add_service_files(
FILES
AddTwoInts.srv
)
add_message_files(
FILES
Num.msg
)
generate_messages(
DEPENDENCIES
std_msgs
)
catkin_package(

CATKIN_DEPENDS message_runtime …
…)

etc.

xml Remove the comments below the file
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>

After finishing the corresponding work ,python The script can be quoted as follows

from std_msgs.msg import String
from beginner_tutorials.msg import Num 

The above sentence is the basic message in the standard message function package String, Contains only one member , namely data, Used to store string information
The following sentence is in the custom package beginner_tutorials Of msg In a folder Num.msg file
Write the inside

int64 num

Introduction to communication mechanism

There are mainly [gugugu]

Use publisher

import rospy
from std_msgs.msg import String

def talker():
    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(10) # 10hz
    while not rospy.is_shutdown():
        hello_str = "hello world %s" % rospy.get_time()# Feeling %s And the back of the %  Can be replaced by +
        rospy.loginfo(hello_str)# Print it to the screen 
        pub.publish(hello_str)
        rate.sleep()#delay
# Prevent intermediate exit to enhance robustness 
if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:
        pass

Use subsriber

import rospy
from std_msgs.msg import String

def callback(data):
    rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)# Print to screen 
    
def listener():

    # In ROS, nodes are uniquely named. If two nodes with the same
    # name are launched, the previous one is kicked off. The
    # anonymous=True flag means that rospy will choose a unique
    # name for our 'listener' node so that multiple listeners can
    # run simultaneously.
    rospy.init_node('listener', anonymous=True)
    #  The same topic “chatter” Next 
    rospy.Subscriber("chatter", String, callback)# register callback As a callback function 

    # spin() simply keeps python from exiting until this node is stopped
    #  Prevent the program from exiting in the middle   Robustness enhancement 
    rospy.spin()

if __name__ == '__main__':
    listener()

Use server

#!/usr/bin/env python3
## Simple demo of a rospy service that add two integers

NAME = 'add_two_ints_server'

# import the AddTwoInts service
from rospy_tutorials.srv import *
import rospy 

def add_two_ints(req):
    print("Returning [%s + %s = %s]" % (req.a, req.b, (req.a + req.b)))
    return AddTwoIntsResponse(req.a + req.b)

def add_two_ints_server():
    rospy.init_node(NAME)
    s = rospy.Service('add_two_ints', AddTwoInts, add_two_ints)

    # spin() keeps Python from exiting until node is shutdown
    rospy.spin()

if __name__ == "__main__":
    add_two_ints_server()

Another way of writing

#!/usr/bin/env python

from __future__ import print_function

from beginner_tutorials.srv import AddTwoInts,AddTwoIntsResponse
import rospy

def handle_add_two_ints(req):
    print("Returning [%s + %s = %s]"%(req.a, req.b, (req.a + req.b)))
    return AddTwoIntsResponse(req.a + req.b)

def add_two_ints_server():
    rospy.init_node('add_two_ints_server')
    s = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints)
    print("Ready to add two ints.")
    rospy.spin()

if __name__ == "__main__":
    add_two_ints_server()

Use client

#!/usr/bin/env python3
## Simple demo of a rospy service client that calls a service to add
## two integers. 

import sys
import os
import rospy
# imports the AddTwoInts service 
from rospy_tutorials.srv import *

## add two numbers using the add_two_ints service
## @param x int: first number to add
## @param y int: second number to add
def add_two_ints_client(x, y):
	#  Don't have to initial initialization   because service It doesn't have to be a node   It is initiated at any time 
    # NOTE: you don't have to call rospy.init_node() to make calls against
    # a service. This is because service clients do not have to be
    # nodes.

    # block until the add_two_ints service is available
    # you can optionally specify a timeout
    rospy.wait_for_service('add_two_ints')
    
    try:
        # create a handle to the add_two_ints service
        add_two_ints = rospy.ServiceProxy('add_two_ints', AddTwoInts) 
        print("Requesting %s+%s"%(x, y))
        
        # simplified style
        resp1 = add_two_ints(x, y)

        # formal style
        resp2 = add_two_ints.call(AddTwoIntsRequest(x, y))

        if not resp1.sum == (x + y):
            raise Exception("test failure, returned sum was %s"%resp1.sum)
        if not resp2.sum == (x + y):
            raise Exception("test failure, returned sum was %s"%resp2.sum)
        return resp1.sum
    except rospy.ServiceException as e:
        print("Service call failed: %s"%e)

def usage():# Output usage 
    return "%s [x y]"%sys.argv[0] #argv[0] For file name 

if __name__ == "__main__":
    
    argv = rospy.myargv()
    if len(argv) == 1:# No input 
        import random
        x = random.randint(-50000, 50000)
        y = random.randint(-50000, 50000)
    elif len(argv) == 3:
        try:
            x = int(argv[1])
            y = int(argv[2])
        except:
            print(usage())
            sys.exit(1)
    else:
        print(usage())
        sys.exit(1)
    print("%s + %s = %s"%(x, y, add_two_ints_client(x, y)))

Another way of writing

#!/usr/bin/env python

from __future__ import print_function

import sys
import rospy
from beginner_tutorials.srv import *

def add_two_ints_client(x, y):
    rospy.wait_for_service('add_two_ints')
    try:
        add_two_ints = rospy.ServiceProxy('add_two_ints', AddTwoInts)
        resp1 = add_two_ints(x, y)
        return resp1.sum
    except rospy.ServiceException as e:
        print("Service call failed: %s"%e)

def usage():
    return "%s [x y]"%sys.argv[0]

if __name__ == "__main__":
    if len(sys.argv) == 3:
        x = int(sys.argv[1])
        y = int(sys.argv[2])
    else:
        print(usage())
        sys.exit(1)
    print("Requesting %s+%s"%(x, y))
    print("%s + %s = %s"%(x, y, add_two_ints_client(x, y)))

finish writing sth. py Configuration after file

Add permissions to make it executable

chmod +x scripts/add_two_ints_server.py

Explanation of this command , See https://blog.csdn.net/u012106306/article/details/80436911

And then in CMakeList Add to file

catkin_install_python(PROGRAMS scripts/add_two_ints_server.py
  DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)

Make sure you install the correct script and use the correct interpreter

rosbag Recording and playback of communication

rostopic list -v

Show the theme in use

cd ~/bagfiles
rosbag record -a 

a Express all

rosbag record /topic_name1 /topic_name2 /topic_name3

Interested in topic Record ,topic Is a slash plus topic name

rosbag record -O filename.bag /topic_name1

Specify a filename

原网站

版权声明
本文为[Captain xiaoyifeng]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110029368023.html