mirror of
https://gitee.com/mirrors_PX4/PX4-Autopilot.git
synced 2026-10-03 14:08:52 +08:00
Move PX4 Guide source into /docs (#24490)
* Add vitepress tree * Update existing workflows so they dont trigger on changes in the docs path * Add nojekyll, package.json, LICENCE etc * Add crowdin docs upload/download scripts * Add docs flaw checker workflows * Used docs prefix for docs workflows * Crowdin obvious fixes * ci: docs move to self hosted runner runs on a beefy server for faster builds Signed-off-by: Ramon Roche <mrpollo@gmail.com> * ci: don't run build action for docs or ci changes Signed-off-by: Ramon Roche <mrpollo@gmail.com> * ci: update runners Signed-off-by: Ramon Roche <mrpollo@gmail.com> * Add docs/en * Add docs assets and scripts * Fix up editlinks to point to PX4 sources * Download just the translations that are supported * Add translation sources for zh, uk, ko * Update latest tranlsation and uorb graphs * update vitepress to latest --------- Signed-off-by: Ramon Roche <mrpollo@gmail.com> Co-authored-by: Ramon Roche <mrpollo@gmail.com>
This commit is contained in:
co-authored by
Ramon Roche
parent
8e6d2ebe4a
commit
88d623bedb
@@ -0,0 +1,3 @@
|
||||
# Безперервна інтеграція
|
||||
|
||||
PX4 збірки і тестування виконуються використовуючи GitHub і сервер Jenkins .
|
||||
@@ -0,0 +1,271 @@
|
||||
# Docker контейнери для PX4
|
||||
|
||||
Docker containers are provided for the complete [PX4 development toolchain](../dev_setup/dev_env.md#supported-targets) including NuttX and Linux based hardware, [Gazebo Classic](../sim_gazebo_classic/index.md) simulation, and [ROS](../simulation/ros_interface.md).
|
||||
|
||||
This topic shows how to use the [available docker containers](#px4_containers) to access the build environment in a local Linux computer.
|
||||
|
||||
:::info
|
||||
Dockerfiles and README can be found on [Github here](https://github.com/PX4/PX4-containers/tree/master?tab=readme-ov-file#container-hierarchy).
|
||||
They are built automatically on [Docker Hub](https://hub.docker.com/u/px4io/).
|
||||
:::
|
||||
|
||||
## Вимоги
|
||||
|
||||
:::info
|
||||
PX4 containers are currently only supported on Linux (if you don't have Linux you can run the container [inside a virtual machine](#virtual_machine)).
|
||||
Do not use `boot2docker` with the default Linux image because it contains no X-Server.
|
||||
:::
|
||||
|
||||
[Install Docker](https://docs.docker.com/installation/) for your Linux computer, preferably using one of the Docker-maintained package repositories to get the latest stable version. You can use either the _Enterprise Edition_ or (free) _Community Edition_.
|
||||
|
||||
For local installation of non-production setups on _Ubuntu_, the quickest and easiest way to install Docker is to use the [convenience script](https://docs.docker.com/install/linux/docker-ce/ubuntu/#install-using-the-convenience-script) as shown below (alternative installation methods are found on the same page):
|
||||
|
||||
```sh
|
||||
curl -fsSL get.docker.com -o get-docker.sh
|
||||
sudo sh get-docker.sh
|
||||
```
|
||||
|
||||
The default installation requires that you invoke _Docker_ as the root user (i.e. using `sudo`). However, for building the PX4 firmware we suggest to [use docker as a non-root user](https://docs.docker.com/install/linux/linux-postinstall/#manage-docker-as-a-non-root-user). Таким чином, директорія для збірки не буде належати користувачу root після використання docker.
|
||||
|
||||
```sh
|
||||
# Create docker group (may not be required)
|
||||
sudo groupadd docker
|
||||
# Add your user to the docker group.
|
||||
sudo usermod -aG docker $USER
|
||||
# Log in/out again before using docker!
|
||||
```
|
||||
|
||||
<a id="px4_containers"></a>
|
||||
|
||||
## Ієрархія контейнерів
|
||||
|
||||
The available containers are on [Github here](https://github.com/PX4/PX4-containers/tree/master?tab=readme-ov-file#container-hierarchy).
|
||||
|
||||
Вони дозволяють тестувати різні цілі збірки та конфігурації (включені інструменти можна зрозуміти з їх назв).
|
||||
Контейнери є ієрархічними, тобто такими, що мають функціональність вихідних контейнерів.
|
||||
For example, the partial hierarchy below shows that the docker container with nuttx build tools (`px4-dev-nuttx-focal`) does not include ROS 2, while the simulation containers do:
|
||||
|
||||
```plain
|
||||
- px4io/px4-dev-base-focal
|
||||
- px4io/px4-dev-nuttx-focal
|
||||
- px4io/px4-dev-simulation-focal
|
||||
- px4io/px4-dev-ros-noetic
|
||||
- px4io/px4-dev-ros2-foxy
|
||||
- px4io/px4-dev-ros2-rolling
|
||||
- px4io/px4-dev-base-jammy
|
||||
- px4io/px4-dev-nuttx-jammy
|
||||
```
|
||||
|
||||
The most recent version can be accessed using the `latest` tag: `px4io/px4-dev-nuttx-focal:latest`
|
||||
(available tags are listed for each container on _hub.docker.com_.
|
||||
For example, the `px4io/px4-dev-nuttx-focal` tags can be found here).
|
||||
|
||||
:::tip
|
||||
Typically you should use a recent container, but not necessarily the `latest` (as this changes too often).
|
||||
:::
|
||||
|
||||
## Використання Docker контейнера
|
||||
|
||||
Наступні інструкції показують, як зібрати вихідний код PX4 на основному комп'ютері за допомогою інструментарію, що працює у docker контейнері.
|
||||
The information assumes that you have already downloaded the PX4 source code to **src/PX4-Autopilot**, as shown:
|
||||
|
||||
```sh
|
||||
mkdir src
|
||||
cd src
|
||||
git clone https://github.com/PX4/PX4-Autopilot.git
|
||||
cd PX4-Autopilot
|
||||
```
|
||||
|
||||
### Допоміжний скрипт (docker_run.sh)
|
||||
|
||||
The easiest way to use the containers is via the [docker_run.sh](https://github.com/PX4/PX4-Autopilot/blob/main/Tools/docker_run.sh) helper script.
|
||||
This script takes a PX4 build command as an argument (e.g. `make tests`). Він запускає docker із найновішою версією відповідного контейнера (вказано в коді) і слушними налаштуваннями середовища.
|
||||
|
||||
For example, to build SITL you would call (from within the **/PX4-Autopilot** directory):
|
||||
|
||||
```sh
|
||||
./Tools/docker_run.sh 'make px4_sitl_default'
|
||||
```
|
||||
|
||||
Або почати сеанс bash використовуючи інструментарій NuttX:
|
||||
|
||||
```sh
|
||||
./Tools/docker_run.sh 'bash'
|
||||
```
|
||||
|
||||
:::tip
|
||||
The script is easy because you don't need to know anything much about _Docker_ or think about what container to use. Однак він не дуже надійний! The manual approach discussed in the [section below](#manual_start) is more flexible and should be used if you have any problems with the script.
|
||||
:::
|
||||
|
||||
<a id="manual_start"></a>
|
||||
|
||||
### Запуск Docker вручну
|
||||
|
||||
Синтаксис типової команди показано нижче.
|
||||
Це запускає Docker контейнер з підтримкою переадресації X (що робить графічний інтерфейс симуляції доступним з середини контейнера).
|
||||
It maps the directory `<host_src>` from your computer to `<container_src>` inside the container and forwards the UDP port needed to connect _QGroundControl_.
|
||||
With the `-–privileged` option it will automatically have access to the devices on your host (e.g. a joystick and GPU). Якщо ви під'єднуєте/від'єднуєте пристрій, вам слід перезапустити контейнер.
|
||||
|
||||
```sh
|
||||
# enable access to xhost from the container
|
||||
xhost +
|
||||
|
||||
# Run docker
|
||||
docker run -it --privileged \
|
||||
--env=LOCAL_USER_ID="$(id -u)" \
|
||||
-v <host_src>:<container_src>:rw \
|
||||
-v /tmp/.X11-unix:/tmp/.X11-unix:ro \
|
||||
-e DISPLAY=:0 \
|
||||
-p 14570:14570/udp \
|
||||
--name=<local_container_name> <container>:<tag> <build_command>
|
||||
```
|
||||
|
||||
Де:
|
||||
|
||||
- `<host_src>`: The host computer directory to be mapped to `<container_src>` in the container. This should normally be the **PX4-Autopilot** directory.
|
||||
- `<container_src>`: The location of the shared (source) directory when inside the container.
|
||||
- `<local_container_name>`: A name for the docker container being created. Це потім можна використовувати, якщо потрібно посилатись на контейнер знову.
|
||||
- `<container>:<tag>`: The container with version tag to start - e.g.: `px4io/px4-dev-ros:2017-10-23`.
|
||||
- `<build_command>`: The command to invoke on the new container. Наприклад, `bash` is used to open a bash shell in the container.
|
||||
|
||||
The concrete example below shows how to open a bash shell and share the directory **~/src/PX4-Autopilot** on the host computer.
|
||||
|
||||
```sh
|
||||
# дозвольте доступ до xhost з контейнера
|
||||
xhost +
|
||||
|
||||
# запуск docker та оболонки bash
|
||||
docker run -it --privileged \
|
||||
--env=LOCAL_USER_ID="$(id -u)" \
|
||||
-v ~/src/PX4-Autopilot:/src/PX4-Autopilot/:rw \
|
||||
-v /tmp/.X11-unix:/tmp/.X11-unix:ro \
|
||||
-e DISPLAY=:0 \
|
||||
--network host \
|
||||
--name=px4-ros px4io/px4-dev-ros2-foxy:2022-07-31 bash
|
||||
```
|
||||
|
||||
:::info
|
||||
We use the host network mode to avoid conflicts between the UDP port access control when using QGroundControl on the same system as the docker container.
|
||||
:::
|
||||
|
||||
:::info
|
||||
If you encounter the error "Can't open display: :0", `DISPLAY` may need to be set to a different value.
|
||||
On Linux (XWindow) hosts you can change `-e DISPLAY=:0` to `-e DISPLAY=$DISPLAY`.
|
||||
On other hosts you might iterate the value of `0` in `-e DISPLAY=:0` until the "Can't open display: :0" error goes away.
|
||||
:::
|
||||
|
||||
Якщо все пройшло добре, ви повинні бути в новій оболонці bash.
|
||||
Перевірте, чи все працює запустивши, наприклад, SITL:
|
||||
|
||||
```sh
|
||||
cd src/PX4-Autopilot #This is <container_src>
|
||||
make px4_sitl_default gazebo-classic
|
||||
```
|
||||
|
||||
### Повторний вхід в контейнер
|
||||
|
||||
The `docker run` command can only be used to create a new container. Щоб повернутися у цей контейнер (що збереже ваші зміни) просто зробіть:
|
||||
|
||||
```sh
|
||||
# запуск контейнера
|
||||
docker start container_name
|
||||
# запуск нової оболонки bash shell в цьому контейнері
|
||||
docker exec -it container_name bash
|
||||
```
|
||||
|
||||
Якщо вам потрібні кілька консолей, підключених до контейнера, просто відкрийте нову оболонку і виконайте останню команду знову.
|
||||
|
||||
### Видалення контейнера
|
||||
|
||||
Іноді може знадобитися взагалі видалити контейнер. Це можна зробити, використовуючи його ім'я:
|
||||
|
||||
```sh
|
||||
docker rm mycontainer
|
||||
```
|
||||
|
||||
Якщо ви не можете згадати назву, ви можете знайти неактивні ідентифікатори контейнерів і видалити їх, як показано нижче:
|
||||
|
||||
```sh
|
||||
docker ps -a -q
|
||||
45eeb98f1dd9
|
||||
docker rm 45eeb98f1dd9
|
||||
```
|
||||
|
||||
### QGroundControl
|
||||
|
||||
When running a simulation instance e.g. SITL inside the docker container and controlling it via _QGroundControl_ from the host, the communication link has to be set up manually. The autoconnect feature of _QGroundControl_ does not work here.
|
||||
|
||||
In _QGroundControl_, navigate to [Settings](https://docs.qgroundcontrol.com/master/en/qgc-user-guide/settings_view/settings_view.html) and select Comm Links. Створіть новий канал, що використовує UDP-протокол. The port depends on the used [configuration](https://github.com/PX4/PX4-Autopilot/blob/main/ROMFS/px4fmu_common/init.d-posix/rcS) e.g. port 14570 for the SITL config. IP-адреса є адресою одного з ваших контейнерів, зазвичай це адреса з мережі 172.17.0.1/16 при використанні мережі за замовчуванням. The IP address of the docker container can be found with the following command (assuming the container name is `mycontainer`):
|
||||
|
||||
```sh
|
||||
$ docker inspect -f '{ {range .NetworkSettings.Networks}}{ {.IPAddress}}{ {end}}' mycontainer
|
||||
```
|
||||
|
||||
:::info
|
||||
Spaces between double curly braces above should be not be present (they are needed to avoid a UI rendering problem in gitbook).
|
||||
:::
|
||||
|
||||
### Усунення проблем
|
||||
|
||||
#### Помилки з правами доступу
|
||||
|
||||
Контейнер створює файли, необхідні для роботи від імені стандартного користувача, як правило, "root". Це може призвести до помилок прав доступу, коли користувач на основному комп'ютері не має доступу до файлів, створених контейнером.
|
||||
|
||||
The example above uses the line `--env=LOCAL_USER_ID="$(id -u)"` to create a user in the container with the same UID as the user on the host. Це гарантує, що всі файли, створені у контейнері, будуть доступні з основного комп'ютера.
|
||||
|
||||
#### Проблеми з драйверами графіки
|
||||
|
||||
Можливо, що запуск Gazebo Classic призведе до подібного повідомлення про помилку:
|
||||
|
||||
```sh
|
||||
libGL error: failed to load driver: swrast
|
||||
```
|
||||
|
||||
У цьому випадку необхідно встановити нативний графічний драйвер для вашої системи. Завантажте відповідний драйвер і встановіть його всередині контейнера. Для драйверів Nvidia слід використовувати наступну команду (інакше встановлювач побачить завантажені модулі на головній машині та відмовиться продовжувати):
|
||||
|
||||
```sh
|
||||
./NVIDIA-DRIVER.run -a -N --ui=none --no-kernel-module
|
||||
```
|
||||
|
||||
More information on this can be found [here](http://gernotklingler.com/blog/howto-get-hardware-accelerated-opengl-support-docker/).
|
||||
|
||||
<a id="virtual_machine"></a>
|
||||
|
||||
## Підтримка віртуальних машин
|
||||
|
||||
Будь-який останній дистрибутив Linux повинен працювати.
|
||||
|
||||
Наступна конфігурація протестована:
|
||||
|
||||
- OS X з підтримкою VMWare Fusion і Ubuntu 14.04 (Docker контейнер з підтримкою GUI в Parallels призводить до падіння X-Server).
|
||||
|
||||
**Memory**
|
||||
|
||||
Потрібно не менше 4 ГБ пам'яті для віртуальної машини.
|
||||
|
||||
**Compilation problems**
|
||||
|
||||
Якщо компіляція завершується з помилками на кшталт:
|
||||
|
||||
```sh
|
||||
The bug is not reproducible, so it is likely a hardware or OS problem.
|
||||
c++: internal compiler error: Killed (program cc1plus)
|
||||
```
|
||||
|
||||
Спробуйте вимкнути паралельну збірку.
|
||||
|
||||
**Allow Docker Control from the VM Host**
|
||||
|
||||
Edit `/etc/defaults/docker` and add this line:
|
||||
|
||||
```sh
|
||||
DOCKER_OPTS="${DOCKER_OPTS} -H unix:///var/run/docker.sock -H 0.0.0.0:2375"
|
||||
```
|
||||
|
||||
Тепер можна керувати docker на вашій основній ОС:
|
||||
|
||||
```sh
|
||||
export DOCKER_HOST=tcp://<ip of your VM>:2375
|
||||
# run some docker command to see if it works, e.g. ps
|
||||
docker ps
|
||||
```
|
||||
@@ -0,0 +1,14 @@
|
||||
# Тестування платформи та безперервна інтеграція
|
||||
|
||||
PX4 широко протестовано за допомогою модульних та інтеграційних тестів шляхом безперервної інтеграції.
|
||||
Тестування польоту також відбувається командою розробників та широкою спільнотою.
|
||||
|
||||
Розділи тестування:
|
||||
|
||||
- [Test Flights](../test_and_ci/test_flights.md) - How to make test flights (e.g. to [test PRs](../contribute/code.md#pull-requests))
|
||||
- [Unit Tests](../test_and_ci/unit_tests.md)
|
||||
- [Continuous Integration (CI)](../test_and_ci/continous_integration.md)
|
||||
- [ROS Integration Testing](../test_and_ci/integration_testing.md)
|
||||
- [MAVSDK Integration Testing](../test_and_ci/integration_testing_mavsdk.md)
|
||||
- [Docker](../test_and_ci/docker.md)
|
||||
- [Maintenance](../test_and_ci/maintenance.md)
|
||||
@@ -0,0 +1,152 @@
|
||||
# Тестування інтеграції з використанням ROS
|
||||
|
||||
У цій темі пояснюється, як запускати (і розширювати) інтеграційні тести PX4 на основі ROS.
|
||||
|
||||
:::info
|
||||
[MAVSDK Integration Testing](../test_and_ci/integration_testing_mavsdk.md) is preferred when writing new tests.
|
||||
Use the ROS-based integration test framework for use cases that _require_ ROS (e.g. object avoidance).
|
||||
|
||||
All PX4 integraton tests are executed automatically by our [Continuous Integration](../test_and_ci/continous_integration.md) system.
|
||||
:::
|
||||
|
||||
## Попередня підготовка:
|
||||
|
||||
- [jMAVSim Simulator](../sim_jmavsim/index.md)
|
||||
- [Gazebo Classic Simulator](../sim_gazebo_classic/index.md)
|
||||
- [ROS and MAVROS](../simulation/ros_interface.md)
|
||||
|
||||
## Виконати тести
|
||||
|
||||
Щоб запустити тести MAVROS:
|
||||
|
||||
```sh
|
||||
source <catkin_ws>/devel/setup.bash
|
||||
cd <PX4-Autopilot_clone>
|
||||
make px4_sitl_default sitl_gazebo
|
||||
make <test_target>
|
||||
```
|
||||
|
||||
`test_target` is a makefile targets from the set: _tests_mission_, _tests_mission_coverage_, _tests_offboard_ and _tests_avoidance_.
|
||||
|
||||
Test can also be executed directly by running the test scripts, located under `test/`:
|
||||
|
||||
```sh
|
||||
source <catkin_ws>/devel/setup.bash
|
||||
cd <PX4-Autopilot_clone>
|
||||
make px4_sitl_default sitl_gazebo
|
||||
./test/<test_bash_script> <test_launch_file>
|
||||
```
|
||||
|
||||
Наприклад:
|
||||
|
||||
```sh
|
||||
./test/rostest_px4_run.sh mavros_posix_tests_offboard_posctl.test
|
||||
```
|
||||
|
||||
Тести також можна запускати за допомогою графічного інтерфейсу користувача, щоб побачити, що відбувається (за замовчуванням тести виконуються без голови):
|
||||
|
||||
```sh
|
||||
./test/rostest_px4_run.sh mavros_posix_tests_offboard_posctl.test gui:=true headless:=false
|
||||
```
|
||||
|
||||
The **.test** files launch the corresponding Python tests defined in `integrationtests/python_src/px4_it/mavros/`
|
||||
|
||||
## Напишіть новий MAVROS-тест (Python)
|
||||
|
||||
Цей розділ пояснює, як написати новий python тест з використанням ROS 1/MAVROS, протестувати його та додати до набору тестів PX4.
|
||||
|
||||
We recommend you review the existing tests as examples/inspiration ([integrationtests/python_src/px4_it/mavros/](https://github.com/PX4/PX4-Autopilot/tree/main/integrationtests/python_src/px4_it/mavros)).
|
||||
The official ROS documentation also contains information on how to use [unittest](http://wiki.ros.org/unittest) (on which this test suite is based).
|
||||
|
||||
Щоб написати новий тест:
|
||||
|
||||
1. Створити новий тестовий скрипт, копіюючи порожній тестовий каркас нижче:
|
||||
|
||||
```python
|
||||
#!/usr/bin/env python
|
||||
# [... LICENSE ...]
|
||||
|
||||
#
|
||||
# @author Example Author <author@example.com>
|
||||
#
|
||||
PKG = 'px4'
|
||||
|
||||
import unittest
|
||||
import rospy
|
||||
import rosbag
|
||||
|
||||
from sensor_msgs.msg import NavSatFix
|
||||
|
||||
class MavrosNewTest(unittest.TestCase):
|
||||
"""
|
||||
Test description
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
rospy.init_node('test_node', anonymous=True)
|
||||
rospy.wait_for_service('mavros/cmd/arming', 30)
|
||||
|
||||
rospy.Subscriber("mavros/global_position/global", NavSatFix, self.global_position_callback)
|
||||
self.rate = rospy.Rate(10) # 10hz
|
||||
self.has_global_pos = False
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
#
|
||||
# General callback functions used in tests
|
||||
#
|
||||
def global_position_callback(self, data):
|
||||
self.has_global_pos = True
|
||||
|
||||
def test_method(self):
|
||||
"""Test method description"""
|
||||
|
||||
# FIXME: hack to wait for simulation to be ready
|
||||
while not self.has_global_pos:
|
||||
self.rate.sleep()
|
||||
|
||||
# TODO: execute test
|
||||
|
||||
if __name__ == '__main__':
|
||||
import rostest
|
||||
rostest.rosrun(PKG, 'mavros_new_test', MavrosNewTest)
|
||||
```
|
||||
|
||||
2. Запустити лише новий тест
|
||||
|
||||
- Запустити симулятор
|
||||
|
||||
```sh
|
||||
cd <PX4-Autopilot_clone>
|
||||
source Tools/simulation/gazebo/setup_gazebo.bash
|
||||
roslaunch launch/mavros_posix_sitl.launch
|
||||
```
|
||||
|
||||
- Запустити тест (в новій оболонці):
|
||||
|
||||
```sh
|
||||
cd <PX4-Autopilot_clone>
|
||||
source Tools/simulation/gazebo/setup_gazebo.bash
|
||||
rosrun px4 mavros_new_test.py
|
||||
```
|
||||
|
||||
3. Додати новий тестовий вузол до файлу запуску
|
||||
|
||||
- In `test/` create a new `<test_name>.test` ROS launch file.
|
||||
- Call the test file using one of the base scripts _rostest_px4_run.sh_ or _rostest_avoidance_run.sh_
|
||||
|
||||
4. (Необов'язково) Створити нову ціль в Makefile
|
||||
|
||||
- Відкрийте Makefile
|
||||
- Search the _Testing_ section
|
||||
- Додати нову назву цілі та викликати тест
|
||||
|
||||
Наприклад:
|
||||
|
||||
```sh
|
||||
tests_<new_test_target_name>: rostest
|
||||
@"$(SRC_DIR)"/test/rostest_px4_run.sh mavros_posix_tests_<new_test>.test
|
||||
```
|
||||
|
||||
Запустити тести, як описані вище.
|
||||
@@ -0,0 +1,157 @@
|
||||
# Інтеграційне тестування за допомогою MAVSDK
|
||||
|
||||
PX4 can be tested end to end to using integration tests based on [MAVSDK](https://mavsdk.mavlink.io).
|
||||
|
||||
Тести в основному розробляються для SITL і запускаються в режимі безперервної інтеграції (CI).
|
||||
В майбутньому ми плануємо зробити їх універсальними для будь-якої платформи/обладнання.
|
||||
|
||||
Інструкції нижче пояснюють, як налаштувати та запустити тести локально.
|
||||
|
||||
## Вимоги
|
||||
|
||||
### Налаштування середовища розробника
|
||||
|
||||
Якщо ви цього ще не зробили:
|
||||
|
||||
- Install the development toolchain for [Linux](../dev_setup/dev_env_linux_ubuntu.md) or [macOS](../dev_setup/dev_env_mac.md) (Windows not supported).
|
||||
[Gazebo Classic](../sim_gazebo_classic/index.md) is required, and should be installed by default.
|
||||
- [Get the PX4 source code](../dev_setup/building_px4.md#download-the-px4-source-code):
|
||||
|
||||
```sh
|
||||
git clone https://github.com/PX4/PX4-Autopilot.git --recursive
|
||||
cd PX4-Autopilot
|
||||
```
|
||||
|
||||
### Збірка PX4 для тестування
|
||||
|
||||
Щоб зібрати вихідний код PX4 для тестування на симуляторі, скористайтеся:
|
||||
|
||||
```sh
|
||||
DONT_RUN=1 make px4_sitl gazebo-classic mavsdk_tests
|
||||
```
|
||||
|
||||
### Встановлення бібліотеки C++ MAVSDK
|
||||
|
||||
The tests need the MAVSDK C++ library installed system-wide (e.g. in `/usr/lib` or `/usr/local/lib`).
|
||||
|
||||
Встановлюйте або з бінарних файлів, або з джерела:
|
||||
|
||||
- [MAVSDK > C++ > C++ QuickStart](https://mavsdk.mavlink.io/main/en/cpp/quickstart.html): Install as a prebuilt library on supported platforms (recommended)
|
||||
- [MAVSDK > C++ Guide > Building from Source](https://mavsdk.mavlink.io/main/en/cpp/guide/build.html): Build C++ library from source.
|
||||
|
||||
## Запуск усіх PX4 тестів
|
||||
|
||||
To run all SITL tests as defined in [sitl.json](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/configs/sitl.json), do:
|
||||
|
||||
```sh
|
||||
test/mavsdk_tests/mavsdk_test_runner.py test/mavsdk_tests/configs/sitl.json --speed-factor 10
|
||||
```
|
||||
|
||||
Буде перелічено всі тести, а потім запущено їх послідовно.
|
||||
|
||||
To see all possible command line arguments use the `-h` argument:
|
||||
|
||||
```sh
|
||||
test/mavsdk_tests/mavsdk_test_runner.py -h
|
||||
|
||||
usage: mavsdk_test_runner.py [-h] [--log-dir LOG_DIR] [--speed-factor SPEED_FACTOR] [--iterations ITERATIONS] [--abort-early] [--gui] [--model MODEL]
|
||||
[--case CASE] [--debugger DEBUGGER] [--verbose]
|
||||
config_file
|
||||
|
||||
positional arguments:
|
||||
config_file JSON config file to use
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
--log-dir LOG_DIR Directory for log files
|
||||
--speed-factor SPEED_FACTOR
|
||||
how fast to run the simulation
|
||||
--iterations ITERATIONS
|
||||
how often to run all tests
|
||||
--abort-early abort on first unsuccessful test
|
||||
--gui display the visualization for a simulation
|
||||
--model MODEL only run tests for one model
|
||||
--case CASE only run tests for one case
|
||||
--debugger DEBUGGER choice from valgrind, callgrind, gdb, lldb
|
||||
--verbose enable more verbose output
|
||||
```
|
||||
|
||||
## Запуск одного тесту
|
||||
|
||||
Run a single test by specifying the `model` and test `case` as command line options.
|
||||
Наприклад, щоб протестувати керування хвостовиком у місії, ви можете виконати:
|
||||
|
||||
```sh
|
||||
test/mavsdk_tests/mavsdk_test_runner.py test/mavsdk_tests/configs/sitl.json --speed-factor 10 --model tailsitter --case 'Fly VTOL mission'
|
||||
```
|
||||
|
||||
The easiest way to find out the current set of models and their associated test cases is to run all PX4 tests [as shown above](#run-all-px4-tests) (note, you can then cancel the build if you wish to test just one).
|
||||
|
||||
На момент написання статті список, згенерований в результаті запуску всіх тестів, є таким:
|
||||
|
||||
```sh
|
||||
About to run 39 test cases for 3 selected models (1 iteration):
|
||||
- iris:
|
||||
- 'Land on GPS lost during mission (baro height mode)'
|
||||
- 'Land on GPS lost during mission (GPS height mode)'
|
||||
- 'Continue on mag lost during mission'
|
||||
- 'Continue on baro lost during mission (baro height mode)'
|
||||
- 'Continue on baro lost during mission (GPS height mode)'
|
||||
- 'Continue on baro stuck during mission (baro height mode)'
|
||||
- 'Continue on baro stuck during mission (GPS height mode)'
|
||||
- 'Takeoff and Land'
|
||||
- 'Fly square Multicopter Missions including RTL'
|
||||
- 'Fly square Multicopter Missions with manual RTL'
|
||||
- 'Fly straight Multicopter Mission'
|
||||
- 'Offboard takeoff and land'
|
||||
- 'Offboard position control'
|
||||
- 'Fly forward in position control'
|
||||
- 'Fly forward in altitude control'
|
||||
- standard_vtol:
|
||||
- 'Land on GPS lost during mission (baro height mode)'
|
||||
- 'Land on GPS lost during mission (GPS height mode)'
|
||||
- 'Continue on mag lost during mission'
|
||||
- 'Continue on baro lost during mission (baro height mode)'
|
||||
- 'Continue on baro lost during mission (GPS height mode)'
|
||||
- 'Continue on baro stuck during mission (baro height mode)'
|
||||
- 'Continue on baro stuck during mission (GPS height mode)'
|
||||
- 'Takeoff and Land'
|
||||
- 'Fly square Multicopter Missions including RTL'
|
||||
- 'Fly square Multicopter Missions with manual RTL'
|
||||
- 'Fly forward in position control'
|
||||
- 'Fly forward in altitude control'
|
||||
- tailsitter:
|
||||
- 'Land on GPS lost during mission (baro height mode)'
|
||||
- 'Land on GPS lost during mission (GPS height mode)'
|
||||
- 'Continue on mag lost during mission'
|
||||
- 'Continue on baro lost during mission (baro height mode)'
|
||||
- 'Continue on baro lost during mission (GPS height mode)'
|
||||
- 'Continue on baro stuck during mission (baro height mode)'
|
||||
- 'Continue on baro stuck during mission (GPS height mode)'
|
||||
- 'Takeoff and Land'
|
||||
- 'Fly square Multicopter Missions including RTL'
|
||||
- 'Fly square Multicopter Missions with manual RTL'
|
||||
- 'Fly forward in position control'
|
||||
- 'Fly forward in altitude control'
|
||||
```
|
||||
|
||||
## Примітки щодо реалізацій:
|
||||
|
||||
- The tests are invoked from the test runner script [mavsdk_test_runner.py](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/mavsdk_test_runner.py), which is written in Python.
|
||||
|
||||
In addition to MAVSDK, this runner starts `px4` as well as Gazebo for SITL tests, and collects the logs of these processes.
|
||||
|
||||
- Модуль виконання тесту - це бінарний файл на мові C++, який містить:
|
||||
- The [main](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/test_main.cpp) function to parse the arguments.
|
||||
- An abstraction around MAVSDK called [autopilot_tester](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/autopilot_tester.h).
|
||||
- The actual tests using the abstraction around MAVSDK as e.g. [test_multicopter_mission.cpp](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/test_multicopter_mission.cpp).
|
||||
- The tests use the [catch2](https://github.com/catchorg/Catch2) unit testing framework.
|
||||
Причини використання цього фреймворку наступні:
|
||||
- Asserts (`REQUIRE`) which are needed to abort a test can be inside of functions (and not just in the top level test as is [the case with gtest](https://github.com/google/googletest/blob/main/docs/advanced.md#assertion-placement)).
|
||||
- Dependency management is easier because _catch2_ can just be included as a header-only library.
|
||||
- _Catch2_ supports [tags](https://github.com/catchorg/Catch2/blob/devel/docs/test-cases-and-sections.md#tags), which allows for flexible composition of tests.
|
||||
|
||||
Терміни:
|
||||
|
||||
- "model": This is the selected Gazebo model, e.g. `iris`.
|
||||
- "test case": This is a [catch2 test case](https://github.com/catchorg/Catch2/blob/master/docs/test-cases-and-sections.md).
|
||||
@@ -0,0 +1,51 @@
|
||||
# Вказівки щодо підтримки
|
||||
|
||||
Тут зібрані та описані деякі інструменти, які допомагають аналізувати стан кодової бази та підтримувати її роботу.
|
||||
|
||||
## Аналіз змін
|
||||
|
||||
Кількість змін, зроблених у файлі, може бути індикатором того, які файли/частини можуть потребувати рефакторингу.
|
||||
|
||||
To find churn metrics a tool such as [Churn](https://github.com/danmayer/churn) can be used:
|
||||
|
||||
```sh
|
||||
gem install churn
|
||||
```
|
||||
|
||||
An example output as of `v1.6.0-rc2` would be:
|
||||
|
||||
```sh
|
||||
cd src/PX4-Autopilot
|
||||
churn --start_date "6 months ago"
|
||||
**********************************************************************
|
||||
* Revision Changes
|
||||
**********************************************************************
|
||||
Files
|
||||
+------------------------------------------+
|
||||
| file |
|
||||
+------------------------------------------+
|
||||
| src/modules/navigator/mission.cpp |
|
||||
| src/modules/navigator/navigator_main.cpp |
|
||||
| src/modules/navigator/rtl.cpp |
|
||||
+------------------------------------------+
|
||||
|
||||
|
||||
|
||||
**********************************************************************
|
||||
* Project Churn
|
||||
**********************************************************************
|
||||
|
||||
Files
|
||||
+---------------------------------------------------------------------------+---------------+
|
||||
| file_path | times_changed |
|
||||
+---------------------------------------------------------------------------+---------------+
|
||||
| src/modules/mc_pos_control/mc_pos_control_main.cpp | 107 |
|
||||
| src/modules/commander/commander.cpp | 67 |
|
||||
| ROMFS/px4fmu_common/init.d/rcS | 52 |
|
||||
| Makefile | 49 |
|
||||
| src/drivers/px4fmu/fmu.cpp | 47 |
|
||||
| ROMFS/px4fmu_common/init.d/rc.sensors | 40 |
|
||||
| src/drivers/boards/aerofc-v1/board_config.h | 31 |
|
||||
| src/modules/logger/logger.cpp | 29 |
|
||||
| src/modules/navigator/navigator_main.cpp | 28 |
|
||||
```
|
||||
@@ -0,0 +1,29 @@
|
||||
# Польотні тести
|
||||
|
||||
<script setup>
|
||||
import { useData } from 'vitepress'
|
||||
const { site } = useData();
|
||||
</script>
|
||||
|
||||
<div v-if="site.title !== 'PX4 Guide (main)'">
|
||||
<div class="custom-block danger">
|
||||
<p class="custom-block-title">Ця сторінка може бути застарілою. <a href="https://docs.px4.io/main/en/test_and_ci/test_flights.html">Переглянути останню версію</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Тестові польоти є важливим етапом для забезпечення якості.
|
||||
|
||||
When submitting [Pull Requests](../contribute/code.md#pull-requests) for new functionality or bug fixes you should provide information about the feature-relative tests performed, along with accompanying flight logs.
|
||||
|
||||
Для значних змін у системі ви також повинні виконати загальні польотні тести за допомогою тестових карток, перерахованих нижче.
|
||||
|
||||
## Тестові картки
|
||||
|
||||
Ці тестові картки визначають "стандартні" польотні тести.
|
||||
Їх виконує тестова команда в рамках тестування випуску та для більш значних змін у системі.
|
||||
|
||||
- [MC_01 - Manual modes](../test_cards/mc_01_manual_modes.md)
|
||||
- [MC_02 - Full Autonomous](../test_cards/mc_02_full_autonomous.md)
|
||||
- [MC_03 - Auto Manual Mix](../test_cards/mc_03_auto_manual_mix.md)
|
||||
- [MC_04 - Failsafe Testing](../test_cards/mc_04_failsafe_testing.md)
|
||||
- [MC_05 - Indoor Flight (Manual Modes)](../test_cards/mc_05_indoor_flight_manual_modes.md)
|
||||
@@ -0,0 +1,180 @@
|
||||
# Модульні Тести
|
||||
|
||||
Розробникам рекомендується писати модульні тести на всіх етапах розробки, включаючи додавання нових функцій, виправлення помилок і рефакторинг
|
||||
|
||||
PX4 надає декілька методів для написання юніт тестів:
|
||||
|
||||
1. Unit tests with [Google Test](https://github.com/google/googletest/blob/main/docs/primer.md) ("GTest") - tests that have minimal, internal-only dependencies
|
||||
2. Функціональні тести з GTest - тести, які залежать від параметрів та uORB повідомлень
|
||||
3. Модульні тести SITL. Це і є тести, які повинні запускатися в повному SITL. Ці тести виконуються набагато повільніше та важче налагодити, тому, якщо можливо, замість них рекомендується використовувати GTest.
|
||||
|
||||
## Написання GTest Unit Test
|
||||
|
||||
**Tip**: In general, if you need access to advanced GTest utilities, data structures from the STL or need to link to `parameters` or `uorb` libraries you should use the functional tests instead.
|
||||
|
||||
Кроки для створення нових функціональних тестів такі:
|
||||
|
||||
1. Модульні тести мають бути організовані в три секції: налаштування, запуск, перевірка результатів. Кожен тест повинен перевіряти одну дуже конкретну поведінку або випадок налаштування, тому, якщо тест провалиться, стане очевидним, що не так. Будь ласка, намагайтеся дотримуватися цих стандартів, коли це можливо.
|
||||
2. Copy and rename the example unit test [AttitudeControlTest](https://github.com/PX4/PX4-Autopilot/blob/main/src/modules/mc_att_control/AttitudeControl/AttitudeControlTest.cpp) to the directory the code to be tested is in.
|
||||
3. Add the new file to the directory's `CMakeLists.txt`. It should look something like `px4_add_unit_gtest(SRC MyNewUnitTest.cpp LINKLIBS <library_to_be_tested>)`
|
||||
4. Додайте бажану функцію тестування. Це означатиме включення файлів заголовків, необхідних для ваших конкретних тестів, додавання нових тестів (кожен з індивідуальною назвою) і розміщення логіки для налаштування, запуск коду для перевірки та перевірка його поведінки, як очікувалося.
|
||||
5. If additional library dependencies are required, they should also be added to the CMakeLists after the `LINKLIBS` as shown above.
|
||||
|
||||
Tests can be run via `make tests`, after which you will find the binary in `build/px4_sitl_test/unit-MyNewUnit`.
|
||||
Він може бути запущений безпосередньо в налагоджувачі.
|
||||
|
||||
## Написання GTest Functional Test
|
||||
|
||||
Функціональні тести GTest слід використовувати, коли тест або компоненти, що тестуються, залежать від параметрів, повідомлень uORB та/або розширеної функціональності GTest.
|
||||
Крім того, функціональні тести можуть містити локальне використання структур даних STL (хоча і будьте обережні відмінності платформ між такими як macOS і Linux).
|
||||
|
||||
Кроки для створення нових функціональних тестів такі:
|
||||
|
||||
1. Загалом (і подібно до модульних тестів), функціональні тести мають бути організовані за трьома розділами: налаштування, запуск, перевірка результатів.
|
||||
Кожен тест повинен перевіряти одну дуже конкретну поведінку або випадок налаштування, тому, якщо тест провалиться, стане очевидним, що не так.
|
||||
Будь ласка, намагайтеся дотримуватися цих стандартів, коли це можливо.
|
||||
2. Copy and rename the example functional test [ParameterTest](https://github.com/PX4/PX4-Autopilot/blob/main/src/lib/parameters/ParameterTest.cpp) to the directory the code to be tested is in.
|
||||
3. Перейменуйте клас з ParameterTest на те, що краще представляє код, що тестується
|
||||
4. Add the new file to the directory's `CMakeLists.txt`.
|
||||
It should look something like `px4_add_functional_gtest(SRC MyNewFunctionalTest.cpp LINKLIBS <library_to_be_tested>)`
|
||||
5. Додайте бажану функцію тестування.
|
||||
Це означатиме включення файлів заголовків, необхідних для ваших конкретних тестів, додавання нових тестів (кожен з індивідуальною назвою) і розміщення логіки для налаштування тесту, запуск коду, який потрібно перевірити, і перевірку його поведінки, як очікувалося.
|
||||
6. If additional library dependencies are required, they should also be added to the CMakeLists after the `LINKLIBS` as shown above.
|
||||
|
||||
Tests can be run via `make tests`, after which you will find the binary in `build/px4_sitl_test/functional-MyNewFunctional`.
|
||||
It can be run directly in a debugger, however be careful to only run one test per executable invocation using the [--gtest_filter=\<regex\>](https://github.com/google/googletest/blob/main/docs/advanced.md#running-a-subset-of-the-tests) arguments, as some parts of the uORB and parameter libraries don't clean themselves up perfectly and may result in undefined behavior if set up multiple times.
|
||||
|
||||
## Написання SITL Unit Test
|
||||
|
||||
Модульні тести SITL слід використовувати, коли вам конкретно потрібні всі компоненти контролера польоту – водії, час тощо.
|
||||
Ці тести виконуються повільніше (1 с+ для кожного нового модуля) і їх важче налагодити, тому їх слід використовувати лише за необхідності.
|
||||
|
||||
Кроки для створення нових модульних тестів SITL такі:
|
||||
|
||||
1. Examine the sample [Unittest-class](https://github.com/PX4/PX4-Autopilot/blob/main/src/include/unit_test.h).
|
||||
|
||||
2. Create a new .cpp file within [tests](https://github.com/PX4/PX4-Autopilot/tree/main/src/systemcmds/tests) with name **test\_[description].cpp**.
|
||||
|
||||
3. Within **test\_[description].cpp** include the base unittest-class `<unit_test.h>` and all files required to write a test for the new feature.
|
||||
|
||||
4. Within **test\_[description].cpp** create a class `[Description]Test` that inherits from `UnitTest`.
|
||||
|
||||
5. Within `[Description]Test` class declare the public method `virtual bool run_tests()`.
|
||||
|
||||
6. Within `[Description]Test` class declare all private methods required to test the feature in question (`test1()`, `test2()`,...).
|
||||
|
||||
7. Within **test\_[description].cpp** implement the `run_tests()` method where each test[1,2,...] will be run.
|
||||
|
||||
8. Within **test\_[description].cpp**, implement the various tests.
|
||||
|
||||
9. At the bottom within **test\_[description].cpp** declare the test.
|
||||
|
||||
```cpp
|
||||
ut_declare_test_c(test_[description], [Description]Test)
|
||||
```
|
||||
|
||||
Тут є шаблон:
|
||||
|
||||
```cpp
|
||||
#include <unit_test.h>
|
||||
#include "[new feature].h"
|
||||
...
|
||||
|
||||
class [Description]Test : public UnitTest
|
||||
{
|
||||
public:
|
||||
virtual bool run_tests();
|
||||
|
||||
private:
|
||||
bool test1();
|
||||
bool test2();
|
||||
...
|
||||
};
|
||||
|
||||
bool [Description]Test::run_tests()
|
||||
{
|
||||
ut_run_test(test1)
|
||||
ut_run_test(test2)
|
||||
...
|
||||
|
||||
return (_tests_failed == 0);
|
||||
}
|
||||
|
||||
bool [Description]Test::test1()
|
||||
{
|
||||
ut_[name of one of the unit test functions](...
|
||||
ut_[name of one of the unit test functions](...
|
||||
...
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool [Description]Test::test2()
|
||||
{
|
||||
ut_[name of one of the unit test functions](...
|
||||
ut_[name of one of the unit test functions](...
|
||||
...
|
||||
|
||||
return true;
|
||||
}
|
||||
...
|
||||
|
||||
ut_declare_test_c(test_[description], [Description]Test)
|
||||
```
|
||||
|
||||
Note that `ut_[name of one of the unit test functions]` corresponds to one of the unittest functions defined within [unit_test.h](https://github.com/PX4/PX4-Autopilot/blob/main/src/include/unit_test.h).
|
||||
|
||||
10. Within [tests_main.h](https://github.com/PX4/PX4-Autopilot/blob/main/src/systemcmds/tests/tests_main.h) define the new test:
|
||||
|
||||
```cpp
|
||||
extern int test_[description](int argc, char *argv[]);
|
||||
```
|
||||
|
||||
11. Within [tests_main.c](https://github.com/PX4/PX4-Autopilot/blob/main/src/systemcmds/tests/tests_main.c) add description name, test function and option:
|
||||
|
||||
```cpp
|
||||
...
|
||||
} tests[] = {
|
||||
{...
|
||||
{"[description]", test_[description], OPTION},
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
`OPTION` can be `OPT_NOALLTEST`,`OPT_NOJIGTEST` or `0` and is considered if within px4 shell one of the two commands are called:
|
||||
|
||||
```sh
|
||||
pxh> tests all
|
||||
```
|
||||
|
||||
або
|
||||
|
||||
```sh
|
||||
pxh> tests jig
|
||||
```
|
||||
|
||||
If a test has option `OPT_NOALLTEST`, then that test will be excluded when calling `tests all`. The same is true for `OPT_NOJITEST` when command `test jig` is called. Option `0` means that the test is never excluded, which is what most developer want to use.
|
||||
|
||||
12. Add the test `test_[description].cpp` to the [CMakeLists.txt](https://github.com/PX4/PX4-Autopilot/blob/main/src/systemcmds/tests/CMakeLists.txt).
|
||||
|
||||
## Тестування на локальній машині
|
||||
|
||||
Запустіть повний список модульних тестів GTest, функціональних тестів GTest і модульних тестів SITL прямо з bash:
|
||||
|
||||
```sh
|
||||
make tests
|
||||
```
|
||||
|
||||
The individual GTest test binaries are in the `build/px4_sitl_test/` directory, and can be run directly in most IDEs' debugger.
|
||||
|
||||
Фільтр, щоб запустити лише підмножину тестів, використовуючи регулярний вираз для імені ctest за допомогою цієї команди:
|
||||
|
||||
```sh
|
||||
make tests TESTFILTER=<regex filter expression>
|
||||
```
|
||||
|
||||
Наприклад:
|
||||
|
||||
- `make tests TESTFILTER=unit` only run GTest unit tests
|
||||
- `make tests TESTFILTER=sitl` only run simulation tests
|
||||
- `make tests TESTFILTER=Attitude` only run the `AttitudeControl` test
|
||||
Reference in New Issue
Block a user