publish() to a closed topic when publishing a marker
Hello guys! I am trying to subscribe a message (/position) and publish a marker. The message(/position) contains series of (x,y,z) as below :
...
---
x: -253.021528805
y: -545.031320081
z: -465.328910428
---
x: -305.591390007
y: -578.07464085
z: -511.685201552
---
...
Below is my code :
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Point, Vector3
from visualization_msgs.msg import Marker
def callback(position):
marker_pub = rospy.Publisher('route', Marker, queue_size = 100)
while not rospy.is_shutdown() :
# print(pos_vec)
marker = Marker()
marker.header.frame_id = '/map'
marker.type = marker.LINE_STRIP
marker.action = marker.ADD
#Marker scale
marker.scale.x = 0.1
marker.scale.y = 0.1
marker.scale.z = 0.1
#Marker color
marker.color.a = 1.0
marker.color.r = 1.0
marker.color.g = 1.0
marker.color.b = 0.0
#Marker orientation
marker.pose.orientation.x = 0.0
marker.pose.orientation.y = 0.0
marker.pose.orientation.z = 0.0
marker.pose.orientation.w = 1.0
#Marker line points
marker.points = []
p = Point()
p.x = position.x
p.y = position.y
p.z = position.z
marker.points.append(p)
#Publish the marker
marker_pub.publish(marker)
if __name__ == "__main__" :
rospy.init_node("marker_publisher")
rospy.Subscriber("/position", Vector3, callback)
rospy.spin()
However, I got the following errors :
[ERROR] [1521469185.321377]: bad callback: <function draw at 0x7f184ad9cb18>
Traceback (most recent call last):
File "/opt/ros/kinetic/lib/python2.7/dist-packages/rospy/topics.py", line 750, in _invoke_callback
cb(msg)
File "/home/parallels/SDC_ws/src/simon/src/marker.py", line 45, in draw
marker_pub.publish(marker)
File "/opt/ros/kinetic/lib/python2.7/dist-packages/rospy/topics.py", line 882, in publish
self.impl.publish(data)
File "/opt/ros/kinetic/lib/python2.7/dist-packages/rospy/topics.py", line 1041, in publish
raise ROSException("publish() to a closed topic")
ROSException: publish() to a closed topic
I have searched the Internet but it seems very few people had encountered this kind of problem. Can anyone give me some hint? Thank you! Sorry for any grammar mistakes.
This is probably not the answer, but please add a
rospy.sleep(1.0)
(or some similar period) to yourwhile not rospy.is_shutdown()
loop. Right now you're unnecessarily burning through 100% of your cpu cycles while publishingMarker
msgs as fast as possible.@gvdhoorn Thank you for your advice! You mean to change the *Publisher to the main function in this case? Is that what you mean?
Create all your
Publisher
andSubscriber
objects in your main, yes.