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:
Hamish Willee
2025-03-13 16:08:27 +11:00
committed by GitHub
co-authored by Ramon Roche
parent 8e6d2ebe4a
commit 88d623bedb
5176 changed files with 558771 additions and 2 deletions
+58
View File
@@ -0,0 +1,58 @@
# Профілювання розміру бінаря
The `bloaty_compare_master` build target allows you to get a better understanding of the impact of changes on code size.
When it is used, the toolchain downloads the latest successful master build of a particular firmware and compares it to the local build (using the [bloaty](https://github.com/google/bloaty) size profiler for binaries).
:::tip
This can help analyse changes that (may) cause `px4_fmu-v2_default` to hit the 1MB flash limit.
:::
_Bloaty_ must be in your path and found at _cmake_ configure time.
The PX4 [docker files](https://github.com/PX4/containers/blob/master/docker/Dockerfile_nuttx-bionic) install _bloaty_ as shown:
```sh
git clone --recursive https://github.com/google/bloaty.git /tmp/bloaty \
&& cd /tmp/bloaty && cmake -GNinja . && ninja bloaty && cp bloaty /usr/local/bin/ \
&& rm -rf /tmp/*
```
The example below shows how you might see the impact of removing the _mpu9250_ driver from `px4_fmu-v2_default`.
Спочатку локально налаштовує збірку без драйвера:
```sh
% git diff
diff --git a/boards/px4/fmu-v2/default.px4board b/boards/px4/fmu-v2/default.px4board
index 40d7778..2ce7972 100644
--- a/boards/px4/fmu-v2/default.px4board
+++ b/boards/px4/fmu-v2/default.px4board
@@ -36,7 +36,7 @@
- CONFIG_DRIVERS_IMU_INVENSENSE_MPU9250=y
+ CONFIG_DRIVERS_IMU_INVENSENSE_MPU9250=n
```
Then use the make target, specifying the target build to compare (`px4_fmu-v2_default` in this case):
```sh
% make px4_fmu-v2_default bloaty_compare_master
...
...
...
VM SIZE FILE SIZE
-------------- --------------
[DEL] -52 MPU9250::check_null_data(unsigned int*, unsigned char) -52 [DEL]
[DEL] -52 MPU9250::test_error() -52 [DEL]
[DEL] -52 MPU9250_gyro::MPU9250_gyro(MPU9250*, char const*) -52 [DEL]
[DEL] -56 mpu9250::info(MPU9250_BUS) -56 [DEL]
[DEL] -56 mpu9250::regdump(MPU9250_BUS) -56 [DEL]
... -336 [DEL]
[DEL] -344 MPU9250_mag::_measure(ak8963_regs) -344 [DEL]
[DEL] -684 MPU9250::MPU9250(device::Device*, device::Device*, char const*, char const*, cha -684 [DEL]
[DEL] -684 MPU9250::init() -684 [DEL]
[DEL] -1000 MPU9250::measure() -1000 [DEL]
-41.3% -1011 [43 Others] -1011 -41.3%
-1.0% -1.05Ki [Unmapped] +24.2Ki +0.2%
-1.0% -10.3Ki TOTAL +14.9Ki +0.1%
```
This shows that removing _mpu9250_ from `px4_fmu-v2_default` would save 10.3 kB of flash.
It also shows the sizes of different pieces of the _mpu9250_ driver.
+89
View File
@@ -0,0 +1,89 @@
# Консолі/Оболонки PX4
PX4 enables terminal access to the system through the [MAVLink Shell](../debug/mavlink_shell.md) and the [System Console](../debug/system_console.md).
Ця сторінка пояснює основні відмінності та як використовується консоль/оболонка.
<a id="console_vs_shell"></a>
## Системна консоль у порівнянні з оболонкою
The PX4 _System Console_ provides low-level access to the system, debug output and analysis of the system boot process.
There is just one _System Console_, which runs on one specific UART (the debug port, as configured in NuttX), and is commonly attached to a computer via an FTDI cable (or some other debug adapter like a [Dronecode probe](https://kb.zubax.com/display/MAINKB/Dronecode+Probe+documentation)).
- Used for _low-level debugging/development_: bootup, NuttX, startup scripts, board bringup, development on central parts of PX4 (e.g. uORB).
- Зокрема, це єдине місце, де виводиться весь вивід завантаження (включаючи інформацію про програми, які автоматично запускаються при завантаженні).
Оболонки надають високорівневий доступ до системи:
- Використовується для базового тестування модулів/виконання команд.
- Only _directly_ display the output of modules you start.
- Cannot _directly_ display the output of tasks running on the work queue.
- Не може налагоджувати проблеми, коли система не запускається (оскільки вона ще не працює).
:::info
The `dmesg` command is now available through the shell on some boards, enabling much lower level debugging than previously possible.
For example, with `dmesg -f &` you also see the output of background tasks.
:::
Може бути кілька оболонок, які працюють на відведеному UART або через MAVLink.
Since MAVLink provides more flexibility, currently only the [MAVLink Shell](../debug/mavlink_shell.md) is used.
The [System Console](../debug/system_console.md) is essential when the system does not boot (it displays the system boot log when power-cycling the board).
The [MAVLink Shell](../debug/mavlink_shell.md) is much easier to setup, and so is more generally recommended for most debugging.
<a id="using_the_console"></a>
## Використання Консолі/Оболонки
The MAVLink shell/console and the [System Console](../debug/system_console.md) are used in much the same way.
For example, type `ls` to view the local file system, `free` to see the remaining free RAM, `dmesg` to look at boot output.
```sh
nsh> ls
nsh> free
nsh> dmesg
```
Below are a couple of commands which can be used in the [NuttShell](https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=139629410) to get insights of the system.
Ця команда NSH надає доступну вільну пам'ять:
```sh
free
```
Команда top показує використання стеку для кожного додатку:
```sh
top
```
Зверніть увагу, що використання стеку обчислюється за допомогою алгоритму забарвлення стеку та є максимумом з моменту початку завдання (а не поточним використанням).
Щоб побачити, що виконується у робочих чергах і з якою швидкістю, використовуйте:
```sh
work_queue status
```
Для налагодження тем uORB:
```sh
uorb top
```
Для перевірки певної рубрики uORB:
```sh
listener <topic_name>
```
Many other system commands and modules are listed in the [Modules and Command Reference](../modules/modules_main.md) (e.g. `top`, `listener`, etc.).
:::tip
Some commands may be disabled on some boards (i.e. the some modules are not included in firmware for boards with RAM or FLASH constraints).
In this case you will see the response: `command not found`
:::
+110
View File
@@ -0,0 +1,110 @@
# Надсилання та отримання дебажних значень
Часто під час розробки програмного забезпечення необхідно виводити окремі важливі числа.
This is where the generic `NAMED_VALUE_FLOAT`, `DEBUG` and `DEBUG_VECT` packets of MAVLink come in.
## Відображення між Повідомленнями відлагодження MAVLink та Темами uORB
Повідомлення для налагодження MAVLink перекладаються в/з тем uORB.
Для того щоб надіслати або отримати відлагоджувальне повідомлення MAVLink, вам потрібно відповідно опублікувати або підписатися на відповідну тему.
Ось таблиці, яка узагальнює відповідність між повідомленнями відладки MAVLink та темами uORB:
| Повідомлення MAVLink | Тема uORB |
| ----------------------------------------------------------- | --------------------------------------------------------- |
| NAMED_VALUE_FLOAT | debug_key_value |
| DEBUG | debug_value |
| DEBUG_VECT | debug_vect |
## Посібник: Надсилання Стрічок / Плаваючих пар
This tutorial shows how to send the MAVLink message `NAMED_VALUE_FLOAT` using the associated uORB topic `debug_key_value`.
Код для цього посібника доступний тут:
- [Debug Tutorial Code](https://github.com/PX4/PX4-Autopilot/blob/main/src/examples/px4_mavlink_debug/px4_mavlink_debug.cpp)
- [Enable the tutorial app](https://github.com/PX4/PX4-Autopilot/blob/main/boards/px4/fmu-v5/default.px4board) by ensuring the MAVLink debug app (**CONFIG_EXAMPLES_PX4_MAVLINK_DEBUG**) is in the config of your board and set set to 'y'.
Все необхідне для налаштування відлагодження публікації - це цей фрагмент коду.
Спочатку додайте файл заголовка:
```C
#include <uORB/uORB.h>
#include <uORB/topics/debug_key_value.h>
#include <string.h>
```
Потім рекламуйте тему значення налагодження (одна реклама для різних опублікованих назв достатня).
Поставте це перед вашим головним циклом:
```C
/* advertise debug value */
struct debug_key_value_s dbg;
strncpy(dbg.key, "velx", sizeof(dbg.key));
dbg.value = 0.0f;
orb_advert_t pub_dbg = orb_advertise(ORB_ID(debug_key_value), &dbg);
```
І навіть надсилання у головному циклі є ще простішим:
```C
dbg.value = position[0];
orb_publish(ORB_ID(debug_key_value), pub_dbg, &dbg);
```
:::warning
Multiple debug messages must have enough time between their respective publishings for Mavlink to process them.
Це означає, що код повинен чекати між публікацією кількох відлагоджувальних повідомлень або чергувати повідомлення при кожному виклику функції.
:::
Результат у QGroundControl виглядає так на графіку в реальному часі:
![QGC debugvalue plot](../../assets/gcs/qgc-debugval-plot.jpg)
## Посібник: Отримання Стрічок / Плаваючих пар
The following code snippets show how to receive the `velx` debug variable that was sent in the previous tutorial.
First, subscribe to the topic `debug_key_value`:
```C
#include <poll.h>
#include <uORB/topics/debug_key_value.h>
int debug_sub_fd = orb_subscribe(ORB_ID(debug_key_value));
[...]
```
Потім проведіть опитування на тему:
```C
[...]
/* one could wait for multiple topics with this technique, just using one here */
px4_pollfd_struct_t fds[] = {
{ .fd = debug_sub_fd, .events = POLLIN },
};
while (true) {
/* wait for debug_key_value for 1000 ms (1 second) */
int poll_ret = px4_poll(fds, 1, 1000);
[...]
```
When a new message is available on the `debug_key_value` topic, do not forget to filter it based on its key attribute in order to discard the messages with key different than `velx`:
```C
[...]
if (fds[0].revents & POLLIN) {
/* obtained data for the first file descriptor */
struct debug_key_value_s dbg;
/* copy data into local buffer */
orb_copy(ORB_ID(debug_key_value), debug_sub_fd, &dbg);
/* filter message based on its key attribute */
if (strcmp(_sub_debug_vect.get().key, "velx") == 0) {
PX4_INFO("velx:\t%8.4f", dbg.value);
}
}
}
```
+158
View File
@@ -0,0 +1,158 @@
# Налагодження з Eclipse та J-Link
This topic explains how to setup and use [MCU Eclipse](https://gnu-mcu-eclipse.github.io/) with a _Segger Jlink adapter_ to debug PX4 running on NuttX (e.g. Pixhawk series boards).
## Необхідне обладнання
- [J-Link EDU Mini](https://www.segger.com/products/debug-probes/j-link/models/j-link-edu-mini/)
- Adapter to connect Segger JLink to Flight Controller [SWD Debug Port](../debug/swd_debug.md) (debug port).
- Мікро USB кабель
## Встановлення
### PX4
Налаштуйте PX4, дотримуючись звичайних вказівок:
- [Setup the PX4 Developer Environment/Toolchain](../dev_setup/dev_env.md) for your platform (e.g. for Linux see: [Development Environment on Ubuntu LTS / Debian Linux](../dev_setup/dev_env_linux_ubuntu.md)).
- [Download PX4](../dev_setup/building_px4.md) and optionally build it on the command line.
### Eclipse
To install _Eclipse_:
1. Download [Eclipse CDT for C/C++ Developers](https://github.com/gnu-mcu-eclipse/org.eclipse.epp.packages/releases/) (MCU GitHub).
2. Розпакуйте папку Eclipse та скопіюйте її куди завгодно (немає потреби запускати будь-які сценарії установки).
3. Run _Eclipse_ and choose a location for your initial workbench.
### Інструменти Segger Jlink
To install the _Segger Jlink_ tools:
1. Download and run the [J-Link Software and Documentation Pack](https://www.segger.com/downloads/jlink/#J-LinkSoftwareAndDocumentationPack) for your OS (Windows and Linux packages available).
- On Linux the tools are installed in **/usr/bin**.
For more information, see: [https://gnu-mcu-eclipse.github.io/debug/jlink/install/](https://gnu-mcu-eclipse.github.io/debug/jlink/install/).
## Перше використання
1. Connect the _Segger JLink_ to the host computer and the [flight controller debug port](../debug/swd_debug.md) (via an adapter).
2. Увімкніть модульний політний контролер.
3. Run _Eclipse_.
4. Add a source by choosing **File > Import > C/C++ > Existing Code as Makefile Project** and click **Next**.
5. Point it to the **PX4-Autopilot** folder and give it a name, then select _ARM Cross GCC_ in the _Toolchain for Indexer Settings_ and click **Finish**.
Імпорт триває деякий час. Дочекайтеся його завершення.
6. Set the MCU settings: right-click on the top-level project in the Project Explorer, select _Properties_ then under MCU choose _SEGGER J-Link Path_.
Встановіть його, як показано на знімку екрану нижче.
![Eclipse: Segger J-Link Path](../../assets/debug/eclipse_segger_jlink_path.png)
7. Пакети з оновленнями:
- Click the small icon on the top right called _Open Perspective_ and open the _Packs_ perspective.
![Eclipse: Workspace](../../assets/debug/eclipse_workspace_perspective.png)
- Click the **update all** button.
:::tip
This takes a VERY LONG TIME (10 minutes).
Ігноруйте всі помилки про відсутні пакети.
:::
![Eclipse: Workspace Packs Perspective](../../assets/debug/eclipse_packs_perspective.jpg)
- The STM32Fxx devices are found in the Keil folder, install by right-clicking and then selecting **install** on the according device for F4 and F7.
8. Налаштування конфігурації налагодження для цілі:
- Right click project and open the _Settings_ (menu: **C/C++ Build > Settings**)
- Choose the _Devices_ Tab, _Devices_ section (Not _Boards_).
- Знайдіть FMU чіп, який ви хочете налагодити.
![Eclipse: Select FMU in settings](../../assets/debug/eclipse_settings_devices_fmu.png)
9. Select debug configurations with the small drop-down next to the bug symbol:
![Eclipse: Debug config](../../assets/debug/eclipse_settings_debug_config.png)
10. Then select _GDB SEGGER J-Link Debugging_ and then the **New config** button on the top left.
![Eclipse: GDB Segger Debug config](../../assets/debug/eclipse_settings_debug_config_gdb_segger.png)
11. Налаштування конфігурації збірки:
- Give it a name and set the _C/C++ Application_ to the corresponding **.elf** file.
- Choose _Disable Auto build_
::: info
Remember that you must build the target from the command line before starting a debug session.
:::
![Eclipse: GDB Segger Debug config](../../assets/debug/eclipse_settings_debug_config_gdb_segger_build_config.png)
12. The _Debugger_ and _Startup_ tabs shouldn’t need any modifications (just verify your settings with the screenshots below)
![Eclipse: GDB Segger Debug config: debugger tab](../../assets/debug/eclipse_settings_debug_config_gdb_segger_build_config_debugger_tab.png)
![Eclipse: GDB Segger Debug config: startup tab](../../assets/debug/eclipse_settings_debug_config_gdb_segger_build_config_startup_tab.png)
## Відлагодження з урахуванням завдань SEGGER
Task-aware debugging (also known as [thread-aware debugging](https://www.segger.com/products/debug-probes/j-link/tools/j-link-gdb-server/thread-aware-debugging/)) allows you to show the context of all running threads/tasks instead of just the stack current task.
Це досить корисно, оскільки PX4 має тенденцію запускати виконання багато різних завдань.
Для активації цієї функції в Eclipse:
1. You first need to enable `CONFIG_DEBUG_TCBINFO` in the NuttX configuration for your build (to expose the TCB offsets).
- Відкрийте термінал у кореневій теці вихідного коду PX4-Autopilot
- In the terminal, open `menuconfig` using the appropriate make target for the build.
Це виглядатиме приблизно так:
```sh
make px4_fmu-v5_default boardguiconfig
```
(See [PX4 Menuconfig Setup](../hardware/porting_guide_config.md#px4-menuconfig-setup) for more information) on using the config tools).
- Ensure that the _Enable TCBinfo struct for debug_ is selected as shown:
![NuttX: Menuconfig: CONFIG\_DEBUG\_TCBINFO](../../assets/debug/nuttx_tcb_task_aware.png)
2. Compile the **jlink-nuttx.so** library in the terminal by running the following command in the terminal: `make jlink-nuttx`
3. Змініть Eclipse, щоб використовувати цю бібліотеку.
In the _J-Link GDB Server Setup_ configuration, update **Other options** to include `-rtos /home/<PX4 path>/Tools/jlink-nuttx.so`, as shown in the image below.
![Eclipse: GDB Segger Debug config RTOS aware: debugger tab](../../assets/debug/eclipse_settings_debug_config_gdb_segger_task_aware.png)
4. Під час запуску налагоджувача ви повинні побачити зараз декілька потоків замість одного:
![Eclipse: GDB Segger Debug config RTOS aware: debug session](../../assets/debug/eclipse_settings_debug_config_gdb_segger_task_aware_tasks.png)
## Усунення проблем
### Цільовий процесор відсутній в Package Manager
Якщо цільовий ЦП не відображається в package manager, вам може знадобитися ці крок для запуску відображення реєстру.
:::tip
This should not generally happen (but anecdotally has been reported when connecting to an STM F7 controller).
:::
Adding missing SVD files for the _Peripheral View_:
1. Find out where MCU Eclipse stores its packages (**Preferences > C/C++ > MCU Packages**):
![Eclipse: MCU Packages](../../assets/debug/eclipse_mcu_packages.png)
2. Завантажте відсутні пакети з: http://www.keil.com/dd2/Pack/
3. Open downloaded pack with a decompression tool, and extract the **.SVD** files from: **/CMSIS/SVD**.
4. Select desired **.SVD** file in: **Debug Options > GDB SEGGER JLink Debugging > SVD Path**
![Eclipse: SVD File path](../../assets/debug/eclipse_svd_file_path.png)
+84
View File
@@ -0,0 +1,84 @@
# Інжекція помилки системи
System failure injection allows you to induce different types of sensor and system failures, either programmatically using the [MAVSDK failure plugin](https://mavsdk.mavlink.io/main/en/cpp/api_reference/classmavsdk_1_1_failure.html), or "manually" via a PX4 console like the [MAVLink shell](../debug/mavlink_shell.md#mavlink-shell).
This enables easier testing of [safety failsafe](../config/safety.md) behaviour, and more generally, of how PX4 behaves when systems and sensors stop working correctly.
Failure injection is disabled by default, and can be enabled using the [SYS_FAILURE_EN](../advanced_config/parameter_reference.md#SYS_FAILURE_EN) parameter.
:::warning
Failure injection still in development.
На момент написання (PX4 v1.14):
- Це можна використовувати лише в симуляції (підтримка як для впровадження в реальному польоті запланована).
- Потребує підтримки в симуляторі.
Це підтримується в Gazebo Classic
- Багато типів відмов не широко реалізовані.
У таких випадках команда повернеться з повідомленням "unsupported".
:::
## Команда системи збою
Failures can be injected using the [failure system command](../modules/modules_command.md#failure) from any PX4 console/shell, specifying both the target and type of the failure.
### Синтаксис
The full syntax of the [failure](../modules/modules_command.md#failure) command is:
```sh
failure <component> <failure_type> [-i <instance_number>]
```
де:
- _component_:
- Датчики:
- `gyro`: Gyro.
- `accel`: Accelerometer.
- `mag`: Magnetometer
- `baro`: Barometer
- `gps`: GPS
- `optical_flow`: Optical flow.
- `vio`: Visual inertial odometry.
- `distance_sensor`: Distance sensor (rangefinder).
- `airspeed`: Airspeed sensor.
- Системи:
- `battery`: Battery.
- `motor`: Motor.
- `servo`: Servo.
- `avoidance`: Avoidance.
- `rc_signal`: RC Signal.
- `mavlink_signal`: MAVLink signal (data telemetry).
- _failure_type_:
- `ok`: Publish as normal (Disable failure injection).
- `off`: Stop publishing.
- `stuck`: Report same value every time (_could_ indicate a malfunctioning sensor).
- `garbage`: Publish random noise. Це схоже на читання неініціалізованої пам'яті.
- `wrong`: Publish invalid values (that still look reasonable/aren't "garbage").
- `slow`: Publish at a reduced rate.
- `delayed`: Publish valid data with a significant delay.
- `intermittent`: Publish intermittently.
- _instance number_ (optional): Instance number of affected sensor.
0 (за замовчуванням) вказує на всі сенсори вказаного типу.
### Приклад
Щоб симулювати втрату сигналу RC без вимкнення вашого пульта керування RC:
1. Enable the parameter [SYS_FAILURE_EN](../advanced_config/parameter_reference.md#SYS_FAILURE_EN).
2. Enter the following commands on the MAVLink console or SITL _pxh shell_:
```sh
# Fail RC (turn publishing off)
failure rc_signal off
# Restart RC publishing
failure rc_signal ok
```
## MAVSDK відлагоджувальний плагін
The [MAVSDK failure plugin](https://mavsdk.mavlink.io/main/en/cpp/api_reference/classmavsdk_1_1_failure.html) can be used to programmatically inject failures.
It is used in [PX4 Integration Testing](../test_and_ci/integration_testing_mavsdk.md) to simulate failure cases (for example, see [PX4-Autopilot/test/mavsdk_tests/autopilot_tester.cpp](https://github.com/PX4/PX4-Autopilot/blob/main/test/mavsdk_tests/autopilot_tester.cpp)).
API плагіна - це пряме відображення команди збою, показаної вище, з деякими додатковими сигналами про помилки, пов'язані з підключенням.
+39
View File
@@ -0,0 +1,39 @@
# Часті Питання
## Помилки збірки
### Переповнення Flash-пам'яті
Кількість коду, яку можна завантажити на плату, обмежується обсягом flash-пам'яті, яку вона має.
При додаванні додаткових модулів або коду можливо, що додача перевищує розмір flash-пам'яті.
Це призведе до "переповнення flash-пам'яті". Оригінальна версія завжди буде компілюватися, але залежно від того що додасть розробник вона може переповнити локально.
```sh
region `flash' overflowed by 12456 bytes
```
Для усунення цього, використовуйте новіше обладнання або видаліть модулі зі збірки, які не є необхідними для вашого випадку.
The configuration is stored in **/PX4-Autopilot/boards/px4** (e.g. [PX4-Autopilot/boards/px4/fmu-v5/default.px4board](https://github.com/PX4/PX4-Autopilot/blob/main/boards/px4/fmu-v5/default.px4board)).
Щоб видалити модуль, просто закоментуйте його:
```cmake
#tune_control
```
#### Визначення великих споживачів пам'яті
Нижче наведена команда, яка перелічить найбільші статичні виділення пам'яті:
```sh
arm-none-eabi-nm --size-sort --print-size --radix=dec build/px4_fmu-v5_default/px4_fmu-v5_default.elf | grep " [bBdD] "
```
## Помилки USB
### Завантаження ніколи не вдається
На Ubuntu видаліть менеджер модему:
```sh
sudo apt-get remove modemmanager
```
+64
View File
@@ -0,0 +1,64 @@
# Відлагодження з GDB
The [GNU DeBugger (GDB)](https://sourceware.org/gdb/documentation/) comes installed with the compiler toolchain in the form of the `arm-none-eabi-gdb` binary.
Налагоджувач читає символи відладки у файлі формату виконання ELF щоб зрозуміти статичну та динамічну структуру пам'яті прошивки PX4.
To access the PX4 autopilot microcontroller, it needs to connect to a [Remote Target](https://sourceware.org/gdb/current/onlinedocs/gdb.html/Connecting.html), which is provided by a [SWD debug probe](swd_debug.md).
Плин інформації виглядає таким чином:
```sh
Developer <=> GDB <=> GDB Server <=> Debug Probe <=> SWD <=> PX4 Autopilot.
```
## Швидкий старт
Для початку сеансу налагодження вам зазвичай потрібно:
1. Need a specialized [SWD debug probe](../debug/swd_debug.md#debug-probes).
2. Find and connect to the [SWD debug port](../debug/swd_debug.md#autopilot-debug-ports).
You may need a [debug adapter](swd_debug.md#debug-adapters).
3. Налаштувати та запустити зонд налагодження для створення сервера GDB.
4. Запустити GDB та під'єднатись до сервера GDB як віддаленої цілі.
5. Налагоджувати прошивку інтерактивно.
Дивіться документацію зонда налагодження для додаткової інформації як налаштувати з'єднання для налагодження:
- [SEGGER J-Link](probe_jlink.md): commercial probe, no built-in serial console, requires adapter.
- [Black Magic Probe](probe_bmp.md): integrated GDB server and serial console, requires adapter.
- [STLink](probe_stlink): best value, integrated serial console, adapter must be soldered.
Рекомендуємо використовувати J-Link з адаптером налагодження Pixhawk або STLinkv3-MINIE зі спеціально спаяним кабелем.
Після підключення ви можете використовувати звичайні команди GDB, такі як:
- `continue` to continue program execution
- `run` to start from the beginning
- `backtrace` to see the backtrace
- `break somewhere.cpp:123` to set a breakpoint
- `delete somewhere.cpp:123` to remove it again
- `info locals` to print local variables
- `info registers` to print the registers
Consult the [GDB documentation](https://sourceware.org/gdb/documentation/) for more details.
:::tip
To avoid having to type all commands to connect in GDB each time, you can write them into `~/.gdbinit`.
:::
## Наступні кроки
Ви під'єднали контролер польоту до налагоджувального зонда SWD!
Наступні розділи пояснюють, як розпочати налагодження на цільовій платформі:
- [MCU Eclipse/J-Link Debugging for PX4](eclipse_jlink.md).
- [Visual Studio Code IDE (VSCode)](../dev_setup/vscode.md).
## Вбудовані інструменти налагодження
The [Embedded Debug Tools](https://pypi.org/project/emdbg/) connect several software and hardware debugging tools together in a user friendly Python package to more easily enable advanced use cases for ARM Cortex-M microcontrollers and related devices.
Ця бібліотека організовує запуск та налаштування апаратних зондів налагодження та зондів трасування, налагоджувачів, логічних аналізаторів, генераторів сигналу та надає інструменти аналізу, перетворювачі та плагіни для отримання суттєвого розуміння стану програмного та апаратного забезпечення під час або після виконання.
The `emdbg` library contains [many useful GDB plugins](https://github.com/Auterion/embedded-debug-tools/blob/main/src/emdbg/debug/gdb.md#user-commands) that make debugging PX4 easier.
It also provides tools for [profiling PX4 in real-time](https://github.com/Auterion/embedded-debug-tools/tree/main/ext/orbetto).
+89
View File
@@ -0,0 +1,89 @@
# Жорстке відлагодження помилок
Помилка апаратної частини - це стан, коли ЦП виконує недійсну інструкцію або звертається до недійсної адреси пам'яті.
Це може статися, коли ключові області в RAM були пошкоджені.
## Відео
Наступне відео демонструє відлагодження hardfault на PX4 за допомогою Eclipse та JTAG-відлагоджувача.
Це було представлено на конференції розробників PX4 2019 року.
<lite-youtube videoid="KZkAM_PVOi0" title="Hardfault debugging on PX4"/>
## Відлагодження важких відмов в NuttX
Типовий сценарій, який може спричинити важку помилку, - це коли процесор перезаписує стек, а потім процесор повертається до недійсної адреси зі стеку.
Це може бути спричинено помилкою в коді, де дикий вказівник порушує стек, або інша задача перезаписує стек цієї задачі.
- NuttX підтримує два стеки: стек IRQ для обробки переривань та стек користувача
- Стек зростає вниз.
Таким чином, найвища адреса в наведеному нижче прикладі - 0x20021060, розмір - 0x11f4 (4596 байтів), і, відповідно, найнижча адреса - 0x2001fe6c.
```sh
Assertion failed at file:armv7-m/up_hardfault.c line: 184 task: ekf_att_pos_estimator
sp: 20003f90
IRQ stack:
base: 20003fdc
size: 000002e8
20003f80: 080d27c6 20003f90 20021060 0809b8d5 080d288c 000000b8 08097155 00000010
20003fa0: 20003ce0 00000003 00000000 0809bb61 0809bb4d 080a6857 e000ed24 080a3879
20003fc0: 00000000 2001f578 080ca038 000182b8 20017cc0 0809bad1 20020c14 00000000
sp: 20020ce8
User stack:
base: 20021060
size: 000011f4
20020ce0: 60000010 2001f578 2001f578 080ca038 000182b8 0808439f 2001fb88 20020d4c
20020d00: 20020d44 080a1073 666b655b 65686320 205d6b63 6f6c6576 79746963 76696420
20020d20: 65747265 63202c64 6b636568 63636120 63206c65 69666e6f 08020067 0805c4eb
20020d40: 080ca9d4 0805c21b 080ca1cc 080ca9d4 385833fb 38217db9 00000000 080ca964
20020d60: 080ca980 080ca9a0 080ca9bc 080ca9d4 080ca9fc 080caa14 20022824 00000002
20020d80: 2002218c 0806a30f 08069ab2 81000000 3f7fffec 00000000 3b4ae00c 3b12eaa6
20020da0: 00000000 00000000 080ca010 4281fb70 20020f78 20017cc0 20020f98 20017cdc
20020dc0: 2001ee0c 0808d7ff 080ca010 00000000 3f800000 00000000 080ca020 3aa35c4e
20020de0: 3834d331 00000000 01010101 00000000 01010001 000d4f89 000d4f89 000f9fda
20020e00: 3f7d8df4 3bac67ea 3ca594e6 be0b9299 40b643aa 41ebe4ed bcc04e1b 43e89c96
20020e20: 448f3bc9 c3c50317 b4c8d827 362d3366 b49d74cf ba966159 00000000 00000000
20020e40: 3eb4da7b 3b96b9b7 3eead66a 00000000 00000000 00000000 00000000 00000000
20020e60: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
20020e80: 00000016 00000000 00000000 00010000 00000000 3c23d70a 00000000 00000000
20020ea0: 00000000 20020f78 00000000 2001ed20 20020fa4 2001f498 2001f1a8 2001f500
20020ec0: 2001f520 00000003 2001f170 ffffffe9 3b831ad2 3c23d70a 00000000 00000000
20020ee0: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
20020f00: 00000000 00000000 00000000 00000000 2001f4f0 2001f4a0 3d093964 00000001
20020f20: 00000000 0808ae91 20012d10 2001da40 0000260b 2001f577 2001da40 0000260b
20020f40: 2001f1a8 08087fd7 08087f9d 080cf448 0000260b 080afab1 080afa9d 00000003
20020f60: 2001f577 0809c577 2001ed20 2001f4d8 2001f498 0805e077 2001f568 20024540
20020f80: 00000000 00000000 00000000 0000260b 3d093a57 00000000 2001f540 2001f4f0
20020fa0: 0000260b 3ea5b000 3ddbf5fa 00000000 3c23d70a 00000000 00000000 000f423f
20020fc0: 00000000 000182b8 20017cc0 2001ed20 2001f4e8 00000000 2001f120 0805ea0d
20020fe0: 2001f090 2001f120 2001eda8 ffffffff 000182b8 00000000 00000000 00000000
20021000: 00000000 00000000 00000009 00000000 08090001 2001f93c 0000000c 00000000
20021020: 00000101 2001f96c 00000000 00000000 00000000 00000000 00000000 00000000
20021040: 00000000 00000000 00000000 00000000 00000000 0809866d 00000000 00000000
R0: 20000f48 0a91ae0c 20020d00 20020d00 2001f578 080ca038 000182b8 20017cc0
R8: 2001ed20 2001f4e8 2001ed20 00000005 20020d20 20020ce8 0808439f 08087c4e
xPSR: 61000000 BASEPRI: 00000000 CONTROL: 00000000
EXC_RETURN: ffffffe9
```
To decode the hard fault, load the _exact_ binary into the debugger:
```sh
arm-none-eabi-gdb build/px4_fmu-v2_default/px4_fmu-v2_default.elf
```
Then in the GDB prompt, start with the last instructions in R8, with the first address in flash (recognizable because it starts with `0x080`, the first is `0x0808439f`).
Виконання здійснюється зліва направо. So one of the last steps before the hard fault was when `mavlink_log.c` tried to publish something,
```sh
(gdb) info line *0x0808439f
Line 77 of "../src/modules/systemlib/mavlink_log.c" starts at address 0x8084398 <mavlink_vasprintf+36>
and ends at 0x80843a0 <mavlink_vasprintf+44>.
```
```sh
(gdb) info line *0x08087c4e
Line 311 of "../src/modules/uORB/uORBDevices_nuttx.cpp"
starts at address 0x8087c4e <uORB::DeviceNode::publish(orb_metadata const*, void*, void const*)+2>
and ends at 0x8087c52 <uORB::DeviceNode::publish(orb_metadata const*, void*, void const*)+6>.
```
+1
View File
@@ -0,0 +1 @@
# Розділи налагодження
+49
View File
@@ -0,0 +1,49 @@
# Консоль MAVLink
The MAVLink Shell is an _NSH console_ that can be accessed via MAVLink over serial (USB/Telemetry) or WiFi (UDP/TCP) links (in particular, on NuttX-based systems like: Pixhawk, Pixracer, etc.).
Консоль можна використовувати для виконання команд та модулів та відображення їх виводу.
While the shell cannot _directly_ display the output of modules that it does not start, it can do so indirectly using the `dmesg` command (`dmesg -f &` can be used to display the output of other modules and tasks running on the work queue).
:::tip
The [QGroundControl MAVLink Console](#qgroundcontrol) is the easiest way to access the console.
If the system does not start properly you should instead use the [System Console](../debug/system_console.md).
:::
## Відкриття консолі
<a id="qgroundcontrol"></a>
### QGroundControl MAVLink Console
The easiest way to access shell is to use the [QGroundControl MAVLink Console](https://docs.qgroundcontrol.com/master/en/qgc-user-guide/analyze_view/mavlink_console.html) (see **Analyze View > Mavlink Console**).
### mavlink_shell.py
You can also access the shell in a terminal using the **mavlink_shell.py** script:
1. Shut down _QGroundControl_.
2. Встановіть залежності:
```sh
pip3 install --user pymavlink pyserial
```
3. Відкрийте термінал (у каталозі PX4-Autopilot) та запустіть оболонку:
```sh
# For serial port
./Tools/mavlink_shell.py /dev/ttyACM0
```
```sh
# For Wifi connection
./Tools/mavlink_shell.py 0.0.0.0:14550
```
Use `mavlink_shell.py -h` to get a description of all available arguments.
## Використання консолі MAVLink
For information see: [PX4 Consoles/Shells > Using Consoles/Shells](../debug/consoles.md#using_the_console).
@@ -0,0 +1,129 @@
# Plotting uORB Topic Data in Real Time using PlotJuggler
This topic shows how you can graph the "live" values of [uORB topics](../msg_docs/index.md) (in real time) using [PlotJuggler](../log/flight_log_analysis.md#plotjuggler) and the _uXRCE-DDS Agent_.
This technique uses PX4 [uXRCE-DDS](../middleware/uxrce_dds.md) middleware to export uORB topics as ROS2 topics, which can then be read and plotted by PlotJuggler as they change (PlotJuggler cannot directly read uORB topics, but the values of the corresponding ROS 2 topics are the same).
The video below demonstrates this for a simulated vehicle — the approach works equally well on real hardware.
<video src="../../assets/debug/realtime_debugging/realtime_debugging.mp4" width="720" controls></video>
## Вимоги
Follow the [ROS 2 Installation & Setup](../ros2/user_guide.md#installation-setup) instructions in the _ROS2 user guide_ to install:
- ROS 2
- [Micro XRCE-DDS Agent](../ros2/user_guide.md#setup-micro-xrce-dds-agent-client)
- [PX4/px4_msgs](https://github.com/PX4/px4_msgs): PX4/ROS2 shared message definitions.
- PX4 source code and build the simulator.
::: tip
If you're using real hardware instead of the simulator, you will only need PX4 source code if you need to change the set of topics that are published to ROS 2 (only a subset of uORB topics are published by default).
:::
You will also need to install:
- [PlotJuggler for ROS2](https://github.com/facontidavide/PlotJuggler)
::: tip
Use the Debian packages (the snap files are not supported).
:::
## Використання
First we need to build a ROS 2 workspace that includes the `px4_msgs` that correspond to the PX4 build to be monitored, and then launch PlotJuggler from within that workspace.
This allows ROS 2 and PlotJuggler to interpret the messages.
If you're using unmodified PX4, the definitions from [PX4/px4_msgs](https://github.com/PX4/px4_msgs) can be used.
:::info
This is the same process as covered in [Build ROS 2 Workspace](../ros2/user_guide.md#build-ros-2-workspace) in _ROS 2 Installation & Setup_.
:::
Assuming your ROS 2 workspace is named `~/ros2_ws/`, fetch and build the `px4_msgs` package in a terminal as shown:
```sh
cd ~/ros2_ws/src/
git clone https://github.com/PX4/px4_msgs.git
cd ..
colcon build
source install/setup.bash
```
Then run PlotJuggler by entering the following commands in a terminal:
```sh
ros2 run plotjuggler plotjuggler
```
To start sending ROS 2 topics from PX4, the uXRCE-DDS **client** has to be running on PX4, and the `MicroXRCEAgent` has to be running on the same computer as PlotJuggler.
### PX4 Simulator
Next we'll start the [Gazebo](../sim_gazebo_gz/index.md) simulator for a quadcopter.
Because we're using a PX4 simulator the client is started automatically, but we will still need to start the agent and connect to the client.
First open another terminal.
Then navigate to the root of the PX4 source code and start the simulator using the following commands:
```sh
cd ~/PX4-Autopilot
make px4_sitl gz_x500
```
Open another terminal and start the `MicroXRCEAgent` to connect to the the simulator:
```sh
MicroXRCEAgent udp4 -p 8888; exec bash
```
That's all that should be needed for connecting to the simulator.
### PX4 on Hardware
If you're working with real hardware you'll need to explicitly start the client on PX4 and your agent connection command will be slightly different.
[Using flight controller hardware](../ros2/user_guide.md#using-flight-controller-hardware) in the _ROS 2 User Guide_ provides links to setup information.
## Unavailable/New Messages
All PX4 message definitions from `main` are exported to the [PX4/px4_msgs](https://github.com/PX4/px4_msgs) repository.
These must be imported into your ROS 2 workspace, allowing PlotJuggler to interpret messages from PX4.
:::info
Exporting the messages allows ROS 2 and the uXRCE-DDS agent to be independent of PX4, which is why you only need the PX4 source code if you need to build the simulator or modify the messages.
:::
While `px4_msgs` has messages for all uORB topics in PX4, not all messages in `px4_msgs` are available to ROS 2/PlotJuggler by default.
The set that are available must be built into the client running on PX4.
These are defined in [dds_topics.yaml](https://github.com/PX4/PX4-Autopilot/blob/main/src/modules/uxrce_dds_client/dds_topics.yaml).
The instructions below explain the changes needed to monitor topics that are not available by default.
### Missing Topics
If a normal uORB topic is not available in PlotJuggler you will need to modify the [dds_topics.yaml](https://github.com/PX4/PX4-Autopilot/blob/main/src/modules/uxrce_dds_client/dds_topics.yaml) to include the topic and rebuild PX4.
If working with real hardware you will need to build and [install](../config/firmware.md#installing-px4-main-beta-or-custom-firmware) custom firmware after changing the YAML file.
### Modified Messages
If you have modified any uORB messages you must update the ROS2 messages used by PlotJuggler.
You will need to rebuild PX4 with your new messages, and replace the `px4_msgs` (from the repository) in your workspace with the new ones.
Assuming that you have already built PX4 in the directory `~/PX4-Autopilot/`, and that `~/ros2_ws` is your ROS2 workspace, enter the following commands to copy the messages across and rebuild your workspace:
```sh
rm -f ~/ros2_ws/src/px4_msgs/msg/*.msg
cp ~/PX4-Autopilot/msg/*.msg ~/ros2_ws/src/px4_msgs/msg/
cd ~/ros2_ws/ && colcon build
```
### Custom Topics
After defining the topic, follow the instructions above to add the topic to [dds_topics.yaml](https://github.com/PX4/PX4-Autopilot/blob/main/src/modules/uxrce_dds_client/dds_topics.yaml), and export the new message into your ROS 2 workspace.
## Дивись також
[ROS 2 User Guide](../ros2/user_guide.md)
+62
View File
@@ -0,0 +1,62 @@
# Black Magic / Dronecode адаптери
The [Black Magic Probe](https://black-magic.org) is an easy to use, mostly plug-and-play, JTAG/SWD debugger for embedded microcontrollers.
Оскільки Black Magic Probe є загальним зондом для налагодження, вам знадобиться адаптер для підключення до керуючих пристроїв польоту Pixhawk, який можна придбати тут:
- [Drone Code Debug Adapter](https://1bitsquared.com/products/drone-code-debug-adapter) (1 BIT SQUARED).
## Dronecode Probe
The [Dronecode Probe](https://kb.zubax.com/display/MAINKB/Dronecode+Probe+documentation) is a specialization of the Black Magic Probe for debugging PX4 autopilots.
The probe's USB interface exposes two separate virtual serial port interfaces: one for connecting to the [System Console](system_console.md) (UART) and the other for an embedded GDB server (SWD interface).
The probe provides a DCD-M connector cable for attaching to the [Pixhawk Debug Mini](swd_debug.md#pixhawk-debug-mini).
:::info
The _6-pos DF13_ connector that comes with the probe cannot be used for SWD debugging (it is for using the System Console).
:::
## Використання зонда
:::info
To debug STM32F7 or later (FMUv5 and newer) the Dronecode probe / Blackmagic probe likely requires a firmware update.
You can find how to update the [blackmagic probe here](https://github.com/blacksphere/blackmagic/wiki/Upgrading-Firmware).
:::
Щоб використовувати зонд Dronecode з GDB, запустіть GDB з точним ELF-файлом, який в даний момент прошивається на автопілоті:
```sh
arm-none-eabi-gdb build/px4_fmu-v5_default/px4_fmu-v5_default.elf
```
Потім вам потрібно вибрати інтерфейс зонду Dronecode, на Linux це, наприклад.:
```sh
target ext /dev/serial/by-id/usb-Black_Sphere_Technologies_Black_Magic_Probe_f9414d5_7DB85DAC-if00
```
Потім проскануйте ціль:
```sh
monitor swdp_scan
```
І ви маєте побачити щось на зразок:
```sh
Target voltage: 3.3V
Available Targets:
No. Att Driver
1 STM32F76x M7
```
Зверніть увагу, що для деяких автопілотів він показує 0.0V, але наступні кроки все одно працюють.
Тепер ви можете підключитися до цієї цілі:
```sh
attach 1
```
Тепер ви повинні бути підключені.
+71
View File
@@ -0,0 +1,71 @@
# JLink Debug Probe
The [J-Link debug probe][jlink] is a closed-source, commercial hardware probe which supports almost all ARM Cortex-M devices.
You need to install the [J-Link drivers][drivers] for this probe to work:
```sh
# Ubuntu
wget --post-data "accept_license_agreement=accepted" https://www.segger.com/downloads/jlink/JLink_Linux_x86_64.deb
sudo dpkg -i JLink_Linux_x86_64.deb
# macOS
brew install segger-jlink
```
Після встановлення ви можете запустити сервер за допомогою:
```sh
JLinkGDBServer -if swd -device STM32F765II
```
Можливо, перед вами відобразиться запит на оновлення JLink, що й рекомендується зробити, а потім вказати, з яким пристроєм він взаємодіє.
Перевірте документацію вашого автопілота для конкретного пристрою.
Once that's done, the GDB server should be start listening on port `2331`, e.g. like so:
```sh
Checking target voltage...
Target voltage: 3.28 V
Listening on TCP/IP port 2331
Connecting to target...
Connected to target
Waiting for GDB connection...
```
Тепер ви можете запустити GDB з точним elf-файлом, який зараз вивантажений на автопілот (у окремому терміналі):
```sh
arm-none-eabi-gdb build/px4_fmu-v5x_default/px4_fmu-v5x_default.elf -ex "target extended-remote :2331"
```
Тепер ви повинні бути підключені.
To use an IDE instead, see the instructions for [Eclipse](../debug/eclipse_jlink.md) or [VSCode](../dev_setup/vscode.md#hardware-debugging).
See the [Embedded Debug Tools][emdbg] for more advanced debug options.
<a id="segger_jlink_edu_mini"></a>
### Embedded Debug Tools
The [Segger JLink EDU Mini](https://www.segger.com/products/debug-probes/j-link/models/j-link-edu-mini/) is an inexpensive and popular SWD debug probe.
The probe's connector pinout looks like the image below (connect to this using an ARM 10-pin mini connector like [FTSH-105-01-F-DV-K](https://www.digikey.com/products/en?keywords=SAM8796-ND)).
![connector\_jlink\_mini.png](../../assets/debug/connector_jlink_mini.png)
The pin mapping to connect the J-Link Edu Mini to [Pixhawk Debug Mini](swd_debug.md#pixhawk-debug-mini) is shown below.
| Pin | Сигнал | JLink |
| --: | :--------- | ----: |
| 1 | **VREF** | 1 |
| 2 | Console TX | |
| 3 | Console RX | |
| 4 | **SWDIO** | 2 |
| 5 | **SWDCLK** | 4 |
| 6 | **GND** | 3, 5 |
Зверніть увагу, що жоден з JLink debug зондів не має вбудованого послідовного з'єднання, тому вам потрібно підключити консоль окремо.
<!-- Image of SWD cable and connector to debug port - proposed? -->
[jlink]: https://www.segger.com/products/debug-probes/j-link/
[drivers]: https://www.segger.com/downloads/jlink/
[emdbg]: https://pypi.org/project/emdbg/
+84
View File
@@ -0,0 +1,84 @@
# MCU-Link адаптер для налагодження
[MCU-Link Debug Probe](https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/mcu-link-debug-probe:MCU-LINK) - це дешевий, швидкий і дуже потужний засіб відлагодження, який може використовуватися як самостійний засіб відлагодження та комунікатор консолі під час роботи з платами Pixhawk.
Основні функції:
- Тільки єдине USB-C з'єднання для Reset, SWD, SWO та послідовного входу у дуже компактному виконанні!
- До 9,6 Мбіт/с підключення SWO.
До 5 MBaud послідовний. 1.2V до 5V цільової напруги.
З'єднання по високошвидкісному протоколу USB2 до 480 Мбіт/c.
- Приводимий в дію програмним забезпеченням NXP LinkServer або pyOCD з широкою підтримкою пристроїв.
- Набагато дешевше (<15€) ніж адаптер відладки Pixhawk (~20€) з JLink EDU mini (~55€) або JLink BASE (~400€) при кращих технічних характеристиках апаратного забезпечення.
[Адаптер відлагодження Pixhawk](https://holybro.com/products/pixhawk-debug-adapter) надає простий спосіб підключення Pixhawk до MCU-Link (зонд не постачається з адаптером для роботи з контролерами польоту Pixhawk).
:::info
Ці інструкції було перевірено на: FMUv6X-RT, FMUv6X, FMUv6c, FMUv5X.
:::
## Налагодження конфігурації за допомогою NXP LinkServer
MCU-Link забезпечує для чіпів NXP (FMUv6X-RT) сервер GDB [LinkServer](https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/linkserver-for-microcontrollers:LINKERSERVER):
[Завантажте](https://www.nxp.com/design/design-center/software/development-software/mcuxpresso-software-and-tools-/linkserver-for-microcontrollers:LINKERSERVER#downloads) Linkserver для вашої операційної системи та дотримуйтесь інструкцій з установки.
На Windows LinkServer встановлюється в `C:\NXP\LinkServer_x.x.x`
На Linux LinkServer встановлюється `/usr/local/LinkServer/LinkServer`
Для прошивки ви можете використовувати команду `LinkServer flash` з метою `MIMXRT1176xxxxx:MIMXRT1170-EVK-CM7-ONLY` для FMUv6X-RT
```sh
/usr/local/LinkServer/LinkServer flash MIMXRT1176xxxxx:MIMXRT1170-EVK-CM7-ONLY load build/px4_fmu-v6xrt_default/px4_fmu-v6xrt_default.elf
```
Ви можете запустити сервер GDB в новому терміналі:
```sh
/usr/local/LinkServer/LinkServer gdbserver MIMXRT1176xxxxx:MIMXRT1170-EVK-CM7-ONLY
```
Потім підключіться до порту 3333 через GDB:
```sh
arm-none-eabi-gdb build/px4_fmu-v6xrt_default/px4_fmu-v6xrt_default.elf -ex "target extended-remote :3333"
```
Використовуйте GDB, щоб завантажити двійковий файл в Pixhawk:
```sh
(gdb) load
```
## Налаштування відлагодження за допомогою pyOCD
MCU-Link надає [GDB сервер через pyOCD](https://pyocd.io/):
```sh
python3 -m pip install -U pyocd
```
Ви можете запустити сервер GDB в новому терміналі:
```sh
pyocd gdb -t mimxrt1170_cm7
```
Потрібно, щоб ціль була однією з:
- FMUv6X-RT: `mimxrt1170_cm7`
- FMUv6X: `stm32h743xx`
- FMUv6C: `stm32h743xx`
- FMUv5X: `stm32f767zi`
Потім можна під'єднатися до порту 3333 через GDB:
```sh
arm-none-eabi-gdb build/px4_fmu-v6xrt_default/px4_fmu-v6xrt_default.elf -ex "target extended-remote :3333"
```
Використовуйте GDB, щоб завантажити двійковий файл в Pixhawk:
```sh
(gdb) load
```
+203
View File
@@ -0,0 +1,203 @@
# Зонд налагодження STLink
The [STLinkv3-MINIE](https://www.st.com/en/development-tools/stlink-v3minie.html) is a cheap, fast and highly capable debug probe that can serve as a stand-alone debug and console communicator for a PX4 developer:
- Тільки єдине USB-C з'єднання для Reset, SWD, SWO та послідовного входу у дуже компактному виконанні!
- З'єднання по протоколах SWD та SWO - до 24 МГц.
Послідовне з'єднання - до 16 мега бод. Цільова напруга від 1.65В до 3.6В.
З'єднання по високошвидкісному протоколу USB2 до 480 Мбіт/c.
- Керований програмним забезпеченням STLink або OpenOCD із широкою підтримкою пристроїв.
- Набагато дешевше (<15€) ніж адаптер відладки Pixhawk (~20€) з JLink EDU mini (~55€) або JLink BASE (~400€) при кращих технічних характеристиках апаратного забезпечення.
Зонд STLink постачається без адаптера для роботи з контролерами польоту Pixhawk.
The [Pixhawk Debug Port Adapter](#pixhawk-debug-port-adapter) section below explains how you can create your own (some soldering required).
:::info
The [CUAV C-ADB Pixhawk Debugging Adapter](../debug/swd_debug.md#cuav-c-adb-pixhawk-debug-adapter) (~65€) comes with an STLinkv3-MINIE!
This has a connector for the [Pixhawk Debug Full](../debug/swd_debug.md#pixhawk-debug-full) 10-pin SH port (but not the [Pixhawk Debug Mini](../debug/swd_debug.md#pixhawk-debug-mini)).
:::
## Налаштування налагодження
The STLink provides the [GDB server via OpenOCD](https://openocd.org/doc-release/html/index.html):
```sh
# Ubuntu
sudo apt install openocd
# macOS
brew install open-ocd
```
Ви можете запустити сервер GDB в новому терміналі:
```sh
openocd -f interface/stlink.cfg -f target/stm32f7x.cfg
```
Файл налаштувань повинен бути:
- FMUv2-v4: `-f target/stm32f4x.cfg`
- FMUv5: `-f target/stm32f7x.cfg`
- FMUv6: `-f target/stm32h7x.cfg`
Потім можна під'єднатися до порту 3333 через GDB:
```sh
arm-none-eabi-gdb build/px4_fmu-v5x_default/px4_fmu-v5x_default.elf -ex "target extended-remote :3333"
```
See the [Embedded Debug Tools][emdbg] for more advanced debug options.
## Адаптер порту налагодження Pixhawk
To connect to the Pixhawk Debug Port, you need to solder an adapter (unless using the [CUAV Debug Adaptor](../debug/swd_debug.md#cuav-c-adb-pixhawk-debug-adapter)).
Для цієї інструкції паяння вам знадобиться:
- 1x [STLinkv3-MINIE](https://www.st.com/en/development-tools/stlink-v3minie.html).
- 1x cable connector for mating with [JST SM10B (Full)](https://www.digikey.com/products/en?keywords=A10SR10SR30K203A) or [JST SM06B (Mini)](https://www.digikey.com/products/en?keywords=A06SR06SR30K152A).
Рекомендуємо купувати повністю зібрані кабелі з двома роз'ємами з обох боків.
- 1x паяльник та припій.
- Щипці, плоскогубці та пінцет.
The [Pixhawk Debug Port is standardized in DS-009](https://github.com/pixhawk/Pixhawk-Standards/blob/master/DS-009%20Pixhawk%20Connector%20Standard.pdf) and needs to be connected to the STLinkv3-MINIE Board-To-Board (BTB) card edge connector CN2.
Зіставлення контактів описано тут:
| № контакту SM10B (Full) | № контакту SM06B (Mini) | Порт Pixhawk | STLinkv3 | № контакту BTB |
| -----------------------------------------: | -----------------------------------------: | :------------------------------------ | :---------------------------- | -------------: |
| 1 | 1 | **VREF** | VCC | 10 |
| 2 | 2 | TX консолі (вихід) | TX (вхід) | 8 |
| 3 | 3 | RX консолі (вхід) | RX (вихід) | 7 |
| 4 | 4 | **SWDIO** | TMS | 3 |
| 5 | 5 | **SWCLK** | CLK | 4 |
| 6 | | SWO | TDO | 5 |
| 7 | | GPIO1 | | |
| 8 | | GPIO2 | | |
| 9 | | nRST | RST | 9 |
| 10 | 6 | **GND** | GND | 6 |
Контакти GPIO1/2 не підтримуються STLinkv3 та ми рекомендуємо користуватись цифровим ITM профілюванням через SWO що є найбільш гнучким та підтримує точний вимір часу між циклами.
Ви можете спаяти короткий або довгий кабель для BTB роз'єму.
Короткий кабель краще підходить для високошвидкісного зв'язку, але його складніше паяти.
Ми рекомендуємо спочатку спаяти довгий кабель і перевірити, наскільки швидким буде з'єднання з цільовим об'єктом.
:::info
This guide is written for the full 10-pin debug port.
Якщо ви хочете спаяти мініверсію з 6 контактами, просто пропустіть сигнали, яких у вас немає.
STLink підтримує будь-який інтерфейс налагодження на основі SWD/JTAG, тому ви можете адаптувати цю інструкцію для будь-якого роз'єму, який у вас є.
Зонди налагодження настільки дешеві, що ви можете мати по одному на кожен роз'єм замість використання адаптерів.
:::
STLinkv3-MINIE постачається ось таким чином.
![](../../assets/debug/stlinkv3_minie_p1.jpeg)
Розпакуйте плату і перевірте її на наявність пошкоджень.
Під'єднайте її до живлення та переконайтеся, що вона вмикається правильно.
![](../../assets/debug/stlinkv3_minie_p2.jpeg)
### Короткий кабель
Короткий кабель потребує інструмент для обрізання та зачистки кабелю та трохи більше навичок пайки.
Однак це робить увесь зонд налагодження ще меншим.
Зберіть 10-контактний роз'єм без GPIO1/2. Якщо у вас вже є зібраний кабель, обережно видаліть два дроти GPIO1/2 за допомогою пінцета, піднімаючи штирі, які утримують їх на місці.
Відріжте дроти на невелику довжину у приблизно 2 см (1 дюйм) та зачистить їх.
![](../../assets/debug/stlinkv3_minie_p3.jpeg)
Залудіть як роз'єм BTB на STLink так і кабелі.
![](../../assets/debug/stlinkv3_minie_p4.jpeg)
Спочатку припаяйте сигнальні дроти для GND та VCC, щоб вирівняти роз'єм паралельно до краю.
Потім припаяйте контакти TX та RX. Припаяйте з'єднання RST останнім.
![](../../assets/debug/stlinkv3_minie_p5.jpeg)
Переверніть STLink і припаяйте три дроти, що залишились.
Start with SWDIO->TMS, then SWCLK->CLK, and finally SWO->TDO.
![](../../assets/debug/stlinkv3_minie_p6.jpeg)
### Довгий кабель
Довгий кабель особливо корисний, якщо ви використовуєте вже зібрані кабелі, оскільки він усуває потребу в обрізанні або знятті ізоляції з проводів.
Обережно вийміть два дроти GPIO1/2 з одного роз'єму кабелю.
Потім від'єднайте всі дроти від іншого роз'єму.
У вас залишилось вісім обжатих роз'ємів на кінці дротів.
![](../../assets/debug/stlinkv3_minie_p7.jpeg)
Залудіть обжаті роз'єми та роз'єм BTB та припаяйте обжаті роз'єми безпосередньо до STLinkv3.
Будьте обережні, щоб не створити коротке замикання між дротами, оскільки обжаті роз'єми досить великі.
![](../../assets/debug/stlinkv3_minie_p8.jpeg)
### Тестування
Тепер слід протестувати зонд для налагодження, щоб переконатися, що немає жодних коротких замикань.
1. Під'єднайте зонд до цілі через роз'єм налагодження Pixhawk.
2. Перевірте послідовний порт за допомогою програми за вибором.
3. Test the SWD and RST connection via [OpenOCD][https://openocd.org] or [STLink](https://www.st.com/en/development-tools/stsw-link004.html) software.
4. Перевірте підключення SWO за допомогою [Orbuculum][https://github.com/orbcode/orbuculum].
See the [Embedded Debug Tools][emdbg] for more information about software support for the PX4 FMUv5 and FMUv6 flight controllers.
### Зменшення зонду
Цей крок видаляє 14-контактний інтерфейс для налагодження на задній частині STLinkv3-MINIE та додає термоусадку навколо всього пристрою для поліпшення поводження та запобігання короткому замиканню STLink на металеві деталі або плати.
Цей крок є виключно необов'язковим та потребує:
- 1x Термоусадка діаметром 20 мм та довжиною приблизно 5 см.
- 1x плаский затискач для утримання STLinkv3 за порт USB-C.
- 1x дрібні плоскогубці або паяльник.
- 1x паяльний фен.
Використайте плоскогубці, щоб обережно витягнути пластикову частину роз'єму STDC14.
Залишаться тільки контакти роз'єму.
![](../../assets/debug/stlinkv3_minie_p9.jpeg)
За допомогою дрібних плоскогубців відріжте контакти роз'єму дуже обережно, щоб не пошкодити плату або будь-які компоненти на платі.
Або ж ви можете випаяти ці контакти роз'єму з плати, але це може зайняти більше часу.
![](../../assets/debug/stlinkv3_minie_p10.jpeg)
Поверніть STLinkv3, щоб обрізати інший ряд контактів, знову дуже обережно, щоб нічого не пошкодити.
![](../../assets/debug/stlinkv3_minie_p11.jpeg)
Відріжте кусок термоусадки довжиною приблизно 5 см (2 дюйми).
Він повинен бути вирівняний з роз'ємом USB-C і трохи виступати за межі краю.
![](../../assets/debug/stlinkv3_minie_p12.jpeg)
Hold both the PCB and the shrink tube with the flat tongs by the **bottom** metal part of the USB-C connector.
Будьте обережні, щоб помилково не стиснути середню пластикову частину роз'єму USB-C!
![](../../assets/debug/stlinkv3_minie_p13.jpeg)
За допомогою фену зменште термоусадку навколо зонду налагодження.
Переконайтеся, що усадка рівномірно стиснута і захищає всю плату.
![](../../assets/debug/stlinkv3_minie_p14.jpeg)
За бажанням, ви можете додати логотип за вибором, надрукований на папері та обрізаний за розміром.
Зверніть увагу, що нагрів може призвести до плину чорнил, тому може знадобитися поекспериментувати з налаштуваннями фену, які працюють з вашим принтером.
![](../../assets/debug/stlinkv3_minie_p15.jpeg)
[emdbg]: https://pypi.org/project/emdbg/
## Дивись також
- [STLINK-V3MINIE debugger/programmer tiny probe for STM32 microcontrollers](https://www.st.com/resource/en/user_manual/um2910-stlinkv3minie-debuggerprogrammer-tiny-probe-for-stm32-microcontrollers-stmicroelectronics.pdf) (User Manual)
+120
View File
@@ -0,0 +1,120 @@
# Poor Man's Sampling Profiler
This section describes how you can use the [Poor Man's Sampling Profiler](https://github.com/PX4/PX4-Autopilot/blob/main/platforms/nuttx/Debug/poor-mans-profiler.sh) (PMSP) shell script to assess the performance of PX4.
This is an implementation of a known method originally invented by [Mark Callaghan and Domas Mituzas](https://poormansprofiler.org/).
## Підхід
PMSP - це оболонковий сценарій, який працює шляхом переривання виконання прошивки періодично для збору поточного стеку викликів.
Відмічені трасування стеку додаються в текстовий файл.
Once sampling is finished (which normally takes about an hour or more), the collected stack traces are _folded_.
The result of _folding_ is another text file that contains the same stack traces, except that all similar stack traces (i.e. those that were obtained at the same point in the program) are joined together, and the number of their occurrences is recorded.
The folded stacks are then fed into the visualization script, for which purpose we employ [FlameGraph - an open source stack trace visualizer](http://www.brendangregg.com/flamegraphs.html).
## Основне використання
### Вимоги
Профілер покладається на GDB для запуску PX4 на вбудованій цілі.
Так що перед профілюванням цілі, вам потрібно мати обладнання, яке ви хочете профілювати, і вам потрібно скомпілювати та завантажити прошивку на це обладнання.
You will then need a [debug probe](../debug/swd_debug.md#debug-probes) (such as the DroneCode Probe), to run the GDB server and interact with the board.
### Визначення пристрою відладки
The `poor-mans-profiler.sh` automatically detects and uses the correct USB device if you use it with a [DroneCode Probe](../debug/probe_bmp.md#dronecode-probe).
If you use a different kind of probe you may need to pass in the specific _device_ on which the debugger is located.
You can use the bash command `ls -alh /dev/serial/by-id/` to enumerate the possible devices on Ubuntu.
Наприклад, наступні пристрої перераховані з підключеними через USB Pixhawk 4 та DroneCode Probe:
```sh
user@ubuntu:~/PX4-Autopilot$ ls -alh /dev/serial/by-id/
total 0
drwxr-xr-x 2 root root 100 Apr 23 18:57 .
drwxr-xr-x 4 root root 80 Apr 23 18:48 ..
lrwxrwxrwx 1 root root 13 Apr 23 18:48 usb-3D_Robotics_PX4_FMU_v5.x_0-if00 -> ../../ttyACM0
lrwxrwxrwx 1 root root 13 Apr 23 18:57 usb-Black_Sphere_Technologies_Black_Magic_Probe_BFCCB401-if00 -> ../../ttyACM1
lrwxrwxrwx 1 root root 13 Apr 23 18:57 usb-Black_Sphere_Technologies_Black_Magic_Probe_BFCCB401-if02 -> ../../ttyACM2
```
In this case, the script would automatically pick up the device named `*Black_Magic_Probe*-if00`.
Але якщо ви використовуєте інший пристрій, ви зможете знайти відповідний ідентифікатор у вищезазначеному переліку.
Then pass in the appropriate device using the `--gdbdev` argument like this:
```sh
./poor-mans-profiler.sh --elf=build/px4_fmu-v4_default/px4_fmu-v4_default.elf --nsamples=30000 --gdbdev=/dev/ttyACM2
```
### Запуск
Основне використання профілера доступне через систему збірки.
For example, the following command builds and profiles px4_fmu-v4pro target with 10000 samples (fetching _FlameGraph_ and adding it to the path as needed).
```sh
make px4_fmu-v4pro_default profile
```
For more control over the build process, including setting the number of samples, see the [Implementation](#implementation).
## Розуміння виводу
Знизу наведено знімок екрану прикладового виводу (зверніть увагу, що тут він не є інтерактивним):
![FlameGraph Example](../../assets/debug/flamegraph-example.png)
На графіку пламені, горизонтальні рівні представляють рамки стеку, тоді як ширина кожної рамки пропорційна кількості разів, коли вона була вибрана.
Зі свого боку, кількість разів, коли функцію виявилися вибраною, пропорційна тривалості множеній на частоту її виконання.
## Можливі проблеми
Сценарій був розроблений як тимчасове рішення, тому він має деякі проблеми.
Будь ласка, будьте обережні з ними під час використання:
- Якщо GDB працює некоректно, скрипт може не виявити це і продовжити виконання.
У цьому випадку, очевидно, не буде вироблено жодних придатних стеків.
In order to avoid that, the user should periodically check the file `/tmp/pmpn-gdberr.log`, which contains the stderr output of the most recent invocation of GDB.
У майбутньому сценарій слід змінити так, щоб він викликав GDB у тихому режимі, де він буде вказувати проблеми через свій код виходу.
- Іноді GDB просто залишається назавжди, поки відбувається вибіркове збереження стеку.
Під час цієї несправності ціль буде припинена на невизначений термін.
The solution is to manually abort the script and re-launch it again with the `--append` option.
У майбутньому сценарій слід змінити, щоб накладати тайм-аут на кожне викликання GDB.
- Багатопотокові середовища не підтримуються.
Це не впливає на однопроцесорні вбудовані цілі, оскільки вони завжди виконуються в одному потоці, але це обмеження робить профілер несумісним з багатьма іншими програмами.
У майбутньому папку стеку слід модифікувати для підтримки кількох стеків викликів на один зразок.
## Імплементація
The script is located at [/platforms/nuttx/Debug/poor-mans-profiler.sh](https://github.com/PX4/PX4-Autopilot/blob/main/platforms/nuttx/Debug/poor-mans-profiler.sh)
Once launched, it will perform the specified number of samples with the specified time interval.
Collected samples will be stored in a text file in the system temp directory (typically `/tmp`).
Після завершення вибіркового відбору сценарій автоматично викличе папку стеку, вихід якої буде збережено в сусідньому файлі в тимчасовому каталозі.
If the stacks were folded successfully, the script will invoke the _FlameGraph_ script and store the result in an interactive SVG file.
Зверніть увагу, що не всі переглядачі зображень підтримують інтерактивні зображення;
рекомендується відкрити отриманий SVG у веб-переглядачі.
The FlameGraph script must reside in the `PATH`, otherwise PMSP will refuse to launch.
PMSP використовує GDB для збору стек-відстежень.
Currently it uses `arm-none-eabi-gdb`, other toolchains may be added in the future.
Для того щоб мати можливість відображати місця розташування пам'яті на символи, сценарій повинен посилатися на виконуваний файл, який в даний момент працює на цільовому пристрої.
This is done with the help of the option `--elf=<file>`, which expects a path (relative to the root of the repository) pointing to the location of the currently executing ELF.
Приклад використання:
```sh
./poor-mans-profiler.sh --elf=build/px4_fmu-v4_default/px4_fmu-v4_default.elf --nsamples=30000
```
Зверніть увагу, що кожен запуск скрипта перезапише старі стеки.
Should you want to append to the old stacks rather than overwrite them, use the option `--append`:
```sh
./poor-mans-profiler.sh --elf=build/px4_fmu-v4_default/px4_fmu-v4_default.elf --nsamples=30000 --append
```
As one might suspect, `--append` with `--nsamples=0` will instruct the script to only regenerate the SVG without accessing the target at all.
Будь ласка, прочитайте сценарій для більш глибокого розуміння того, як це працює.
@@ -0,0 +1,22 @@
# Sensor/Topic Debugging using the Listener Command
The uORB is an asynchronous `publish()` / `subscribe()` messaging API used for
inter-thread/inter-process communication. The `listener` command can be used from the _QGroundControl MAVLink Console_ to inspect topic (message) values, including the current values published by sensors.
:::tip
Це потужний інструмент для відлагодження, оскільки його можна використовувати навіть тоді, коли QGC підключений через бездротове з'єднання (наприклад, коли транспортний засіб летить).
:::
:::info
The `listener` command is also available through the [System Console](../debug/system_console.md) and the [MAVLink Shell](../debug/mavlink_shell.md).
:::
:::tip
To check what topics are available at what rate, just use the `uorb top` command.
:::
The image below demonstrates _QGroundControl_ being used to get the value of the acceleration sensor.
![QGC MAVLink Console](../../assets/gcs/qgc_mavlink_console_listener_command.png)
For more information about how to determine what topics are available and how to call `listener` see: [uORB Messaging > Listing Topics and Listening in](../middleware/uorb.md#listing-topics-and-listening-in).
+194
View File
@@ -0,0 +1,194 @@
# Відлагодження симуляції
Поскільки симуляція виконується на машині-хості, всі інструменти розробки робочого стола доступні.
## CLANG Address Sanitizer (Mac OS, Linux)
Засіб очищення адрес Clang може допомогти знайти помилки вирівнювання (шини) та інші помилки пам’яті, такі як помилки сегментації. Команда нижче встановлює правильні параметри компіляції.
```sh
make clean # only required on first address sanitizer run after a normal build
PX4_ASAN=1 make px4_sitl jmavsim
```
## Valgrind
```sh
brew install valgrind
```
або
```sh
sudo apt-get install valgrind
```
Для використання valgrind під час симуляції SITL:
```sh
make px4_sitl_default jmavsim___valgrind
```
## Запустіть Gazebo Classic SITL без відлагоджувача
За замовчуванням SITL запускається без приєднаного відлагоджувача при використанні будь-якого симулятора:
```sh
make px4_sitl_default gz
make px4_sitl_default gazebo-classic
make px4_sitl_default jmavsim
```
Для Gazebo Classic (тільки) ви також можете запустити симулятор з прикріпленим відладчиком.
Зверніть увагу, що ви повинні вказати тип транспортного засобу в цільовому симуляторі, як показано нижче:
```sh
make px4_sitl_default gazebo-classic_iris_gdb
make px4_sitl_default gazebo-classic_iris_lldb
```
Це запустить відлагоджувач та запустить додаток SITL з Gazebo та симулятором Iris.
In order to break into the debugger shell and halt the execution, hit `CTRL-C`:
```sh
Process 16529 stopped
* thread #1: tid = 0x114e6d, 0x00007fff90f4430a libsystem_kernel.dylib`__read_nocancel + 10, name = 'px4', queue = 'com.apple.main-thread', stop reason = signal SIGSTOP
frame #0: 0x00007fff90f4430a libsystem_kernel.dylib`__read_nocancel + 10
libsystem_kernel.dylib`__read_nocancel:
-> 0x7fff90f4430a <+10>: jae 0x7fff90f44314 ; <+20>
0x7fff90f4430c <+12>: movq %rax, %rdi
0x7fff90f4430f <+15>: jmp 0x7fff90f3fc53 ; cerror_nocancel
0x7fff90f44314 <+20>: retq
(lldb)
```
In order to not have the DriverFrameworks scheduling interfere with the debugging session `SIGCONT` should be masked in LLDB and GDB:
```sh
(lldb) process handle SIGCONT -n false -p false -s false
```
Або у випадку GDB:
```sh
(gdb) обробка SIGCONT noprint nostop
```
Після цього оболонки lldb або gdb працюють як звичайні сеанси, будь ласка, зверніться до документації LLDB / GDB.
Останній параметр, триплет &lt;viewer_model_debugger&gt;, фактично передається make у каталозі збірки, отже
```sh
make px4_sitl_default gazebo-classic_iris_gdb
```
еквівалентний з
```sh
make px4_sitl_default # Configure with cmake
make -C build/px4_sitl_default classic_iris_gdb
```
Повний список доступних цілей make в каталозі збірки можна отримати за допомогою:
```sh
make help
```
## Прикріплення GDB до запущеного SITL
You can also start your simulation, and _then_ attach `gdb`:
1. У одному термінальному вікні введіть команду для запуску вашої симуляції:
```sh
make px4_sitl_default gazebo-classic
```
As the script runs, note the **SITL COMMAND:** output text located right above the large "PX4" text.
Він перерахує місце розташування вашого файлу px4 bin для подальшого використання.
```sh
SITL COMMAND: "<px4 bin file>" "<build dir>"/etc
______ __ __ ___
| ___ \ \ \ / / / |
| |_/ / \ V / / /| |
| __/ / \ / /_| |
| | / /^\ \ \___ |
\_| \/ \/ |_/
px4 starting.
INFO [px4] startup script: /bin/sh etc/init.d-posix/rcS 0
INFO [init] found model autostart file as SYS_AUTOSTART=10015
```
2. Відкрийте ще один термінал та введіть:
```sh
ps -a
```
Вам слід зафіксувати PID процесу з назвою "PX4"
(У цьому прикладі це 14149)
```sh
atlas:~/px4/main/PX4-Autopilot$ ps -a
PID TTY TIME CMD
1796 tty2 00:01:59 Xorg
1836 tty2 00:00:00 gnome-session-b
14027 pts/1 00:00:00 make
14077 pts/1 00:00:00 sh
14078 pts/1 00:00:00 cmake
14079 pts/1 00:00:00 ninja
14090 pts/1 00:00:00 sh
14091 pts/1 00:00:00 bash
14095 pts/1 00:01:23 gzserver
14149 pts/1 00:02:48 px4
14808 pts/2 00:00:00 ps
```
3. Потім введіть у тому ж вікні
```sh
sudo gdb [px4 bin file path (from step 1) here]
```
Наприклад,
```sh
sudo gdb /home/atlas/px4/base/PX4-Autopilot/build/px4_sitl_default/bin/px4
```
Тепер ви можете прикріпитися до екземпляра PX4, введіть PID, вказаний у кроці 2.
```sh
attach [PID on px4]
```
Тепер у вас повинен бути інтерфейс GDB для налагодження.
## Оптимізація компілятора
It is possible to suppress compiler optimization for given executables and/or modules (as added by cmake with `add_executable` or `add_library`) when configuring
for `posix_sitl_*`.
Це може бути зручним, коли необхідно пройтися по коду з відлагоджувачем або роздрукувати змінні, які інакше були б оптимізовані.
To do so, set the environment variable `PX4_NO_OPTIMIZATION` to be a semi-colon separated list of regular expressions that match the targets that need to be compiled without optimization.
This environment variable is ignored when the configuration isn&#39;t `posix_sitl_*`.
Наприклад,
```sh
export PX4_NO_OPTIMIZATION='px4;^modules__uORB;^modules__systemlib$'
```
would suppress optimization of the targets: platforms\_\_posix\_\_px4_layer, modules\_\_systemlib, modules\_\_uORB, examples\_\_px4_simple_app, modules\_\_uORB\_\_uORB_tests and px4.
Цілі, які можуть відповідати цим регулярним виразам, можна надрукувати за допомогою команди:
```sh
make -C build/posix_sitl_* list_cmake_targets
```
+221
View File
@@ -0,0 +1,221 @@
# Порт для налагодження SWD
PX4 runs on ARM Cortex-M microcontrollers, which contain dedicated hardware for interactive debugging via the [_Serial Wire Debug (SWD)_][swd] interface and non-invasive profiling and high-bandwidth tracing via the [_Serial Wire Ouput (SWO)_][itm] and [_TRACE_ pins][etm].
Інтерфейс відладки SWD дозволяє прямий, низькорівневий, апаратний доступ до процесора мікроконтролера та периферійних пристроїв, тому він не залежить від будь-якого програмного забезпечення на пристрої.
Отже, його можна використовувати для налагодження завантажувальних програм та операційних систем, таких як NuttX.
## Налагодження сигналів
Чотири сигнали необхідні для відлагодження (в жирному шрифті), а решту лише рекомендується.
| Назва | Тип | Опис |
| :-------------------------------------------------------------- | :----- | :----------------------------------------------------------------------------------------------------------- |
| **GND** | Power | Спільний потенціал, спільна основа. |
| **VREF** | Power | Цільове довідкове напруга дозволяє засоби налагодження використовувати рівнеміри на сигнали. |
| **SWDIO** | I/O | Пін даних для послідовного знавантаження через мережу. |
| **SWCLK** | Вхід | Пін годинника для послідовного знавантаження через мережу. |
| nRST | Вхід | PIN скидання є необов’язковим (n = активним низьким). |
| SWO | Output | Однопровідний шлейф асинхронних даних з можливістю виведення даних ITM та DWT. |
| TRACECK | Output | Трасування годинника для паралельної шини. |
| TRACED[0-3] | Output | Трасування синхронної шини даних з 1, 2 чи 4 бітами. |
Пін скидання апаратного забезпечення є необов'язковим, оскільки більшість пристроїв також можуть бути скинуті через лінії SWD. Однак швидке скидання пристрою за допомогою кнопки може бути великим плюсом для розробки.
SWO-пін може випромінювати дані профілювання в реальному часі з наносекундним відмітками часу, тому настійно рекомендується мати доступ до нього для відлагодження.
Піни TRACE потребують спеціалізованих засобів відлагодження для роботи з високою пропускною здатністю та наступним декодуванням потоку даних.
Зазвичай вони недоступні і зазвичай використовуються лише для відлагодження дуже конкретних питань з часом.
<a id="debug-ports"></a>
## Порти налагодження автопілота
Flight controllers commonly provide a single debug port that exposes both the [SWD Interface](#debug-signals) and [System Console](system_console).
The [Pixhawk Connector Standards](#pixhawk-standard-debug-ports) formalize the port that must be used in each FMU version.
However there are still many boards that use different pinouts or connectors, so we recommend you check the [documentation for your autopilot](../flight_controller/index.md) to confirm port location and pinout.
Місцезнаходження порту налагодження та роз'єми для підмножини автопілотів зв'язані нижче:
<a id="port-information"></a>
| Автопілот | Відладочний порт |
| :----------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Holybro Pixhawk 6X-RT (FMUv6X-RT) | [Pixhawk Debug Full](#pixhawk-debug-full) |
| Holybro Pixhawk 6X (FMUv6x) | [Pixhawk Debug Full](#pixhawk-debug-full) |
| Holybro Pixhawk 5X (FMUv5x) | [Pixhawk Debug Full](#pixhawk-debug-full) |
| [Holybro Durandal](../flight_controller/durandal.md#debug-port) | [Pixhawk Debug Mini](#pixhawk-debug-mini) |
| [Holybro Kakute F7](../flight_controller/kakutef7.md#debug-port) | Паяльні майданчики |
| [Holybro Pixhawk 4 Mini](../flight_controller/pixhawk4_mini.md#debug-port) (FMUv5) | [Pixhawk Debug Mini](#pixhawk-debug-mini) |
| [Holybro Pixhawk 4](../flight_controller/pixhawk4.md#debug_port) (FMUv5) | [Pixhawk Debug Mini](#pixhawk-debug-mini) |
| [Drotek Pixhawk 3 Pro](../flight_controller/pixhawk3_pro.md#debug-port) (FMU-v4pro) | [Pixhawk Debug Mini](#pixhawk-debug-mini) |
| [CUAV V5+](../flight_controller/cuav_v5_plus.md#debug-port) | 6-pin JST GH<br>Digikey: [BM06B-GHS-TBT(LF)(SN)(N)][bm06b-ghs-tbt(lf)(sn)(n)] (vertical mount), [SM06B-GHS-TBT(LF)(SN)(N)][sm06b-ghs-tbt(lf)(sn)(n)] (side mount) |
| [CUAV V5nano](../flight_controller/cuav_v5_nano.md#debug_port) | 6-pin JST GH<br>Digikey: [BM06B-GHS-TBT(LF)(SN)(N)][bm06b-ghs-tbt(lf)(sn)(n)] (vertical mount), [SM06B-GHS-TBT(LF)(SN)(N)][sm06b-ghs-tbt(lf)(sn)(n)] (side mount) |
| [3DR Pixhawk](../flight_controller/pixhawk.md#swd-port) | ARM 10-pin JTAG Connector (also used for FMUv2 boards including: _mRo Pixhawk_, _HobbyKing HKPilot32_). |
<a id="pixhawk-standard-debug-ports"></a>
## Стандарт роз'ємів Pixhawk Debug Портів
Проект Pixhawk визначив стандартну схему виводів та тип роз'єму для різних випусків Pixhawk FMU:
:::tip
Check your [specific board](#port-information) to confirm the port used.
:::
| Версія FMU | Версія Pixhawk | Відладочний порт |
| :--------- | :-------------------------------------------------------------- | :---------------------------------------- |
| FMUv2 | [Pixhawk / Pixhawk 1](../flight_controller/pixhawk.md#swd-port) | 10 pin ARM Debug |
| FMUv3 | Pixhawk 2 | 6 pin SUR Debug |
| FMUv4 | Pixhawk 3 | [Pixhawk Debug Mini](#pixhawk-debug-mini) |
| FMUv5 | Pixhawk 4 FMUv5 | [Pixhawk Debug Mini](#pixhawk-debug-mini) |
| FMUv5X | Pixhawk 5X | [Pixhawk Debug Full](#pixhawk-debug-full) |
| FMUv6 | Pixhawk 6 | [Pixhawk Debug Full](#pixhawk-debug-full) |
| FMUv6X | Pixhawk 6X | [Pixhawk Debug Full](#pixhawk-debug-full) |
| FMUv6X-RT | Pixhawk 6X-RT | [Pixhawk Debug Full](#pixhawk-debug-full) |
:::info
There FMU and Pixhawk versions are (only) consistent after FMUv5X.
:::
### Pixhawk Debug Mini
The [Pixhawk Connector Standard](https://github.com/pixhawk/Pixhawk-Standards/blob/master/DS-009%20Pixhawk%20Connector%20Standard.pdf) defines the _Pixhawk Debug Mini_, a _6-Pin SH Debug Port_ that provides access to both SWD pins and the [System Console](system_console).
Це використовується в FMUv4 та FMUv5.
Схема виводів показана нижче (виводи, необхідні для налагодження, виділені жирним шрифтом):
| Pin | Сигнал |
| --: | :--------- |
| 1 | **VREF** |
| 2 | Console TX |
| 3 | Console RX |
| 4 | **SWDIO** |
| 5 | **SWDCLK** |
| 6 | **GND** |
Визначення порту налагодження містить наступні припояні пластины (на платі поряд із роз'ємом):
| Pad | Сигнал | Напруга |
| --: | :----- | :-------------------- |
| 1 | nRST | +3.3V |
| 2 | GPIO1 | +3.3V |
| 3 | GPIO2 | +3.3V |
The socket is a _6-pin JST SH_ - Digikey number: [BM06B-SRSS-TBT(LF)(SN)](https://www.digikey.com/products/en?keywords=455-2875-1-ND) (vertical mount), [SM06B-SRSS-TBT(LF)(SN)](https://www.digikey.com/products/en?keywords=455-1806-1-ND)(side mount).
You can connect to the debug port using a [cable like this one](https://www.digikey.com/products/en?keywords=A06SR06SR30K152A).
![6-pin JST SH Cable](../../assets/debug/cable_6pin_jst_sh.jpg)
### Порти відладки Pixhawk Full
The [Pixhawk Connector Standard](https://github.com/pixhawk/Pixhawk-Standards/blob/master/DS-009%20Pixhawk%20Connector%20Standard.pdf) defines _Pixhawk Debug Full_, a _10-Pin SH Debug Port_ that provides access to both SWD pins and the [System Console](system_console).
This essentially moves the solder pads from beside the [Pixhawk Debug Mini](#pixhawk-debug-mini) into the connector, and also adds an SWO pin.
Цей порт вказаний для використання в FMUv5x, FMUv6, FMUv6x.
Схема виводів показана нижче (виводи, необхідні для налагодження, виділені жирним шрифтом):
| Pin | Сигнал |
| --: | :--------- |
| 1 | **VREF** |
| 2 | Console TX |
| 3 | Console RX |
| 4 | **SWDIO** |
| 5 | **SWDCLK** |
| 6 | SWO |
| 7 | GPIO1 |
| 8 | GPIO2 |
| 9 | nRST |
| 10 | **GND** |
Піни GPIO1/2 є вільними пінами, які можуть бути використані для генерації сигналів у програмному забезпеченні для аналізу часу з логічним аналізатором.
The socket is a _10-pin JST SH_ - Digikey number: [BM10B-SRSS-TB(LF)(SN)](https://www.digikey.com/products/en?keywords=455-1796-2-ND) (vertical mount) or [SM10B-SRSS-TB(LF)(SN)](https://www.digikey.com/products/en?keywords=455-1810-2-ND) (side mount).
You can connect to the debug port using a [cable like this one](https://www.digikey.com/products/en?keywords=A10SR10SR30K203A).
<!-- FIXME: better to have image showing proper connections for SWD+SWO -->
![10-pin JST SH Cable](../../assets/debug/cable_10pin_jst_sh.jpg)
<a id="debug-probes"></a>
## Зонди налагодження для апаратного забезпечення PX4
Flight controllers commonly provide a [single debug port](#autopilot-debug-ports) that exposes both the [SWD Interface](#debug-signals) and [System Console](system_console).
Є кілька зондів відлагодження, які були перевірені та підтримуються для підключення до одного або обох цих інтерфейсів:
- [SEGGER J-Link](../debug/probe_jlink.md): commercial probe, no built-in serial console, requires adapter.
- [Black Magic Probe](../debug/probe_bmp.md): integrated GDB server and serial console, requires adapter.
- [STLink](../debug/probe_stlink): best value, integrated serial console, adapter must be soldered.
- [MCU-Link](../debug/probe_mculink): best value, integrated serial console, requires adapter.
Адаптер для підключення до роз'єму відладки може поставлятися разом із вашим контролером польоту або відлагоджувальним зондом.
Інші варіанти наведено нижче.
## Адаптери для відлагоджування
### Адаптер відлагодження Holybro Pixhawk
The [Holybro Pixhawk Debug Adapter](https://holybro.com/products/pixhawk-debug-adapter) is _highly recommended_ when debugging controllers that use one of the Pixhawk-standard debug connectors.
Це найлегший спосіб підключення:
- Flight controllers that use either the [Pixhawk Debug Full](#pixhawk-debug-full) (10-pin SH) or [Pixhawk Debug Mini](#pixhawk-debug-mini) (6-pin SH) debug port.
- SWD debug probes that support the 10-pin ARM compatible interface standard used by the [Segger JLink EDU mini](../debug/probe_jlink.md) or 20-pin compatible with the Segger JLink or STLink.
![Holybro Pixhawk Debug Adapter](../../assets/debug/holybro_pixhawk_debug_adapter.png)
### Адаптер відлагодження CUAV C-ADB Pixhawk
The [CUAV C-ADB Secondary Development Pixhawk Flight Controller Debug Adapter](https://store.cuav.net/shop/cuav-c-adb/) comes with an [STLinkv3-MINIE Debug Probe](../debug/probe_stlink.md).
This has a ports for connecting to the [Pixhawk Debug Full](#pixhawk-debug-full) (10-pin SH) and CUAV-standard DSU interface (but not the [Pixhawk Debug Mini](../debug/swd_debug.md#pixhawk-debug-mini) (6-pin SH)).
The M2 connector on the adaptor is 14-pin CN4 STDC14 (see the [STLinkv3-MINIE User Manual](https://www.st.com/resource/en/user_manual/um2910-stlinkv3minie-debuggerprogrammer-tiny-probe-for-stm32-microcontrollers-stmicroelectronics.pdf) for more information).
Кабель, який використовується для підключення M2 та STLinkv3-MINIE, постачається з адаптером.
![CUAV C-ADB adaptor connected to the STLinkv3-MINIE](../../assets/debug/cuav_c-adb_debug_adapter/hero.jpg)
### Адаптери для відлагоджування
Some SWD [debug probes](#debug-probes) come with adapters/cables for connecting to common Pixhawk [debug ports](#debug-ports).
Зонди, про які відомо, що поставляються з роз'ємами, перераховані нижче:
- [DroneCode Probe](../debug/probe_bmp.md#dronecode-probe): comes with a connector for attaching to the [Pixhawk Debug Mini](#pixhawk-debug-mini)
### Адаптери, специфічні для плати
Some manufacturers provide cables to make it easy to connect the SWD interface and [System Console](../debug/system_console).
- [CUAV V5nano](../flight_controller/cuav_v5_nano.md#debug_port) and [CUAV V5+](../flight_controller/cuav_v5_plus.md#debug-port) include this debug cable:
![6-pin JST SH Cable](../../assets/debug/cuav_v5_debug_cable.jpg)
### Користувацькі кабелі
Ви також можете створити власні кабелі для підключення до різних плат або зондів:
- Connect `SWDIO`, `SWCLK` and `GND` pins on the debug probe to the corresponding pins on the debug port.
- Підключіть контакт VREF, якщо його підтримує засіб відлагодження.
- Підключіть залишкові контакти, якщо вони є.
See the [STLinkv3-MINIE](probe_stlink) for a guide on how to solder a custom cable.
:::tip
Where possible, we highly recommend that you create or obtain an adapter board rather than custom cables for connecting to SWD/JTAG debuggers and computers.
Це зменшує ризик неправильного підключення проводів, що призводить до проблем з налагодженням, і має перевагу в тому, що адаптери зазвичай надають спільний інтерфейс для підключення до кількох популярних плат керування польотом.
:::
<!-- Reference links used above -->
[swd]: https://developer.arm.com/documentation/ihi0031/a/The-Serial-Wire-Debug-Port--SW-DP-
[itm]: https://developer.arm.com/documentation/ddi0403/d/Appendices/Debug-ITM-and-DWT-Packet-Protocol?lang=en
[etm]: https://developer.arm.com/documentation/ihi0064/latest/
[bm06b-ghs-tbt(lf)(sn)(n)]: https://www.digikey.com/products/en?keywords=455-1582-1-ND
[sm06b-ghs-tbt(lf)(sn)(n)]: https://www.digikey.com/products/en?keywords=455-1568-1-ND
+81
View File
@@ -0,0 +1,81 @@
# Системна консоль PX4
The PX4 _System Console_ provides low-level access to the system, debug output and analysis of the system boot process.
:::tip
The console should be used for debugging if the system won't boot.
The [MAVLink Shell](../debug/mavlink_shell.md) may otherwise be more suitable, as it is much easier to set up and can be used for [many of the same tasks](../debug/consoles.md#console_vs_shell).
:::
## Підключення консолі
The console is made available through a (board-specific) UART that can be connected to a computer USB port using a [3.3V FTDI](https://www.digikey.com/en/products/detail/TTL-232R-3V3/768-1015-ND/1836393) cable.
Це дозволяє доступ до консолі за допомогою термінальної програми.
Pixhawk controller manufacturers are expected to expose the console UART and SWD (JTAG) debug interfaces through a dedicated _debug port_ that complies with the [Pixhawk Connector Standard](#pixhawk_debug_port).
На жаль, деякі дошки попередні цьому стандарту або не відповідають йому.
:::info
Developers targeting a number of different boards may wish to use a [debug adapter](../debug/swd_debug.md#debug-adapters) to simplify connecting boards to FTDI cables and [debug probes](../debug/swd_debug.md#debug-probes-for-px4-hardware).
:::
Розділи нижче наводять посилання на інформацію про проводку та консоль системи для багатьох загальних дошок.
### Проводка, специфічна для плати
The System Console UART pinouts/debug ports are typically documented in [autopilot overview pages](../flight_controller/index.md) (some are linked below):
- [3DR Pixhawk v1 Flight Controller](../flight_controller/pixhawk.md#console-port) (also applies to
[mRo Pixhawk](../flight_controller/mro_pixhawk.md#debug-ports), [Holybro pix32](../flight_controller/holybro_pix32.md#debug-port))
- [Pixhawk 3](../flight_controller/pixhawk3_pro.md#debug-port)
- [Pixracer](../flight_controller/pixracer.md#debug-port)
<a id="pixhawk_debug_port"></a>
### Порти відладки Pixhawk
Pixhawk flight controllers usually come with a [Pixhawk Connector Standard Debug Port](../debug/swd_debug.md#pixhawk-connector-standard-debug-ports) which will be either the 10 pin [Pixhawk Debug Full](../debug/swd_debug.md#pixhawk-debug-full) or 6 pin [Pixhawk Debug Mini](../debug/swd_debug.md#pixhawk-debug-mini) port.
Ці порти мають контакти для консольного TX та RX, які можуть бути підключені до кабелю FTDI.
The mapping for the [Pixhawk Debug Mini](../debug/swd_debug.md#pixhawk-debug-mini) to FTDI is shown below.
| Порти відладки Pixhawk | - | FTDI | - |
| -------------------------- | ----------------------------------- | ---- | ------------------------------------------------------------------- |
| 1 (red) | TARGET PROCESSOR VOLTAGE | | N/C (використовується для налагодження SWD/JTAG) |
| 2 (blk) | CONSOLE TX (OUT) | 5 | FTDI RX (yellow) |
| 3 (blk) | CONSOLE RX (IN) | 4 | FTDI TX (orange) |
| 4 (blk) | SWDIO | | N/C (використовується для налагодження SWD/JTAG) |
| 5 (blk) | SWCLK | | N/C (використовується для налагодження SWD/JTAG) |
| 6 (blk) | GND | 1 | FTDI GND (black) |
The [SWD Debug Port](../debug/swd_debug.md) page and individual flight controller pages have more information about debug port pinouts.
## Відкриття консолі
Після підключення консолі використовуйте інструмент вибору або типові порти з'єднання, описані нижче:
### Linux / Mac OS: Screen
Встановіть screen на Ubuntu (Mac OS вже має його встановленим):
```sh
sudo apt-get install screen
```
- Серійний підключення: Pixhawk v1 / Pixracer використовує швидкість передачі 57600 бод
Connect screen at BAUDRATE baud, 8 data bits, 1 stop bit to the right serial port (use `ls /dev/tty*` and watch what changes when unplugging / replugging the USB device). Common names are `/dev/ttyUSB0` and `/dev/ttyACM0` for Linux and `/dev/tty.usbserial-ABCBD` for Mac OS.
```sh
screen /dev/ttyXXX BAUDRATE 8N1
```
### Windows: PuTTY
Download [PuTTY](http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) and start it.
Потім виберіть 'серійне підключення' і встановіть параметри порту:
- 57600 baud
- 8 data bits
- 1 stop bit
+185
View File
@@ -0,0 +1,185 @@
# Відтворення усієї системи
Можливо записувати та відтворювати довільні частини системи на основі повідомлень ORB.
Перегравання корисне для тестування ефекту різних значень параметрів на основі реальних даних, порівняння різних оцінювачів тощо.
## Вимоги
Перший крок - визначити модуль або модулі, які слід відтворити.
Потім визначте всі вхідні дані для цих модулів, тобто підписані теми ORB.
Для системного відтворення це включає в себе всі апаратні вхідні дані: сенсори, вхід RC, команди MAVLink та файлову систему.
All identified topics need to be logged at full rate (see [logging](../dev_log/logging.md)).
For `ekf2` this is already the case with the default set of logged topics.
It is important that all replayed topics contain only a single absolute timestamp, which is the automatically generated field `timestamp`.
Якщо потрібно додати більше відміток часу, вони повинні бути відносно основної відмітки.
For an example, see [SensorCombined.msg](https://github.com/PX4/PX4-Autopilot/blob/main/msg/SensorCombined.msg).
Причини цього наведено нижче.
## Використання
- Спочатку виберіть файл для відтворення та побудуйте ціль (з каталогу PX4-Autopilot):
```sh
export replay=<absolute_path_to_log_file.ulg>
make px4_sitl_default
```
This will create the build/make output in a separate build directory `build/px4_sitl_default_replay` (so that the parameters don't interfere with normal builds).
It's possible to choose any posix SITL build target for replay, since the build system knows through the `replay` environment variable that it's in replay mode.
- Add ORB publisher rules in the file `build/px4_sitl_default_replay/rootfs/orb_publisher.rules`.
Цей файл визначає модулі, які мають право публікувати певні повідомлення.
Має наступний формат:
```sh
restrict_topics: <topic1>, <topic2>, ..., <topicN>
module: <module>
ignore_others: <true/false>
```
This means that the given list of topics should only be published by `<module>` (which is the command name).
Публікації з будь-якої з цих тем з іншого модуля мовчки ігноруються.
If `ignore_others` is `true`, publications to other topics from `<module>` are ignored.
For replay, we only want the `replay` module to be able to publish the previously identified list of topics.
So, for replaying `ekf2`, the rules file should look like this:
```sh
restrict_topics: sensor_combined, vehicle_gps_position, vehicle_land_detected
module: replay
ignore_others: true
```
З цим модулями, які зазвичай публікують ці теми, не потрібно вимикати для повторення.
- _(Optional)_ Setup parameter overrides (see [instructions below](#overriding-parameters-in-the-original-log)).
- _(Optional)_ Copy a `dataman` mission file from the SD card to the build directory.
Це потрібно лише у випадку, якщо місію слід переграти.
- Почніть відтворення:
```sh
make px4_sitl_default jmavsim
```
Це автоматично відкриє файл журналу, застосує параметри та почне відтворення.
Після завершення буде повідомляти про результат і вихід.
Новостворений файл журналу можна потім проаналізувати. It can be found in `rootfs/fs/microsd/log`, in subdirectories organised by date.
Replayed log file names will have the `_replayed` suffix.
Зверніть увагу, що вищезазначена команда також покаже симулятор, але - в залежності від того, що відтворюється - вона не покаже, що насправді відбувається.
Ще завжди можна підключитися через QGC та, наприклад, переглянути зміну ставлення під час відтворення.
- Нарешті, скасуйте змінну середовища, щоб знову використовувалися звичайні цілі збирання:
```sh
unset replay
```
### Перевизначення параметрів у вихідному журналі
За замовчуванням, під час відтворення застосовуються всі параметри зі стартового файлу журналу.
Якщо параметр змінюється під час запису, він буде змінений у відповідний час під час відтворення.
Parameters can be overridden during a replay in two ways: _fixed_ and _dynamic_.
Коли параметри перевизначаються, відповідні зміни параметрів в журналі не застосовуються під час повторного відтворення.
- **Fixed parameter overrides** will override parameters from the start of the replay.
They are defined in the file `build/px4_sitl_default_replay/rootfs/replay_params.txt`, where each line should have the format `<param_name> <value>`.
Наприклад:
```sh
EKF2_RNG_NOISE 0.1
```
- **Dynamic parameter overrides** will update parameter values at specified times.
Ці параметри все ще будуть ініціалізовані до значень у журналі або в зафіксованих замінах.
Parameter update events should be defined in `build/px4_sitl_default_replay/rootfs/replay_params_dynamic.txt`, where each line has the format `<param_name> <value> <timestamp>`.
Відмітка часу - це час у секундах з моменту початку журналу. Наприклад:
```sh
EKF2_RNG_NOISE 0.15 23.4
EKF2_RNG_NOISE 0.05 56.7
EKF2_RNG_DELAY 4.5 30.0
```
### Важливе зауваження
- Під час відтворення всі відключення в журналі звітуються.
Вони мають негативний вплив на повторення, тому слід уникати втрат під час запису.
- Наразі можливо лише відтворення в 'реальному часі': так швидко, як було зроблено запис.
Це планується розширити у майбутньому.
- Повідомлення з міткою часу 0 буде вважатися недійсним і не буде відтворено.
## EKF2 Повтор
Це спеціалізація системного повторення для швидкого відтворення EKF2.
:::info
The recording and replay of flight logs with [multiple EKF2 instances](../advanced_config/tuning_the_ecl_ekf.md#running-multiple-ekf-instances) is not supported.
To enable recording for EKF replay you must set the parameters to enable a [single EKF2 instance](../advanced_config/tuning_the_ecl_ekf.md#running-a-single-ekf-instance).
:::
У режимі EKF2 відтворення автоматично створить правила публікації ORB, описані вище.
Для виконання повторення EKF2:
- Запишіть оригінальний журнал.
Optionally set `SDLOG_MODE` to `1` to log from boot.
- In addition to the `replay` environment variable, set `replay_mode` to `ekf2`:
```sh
export replay_mode=ekf2
export replay=<absolute_path_to_log.ulg>
```
- Run the replay with the `none` target:
```sh
make px4_sitl none
```
- Once finished, unset both `replay` and `replay_mode`.
```sh
unset replay; unset replay_mode
```
### Налаштування конкретних параметрів EKF2 для відтворення
First install `pyulog`:
```sh
pip install --user pyulog
```
Extract the original log's parameters to `replay_params.txt`:
```sh
ulog_params -i "$replay" -d ' ' | grep -e '^EKF2' > build/px4_sitl_default_replay/rootfs/replay_params.txt
```
Adjust these as desired, and add dynamic parameter overrides in `replay_params_dynamic.txt` if necessary.
## Позаду кадру
Перегравання розділено на 3 компоненти:
- A replay module
These have a negative effect on replay, so care should be taken to avoid dropouts during recording.
- Наразі можливо лише відтворення в 'реальному часі': так швидко, як було зроблено запис.
Модуль відтворення читає журнал та публікує повідомлення з тією самою швидкістю, з якою вони були записані.
До часового позначення кожного повідомлення додається постійний зсув, щоб відповідати поточному часу системи (це причина, чому всі інші часові позначення повинні бути відносними).
The command `replay tryapplyparams` is executed before all other modules are loaded and applies the parameters from the log and user-set parameters.
Then as the last command, `replay trystart` will again apply the parameters and start the actual replay.
Both commands do nothing if the environment variable `replay` is not set.
Правила видавця ORB дозволяють вибрати, яка частина системи повторюється, як описано вище. Вони компілюються лише для цільових posix SITL.
The **time handling** is still an **open point**, and needs to be implemented.