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

ROS / Python: How to access data from a rostopic in python?

我正在尝试编写 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 我想计算“跟踪器名称”/姿势主题的数据

是的,您可以在 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 一样将其打印出来。