Ros Notes: Python__python

Source: Internet
Author: User
Ros notes: Python

@ (ROS) [ros| python|rospy| environment variable]
Document and analyze the entire Python system of Ros to try to understand internal principles. Also learn Python programming in depth.

Ros notes Python Rospy initialization and Shutdown Messages Publishers and Subscribers Services Parameter Server Logging time E Xceptions Rospy_tutorials Sample Package

1. Rospy

Http://wiki.ros.org/rospy/Overview initialization and Shutdown

Pythonpath:

You can use the echo $PYTHONPATH view. This environment variable is used by the python under bash to search for a Python module that can be import according to the directory in this environment variable. The Python package directory for the current workspace is automatically added to this environment variable when the "$ source xxx/setup.bash" command is executed. For example, when Ros was installed "$ source/opt/ros/indigo/setup.bash"was added to the pythonpath directory "/opt/ros/indigo/lib/ Python2.7/dist-packages ". For example, the "$ source Devel/setup.bash"in your own workspace is added to the pythonpath directory "{your_catkin_ws}/devel/lib/ Python2.7/dist-packages ".? It seems setup.bash and setup.py have some relationship?

Init and shutdown Rospy.init_node (name, Anonymous=false, Log_level=rospy.info, Disable_signals=false) Rospy.on_shutdown (h) This function creates an exit callback function h for a shutdown event such as CTRL + C, and you can do something before the program exits. If you publish a message within the H function, you are not guaranteed to send the message successfully. validated in the rospy_tutorial example. Messages

Message generation custom MSG and SRV, which are automatically born into Python module source in catkin_make, stored in "{your_catkin_ws}/devel/lib/ Python2.7/dist-packages " directory. The corresponding relationship between the msg file and the Python module is: Thepackage_name/msg/foo.msg→package_name.msg.foo srv file corresponds to the Python module:package_ Name/srv/bar.srv→package_name.srv.bar

Message Initialization
Follow the Python syntax for instantiating message variables. There are three ways: no parameters, sequential parameters, keyword parameters.

No arguments

msg = Std_msgs.msg.ColorRGBA ()
msg.b=255
msg.a=121

In-order Arguments (*args)

msg = Std_msgs.msg.ColorRGBA (255.0, 255.0, 255.0, 128.0)

Keyword Arguments (**KWDS)

msg = Std_msgs.msg.ColorRGBA (b=255)

Each of the three ways has its pros and cons. The official recommendation is to use the keyword method to better accommodate the change in the definition of the message type. Publishers and Subscribers

Rospy. Publisher initialization

Pub = Rospy. Publisher (' topic_name ', std_msgs.msg.String, queue_size=10)

Other parameters: subscriber_listener=rospy. Subscribelistener
callback function when there is a subscriber connection or disconnect. Tcp_nodelay=false
Whether the function can be tcp_nodelay . Transmission low latency, but also more resource consumption. Latch=false
Whether to link the latch function. Save the last data sent, and then send the latch data when there is a new link. In favor of such as map this kind of change very small large amount of data message. Headers=none (dict)
Add a custom key-value pair (dict type) to the header when the link is established. queue_size=none (int)
This is important ... See below for a detailed explanation.

publisher.publish ()
Following the Python syntax, there are three ways to invoke the Publish () function:

An explicit method:

Pub.publish (Std_msgs.msg.ColorRGBA (255, 255, 255, 128))

Implicit (sequential parameter) methods:

Pub.publish (255, 255, 255, 128)

Implicit (keyword parameter) method:

Pub.publish (b=255)

queue_size: Send mode
Because of backward compatibility for historical reasons, the Publish () in Rospy is by default a blocking synchronous send mode. This causes the publish to die after the connection is disconnected (such as publisher and subscriber for wireless connections).
However, publish and subscribe queue_size can be written to a value greater than 0 to make publish an asynchronous pattern.

queue_size: queue_size:none (not recommended)
This will be set to the blocking synchronous transceiver mode. Queue_size:0 (not recommended)
This will be set to an infinite buffer mode, which is dangerous. queue_size:1,2,3
For sensor messages that care only about the latest data, you can set to 1;
For the system load is not high, can be processed in time message, can be set to 1,2,3. Queue_size:10 or more
In general, set to 10. Queue_size too large can cause data delays to be different.

_connection_header
After the topic connection, the header information is included in the sent data, and subscriber Subscriber can view header information in the callback function data:data._connection_header. The internal contents may include:

{' CallerID ': '/talker_38321_1284999593611 ',
' Latching ': ' 0 ',
' md5sum ': ' 992ce8a1687cec8c8bd883ec73ca41d1 ',
' Message_definition ': ' String data\n\n ',
' topic ': '/chatter ',
' type ': ' Std_msgs/string '}

The publisher talker can add a custom header content when creating topic, examples are:

Pub = Rospy. Publisher (' Topic_demo ', String, headers={' cookies ': ' Hello '}, queue_size=10) Services

Service Definitions custom MSG and SRV, which were automatically born into Python module source in catkin_make, stored in "{your_catkin_ws}/devel/lib/python2.7/ Dist-packages "directory.

