程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

ROS notes (05) - Python implementation of publisher and subscriber

編輯:Python

Robot is a highly complex systematic implementation , Various sensors may be integrated into the robot ( radar 、 camera 、GPS…) And the realization of motion control , To understand the coupling , stay ROS Each function point in is a separate process , Each process runs independently .

More precisely ,ROS Is a process ( Also known as Nodes) The distributed framework of . Because these processes can even be distributed on different hosts , Different hosts work together , So as to disperse the calculated pressure . But then there is a problem : How different processes communicate ? That is, how to realize data exchange between different processes ? Here we need to introduce ROS Communication mechanism in .

ROS The basic communication mechanism in mainly has the following three implementation strategies :

  • Topic communication ( Publish subscribe mode )
  • Service communications ( Request response pattern )
  • Parameter server ( Parameter sharing mode )

Topic communication is ROS One of the most frequently used communication modes in , Topic communication is based on publish subscribe mode , That is to say : A node publishes messages , Another node subscribes to the message . The application scenarios of topic communication are also extremely extensive , For example, the following common scenario :

The robot is performing a navigation function , The sensor used is lidar , The robot will collect the information sensed by the lidar and calculate , Then the motion control information is generated to drive the robot chassis to move .

In the above scenario , Topic communication has been used more than once .

  • Take the acquisition and processing of lidar information as an example , stay ROS There is a node in the system that needs to publish the data collected by the current radar from time to time , There are also nodes in the navigation module that subscribe to and analyze radar data .
  • Take the release of sports news as an example , The navigation module will calculate the motion control information from time to time according to the data collected by the sensor and release it to the chassis , The chassis can also have a node to subscribe to the motion information and finally convert it into the pulse signal of the control motor .

And so on , Like radar 、 camera 、GPS… And so on, some sensor data collection , They also use topic communication , In other words , Topic communication is applicable to the application scenarios related to data transmission that are constantly updated .

1. Publisher Publisher

1.1 Topic model

First, we need to implement the topic model shown in the following figure , The model is shown in the figure below , There are three roles involved in the model :

  • ROS Master ( managers )
  • Talker ( Publisher )
  • Listener ( subscriber )

ROS Master Responsible for keeping Talker and Listener Registered information , And match the same topic Talker And Listener, help Talker And Listener Establishing a connection , After the connection is established ,Talker Can publish news , And the news will be Listener subscribe .

among , The topic name node is /turtle1/cmd_vel , The message types of publishers and subscribers are geometry_msgs::Twist .

1.2 Create Feature Pack

stay src Create a function package under the directory , Package name is topic_demo, The dependencies are rospystd_msgsgeometry_msgs.

[email protected]:~/project/ros/ros_demo/src$ catkin_create_pkg topic_demo rospy std_msgs geometry_msgs

Output is as follows :

turtlesim Created file topic_demo/package.xml
Created file topic_demo/CMakeLists.txt
Created folder topic_demo/src
Successfully created files in /home/wohu/project/ros/ros_demo/src/topic_demo. Please adjust the values in package.xml.

1.3 Create publisher code

Create a... Under the feature pack scripts Folder , stay scripts Create a in the file .py file .


publisher.py Code content :

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# The routine will publish turtle1/cmd_vel topic of conversation , Message type geometry_msgs::Twist
import rospy
from geometry_msgs.msg import Twist
def velocity_publisher():
# ROS Node initialization 
rospy.init_node('velocity_publisher', anonymous=True)
# Create a Publisher, The release is called /turtle1/cmd_vel Of topic, The message type is geometry_msgs::Twist, The queue length 10
turtle_vel_pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)
# Set the frequency of the cycle 
rate = rospy.Rate(10)
while not rospy.is_shutdown():
# initialization geometry_msgs::Twist Type of message 
vel_msg = Twist()
vel_msg.linear.x = 0.5
vel_msg.angular.z = 0.2
# Release the news 
turtle_vel_pub.publish(vel_msg)
rospy.loginfo("Publsh turtle velocity command[%0.2f m/s, %0.2f rad/s]",
vel_msg.linear.x, vel_msg.angular.z)
# Delay according to the cycle frequency 
rate.sleep()
if __name__ == '__main__':
try:
velocity_publisher()
except rospy.ROSInterruptException:
pass

1.4 modify Python Code executable permissions

$ chmod +x publisher.py

1.5 Run publisher code

  • perform roscore start-up ROS service
$ roscore
  • Start the little turtle simulator
    Let's open another terminal , Execute the following command
$ rosrun turtlesim turtlesim_node
  • Run publisher code
$ rosrun topic_demo publisher.py

rosrun Followed by the created package name topic_demo And publisher's files publisher.py

The demonstration results are as follows :

If an error is reported after operation :

$ rosrun topic_demo publisher.py
[rosrun] Couldn't find executable named publisher.py below /home/wohu/project/ros/ros_demo/src/topic_demo [rosrun] Found the following, but they're either not files,
[rosrun] or not executable:
[rosrun] /home/wohu/project/ros/ros_demo/src/topic_demo/scripts/publisher.py
[email protected]:~/project/ros/ros_demo/src$

explain publisher.py File permissions have not been modified .

2. subscriber subscriber

Same as before , In Feature Pack topic_demo The directory src Store subscriber files in the directory


The subscriber code implements

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This routine will subscribe to /turtle1/pose topic of conversation , Message type turtlesim::Pose
import rospy
from turtlesim.msg import Pose
def poseCallback(msg):
rospy.loginfo("Turtle pose: x:%0.6f, y:%0.6f", msg.x, msg.y)
def pose_subscriber():
# ROS Node initialization 
rospy.init_node('pose_subscriber', anonymous=True)
# Create a Subscriber, The subscription is called /turtle1/pose Of topic, Register callback function poseCallback
rospy.Subscriber("/turtle1/pose", Pose, poseCallback)
# Loop waiting for callback function 
rospy.spin()
if __name__ == '__main__':
pose_subscriber()

Open them in turn 3 Terminals execute the following commands :

$ roscore
$ rosrun turtlesim turtlesim_node
$ rosrun turtlesim turtle_teleop_key

Start the subscriber with the following command

$ rosrun topic_demo pose_subscriber.py

Pass on 、 Next 、 Left 、 Right Control turtle movement , And then you can see pose_subscriber.py The script outputs the turtle's location information .

3. Other

Tested and verified ,publisher.py The code can also be placed in src Under the table of contents


After changing the script name, run the following command , It can also run .

$ rosrun topic_demo publisher_demo.py

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved