(Jetson Project2#4)hector mapping 완성

mseokq23·2024년 12월 2일

RPLIDAR A1로 Hector SLAM 맵을 완성하고 저장한 다음, Flask 서버랑 ngrok으로 Flutter 앱에 보냄.
방 전체 맵이 완성됐고 ngrok을 통해 POST /save_map, GET /image가 200 OK로 응답함. 서버 코드는 최종 코드에서 정리함. 최종 코드는 최종 코드 글의 src/robot_bringup/launch/hector_mapping.launch, src/robot_bringup/launch/lidar.launch, src/robot_bringup/launch/mapping.launch, server/map_api_server.py.

1. 매핑 실행

터미널 1, RPLIDAR

roslaunch rplidar_ros rplidar_a1.launch

터미널 2, Hector SLAM (RViz 포함)

roslaunch hector_slam_launch tutorial.launch

왼쪽이 rplidar_a1.launch(A1M8, health status OK), 오른쪽이 tutorial.launch. p_use_tf_scan_transformation_: true, p_pub_map_odom_transform_: true가 찍히고 rviz, hector_mapping, map_nav_broadcaster, hector_trajectory_server, hector_geotiff_node 노드가 뜸.

2. 잘 됐던 설정

잘 됐던 설정은 아래 세 파일임. rplidar_a1.launch는 기본 파일 그대로고, tutorial.launch랑 mapping_default.launch는 clone한 hector_slam 레포 안에서 고쳤음. 전에는 고친 내용이 스크린샷으로만 있어서 여기에 텍스트로 옮겨둠.

2.1 rplidar_a1.launch (기본 파일, frame_id는 laser)

~/catkin_ws/src/rplidar_ros/launch/rplidar_a1.launch

<launch>
  <node name="rplidarNode"          pkg="rplidar_ros"  type="rplidarNode" output="screen">
  <param name="serial_port"         type="string" value="/dev/ttyUSB0"/>
  <param name="serial_baudrate"     type="int"    value="115200"/>
  <param name="frame_id"            type="string" value="laser"/>
  <param name="inverted"            type="bool"   value="false"/>
  <param name="angle_compensate"    type="bool"   value="true"/>
  </node>
</launch>

2.2 tutorial.launch (/use_sim_time을 false로)

~/catkin_ws/src/hector_slam/hector_slam_launch/launch/tutorial.launch

<?xml version="1.0"?>

<launch>

  <arg name="geotiff_map_file_path" default="$(find hector_geotiff)/maps"/>

  <param name="/use_sim_time" value="false"/>

  <node pkg="rviz" type="rviz" name="rviz"
    args="-d $(find hector_slam_launch)/rviz_cfg/mapping_demo.rviz"/>

  <include file="$(find hector_mapping)/launch/mapping_default.launch"/>

  <include file="$(find hector_geotiff_launch)/launch/geotiff_mapper.launch">
    <arg name="trajectory_source_frame_name" value="scanmatcher_frame"/>
    <arg name="map_file_path" value="$(arg geotiff_map_file_path)"/>
  </include>

</launch>

기본 tutorial.launch는 /use_sim_time이 true인데 이건 bag 파일 재생용임. 실제 로봇에는 /clock이 없어서 false로 해야 함.

2.3 mapping_default.launch (frame과 LiDAR TF)

기본 파일에서 바꾼 부분

-  <arg name="base_frame" default="base_footprint"/>
-  <arg name="odom_frame" default="nav"/>
+  <arg name="base_frame" default="base_link"/>
+  <arg name="odom_frame" default="base_link"/>
...
-  <!--<node pkg="tf" type="static_transform_publisher" name="map_nav_broadcaster" args="0 0 0 0 0 0 map nav 100"/>-->
+  <node pkg="tf" type="static_transform_publisher" name="map_nav_broadcaster" args="0 0 0 0 0 0 base_link laser 100"/>

~/catkin_ws/src/hector_slam/hector_mapping/launch/mapping_default.launch (전체 파일)

<?xml version="1.0"?>

<launch>
  <arg name="tf_map_scanmatch_transform_frame_name" default="scanmatcher_frame"/>
  <arg name="base_frame" default="base_link"/>
  <arg name="odom_frame" default="base_link"/>
  <arg name="pub_map_odom_transform" default="true"/>
  <arg name="scan_subscriber_queue_size" default="5"/>
  <arg name="scan_topic" default="scan"/>
  <arg name="map_size" default="2048"/>

  <node pkg="hector_mapping" type="hector_mapping" name="hector_mapping" output="screen">

    <!-- Frame names -->
    <param name="map_frame" value="map" />
    <param name="base_frame" value="$(arg base_frame)" />
    <param name="odom_frame" value="$(arg odom_frame)" />

    <!-- Tf use -->
    <param name="use_tf_scan_transformation" value="true"/>
    <param name="use_tf_pose_start_estimate" value="false"/>
    <param name="pub_map_odom_transform" value="$(arg pub_map_odom_transform)"/>

    <!-- Map size / start point -->
    <param name="map_resolution" value="0.050"/>
    <param name="map_size" value="$(arg map_size)"/>
    <param name="map_start_x" value="0.5"/>
    <param name="map_start_y" value="0.5" />
    <param name="map_multi_res_levels" value="2" />

    <!-- Map update parameters -->
    <param name="update_factor_free" value="0.4"/>
    <param name="update_factor_occupied" value="0.9" />
    <param name="map_update_distance_thresh" value="0.4"/>
    <param name="map_update_angle_thresh" value="0.06" />
    <param name="laser_z_min_value" value = "-1.0" />
    <param name="laser_z_max_value" value = "1.0" />

    <!-- Advertising config -->
    <param name="advertise_map_service" value="true"/>

    <param name="scan_subscriber_queue_size" value="$(arg scan_subscriber_queue_size)"/>
    <param name="scan_topic" value="$(arg scan_topic)"/>

    <!-- Debug parameters -->
    <!--
      <param name="output_timing" value="false"/>
      <param name="pub_drawings" value="true"/>
      <param name="pub_debug_output" value="true"/>
    -->
    <param name="tf_map_scanmatch_transform_frame_name" value="$(arg tf_map_scanmatch_transform_frame_name)" />
  </node>

  <node pkg="tf" type="static_transform_publisher" name="map_nav_broadcaster" args="0 0 0 0 0 0 base_link laser 100"/>
</launch>

이렇게 바꾼 이유

  • 로봇에 바퀴 odometry가 없어서 odom_frame을 base_link로 두고, hector가 map에서 base_link로 가는 TF를 직접 보냄 (pub_map_odom_transform은 true).
  • base_frame은 base_link이고, base_link에서 laser로 가는 static TF가 스캔 frame(rplidar_a1.launch의 laser)을 로봇에 연결해줌.

최종 코드에서는 이 수정 내용을 clone한 hector_slam 레포 안에 두지 않음. src/robot_bringup/launch/hector_mapping.launch에 같은 파라미터가 있고, src/robot_bringup/launch/lidar.launch가 base_link에서 laser로 가는 TF를 보내고, 터미널 두 개 대신 roslaunch robot_bringup mapping.launch 하나로 띄움.

3. 결과

매핑하는 화면. roscore, hector_mapping, RPLIDAR 터미널이랑 RViz의 맵(mapping_demo.rviz, Fixed Frame map), 그리고 수정한 mapping_default.launch.

완성된 맵 (위에서 본 것). 0.05 m 셀 2048 x 2048 맵이고, 초록색이 이동 경로 /trajectory, 위치는 /slam_out_pose.

같은 맵을 3D로 본 것 (Imu display도 켜져 있음).

다른 매핑 결과.

4. 맵 저장

지금 맵 저장하기

rosrun map_server map_saver -f ~/my_map

~/my_map.pgm(이미지)이랑 ~/my_map.yaml(해상도, 원점)이 생김.

최종 코드에서는 자동으로 저장함. map_autosaver.py가 30초마다 ~/my_map.pgm/.yaml로 저장하고, 매핑을 끝낼 때(Ctrl+C) ~/maps/에 사본을 남김.

5. Flutter 앱으로 맵 보내기 (Flask, ngrok)

5.1 ngrok으로 서버를 외부에 열기

ngrok http --subdomain=arto 5000

나중에는 (지금 ngrok 기준)

ngrok http --url=arto.ngrok.io 5000

--subdomain은 예전 ngrok 옵션이고, ngrok 3(아래 스크린샷은 3.18.4)에서는 --url을 씀. ngrok이 https://arto.ngrok.io로 들어온 요청을 http://localhost:5000으로 넘겨줌.

5.2 Flask 서버 실행

python3 server_2.py

주의) 이 글 처음 버전에서는 sudo python3 server_2.py로 실행했는데 sudo 없이 실행해야 함. sudo로 돌리면 map_saver -f ~/my_map의 ~가 /root가 되는데 서버는 /home/jetson/my_map.pgm을 읽음. (아래 스크린샷의 잘 된 실행도 sudo 없이 띄운 것)