The corresponding relationship between the SRV file and the Python module is as follows:

My_package/srv/foo.srv→my_package.srv.foo
My_package/srv/foo.srv→my_package.srv.foorequest
My_package/srv/foo.srv→my_package.srv.fooresponse

You need source {Your_catkin_ws}/devel/setup.bash to add the module directory to the pythonpath environment variable to use the from x.srv in the Python code The SRV module is introduced in the form of import *.

Service Proxy

Client-side uses proxy proxy to establish communication with service:

Add_two_ints = Rospy. Serviceproxy (' add_two_ints ', addtwoints)

Rospy.wait_for_service () can be used to block waiting for service to exist. There are also three ways to build the request instance: Display method, implicit (sequential parameter) method, implicit (keyword parameter) method.

Exceptions
Service may throw 3 kinds of exceptions: TypeError
The request type is not correct. Serviceexception
Connection to the remote service failed. Rosserializationexception
Data exception.

Persistent Connections
The client setting Serviceproxy () parameter persistent=true will establish a persistent connection, or the default is to connect-communicate-disconnect each time.
Persistent connections are more fragile and are not recommended.

Service Connection Headers
The server and client communication data for the service also has header information, and the client side can customize additional information to the header.

h = {' Cookies ': ' Peanut Butter '}
s = rospy. Serviceproxy (' foo ', Foo, headers=h)

Header data can be viewed in both the request and response:

Request._connection_header
Response._connection_header Parameter Server

Getting Parameters

Global_name = Rospy.get_param ("/global_name")
Relative_name = Rospy.get_param ("Relative_name")
Private_param = Rospy.get_param (' ~private_name ')
Default_param = Rospy.get_param (' Default_param ', ' default_value ')
# Fetch a group (dictionary) of parameters
gains = Rospy.get_param (' gains ')
P, I, d = gains[' P '], gains[' i ', gains[' d ']

Setting Parameters

Rospy.set_param (' a_string ', ' Baz ')
Rospy.set_param (' ~private_int ', 2)
Rospy.set_param (' List_of_floats ', [1., 2., 3., 4.])
Rospy.set_param (' Bool_true ', True)
Rospy.set_param (' gains ', {' P ': 1, ' I ': 2, ' d ': 3})

Deleting Parameters

Rospy.delete_param (Param_name)

Parameter Existence
Before executing Get_param () and Delete_param (), it is a good idea to check for the existence of parameter names. Otherwise, a keyerror exception is thrown.

Rospy.has_param (param_name) Logging Reading log Messages
Each node can send log, which can be read in 4 places: Logs

Debug Info Warn Error Fatal
StdOut X
StdErr X X X
Log file X X X X X
/rosout O X X X X
Time

Time and duration are two important concepts in rospy.
In both units, the direct print is nanosecond. Numeric in the same way:

Int32 secs
Int32 nsecs

time refers to the moment , the type is rospy. Time.
duration refers to the time period , the type is rospy. Duration.

The computational relationship between moments and periods:

Two_hours = Rospy. Duration (60*60) + Rospy. Duration (60*60)
One_hour = Rospy. Duration (2*60*60)-Rospy. Duration (60*60)
Tomorrow = Rospy. Time.now () + Rospy. Duration (24*60*60)
Negative_one_day = Rospy. Time.now ()-Tomorrow

Timer

Rospy. Timer (period, callback, Oneshot=false)

The parameter in the callback function is Event:rospy. TimerEvent. The internal properties of TimerEvent include: current_expected: Ideal value, this time the callback is called. Current_real: Realistic value, this time the callback is called. Last_expected: The last ideal value. Last_real: The last realistic value. Last_duration: Last period of callback. Exceptions

In addition to the exception types within the Python system, Rospy has the following exception exception types:
- rosexception: base class for Ros-related anomalies.
- rosserializationexception: Ros message Serialization exception.
- rosinitexception: Ros initialization exception.
- rosinterruptexception: Ros Interrupt exception.
- rosinternalexception: Ros internal anomaly.
- serviceexception: Service communication exception. 2. Rospy_tutorials Sample Package

Home: Http://wiki.ros.org/rospy_tutorials
Source: Https://github.com/ros/ros_tutorials/tree/indigo-devel/rospy_tutorials

Rospy_tutorial is a package in the Ros_tutorial group, providing a basic code example that is easy for beginners to learn. Ros_tutorial is installed when the full version of ROS is installed Desktop-full. However, to facilitate the understanding of the source code, it is recommended that you remove the ros_tutorial packages and dependent packages (Roscpp_tutorial and rospy_tutorial).

sudo apt-get remove ros-indigo-ros-tutorial

Most common concepts and examples of rospy are included in the Rospy_tutorial package. You can download this package to your own Catkin_workspace and run Catkin_make compilation.

Catkin_make will generate the MSG and SRV module py files in the devel/lib/python2.7/dist-packages/ directory.

Then, after source Devel/setup.bash, you can run it with Roslaunch or Rosrun. You can also run the py file directly in Python, the same way as Rosrun.

Note: The python file you created needs to be chmod +x your.py to increase execution permissions to be recognized by rosrun full tab.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.