ROS如何使用从一个回调函数到另一个回调函数的值

2024-09-30 12:16:32 发布

您现在位置:Python中文网/ 问答频道 /正文

对不起,英语不是我的母语。我希望你能正确理解我的问题

我正在使用Ubuntu 18.04和ROS Melodic。我试图从mapCallbackodometryCallback函数中获取数据,并在SampleTree函数中使用这些值。当我运行下面的代码时,我希望返回frontCones数组,但我的输出是空数组。如何使SampleTree函数获取在mapCallbackodometryCallback函数中发布的值,并在循环中使用此数据返回数组

这是我的密码:

# !/usr/bin/python

import rospy

from nav_msgs.msg import Odometry
from egn_messages.msg import Map
from tf.transformations import euler_from_quaternion

odometry = Odometry()
map = Map()


class Test:
    def __init__(self):
        rospy.init_node('test_node')

        rospy.Subscriber('/map1', Map, self.mapCallback)
        rospy.Subscriber('/odometry', Odometry, self.odometryCallback)
        self.map = []

        self.carPosX = 0.0
        self.carPosY = 0.0
        self.carPosYaw = 0.0

    def odometryCallback(self, odometry):
        orientation_q = odometry.pose.pose.orientation
        orientation_list = [orientation_q.x, orientation_q.y,
                            orientation_q.z, orientation_q.w]
        (roll, pitch, yaw) = euler_from_quaternion(orientation_list)
        self.carPosX = odometry.pose.pose.position.x
        self.carPosY = odometry.pose.pose.position.y
        self.carPosYaw = yaw

    def mapCallback(self, map):
        self.map = map

    def SampleTree(self):
        if not self.map:
            print
            'map is empty, return'
            return

        frontConesDist = 12
        frontCones = self.getFrontConeObstacles(frontConesDist)
        print(frontCones)

    def getFrontConeObstacles(self, frontDist):
        if not map:
            return []

        headingVector = [1.0, 0]

        behindDist = 0.5
        carPosBehindPoint = [self.carPosX - behindDist * headingVector[0], self.carPosY - behindDist * headingVector[1]]

        frontDistSq = frontDist ** 2

        frontConeList = []
        for cone in map.cones:
            if (headingVectorOrt[0] * (cone.y - carPosBehindPoint[1]) - headingVectorOrt[1] * (
                    cone.x - carPosBehindPoint[0])) < 0:
                if ((cone.x - self.carPosX) ** 2 + (cone.y - self.carPosY) ** 2) < frontDistSq:
                    frontConeList.append(cone)
        return frontConeList


if __name__ == "__main__":
    inst = Test()
    inst.SampleTree()
    try:
        rospy.spin()
    except KeyboardInterrupt:
        print("Shutting down")


Tags: 函数fromimportselfmapifdefrospy
1条回答
网友
1楼 · 发布于 2024-09-30 12:16:32

通过在回调函数中打印新的映射信息,确保self.map Check中的值实际上正在更新

还添加:

if __name__ == "__main__"():
    inst = Test()
    inst.SampleTree()
    try:
        rospy.spin()
    except KeyboardInterrupt:
        print("Shutting down")

除非中断,否则rospy.spin()将在无限循环中执行代码

建议:

您可以命名该函数

def getFrontConeObstacles(self, frontDist):

而不是

def getFrontConeObstacles(self, map, frontDist):

因为您可以在类中轻松访问self.map

相关问题 更多 >

    热门问题