주의) server_2.py에서 나중에 고친 문제들

  • API 키가 코드에 그대로 들어가 있었고 이 글 첫 버전에 공개돼 있었음. 아래 코드에서는 지웠고 이제 키는 ROBOT_API_KEY 환경 변수에서 읽음. 공개됐던 값이 실제 키나 ngrok authtoken이었으면 새로 발급받아야 함 (ngrok 대시보드에서 authtoken 재설정).
  • app.config['UPLOAD_FOLDER']를 어디서도 설정 안 해서 /picture, /uploads/<filename>이 KeyError로 실패함.
  • 업로드 파일 이름을 그대로 써서 ../../x.png 같은 이름이면 폴더 밖으로 나갈 수 있음 (werkzeug.utils.secure_filename을 써야 함).
  • 대기 루프가 예전에 저장된 my_map.pgm이 있으면 성공으로 처리함. 경로도 /home/jetson으로 고정돼 있음.

최종 버전은 server/map_api_server.py. route랑 응답은 같고 POST /command(앱에서 F, B, L, R, S), POST /mapping(매핑 시작, 정지), GET /status를 추가함.

~/server_2.py

from flask import Flask, request, jsonify, send_file
import os
import subprocess
from PIL import Image
import atexit
import time
import io
from functools import wraps

