pythonpublish-subscriberosrospy

How to publish/subscribe a python “list of list” as topic in ROS


I am new to ROS and rospy, and I am not familiar with non-simple data type as topic.

I want to build a ROS node as both a subscriber and publisher: it receives a topic (a list of two float64), and uses a function (say my_function) which returns a list of lists of float64, then publish this list of list as a topic.

To do this, I built a node as following:

from pymongo import MongoClient
from myfile import my_function
import rospy
import numpy as np

pub = None
sub = None

def callback(req):
    client = MongoClient()
    db = client.block
    lon = np.float64(req.b)
    lat = np.float64(req.a)
    point_list = my_function(lon, lat, db)
    pub.publish(point_list)

def calculator():
    global sub, pub
    rospy.init_node('calculator', anonymous=True)
    pub = rospy.Publisher('output_data', list)
    # Listen
    sub = rospy.Subscriber('input_data', list, callback)
    print "Calculation finished. \n"
    ros.spin()

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

I know clearly that list in Subscriber and Publisher is not a message data, but I cannot figure out how to fix it since it is not an integer nor list of integer.


Solution

  • You can complicate yourself by defining a new ros Type in the msg OR use the default and easy to implement std_msgs Type, maybe will be useful to use a json module, so you serialize the data before publishing and deserialize it back on the other side after receiving...

    the rest Pub/Sub , topic and handlers remain the same :)