[Python] It was very convenient to use a Python class for a ROS program.

Introduction

Recently, I've been touching ROS little by little, and when implementing a node in Python, I'd like to introduce a problem with ** implementing publisher and subscriber in one node **. I was able to clean it up by using a Python class. It is assumed that you have enough ROS knowledge and a little object-oriented knowledge to make a package by yourself.

An implementation example is [here](https://qiita.com/drafts/d15d52856188120647f4/edit#publish-%E3%81%A8-subscribe%E3%82%92%E5%90%8C%E6%99%82% E3% 81% AB1% E3% 81% A4% E3% 81% AE% E3% 83% 8E% E3% 83% BC% E3% 83% 89% E3% 81% A7% E3% 82% 84% E3% 82% 8B)

What I wanted to do

I want to subscribe to the data on this topic, process it, and publish it to that topic

I think there is something like that. Did you find out wrong ** What should I do when using subscriber and publisher at the same time on one node **? I was quite addicted to it.

ROS Publisher and Subscriber implemented in Python

ROS.org and the popular Publisher and Subscriber tutorials often look like this: I think.

Publisher (also known as talker)

Specify the topic name and message type with rospy.Publisher and publish withpub.publish ().

talker.py


#rospy and message import
import rospy
import std_msgs.msg import String

def talker():
    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('talker', anonymous=True)

    #Processing continues
    
    pub.publish(data)

if __name__ == '__main__':
    try:
         talker()
    except rospy.ROSInterruptException: pass

Subscriber (also known as listener)

In rospy.Subscriber, specify the topic name, data type, and specify the callback function, and perform the post-subscribe processing with the callback function.

listener.py


#rospy and message import
import rospy
from std_msgs.msg import String

def callback(data):
    #subscribe callback function
    
def listener():
    rospy.init_node('listener', anonymous=True)

    rospy.Subscriber("chatter", String, callback)

    rospy.spin()
        
if __name__ == '__main__':
    listener()

Publish and Subscribe on one node at the same time

After the tutorial, I understood the mechanism of Publish and Subscribe. Then, let's create a new node and do Publish and Subscribe at the same time. I thought, and when I implemented it, should I publish it in the callback function of rospy.Subscriber? I was worried because I couldn't clean the code.

At that time, I was looking at this article and I also saw the code /main.py#L10) By the way, it was very beautiful, so I used it as a reference. I didn't use Python classes in the tutorial above, but they can be nicely implemented.

Create Publisher and Subscriber with __init__ (), and process in the flow of callback function and publish function. When you run it, create a class in the main part and you're done!

test.py


import rospy
from std_msgs.msg import String

class testNode():
    def __init__(self):
        #Creating a Subscriber
        self.sub = rospy.Subscriber('topic name', String, self.callback)
        #Creating Publisher
        self.pub = rospy.Publisher('topic name', String, queue_size=1)

    def callback(self, data):
        #Write the processing of the callback function

        Publisher(data)

    def Publisher(self, data):
        self.pub.publish(data)

    def function(self, data):
        #Write if there is any other processing

        return data

if __name__ == '__main__':
    rospy.init_node('test_node')

    time.sleep(3.0)
    node = testNode()

    while not rospy.is_shutdown():
        rospy.sleep(0.1)

in conclusion

I personally thought that object-oriented programming was difficult to get started with, but I was able to write it conveniently and neatly. Some people have made templates with like this!

I didn't have the information I wanted to search for "ros python publish subscribe same node". .. .. I'm too new to ROS, so am I doing something wrong? Please let me know if something is wrong.

reference

For machine learning of ROS, I made a package to flow joint angles from OpenPose with Topic ROS course 31 python basics ROS program template Write a Simple Publisher and Subscriber (Python)

Recommended Posts

[Python] It was very convenient to use a Python class for a ROS program.
Convenient to use matplotlib subplots in a for statement
How to use the __call__ method in a Python class
Use a scripting language for a comfortable C ++ life-OpenCV-Port Python to C ++-
How to write a Python class
[Introduction to Python] How to use the in operator in a for statement?
[Introduction to Python] How to use class in Python?
[Python] How to make a class iterable
[Python] Organizing how to use for statements
How to use __slots__ in Python class
How to use "deque" for Python data
I made a Docker container to use JUMAN ++, KNP, python (for pyKNP).
Use Python from Java with Jython. I was also addicted to it.
Tips for Python beginners to use Scikit-image examples for themselves 3 Write to a file
[Python] I was hooked for an hour trying to use list comprehensions
It is convenient to use Layers when putting a library on Lambda
It is more convenient to use csv-table when writing a table with python-sphinx
Creating a Python document generation tool because it is difficult to use sphinx
Let's write a Python program and run it
python: Use your own class for numpy ndarray
Tips for Python beginners to use the Scikit-image example for themselves 7 How to make a module
How to use pip, a package management system that is indispensable for using Python
[Python] I want to use only index when looping a list with a for statement
A program that asks for a few kilograms to reach BMI and standard weight [Python]
A python script that wants to use Mac startup / end time for attendance management
How to use python multiprocessing (continued 3) apply_async in class with Pool as a member
Use data class for data storage of Python 3.7 or higher
Create a dataset of images to use for learning
[BigQuery] How to use BigQuery API for Python -Table creation-
[For beginners] How to use say command in python!
[Introduction to python] A high-speed introduction to Python for busy C ++ programmers
From buying a computer to running a program with python
[Python] A convenient library that converts kanji to hiragana
I was able to repeat it in Python: lambda
It was a painful memory when I was told TypeError: must be type, not class obj when trying to inherit with Python.
I made a function to crop the image of python openCV, so please use it.
I made a tool that makes it convenient to set parameters for machine learning models.
[Python] What is a tuple? Explains how to use without tuples and how to use it with examples.
It may be a problem to use Japanese for folder names and notebook names in Databricks
Tips for Python beginners to use Scikit-image examples for themselves 4 Use GUI
Experiment to collect tweets for a long time (Program preparation (1))
[python] How to use the library Matplotlib for drawing graphs
How to run a Python program from within a shell script
Experiment to make a self-catering PDF for Kindle with Python
A simple way to avoid multiple for loops in Python
How to make a Python package (written for an intern)
How to use machine learning for work? 03_Python coding procedure
Experiment to collect tweets for a long time (program preparation (2))
Experiment to collect tweets for a long time (Program preparation (5))
I didn't know how to use the [python] for statement
Tips for Python beginners to use the Scikit-image example for themselves
A very convenient way to give a presentation on Jupyter Notebook
A python beginner tried to intern at an IT company
Create a virtual environment for python on mac [Very easy]
[Python] What is a slice? An easy-to-understand explanation of how to use it with a concrete example.
Let's use a scripting language for a comfortable C ++ life 6-How about developing a program as a library for Python?
[Python] How to use the for statement. A method of extracting by specifying a range or conditions.
python3: How to use bottle (2)
A road to intermediate Python
[Python] How to use list 1
How to use Python argparse