ROS/Python:如何在Python中访问rostopic的数据?

3

我正在尝试编写一段控制无人机的Python代码。我通过rostopic从刚体接收位置信息,并希望在我的代码中使用这些数据。我该如何在Python代码中访问这些数据?

#!/usr/bin/env python

import numpy as np
from pycrazyswarm import *

Z = 1.0

if __name__ == "__main__":
    swarm = Crazyswarm()

    # get initial position for maneuver
    swarm.allcfs.takeoff(targetHeight=Z, duration=1.0+Z)
    swarm.timeHelper.sleep(1.5+Z)

    print("press button to continue...")
    swarm.input.waitUntilButtonPressed()
    
    # After the button is pressed, I want, that the drone is aligned by a rigid body.
    # Means if the rigid body moves 1m left the drone should follow

    # finished following the rigid body. Get back landing
    swarm.allcfs.land(targetHeight=0.02, duration=1.0+Z)
    swarm.timeHelper.sleep(1.0+Z)

当按钮被按下后,我想要使用rostopic的数据。在主机上,我通过ROS的VRPN客户端发送数据。 http://wiki.ros.org/vrpn_client_ros 我想要计算“tracker name”/pose主题的数据。


这个问题可能在深度上被过于简化了。或者答案确实非常简单。您是否已经阅读了Python ROS订阅者教程 - J.P.S.
我对ROS非常陌生。我看过这个,但如果我理解正确的话,这是如何构建订阅者,但我想直接在Python脚本中访问数据并在那里使用它。 - flrnhbr1
问题需要一些代码: 请提供足够的代码,以便他人更好地理解或重现问题:https://stackoverflow.com/help/minimal-reproducible-example - D.L
对不起,你是正确的。 - flrnhbr1
你所说的“compute”,是指“process”吗?如果是这样,我想说你不能轻易地这样做。ROSTopics的消息是通过Subscribers进行处理的。否则,基本上,你需要打开一个套接字到Publishers主题(在这种情况下,每个VRPN主题),你可以从ROS master获取IP和端口。然后,你需要定期从中读取数据。因此,你可以尝试通过重新实现轮子并编写自己的循环来监听网络套接字以处理传入的消息来走过地狱。这是你的目标吗?我不能推荐这样做。 - J.P.S.
如果我在shell中使用rostopic echo /vrpn_client_ros/RigidBody/pose命令,我就可以在标准输出上得到位置和方向信息。因此,我的想法是直接从Python访问该主题的数据,将其转换为变量,并计算与无人机的相对距离。这只是一个想法,我很好奇是否可能实现。如果非常复杂,我会寻找另一种方法。 - flrnhbr1
1个回答

2

是的,您可以在Python代码中访问ROS主题数据。参考以下示例:

#!/usr/bin/env python

import numpy as np
import rospy
from pycrazyswarm import *
from geometry_msgs.msg import Pose


Z = 1.0

def some_callback(msg):
    rospy.loginfo('Got the message: ' + str(msg))

if __name__ == "__main__":
    swarm = Crazyswarm()
 
    # get initial position for maneuver
    swarm.allcfs.takeoff(targetHeight=Z, duration=1.0+Z)
    swarm.timeHelper.sleep(1.5+Z)

    print("press button to continue...")
    swarm.input.waitUntilButtonPressed()
    
    #start ros node
    rospy.init_node('my_node')
    #Create a subscriber
    rospy.Subscriber('/vrpn_client_ros/RigidBody/pose', Pose, some_callback)

    # finished following the rigid body. Get back landing
    swarm.allcfs.land(targetHeight=0.02, duration=1.0+Z)
    swarm.timeHelper.sleep(1.0+Z)

这将创建一个ROS节点,监听来自您的主题的数据,并像 rostopic echo 一样将其打印出来。


谢谢,但是rospy.loginfo(...)会将话题打印到标准输出吗? - flrnhbr1
@flrnhbr1 rospy.loginfo() 将打印到标准输出。我只是将其留在那里作为话题数据可能使用的示例。 - BTables
好的,现在我明白了。我会在回到实验室后尝试一下。 - flrnhbr1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接