app = Flask(__name__)

# API Key Authentication (For Enhanced Security)
API_KEY = os.environ['ROBOT_API_KEY']  # was hard-coded (and public) here - set it with: export ROBOT_API_KEY='...'

def require_api_key(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if 'x-api-key' not in request.headers:
            return jsonify({"error": "API 키가 필요합니다."}), 401
        if request.headers['x-api-key'] != API_KEY:
            return jsonify({"error": "유효하지 않은 API 키입니다."}), 403
        return f(*args, **kwargs)
    return decorated

# Function to Execute ROS Command
def execute_ros_command():
    """
    Executes the ROS map_saver command in the background and waits for the .pgm file to be created.
    """
    try:
        # Execute the ROS command in a bash shell
        command = "rosrun map_server map_saver -f ~/my_map"
        process = subprocess.Popen(command, shell=True, executable='/bin/bash')

        # Path to the generated .pgm file
        pgm_path = '/home/jetson/my_map.pgm'  # Update this path as needed

        # Wait for the .pgm file to be created with a timeout
        timeout = 60  # seconds
        elapsed_time = 0
        while not os.path.exists(pgm_path) and elapsed_time < timeout:
            time.sleep(1)
            elapsed_time += 1

        if os.path.exists(pgm_path):
            # Optionally, wait for the process to finish
            process.wait(timeout=10)
            return True
        else:
            print("맵 파일 생성 시간이 초과되었습니다.")
            return False
    except Exception as e:
        print(f"명령 실행 중 오류 발생: {e}")
        return False

# Route to Save Map and Convert to PNG
@app.route('/save_map', methods=['POST'])
@require_api_key
def save_map():
    """
    Executes the ROS map_saver command and converts the resulting .pgm file to .png.
    """
    data = request.get_json()
    if data and data.get('command') == 'save_map':
        if execute_ros_command():
            pgm_path = '/home/jetson/my_map.pgm'  # Update this path as needed
            png_path = '/home/jetson/my_map.png'  # Desired PNG path

            try:
                # Open the .pgm file and convert it to .png
                with Image.open(pgm_path) as img:
                    img = img.convert('RGB')  # Convert to RGB if necessary
                    img.save(png_path, 'PNG')
                return jsonify({"status": "success", "message": "Map saved and converted to PNG"}), 200
            except Exception as e:
                print(f"PNG 변환 중 오류 발생: {e}")
                return jsonify({"status": "error", "message": "맵을 PNG로 변환하는 데 실패했습니다."}), 500
        else:
            return jsonify({"status": "error", "message": "맵 저장 명령을 실행하지 못했습니다."}), 500
    return jsonify({"status": "error", "message": "유효하지 않은 명령입니다."}), 400


# 홈 디렉토리에 있는 .pgm 파일을 PNG로 변환하여 전송하는 라우트
@app.route('/image')
def send_image():
    # 홈 디렉토리에서 파일 경로 지정
    file_path = '/home/jetson/my_map.pgm'

    if not os.path.exists(file_path):
        return jsonify({'error': 'Map file not found'}), 404

    # .pgm 이미지를 열어서 PNG로 변환
    try:
        with Image.open(file_path) as img:
            img = img.convert('RGB')  # 필요에 따라 색상 모드 변환
            img_io = io.BytesIO()
            img.save(img_io, 'PNG')
            img_io.seek(0)

            return send_file(img_io, mimetype='image/png')
    except Exception as e:
        print(f"Error converting map image: {e}")
        return jsonify({'error': 'Failed to process map image'}), 500


# 외부에서 업로드된 .png 파일을 바로 처리하는 라우트
@app.route('/picture', methods=['POST'])
def handle_uploaded_picture():
    if 'image' not in request.files:
        return jsonify({'error': '파일이 없습니다.'}), 400

    file = request.files['image']
    if file.filename == '':
        return jsonify({'error': '파일명이 없습니다.'}), 400

    if file and file.filename.lower().endswith('.png'):
        # 파일을 업로드 폴더에 저장
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(filepath)
        return jsonify({'message': '파일 업로드 성공', 'filename': file.filename}), 200

    return jsonify({'error': '유효하지 않은 파일 형식입니다. .png 파일을 업로드하세요.'}), 400


# 업로드된 이미지를 가져오는 라우트 (Flutter 앱에서 호출)
@app.route('/uploads/<filename>')
def get_uploaded_picture(filename):
    filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    if os.path.exists(filepath):
        return send_file(filepath, mimetype='image/png')
    else:
        return jsonify({'error': '파일을 찾을 수 없습니다.'}), 404


# Run the Flask App
if __name__ == '__main__':
    # Register a shutdown handler
    atexit.register(lambda: print("Flask 서버가 종료됩니다."))
    # Run the app on all interfaces, port 5000
    app.run(host='0.0.0.0', port=5000)

에디터에서 본 server_2.py. execute_ros_command()가 map_saver를 실행하고 .pgm이 생길 때까지 기다리고, /save_map이 PNG로 바꿈.

전부 돌고 있는 화면. RPLIDAR, Hector SLAM, Flask 서버(map_saver가 /home/jetson/my_map.pgm, .yaml 저장), ngrok이 https://arto.ngrok.io를 http://localhost:5000으로 넘기고 POST /save_map, GET /image가 200 OK.

서버 로그. POST /save_map(맵을 2048 x 2048, 0.050 m/pix로 저장)이랑 GET /image 요청이 반복되고 전부 200.

다음 글: (Jetson Project Final) Jetson Nano Hector SLAM 로봇 최종 코드

profile
mseokq23.tistory.com 으로 이사했어요~ 많이 와주세요!

0개의 댓글