Search code examples
pythonpublish-subscriberos

How to Automate terminal commands of ROS using a python script


I am currently trying to write an executable program in python that runs the following ROS command: rostopic echo dvrk/PSM1/position_cartesian_current however despite reading the ROS Tutorials, I am unsure how to go about doing this. Within a file called arm.py the following subscriber and definition already exist:

rospy.Subscriber(self.__full_ros_namespace + '/position_cartesian_current', PoseStamped, self.__position_cartesian_current_cb)

def __position_cartesian_current_cb(self, data):
        self.__position_cartesian_current = posemath.fromMsg(data.pose)

Am I supposed to reuse this subscriber and definition in the new automated python script? After obtaining the current Cartesian position, the robot will subsequently be moved to a different position, which can currently be accomplished using ROS commands in the terminal, however, the aim is to write a python script that automates these commands. Any help would be greatly appreciated!

import rospy
from tf import transformations
from tf_conversions import posemath
from std_msgs.msg import String, Bool, Float32, Empty, Float64MultiArray
from geometry_msgs.msg import Pose, PoseStamped, Vector3, Quaternion, Wrench, WrenchStamped, TwistStamped

def callback(data):
  rospy.loginfo(rospy.get_caller_id() + data.data)

def listener():
    rospy.init_node('listener', anonymous=True)
    rospy.Subscriber(self.__full_ros_namespace + '/position_cartesian_current', PoseStamped, callback)
    rospy.spin()

if __name__ == '__main__':
    listener()

Solution

  • What you want to do is write a Python ROS Node to subscribe to the topic and implement your logic.

    You can do so by following this guide.

    The main idea is to subscribe to the position topic, get the relevant data in the callback function and publish, in that same callback, the commands you usually perform by command line.

    To reproduce a simple rostopic echo, you can just print the values you receive in the callback.