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
@@ -0,0 +1,350 @@
# Запобігання зіткненням
_Collision Prevention_ may be used to automatically slow and stop a vehicle before it can crash into an obstacle.
It can be enabled for multicopter vehicles when using acceleration-based [Position mode](../flight_modes_mc/position.md) (or VTOL vehicles in MC mode).
It can be enabled for multicopter vehicles in [Position mode](../flight_modes_mc/position.md), and can use sensor data from an offboard companion computer, offboard rangefinders over MAVLink, a rangefinder attached to the flight controller, or any combination of the above.
Collision prevention may restrict vehicle maximum speed if the sensor range isn't large enough!
It also prevents motion in directions where no sensor data is available (i.e. if you have no rear-sensor data, you will not be able to fly backwards).
:::tip
If high flight speeds are critical, consider disabling collision prevention when not needed.
:::
:::tip
Ensure that you have sensors/sensor data in all directions that you want to fly (when collision prevention is enabled).
:::
## Загальний огляд
The vehicle restricts the current velocity in order to slow down as it gets closer to obstacles and adapts the acceleration setpoint in order to disallow collision trajectories.
Для того, щоб відійти від перешкоди (або паралельно їй), користувач повинен наказати транспортному засобу рухатися до заданої точки, яка не наближає транспортний засіб до перешкоди.
The algorithm will make minor adjustments to the setpoint direction if it is determined that a “better” setpoint exists within a fixed margin on either side of the requested setpoint.
Users are notified through _QGroundControl_ while _Collision Prevention_ is actively controlling velocity setpoints.
PX4 software setup is covered in the next section.
If you are using a distance sensor attached to your flight controller for collision prevention, it will need to be attached and configured as described in [PX4 Distance Sensor](#rangefinder).
If you are using a companion computer to provide obstacle information see [companion setup](#companion
## Supported Rangefinders {#rangefinder}
### Lanbao PSK-CM8JL65-CC5 [Discontinued]
At time of writing PX4 allows you to use the [Lanbao PSK-CM8JL65-CC5](../sensor/cm8jl65_ir_distance_sensor.md) IR distance sensor for collision prevention “out of the box”, with minimal additional configuration:
- First [attach and configure the sensor](../sensor/cm8jl65_ir_distance_sensor.md), and enable collision prevention (as described above, using [CP_DIST](#CP_DIST)).
- Set the sensor orientation using [SENS_CM8JL65_R_0](../advanced_config/parameter_reference.md#SENS_CM8JL65_R_0).
### LightWare LiDAR SF45 Поворотний лідар
PX4 v1.14 (and later) supports the [LightWare LiDAR SF45](../sensor/sf45_rotating_lidar.md) rotating lidar which provides 320 degree sensing.
### Other Rangefinders
Інші датчики можуть бути активовані, але це вимагає модифікації коду драйвера для встановлення орієнтації датчика та поля зору.
- Attach and configure the distance sensor on a particular port (see [sensor-specific docs](../sensor/rangefinders.md)) and enable collision prevention using [CP_DIST](#CP_DIST).
- Модифікуйте драйвер для встановлення орієнтації.
This should be done by mimicking the `SENS_CM8JL65_R_0` parameter (though you might also hard-code the orientation in the sensor _module.yaml_ file to something like `sf0x start -d ${SERIAL_DEV} -R 25` - where 25 is equivalent to `ROTATION_DOWNWARD_FACING`).
- Modify the driver to set the _field of view_ in the distance sensor UORB topic (`distance_sensor_s.h_fov`).
## PX4 (Software) Setup
Configure collision prevention by [setting the following parameters](../advanced_config/parameters.md) in _QGroundControl_:
| Параметр | Опис |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| <a id="CP_DIST"></a>[CP_DIST](../advanced_config/parameter_reference.md#CP_DIST) | Set the minimum allowed distance (the closest distance that the vehicle can approach the obstacle). Set negative to disable _collision prevention_. <br>> **Warning** This value is the distance to the sensors, not the outside of your vehicle or propellers. Be sure to leave a safe margin! |
| <a id="CP_DELAY"></a>[CP_DELAY](../advanced_config/parameter_reference.md#CP_DELAY) | Set the sensor and velocity setpoint tracking delay. See [Delay Tuning](#delay_tuning) below. |
| <a id="CP_GUIDE_ANG"></a>[CP_GUIDE_ANG](../advanced_config/parameter_reference.md#CP_GUIDE_ANG) | Set the angle (to both sides of the commanded direction) within which the vehicle may deviate if it finds fewer obstacles in that direction. See [Guidance Tuning](#angle_change_tuning) below. |
| <a id="CP_GO_NO_DATA"></a>[CP_GO_NO_DATA](../advanced_config/parameter_reference.md#CP_GO_NO_DATA) | Set to 1 to allow the vehicle to move in directions where there is no sensor coverage (default is 0/`False`). |
| <a id="MPC_POS_MODE"></a>[MPC_POS_MODE](../advanced_config/parameter_reference.md#MPC_POS_MODE) | Set to `Direct velocity` or `Smoothed velocity` to enable Collision Prevention in Position Mode (default is `Acceleration based`). |
## Опис алгоритму
The data from all sensors are fused into an internal representation of 36 sectors around the vehicle, each containing either the sensor data and information about when it was last observed, or an indication that no data for the sector was available.
When the vehicle is commanded to move in a particular direction, all sectors in the hemisphere of that direction are checked to see if the movement will bring the vehicle closer to any obstacles.
Якщо так, то швидкість транспортного засобу буде обмежена.
This velocity restriction takes into account both the inner velocity loop tuned by [MPC_XY_P](../advanced_config/parameter_reference.md#MPC_XY_P), as well as the [jerk-optimal velocity controller](../config_mc/mc_jerk_limited_type_trajectory.md) via [MPC_JERK_MAX](../advanced_config/parameter_reference.md#MPC_JERK_MAX) and [MPC_ACC_HOR](../advanced_config/parameter_reference.md#MPC_ACC_HOR).
The velocity is restricted such that the vehicle will stop in time to maintain the distance specified in [CP_DIST](#CP_DIST).
The range of the sensors for each sector is also taken into account, limiting the velocity via the same mechanism.
:::info
If there is no sensor data in a particular direction, velocity in that direction is restricted to 0 (preventing the vehicle from crashing into unseen objects).
If you wish to move freely into directions without sensor coverage, this can be enabled by setting [CP_GO_NO_DATA](#CP_GO_NO_DATA) to 1.
:::
Delay, both in the vehicle tracking velocity setpoints and in receiving sensor data from external sources, is conservatively estimated via the [CP_DELAY](#CP_DELAY) parameter.
This should be [tuned](#delay_tuning) to the specific vehicle.
If the sectors adjacent to the commanded sectors are 'better' by a significant margin, the direction of the requested input can be modified by up to the angle specified in [CP_GUIDE_ANG](#CP_GUIDE_ANG).
This helps to fine-tune user input to 'guide' the vehicle around obstacles rather than getting stuck against them.
### Range Data Loss
If the autopilot does not receive range data from any sensor for longer than 0.5s, it will output a warning _No range data received, no movement allowed_.
This will force the velocity setpoints in xy to zero.
After 5 seconds of not receiving any data, the vehicle will switch into [HOLD mode](../flight_modes_mc/hold.md).
If you want the vehicle to be able to move again, you will need to disable Collision Prevention by either setting the parameter [CP_DIST](#CP_DIST) to a negative value, or switching to a mode other than [Position mode](../flight_modes_mc/position.md) (e.g. to _Altitude mode_ or _Stabilized mode_).
If you have multiple sensors connected and you lose connection to one of them, you will still be able to fly inside the field of view (FOV) of the reporting sensors.
The data of the faulty sensor will expire and the region covered by this sensor will be treated as uncovered, meaning you will not be able to move there.
:::warning
Be careful when enabling [CP_GO_NO_DATA=1](#CP_GO_NO_DATA), which allows the vehicle to fly outside the area with sensor coverage.
If you lose connection to one of multiple sensors, the area covered by the faulty sensor is also treated as uncovered and you will be able to move there without constraint.
:::
### CP_DELAY Delay Tuning {#delay_tuning}
There are two main sources of delay which should be accounted for: _sensor delay_, and vehicle _velocity setpoint tracking delay_.
Both sources of delay are tuned using the [CP_DELAY](#CP_DELAY) parameter.
The _sensor delay_ for distance sensors connected directly to the flight controller can be assumed to be 0.
Для зовнішніх систем на основі зору затримка датчика може досягати 0,2 с.
Vehicle _velocity setpoint tracking delay_ can be measured by flying at full speed in [Position mode](../flight_modes_mc/position.md), then commanding a stop.
Затримка між фактичною швидкістю та заданою швидкістю може бути виміряна з лог-файлів.
Зазвичай затримка відстеження становить від 0,1 до 0,5 секунди, в залежності від розміру транспортного засобу та налаштувань.
:::tip
If vehicle speed oscillates as it approaches the obstacle (i.e. it slows down, speeds up, slows down) the delay is set too high.
:::
### CP_GUIDE_ANG Guidance Tuning {#angle_change_tuning}
Залежно від транспортного засобу, типу середовища та навичок пілота можуть бути вимоги щодо різних рівнів керування.
Setting the [CP_GUIDE_ANG](#CP_GUIDE_ANG) parameter to 0 will disable the guidance, resulting in the vehicle only moving exactly in the directions commanded.
Збільшення цього параметра дозволить транспортному засобу вибирати оптимальні напрямки для уникнення перешкод, що полегшує прохід через вузькі проміжки і точне збереження мінімальної відстані при об'єзді об'єктів.
If this parameter is too small the vehicle may feel "stuck" when close to obstacles, because only movement away from obstacles at minimum distance are allowed.
If the parameter is too large the vehicle may feel like it slides away from obstacles in directions not commanded by the operator.
Згідно з тестуванням, 30 градусів - це хороший баланс, хоча різні транспортні засоби можуть мати різні вимоги.
:::info
The guidance feature will never direct the vehicle in a direction without sensor data.
If the vehicle feels stuck with only a single distance sensor pointing forwards, this is probably because the guidance cannot safely adapt the direction due to lack of information.
:::
## Опис алгоритму
The data from all sensors are fused into an internal representation of 72 sectors around the vehicle, each containing either the sensor data and information about when it was last observed, or an indication that no data for the sector was available.
When the vehicle is commanded to move in a particular direction, all sectors in the hemisphere of that direction are checked to see if the movement will bring the vehicle closer than allowed to any obstacles. Якщо так, то швидкість транспортного засобу буде обмежена.
The Algorithm then can be split into two parts, the constraining of the acceleration setpoint coming from the operator, and the compensation of the current velocity of the vehicle.
:::info
If there is no sensor data in a particular direction, movement in that direction is restricted to 0 (preventing the vehicle from crashing into unseen objects).
If you wish to move freely into directions without sensor coverage, this can be enabled by setting [CP_GO_NO_DATA](#CP_GO_NO_DATA) to 1.
:::
### Acceleration Constraining
For this we split out the acceleration setpoint into two components, one parallel to the closest distance to the obstacle and one normal to it. Then we scale each of these components according the the figure below.
![Scalefactor](../../assets/computer_vision/collision_prevention/scalefactor.png)
<!-- the code for this figure is at the end of this file -->
### Velocity compensation
This velocity restriction takes into account the [jerk-optimal velocity controller](../config_mc/mc_jerk_limited_type_trajectory.md) via [MPC_JERK_MAX](../advanced_config/parameter_reference.md#MPC_JERK_MAX) and [MPC_ACC_HOR](../advanced_config/parameter_reference.md#MPC_ACC_HOR). Whereby <!--this is only partially valid anymore... check -->
The current velocity is compared with the maximum allowed velocity so that we are still able to break based on the maximal allowed jerk, acceleration and delay. from this we are able to use the proportional gain of the acceleration controller([MPC_XY_VEL_P_ACC](../advanced_config/parameter_reference.md#MPC_XY_VEL_P_ACC)) to transform it into an acceleration.
### Delay
The delay associated with collision prevention, both in the vehicle tracking velocity setpoints and in receiving sensor data from external sources, is conservatively estimated via the [CP_DELAY](#CP_DELAY) parameter.
This should be [tuned](#delay_tuning) to the specific vehicle.
## Companion Setup {#companion}
:::warning
The companion implementation/setup is currently untested (the original companion project was unmaintained and has been archived).
:::
If using a companion computer or external sensor, it needs to supply a stream of [OBSTACLE_DISTANCE](https://mavlink.io/en/messages/common.html#OBSTACLE_DISTANCE) messages, which should reflect when and where obstacle were detected.
The minimum rate at which messages _must_ be sent depends on vehicle speed - at higher rates the vehicle will have a longer time to respond to detected obstacles.
Initial testing of the system used a vehicle moving at 4 m/s with `OBSTACLE_DISTANCE` messages being emitted at 10Hz (the maximum rate supported by the vision system).
The system may work well at significantly higher speeds and lower frequency distance updates.
## Gazebo Simulation
_Collision Prevention_ can be tested using [Gazebo](../sim_gazebo_gz/index.md) with the [x500_lidar_2d](../sim_gazebo_gz/vehicles.md#x500-quadrotor-with-2d-lidar) model.
To do this, start a simulation with the x500 lidar model by running the following command:
```sh
make px4_sitl gz_x500_lidar_2d
```
Next, adjust the relevant parameters to the appropriate values and add arbitrary obstacles to your simulation world to test the collision prevention functionality.
The diagram below shows a simulation of collision prevention as viewed in Gazebo.
![RViz image of collision detection using the x500\_lidar\_2d model in Gazebo](../../assets/simulation/gazebo/vehicles/x500_lidar_2d_viz.png)
## Development Information/Tools
### Plotting Obstacle Distance and Minimum Distance in Real-Time with PlotJuggler
[PlotJuggler](../log/plotjuggler_log_analysis.md) can be used to monitor and visualize obstacle distances in a real-time plot, including the minimum distance to the closest obstacle.
<lite-youtube videoid="amLheoHgwc4" title="Plotting Obstacle Distance and Minimum Distance in Real-Time with PlotJuggler"/>
To use this feature you need to add a reactive Lua script to PlotJuggler, and also configure PX4 to export [`obstacle_distance_fused`](../msg_docs/ObstacleDistance.md) UORB topic data.
The Lua script works by extracting the `obstacle_distance_fused` data at each time step, converting the distance values into Cartesian coordinates, and pushing them to PlotJuggler.
Кроки наступні:
1. Follow the instructions in [Plotting uORB Topic Data in Real Time using PlotJuggler](../debug/plotting_realtime_uorb_data.md)
2. Configure PX4 to publish obstacle distance data (so that it is available to PlotJuggler):
Add the [`obstacle_distance_fused`](../msg_docs/ObstacleDistance.md) UORB topic to your [`dds_topics.yaml`](https://github.com/PX4/PX4-Autopilot/blob/main/src/modules/uxrce_dds_client/dds_topics.yaml) so that it is published by PX4:
```sh
- topic: /fmu/out/obstacle_distance_fused
type: px4_msgs::msg::ObstacleDistance
```
For more information see [DDS Topics YAML](../middleware/uxrce_dds.md#dds-topics-yaml) in _uXRCE-DDS (PX4-ROS 2/DDS Bridge)_.
3. Open PlotJuggler and navigate to the **Tools > Reactive Script Editor** section.
In the **Script Editor** tab, add following scripts in the appropriate sections:
- **Global code, executed once:**
```lua
obs_dist_fused_xy = ScatterXY.new("obstacle_distance_fused_xy")
obs_dist_min = Timeseries.new("obstacle_distance_minimum")
```
- **function(tracker_time)**
```lua
obs_dist_fused_xy:clear()
i = 0
angle_offset = TimeseriesView.find("/fmu/out/obstacle_distance_fused/angle_offset")
increment = TimeseriesView.find("/fmu/out/obstacle_distance_fused/increment")
min_dist = 65535
-- Cache increment and angle_offset values at tracker_time to avoid repeated calls
local angle_offset_value = angle_offset:atTime(tracker_time)
local increment_value = increment:atTime(tracker_time)
if increment_value == nil or increment_value <= 0 then
print("Invalid increment value: " .. tostring(increment_value))
return
end
local max_steps = math.floor(360 / increment_value)
while i < max_steps do
local str = string.format("/fmu/out/obstacle_distance_fused/distances[%d]", i)
local distance = TimeseriesView.find(str)
if distance == nil then
print("No distance data for: " .. str)
break
end
local dist = distance:atTime(tracker_time)
if dist ~= nil and dist < 65535 then
-- Calculate angle and Cartesian coordinates
local angle = angle_offset_value + i * increment_value
local y = dist * math.cos(math.rad(angle))
local x = dist * math.sin(math.rad(angle))
obs_dist_fused_xy:push_back(x, y)
-- Update minimum distance
if dist < min_dist then
min_dist = dist
end
end
i = i + 1
end
-- Push minimum distance once after the loop
if min_dist < 65535 then
obs_dist_min:push_back(tracker_time, min_dist)
else
print("No valid minimum distance found")
end
```
4. Enter a name for the script on the top right, and press **Save**.
Once saved, the script should appear in the _Active Scripts_ section.
5. Start streaming the data using the approach described in [Plotting uORB Topic Data in Real Time using PlotJuggler](../debug/plotting_realtime_uorb_data.md).
You should see the `obstacle_distance_fused_xy` and `obstacle_distance_minimum` timeseries on the left.
Note that you have to press **Save** again to re-enable the scripts after loading a new log file or otherwise clearing data.
### Sensor Data Overview
Collision Prevention has an internal obstacle distance map that divides the plane around the drone into 72 Sectors.
Internally this information is stored in the [`obstacle_distance`](../msg_docs/ObstacleDistance.md) UORB topic.
New sensor data is compared to the existing map, and used to update any sections that has changed.
The angles in the `obstacle_distance` topic are defined as follows:
![Obstacle\_Distance Angles](../../assets/computer_vision/collision_prevention/obstacle_distance_def.svg)
The data from rangefinders, rotary lidars, or companion computers, is processed differently, as described below.
#### Rotary Lidars
Rotary Lidars add their data directly to the [`obstacle_distance`](../msg_docs/ObstacleDistance.md) uORB topic.
#### Rangefinders
Rangefinders publish their data to the [`distance_sensor`](../msg_docs/DistanceSensor.md) uORB topic.
This data is then mapped onto the `obstacle_distance` topic.
All sectors which have any overlap with the orientation (`orientation` and `q`) of the rangefinder, and the horizontal field of view (`h_fov`) are assigned that measurement value.
For example, a distance sensor measuring from 9.99° to 10.01° the measurements will get added to the bin's corresponding to 5° and 10° covering the arc from 2.5° and 12.5°
:::info
the quaternion `q` is only used if the `orientation` is set to `ROTATION_CUSTOM`.
:::
#### Супутні комп'ютери
Companion computers update the `obstacle_distance` topic using ROS2 or the [OBSTACLE_DISTANCE](https://mavlink.io/en/messages/common.html#OBSTACLE_DISTANCE) MAVLink message.
<!-- to edit the image, open it in inkscape -->
<!-- Code to generate the scalefactor plot
import numpy as np
import matplotlib.pyplot as plt
obstacle_dist = -5
cp_dist = 0
scale_dist = 10
x_values_1 = np.linspace(obstacle_dist, cp_dist, 100) # Segment 1: obstacle to cp_dist
x_values_2 = np.linspace(cp_dist, scale_dist, 100) # Segment 2: cp_dist to scale_dist
x_values_3 = np.linspace(scale_dist, 15, 100) # Segment 3: scale_dist onwards
def acceleration_setpoint_1(x):
return -1 + (x - obstacle_dist) / (cp_dist - obstacle_dist)
def acceleration_setpoint_2(x):
return ((x - cp_dist) / (scale_dist - cp_dist))**2
def acceleration_setpoint_3(x):
return 1
y_values_1 = [acceleration_setpoint_1(x) for x in x_values_1]
y_values_2 = [acceleration_setpoint_2(x) for x in x_values_2]
y_values_3 = [acceleration_setpoint_3(x) for x in x_values_3]
plt.figure(figsize=(15, 5))
plt.plot(x_values_1, y_values_1, color='red', label="Below Zero", linewidth=4)
plt.plot(x_values_2, y_values_2, color='orange', label="Above Zero", linewidth=4)
plt.plot(x_values_3, y_values_3, color='green', label="Above Scale Distance", linewidth=4)
plt.xlabel("Distance")
plt.yticks([-1, 0, 1], ['-1', '0', '1']) # Set ticks at -1, 0, and 1
plt.ylabel("Scalefactor") # Change y-axis label to "Scale"
plt.title("Manual Acceleration Setpoint Scaling")
plt.xticks([obstacle_dist, cp_dist, scale_dist], ['Obstacle', 'CP_DIST', 'scale_distance = MPC_VEL_MANUAL / MPC_XY_P'])
plt.grid(True)
plt.show() -->
+23
View File
@@ -0,0 +1,23 @@
# Комп'ютерний зір (оптичний потік, MoCap, VIO, уникання)
Техніки [комп'ютерного зору](https://en.wikipedia.org/wiki/Computer_vision) дозволяють комп'ютерам використовувати візуальні дані для розуміння їх оточення.
PX4 використовує системи комп'ютерного зору (переважно запущені на [супутніх комп'ютерах](../companion_computer/README.md)) для підтримки наступних функцій:
- Оцінка положення/швидкості:
- [Оптичний потік](../sensor/optical_flow.md) забезпечує оцінку швидкості у двох вимірах (з використанням камери, спрямованої вниз, та датчика відстані, спрямованого вниз).
- [Motion Capture](../computer_vision/motion_capture.md) забезпечує 3D-оцінку положення за допомогою системи комп'ютерного зору, яка є _зовнішньою_ відносно апарату.
Це переважно використовується для внутрішньої навігації.
- [Візуальна інерційна одометрія (VIO)](../computer_vision/visual_inertial_odometry.md) забезпечує оцінку 3D-позиції та швидкості за допомогою бортової системи зору та IMU.
Використовується для навігації, коли інформація про глобальне місцезнаходження відсутня або ненадійна.
- Уникнення/планування шляху:
- [Collision Prevention](../computer_vision/collision_prevention.md) використовується для зупинки транспортних засобів до того, як вони можуть зіткнутися з перешкодою (переважно під час польоту в ручному режимі).
:::tip
[Набір для розвитку автономності візійної системи PX4](../complete_vehicles_mc/px4_vision_kit.md) (від Holybro) - це надійний та доступний набір для розробників, які працюють з комп'ютерним зором на PX4.
:::
## Додаткові ресурси
- [XTDrone](https://github.com/robin-shaun/XTDrone/blob/master/README.en.md) - середовище моделювання ROS + PX4 v1.9 для комп'ютерного зору.
У посібнику [XTDrone](https://www.yuque.com/xtdrone/manual_en) є все необхідне для початку роботи!
+19
View File
@@ -0,0 +1,19 @@
# Motion Capture (MoCap)
Захоплення руху (MoCap) — це техніка [комп’ютерного бачення](https://en.wikipedia.org/wiki/Computer_vision) для оцінки 3D _pose_ (положення та орієнтації) транспортного засобу за допомогою механізму позиціонування, який є _зовнішнім_ до засобу.
Він зазвичай використовується для навігації транспортним засобом у ситуаціях, коли GPS відсутній (наприклад, у приміщенні), і надає положення відносно _локальної_ системи координат.
Системи _MoCap_ найчастіше виявляють рух за допомогою інфрачервоних камер, але також можна використовувати інші типи камер, Lidar або Ultra Wideband (UWB).
:::info
_MoCap_ концептуально схожий на [Visual Inertial Odometry (VIO)](../computer_vision/visual_inertial_odometry.md).
Основна відмінність полягає в тому, що у VIO система бачення працює на транспортному засобі та додатково використовує IMU транспортного засобу для надання інформації про швидкість.
:::
## MoCap Ресурси
Для отримання інформації про MoCap, перегляньте:
- [Використання Vision або Motion Capture систем для Position Estimation](../ros/external_position_estimation.md). <!-- bring across info into user guide? -->
- [Політ з Motion Capture (VICON, NOKOV, Optitrack)](../tutorials/motion-capture.md). <!-- bring across info into user guide? -->
- [Using PX4's Navigation Filter (EKF2) > External Vision System](../advanced_config/tuning_the_ecl_ekf.md#external-vision-system)
@@ -0,0 +1 @@
<Redirect to="../computer_vision/path_planning_interface" />
@@ -0,0 +1,21 @@
# Інтерфейс планування маршруту
<Badge type="warning" text="Removed" />
:::warning
The **Path Planning Interface**, along with the features **Obstacle avoidance in Missions** and **Safe Landing** are no longer supported or maintained, and _should not_ be used in any PX4 version.
This code was abandoned due to architectural constraints of the implementation making it hard to maintain, extend, and adopt.
Support has been withdrawn make it clear that this interface is untested.
:::
:::tip
PX4 is now adopting more generic and scalable approaches for integrating these kinds of features.
For example the [PX4 ROS 2 Interface Library](../ros2/px4_ros2_interface_lib.md) allows complete replacement of PX4 flight modes with enhanced versions written using ROS 2.
:::
This interface allows PX4 to stream a proposed path to a companion computer, and receive back a stream of setpoints that more safely achieves the emitted path, or a mirror of the same stream if the path planning software does not support planning for the current PX4 mode.
This enables features such obstacle avoidance in missions and safer landing to be provided by a planner on a companion computer.
This actual code is still present in code at time of writing (PX4 v1.15).
Information about the API and associated features can be found in the [PX4 v1.14 docs](https://docs.px4.io/v1.14/en/computer_vision/path_planning_interface.html).
+1
View File
@@ -0,0 +1 @@
<Redirect to="../computer_vision/path_planning_interface" />
@@ -0,0 +1,176 @@
# Візуальна інерціальна оцінка положення (VIO)
_Візуальна інерціальна одометрія_ (VIO) — це техніка [комп’ютерного бачення](../computer_vision/index.md), яка використовується для оцінки тривимірної _пози_ (локального положення та орієнтації) і _швидкості_ транспортного засобу, що рухається, відносно _локальної_ вихідної позиції.
Він зазвичай використовується для навігації транспортного засобу в ситуаціях, коли GPS відсутній або ненадійний (наприклад, у приміщенні або під час прольоту під мостом).
VIO використовує [Візуальну одометрію](https://en.wikipedia.org/wiki/Visual_odometry) для оцінки _позиції_ транспортного засобу на основі зображень із камери в поєднанні з інерційними вимірюваннями з IMU транспортного засобу (щоб виправити помилки, пов’язані зі швидким рухом транспортного засобу, що призводить до поганого захоплення зображення).
Ця тема надає керівництво щодо налаштування PX4 та супутнього комп'ютера для налаштування VIO.
:::info
Рекомендоване налаштування використовує ROS для передачі інформації VIO до PX4.
Однак сам PX4 не цікавиться джерелом повідомлень, якщо вони надаються через відповідний [інтерфейс MAVLink](../ros/external_position_estimation.md#px4-mavlink-integration).
:::
## Рекомендована настройка
Апаратна та програмна настройка для VIO запропонована в розділах нижче як ілюстрація того, як підключити систему VIO до PX4. Вона використовує готову систему відстеження камери та супутній комп'ютер, що працює під керуванням ROS.
ROS використовується для зчитування інформації про одометрію з камери та подачі її до PX4.
Прикладом підходящої відстежуючої камери є камера відстеження [Intel® RealSense™ T265](../peripherals/camera_t265_vio.md).
### Встановлення камери
Прикріпіть камеру до супутнього комп'ютера та закріпіть її на рамі:
- Прикріпіть камеру з лінзами, спрямованими вниз, якщо це можливо (за замовчуванням).
- Камери зазвичай дуже чутливі до вібрацій; рекомендується використовувати м'яке кріплення (наприклад, за допомогою віброізоляційної піни).
### Налаштування комп'ютера компаньйона
Для налаштування ROS та PX4:
- На комп'ютері-супутнику встановіть та налаштуйте [MAVROS](../ros/mavros_installation.md).
- Реалізуйте та запустіть вузол ROS для зчитування даних з камери та публікації відомостей VIO за допомогою MAVROS.
- Дивіться розділ нижче про вузол [ROS VIO](#vio_ros_node) для подробиць щодо вимог до цього вузла.
- Слідуйте інструкціям [нижче](#ekf2_tuning) для налаштування оцінювача EKF2 в PX4.
- Перевірте підключення до керуючого контролера.
Ви можете використовувати _QGroundControl_ [MAVLink Inspector](https://docs.qgroundcontrol.com/master/en/qgc-user-guide/analyze_view/mavlink_inspector.html), щоб переконатися, що ви отримуєте повідомлення `ODOMETRY` або `VISION_POSITION_ESTIMATE` (або перевірити наявність Повідомлення `HEARTBEAT`, які мають ідентифікатор компонента 197 (`MAV_COMP_ID_VISUAL_INERTIAL_ODOMETRY`)).
:::
- [Перевірте, чи VIO налаштовано правильно](#verify_estimate) перед першим польотом!
<a id="vio_ros_node"></a>
### ROS VIO вузол
У цьому рекомендованому налаштуванні ROS вузла VIO потрібно
1. інтерфейс з обраною апаратурою камери або сенсора,
2. створити повідомлення відомостей, що містять оцінку позиції, які будуть надіслані до PX4 за допомогою MAVROS, та
3. публікувати повідомлення для вказівки стану системи VIO.
Реалізація вузла ROS буде конкретною для використовуваної камери і буде потребувати розробки для використання відповідного інтерфейсу та драйверів для камери.
Повідомлення відомостей повинні бути типу [`nav_msgs/Odometry`](http://docs.ros.org/en/noetic/api/nav_msgs/html/msg/Odometry.html) та публікуватися на темі `/mavros/odometry/out`.
Повідомлення відомостей повинні бути типу [`nav_msgs/Odometry`](http://docs.ros.org/en/noetic/api/nav_msgs/html/msg/Odometry.html) та публікуватися на темі `/mavros/odometry/out`. Вони повинні ідентифікувати компонент як `MAV_COMP_ID_VISUAL_INERTIAL_ODOMETRY` (197) та вказувати `стан системи`. Рекомендовані значення статусу:
- `MAV_STATE_ACTIVE` коли система VIO працює як очікувалося,
- `MAV_STATE_CRITICAL` коли система VIO працює, але з низькою впевненістю, та
- `MAV_STATE_FLIGHT_TERMINATION` коли система зазнала відмови або впевненість в оцінці неприйнятно низька.
<a id="ekf2_tuning"></a>
### Вдосконалення
Наступні параметри повинні бути задані для використання зовнішньої позиції з EKF2.
| Параметр | Налаштування для Зовнішньої Оцінки Положення |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [EKF2_EV_CTRL](../advanced_config/parameter_reference.md#EKF2_EV_CTRL) | Встановіть _горизонтальне об'єднання позиції_, _вертикальне об'єднання позиції_, _об'єднання швидкості_ та _об'єднання кута_ курсу згідно з вашою бажаною моделлю об'єднання. |
| [EKF2_HGT_REF](../advanced_config/parameter_reference.md#EKF2_HGT_REF) | Set to _Vision_ to use the vision as the reference sensor for altitude estimation. |
| [EKF2_EV_DELAY](../advanced_config/parameter_reference.md#EKF2_EV_DELAY) | Встановіть різницю між міткою часу вимірювання та "фактичним" часом захоплення. Для отримання додаткової інформації див. [нижче](#tuning-EKF2_EV_DELAY). |
| [EKF2_EV_POS_X](../advanced_config/parameter_reference.md#EKF2_EV_POS_X), [EKF2_EV_POS_Y](../advanced_config/parameter_reference.md#EKF2_EV_POS_Y), [EKF2_EV_POS_Z](../advanced_config/parameter_reference.md#EKF2_EV_POS_Z) | Встановіть положення візуального датчика відносно корпусу транспортного засобу. |
Їх можна встановити в _QGroundControl_ > **Налаштування автомобіля > Параметри > EKF2** (не забудьте перезавантажити контролер польоту, щоб зміни параметрів набули чинності).
For more detailed/additional information, see: [Using PX4's Navigation Filter (EKF2) > External Vision System](../advanced_config/tuning_the_ecl_ekf.md#external-vision-system).
<a id="tuning-EKF2_EV_DELAY"></a>
#### Налаштування EKF2_EV_DELAY
[EKF2_EV_DELAY](../advanced_config/parameter_reference.md#EKF2_EV_DELAY) - це _затримка оцінювача позиції за допомогою візійної системи відносно вимірювань_.
Іншими словами, це різниця між міткою часу візійної системи та "фактичним" часом захоплення, який був би записаний годинником IMU (тобто "базовий годинник" для EKF2).
Технічно це може бути встановлено на 0, якщо є правильне відміткове (не тільки час прибуття) та синхронізація часу (наприклад, за допомогою NTP) між MoCap та (наприклад) комп'ютерами ROS.
На практиці це може потребувати емпіричного налаштування, оскільки затримки в ланцюгу зв'язку дуже специфічні для конкретного обладнання.
Рідко коли система налаштована з повністю синхронізованим ланцюгом!
Приблизна оцінка затримки може бути отримана з журналів, перевіряючи зсув між частотами IMU та частотами EV:
![ekf2\_ev\_delay log](../../assets/ekf2/ekf2_ev_delay_tuning.png)
:::info
Графік зовнішніх даних проти вбудованої оцінки (як вище) може бути створений за допомогою [FlightPlot](../log/flight_log_analysis.md#flightplot) або подібних засобів аналізу польоту.
:::
Значення можна додатково налаштувати, змінюючи параметр, щоб знайти значення, яке дає найнижчі інновації EKF під час динамічних маневрів.
<a id="verify_estimate"></a>
## Перевірка/підтвердження оцінки VIO
:::info
Параметр [MAV_ODOM_LP](../advanced_config/parameter_reference.md#MAV_ODOM_LP), згаданий нижче, був вилучений у PX4 v1.14.
Цей розділ потрібно оновити. <!-- https://github.com/PX4/PX4-Autopilot/pull/20501#issuecomment-1993788815 -->
:::
Виконайте наступні перевірки, щоб переконатися, що VIO працює належним чином _перед_ першим польотом:
- Встановіть параметр PX4 `MAV_ODOM_LP` на `1`.
Встановіть параметр PX4 `MAV_ODOM_LP` на `1`.
Після цього PX4 буде передавати отриману зовнішню позицію у вигляді повідомлень MAVLink [ODOMETRY](https://mavlink.io/en/messages/common.html#ODOMETRY).
Ви можете перевірити ці повідомлення MAVLink за допомогою [інспектора MAVLink](https://docs.qgroundcontrol.com/master/en/qgc-user-guide/analyze_view/mavlink_inspector.html) в _QGroundControl_
- Поверніть літак так, щоб кватерніон повідомлення `ODOMETRY` був дуже близьким до одиничного кватерніону (w=1, x=y=z=0).
- На цьому етапі корпус виробу зорієнтований у відповідності з ориєнтацією відносно зовнішньої системи координат.
- Якщо вам не вдається отримати кватерніон, близький до одиничного, без обертання або нахилу вашого літака, це, ймовірно, означає, що ваша рама все ще має зміщення нахилу або кочування.
У цьому випадку не продовжуйте і перевірте знову свої координатні рамки.
- Після зорієнтування ви можете підняти літак з землі, і ви маєте бачити, як координата z позиції зменшується.
Переміщення літака вперед повинно збільшувати координату x позиції, а переміщення вправо - збільшувати координату y.
Переміщення засобу праворуч повинно збільшити координату Y.
- Перевірте, що лінійні швидкості у повідомленні виражені в описаній відносно корпусу _FRD_ відліковій системі.
- Встановіть параметр PX4 `MAV_ODOM_LP` назад на 0.
PX4 припинить передавати повідомлення `ODOMETRY` назад.
Якщо ці кроки є послідовними, ви можете спробувати свій перший польот:
1. Покладіть літак на землю і почніть передавати зворотний зв'язок `ODOMETRY` (як вище).
Потягніть палицю газу вниз і зберметизуйте двигуни.
На цьому етапі, зліва палиця на найнижчому положенні, перейдіть у режим позиціонного контролю.
Ви повинні побачити зелену лампочку.
Зелена лампочка свідчить про те, що доступний зворотний зв'язок позиції, і позиційний контроль активований.
2. Покладіть палицю газу в середину (мертву зону), щоб літак підтримував свою висоту.
Підняття палиці збільшить висоту посилки, тоді як зниження значення зменшить її.
Так само, інша палиця змінить положення над землею.
3. Збільшуйте значення перемикача газу, і літак злетить. Відразу після цього поверніть його в середину.
4. Переконайтеся, що літак може утримувати свою позицію.
## Усунення проблем
Спочатку переконайтеся, що MAVROS успішно підключається до автопілота.
Якщо підключення відбувається належним чином, можливі проблеми/рішення:
- **Проблема:** У мене виникає дрейф / відліт дрона, коли він літає, але не коли я несу його без пропелерів.
- Якщо використовуєте [T265](../peripherals/camera_t265_vio.md), спробуйте його м'яко кріпити (ця камера дуже чутлива до високочастотних вібрацій).
- **Проблема:** У мене виникає "туалетний боулінг", коли ввімкнено VIO.
- Переконайтеся, що орієнтація камери відповідає трансформації в запущеному файлі.
Використовуйте [Інспектор MAVLink](https://docs.qgroundcontrol.com/master/en/qgc-user-guide/analyze_view/mavlink_inspector.html) _QGroundControl_, щоб перевірити, що швидкості в повідомленні `ODOMETRY`, що надходить від MAVROS, вирівнані з системою координат FRD.
- **Проблема:** Я хочу використовувати позицію зору для замикання петель, і також хочу запустити GPS.
- Це дійсно складно, оскільки коли вони не збігаються, це збентежить EKF.
За результатами тестування, надійніше використовувати візійну швидкість (якщо ви знайдете спосіб зробити цю конфігурацію надійною, дайте нам знати).
## Інформація для розробників
Розробники, які зацікавлені в розширенні цієї реалізації (або написанні іншої, яка може не залежати від ROS), повинні подивитися [використання візійних або систем відстеження руху для оцінки позиції.](../ros/external_position_estimation.md).
Ця тема також пояснює, як налаштувати VIO для використання з оцінювачем LPE (застарілим).
## Подальша інформація
- [Using PX4's Navigation Filter (EKF2) > External Vision System](../advanced_config/tuning_the_ecl_ekf.md#external-vision-system)