LucaT3X
LucaT3X

Reputation: 11

Publisher/Subscriber ROS Python

Good evening, I need to create a publisher that sends pointcloud2 after reading them from my previously acuisite bag. This is to simulate realtime execution.

In rqt_graph, everything seems to be connected correctly but pub and sub don't seem to communicate at all.

This is my publisher:

#!/usr/bin/env python
import rospy

from sensor_msgs.msg import PointCloud2
import std_msgs.msg
import sensor_msgs.point_cloud2 as pcl2
import rosbag

def talker(msg):
    pub = rospy.Publisher('chatter', PointCloud2)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(1) #hz
    rospy.loginfo(msg)
    pub.publish(msg)
    rate.sleep()
 
if __name__ == '__main__':
    bag = rosbag.Bag('bag2.bag')
    
    for msg in bag.read_messages(topics=['/d435/depth/color/points']):
        talker(msg)

And this is my subscriber:

#!/usr/bin/env python
import rospy
from sensor_msgs.msg import PointCloud2
import std_msgs.msg
import sensor_msgs.point_cloud2 as pcl2

def callback(data):
   #rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
    print("ptCloud received")

    ptc = Point

def listener():
   rospy.init_node('listener', anonymous=True)

   rospy.Subscriber("chatter", PointCloud2, callback)
   rospy.spin()

if __name__ == '__main__':
   listener()

Could someone help me? Trying with strings using

from std_msgs.msg import String

the communication worked, but not with pointclouds. I'm a newbie to ROS, help!

Upvotes: 0

Views: 2751

Answers (2)

LucaT3X
LucaT3X

Reputation: 11

It works by doing this!

def Talk(self):
    for topic, msg, t in self.bag_file.read_messages(topics=['/d435/depth/color/points']):
        
        self.pub.publish(msg)  
        self.rate.sleep()       

Upvotes: 0

ehsana94
ehsana94

Reputation: 1

On the talker side, you are calling rospy.init_node multiple times. The node initialization should be done exactly once. Using a Python "Class" you can solve the problem this way:

#!/usr/bin/env python
import rospy

from sensor_msgs.msg import PointCloud2
import std_msgs.msg
import sensor_msgs.point_cloud2 as pcl2
import rosbag

class Talker():
    def __init__(self, bag_file):
        self.pub = rospy.Publisher('chatter', PointCloud2)
        self.rate = rospy.Rate(1) #hz
        self.bag_file = bag_file

    def Talk(self):
        for msg in self.bag_file.read_messages(topics=['/d435/depth/color/points']):
            self.pub.publish(msg)
            self.rate.sleep()

if __name__ == '__main__':
    rospy.init_node('talker', anonymous=True)
    bag = rosbag.Bag('bag2.bag')
    talker = Talker(bag)
    talker.Talk()

Upvotes: 0

Related Questions