def post_topic_message(topic_name):
"""
POST /api/<version>/topic/<topic_name>
POST a message to a ROS topic by name.
Requires a JSON payload of shape: ``[x, y, z]``. The values of the JSON
array must match the argument types of the topic's type constructor.
"""
topic_name = "/" + topic_name
# Get the list of ROS topics in the system.
# Returns a list of [topic, type_string] pairs.
topic_list = rostopic_master.getTopicTypes()
# Find topic in list (this is Python's approach to find).
try:
topic_match = next(x for x in topic_list if x[0] == topic_name)
except StopIteration:
# If we can't find the topic, return early (400 bad request).
return error("Topic does not exist")
json = request.get_json(silent=True)
args = json if json else []
try:
# Get the message type constructor for the topic's type string.
MsgType = get_message_class(topic_match[1])
pub = rospy.Publisher(topic_name, MsgType, queue_size=10)
# Unpack JSON list and pass to publish.
# pub.publish() will pass the list of arguments to the message
# type constructor.
pub.publish(*args)
except Exception, e:
return error("Wrong arguments for topic type constructor")
return success("Posted message to topic")
评论列表
文章目录