Download experiments/rtabmap/scripts/follow_route.py from jacodd/SynthField: direct link, hf CLI and curl.
- Browser
- Download file 6.25 kB
-
https://huggingface.co/datasets/jacodd/SynthField/resolve/main/experiments/rtabmap/scripts/follow_route.py
- Command line
-
hf download hf://datasets/jacodd/SynthField/experiments/rtabmap/scripts/follow_route.py
-
curl -L -o follow_route.py https://huggingface.co/datasets/jacodd/SynthField/resolve/main/experiments/rtabmap/scripts/follow_route.py
6.25 kB
| 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() | |