pythonrosrospy

Subscriber receives String with 'Data: ""'


I have a publisher that sends a number from 0 to 6, or None. So I convert it to a string before sending it to make sure it can send the "None" value.

        self.pub = rospy.Publisher("jugada", String, queue_size=1)
        self.pub.publish(str(col))

and then i want the subscriber to receive it:

    class clicker(object):
        def __init__(self):
            self.jugada_sub = rospy.Subscriber("jugada",String, self.callback)

        def callback(self, data): 
            jugada = data
            print(jugada)

and instead of printing:

3

instead it prints

Data: "3"

which breaks up the rest of the code I need that number (or None) for. I tried to str(data) and then try to edit the string to remove the 'Data:' part, but that doesn't work. I tried to google it for like an hour, but can't figure out how to get rid of the "Data:" or how to change the message type to send only the string.

PS Later in the code i do:

        if jugada != "None":
            jugada = int(jugada)

and I get the error: int() argument must be a string

and if i do jugada = str(data) at the beginning, i get the error: Invalid literal for int() with base 10: 'data: "3"'


Solution

  • ROS messages are defined as classes, not built in types. For std_msg types you need to retrieve the data directly using the .data attribute. Take the following example:

    def callback(self, data): 
        jugada = data.data
        print(jugada)
    

    Another couple of notes. When publishing data it is usually a best practice to not pass the raw type directly to .publish and instead use a message type as follows:

    output_msg = String()
    output_msg.data = 'some string val'
    pub.publish(output_msg)
    

    Lastly, if you're publishing integer data you should use one of the integer types: Int8, Int16, Int32, etc