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
+159
View File
@@ -0,0 +1,159 @@
# PX4 Architectural Overview
PX4 consists of two main layers: the [flight stack](#flight-stack) is an estimation and flight control system,
and the [middleware](#middleware) is a general robotics layer that can support any type of autonomous robot, providing internal/external communications and hardware integration.
All PX4 [airframes](../airframes/index.md) share a single codebase (this includes other robotic systems like boats, rovers, submarines etc.). The complete system design is [reactive](http://www.reactivemanifesto.org), which means that:
- All functionality is divided into exchangeable and reusable components
- Communication is done by asynchronous message passing
- The system can deal with varying workload
<a id="architecture"></a>
## High-Level Software Architecture
The diagram below provides a detailed overview of the building blocks of PX4.
The top part of the diagram contains middleware blocks, while the lower
section shows the components of the flight stack.
![PX4 Architecture](../../assets/diagrams/PX4_Architecture.svg)
<!-- This diagram can be updated from
[here](https://drive.google.com/file/d/0B1TDW9ajamYkaGx3R0xGb1NaeU0/view?usp=sharing)
and opened with draw.io Diagrams. You might need to request access if you
don't have a px4.io Google account.
Caution: it can happen that after exporting some of the arrows are wrong. In
that case zoom into the graph until the arrows are correct, and then export
again. -->
The source code is split into self-contained modules/programs (shown in `monospace` in the diagram).
Usually a building block corresponds to exactly one module.
:::tip
At runtime, you can inspect which modules are executed with the `top` command in shell, and each module can be started/stopped individually via `<module_name> start/stop`.
While `top` command is specific to NuttX shell, the other commands can be used in the SITL shell (pxh>) as well.
For more information about each of these modules see the [Modules & Commands Reference](../modules/modules_main.md).
:::
The arrows show the information flow for the _most important_ connections between the modules.
In reality, there are many more connections than shown, and some data (e.g. for parameters) is accessed by most of the modules.
Modules communicate with each other through a publish-subscribe message bus named [uORB](../middleware/uorb.md).
The use of the publish-subscribe scheme means that:
- The system is reactive — it is asynchronous and will update instantly when new data is available
- All operations and communication are fully parallelized
- A system component can consume data from anywhere in a thread-safe fashion
::: info
This architecture allows every single one of these blocks to be rapidly and easily replaced, even at runtime.
:::
### Flight Stack
The flight stack is a collection of guidance, navigation and control algorithms for autonomous drones.
It includes controllers for fixed-wing, multirotor and VTOL airframes as well as estimators for attitude and position.
The following diagram shows an overview of the building blocks of the flight stack.
It contains the full pipeline from sensors, RC input and autonomous flight control (Navigator), down to the motor or servo control (Actuators).
![PX4 High-Level Flight Stack](../../assets/diagrams/PX4_High-Level_Flight-Stack.svg)
<!-- This diagram can be updated from
[here](https://drive.google.com/a/px4.io/file/d/15J0eCL77fHbItA249epT3i2iOx4VwJGI/view?usp=sharing)
and opened with draw.io Diagrams. You might need to request access if you
don't have a px4.io Google account.
Caution: it can happen that after exporting some of the arrows are wrong. In
that case zoom into the graph until the arrows are correct, and then export
again. -->
An **estimator** takes one or more sensor inputs, combines them, and computes a vehicle state (for example the attitude from IMU sensor data).
A **controller** is a component that takes a setpoint and a measurement or estimated state (process variable) as input.
Its goal is to adjust the value of the process variable such that it matches the setpoint.
The output is a correction to eventually reach that setpoint.
For example the position controller takes position setpoints as inputs, the process variable is the currently estimated position, and the output is an attitude and thrust setpoint that move the vehicle towards the desired position.
A **mixer** takes force commands (such as "turn right") and translates them into individual motor commands, while ensuring that some limits are not exceeded.
This translation is specific for a vehicle type and depends on various factors, such as the motor arrangements with respect to the center of gravity, or the vehicle's rotational inertia.
<a id="middleware"></a>
### Middleware
The [middleware](../middleware/index.md) consists primarily of device drivers for embedded sensors, communication with the external world (companion computer, GCS, etc.) and the uORB publish-subscribe message bus.
In addition, the middleware includes a [simulation layer](../simulation/index.md) that allows PX4 flight code to run on a desktop operating system and control a computer modeled vehicle in a simulated "world".
## Update Rates
Since the modules wait for message updates, typically the drivers define how fast a module updates.
Most of the IMU drivers sample the data at 1kHz, integrate it and publish with 250Hz.
Other parts of the system, such as the `navigator`, don't need such a high update rate, and thus run considerably slower.
The message update rates can be [inspected](../middleware/uorb.md) in real-time on the system by running `uorb top`.
<a id="runtime-environment"></a>
## Runtime Environment
PX4 runs on various operating systems that provide a POSIX-API (such as Linux, macOS, NuttX or QuRT).
It should also have some form of real-time scheduling (e.g. FIFO).
The inter-module communication (using [uORB](../middleware/uorb.md)) is based on shared memory.
The whole PX4 middleware runs in a single address space, i.e. memory is shared between all modules.
::: info
The system is designed such that with minimal effort it would be possible to run each module in separate address space (parts that would need to be changed include `uORB`, `parameter interface`, `dataman` and `perf`).
:::
There are 2 different ways that a module can be executed:
- **Tasks**: The module runs in its own task with its own stack and process priority.
- **Work queue tasks**: The module runs on a shared work queue, sharing the same stack and work queue thread priority as other modules on the queue.
- All the tasks must behave co-operatively as they cannot interrupt each other.
- Multiple _work queue tasks_ can run on a queue, and there can be multiple queues.
- A _work queue task_ is scheduled by specifying a fixed time in the future, or via uORB topic update callback.
The advantage of running modules on a work queue is that it uses less RAM, and potentially results in fewer task switches.
The disadvantages are that _work queue tasks_ are not allowed to sleep or poll on a message, or do blocking IO (such as reading from a file).
Long-running tasks (doing heavy computation) should potentially also run in a separate task or at least a separate work queue.
::: info
Tasks running on a work queue do not show up in [`top`](../modules/modules_command.md#top) (only the work queues themselves can be seen - e.g. as `wq:lp_default`).
Use [`work_queue status`](../modules/modules_system.md#work-queue) to display all active work queue items.
:::
### Background Tasks
`px4_task_spawn_cmd()` is used to launch new tasks (NuttX) or threads (POSIX - Linux/macOS) that run independently from the calling (parent) task:
```cpp
independent_task = px4_task_spawn_cmd(
"commander", // Process name
SCHED_DEFAULT, // Scheduling type (RR or FIFO)
SCHED_PRIORITY_DEFAULT + 40, // Scheduling priority
3600, // Stack size of the new task or thread
commander_thread_main, // Task (or thread) main function
(char * const *)&argv[0] // Void pointer to pass to the new task
// (here the commandline arguments).
);
```
### OS-Specific Information
#### NuttX
[NuttX](https://nuttx.apache.org//) is the primary RTOS for running PX4 on a flight-control board.
It is open source (BSD license), light-weight, efficient and very stable.
Modules are executed as tasks: they have their own file descriptor lists, but they share a single address space.
A task can still start one or more threads that share the file descriptor list.
Each task/thread has a fixed-size stack, and there is a periodic task which checks that all stacks have enough free space left (based on stack coloring).
#### Linux/macOS
On Linux or macOS, PX4 runs in a single process, and the modules run in their own threads (there is no distinction between tasks and threads as on NuttX).
+82
View File
@@ -0,0 +1,82 @@
# Control Allocation (Mixing)
::: info
Control allocation replaces the legacy mixing approach used in PX4 v1.13 and earlier.
For PX4 v1.13 documentation see: [Mixing & Actuators](https://docs.px4.io/v1.13/en/concept/mixing.html), [Geometry Files](https://docs.px4.io/v1.13/en/concept/geometry_files.html) and [Adding a New Airframe Configuration](https://docs.px4.io/v1.13/en/dev_airframes/adding_a_new_frame.html).
:::
PX4 takes desired torque and thrust commands from the core controllers and translates them to actuator commands which control motors or servos.
The translation depends on the physical geometry of the airframe.
For example, given a torque command to "turn right" (say):
- A plane with one servo per aileron will command one of servo high and the other low.
- A multicopter will yaw right by changing the speed of all motors.
PX4 separates this translation logic, which is referred to as "mixing" from the attitude/rate controller.
This ensures that the core controllers do not require special handling for each airframe geometry, and greatly improves reusability.
In addition, PX4 abstracts the mapping of output functions to specific hardware outputs.
This means that any motor or servo can be assigned to almost any physical output.
<!-- https://docs.google.com/drawings/d/1Li9YhTLc3yX6mGX0iSOfItHXvaUhevO2DRZwuxPQ1PI/edit -->
![Mixing Overview](../../assets/diagrams/mixing_overview.png)
## Actuator Control Pipeline
Overview of the mixing pipeline in terms of modules and uORB topics (press to show full-screen):
<!-- https://drive.google.com/file/d/1L2IoxsyB4GAWE-s82R_x42mVXW_IDlHP/view?usp=sharing -->
![Pipeline Overview](../../assets/concepts/control_allocation_pipeline.png)
Notes:
- The rate controller outputs torque and thrust setpoints
- the `control_allocator` module:
- handles different geometries based on configuration parameters
- does the mixing
- handles motor failures
- publishes the motor and servo control signals
- publishes the servo trims separately so they can be added as an offset when [testing actuators](../config/actuators.md#actuator-testing) (using the test sliders).
- the output drivers:
- handle the hardware initialization and update
- use a shared library [src/libs/mixer_module](https://github.com/PX4/PX4-Autopilot/blob/main/src/lib/mixer_module/).
The driver defines a parameter prefix, e.g. `PWM_MAIN` that the library then uses for configuration.
Its main task is to select from the input topics and assign the right data to the outputs based on the user set `<param_prefix>_FUNCx` parameter values.
For example if `PWM_MAIN_FUNC3` is set to **Motor 2**, the 3rd output is set to the 2nd motor from `actuator_motors`.
- output functions are defined under [src/lib/mixer_module/output_functions.yaml](https://github.com/PX4/PX4-Autopilot/blob/main/src/lib/mixer_module/output_functions.yaml).
- if you want to control an output from MAVLink, set the relevant output function to **Offboard Actuator Set x**, and then send the [MAV_CMD_DO_SET_ACTUATOR](https://mavlink.io/en/messages/common.html#MAV_CMD_DO_SET_ACTUATOR) MAVLink command.
## Adding a new Geometry or Output Function
See [this commit](https://github.com/PX4/PX4-Autopilot/commit/5cdb6fbd8e1352dcb94bd58918da405f8ff930d7) for how to add a new geometry.
The QGC UI will then automatically show the right configuration UI when [CA_AIRFRAME](../advanced_config/parameter_reference.md#CA_AIRFRAME) is set to the new geometry.
[This commit](https://github.com/PX4/PX4-Autopilot/commit/a65533b46986e32254b64b7c92469afb8178e370) shows how to add a new output function.
Any uORB topic can be subscribed and assigned to a function.
Note that parameters for control allocation are defined in [src/modules/control_allocator/module.yaml](https://github.com/PX4/PX4-Autopilot/blob/main/src/modules/control_allocator/module.yaml)
The schema for this file is [here](https://github.com/PX4/PX4-Autopilot/blob/main/validation/module_schema.yaml#L440=) (in particular, search for the key `mixer:`
## Setting the Default Frame Geometry
When [adding a new frame configuration](../dev_airframes/adding_a_new_frame.md), set the appropriate [CA_AIRFRAME](../advanced_config/parameter_reference.md#CA_AIRFRAME) and other default mixer values for the geometry.
You can see this, for example, in the airframe configuration file [13200_generic_vtol_tailsitter](https://github.com/PX4/PX4-Autopilot/blob/main/ROMFS/px4fmu_common/init.d/airframes/13200_generic_vtol_tailsitter)
```sh
...
param set-default CA_AIRFRAME 4
param set-default CA_ROTOR_COUNT 2
param set-default CA_ROTOR0_KM -0.05
param set-default CA_ROTOR0_PY 0.2
...
```
## Setting up Geometry and Outputs
The broad geometry and default parameters for a vehicle are set (from the frame configuration file) when selecting the airframe in QGroundControl: [Basic Configuration > Airframe](../config/airframe.md).
The geometry parameters and output mapping for the specific frame and flight controller hardware are then configured using the QGroundControl **Actuators** setup screen: [Basic Configuration > Actuator Configuration and Testing](../config/actuators.md).
+175
View File
@@ -0,0 +1,175 @@
# Events Interface
<Badge type="tip" text="PX4 v1.13" />
The _Events Interface_ provides a system-wide API for notification of events, which are published to GCSs via the _MAVLink Events Service_ (to GCSs and other components) and also stored in [system logs](../dev_log/logging.md).
The interface can be used for publishing events for state changes or any other type of occurrence, including things like arming readiness, calibration completion, and reaching the target takeoff height.
::: info
The events interface will replace the use of `mavlink_log_*` calls in PX4 code, (and `STATUS_TEXT` messages in MAVLink) for event notification in PX4 v1.13 and later.
There will be an intermediate period where [both approaches are supported](#backward-compatibility).
:::
## Usage
### Basic
To use the API, add this include:
```cpp
#include <px4_platform_common/events.h>
```
And then define and send the event from the desired code location:
```cpp
events::send(events::ID("mymodule_test"), events::Log::Info, "Test Message");
```
#### Backward compatibility
For older GCS versions without events interface support, PX4 currently sends out all events also as `mavlink_log_*` `STATUSTEXT` message.
In addition, the message must be tagged with an appended tab (`\t`) so that newer GCS's can ignore that and only show the event.
So whenever adding an event, be sure to also add a `mavlink_log_` call. For example:
```cpp
mavlink_log_info(mavlink_log_pub, "Test Message\t");
events::send(events::ID("mymodule_test"), events::Log::Info, "Test Message");
```
All such `mavlink_log_` calls will be removed after the next release.
### Detailed
The above is a minimal example, this is a more extensive one:
```cpp
uint8_t arg1 = 0;
float arg2 = -1.f;
/* EVENT
* @description
* This is the detailed event description.
*
* - value of arg1: {1}
* - value of arg2: {2:.1}
*
* <profile name="dev">
* (This paragraph is only meant to be shown to developers).
* This behavior can be configured with the parameter <param>COM_EXAMPLE</param>.
* </profile>
*
* Link to documentation: <a>https://docs.px4.io</a>
*/
events::send<uint8_t, float>(events::ID("event_name"),
{events::Log::Error, events::LogInternal::Info}, "Event Message", arg1, arg2);
```
Explanations and requirements:
- `/* EVENT`: This tag indicates that a comment defines metadata for the following event.
- **event_name**: the event name (`events::ID(event_name)`).
- must be unique within the whole source code of PX4.
As a general convention, prefix it with the module name, or the source file for larger modules.
- must be a valid variable name, i.e. must not contain spaces, colons, etc.
- from that name, a 24 bit event ID is derived using a hash function.
This means as long as the event name stays the same, so will the ID.
- **Log Level**:
- valid log levels are the same as used in the MAVLink [MAV_SEVERITY](https://mavlink.io/en/messages/common.html#MAV_SEVERITY) enum.
In order of descending importance these are:
```plain
Emergency,
Alert,
Critical,
Error,
Warning,
Notice,
Info,
Debug,
Disabled,
```
```
- Above we specify a separate external and internal log level, which are the levels displayed to GCS users and in the log file, respectively: `{events::Log::Error, events::LogInternal::Info}`.
For the majority of cases you can pass a single log level, and this will be used for both exernal and internal cases.
There are cases it makes sense to have two different log levels.
For example an RTL failsafe action: the user should see it as Warning/Error, whereas in the log, it is an expected system response, so it can be set to `Info`.
```
- **Event Message**:
- Single-line, short message of the event.
It may contain template placeholders for arguments (e.g. `{1}`). For more information see below.
- **Event Description**:
- Detailed, optional event description.
- Can be multiple lines/paragraphs.
- It may contain template placeholders for arguments (e.g. `{2}`) and supported tags (see below)
#### Arguments and Enums
Events can have a fixed set of arguments that can be inserted into the message or description using template placeholders (e.g. `{2:.1m}` - see next section).
Valid types: `uint8_t`, `int8_t`, `uint16_t`, `int16_t`, `uint32_t`, `int32_t`, `uint64_t`, `int64_t` and `float`.
You can also use enumerations as arguments:
- PX4-specific/custom enumerations for events should be defined in [src/lib/events/enums.json](https://github.com/PX4/PX4-Autopilot/blob/main/src/lib/events/enums.json), and can then be used as event argument in the form of `events::send<events::px4::enums::my_enum_t>(...)`.
- MAVLink "common" events are defined in [mavlink/libevents/events/common.json](https://github.com/mavlink/libevents/blob/master/events/common.json) and can be used as event argument in the form of `events::send<events::common::enums::my_enum_t>(...)`.
#### Text format
Text format for event message description:
- characters can be escaped with \\
These have to be escaped: '\\\\', '\\<', '\\{'.
- supported tags:
- Profiles: `<profile name="[!]NAME">CONTENT</profile>`
`CONTENT` will only be shown if the name matches the configured profile.
This can be used for example to hide developer information from end-users.
- URLs: `<a [href="URL"]>CONTENT</a>`.
If `href` is not set, use `CONTENT` as `URL` (i.e.`<a>https://docs.px4.io</a>` is interpreted as `<a href="https://docs.px4.io">https://docs.px4.io</a>`)
- Parameters: `<param>PARAM_NAME</param>`
- no nested tags of the same type are allowed
- arguments: template placeholders that follow python syntax, with 1-based indexing (instead of 0)
- general form: `{ARG_IDX[:.NUM_DECIMAL_DIGITS][UNIT]}`
UNIT:
- m: horizontal distance in meters
- m_v: vertical distance in meters
- m^2: area in m^2
- m/s: speed in m/s
- C: temperature in degrees celsius
- `NUM_DECIMAL_DIGITS` only makes sense for real number arguments.
## Logging
Events are logged according to the internal log level, and [Flight Review](../log/flight_review.md) displays events.
::: info
Flight review downloads metadata based on PX4 master, so if a definition is not yet on master, it will only be able to display the event ID.
:::
## Implementation
During PX4 build, only the code is added directly to the binary by the compiler (i.e. the event ID, log level(s) and any arguments).
The metadata for all events is built into a separate JSON metadata file (using a python script that scans the whole source code for event calls).
### Publishing Event Metadata to a GCS
The event metadata JSON file is compiled into firmware (and/or hosted on the Internet), and made available to ground stations via the [MAVLink Component Metadata service](https://mavlink.io/en/services/component_information.html).
This ensures that metadata is always up-to-date with the code running on the vehicle.
This process is the same as for [parameter metadata](../advanced/parameters_and_configurations.md#publishing-parameter-metadata-to-a-gcs).
For more information see [PX4 Metadata (Translation & Publication)](../advanced/px4_metadata.md)
+120
View File
@@ -0,0 +1,120 @@
# Flight Modes (Developers)
Modes ("flight modes", "drive modes", and so on) are special operational states that control how the autopilot responds to user input and controls vehicle movement.
They are loosely grouped into _manual_, _assisted_ and _auto_ modes, based on the level/type of control provided by the autopilot.
The pilot transitions between flight modes using switches on the remote control or with a ground control station.
Modes can be implemented as [PX4 internal modes](#px4-internal-modes) running on the flight controller, or as [PX4 external (ROS2) modes](#px4-external-modes) running on a companion computer.
From the perspective of a ground station (MAVLink), the origin of a mode is indistinguishable.
This topic links to documentation for the supported modes, compares PX4 internal and external modes, provides implementation hints, and provides links to how PX4 modes can be used with MAVLink.
## Supported Modes
Not all modes are available (or makes sense), on all vehicle types, and some modes behave differently on different vehicle types.
Mode documentation for the PX4 internal modes are listed below:
- [Flight Modes (Multicopter)](../flight_modes_mc/index.md)
- [Flight Modes (Fixed-Wing)](../flight_modes_fw/index.md)
- [Flight Modes (VTOL)](../flight_modes_vtol/index.md)
- [Drive Modes (Differential Rover)](../flight_modes_rover/differential.md)
- [Drive Modes (Ackermann Rover)](../flight_modes_rover/ackermann.md)
- [Basic Configuration > Flight Modes](../config/flight_mode.md)
## Internal vs External Modes
With some exceptions a mode can be implemented in either the FC or companion computer.
The main considerations are listed below.
PX4 external modes cannot be used in the following cases:
- Modes that need to run on vehicles that don't have a companion computer.
- Modes that require low-level access, strict timing, and/or high update rate requirements.
For example, a multicopter mode that implements direct motor control.
- Safety critical modes, such as [Return mode](../flight_modes_mc/return.md).
- When you can't use ROS (for any reason).
External modes should be considered for all other cases.
They have the following benefits:
- Easier to implement as there is no need to deal with low-level embedded constraints and requirements (such as restricted stack sizes).
- Easier to maintain as the integration API is small, well defined, and stable.
- Porting custom PX4 modes on the flight controller between PX4 versions can be much harder, as often flight modes use interfaces that are considered internal, and allowed to change.
- Process termination of a ROS 2 mode results in a fallback to an internal flight mode (while termination of an internal mode may well crash the vehicle).
- They can override existing modes to provide more advanced features.
You can even override a safety-critical mode with a better versions: if the ROS 2 mode crashes the original mode will be engaged.
- High-level functionality is available, including a better-feature programming environment, and many useful Linux and ROS libraries.
- More available compute to do more advanced processing (e.g. computer vision).
Note that the [PX4 ROS 2 Control Interface](../ros2/px4_ros2_control_interface.md) used to create external modes first appeared in PX4 v1.15 and is still considered experimental.
There are still some limitations, but expect changes and ongoing enhancement.
## PX4 External Modes
PX4 external modes, are written in ROS 2 using the [PX4 ROS 2 Control Interface](../ros2/px4_ros2_control_interface.md) (see link for instructions).
## PX4 Internal Modes
<!--
The specific control behaviour of a mode at any time is determined by a [Flight Task](../concept/flight_tasks.md).
A mode might define one or more tasks that define variations of the mode behavior, for example whether inputs are treated as acceleration or velocity setpoints.
The task that is used is normally defined in a parameter, and selected in [src/modules/flight_mode_manager/FlightModeManager.cpp](https://github.com/PX4/PX4-Autopilot/blob/main/src/modules/flight_mode_manager/FlightModeManager.cpp#L266-L285)
Name the relevant modules in which code directly related to flight modes is defined.
Name any base classes that modes must/should derive from
Explain the core things you need to do to make a mode work
Very high level architecture
-->
### Mode Restrictions
Some modes only make sense only under specific pre-flight and in-flight conditions.
For example, a manual control mode should not be used unless the system has a manual controller.
PX4 modes can specify these conditions as _restrictions_.
For internal modes the types of restrictions are listed in the [FailsafeFlags](../msg_docs/FailsafeFlags.md) uORB topic under "Per mode requirements" (duplicated below)
```text
# Per-mode requirements
mode_req_angular_velocity
mode_req_attitude
mode_req_local_alt
mode_req_local_position
mode_req_local_position_relaxed
mode_req_global_position
mode_req_mission
mode_req_offboard_signal
mode_req_home_position
mode_req_wind_and_flight_time_compliance # if set, mode cannot be entered if wind or flight time limit exceeded
mode_req_prevent_arming # if set, cannot arm while in this mode
mode_req_manual_control
mode_req_other # other requirements, not covered above (for external modes)
```
If the condition of restriction is not met:
- arming is not allowed, while the mode is selected
- when already armed, the mode cannot be selected
- when armed and the mode is selected, the relevant failsafe is triggered (e.g. RC loss for the manual control requirement).
Check [Safety (Failsafe) Configuration](../config/safety.md) for how to configure failsafe behaviour.
This is the corresponding flow diagram for the manual control flag (`mode_req_manual_control`):
![Mode requirements diagram](../../assets/middleware/ros2/px4_ros2_interface_lib/mode_requirements_diagram.png)
The requirements for all modes are set in `getModeRequirements()` in [src/modules/commander/ModeUtil/mode_requirements.cpp](https://github.com/PX4/PX4-Autopilot/blob/main/src/modules/commander/ModeUtil/mode_requirements.cpp#L46).
When adding a new mode you will need to add appropriate requirements in that method.
::: tip
Readers may note that this image is from [PX4 ROS2 Control Interface > Failsafes and mode requirements](../ros2/px4_ros2_control_interface.md#failsafes-and-mode-requirements).
The requirements and concepts are the same (though defined in different places).
The main difference is that ROS 2 modes _infer_ the correct requirements to use, while modes in PX4 source code must explicitly specify them.
:::
## MAVLink Integration
PX4 implements the MAVLink [Standard Modes Protocol](../mavlink/standard_modes.md) from PX4 v1.15.
This can be used to discover all modes and the current mode, and to set the current mode.
+219
View File
@@ -0,0 +1,219 @@
# Flight Tasks
_Flight Tasks_ are used within [Flight Modes](../concept/flight_modes.md) to provide specific movement behaviours: e.g. follow me, or flight smoothing.
## Overview
A flight task is a class in the flight task framework derived from the base class [FlightTask](https://github.com/PX4/PX4-Autopilot/blob/main/src/modules/flight_mode_manager/tasks/FlightTask/FlightTask.hpp). Its goal is to generate setpoints for the controller from arbitrary input data, where each task implements the desired vehicle behavior for a specific mode.
Programmers typically override the `activate()` and `update()` virtual methods by calling the base task's minimal implementation and extending with the implementation of the desired behavior.
The `activate()` method is called when switching to the task and allows to initialize its state and take over gently from the passed over setpoints the previous task was just applying.
`update()` is called on every loop iteration during the execution and contains the core behavior implementation producing setpoints.
By convention tasks are contained in a subfolder of [PX4-Autopilot/src/modules/flight_mode_manager/tasks](https://github.com/PX4/PX4-Autopilot/tree/main/src/modules/flight_mode_manager/tasks) named after the task, and the source files are named with the prefix "FlightTask".
::: info
Video overviews from PX4 developer summits are [provided below](#video).
:::
## Creating a Flight Task
The instructions below might be used to create a task named _MyTask_:
1. Create a directory for the new flight task in [PX4-Autopilot/src/modules/flight_mode_manager/tasks](https://github.com/PX4/PX4-Autopilot/tree/main/src/modules/flight_mode_manager/tasks).
By convention the directory is named after the task, so we will call it **/MyTask**.
```sh
mkdir PX4-Autopilot/src/modules/flight_mode_manager/tasks/MyTask
```
2. Create empty source code and _cmake_ files for the new flight task in the _MyTask_ directory using the prefix "FlightTask":
- CMakeLists.txt
- FlightTaskMyTask.hpp
- FlightTaskMyTask.cpp
3. Update **CMakeLists.txt** for the new task
- Copy the contents of the **CMakeLists.txt** for another task - e.g. [Orbit/CMakeLists.txt](https://github.com/PX4/PX4-Autopilot/blob/main/src/modules/flight_mode_manager/tasks/Orbit/CMakeLists.txt)
- Update the copyright to the current year
```cmake
############################################################################
#
# Copyright (c) 2021 PX4 Development Team. All rights reserved.
#
```
- Modify the code to reflect the new task - e.g. replace `FlightTaskOrbit` with `FlightTaskMyTask`.
The code will look something like this:
```cmake
px4_add_library(FlightTaskMyTask
FlightTaskMyTask.cpp
)
target_link_libraries(FlightTaskMyTask PUBLIC FlightTask)
target_include_directories(FlightTaskMyTask PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
```
4. Update the header file (in this case **FlightTaskMyTask.hpp**):
Most tasks reimplement the virtual methods `activate()` and `update()`, and in this example we also have a private variable.
```cpp
#pragma once
#include "FlightTask.hpp"
class FlightTaskMyTask : public FlightTask
{
public:
FlightTaskMyTask() = default;
virtual ~FlightTaskMyTask() = default;
bool update();
bool activate(const trajectory_setpoint_s &last_setpoint) override;
private:
float _origin_z{0.f};
};
```
5. Update the cpp file as appropriate.
This example provides as simple implementation of **FlightTaskMyTask.cpp** that simply indicates that the task methods are called.
```cpp
#include "FlightTaskMyTask.hpp"
bool FlightTaskMyTask::activate(const trajectory_setpoint_s &last_setpoint)
{
bool ret = FlightTask::activate(last_setpoint);
PX4_INFO("FlightTaskMyTask activate was called! ret: %d", ret); // report if activation was successful
return ret;
}
bool FlightTaskMyTask::update()
{
PX4_INFO("FlightTaskMyTask update was called!"); // report update
return true;
}
```
6. Add the new task to the list of tasks to be built in [PX4-Autopilot/src/modules/flight_mode_manager/CMakeLists.txt](https://github.com/PX4/PX4-Autopilot/blob/main/src/modules/flight_mode_manager/CMakeLists.txt#L41).
```cmake
...
list(APPEND flight_tasks_all
Auto
Descend
...
ManualPositionSmoothVel
Transition
MyTask
)
...
```
::: tip
The task added above will be built on all boards, including those with constrained flash such as Pixhawk FMUv2.
If your task is not indended for use on boards with constrained flash it should instead be added to the conditional block shown below (as shown).
```cmake
...
if(NOT px4_constrained_flash_build)
list(APPEND flight_tasks_all
AutoFollowTarget
Orbit
MyTask
)
endif()
...
```
:::
7. Update a flight mode to ensure that the task is called.
Usually a parameter is used to select when a particular flight task should be used.
For example, to enable our new `MyTask` in multicopter Position mode:
- Update `MPC_POS_MODE` ([multicopter_position_mode_params.c](https://github.com/PX4/PX4-Autopilot/blob/main/src/modules/mc_pos_control/multicopter_position_mode_params.c)) to add an option for selecting "MyTask" if the parameter has a previously unused value like 5:
```c
...
* @value 0 Direct velocity
* @value 3 Smoothed velocity
* @value 4 Acceleration based
* @value 5 My task
* @group Multicopter Position Control
*/
PARAM_DEFINE_INT32(MPC_POS_MODE, 5);
```
- Add a case for your new option in the switch for the parameter [FlightModeManager.cpp](https://github.com/PX4/PX4-Autopilot/blob/main/src/modules/flight_mode_manager/FlightModeManager.cpp#L266-L285) to enable the task when `_param_mpc_pos_mode` has the right value.
```cpp
...
// manual position control
...
switch (_param_mpc_pos_mode.get()) {
...
case 3:
error = switchTask(FlightTaskIndex::ManualPositionSmoothVel);
break;
case 5: // Add case for new task: MyTask
error = switchTask(FlightTaskIndex::MyTask);
break;
case 4:
....
...
```
## Test New Flight Task
To test the flight task you need to run the vehicle with the task enabled.
For the example above, this means setting the parameter `MPC_POS_MODE` to 5, taking off, and switching the vehicle to [Position mode](../flight_modes_mc/position.md).
::: info
The task defined above should only be tested on the simulator.
The code doesn't actually create setpoints so the vehicle will not fly.
:::
Build SITL simulation (gazebo-classic)
```sh
make px4_sitl gazebo-classic
```
Open QGroundControl (if not open, no message information will be printed out).
In the console, takeoff and switch to Position mode:
```sh
pxh> commander takeoff
pxh> commander mode posctl
```
The console will continuously display: `INFO [FlightTaskMyTask] FlightTaskMyTask update was called!`.
If you want to change to another flight mode, you can type a command to change the mode, such as `commander mode altctl`.
## Video
The following videos provide an overview of flight tasks in PX4.
The first covers the state of the flight task framework in PX4 v1.9.
The second is an update, which covers the changes in PX4 v1.11.
### PX4 Flight Task Architecture Overview (PX4 Developer Summit 2019)
A description of how flight modes work in PX4 v1.9 (Dennis Mannhart, Matthias Grob).
<lite-youtube videoid="-dkQG8YLffc" title="PX4 Flight Task Architecture Overview"/>
<!-- datestamp:video:youtube:20190704:PX4 Flight Task Architecture Overview — PX4 Developer Summit 2019 -->
### Overview of multicopter control from sensors to motors (PX4 Developer Summit Virtual 2020)
<lite-youtube videoid="orvng_11ngQ" params="start=560" title="Overview of multicopter control from sensors to motors"/>
<!-- datestamp:video:youtube:20200720:Overview of multicopter control from sensors to motors — PX4 Developer Summit Virtual 2020 From 9min20sec - Section on flight tasks-->
The relevant section of this video is an update of flight tasks in PX4 v11.1 at (9min 20sec).
The [slides can be found here (PDF)](https://static.sched.com/hosted_files/px4developersummitvirtual2020/1b/PX4%20Developer%20Summit%202020%20-%20Overview%20of%20multicopter%20control%20from%20sensors%20to%20motors.pdf) - Slides 9 and 12 are relevant.
+3
View File
@@ -0,0 +1,3 @@
# Concepts
This section contains topics about the [PX4 System Architecture](../concept/architecture.md) and other core concepts.
+27
View File
@@ -0,0 +1,27 @@
# PWM_limit State Machine
The`PWM_limit State Machine` controls PWM outputs as a function of pre-armed and armed inputs.
Provides a delay between assertion of "armed" and a ramp-up of throttle on assertion of the armed signal.
## Quick Summary
**Inputs**
- armed: asserted to enable dangerous behaviors such as spinning propellers
- pre-armed: asserted to enable benign behaviors such as moving control surfaces
- this input overrides the current state
- assertion of pre-armed immediately forces behavior of state ON, regardless of current state
- deassertion of pre-armed reverts behavior to current state
**States**
- INIT and OFF
- pwm outputs set to disarmed values.
- RAMP
- pwm outputs ramp from disarmed values to min values.
- ON
- pwm outputs set according to control values.
## State Transition Diagram
![PWM Limit state machine diagram](../../assets/diagrams/pwm_limit_state_diagram.svg)
@@ -0,0 +1,52 @@
# PX4 System Architecture
The sections below provide high-level overview of the PX4 hardware and software stack for two "typical" PX4 systems; one that has just a flight controller, and another that has a flight controller and a companion computer (also known as a "mission computer").
::: info
The [PX4 Architectural Overview](../concept/architecture.md) provides information about the flight stack and middleware.
Offboard APIs are covered in [ROS](../ros/index.md) and [MAVSDK](https://mavsdk.mavlink.io/main/en/).
:::
## Flight Controller (only)
The diagram below provides a high level overview of a typical "simple" PX4 system based around a flight controller.
![PX4 architecture - FC only system](../../assets/diagrams/px4_arch_fc.svg)
<!-- Source for drawing: https://docs.google.com/drawings/d/1_2n43WrbkWTs1kz0w0avVEeebJbfTj5SSqvCmvSOBdU/edit -->
The hardware consists of
- [Flight controller](../flight_controller/index.md) (running the PX4 flight stack). This often includes internal IMUs, compass and barometer.
- [Motor ESCs](../peripherals/esc_motors.md) connected to [PWM outputs](../peripherals/pwm_escs_and_servo.md), [DroneCAN](../dronecan/escs.md) (DroneCAN allows two-way communication, not single direction as shown) or some other bus.
- Sensors ([GPS](../gps_compass/index.md), [compass](../gps_compass/index.md), distance sensors, barometers, optical flow, barometers, ADSB transponders, etc.) connected via I2C, SPI, CAN, UART etc.
- [Camera](../camera/index.md) or other payload. Cameras can be connected to PWM outputs or via MAVLink.
- [Telemetry radios](../telemetry/index.md) for connecting to a ground station computer/software.
- [RC Control System](../getting_started/rc_transmitter_receiver.md) for manual control
The left hand side of the diagram shows the software stack, which is horizontally aligned (approximately) with the hardware parts of the diagram.
- The ground station computer typically runs [QGroundControl](../getting_started/px4_basic_concepts.md#qgc) (or some other ground station software).
It may also run robotics software like [MAVSDK](https://mavsdk.mavlink.io/) or [ROS](../ros/index.md).
- The PX4 flight stack running on the flight controller includes [drivers](../modules/modules_driver.md), [comms modules](../modules/modules_communication.md), [controllers](../modules/modules_controller.md), [estimators](../modules/modules_controller.md) and other [middleware and system modules](../modules/modules_main.md).
## FC and Companion Computer
The diagram below shows a PX4 system that includes both a flight controller and a companion computer (here referred to as a "mission computer").
![PX4 architecture - FC + Companion Computer](../../assets/diagrams/px4_arch_fc_companion.svg)
<!-- source for drawing: https://docs.google.com/drawings/d/1zFtvA_B-BmfmxFmAd-XIvAZ-jRqOydj0aBtqSolBcqI/edit -->
The flight controller runs the normal PX4 flight stack, while a companion computer provides advanced features that utilise [computer vision](../computer_vision/index.md).
The two systems are connected using a fast serial or IP link, and typically communicate using the [MAVLink protocol](https://mavlink.io/en/).
Communications with the ground stations and the cloud are usually routed via the companion computer (e.g. using the [MAVLink Router](https://github.com/mavlink-router/mavlink-router) (from Intel)).
PX4 systems typically run a Linux OS on the companion computer.
Linux is a much better platform for "general" software development than NuttX; there are many more Linux developers and a lot of useful software has already been written (e.g. for computer vision, communications, cloud integrations, hardware drivers).
Companion computers sometimes run Android for the same reason.
::: info
The diagram shows a cloud or ground station connection via LTE, an approach that has been used a number of PX4-based systems.
PX4 does not deliver software specifically for LTE and/or cloud integration (this requires custom development).
:::
+24
View File
@@ -0,0 +1,24 @@
# PX4 SD Card Layout
The PX4 SD Card is used for storing configuration files, flight logs, mission information etc.
:::tip
The SD card should be FAT32 formatted for use with PX4 (this is the default for SD cards).
We recommend that you reformat cards that are using a different file system.
:::
The directory structure/layout is shown below.
| Directory/File(s) | Description |
| ----------------------- | ---------------------------------------------------------------------------------------- |
| `/etc/` | Extra config. See [System Startup > Replacing the System Startup][replace system start]. |
| `/log/` | Full [flight logs](../dev_log/logging.md) |
| `/mission_log/` | Reduced flight logs |
| `/fw/` | [DroneCAN](../dronecan/index.md) firmware |
| `/uavcan.db/` | DroneCAN DNA server DB + logs |
| `/params` | Parameters (if not in FRAM/FLASH) |
| `/dataman` | Mission storage file |
| `/fault_<datetime>.txt` | Hardfault files |
| `/bootlog.txt` | Boot log file |
[replace system start]: ../concept/system_startup.md#replacing-the-system-startup
+147
View File
@@ -0,0 +1,147 @@
# System Startup
The PX4 startup is controlled by shell scripts.
On NuttX they reside in the [ROMFS/px4fmu_common/init.d](https://github.com/PX4/PX4-Autopilot/tree/main/ROMFS/px4fmu_common/init.d) folder - some of these are also used on Posix (Linux/MacOS).
The scripts that are only used on Posix are located in [ROMFS/px4fmu_common/init.d-posix](https://github.com/PX4/PX4-Autopilot/tree/main/ROMFS/px4fmu_common/init.d-posix).
All files starting with a number and underscore (e.g. `10000_airplane`) are predefined airframe configurations.
They are exported at build-time into an `airframes.xml` file which is parsed by [QGroundControl](http://qgroundcontrol.com) for the airframe selection UI.
Adding a new configuration is covered [here](../dev_airframes/adding_a_new_frame.md).
The remaining files are part of the general startup logic.
The first executed file is the [init.d/rcS](https://github.com/PX4/PX4-Autopilot/blob/main/ROMFS/px4fmu_common/init.d/rcS) script (or [init.d-posix/rcS](https://github.com/PX4/PX4-Autopilot/blob/main/ROMFS/px4fmu_common/init.d-posix/rcS) on Posix), which calls all other scripts.
The following sections are split according to the operating system that PX4 runs on.
## Posix (Linux/MacOS)
On Posix, the system shell is used as script interpreter (e.g. /bin/sh, being symlinked to dash on Ubuntu).
For that to work, a few things are required:
- PX4 modules need to look like individual executables to the system.
This is done via symbolic links.
For each module a symbolic link `px4-<module> -> px4` is created in the `bin` directory of the build folder.
When executed, the binary path is checked (`argv[0]`), and if it is a module (starts with `px4-`), it sends the command to the main px4 instance (see below).
:::tip
The `px4-` prefix is used to avoid conflicts with system commands (e.g. `shutdown`), and it also allows for simple tab completion by typing `px4-<TAB>`.
:::
- The shell needs to know where to find the symbolic links.
For that the `bin` directory with the symbolic links is added to the `PATH` variable right before executing the startup scripts.
- The shell starts each module as a new (client) process.
Each client process needs to communicate with the main instance of px4 (the server), where the actual modules are running as threads.
This is done through a [UNIX socket](http://man7.org/linux/man-pages/man7/unix.7.html).
The server listens on a socket, to which clients can connect and send a command.
The server then sends the output and return code back to the client.
- The startup scripts call the module directly, e.g. `commander start`, rather than using the `px4-` prefix.
This works via aliases: for each module an alias in the form of `alias <module>=px4-<module>` is created in the file `bin/px4-alias.sh`.
- The `rcS` script is executed from the main px4 instance.
It does not start any modules, but first updates the `PATH` variable and then simply runs a shell with the `rcS` file as argument.
- In addition to that, multiple server instances can be started for multi-vehicle simulations.
A client selects the instance via `--instance`.
The instance is available in the script via `$px4_instance` variable.
The modules can be executed from any terminal when PX4 is already running on a system.
For example:
```sh
cd <PX4-Autopilot>/build/px4_sitl_default/bin
./px4-commander takeoff
./px4-listener sensor_accel
```
### Dynamic Modules
Normally, all modules are compiled into a single PX4 executable.
However, on Posix, there's the option of compiling a module into a separate file, which can be loaded into PX4 using the `dyn` command.
```sh
dyn ./test.px4mod
```
## NuttX
NuttX has an integrated shell interpreter ([NuttShell (NSH)](https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=139629410)), and thus scripts can be executed directly.
### Debugging the System Boot
A failure of a driver of software component will not lead to an aborted boot.
This is controlled via `set +e` in the startup script.
The boot sequence can be debugged by connecting the [system console](../debug/system_console.md) and power-cycling the board.
The resulting boot log has detailed information about the boot sequence and should contain hints why the boot aborted.
#### Common boot failure causes
- For custom applications: The system was out of RAM.
Run the `free` command to see the amount of free RAM.
- A software fault or assertion resulting in a stack trace
### Replacing the System Startup
The whole boot can be replaced by creating a file `/etc/rc.txt` on the microSD card with a new configuration (nothing in the old configuration will be auto-started, and if the file is empty, nothing at all will be started).
Customizing the default boot is almost always a better approach.
This is documented below.
### Customizing the System Startup
The best way to customize the system startup is to introduce a [new frame configuration](../dev_airframes/adding_a_new_frame.md).
The frame configuration file can be included in the firmware or on an SD Card.
If you only need to "tweak" the existing configuration, such as starting one more application or setting the value of a few parameters, you can specify these by creating two files in the `/etc/` directory of the SD Card:
- [/etc/config.txt](#customizing-the-configuration-config-txt): modify parameter values
- [/etc/extras.txt](#starting-additional-applications-extras-txt): start applications
The files are described below.
:::warning
The system boot files are UNIX FILES which require UNIX LINE ENDINGS.
If editing on Windows use a suitable editor.
:::
::: info
These files are referenced in PX4 code as `/fs/microsd/etc/config.txt` and `/fs/microsd/etc/extras.txt`, where the root folder of the microsd card is identified by the path `/fs/microsd`.
:::
#### Customizing the Configuration (config.txt)
The `config.txt` file can be used to modify parameters.
It is loaded after the main system has been configured and _before_ it is booted.
For example, you could create a file on the SD card, `etc/config.txt` with that sets parameter values as shown:
```sh
param set-default PWM_MAIN_DIS3 1000
param set-default PWM_MAIN_MIN3 1120
```
#### Starting Additional Applications (extras.txt)
The `extras.txt` can be used to start additional applications after the main system boot.
Typically these would be payload controllers or similar optional custom components.
:::warning
Calling an unknown command in system boot files may result in boot failure.
Typically the system does not stream mavlink messages after boot failure, in this case check the error messages that are printed on the system console.
:::
The following example shows how to start custom applications:
- Create a file on the SD card `etc/extras.txt` with this content:
```sh
custom_app start
```
- A command can be made optional by gating it with the `set +e` and `set -e` commands:
```sh
set +e
optional_app start # Will not result in boot failure if optional_app is unknown or fails
set -e
mandatory_app start # Will abort boot if mandatory_app is unknown or fails
```