20. ROS programming learning: various advanced communication uses python

Table of contents

1. Advanced use of python initialization node api for topic communication

1. Initialize node code prompts and python topic communication routines

2. Initialize the node to use advanced

2. Topic communication publisher object advanced

Three, return function


Learning reference: Zhao Xuzuo's ROS tutorial at Station B

1. Advanced use of python initialization node api for topic communication

1. Initialize node code prompts and python topic communication routines

def init_node(name, argv=None, anonymous=False, log_level=None, disable_rostime=False,disable_rosout=False, disable_signals=False, xmlrpc_port=0, tcpros_port=0):

Use the previously learned topic communication python to achieve

(4 messages) 3. ROS programming learning: topic communication python_ mechanical professional computer Xiaobai's blog - CSDN blog icon-default.png?t=M85Bhttps://blog.csdn.net/wzfafabga/article/details/127107231

2. Initialize the node to use advanced

Function : ROS initialization
parameters : name ---- set the node name, the node name must be unique, argv=None ---- encapsulate the parameters passed when the node is called, anonymous=False ---- can generate a random number suffix for the node , which can solve the problem of shotdown of the previous node caused by the same node starting twice with the same node name.
Use :
1.argv
can be used to pass parameters according to the grammar format specified in ROS, and ROS can parse and use them.

When starting the node, _A:=1000 is added, the function is to add the key name A in the parameter server, and the key value is 1000

rosmelodic@rosmelodic-virtual-machine:~/catkin_ws$ rosrun sub_pub pub_p.py _A:=1000

Refer to the parameter server python implementation:

(4 messages) 11. ROS programming learning: parameter management mechanism python icon-default.png?t=M85Bimplementation

List all parameters of the parameter server.

rosparam list

 It can be seen that the key name is /pub_py/A

rosmelodic@rosmelodic-virtual-machine:~/catkin_ws$ rosparam list
/pub_py/A
/rosdistro
/roslaunch/uris/host_rosmelodic_virtual_machine__41671
/rosversion
/run_id

Find the key value of the specified key name

rosparam get /pub_py/A 

key value is 1000

rosmelodic@rosmelodic-virtual-machine:~/catkin_ws$ rosparam get /pub_py/A 
1000

It can be seen that when starting a node, adding code that conforms to a specific syntax can be parsed by ROS and realize the function. This is because the incoming parameters are received by the argv formal parameter (a list) of the initialization node, and the function is realized. The following is a part of the code encapsulated by the initialization function. It can be seen that the argv passed in is the argv of the system. If the operation is relative to argv, import sys.

    if argv is None:
        argv = sys.argv

The same argv is also applied in the client optimization of service communication

icon-default.png?t=M85B(4 messages ) 8. ROS programming learning: custom service data python calls

If started twice at the same time

rosmelodic@rosmelodic-virtual-machine:~/catkin_ws$ rosrun sub_pub pub_p.py

The terminal of the first node started will prompt:

shutdown request: [/pub_py] Reason: new node registered with same name

 Modify the initialization node:

pub_p.py 

#! /usr/bin/env python
# -*- coding: UTF-8 -*-

import rospy
from std_msgs.msg import String

if __name__ == "__main__":
    rospy.init_node(name = "pub_py", anonymous = True) 
    pub = rospy.Publisher (name="chongfu_py", data_class = String, queue_size=10)
    msg = String()
    rate = rospy.Rate(1)
    count = 0
    rospy.sleep(3)
    while not rospy.is_shutdown():
        count += 1
        if(count <= 10):
            msg.data = "hello" + str(count)
            pub.publish(msg)
            rospy.loginfo("发布数据:%s", msg.data)
        else:
            rospy.signal_shutdown("退出循环")
        rate.sleep()

from 

rospy.init_node(name = "pub_py") 

change into

rospy.init_node(name = "pub_py", anonymous = True) 

Start the nodes twice at the same time.

rosrun sub_pub pub_p.py 
rosrun sub_pub pub_p.py 

 View all startup nodes.

rosnode list

 The node is followed by a random number, so that the same node starts with a different node name, and will not cause the first started node to be shotdown.

rosmelodic@rosmelodic-virtual-machine:~/catkin_ws$ rosnode list 
/pub_py_20907_1667219173751
/pub_py_20951_1667219175884
/rosout

2. Topic communication publisher object advanced

The function corresponds to C++, mainly dealing with the Boolean value of the latch.

Official explanation : @param latch: If True, the last published message is "latch", which means that any future subscribers will receive the message immediately after connecting.

@param latch: If True, the last message published is 'latched', meaning that any future subscribers will be sent that message immediately upon connection.

pub_p.py 

#! /usr/bin/env python
# -*- coding: UTF-8 -*-

import rospy
from std_msgs.msg import String

if __name__ == "__main__":
    rospy.init_node(name = "pub_py", anonymous = True) 
    pub = rospy.Publisher(name="chongfu_py", data_class = String, queue_size= 10, latch = True)
    msg = String()
    rate = rospy.Rate(1)
    count = 0
    rospy.sleep(3)
    while not rospy.is_shutdown():
        count += 1
        if(count <= 10):
            msg.data = "hello" + str(count)
            pub.publish(msg)
            rospy.loginfo("发布数据:%s", msg.data)
        # else:
        #     rospy.signal_shutdown("退出循环")
        rate.sleep()

Modify :

Publisher's creation before modification:

pub = rospy.Publisher(name="chongfu_py", data_class = String, queue_size= 10)

Publisher creation modified:

pub = rospy.Publisher(name="chongfu_py", data_class = String, queue_size= 10, latch = True)

test :

Start the publisher

rosrun sub_pub pub_p.py

Stop publishing messages when the loop reaches ten times. If latch is False, subscribers will not receive any messages when they start at this time.

rosmelodic@rosmelodic-virtual-machine:~/catkin_ws$ rosrun sub_pub pub_p.py
[INFO] [1667221214.189930]: 发布数据:hello1
[INFO] [1667221214.191267]: 发布数据:hello2
[INFO] [1667221215.193347]: 发布数据:hello3
[INFO] [1667221216.192330]: 发布数据:hello4
[INFO] [1667221217.192395]: 发布数据:hello5
[INFO] [1667221218.192578]: 发布数据:hello6
[INFO] [1667221219.193270]: 发布数据:hello7
[INFO] [1667221220.192703]: 发布数据:hello8
[INFO] [1667221221.193090]: 发布数据:hello9
[INFO] [1667221222.192738]: 发布数据:hello10

Since the latch of this program is True, the subscriber has received the last published message. The principle is the same as the c++ implementation, except that ROS provides a python interface.

rosmelodic@rosmelodic-virtual-machine:~/catkin_ws$ rosrun sub_pub sub_p.py 
[INFO] [1667221300.839786]: 订阅的数据:hello10

Three, return function

In python, there is only spin that keeps turning back, and there is no function spinonce that turns back once.

rospy.spin()

Same as C++, when running to the callback function, it will keep looping in the callback function, and the code behind the callback function will not run.

Guess you like

Origin blog.csdn.net/wzfafabga/article/details/127622317