File size: 6,248 Bytes
9869d0d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | import rclpy
from rclpy.node import Node
from NAME_OF_YOUR_PKG.navigator import Navigator, TaskResult
from geometry_msgs.msg import PoseStamped
from visualization_msgs.msg import Marker, MarkerArray
from rclpy.qos import QoSProfile, DurabilityPolicy
import yaml
import math
import time
from ament_index_python.packages import get_package_share_directory
import os
def euler_to_quaternion(yaw, pitch, roll):
"""Converte ângulos Euler para quaternião."""
cy = math.cos(yaw * 0.5)
sy = math.sin(yaw * 0.5)
cp = math.cos(pitch * 0.5)
sp = math.sin(pitch * 0.5)
cr = math.cos(roll * 0.5)
sr = math.sin(roll * 0.5)
q = [0.0] * 4
q[0] = cy * cp * sr - sy * sp * cr # x
q[1] = sy * cp * sr + cy * sp * cr # y
q[2] = sy * cp * cr - cy * sp * sr # z
q[3] = cy * cp * cr + sy * sp * sr # w
return q
class WaypointFollower(Node):
"""
Nó para carregar uma rota de um arquivo YAML e usar o ScoutNavigator para executá-la.
"""
def __init__(self):
super().__init__('waypoint_follower')
self.navigator = ScoutNavigator()
# Define o perfil de QoS para "latched"
qos_profile = QoSProfile(
depth=1,
durability=DurabilityPolicy.TRANSIENT_LOCAL)
# Publisher para os marcadores dos waypoints
self.marker_publisher = self.create_publisher(MarkerArray, 'waypoints', qos_profile)
# Ativa os nós do Nav2 usando o método simplificado do ScoutNavigator
self.navigator.startup()
# Pequena pausa para garantir que os tópicos estejam prontos após a ativação
self.get_logger().info('Aguardando 2 segundos para a inicialização dos tópicos...')
time.sleep(2)
self.get_logger().info('ScoutNavigator está pronto para uso.')
def publish_waypoint_markers(self, waypoints):
"""
Publica os waypoints como uma MarkerArray para visualização no RViz.
"""
marker_array = MarkerArray()
for i, waypoint in enumerate(waypoints):
marker = Marker()
marker.header.frame_id = 'map'
marker.header.stamp = self.get_clock().now().to_msg()
marker.ns = "waypoints"
marker.id = i
marker.type = Marker.ARROW
marker.action = Marker.ADD
marker.pose = waypoint.pose
marker.scale.x = 0.5 # Comprimento da seta
marker.scale.y = 0.1 # Largura da seta
marker.scale.z = 0.1 # Altura da seta
marker.color.a = 1.0 # Alpha
marker.color.r = 0.0 # Red
marker.color.g = 1.0 # Green
marker.color.b = 0.0 # Blue
marker_array.markers.append(marker)
self.get_logger().info(f'Publicando {len(waypoints)} marcadores de waypoint.')
self.marker_publisher.publish(marker_array)
def follow_route_from_yaml(self, yaml_path):
"""
Carrega waypoints de um arquivo YAML e os envia para o Nav2.
"""
self.get_logger().info(f"Carregando rota do arquivo: {yaml_path}")
try:
with open(yaml_path, 'r') as file:
route_data = yaml.safe_load(file)
except (IOError, yaml.YAMLError) as e:
self.get_logger().error(f"Erro ao ler ou processar o arquivo YAML: {e}")
return
if not route_data or 'waypoints' not in route_data:
self.get_logger().error("Arquivo YAML não contém a chave 'waypoints' ou está vazio.")
return
waypoints = []
for wp_data in route_data['waypoints']:
pose_data = wp_data.get('pose', {})
position = pose_data.get('position', {})
orientation = pose_data.get('orientation', {})
waypoint = PoseStamped()
waypoint.header.frame_id = 'map'
waypoint.header.stamp = self.get_clock().now().to_msg()
waypoint.pose.position.x = float(position.get('x', 0.0))
waypoint.pose.position.y = float(position.get('y', 0.0))
if 'theta' in orientation:
q = euler_to_quaternion(orientation['theta'], 0, 0)
waypoint.pose.orientation.x = q[0]
waypoint.pose.orientation.y = q[1]
waypoint.pose.orientation.z = q[2]
waypoint.pose.orientation.w = q[3]
else:
waypoint.pose.orientation.x = float(orientation.get('x', 0.0))
waypoint.pose.orientation.y = float(orientation.get('y', 0.0))
waypoint.pose.orientation.z = float(orientation.get('z', 0.0))
waypoint.pose.orientation.w = float(orientation.get('w', 1.0))
waypoints.append(waypoint)
if not waypoints:
self.get_logger().info("Nenhum waypoint encontrado para seguir.")
return
# Publica os marcadores dos waypoints
self.publish_waypoint_markers(waypoints)
self.get_logger().info(f"Enviando {len(waypoints)} waypoints para o Nav2.")
self.navigator.goThroughPoses(waypoints)
# Verifica o status da tarefa
while not self.navigator.isTaskComplete():
feedback = self.navigator.getFeedback()
if feedback:
self.get_logger().info(f'Poses restantes: {feedback.number_of_poses_remaining}')
time.sleep(1)
result = self.navigator.getResult()
if result == TaskResult.SUCCEEDED:
self.get_logger().info("Rota concluída com sucesso!")
elif result == TaskResult.CANCELED:
self.get_logger().warn("A rota foi cancelada.")
elif result == TaskResult.FAILED:
self.get_logger().error("A rota falhou.")
else:
self.get_logger().error("Resultado da rota desconhecido!")
def main(args=None):
rclpy.init(args=args)
share_dir = get_package_share_directory('NAME_OF_YOUR_PKG')
route_yaml_path = os.path.join(share_dir, 'params', 'route.yaml')
waypoint_follower = WaypointFollower()
waypoint_follower.follow_route_from_yaml(route_yaml_path)
rclpy.shutdown()
if __name__ == '__main__':
main()
|