ROS 2 Foxy 설치 & VS code 기본 설정
책 ROS 2로 시작하는 로봇 프로그래밍 내용을 기반으로 정리함.
ROS 2 Foxy Fitzroy를 쓰기 위해 Ubuntu 20.04를 기본 운영 체제로 준비해야 한다. Linux Mint 20.x - Cinnamon (64-bit)를 설치해도 된다. Ubuntu나 Linux는 인터넷을 조금만 찾아보면 설치하기 쉬우니 설명은 생략한다.
나는 Ubuntu 20.04.6 LTS (Focal Fossa)를 기반으로 ROS 2를 설치했다.
- Ubuntu 20.04.6 LTS 설치 링크
- 참고로, Ubuntu 기본 언어는 English로 설정하는 것을 추천한다.
이 포스트에서는 복사 붙여넣기로 빠르게 설치할 수 있도록 터미널에 입력할 명령어만 정리해두었다.
1. ROS 2 Foxy 설치
(1) 지역 설정
1
sudo apt update && sudo apt install locales
1
sudo locale-gen en_US en_US.UTF-8
1
sudo update-locale LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8
1
export LANG=en_US.UTF-8
(2) 소스 설정
1
sudo apt update && sudo apt install curl gnupg2 lsb-release
1
sudo curl -sSL https://raw.githubusercontent.com/ros/rosdistro/master/ros.key -o /usr/share/keyrings/ros-archive-keyring.gpg
1
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/ros-archive-keyring.gpg] http://packages.ros.org/ros2/ubuntu focal main" | sudo tee /etc/apt/sources.list.d/ros2.list > /dev/null
(3) ROS 2 패키지 설치
1
sudo apt update
1
sudo apt install ros-foxy-desktop ros-foxy-rmw-fastrtps* ros-foxy-rmw-cyclonedds*
이 과정이 좀 오래 걸린다. 나는 30분 정도 걸렸다.
(4) ROS 2 패키지 설치 확인
잘 설치되었다면 아래와 같이 두 터미널 창에서 기본적인 publish와 subscribe 동작을 확인할 수 있다.
(아래 내용을 전부 붙여 넣는 것이 아니다!!)
1
2
3
4
5
6
7
8
9
10
$ source /opt/ros/foxy/setup.bash
$ ros2 run demo_nodes_cpp talker
[INFO] [1612912263.574031946] [talker]: Publishing: 'Hello World: 1'
[INFO] [1612912264.574010597] [talker]: Publishing: 'Hello World: 2'
[INFO] [1612912265.574381893] [talker]: Publishing: 'Hello World: 3'
[INFO] [1612912266.574508130] [talker]: Publishing: 'Hello World: 4'
[INFO] [1612912267.574615200] [talker]: Publishing: 'Hello World: 5'
[INFO] [1612912268.574767202] [talker]: Publishing: 'Hello World: 6'
[INFO] [1612912269.574953419] [talker]: Publishing: 'Hello World: 7'
...
1
2
3
4
5
6
7
8
$ source /opt/ros/foxy/setup.bash
$ ros2 run demo_nodes_py listener
[INFO] [1612912265.593335793] [listener]: I heard: [Hello World: 3]
[INFO] [1612912266.576514520] [listener]: I heard: [Hello World: 4]
[INFO] [1612912267.576780341] [listener]: I heard: [Hello World: 5]
[INFO] [1612912268.576769156] [listener]: I heard: [Hello World: 6]
[INFO] [1612912269.577142775] [listener]: I heard: [Hello World: 7]
...
2. ROS 개발 툴 설치
ROS 2를 이용한 로봇 개발에 필수인 소프트웨어들을 설치해주자.
1
2
3
4
5
6
7
8
9
10
11
12
13
sudo apt update && sudo apt install -y \
build-essential \
cmake \
git \
libbullet-dev \
python3-colcon-common-extensions \
python3-flake8 \
python3-pip \
python3-pytest-cov \
python3-rosdep \
python3-setuptools \
python3-vcstool \
wget
1
2
3
4
5
6
7
8
9
10
11
12
13
python3 -m pip install -U \
argcomplete \
flake8-blind-except \
flake8-builtins \
flake8-class-newline \
flake8-comprehensions \
flake8-deprecated \
flake8-docstrings \
flake8-import-order \
flake8-quotes \
pytest-repeat \
pytest-rerunfailures \
pytest
1
2
3
4
sudo apt install --no-install-recommends -y \
libasio-dev \
libtinyxml2-dev \
libcunit1-dev
3. ROS 2 빌드 테스트
ROS 2 Foxy Fitzory 설치를 마쳤으면 아래와 같이 workspace 폴더를 생성한 후 빌드해보자. 폴더 이름은 ‘robot_ws’처럼 보통 원하는 이름 뒤에 ‘_ws’를 붙인다. 이 workspace에는 패키지가 하나도 없기에 무엇을 빌드하는 것이 아닌 빌드가 문제없이 잘 되는지 확인하는 과정이다.
1
source /opt/ros/foxy/setup.bash
1
mkdir -p ~/robot_ws/src
1
cd ~/robot_ws/
1
colcon build --symlink-install
위 과정대로 진행하여 빌드에 오류가 없었다면 workspace의 하위 폴더로 src, build, install, log 폴더가 생성되었을 것이다.
4. Run commands 설정
ROS 2의 명령어를 실행하기 전에 항상 터미널에 ‘source /opt/ros/foxy/setup.bash’를 입력해서 setup.bash 환경 설정을 적용해야 한다. 1. ROS 2 Foxy 설치의 (4) ROS 2 패키지 설치 확인에서도 이를 실행했었다. 매번 setup.bash의 환경 설정을 불러와주기 귀찮으니 아래와 같이 Run commands들을 모아두는 bashrc 파일에 alias, source, export를 설정해두자. 그러면 새 터미널 창을 열 때마다 자동으로 환경 설정이 적용된다.
원하는 편집기(nano, vim, xed 등)으로 bashrc 파일을 열어서 파일의 맨 아래에 아래 내용을 추가해주자.
1
nano ~/.bashrc
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
source /opt/ros/foxy/setup.bash
source ~/robot_ws/install/local_setup.bash
source /usr/share/colcon_argcomplete/hook/colcon-argcomplete.bash
source /usr/share/vcstool-completion/vcs.bash
source /usr/share/colcon_cd/function/colcon_cd.sh
export _colcon_cd_root=~/robot_ws
export ROS_DOMAIN_ID=7
export ROS_NAMESPACE=robot1
export RMW_IMPLEMENTATION=rmw_fastrtps_cpp
# export RMW_IMPLEMENTATION=rmw_connext_cpp
# export RMW_IMPLEMENTATION=rmw_cyclonedds_cpp
# export RMW_IMPLEMENTATION=rmw_gurumdds_cpp
# export RCUTILS_CONSOLE_OUTPUT_FORMAT='[{severity} {time}] [{name}]: {message} ({function_name}() at {file_name}:{line_number})'
export RCUTILS_CONSOLE_OUTPUT_FORMAT='[{severity}]: {message}'
export RCUTILS_COLORIZED_OUTPUT=1
export RCUTILS_LOGGING_USE_STDOUT=0
export RCUTILS_LOGGING_BUFFERED_STREAM=1
alias cw='cd ~/robot_ws'
alias cs='cd ~/robot_ws/src'
alias ccd='colcon_cd'
alias cb='cd ~/robot_ws && colcon build --symlink-install'
alias cbs='colcon build --symlink-install'
alias cbp='colcon build --symlink-install --packages-select'
alias cbu='colcon build --symlink-install --packages-up-to'
alias ct='colcon test'
alias ctp='colcon test --packages-select'
alias ctr='colcon test-result'
alias rt='ros2 topic list'
alias re='ros2 topic echo'
alias rn='ros2 node list'
alias killgazebo='killall -9 gazebo & killall -9 gzserver & killall -9 gzclient'
alias af='ament_flake8'
alias ac='ament_cpplint'
alias testpub='ros2 run demo_nodes_cpp talker'
alias testsub='ros2 run demo_nodes_cpp listener'
alias testpubimg='ros2 run image_tools cam2image'
alias testsubimg='ros2 run image_tools showimage'
5. 통합 개발 환경(IDE) 설치
여기까지 했으면 ROS 2를 이용해 개발을 시작할 수 있다. 개발의 편의성을 위해 통합 개발 환경(IDE)도 필요한데, 보통 Visual Studio Code를 추천한다. ROS를 지원하는 IDE 중 QtCreator도 있는데, QtCreator는 ROS 2의 RQt의 Plugin 개발에 UI 작성할 때, 편리하기에 서브로 사용하면 좋다.
(1) 설치
아래 링크에서 ‘.deb’ 데비안 설치 파일을 다운로드해서 설치하자.
(2) 실행
터미널에 ‘code’를 입력해 실행할 수 있다.
1
code
(3) 유용한 Extensions 설치
왼쪽 바의 Extensions에 들어가서(단축키 ‘Ctrl + Shift + x’) 설치할 수 있다.
- C/C++/Python Extensions (VS Code Extensions for C++ and Python)
이름 | 설명 |
---|---|
C/C++ | C/C++ IntelliSense, 디버깅 및 코드 검색 |
CMake | CMake 언어 지원 |
CMake Tools | CMake 언어 지원 및 다양한 툴 |
Python | 린팅, 디버깅, IntelliSense, 코드 서식 지정, 리팩토링, 단위 테스트 등 |
- ROS Extensions (VS Code Extensions for ROS, URDF, Colcon)
이름 | 설명 |
---|---|
ROS | ROS 개발 지원 |
URDF | URDF/xacro 지원 |
Colcon Tasks | Colcon 명령어를 위한 VSCode Task |
- File Format Extensions (VS Code Extensions for XML, YAML, Markdown)
이름 | 설명 |
---|---|
XML Tools | XML, XQuery, XPath 지원 |
YAML | YAML 지원 |
Markdown All in One | Markdown 지원 |
- 유용한 Extensions (VS Code Extensions for Etc.)
이름 | 설명 |
---|---|
Trailing Spaces | 의미 없이 사용된 공백의 스페이스 문자 강조 |
EOF Mark | [EOF]이 없이 끝난 파일에 [EOF] 문자 추가 |
Better Comments | alert, informational, TODO 등의 코멘트 강화 기능 |
VS Code Extensions에는 다른 신기하고 유용한 것들이 많으니 직접 찾아서 추가해도 좋다.
(4) 워크스페이스 설정(VS Code 폴더 설정)
- “File” - “Add Folder to Workspace…” 메뉴 선택
- “robot_ws” 폴더 선택
(5) VS Code 개발 환경 설정
이 설정 과정에서 settings.json / c_cpp_properties.json / tasks.json / launch.json 파일들을 생성할 것이다. 파일 경로는 아래와 같다. 참고로 이름에 ‘.’이 접두어로 붙은 폴더 및 파일은 숨겨져 있는 폴더나 파일이다.
참고로 라이브러리(탐색기? GUI?)에서는 ‘Ctrl + h’ 단축키로 숨김 폴더 및 파일을 볼 수 있다. 터미널에서는 ls만 해서는 숨김 폴더가 안 뜨고, ls -a를 입력하면 숨김 폴더도 같이 뜬다.
~/.config/Code/User/settings.json
~/robot_ws/.vscode/c_cpp_properties.json
~/robot_ws/.vscode/tasks.json
~/robot_ws/.vscode/launch.json
User settings 설정
settings.json 파일은 VSCode에서 사용자 맞춤형 글로벌 환경 설정을 지정하는 파일로, 여기서 지정된 설정은 모든 작업 공간에 걸쳐 동일하게 적용된다. 예를 들어, 미니맵 표시 여부, 세로 제한 줄 표시, 탭 크기 등을 설정할 수 있다.
ROS 관련 설정으로는 주요하게 세 가지가 있다. 첫째, “ros.distro”: “foxy”와 같이 ‘ms-iot.vscode-ros’ 확장팩에서 ROS 배포 버전을 지정한다. 둘째, “colcon.provideTasks”: true와 같이 ‘deitry.colcon-helper’에서 colcon 지원 Task를 사용할 수 있도록 설정한다. 셋째, files.associations를 통해 *.repos, *.world, *.xacro 같은 확장자를 ROS 전용 파일로 인식하도록 파일 형식을 명시해준다.
~/.config/Code/User/ 에 settings.json을 만들고, 다음과 같이 설정하면 된다.
~/.config/Code/User/settings.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"cmake.configureOnOpen": false,
"editor.minimap.enabled": false,
"editor.mouseWheelZoom": true,
"editor.renderControlCharacters": true,
"editor.rulers": [100],
"editor.tabSize": 2,
"files.associations": {
"*.repos": "yaml",
"*.world": "xml",
"*.xacro": "xml"
},
"files.insertFinalNewline": true,
"files.trimTrailingWhitespace": true,
"terminal.integrated.scrollback": 1000000,
"workbench.iconTheme": "vscode-icons",
"workbench.editor.pinnedTabSizing": "compact",
"ros.distro": "foxy",
"colcon.provideTasks": true
}
C/C++ properties 설정
~/robot_ws/.vscode/c_cpp_properties.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${default}",
"${workspaceFolder}/**",
"/opt/ros/foxy/include/**"
],
"defines": [],
"compilerPath": "/usr/bin/g++",
"cStandard": "c99",
"cppStandard": "c++14",
"intelliSenseMode": "linux-gcc-x64"
}
],
"version": 4
}
만약 robot_ws 폴더에 .vscode 폴더가 나타나지 않는다면, VS Code에서 ‘Ctrl + Shift + p”를 누르고, “Developer: Reload Window 검색 후 클릭”을 해보자.
Tasks 설정
VSCode에는 외부 프로그램을 Command Line Interface(CLI)를 통해 연동할 수 있는 기능이 있으며, 이를 Task라고 부른다. 기본적으로 텍스트 에디터 기능을 제공하는 VSCode가 다양한 기능을 수행하고 쉽게 확장 가능하게 된 이유도 이 Task 기능 덕분이다.
아래의 내용은 ROS 2에서 빌드할 때 사용되는 colcon과 관려한 build, test, clean 작업을 Task로 만들었다. 이를 통해 VScode에서 Ctrl + Shift + b
로 빌드할 수 있고, Ctrl + Shift + p
> Tasks: Run Task > ‘지정한 Task 선택’ 할 수도 있다.
~/robot_ws/.vscode/tasks.json
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
{
"version": "2.0.0",
"tasks": [
{
"label": "colcon: build",
"type": "shell",
"command": "colcon build --cmake-args '-DCMAKE_BUILD_TYPE=Debug'",
"problemMatcher": [],
"group": {
"kind": "build",
"isDefault": true
}
},
{
"label": "colcon: test",
"type": "shell",
"command": "colcon test && colcon test-result"
},
{
"label": "colcon: clean",
"type": "shell",
"command": "rm -rf build install log"
}
]
}
Launch 설정
VS Code에서의 Launch는 ‘Run and Debug’ (Ctrl + Shift + d
)에서 사용되는 실행 명령어로 언어별, 디버거별로 설정이 가능하고, 디버깅을 시작하기 전에 수행할 Task나 콘솔 설정도 세부 옵션에서 조정할 수 있다.
여기서는 ROS 2 환경에서 주로 사용하는 Python과 C++ 언어에 맞춰 VSCode 디버깅 툴을 설정했다. C++은 GDB를, Python은 debugpy를 사용하며, Python은 별도의 빌드 과정 없이 바로 디버깅이 가능하도록 설정했다. 반면 C++은 GDB를 실행하기 전에 colcon build를 먼저 수행하도록 구성했다.
~/robot_ws/.vscode/launch.json
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
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug-rclpy(debugpy)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
},
{
"name": "Debug-rclcpp(gbd)",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/install/${input:package}/lib/${input:package}/${input:node}",
"args": [],
"preLaunchTask": "colcon: build",
"stopAtEntry": true,
"cwd": "${workspaceFolder}",
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
],
"inputs": [
{
"id": "package",
"type": "promptString",
"description": "package name",
"default": "topic_service_action_rclcpp_example"
},
{
"id": "node",
"type": "promptString",
"description": "node name",
"default": "argument"
}
]
}
빌드
‘Ctrl + Shift + b’ 로 빌드를 진행할 수 있다.
디버깅
rclcpp
Run and Debug (
Ctrl + Shift + d
)로 이동“Debug-rclcpp(gbd)” 선택
“Package name” 입력 (예: topic_service_action_rclcpp_example)
“node name” 입력 (예: argument)
Start Debugging 클릭 (
F5
)
rclpy
Run and Debug (
Ctrl + Shift + d
)로 이동“Debug-rclpy(debugpy)” 선택
Start Debugging 클릭 (
F5
)
[출처] 001 ROS 2 개발 환경 구축 (오픈소스 소프트웨어 & 하드웨어: 로봇 기술 공유 카페 (오로카)) | 작성자 표윤석