flrnhbr1
flrnhbr1

Reputation: 33

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

I'm trying to write a python code, that controls a drone. I receive the position from a Rigid-body trough a rostopic, and I want to use that data in my code. How can i access it in my python code?

#!/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)

So after the button is pressed, I would like to use the data of the rostopic. On the host i send the data over the VRPN client of ROS http://wiki.ros.org/vrpn_client_ros I want to compute the data of the "tracker name"/pose topic

Upvotes: 3

Views: 5068

Answers (1)

BTables
BTables

Reputation: 4843

Yes, you can access the ROS topic data in your Python code. Take the following example:

#!/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)

This will create a ROS node, listen to the data coming from your topic, and print it out much like rostopic echo would.

Upvotes: 2

Related Questions