尝试使用numpy在rospy中发布单词数组
我正在尝试创建一个订阅者,它可以接受一个单词(也就是一串字符),然后把这些单词收集到一个数组里,最后发布这个数组。
我想用numpy来实现这个功能。我的数组长度必须始终保持为3,最新的单词放在最后。这样的话,我就可以在数组中保留两个之前的单词,最新的单词在最后。
这是我的代码:
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
from rospy.numpy_msg import numpy_msg
import numpy
#added
def callback(data):
global c
pub = rospy.Publisher('tag_history',numpy_msg(String))
c.append(str(data.data))
if len(c)>3:
c=c[1:4]
d=numpy.array(c,dtype=numpy.str)
print c
pub.publish(d)
rospy.sleep(0.5)
def listener():
rospy.init_node('tag_history', anonymous=True)
rospy.Subscriber("DA_tags", String, callback)
rospy.spin()
if __name__ == '__main__':
global c
c=[]
listener()
当我运行这段代码时,出现了这个错误:
[ERROR] [WallTime: 1401656539.688481] bad callback: <function callback at 0x2456758>
Traceback (most recent call last):
File "/opt/ros/hydro/lib/python2.7/dist-packages/rospy/topics.py", line 682, in _invoke_callback
cb(msg)
File "./tag_history.py", line 17, in callback
pub.publish(d)
File "/opt/ros/hydro/lib/python2.7/dist-packages/rospy/topics.py", line 802, in publish
raise ROSSerializationException(str(e))
ROSSerializationException: field data must be of type str
这个错误“field data must be of type str”是什么意思?我该如何解决它?
2 个回答
0
谢谢你指出这个问题,RodrigoOlma。我通过在ROS中创建一个自定义消息来解决了我的问题,这个消息是一个字符串数组。我这样声明它:string[] data,并把数据类型命名为StringArray。然后我把我的代码改成了这样:
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
from beginner_tutorials.msg import StringArray
def callback(data):
global c
str=StringArray()
pub = rospy.Publisher('tag_history',StringArray)
c.append(data.data)
if len(c)>3:
c=c[1:4]
str.data=c
print str
pub.publish(str)
def listener():
rospy.init_node('tag_history', anonymous=True)
rospy.Subscriber("DA_tags", String, callback)
rospy.spin()
if __name__ == '__main__':
global c
c=[]
listener()
0
这个错误的意思是,在第17行,你把一个numpy数组传给了pub.publish
,但它其实需要的是一个字符串。