Armed-time param writes are deferred to the disarm edge (autosave), so
when the append wraps the single 128 KB sector, the full sector erase
lands right after disarm. On dual-bank H7 parts with firmware spanning
into the param bank (ark/fpv: ~780 KB of .text in bank 2), the erase
hardware-stalls every same-bank fetch for its 1-2 s duration — the
DShot outputs go silent long enough to trip the AM32 ESC signal-loss
reset (0.5 s armed). Paying the wrap at boot keeps in-service saves
append-only.
(cherry picked from commit 4b5ea8f04a)
Battery::updateDt() clamps _dt to a maximum of 2 seconds:
_dt = math::min((timestamp - _last_timestamp) / 1e6f, 2.f);
This same _dt is then used for two different purposes:
1. Battery::sumDischarged(), the coulomb count that accumulates
discharged_mah: discharged_mah_loop = current_a * dt.
2. The current average low-pass filter update
(_current_average_filter_a.update(current_a, _dt)).
The 2-second clamp makes sense for (2): a low-pass filter update
generally assumes a roughly steady sample interval and shouldn't see a
single very large dt distort its state. It does not make sense for
(1): the coulomb count is a plain physical integral (charge = current
x time), and clamping dt there just means an update that arrives less
often than every 2 seconds (e.g. some DroneCAN/UAVCAN battery devices,
as reported in #27797) has its actual elapsed time silently truncated
to 2 seconds, systematically underestimating discharged_mah for that
update - the error accumulates over the life of the battery.
Fix: track a second, unclamped dt (_dt_discharge) alongside the
existing clamped one, and use it specifically for the coulomb count in
sumDischarged(). The filter update keeps using the existing clamped
_dt unchanged.
Fixes#27797
Test plan:
- I don't have hardware with a >2-second-interval battery update
source to reproduce this end-to-end, so I verified the corrected
arithmetic with a standalone C reproduction of updateDt()/
sumDischarged(): a 5-second update interval at a constant 10A
before the fix accumulates 5.56 mAh (current x 2s, clamped) instead
of the physically correct 13.89 mAh (current x 5s); after the fix it
correctly accumulates 13.89 mAh.
- Verified a normal high-frequency update pattern (10 x 100ms updates
at 5A) is unaffected: both before and after the fix accumulate the
same, correct 1.39 mAh for that 1-second span.
Signed-off-by: yi chen <94xhn1@gmail.com>
Co-authored-by: yi chen <94xhn1@gmail.com>
(cherry picked from commit 795c69a362)
* feat(FlightTaskAuto): add RC yaw override during Auto modes
* feat(FlightTaskAuto): disengage RC yaw nudge on flight-mode switch
* docs: document MPC_AUTO_RC_YAW in MC Auto mode pages
Describe the RC yaw nudge (MPC_AUTO_RC_YAW) on the Mission page.
Add parameter rows to the Hold and Land pages where MPC_LAND_RC_HELP takes
precedence over it for yaw, and document MPC_LAND_RC_HELP there too.
* feat(FlightTaskAuto): updated param description to warn against COM_RC_OVERRIDE disabled
The long description recommends to have a switch on the RC to change to Position mode
* fix(FlightTaskAuto): unified yaw nudging with new MPC_AUTO_NUDGING parameter
* docs(FlightTaskAuto): MPC_AUTO_RC_YAW and MPC_LAND_RC_HELP parameters were replaced by the unified MPC_AUTO_NUDGING bitmask
* fix(parameters): migrate MPC_LAND_RC_HELP to MPC_AUTO_NUDGING bit 1
* docs(1.18): move stick override and add nudging changes
---------
Co-authored-by: Matthias Grob <maetugr@gmail.com>
* tecs: Prevent. NaN in pitch integrator
Prevents NaN propagation into _pitch_integ_state when seb_rate.setpoint is non-finite (as seen when exiting FW velocity Offboard). Mirrors the existing throttle integrator finite check. Fixes#25906.
* tecs: Harden the TECS pitch integrator against NaN contamination
* fix(tecs): guard pitch output against non-finite SEB rate
The integrator guard alone does not prevent the reported NaN lockup when
the non-finite value originates on the energy/speed side: the feedforward
and damping terms in _calcPitchControlOutput feed seb_rate straight into
the pitch demand, bypassing the integrator. constrain() does not reject
NaN, so the pitch setpoint latches NaN permanently and the aircraft
becomes uncontrollable.
Fall back to the (now guaranteed finite) integrator state when the
uncorrected pitch setpoint is non-finite, and drop the stray trailing
whitespace introduced by the previous commit.
Signed-off-by: Ramon Roche <mrpollo@gmail.com>
* test(tecs): regression test for NaN pitch integrator and output
Drives TECSControl::update with a non-finite true airspeed setpoint, the
same way seb_rate goes non-finite on the energy/speed side when exiting
offboard velocity mode, and asserts the pitch integrator state and the
pitch setpoint both stay finite, across a single bad frame and sustained
non-finite input. Both assertions fail against unguarded TECS.
Signed-off-by: Ramon Roche <mrpollo@gmail.com>
* test(tecs): cover the corrupted-integrator-state safety reset
Addresses review feedback on #27749: the existing tests inject a
non-finite airspeed setpoint, which the integrator-input guard rejects
before it can reach _pitch_integ_state, so the state-corruption reset
branch in _calcPitchControlUpdate was never actually exercised.
Add a FRIEND_TEST seam so the regression test can pre-corrupt
_pitch_integ_state directly, then confirm a single update() call detects
the non-finite state, resets it, and keeps the pitch setpoint finite.
Verified the test fails against the code with the reset guard removed and
passes with it in place.
---------
Signed-off-by: Ramon Roche <mrpollo@gmail.com>
Co-authored-by: Ryan Johnston <31726584+ryanjAA@users.noreply.github.com>
Co-authored-by: Ryan Johnston <rjohnston@appliedaeronautics.com>
The trajectory time-stretch is skipped when the max-error param is at or below
FLT_EPSILON, so zero is a valid 'disabled' setting. Lower the minimum of
MPC_XY_ERR_MAX and MPC_Z_ERR_MAX from 0.1 to 0 so users can actually select it,
and document it in both params.
Also fix the setMaxAllowedVerticalError() doc comment, which incorrectly
claimed zero was the default: the MPC_Z_ERR_MAX param default is 1 m.
Signed-off-by: Julian Oes <julian@oes.ch>
These helpers are no longer called from production code after the smoother
was reworked to clamp XY and Z velocity components independently. Their only
remaining references were in TrajectoryConstraintsTest.cpp, which is not
registered in CMake and therefore never compiled. Drop both the functions and
the orphaned tests.
Signed-off-by: Julian Oes <julian@oes.ch>
PositionSmoothing already has a horizontal-error gate (MPC_XY_ERR_MAX)
that slows trajectory integration when the smoother's virtual position
runs ahead of the drone in XY. The same time-stretch was applied to
all three axes, but it was only ever computed from XY error. So:
- Z lag never slowed Z down: a noisy altitude reference (e.g. mission
setpoint jittering as home altitude is refined in flight) could
walk the commanded z 5+ m above the mission target while horizontal
tracking stayed fine. The jerk-limited smoother integrates each
small step into a velocity ramp, and successive ramps superpose
into multi-meter altitude excursions.
- Z lag dragging XY: when a Z stretch eventually was added, applying
the same scalar to all axes meant a ±1 m altitude jitter could
cap forward flight speed during a straight mission leg. That's
almost never what we want.
Fix: compute time_stretch_xy and time_stretch_z independently using
their own _max_allowed_*_error thresholds and apply per-axis. Default
the new MPC_Z_ERR_MAX to 1 m (tighter than XY's 2 m because altitude
holds are usually crisper). Other PositionSmoothing users (Orbit,
GotoControl) keep zero as the vertical error cap, which is the
explicit "disable Z stretch" sentinel — so behaviour there is
unchanged.
PositionSmoothing::_generateVelocitySetpoint computed a single
constrained 3D velocity vector and then ran clampToXYNorm /
clampToZNorm in series. The XY clamp could shorten the Z component
(and vice versa), so a Z speed limit ended up capping forward speed
and a tight altitude error capped horizontal motion. Compute XY and
Z velocity components independently using their own speed limits so
they don't mutually clamp.
Companion to the per-axis time-stretch fix (commit added later in
the chain). Together they decouple the horizontal and vertical
trajectory dynamics in the smoother.
The param access mutex must be recursive because a layered param lookup
re-enters the lock on the same thread (Layer::get() -> _parent->get()).
Initialize it in param_init() - which runs once before any thread accesses
parameters - via pthread_mutexattr_settype(PTHREAD_MUTEX_RECURSIVE), replacing
the previous pthread_once lazy init. This avoids the non-portable glibc static
initializer PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP, which is unavailable on QURT
and gated behind _GNU_SOURCE elsewhere (broke the voxl2 and SITL builds).
The publisher fires callbacks via SubscriptionCallbackWorkItem::call(), which read
the subscriber's _last_generation (and called updated(), which reads it again) to
decide whether to schedule the work item. That made the subscriber's read cursor a
cross-thread field - publisher reads it while the subscriber writes it in copy() -
which TSan flagged and which we had wrapped in an atomic.
Instead, hand the publishing node's generation into call() and let the callback keep
its own _last_scheduled_generation cursor for the count gate (_required_updates).
call() runs under the node lock, so that cursor is only ever touched there and is
serialized - no atomic needed, and using the real generation (not a plain counter)
means a coalesced/missed call() does not drift the batch. The redundant updated()
generation check is dropped (call() only runs right after a publish, so it is always
true); the interval gate (_last_update / _interval_us) is kept unchanged.
With the publisher no longer reading it, _last_generation reverts to a plain unsigned
(subscriber-thread only). Behaviour is unchanged: the count and interval throttles
fire at the same rates (verified via work_queue status - gyro_fft 62.5 Hz,
flight_mode_manager 50 Hz) and TSan stays clean.
This fixes TSAN issues on destruction of AtomicTransaction happening
during the unit tests.
The static _MutexHolder instance wraps a pthread_mutex_t in a C++ class,
creating a destructor ordering problem during process exit when worker
threads may still hold the lock. Replace with a raw pthread_mutex_t
initialized via pthread_once, eliminating the C++ destructor entirely.
perf counters are written on the hot path (perf_begin / perf_end /
perf_count) and read concurrently by the `perf` command and the logger,
which ThreadSanitizer flags as data races.
Wrap the counter fields in PerfVar: px4::atomic on POSIX (where TSan runs
and native 64-bit atomics are essentially free) and a plain scalar on
flight hardware (NuttX/QURT). The call sites are identical in both
configurations.
The embedded path matters because a 64-bit atomic on Cortex-M has no
native instruction and lowers to a locked, interrupt-disabling
__atomic_* sequence. Measured on fmu-v6x (microbench microbench_perf):
perf_count 73.7 ns -> 171.8 ns
perf_begin+end 982.9 ns -> 1831.7 ns
~2x on instrumentation that wraps many module Run() loops. These are
single-writer diagnostic counters; the only effect of the plain path is
that a concurrent reader may observe an off-by-one torn read of a 64-bit
field, which is benign and self-correcting (the counter list itself is,
and remains, mutex-protected). The conditional version restores embedded
performance (76.6 ns / 1015 ns) while keeping SITL TSan-clean.
Single TSan/ASan-clean implementation that works on both POSIX and NuttX:
- size()/byteSize() take the AtomicTransaction lock so they don't race
with store() updating _next_slot/_n_slots.
- _grow() snapshots _n_slots under the lock for sizing the malloc, so
another thread's growth between the malloc and the memcpy can't make
the memcpy exceed the allocation. Both platforms use the unlock-
around-malloc + CAS-retry pattern: NuttX requires it (malloc can't
be called with IRQs disabled), and on POSIX it's safe because the
AtomicTransaction mutex still serializes everything else and the
brief unlock window doesn't touch shared state.
- ~DynamicSparseLayer() takes the lock, zeros _next_slot / _n_slots,
stores nullptr into _slots, then frees the buffer. This fixes the
heap-use-after-free TSan caught at process exit on POSIX, where the
static DynamicSparseLayer instances in parameters.cpp are torn down
by cxa_atexit while other threads (commander etc.) are still calling
param_get(). Any reader that acquires the lock post-destruction sees
_next_slot == 0 and falls through to the parent layer; the parent
chain in parameters.cpp is in reverse-declaration order, so the
parent is still alive when the child is destroyed.
Add DynamicSparseLayerTest with concurrent stress tests that reproduce
the races. ConcurrentMultipleWriters pre-allocates to TOTAL to avoid
the known ABA limitation in the CAS retry loop with concurrent _grow().
Drive-by: drop the unused void *p member from param_value_u — nothing
in the tree reads or writes it, and on 64-bit POSIX it was silently
doubling the size of every parameter slot.
Originally found while running the new SIH-based CI tests.
- Separate stopped motor mask into separate state variables (one for
stopping due to flight phase, one for stopping due to NaN thrust in
each direction) and combine them on demand in getStoppedMotors. This
removes the need of hard to follow &= and |= operation involving
shared state.
- use the new nanToZero to clean _thrust_sp for CA internal use
- Introduce lateral/longitudinal/vertical motor masks in base
ActuatorEffecctiveness (and remove previous from individual
Effectiveness classes)
- Populate the bitmasks from all relevant effectivenesses by calling
the new _rotors.setMotorDirectionBitmasks()
- isAlignedWithCoordinateAxis checks axis alignment with given
angle tolerance
- motor stopping is the same as before, using the result of
getStoppedMotors
* feat(manual_control): trigger RC override on stick velocity
COM_RC_STICK_OV is now a velocity threshold (1/s) instead of a deflection percentage.
Default 3.0, range [1.0, 10.0]. A stick held statically cannot trigger override.
* docs(manual_control): update COM_RC_STICK_OV description for velocity-based override
* feat(manual_control): gate RC override with sign-consistency check
* fix(ManualControl): lower threshold and filter constant for RC override, add tests for MovingDiff
* refactor(commander): merge RC override params into COM_RC_OVR_SPEED
Replace the COM_RC_OVERRIDE bitmask + COM_RC_STICK_OV threshold with a
single float COM_RC_OVR_SPEED (stick override velocity, 0 = disabled).
Override now applies uniformly in auto and offboard modes.
- ManualControl: rename param, treat 0 as disabled (FLT_EPSILON guard)
- Commander: drop the per-mode bitmask gate and the RcOverrideBits enum
- param_translation: migrate COM_RC_OVERRIDE on import (enabled -> 1.0,
disabled -> 0.0) and drop the unit-incompatible COM_RC_STICK_OV value
- docs: collapse the two params into one across the mode pages
* fix(manual_override): Move configuration to manual_control module
with MAN_OVERRIDE_SPD parameter and a negative value disabling the feature. All other logic stays in Commander.
* docs(releases): add release note for RC override rework (MAN_OVERRIDE_SPD)
---------
Co-authored-by: Matthias Grob <maetugr@gmail.com>
Estimates the offset between a remote node clock and FC HRT by tracking
the minimum of (local - remote), then maps remote timestamps into HRT;
residual bias is the minimum observed transport latency. Unit-tested for
convergence, jitter hold, and clock-discontinuity reset.
Disabled if ICE_IDLE_RPM is 0.
The idle state is entered when the commanded throttle is close to zero
or the measured RPM drops below the idle threshold.
The idle state is exited if the commanded thrust is increased to above
the last needed throttle to keep idle.
Signed-off-by: Silvan <silvan@auterion.com>
Co-authored-by: Silvan <silvan@auterion.com>
* platforms/common/uORB/uORB.h: Add definition for orb_sub_t and handle check functions
Signed-off-by: Jukka Laitinen <jukkax@ssrc.tii.ae>
* uORB: Change subscriber id:s from int to orb_sub_t
Signed-off-by: Jukka Laitinen <jukkax@ssrc.tii.ae>
* uxrce_dds_client: Change polling of transport device from px4_poll to poll
Use posix poll directly, there is no need to use px4_poll unless uORBs are
being polled.
The one used here is a normal filesystem/device poll, so we can use normal "poll",
this is the common pattern in the codebase.
Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
* Fix linking for protected build
This fixes errors for memalign not linking on some configurations.
Memalign exists in nuttx kernel-side mm library and it may fail in configurations
where kernel and userspace are separated. This has no effect on other than
"CONFIG_BUILD_PROTECTED" or "CONFIG_BUILD_KERNEL" NuttX builds.
Signed-off-by: Jukka Laitinen <jukkax@ssrc.tii.ae>
---------
Signed-off-by: Jukka Laitinen <jukkax@ssrc.tii.ae>
Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
Co-authored-by: Jukka Laitinen <jukkax@ssrc.tii.ae>
* fix(geo): correct arc endpoint projection in get_distance_to_arc
The out-of-sector branch placed the arc start/end points with two errors:
- The cosine scaling was inverted and evaluated in degrees: cos() multiplied
the latitude term and was missing from the longitude term. One degree of
longitude is 111111 m * cos(latitude), so the east displacement must be
divided by cos(lat) in radians, while latitude needs no cosine.
- The displacement was added to the vehicle position instead of the arc
center, so the computed endpoints, and the returned crosstrack
distance/bearing, were meaningless.
Anchor the endpoints to the center and apply the projection correctly, and
add a unit test for the out-of-sector case.
Fixes#27557
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
* fix(geo): correct arc sector membership test
The in-sector check in get_distance_to_arc() compared the vehicle->center
bearing against a sector defined by center->endpoint bearings, so it was
off by pi: a point lying exactly on the arc was classified out-of-sector
and reported kilometers of crosstrack error instead of ~zero. The
negative-sweep branch also computed the sector bounds with the wrong sign
(arc_start_bearing - arc_sweep), reflecting the wedge to the wrong side.
Replace the bound bookkeeping with a single sweep-direction-aware test on
the center->vehicle bearing, which handles either sweep sign and any zero
crossing. Add in-sector and negative-sweep unit tests.
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
* test(geo): avoid underscores in get_distance_to_arc test names
Rename the new tests to underscore-free lowerCamelCase (matching the
existing reprojectProject / projectReproject tests) to satisfy clang-tidy
google-readability-avoid-underscore-in-googletest-name.
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
* fix(geo): suppress false-positive clang-tidy swapped-argument warning
readability-suspicious-call-argument flags the center->vehicle bearing
call because the argument names cross-match the parameter names, but the
reversed order is intentional (it is the reciprocal of bearing_now). With
WarningsAsErrors this failed CI; annotate the line with NOLINTNEXTLINE.
---------
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
Flashing PX4 over another firmware (e.g. ArduPilot on an ARK FPV) or
first-booting a board with blank parameter storage played the error tune
on every boot: the param layer treated a blank store as corruption, and
the rcS recovery persisted with a file cp that is a no-op on
FLASH_BASED_PARAMS boards, so the store never became valid.
- param_import()/param_load() return 1 ("not yet stored") for a blank
source - empty file, zeroed FRAM, or erased flash - on both the file
and flash backends; a store that holds data but no valid entry (torn
write, bit-rot, foreign data) is still reported as corrupt (-EILSEQ).
The file backend detects a zero-length file via fstat (NuttX FAT
cannot read() a 0-byte file: no cluster chain returns an error, not
EOF) and otherwise inspects the leading BSON document length; the
flash backend scans the whole store
- new 'param load-or-init <backup>' command: loads from the default
storage; a blank store is seeded from the SD backup (or firmware
defaults) and persisted so the next boot loads normally. A corrupt
store, a backup that exists but cannot be opened or imported, or a
result that cannot be persisted returns failure. The three-way
loaded/blank/corrupt logic lives in C because nsh $? is a binary
success flag. A failed backup seed does not reset to defaults, which
preserves parameters loaded earlier in boot (e.g. factory calibration
from /fs/mtd_caldata)
- rcS uses 'param load-or-init' instead of 'param import', and the
corrupt-store recovery persists via 'param save' (works on
flash-backed boards) only when the backup actually imported, so a
corrupt backup keeps alerting the operator on the next boot
- commander ParamLoadDefault treats blank storage (1) as success and
warns the GCS that parameters were reset to defaults, instead of
reporting "Error loading settings"
- parameter_flashfs_init() in flashfs.c no longer reports a successful
erase byte count as a failure (parity with flashfs32.c)
Tested with new blankImport and corruptImport cases in 'tests
parameters' (empty/zeroed/erased sources import as "not yet stored",
garbage fails to import); the CustomDefaults test now restores the
firmware default so the suite is repeatable within one boot.
The STM32H7 flash-erase DCACHE invalidate fix this depends on
(PX4/NuttX#381) is already in main's NuttX submodule.
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
* feat(baro): refactor barometer drivers to use PX4Barometer class
* fix(baro): incoperated feedback
* feat(baro): initialize PX4Barometer with device ID in barometer drivers
* fix(baro): set default temperature to 15°C in PX4Barometer constructor
* fix(baro): clarify default temperature comment in PX4Barometer constructor
---------
Co-authored-by: Claudio Chies <chiesc@chies.com>
Compared to the previous state this fixes two issues:
- Start ramping at user-defined speed weight rather than 1 (leading to a
discontinuity, and possibly too low speed weight)
- Prefer the higher of the two speed weights given by fast descend and
underspeed (previously underspeed took priority, also leading to a
discontinuity)
Add LatLonAlt::Wgs84::gravity(), the Somigliana normal-gravity formula
returning surface gravity as a function of latitude (~9.780 m/s^2 at the
equator to ~9.832 m/s^2 at the poles), plus a unit test against known
reference values.
Replace static fops member with platform-defined fops_ref() accessor to avoid
bugprone-dynamic-static-initializers warning.
Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
* feat(fw_perf_model): warn in max bank infeasible due to empty airspeed range
* style(fw_perf_model): refer explicitly to max airspeed param
and only implicitly to max bank, so users will be inclined to adjust the
former.
* docs(fw-tuning): add section on roll compensation and effect on airspeed limits
* docs(fw-tuning): fix LaTeX
- wrap text in \text{} so it does not render as if it were variable
names
- fix incorrect double escaping which made \sqrt{} and \frac{} not
render
- replace \over with \frac - the latter is nicer and handles more edge
cases
* docs(fw-tuning): fix typo
In the above equation (supposed to be rearranged) there is only C_L, no C_D.
* docs(fw-tuning): correct mistake
only stall and min airspeed are load factor (due to bank) compensated in
the performance model, not trim.
* src/drivers/cdcacm_autostart: Include posix.h for px4_close
Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
* platforms/nuttx/CMakeLists.txt: Fix linking of nuttx libaries for memalign
This fixes memalign not found in linking step for some boards
Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
* Add "flock" to macos.sh setup script
"flock" is not standard on macOS, and a dependency was missing from the
macOS setup path.
Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
* Fix clang-tidy errors in Bitset.hpp and in src/lib/matrix
Fix the "bugprone-dynamic-static-initializers" linter errors.
Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
* systemlib/hardfault_log: Fix clang-diagnostics error
Fix for
"[error] clang-diagnostic-error [error]
use of undeclared identifier XCPTCONTEXT_REGS".
XCPTCONTEXT_REGS is defined in nuttx irq.h, so include that.
Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
* uORB: Fix clang-tidy error "bugprone-dynamic-static-initializers"
Fix the clang-tidy error appearing on uORBManager _Instance variable by
adding a getter for the reference to the _Instance and using that instead.
Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
* CI: Add default ubuntu mirrors as fallback
In case of specified aws mirror doesn't have the package idicated by the
metadata, a the default ubuntu mirror as a backup.
Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
---------
Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
math::expo_deadzone generates ~240bytes of code for 32-bit arm
platform, and it gets currently inlined several times.
Localizing the function in Sticks.cpp saves ~2KB of flash, measured
on px4_fmu-v5_default target.
Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
Implements a new GUIDED_COURSE navigator mode that maintains a constant
ground-track bearing, altitude, and airspeed without manual stick input.
The mode is activated via MAVLink and accepts real-time in-flight updates:
- MAV_CMD_GUIDED_CHANGE_HEADING (HEADING_TYPE_COURSE_OVER_GROUND): set course
- MAV_CMD_DO_CHANGE_ALTITUDE: adjust target altitude
- MAV_CMD_DO_CHANGE_SPEED: adjust target airspeed
On activation the vehicle captures its current velocity vector as the
initial course bearing. A valid horizontal velocity estimate (GPS or
dead-reckoning) is required; course commands are rejected if unavailable.
* mavlink: reassemble GPS_RTCM_DATA before GPS injection
* Apply minor comment requested changes
* Simplification: remove _completed_sequence asymetric protection
* Handle RTCM payload length which is an exact multiple of 180
* update docs
* lib gnss: new GpsRtcmMessageFragmenter to send RTCM via GPS_RTCM_DATA.hpp
* fix clang
* Remove RTCM fragmenter
* update docs
* Compatibility fallback for older QGroundControl builds that omit the final zero-length fragment
* mavlink receiver, remove while loop to avoid dead lock
* docs(update): Subedit
Co-authored-by: Hamish Willee <hamishwillee@gmail.com>
* docs(docs): format
---------
Co-authored-by: jonas <jonas.perolini@rigi.tech>
Co-authored-by: Hamish Willee <hamishwillee@gmail.com>
- Expose overrideCollectiveTilt in ActuatorEffectiveness, empty base, only overridden for Tiltrotor
- Allow giving collective tilt that is used in updateSetpoint in place
of command from tiltrotor_extra_controls
- Needs to be called with do_override = false to clear override
- add comment explaining technical debt
A successful I2C::init() attaches to the bus (per-platform: NuttX
i2c_master_s* via px4_i2cbus_initialize, POSIX /dev/i2c-N fd via
::open, QuRT bus fd via _config_i2c_bus). Only the destructor releases
it. The init() implementations on all three platforms unconditionally
re-attached on every call, so any driver that called init() more than
once on the same instance leaked:
- NuttX: kmm_malloc() of a fresh i2c_master_s inst, plus an unbalanced
increment of the per-port refcount in stm32_i2cbus_initialize() (and
the equivalent across other arch ports). The previous inst pointer
was overwritten and the matching uninitialize() never ran, so the
bus refcount could not reach zero on destruct.
- POSIX/QuRT: file descriptor leak (re-open without close).
The pattern that triggers this is "init() retried on failure," used in
keep_running mode and in drivers like INA228 whose RunImpl re-enters
init() whenever a later step (e.g. a register write) failed. Drivers
that init() exactly once from instantiate() were unaffected.
Mirror what SPI::init() (nuttx/SPI.cpp) already does for its bus-bind
step and short-circuit on second-and-later calls. Re-running probe()
and CDev::init() on an already-attached device was also avoided here
because the existing cleanup path on probe failure would tear down the
preserved _dev that earlier callers still depended on.
Signed-off-by: Jacob Dahl <dahl.jakejacob@gmail.com>
* feat(gpsRedundancyCheck): add GPS redundancy failsafe with divergence check
- Monitors GPS count and triggers configurable failsafe (COM_GPS_LOSS_ACT) when count drops below SYS_HAS_NUM_GPS
- Tracks online (present+fresh) and fixed (3D fix) receivers separately; emits "receiver offline" vs "receiver lost fix"
- Detects position divergence between two receivers against combined RMS eph uncertainty plus lever-arm separation
- Pre-arm warns immediately; in-flight requires 2s sustained divergence to suppress multipath false alarms
- Adds GpsRedundancyCheckTest functional test suite
New parameters: SYS_HAS_NUM_GPS, COM_GPS_LOSS_ACT
* feat(sensor_gps_sim): publish second GPS instance using SENS_GPS1 lever arm params
When SENS_GPS1_OFFX or SENS_GPS1_OFFY is non-zero, publish a second sensor_gps instance offset by those values from the vehicle position.
fix(sensor_gps_sim): give second instance distinct device_id
Both simulated GPS instances previously shared the same device_id (address 0x00). This prevented testing the device-ID matching path in SITL since both slots would match the same receiver.
* refactor(gpsRedundancyCheck): address code review feedback
* refactor(gpsRedundancyCheck): address code review feedback
* docs: add GNSS check failsafe documentation
Update safety.md and releases/main.md to document the new GNSS check
failsafe (SYS_HAS_NUM_GNSS, COM_GPS_LOSS_ACT) introduced in PX4.
* docs(update): Subedit to taste
* refactor(gps): move GNSS redundancy detection into sensors module
Add GnssRedundancyStatus topic and GnssRedundancyMonitor in
vehicle_gps_position. Commander's gpsRedundancyCheck becomes a thin
consumer of the new topic. Detection lives with blending/fallback in
one module.
Also rename COM_GPS_LOSS_ACT -> COM_GNSS_LSS_ACT.
* docs(safety): clarify GNSS failsafe wording and rename COM_GNSS_LSS_ACT
* refactor(failsafe): consistent default case as fallback for existing option
* Rename COM_GNSS_LSS_ACT -> COM_GNSSLOSS_ACT
for readability
* fix(gnssRedundancyCheck): move logic back into the commander checks and various improvement suggestions
- Rename to GNSS instead of gps
- Use hysteresis
- Small logic refactorings
- Adapt unit tests to different interface
- User reporting on which GPS is offline or doesn't have a fix
* docs(gnssRedundancyCheck): simplify explanations
* refactor(gnssRedundancyCheck): update year numbers in copyright
---------
Co-authored-by: Hamish Willee <hamishwillee@gmail.com>
Co-authored-by: Matthias Grob <maetugr@gmail.com>