Merge branch 'master' into ros-book
BIN
docs/assets/simulation_setup_vm/01_import_vm.png
Normal file
|
After Width: | Height: | Size: 86 KiB |
BIN
docs/assets/simulation_setup_vm/02_import_failure.png
Normal file
|
After Width: | Height: | Size: 88 KiB |
BIN
docs/assets/simulation_setup_vm/03_max_memory.png
Normal file
|
After Width: | Height: | Size: 71 KiB |
BIN
docs/assets/simulation_setup_vm/04_core_count.png
Normal file
|
After Width: | Height: | Size: 53 KiB |
BIN
docs/assets/simulation_setup_vm/05_3d_acceleration.png
Normal file
|
After Width: | Height: | Size: 61 KiB |
BIN
docs/assets/simulation_setup_vm/06_usb_3_0.png
Normal file
|
After Width: | Height: | Size: 59 KiB |
BIN
docs/assets/simulation_setup_vm/07_bridge_networking.png
Normal file
|
After Width: | Height: | Size: 60 KiB |
BIN
docs/assets/simulation_setup_vm/08_no_3d_acceleration.png
Normal file
|
After Width: | Height: | Size: 63 KiB |
BIN
docs/assets/simulation_setup_vm/09_netcfg.png
Normal file
|
After Width: | Height: | Size: 66 KiB |
BIN
docs/assets/simulation_usage/01_running_gazebo.jpg
Normal file
|
After Width: | Height: | Size: 189 KiB |
BIN
docs/assets/simulation_usage/02_gazebo_qgc.jpg
Normal file
|
After Width: | Height: | Size: 160 KiB |
BIN
docs/assets/simulation_usage/03_gazebo_rqt.jpg
Normal file
|
After Width: | Height: | Size: 147 KiB |
BIN
docs/assets/simulation_usage/04_vscode_config.jpg
Normal file
|
After Width: | Height: | Size: 272 KiB |
BIN
docs/assets/simulation_usage/05_real_time_factor.png
Normal file
|
After Width: | Height: | Size: 3.1 KiB |
BIN
docs/assets/simulation_usage/06_gazebo_px4_launcher.png
Normal file
|
After Width: | Height: | Size: 37 KiB |
@@ -47,6 +47,11 @@
|
||||
* [Using JavaScript](javascript.md)
|
||||
* [ROS](ros.md)
|
||||
* [MAVROS](mavros.md)
|
||||
* Simulation
|
||||
* [Overview](simulation.md)
|
||||
* [Native setup](simulation_native.md)
|
||||
* [VM setup](simulation_vm.md)
|
||||
* [Usage](simulation_usage.md)
|
||||
* Supplementary materials
|
||||
* [COEX Pix](coex_pix.md)
|
||||
* [Guide on autonomous flight](auto_setup.md)
|
||||
|
||||
@@ -160,7 +160,7 @@ Install the damper struts, fix *COEX Pix* on them with nylon nuts.
|
||||
<img src="../assets/assembling_clever4_2/fc_connection_6.png" width=300 class="zoom border">
|
||||
</div>
|
||||
|
||||
2. On a mounting deck, install 6mm racks and 30mm racks, fasten them with the M3x8 and M3x12 bolts, respectively.
|
||||
2. On a mounting deck, install 6mm racks and 30mm racks, fasten them with the M3x5 and M3x12 bolts, respectively.
|
||||
|
||||
<img src="../assets/assembling_clever4_2/raspberry_1.png" width=300 class="zoom border center">
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ Our [Raspberry Pi image](image.md) contains preinstalled modules for interfacing
|
||||
## High-level control
|
||||
|
||||
1. Connect the +5v and GND leads of your LED to a power source and the DIN (data in) lead to GPIO21. Consult the [assembly instructions](assemble_4_2.md#installing-led-strip) for details.
|
||||
2. Enable LED strip support in `~/catkin_ws/src/clever/clever/launch/clever.launch`:
|
||||
2. Enable LED strip support in `~/catkin_ws/src/clover/clover/launch/clover.launch`:
|
||||
|
||||
```xml
|
||||
<arg name="led" default="true"/>
|
||||
|
||||
32
docs/en/simulation.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# Simulation overview
|
||||
|
||||
The Clover simulation environment allows users to run and debug their code within a simulator while using most of the features available on the real drone. The simulation utilizes [PX4 SITL mode](sitl.md) and uses the same ROS code as the real drone. Most hardware is simulated as well.
|
||||
|
||||
## Features
|
||||
|
||||
Basic, user-installable environment includes:
|
||||
|
||||
* high-quality Clover 4 visual model;
|
||||
* Gazebo plugins for Clover-specific hardware (e.g. LED strip);
|
||||
* modification-friendly [`xacro`](https://wiki.ros.org/xacro) drone descriptions;
|
||||
* sample models and worlds;
|
||||
* [`roslaunch`](https://wiki.ros.org/roslaunch) files for quick simulation launching and configuration.
|
||||
|
||||
Additionally, a [virtual machine image](simulation_vm.md) that mimics the real drone as closely as possible is provided with the following features:
|
||||
|
||||
* easy access to the simulation environment;
|
||||
* Visual Studio Code editor, preconfigured to work with ROS packages;
|
||||
* Monkey web server for web-based Clover plugins;
|
||||
* always-running `roscore` service;
|
||||
* ROS GUI tools (`rviz`, `rqt`).
|
||||
|
||||
## Architecture
|
||||
|
||||
The simulation environment is based on the following components:
|
||||
|
||||
* [Gazebo](http://gazebosim.org/), a state-of-the-art robotics simulator;
|
||||
* [PX4](https://px4.io/), specifically its SITL (software-in-the-loop) components;
|
||||
* [`sitl_gazebo`](https://github.com/PX4/sitl_gazebo) package containing Gazebo plugins for PX4;
|
||||
* ROS packages and Gazebo plugins.
|
||||
|
||||
<!-- TODO: Write more, add a diagram, etc -->
|
||||
96
docs/en/simulation_native.md
Normal file
@@ -0,0 +1,96 @@
|
||||
# Native setup
|
||||
|
||||
Setting up the simulation environment from scratch requires some effort, but results in the most performant setup, with less chance of driver issues.
|
||||
|
||||
Prerequisites: Ubuntu 18.04, [native ROS installation](ros-install.md).
|
||||
|
||||
## Create a workspace for the simulation
|
||||
|
||||
Throughout this guide we will be using the `catkin_ws` as the workspace name. Feel free to change it in your setup. We will be creating it in the home directory of the current user (`~`).
|
||||
|
||||
Create the workspace and clone Clover sources:
|
||||
|
||||
```bash
|
||||
mkdir -p ~/catkin_ws/src
|
||||
cd ~/catkin_ws/src
|
||||
git clone https://github.com/CopterExpress/clover
|
||||
git clone https://github.com/CopterExpress/ros_led
|
||||
```
|
||||
|
||||
Install all prerequisites using `rosdep`:
|
||||
|
||||
```bash
|
||||
cd ~/catkin_ws
|
||||
rosdep update
|
||||
rosdep install --from-paths src --ignore-src -y
|
||||
```
|
||||
|
||||
## Get PX4 sources
|
||||
|
||||
PX4 will be built along with the other packages in our workspace. You may clone it directly into the workspace or put it somewhere and symlink to `~/catkin_ws/src`. We will need to put its `sitl_gazebo` submodule in `~/catkin_ws/src` as well. For simplicity's sake we will clone the firmware directly to the workspace:
|
||||
|
||||
```bash
|
||||
cd ~/catkin_ws/src
|
||||
git clone --recursive https://github.com/CopterExpress/Firmware -b v1.10.1-clever
|
||||
ln -s Firmware/Tools/sitl_gazebo ./sitl_gazebo
|
||||
```
|
||||
|
||||
## Install PX4 prerequisites
|
||||
|
||||
PX4 comes with its own script for dependency installation. We may as well leverage it:
|
||||
|
||||
```bash
|
||||
cd ~/catkin_ws/src/Firmware/Tools/setup
|
||||
sudo ./ubuntu.sh
|
||||
```
|
||||
|
||||
This will install everything required to build PX4 and its SITL environment.
|
||||
|
||||
You may want to skip installing the ARM toolchain if you're not planning on compiling PX4 for your flight controller. To do this, use the `--no-nuttx` flag:
|
||||
|
||||
```
|
||||
sudo ./ubuntu.sh --no-nuttx
|
||||
```
|
||||
|
||||
## Patch Gazebo plugins
|
||||
|
||||
The `sitl_gazebo` package containing required Gazebo plugins needs patching due to recent changes in MAVLink. These patches are already preapplied in the [virtual machine image](simulation_vm.md) and are stored in the VM repository. Run the following commands to download and apply the patches:
|
||||
|
||||
```bash
|
||||
cd ~/catkin_ws/src/Firmware/Tools/sitl_gazebo
|
||||
wget https://raw.githubusercontent.com/CopterExpress/clover_vm/master/assets/patches/sitl_gazebo.patch
|
||||
patch -p1 < sitl_gazebo.patch
|
||||
rm sitl_gazebo.patch
|
||||
```
|
||||
|
||||
## Install geographiclib datasets
|
||||
|
||||
`mavros` requires geographiclib datasets to be present:
|
||||
|
||||
```bash
|
||||
cd ~
|
||||
wget https://raw.githubusercontent.com/mavlink/mavros/6f5bd5a1a67c19c2e605f33de296b1b1be9d02fc/mavros/scripts/install_geographiclib_datasets.sh
|
||||
chmod +x ./install_geographiclib_datasets.sh
|
||||
sudo ./install_geographiclib_datasets.sh
|
||||
rm ./install_geographiclib_datasets.sh
|
||||
```
|
||||
|
||||
## Build the simulator
|
||||
|
||||
With all dependencies installed, you can build your workspace:
|
||||
|
||||
```bash
|
||||
cd ~/catkin_ws
|
||||
catkin_make
|
||||
```
|
||||
|
||||
> **Note** Some of the files - particularly Gazebo plugins - require large amounts of RAM to be built. You may wish to reduce the number of parallel jobs; the number of parallel jobs should be equal to the amount of RAM in gigabytes divided by 2 - so a 16GB machine should use no more than 8 jobs. You can specify the number of jobs using the `-j` flag: `catkin_make -j8`
|
||||
|
||||
## Run the simulator
|
||||
|
||||
In order to be sure that everything was built correctly, try running the simulator for the first time:
|
||||
|
||||
```bash
|
||||
source ~/catkin_ws/devel/setup.bash
|
||||
roslaunch clover_simulation simulator.launch
|
||||
```
|
||||
89
docs/en/simulation_usage.md
Normal file
@@ -0,0 +1,89 @@
|
||||
# Using the simulator
|
||||
|
||||
The Clover simulation environment allows the user to test their code without any risk of equipment damage. Additionally, the [virtual machine](simulation_vm.md)-based environment has additional (non-ROS) services that are present on a real drone, like Monkey web server.
|
||||
|
||||
## Running the simulation
|
||||
|
||||
After [setting up the simulation packages](simulation_native.md) or [importing and running the VM](simulation_vm.md), you can use `roslaunch` to start Gazebo simulation:
|
||||
|
||||
```bash
|
||||
# Be sure to activate your workspace first
|
||||
source ~/catkin_ws/devel/setup.bash
|
||||
roslaunch clover_simulation simulator.launch
|
||||
```
|
||||
|
||||
> **Note** Alternatively, if you are using the VM, just double-click on the `Gazebo PX4` icon on the desktop.
|
||||
|
||||
This will launch Gazebo server and client, the PX4 SITL binary and Clover nodes. The terminal in which the command was run will display diagnostic messages from the nodes and PX4, and will accept input for the PX4 command interpreter:
|
||||
|
||||

|
||||
|
||||
You can use QGroundControl to configure the simulated drone parameters, plan missions (if GPS is simulated) and control the drone using a joystick:
|
||||
|
||||

|
||||
|
||||
You can also use [our simplified OFFBOARD control](simple_offboard.md) to control the drone, and traditional ROS GUI utilities like [rviz and rqt](rviz.md) to analyze the drone state:
|
||||
|
||||

|
||||
|
||||
## Configuring the simulation
|
||||
|
||||
The simulation can be configured by passing additional arguments to the `roslaunch` command or by changing the `~/catkin_ws/src/clover/clover_simulation/launch/simulator.launch` file. Nodes that provide [ArUco detection](aruco.md), [optical flow calculation](optical_flow.md) and other services can be configured by changing their respective `.launch` files, just like on a real drone.
|
||||
|
||||
### Changing the drone parameters
|
||||
|
||||

|
||||
|
||||
You can enable or disable some of the drone sensors by changing parameters in the `simulator.launch` file. For example, in order to enable GPS, set the `gps` argument to `true`:
|
||||
|
||||
```xml
|
||||
<arg name="gps" value="true"/>
|
||||
```
|
||||
|
||||
Note that this will simply enable the sensor, you will have to change the PX4 estimator parameters to enable GPS fusion.
|
||||
|
||||
If you wish to add additional sensors or change their placement, you will have to change the drone description. The description file is located in `~/catkin_ws/src/clover/clover_description/urdf/clover/clover4.xacro`, and uses the [xacro](http://wiki.ros.org/xacro) format to build URDF description.
|
||||
|
||||
### Changing the default world
|
||||
|
||||
Gazebo plugins for the drone currently require the `real_time_update_rate` world parameter to be 250, and `max_step_size` to be 0.004. Using other values will not work. Consider using `~/catkin_ws/src/clover/clover_simulation/resources/worlds/clover.world` as a base.
|
||||
|
||||
## Performance suggestions
|
||||
|
||||
Gazebo simulation environment is resource-intensive, and requires a fast CPU and a decent GPU for real-time execution. However, the simulation may still work on less powerful systems at slower-than-realtime rate. Below are some suggestions for running Gazebo on hardware that does not allow realtime execution.
|
||||
|
||||
### Use `throttling_camera` plugin
|
||||
|
||||
By default, Gazebo does not slow simulation down for visual sensors. This can be remedied by using the `throttling_camera` plugin from `clover_simulation`.
|
||||
|
||||
You can enable it for the drone by changing the `maintain_camera_rate` argument to `true` in `clover_description/launch/spawn_drone.launch`:
|
||||
|
||||
```xml
|
||||
<!-- Slow simulation down to maintain camera rate -->
|
||||
<arg name="maintain_camera_rate" default="true"/>
|
||||
```
|
||||
|
||||
The plugin will collect publishing rate statistics and slow the simulation down so that the camera publishing rate is no less than requested. However, large slowdowns may negatively affect non-ROS software that connects to PX4. If your simulation is being slowed down to values lower than 0.5 of realtime, consider using the next suggestion.
|
||||
|
||||
### Set simulation speed
|
||||
|
||||
Since v1.9 the PX4 SITL setup supports [setting the simulation speed](https://dev.px4.io/v1.9.0/en/simulation/#simulation_speed) by setting the `PX4_SIM_SPEED_FACTOR` environment variable. Its value is picked up by PX4 startup scripts, which in turn reconfigure it to expect a certain speedup/slowdown.
|
||||
|
||||
You should set its value to the actual real time factor that you get with `throttling_camera`. The real time factor may be found in the Gazebo GUI window at the bottom:
|
||||
|
||||

|
||||
|
||||
In this example you should set `PX4_SIM_SPEED_FACTOR` to `0.42` when launching the simulation:
|
||||
|
||||
```bash
|
||||
PX4_SIM_SPEED_FACTOR=0.42 roslaunch clover_simulation simulator.launch
|
||||
```
|
||||
|
||||
> **Note** If you are using the VM, it may be convenient to put the value in the Gazebo desktop shortcut. Right-click on the Gazebo icon, select "Properties..." and add `PX4_SIM_SPEED_FACTOR=0.42` to the Command field as follows:
|
||||

|
||||
|
||||
### Allocate more resources to the VM
|
||||
|
||||
The virtual machine may benefit from several CPU cores, especially if the cores are not very performant. In our tests, a four-core machine with only a single core allocated to the VM was unable to run the simulation, with constant interface freezes and dropped ROS messages. The same machine with all four cores available to the VM was able to run the simulation at 0.25 real-time speed.
|
||||
|
||||
Do note that you should not allocate more resources than you have on your host hardware.
|
||||
64
docs/en/simulation_vm.md
Normal file
@@ -0,0 +1,64 @@
|
||||
# Simulation VM setup
|
||||
|
||||
In addition to [native installation instructions](simulation_native.md), we provide a [preconfigured developer virtual machine image](https://github.com/CopterExpress/clover_vm/releases). The image contains:
|
||||
|
||||
* Ubuntu 18.04 with XFCE lightweight desktop environment;
|
||||
* ROS packages required to develop for the Clover platform;
|
||||
* QGroundControl;
|
||||
* preconfigured Gazebo simulation environment;
|
||||
* Visual Studio Code with C++ and Python plugins.
|
||||
|
||||
The VM is an easy way to set up a simulation environment, but can be used as a development environment for a real drone as well.
|
||||
|
||||
You can download the latest VM image [in the VM releases repository](https://github.com/CopterExpress/clover_vm/releases).
|
||||
|
||||
> **Note** The virtual machine should be used when native installation is not feasible or possible. You may experience reduced performance in programs that use 3D rendering, like rviz and Gazebo.
|
||||
|
||||
## Setting up the VM
|
||||
|
||||
You need to use a VM manager that supports OVF format, like [Virtualbox](https://www.virtualbox.org/wiki/Downloads), [VMware Player](https://www.vmware.com/products/workstation-player.html) or [VMware Workstation](https://www.vmware.com/products/workstation-pro.html).
|
||||
|
||||
> **Note** At the time of writing Virtualbox had issues running the VM, particularly with 3D applications. We recommend using VMware Player or VMware Workstation if possible. The following steps assume you're using VMware Player.
|
||||
|
||||
Make sure that you have hardware virtualization enabled in your BIOS/UEFI (it may be supported by your hardware but turned off by default). The steps to enable virtualization differ from manufacturer to manufacturer, but should be described in your system manual. Consult your system's manufacturer if you're having trouble turning virtualization on.
|
||||
|
||||
1. Import the OVA archive into your virtualization environment. Use the **Open a Virtual Machine** option in VMware Player:
|
||||
|
||||

|
||||
|
||||
> **Note** You may see a dialog box with a warning about the VM format:
|
||||

|
||||
You can safely ignore the warning and press **Retry**.
|
||||
|
||||
2. Right-click on the VM name and select **Virtual Machine Settings**. In the new window, set the following parameters:
|
||||
|
||||
* increase the amount of memory available to the virtual machine (a good rule of thumb is 2048 MB per CPU core, but no less than 4 GB):
|
||||

|
||||
* increase the amount available CPU cores:
|
||||

|
||||
* enable 3D acceleration:
|
||||

|
||||
* enable USB 2.0/3.0 controller (if you plan to connect external devices to the VM):
|
||||

|
||||
* optionally enable the "bridged" network connection (if you plan to connect to a real drone):
|
||||

|
||||
|
||||
> **Note** Some host network adapters may not work well with the bridged network. Consider using external USB Wi-Fi adapters managed by your VM to connect to a real drone.
|
||||
|
||||
3. "Power on" the virtual machine. You may see a warning message about your host system not providing 3D acceleration:
|
||||
|
||||

|
||||
|
||||
Make sure you have the latest GPU drivers for your host system. If the warnings persist, add the following line to `clover-devel.vmx` (actual file name may differ based on the VM name):
|
||||
|
||||
```
|
||||
mks.gl.allowBlacklistedDrivers = "TRUE"
|
||||
```
|
||||
|
||||
You can find this file in a folder where the VM is imported to.
|
||||
|
||||
4. (Bridged networking only) Set up network bridge configuration in VM settings or using `vmware-netcfg` utility (in Linux):
|
||||
|
||||

|
||||
|
||||
Select `vmnet0` in the networks list, set it to *Bridged*, and choose the adapter you are planning to use to connect to drone in the drop-down menu.
|
||||
@@ -1,6 +1,8 @@
|
||||
PX4 Simulation
|
||||
===
|
||||
|
||||
> **Hint** This article is about running a standalone PX4 simulation with a generic quadcopter. Consider using [our configuration](simulation.md) for a more Clover-like experience.
|
||||
|
||||
Main article: https://dev.px4.io/en/simulation/
|
||||
|
||||
PX4 simulation is possible in Linux and macOS with the use of physical environment simulation systems [jMAVSim](https://pixhawk.org/dev/hil/jmavsim) and [the Gazebo](http://gazebosim.org).
|
||||
|
||||
@@ -47,11 +47,18 @@
|
||||
* [Автозапуск ПО](autolaunch.md)
|
||||
* [Использование JavaScript](javascript.md)
|
||||
* [`mavros`](mavros.md)
|
||||
* Симулятор
|
||||
* [Общая информация](simulation.md)
|
||||
* [Сборка на собственной машине](simulation_native.md)
|
||||
* [Установка виртуальной машины](simulation_vm.md)
|
||||
* [Использование симулятора](simulation_usage.md)
|
||||
* ROS: учебник
|
||||
* [Общая информация](ros.md)
|
||||
* [Графические инструменты](ros_gui.md)
|
||||
* [Соглашения ROS](ros_conventions.md)
|
||||
* [Продвинутое использование](ros_advanced.md)
|
||||
* [ROS](ros.md)
|
||||
* [MAVROS](mavros.md)
|
||||
* Дополнительные материалы
|
||||
* [COEX Pix](coex_pix.md)
|
||||
* [Гид по автономному полету](auto_setup.md)
|
||||
|
||||
@@ -160,7 +160,7 @@
|
||||
<img src="../assets/assembling_clever4_2/fc_connection_6.png" width=300 class="zoom border">
|
||||
</div>
|
||||
|
||||
2. На монтажную деку установите стойки 6мм и стойки 30мм, закрепите их с помощью винт М3х8 и М3х12 соответственно.
|
||||
2. На монтажную деку установите стойки 6мм и стойки 30мм, закрепите их с помощью винт М3х5 и М3х12 соответственно.
|
||||
|
||||
<img src="../assets/assembling_clever4_2/raspberry_1.png" width=300 class="zoom border center">
|
||||
|
||||
@@ -204,6 +204,10 @@
|
||||
|
||||
<img src="../assets/assembling_clever4_2/raspberry_11.png" width=300 class="zoom border center">
|
||||
|
||||
13. Подключите полетный контроллер к *Raspberry Pi* с помощью USB кабеля.
|
||||
|
||||
<img src="../assets/assembling_clever4_2/final_2.png" width=300 class="zoom border">
|
||||
|
||||
## Установка LED ленты
|
||||
|
||||
1. Соберите обруч для светодиодной ленты, объединив замок на концах.
|
||||
@@ -252,21 +256,4 @@
|
||||
|
||||
<img src="../assets/assembling_clever4_2/guard_4.png" width=300 class="zoom border center">
|
||||
|
||||
## Подготовка к полету
|
||||
|
||||
1. Установите ремешок для аккумулятора и подключите полетный контроллер к *Raspberry Pi* с помощью USB кабеля.
|
||||
|
||||
<div class="image-group">
|
||||
<img src="../assets/assembling_clever4_2/final_1.png" width=300 class="zoom border">
|
||||
<img src="../assets/assembling_clever4_2/final_2.png" width=300 class="zoom border">
|
||||
</div>
|
||||
|
||||
2. Установите пропеллеры в соответствии со [схемой направления движения моторов](#prop_rotation).
|
||||
|
||||
<img src="../assets/assembling_clever4_2/final_3.png" width=300 class="zoom border center">
|
||||
|
||||
3. Установите аккумулятор.
|
||||
|
||||
<img src="../assets/assembling_clever4_2/final_4.png" width=300 class="zoom border center">
|
||||
|
||||
> **Success** Дрон собран, далее произведите ["настройку"](setup.md).
|
||||
|
||||
34
docs/ru/simulation.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Общая информация
|
||||
|
||||
Среда симуляции Клевера позволяет пользователям запускать и отлаживать свой код в симуляторе, используя большинство функций, доступных на реальном дроне. Симулятор использует [режим PX4 SITL](sitl.md) и тот же код, использующий ROS, что и настоящий дрон. Большинство железа также симулируется.
|
||||
|
||||
## Особенности
|
||||
|
||||
Устанавливаемая пользователем среда включает в себя:
|
||||
|
||||
* высококачественную модель Клевера 4;
|
||||
* плагины Gazebo для железа Клевера (например, для светодиодной ленты);
|
||||
* легко изменяемые файлы описания дрона в формате [`xacro`](https://wiki.ros.org/xacro);
|
||||
* примеры моделей и миров;
|
||||
* [`roslaunch`](https://wiki.ros.org/roslaunch) файлы для быстрого запуска и настройки.
|
||||
|
||||
Кроме того, предоставляется [образ виртуальной машины](simulation_vm.md), который максимально точно имитирует реальный дрон.
|
||||
|
||||
Особенности:
|
||||
|
||||
* легкий доступ к симулятору;
|
||||
* установлен и настроен для работы с ROS Visual Studio Code;
|
||||
* веб-сервер (Monkey) для плагинов Клевера, работающих в браузере;
|
||||
* постоянно работающий сервис `roscore`;
|
||||
* средства визуализации (`rviz`, `rqt`).
|
||||
|
||||
## Состав симулятора
|
||||
|
||||
Симулятор основан на следующих элементах:
|
||||
|
||||
* [Gazebo](http://gazebosim.org/), универсальная среда симуляции для любых типов роботов;
|
||||
* [PX4](https://px4.io/), в частности, его компонент SITL (software-in-the-loop);
|
||||
* [`sitl_gazebo`](https://github.com/PX4/sitl_gazebo) пакет, содержащий плагины Gazebo для PX4;
|
||||
* пакеты ROS и плагины Gazebo;
|
||||
|
||||
<!-- TODO: Write more, add a diagram, etc -->
|
||||
96
docs/ru/simulation_native.md
Normal file
@@ -0,0 +1,96 @@
|
||||
# Сборка на собственной машине
|
||||
|
||||
Настройка среды для симуляции с нуля требует некоторых усилий, однако это приведет к улучшению производительности и к уменьшению вероятности появления проблем с драйверами.
|
||||
|
||||
Требования для сборки: установлены Ubuntu 18.04 и [ROS](ros-install.md).
|
||||
|
||||
## Создание рабочего пространства для симулятора
|
||||
|
||||
В этой статье мы будем использовать `catkin_ws` как имя рабочего пространства (вы можете поменять её). Мы создадим её в домашнем каталоге текущего пользователя (`~`).
|
||||
|
||||
Создайте рабочее пространство и загрузите исходный код Клевера:
|
||||
|
||||
```bash
|
||||
mkdir -p ~/catkin_ws/src
|
||||
cd ~/catkin_ws/src
|
||||
git clone https://github.com/CopterExpress/clover
|
||||
git clone https://github.com/CopterExpress/ros_led
|
||||
```
|
||||
|
||||
Установите все зависимости, используя `rosdep`:
|
||||
|
||||
```bash
|
||||
cd ~/catkin_ws
|
||||
rosdep update
|
||||
rosdep install --from-paths src --ignore-src -y
|
||||
```
|
||||
|
||||
## Загрузка исходного кода PX4
|
||||
|
||||
Сборка PX4 будет осуществлена вместе с другими пакетами в нашем рабочем пространстве. Вы можете загрузить его прямо в рабочее пространство или поместить куда-нибудь и создать симлинк к `~/catkin_ws/src`. Нам также нужно будет поместить его подмодуль `sitl_gazebo` в `~/catkin_ws/src`. Для упрощения мы загрузим прошивку прямо в рабочее пространство:
|
||||
|
||||
```bash
|
||||
cd ~/catkin_ws/src
|
||||
git clone --recursive https://github.com/CopterExpress/Firmware -b v1.10.1-clever
|
||||
ln -s Firmware/Tools/sitl_gazebo ./sitl_gazebo
|
||||
```
|
||||
|
||||
## Установка зависимостей PX4
|
||||
|
||||
PX4 имеет свой собственный скрипт для установки зависимостей. Воспользуемся им:
|
||||
|
||||
```bash
|
||||
cd ~/catkin_ws/src/Firmware/Tools/setup
|
||||
sudo ./ubuntu.sh
|
||||
```
|
||||
|
||||
Он установит все, что нужно для сборки PX4 и SITL.
|
||||
|
||||
Также вы можете пропустить установку ARM тулчейна, если вы не планируете компилировать PX4 для вашего полетного контроллера. Для этого воспользуйтесь флагом `--no-nuttx`:
|
||||
|
||||
```
|
||||
sudo ./ubuntu.sh --no-nuttx
|
||||
```
|
||||
|
||||
## Патчинг плагинов Gazebo
|
||||
|
||||
Пакет `sitl_gazebo`, содержащий плагины нужно пропатчить, из-за недавних изменений в MAVLink. Эти патчи уже применены в [образе виртуальной машины](simulation_vm.md) и хранятся в репозитории CopterExpress/VM. Запустите следующие команды для загрузки и применения патчей:
|
||||
|
||||
```bash
|
||||
cd ~/catkin_ws/src/Firmware/Tools/sitl_gazebo
|
||||
wget https://raw.githubusercontent.com/CopterExpress/clover_vm/master/assets/patches/sitl_gazebo.patch
|
||||
patch -p1 < sitl_gazebo.patch
|
||||
rm sitl_gazebo.patch
|
||||
```
|
||||
|
||||
## Установка датасетов geographiclib
|
||||
|
||||
Для `mavros` нужны датасеты geographiclib:
|
||||
|
||||
```bash
|
||||
cd ~
|
||||
wget https://raw.githubusercontent.com/mavlink/mavros/6f5bd5a1a67c19c2e605f33de296b1b1be9d02fc/mavros/scripts/install_geographiclib_datasets.sh
|
||||
chmod +x ./install_geographiclib_datasets.sh
|
||||
sudo ./install_geographiclib_datasets.sh
|
||||
rm ./install_geographiclib_datasets.sh
|
||||
```
|
||||
|
||||
## Сборка симулятора
|
||||
|
||||
После установки всех зависимостей можно начинать сборку рабочего пространства:
|
||||
|
||||
```bash
|
||||
cd ~/catkin_ws
|
||||
catkin_make
|
||||
```
|
||||
|
||||
> **Note** Некоторые файлы, особенно плагины Gazebo, требуют большого объема оперативной памяти для сборки. Вы можете уменьшить количество параллельных процессов; количество параллельных процессов должно быть равно объёму RAM в гигабайтах, поделенному на 2. Например, для машины с 16Гб следует указывать не более 8 процессов. Вы можете указать количество процессов, используя флаг `-j` : ```catkin_make -j8```
|
||||
|
||||
## Запуск симулятора
|
||||
|
||||
Чтобы удостовериться в том, что все было собрано корректно, попробуйте запустить симулятор:
|
||||
|
||||
```bash
|
||||
source ~/catkin_ws/devel/setup.bash
|
||||
roslaunch clover_simulation simulator.launch
|
||||
```
|
||||
89
docs/ru/simulation_usage.md
Normal file
@@ -0,0 +1,89 @@
|
||||
# Использование симулятора
|
||||
|
||||
Среда симуляции Клевера позволяет пользователям тестировать свой код без какого-либо риска повреждения оборудования. Кроме того, в [виртуальной машине](simulation_vm.md) по умолчанию запущены дополнительные (не относящиеся к ROS) сервисы, которые присутствуют на реальном дроне, например, веб-сервер Monkey.
|
||||
|
||||
## Запуск симулятора
|
||||
|
||||
После [сборки симулятора с нуля](simulation_native.md) или [запуска виртуальной машины](simulation_vm.md), вы можете использовать `roslaunch` для запуска симулятора Gazebo:
|
||||
|
||||
```bash
|
||||
# Не забудьте сначала активировать ваше рабочее пространство
|
||||
source ~/catkin_ws/devel/setup.bash
|
||||
roslaunch clover_simulation simulator.launch
|
||||
```
|
||||
|
||||
> **Note** Кроме того, если вы используете виртуальную машину, просто дважды щелкните `Gazebo PX4` на рабочем столе.
|
||||
|
||||
Это запустит Gazebo сервер и клиент, бинарные файлы PX4 и ноды Клевера. Терминал, в котором была запущена команда, будет отображать отладочные сообщения от нод и PX4, а также принимать входные данные для интерпретатора команд PX4:
|
||||
|
||||

|
||||
|
||||
Вы также можете использовать QGroundControl для настройки параметров дрона в симуляторе, планирование миссий полета (если GPS также симулируется) и управление дроном с пульта:
|
||||
|
||||

|
||||
|
||||
Также вы можете использовать [simplified OFFBOARD](simple_offboard.md) для управления дроном, и средства визуализации ROS, например, [rviz and rqt](rviz.md) для анализа состояния дрона:
|
||||
|
||||

|
||||
|
||||
## Настройка симулятора
|
||||
|
||||
Симулятор можно настроить, передав дополнительные аргументы команде `roslaunch` или изменив файл `~/catkin_ws/src/clover/clover_simulation/launch/simulator.launch`. Ноды, обеспечивающие [распознавание ArUco](aruco.md), [расчет optical flow](optical_flow.md) и другие сервисы могут быть настроены изменением соответствующих `.launch` файлов, как на реальном дроне.
|
||||
|
||||
### Изменение параметров дрона
|
||||
|
||||

|
||||
|
||||
Вы можете включить или отключить некоторые датчики дрона, изменив параметры в файле `simulator.launch`. Например, чтобы включить GPS, установите аргумент `gps` в значение `true`:
|
||||
|
||||
```xml
|
||||
<arg name="gps" value="true"/>
|
||||
```
|
||||
|
||||
Обратите внимание, что это просто включит датчик, вам придется также изменить параметры PX4.
|
||||
|
||||
Если вы хотите добавить датчики или изменить их расположение, вам придется изменить файл описания дрона. Этот файл находится в `~/catkin_ws/src/clover/clover_description/urdf/clover/clover4.xacro`, и использует формат [xacro](http://wiki.ros.org/xacro) для сборки описания URDF.
|
||||
|
||||
### Изменение мира по умолчанию
|
||||
|
||||
Плагины Gazebo для дрона на данный момент требуют, чтобы значение параметра мира `real_time_update_rate` было равно 250, а значение `max_step_size` было равно 0.004. С другими параметрами симулятор не заработает. Используйте файл `~/catkin_ws/src/clover/clover_simulation/resources/worlds/clover.world` как шаблон.
|
||||
|
||||
## Повышение производительности
|
||||
|
||||
Симуляция с использованием Gazebo требовательна к ресурсам, и для нормальной скорости работы требуются мощный процессор и видеокарта. При этом симуляции можно запускать и на менее мощном оборудовании, жертвуя при этом скоростью работы. Ниже приведены рекомендации для компьютеров, на которых симуляция не может работать в реальном времени.
|
||||
|
||||
### Использование плагина `throttling_camera`
|
||||
|
||||
По умолчанию Gazebo не замедляет симуляцию для достижения требуемой частоты работы визуальных сенсоров. Это можно исправить с помощью плагина `throttling_camera` из пакета `clover_simulation`.
|
||||
|
||||
Включение этого плагина происходит путём выставления параметра `maintain_camera_rate` в значение `true` в файле `clover_description/launch/spawn_drone.launch`:
|
||||
|
||||
```xml
|
||||
<!-- Slow simulation down to maintain camera rate -->
|
||||
<arg name="maintain_camera_rate" default="true"/>
|
||||
```
|
||||
|
||||
Этот плагин будет собирать статистику по частоте публикации изображений, и будет замедлять симуляцию до тех пор, пока частота публикации не станет соответствовать или превышать требуемую. При этом значительные замедления симуляции могут негативно сказаться на программном обеспечении, которое подключается к PX4 (например, QGroundControl). Если скорость симуляции опускается ниже, чем 0.5 от реального времени, следует воспользоваться следующей рекомендацией.
|
||||
|
||||
### Выставление скорости симуляции
|
||||
|
||||
PX4, начиная с версии 1.9, поддерживает [принудительную установку скорости симуляции](https://dev.px4.io/v1.9.0/en/simulation/#simulation_speed) с помощью переменной окружения `PX4_SIM_SPEED_FACTOR`. Выставление этой переменной подготавливает все компоненты симулятора к соответствующему ускорению/замедлению.
|
||||
|
||||
Значение этой переменной должно соответствовать величине Real Time Factor (скорости симуляции по отношению к реальному времени), получаемой при использовании `throttling_camera`. Величина Real Time Factor отображается в окне Gazebo на нижней панели:
|
||||
|
||||

|
||||
|
||||
В данном случае `PX4_SIM_SPEED_FACTOR` следует выставить в значение `0.42` перед запуском симулятора:
|
||||
|
||||
```bash
|
||||
PX4_SIM_SPEED_FACTOR=0.42 roslaunch clover_simulation simulator.launch
|
||||
```
|
||||
|
||||
> **Note** При использовании виртуальной машины удобнее добавить эту переменную в ярлык запуска Gazebo на рабочем столе. Нажмите правой кнопкой на значок Gazebo, выберите "Properties..." и добавьте `PX4_SIM_SPEED_FACTOR=0.42` в поле Command, как показано на иллюстрации:
|
||||

|
||||
|
||||
### Выделение ресурсов для виртуальной машины
|
||||
|
||||
Выделение нескольких процессорных ядер для виртуальной машины может значительно повысить производительность симуляции. В наших испытаниях виртуальная машина, для которой было выделено одно ядро, не позволяла работать в симуляторе: окно Gazebo не реагировало на пользовательский ввод, сообщения ROS терялись. После выделения четырёх ядер для этой же виртуальной машины симуляция стала работать со скоростью 0.25 от реального времени.
|
||||
|
||||
При этом не следует пытаться выделить для виртуальной машины больше ресурсов, чем доступно на основной системе.
|
||||
66
docs/ru/simulation_vm.md
Normal file
@@ -0,0 +1,66 @@
|
||||
# Установка виртуальной машины
|
||||
|
||||
Для работы с платформой Клевер рекомендуется иметь [установленное окружение ROS](ros.md) на своём компьютере. К сожалению, [установка ROS](ros-install.md) сопряжена с рядом трудностей: требуется использовать операционную систему Ubuntu 18.04, процесс установки длительный и требует выполнения большого количества команд в терминале.
|
||||
|
||||
Для облегчения процесса настройки окружения мы предлагаем использовать виртуальную машину со всем необходимым для работы с платформой Клевер. В состав виртуальной машины входят:
|
||||
|
||||
* операционная система Ubuntu 18.04 с легковесной графической оболочкой XFCE;
|
||||
* предустановленные пакеты ROS для работы с Клевером;
|
||||
* QGroundControl;
|
||||
* предварительно настроенный симулятор Gazebo;
|
||||
* среда разработки Visual Studio Code с плагинами для разработки на Python и C++.
|
||||
|
||||
Виртуальная машина может использоваться как для запуска симуляторов, так и для работы с настоящим дроном.
|
||||
|
||||
Скачать текущую версию виртуальной машины можно [в релизах репозитория виртуальной машины](https://github.com/CopterExpress/clover_vm/releases)
|
||||
|
||||
> **Warning** Виртуальную машину следует использовать только в тех случаях, когда по каким-то причинам использование Ubuntu 18.04 напрямую невозможно. Производительность всех программ, особенно тех, которые используют 3D-графику - jMAVSim, Gazebo, rviz - будет существенно ниже; кроме того, в ряде случаев будут возникать графические ошибки, приводящие к частичной или полной неработоспособности указанных программ.
|
||||
|
||||
## Установка виртуальной машины
|
||||
|
||||
Для запуска виртуальной машины разработчика требуется использовать одну из совместимых сред виртуализации: [VirtualBox](https://www.virtualbox.org/wiki/Downloads), [VMware Player](https://www.vmware.com/products/workstation-player.html), [VMware Workstation](https://www.vmware.com/products/workstation-pro.html).
|
||||
|
||||
> **Note** На момент написания данной статьи VirtualBox не обеспечивал достаточный уровень совместимости с виртуальной машиной. Рекомендуется по возможности использовать VMware Player или VMware Workstation; дальнейшая инструкция будет преимущественно написана для VMware Player.
|
||||
|
||||
Убедитесь, что поддержка аппаратной виртуализации включена в настройках BIOS/UEFI вашего компьютера. Шаги для включения аппаратной виртуализации, как правило, описаны в руководстве пользователя компьютера. Проконсультируйтесь с производителем компьютера, если включить виртуализацию не получается.
|
||||
|
||||
1. Импортируйте архив виртуальной машины в среду виртуализации. Для VMware Player используйте опцию **Open a Virtual Machine**:
|
||||
|
||||

|
||||
|
||||
> **Note** При импорте архива, скорее всего, появится окно с предупреждением о формате виртуальной машины:
|
||||

|
||||
Это предупреждение можно игнорировать и нажать кнопку **Retry**.
|
||||
|
||||
2. Откройте окно настроек виртуальной машины и измените параметры для наилучшего соответствия основной системе:
|
||||
|
||||
* увеличьте объём оперативной памяти, отводимый для виртуальной машины:
|
||||

|
||||
* увеличьте количество доступных процессорных ядер:
|
||||

|
||||
* включите 3D-ускорение:
|
||||

|
||||
* включите использование USB 2.0/3.0:
|
||||

|
||||
* опционально включите режим "мост" для виртуального сетевого адаптера:
|
||||

|
||||
|
||||
> **Note** Режим "мост" может некорректно работать с некоторыми сетевыми адаптерами. Если в режиме "мост" вы не можете подключиться к дрону, используйте USB Wi-Fi-адаптеры, "проброшенные" в виртуальную машину.
|
||||
|
||||
3. Запустите виртуальную машину. Возможно, при первом запуске справа появятся сообщения об отсутствии поддержки 3D-ускорения со стороны основной системы:
|
||||
|
||||

|
||||
|
||||
В этом случае убедитесь, что у вас установлены самые последние драйверы для видеокарты в основной системе. Если сообщения появляются при повторных запусках виртуальной машины, добавьте строку
|
||||
|
||||
```
|
||||
mks.gl.allowBlacklistedDrivers = "TRUE"
|
||||
```
|
||||
|
||||
в файл `clever-devel.vmx`, находящийся в папке, в которую был импортирован архив в п. 1.
|
||||
|
||||
4. Настройте режим моста через настройки виртуальной машины (если используется VMware Player для Windows) или с помощью утилиты `vmware-netcfg` (если используется версия для Linux-дистрибутивов):
|
||||
|
||||

|
||||
|
||||
В списке сетей выберите `vmnet0`, ниже - режим *Bridged*, в выпадающем списке *Bridged to* - название беспроводного адаптера, с помощью которого будет производиться подключение к дрону.
|
||||
@@ -1,6 +1,6 @@
|
||||
# Симуляция PX4
|
||||
|
||||
> **Hint** Мы также предоставляем [предварительно настроенный](sitl_docker.md) симулятор, поставляемый в виде Docker-контейнера!
|
||||
> **Hint** Мы также предоставляем [конфигурации для Gazebo](simulation.md) и [образ виртуальной машины](simulation_vm.md) со всем необходимым для запуска симуляции Клевера.
|
||||
|
||||
Основная статья: https://dev.px4.io/en/simulation/
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# Docker-контейнер с преднастроенным SITL
|
||||
|
||||
> **Warning** Рекомендуется использовать [образ виртуальной машины](simulation_vm.md) или [нативную установку](simulation_native.md) для работы в симуляторе.
|
||||
|
||||

|
||||
|
||||
Для упрощения запуска симулятора предлагается использовать предварительно настроенный [Docker-контейнер](https://hub.docker.com/r/sfalexrog/clever-sitl) с симулятором [Gazebo](http://gazebosim.org/), автопилотом [PX4](https://px4.io/) и предустановленными пакетами Клевера.
|
||||
|
||||