如何在ROS中将值传递给发布者?

时间:2019-06-21 10:13:33

标签: python publish-subscribe ros

我目前正在尝试编写一个Python ROS程序,该程序可以作为ROS节点(使用rosrun)执行,以实现在单独的Python文件arm.py(可在https://github.com/nortega1/dvrk-ros/blob/44c8604b6c120e91f5357e7fd3649a8f7936c504/dvrk_python/src/dvrk/arm.py中声明)中定义的defs。该程序最初检查手臂的当前笛卡尔位置。随后,当程序提供了手臂必须经过的一系列点时,该程序将计算一个多项式方程,并在给定x值范围的情况下,该程序将对该方程进行评估以找到相应的y值。

arm.py文件中,有一个发布者set_position_cartesian_pub,其设置手臂的笛卡尔位置的方法如下:

self.__set_position_cartesian_pub = rospy.Publisher(self.__full_ros_namespace + '/set_position_cartesian', Pose, latch = True, queue_size = 1)

但是,我不确定如何将x和y值(稍后将计算z值)传递给我正在创建的python程序中的发布者。这是我到目前为止所写的:

#!/usr/bin/env python

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(data.pose)

def currentPositionListener():
    rospy.init_node('currentPositionListener', anonymous=True)
    rospy.Subscriber('/dvrk/PSM1/position_cartesian_current', PoseStamped, callback)
    rospy.spin()

def lagrange(f, x):
    total = 0
    n = len(f)
    for i in range(n):
        xi, yi = f[i]

        def g(i, n):
            g_tot = 1
            for j in range(n):
                if i == j:
                    continue
                xj, yj = f[j]
                g_tot *= (x - xj) / float(xi - xj)

            return g_tot

        total += yi * g(i, n)
    return total

def newPositionListener():
    rospy.Subscriber('/dvrk/PSM1/set_position_cartesian', PoseStamped, trajectoryMover)
    rospy.spin()

def trajectoryMover(data):
    points =[(0,0),(45,30),(23,10), (48,0)]
    xlist = [i for i in range(100)]
    ylist = [lagrange(points, xlist[i]) for i in range(100)]
    for x, y in zip(xlist, ylist):
        data.pose.x = x
        data.pose.y = y
        data.pose.z = 0

if __name__ == '__main__':
    currentPositionListener()
    newPositionListener()

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

问题出在.trajectoryMover()中:

如果您要发布Pose消息,则应创建一条Pose消息,并按照以下代码段的位置填写它:

from geometry_msgs.msg import Pose


def trajectoryMover(data):
    pose = Pose()
    self.__set_position_cartesian_pub = rospy.Publisher(
        self.__full_ros_namespace + '/set_position_cartesian',
        Pose, latch = True, queue_size = 1
    )

    points =[(0,0),(45,30),(23,10), (48,0)]
    xlist = [i for i in range(100)]
    ylist = [lagrange(points, xlist[i]) for i in range(100)]
    for x, y in zip(xlist, ylist):
        pose.x = x
        pose.y = y
        pose.z = 0
        self.__set_position_cartesian_pub.publish(pose)

[注意]:

  • .spin()足以满足您的代码要求。
  • 我没意识到你需要什么数据。