diff --git a/ROMFS/px4fmu_common/init.d-posix/airframes/1010_gazebo-classic_iris_opt_flow b/ROMFS/px4fmu_common/init.d-posix/airframes/1010_gazebo-classic_iris_opt_flow index d334bdb4308..98d07ea9d36 100644 --- a/ROMFS/px4fmu_common/init.d-posix/airframes/1010_gazebo-classic_iris_opt_flow +++ b/ROMFS/px4fmu_common/init.d-posix/airframes/1010_gazebo-classic_iris_opt_flow @@ -34,7 +34,7 @@ param set-default EKF2_GPS_CTRL 0 param set-default EKF2_HGT_REF 0 param set-default EKF2_EVP_NOISE 0.05 param set-default EKF2_EVA_NOISE 0.05 -param set-default EKF2_OF_CTRL 1 +param set-default EKF2_OF0_CTRL 1 # LPE: Flow-only mode param set-default LPE_FUSION 242 @@ -45,7 +45,7 @@ param set-default LPE_FAKE_ORIGIN 1 param set-default MPC_ALT_MODE 2 -param set-default SENS_FLOW_ROT 6 -param set-default SENS_FLOW_MINHGT 0.7 -param set-default SENS_FLOW_MAXHGT 15 -param set-default SENS_FLOW_MAXR 2.5 +param set-default SENS_FLOW0_ROT 6 +param set-default SENS_FLOW0_HMIN 0.7 +param set-default SENS_FLOW0_HMAX 15 +param set-default SENS_FLOW0_MAXR 2.5 diff --git a/ROMFS/px4fmu_common/init.d-posix/airframes/1017_gazebo-classic_iris_opt_flow_mockup b/ROMFS/px4fmu_common/init.d-posix/airframes/1017_gazebo-classic_iris_opt_flow_mockup index 23928c0a9b2..bca7a1555e6 100644 --- a/ROMFS/px4fmu_common/init.d-posix/airframes/1017_gazebo-classic_iris_opt_flow_mockup +++ b/ROMFS/px4fmu_common/init.d-posix/airframes/1017_gazebo-classic_iris_opt_flow_mockup @@ -31,7 +31,7 @@ param set-default PWM_MAIN_FUNC4 104 # EKF2 param set-default EKF2_GPS_CTRL 0 -param set-default EKF2_OF_CTRL 1 +param set-default EKF2_OF0_CTRL 1 # LPE: Flow-only mode param set-default LPE_FUSION 242 diff --git a/ROMFS/px4fmu_common/init.d-posix/airframes/4006_gz_px4vision b/ROMFS/px4fmu_common/init.d-posix/airframes/4006_gz_px4vision index 20a9278463b..a80974cc2a7 100644 --- a/ROMFS/px4fmu_common/init.d-posix/airframes/4006_gz_px4vision +++ b/ROMFS/px4fmu_common/init.d-posix/airframes/4006_gz_px4vision @@ -23,10 +23,10 @@ param set-default EKF2_IMU_POS_X 0.02 param set-default SENS_GNSS0_OFFX 0.055 param set-default SENS_GNSS0_OFFZ -0.15 param set-default EKF2_MIN_RNG 0.03 -param set-default EKF2_OF_CTRL 1 -param set-default EKF2_OF_POS_X 0.055 -param set-default EKF2_OF_POS_Y 0.02 -param set-default EKF2_OF_POS_Z 0.065 +param set-default EKF2_OF0_CTRL 1 +param set-default SENS_FLOW0_POS_X 0.055 +param set-default SENS_FLOW0_POS_Y 0.02 +param set-default SENS_FLOW0_POS_Z 0.065 param set-default GNSS_REQ_HDRIFT 0.3 param set-default GNSS_REQ_SACC 1 param set-default GNSS_REQ_VDRIFT 0.3 @@ -84,8 +84,8 @@ param set-default SDLOG_PROFILE 131 # Sensors Parameters # param set-default SENS_CM8JL65_CFG 202 Not found -param set-default SENS_FLOW_MAXHGT 25 -param set-default SENS_FLOW_MINHGT 0.5 +param set-default SENS_FLOW0_HMAX 25 +param set-default SENS_FLOW0_HMIN 0.5 param set-default IMU_GYRO_CUTOFF 100 # param set-default SENS_TFLOW_CFG 103 Not found diff --git a/ROMFS/px4fmu_common/init.d/airframes/4016_holybro_px4vision b/ROMFS/px4fmu_common/init.d/airframes/4016_holybro_px4vision index bc1bb03b8d2..e3c707b2a71 100644 --- a/ROMFS/px4fmu_common/init.d/airframes/4016_holybro_px4vision +++ b/ROMFS/px4fmu_common/init.d/airframes/4016_holybro_px4vision @@ -22,10 +22,10 @@ param set-default EKF2_IMU_POS_X 0.02 param set-default SENS_GNSS0_OFFX 0.055 param set-default SENS_GNSS0_OFFZ -0.15 param set-default EKF2_MIN_RNG 0.03 -param set-default EKF2_OF_CTRL 1 -param set-default EKF2_OF_POS_X 0.055 -param set-default EKF2_OF_POS_Y 0.02 -param set-default EKF2_OF_POS_Z 0.065 +param set-default EKF2_OF0_CTRL 1 +param set-default SENS_FLOW0_POS_X 0.055 +param set-default SENS_FLOW0_POS_Y 0.02 +param set-default SENS_FLOW0_POS_Z 0.065 param set-default GNSS_REQ_HDRIFT 0.3 param set-default GNSS_REQ_SACC 1 param set-default GNSS_REQ_VDRIFT 0.3 @@ -79,8 +79,8 @@ param set-default RTL_RETURN_ALT 5 # Sensors Parameters param set-default SENS_CM8JL65_CFG 104 -param set-default SENS_FLOW_MAXHGT 25 -param set-default SENS_FLOW_MINHGT 0.5 +param set-default SENS_FLOW0_HMAX 25 +param set-default SENS_FLOW0_HMIN 0.5 param set-default IMU_GYRO_CUTOFF 100 param set-default SENS_EN_PMW3901 1 diff --git a/ROMFS/px4fmu_common/init.d/airframes/4020_holybro_px4vision_v1_5 b/ROMFS/px4fmu_common/init.d/airframes/4020_holybro_px4vision_v1_5 index 58440271e7b..f80774765b3 100644 --- a/ROMFS/px4fmu_common/init.d/airframes/4020_holybro_px4vision_v1_5 +++ b/ROMFS/px4fmu_common/init.d/airframes/4020_holybro_px4vision_v1_5 @@ -22,10 +22,10 @@ param set-default EKF2_IMU_POS_X 0.02 param set-default SENS_GNSS0_OFFX 0.055 param set-default SENS_GNSS0_OFFZ -0.15 param set-default EKF2_MIN_RNG 0.03 -param set-default EKF2_OF_CTRL 1 -param set-default EKF2_OF_POS_X 0.055 -param set-default EKF2_OF_POS_Y 0.02 -param set-default EKF2_OF_POS_Z 0.065 +param set-default EKF2_OF0_CTRL 1 +param set-default SENS_FLOW0_POS_X 0.055 +param set-default SENS_FLOW0_POS_Y 0.02 +param set-default SENS_FLOW0_POS_Z 0.065 param set-default GNSS_REQ_HDRIFT 0.3 param set-default GNSS_REQ_SACC 1 param set-default GNSS_REQ_VDRIFT 0.3 @@ -80,8 +80,8 @@ param set-default RTL_RETURN_ALT 5 # Sensors Parameters param set-default SENS_CM8JL65_CFG 202 -param set-default SENS_FLOW_MAXHGT 25 -param set-default SENS_FLOW_MINHGT 0.5 +param set-default SENS_FLOW0_HMAX 25 +param set-default SENS_FLOW0_HMIN 0.5 param set-default IMU_GYRO_CUTOFF 100 param set-default SENS_TFLOW_CFG 103 diff --git a/ROMFS/px4fmu_common/init.d/airframes/4061_atl_mantis_edu b/ROMFS/px4fmu_common/init.d/airframes/4061_atl_mantis_edu index f4b73b833bc..a8cdeff3830 100644 --- a/ROMFS/px4fmu_common/init.d/airframes/4061_atl_mantis_edu +++ b/ROMFS/px4fmu_common/init.d/airframes/4061_atl_mantis_edu @@ -58,13 +58,13 @@ param set-default EKF2_MAG_NOISE 0.1 param set-default EKF2_MIN_RNG 0.15 -param set-default EKF2_OF_DELAY 38 -param set-default EKF2_OF_GATE 2 -param set-default EKF2_OF_POS_X -0.035 -param set-default EKF2_OF_POS_Z 0.033 +param set-default SENS_FLOW0_DELAY 38 +param set-default EKF2_OF0_GATE 2 +param set-default SENS_FLOW0_POS_X -0.035 +param set-default SENS_FLOW0_POS_Z 0.033 param set-default EKF2_OF_MIN_RNG 0.01 param set-default EKF2_OF_A_HMAX 7 -param set-default EKF2_OF_QMIN 30 +param set-default EKF2_OF0_QMIN 30 param set-default EKF2_PCOEF_XN -0.3 param set-default EKF2_PCOEF_XP -0.4 @@ -147,9 +147,9 @@ param set-default RC_MAP_RETURN_SW 7 param set-default RC1_TRIM 1000 # optical flow -param set-default SENS_FLOW_MAXR 7.4 -param set-default SENS_FLOW_MINHGT 0.15 -param set-default SENS_FLOW_MAXHGT 5 +param set-default SENS_FLOW0_MAXR 7.4 +param set-default SENS_FLOW0_HMIN 0.15 +param set-default SENS_FLOW0_HMAX 5 # ignore the SD card errors and use normal startup sound set STARTUP_TUNE "1" diff --git a/ROMFS/px4fmu_common/init.d/airframes/4073_ifo-s b/ROMFS/px4fmu_common/init.d/airframes/4073_ifo-s index ecc7ed50789..41b4c6853a6 100644 --- a/ROMFS/px4fmu_common/init.d/airframes/4073_ifo-s +++ b/ROMFS/px4fmu_common/init.d/airframes/4073_ifo-s @@ -31,7 +31,7 @@ param set-default IMU_GYRO_CUTOFF 100 # Sensors param set-default SENS_BOARD_ROT 10 # Yaw 180 -param set-default SENS_FLOW_ROT 4 +param set-default SENS_FLOW0_ROT 4 # TFMini on TELEM3 param set-default SENS_TFMINI_CFG 103 @@ -43,8 +43,8 @@ param set-default EKF2_GND_EFF_DZ 6 param set-default EKF2_MIN_RNG 0.3 # Flow -param set-default EKF2_OF_CTRL 1 -param set-default EKF2_OF_QMIN 70 +param set-default EKF2_OF0_CTRL 1 +param set-default EKF2_OF0_QMIN 70 # Position control param set-default MPC_Z_P 1.1 @@ -86,9 +86,9 @@ param set-default MAV_1_MODE 0 param set-default SER_TEL2_BAUD 57600 # EKF OF POSITION -param set-default EKF2_OF_POS_X 0.06 -param set-default EKF2_OF_POS_Y 0.03 -param set-default EKF2_OF_POS_Z -0.07 +param set-default SENS_FLOW0_POS_X 0.06 +param set-default SENS_FLOW0_POS_Y 0.03 +param set-default SENS_FLOW0_POS_Z -0.07 # Failsafe param set-default COM_LOW_BAT_ACT 3 diff --git a/ROMFS/px4fmu_common/init.d/airframes/4601_droneblocks_dexi_5 b/ROMFS/px4fmu_common/init.d/airframes/4601_droneblocks_dexi_5 index 05452a1af1f..079d1810765 100644 --- a/ROMFS/px4fmu_common/init.d/airframes/4601_droneblocks_dexi_5 +++ b/ROMFS/px4fmu_common/init.d/airframes/4601_droneblocks_dexi_5 @@ -47,9 +47,9 @@ param set-default PWM_MAIN_TIM0 -3 param set-default DSHOT_TEL_CFG 104 param set-default EKF2_MIN_RNG 0.01 -param set-default EKF2_OF_POS_X 0.043 -param set-default EKF2_OF_POS_Y 0.011 -param set-default EKF2_OF_QMIN_GND 1 +param set-default SENS_FLOW0_POS_X 0.043 +param set-default SENS_FLOW0_POS_Y 0.011 +param set-default EKF2_OF0_QMINGND 1 param set-default EKF2_RNG_POS_X 0.043 param set-default EKF2_RNG_POS_Y 0 param set-default EKF2_RNG_A_HMAX 25 @@ -78,7 +78,7 @@ param set-default RC_CRSF_TEL_EN 1 param set-default RTL_RETURN_ALT 15 -param set-default SENS_FLOW_MINHGT 0 +param set-default SENS_FLOW0_HMIN 0 param set-default SER_TEL2_BAUD 3000000 diff --git a/ROMFS/px4fmu_common/init.d/airframes/4901_crazyflie21 b/ROMFS/px4fmu_common/init.d/airframes/4901_crazyflie21 index d3dc7578c07..9e9e7b842f5 100644 --- a/ROMFS/px4fmu_common/init.d/airframes/4901_crazyflie21 +++ b/ROMFS/px4fmu_common/init.d/airframes/4901_crazyflie21 @@ -20,7 +20,7 @@ . ${R}etc/init.d/rc.mc_defaults param set-default SYS_HAS_MAG 0 -param set-default EKF2_OF_CTRL 1 +param set-default EKF2_OF0_CTRL 1 param set-default EKF2_GPS_CTRL 0 param set-default EKF2_MAG_TYPE 5 diff --git a/ROMFS/px4fmu_common/init.d/airframes/6002_draco_r b/ROMFS/px4fmu_common/init.d/airframes/6002_draco_r index 99b2be3e697..1dde92e8abe 100644 --- a/ROMFS/px4fmu_common/init.d/airframes/6002_draco_r +++ b/ROMFS/px4fmu_common/init.d/airframes/6002_draco_r @@ -67,13 +67,13 @@ param set-default MIS_TAKEOFF_ALT 1.1 ##################################### # Enable optical flow and GPS param set-default EKF2_MAG_TYPE 1 -param set-default EKF2_OF_QMIN 80 +param set-default EKF2_OF0_QMIN 80 # default horizontal stablization sensors param set-default SENS_EN_PMW3901 1 param set-default SENS_EN_PX4FLOW 1 param set-default SENS_EN_LL40LS 2 -param set-default SENS_FLOW_ROT 2 +param set-default SENS_FLOW0_ROT 2 param set-default COM_DISARM_LAND 3 diff --git a/boards/ark/can-flow-mr/init/rc.board_sensors b/boards/ark/can-flow-mr/init/rc.board_sensors index d08b1f9cf22..66672ed6db8 100644 --- a/boards/ark/can-flow-mr/init/rc.board_sensors +++ b/boards/ark/can-flow-mr/init/rc.board_sensors @@ -4,7 +4,7 @@ #------------------------------------------------------------------------------ param set-default IMU_GYRO_RATEMAX 1000 -param set-default SENS_FLOW_RATE 150 +param set-default SENS_FLOW0_RATE 150 param set-default SENS_IMU_CLPNOTI 0 # Internal SPI diff --git a/boards/ark/can-flow/init/rc.board_sensors b/boards/ark/can-flow/init/rc.board_sensors index 13502ed7ce0..dcbb87c6913 100644 --- a/boards/ark/can-flow/init/rc.board_sensors +++ b/boards/ark/can-flow/init/rc.board_sensors @@ -4,7 +4,7 @@ #------------------------------------------------------------------------------ param set-default IMU_GYRO_RATEMAX 1000 -param set-default SENS_FLOW_RATE 150 +param set-default SENS_FLOW0_RATE 150 param set-default SENS_IMU_CLPNOTI 0 # Internal SPI diff --git a/boards/ark/pi6x/init/rc.board_defaults b/boards/ark/pi6x/init/rc.board_defaults index 7b264629237..ecc97dd1504 100644 --- a/boards/ark/pi6x/init/rc.board_defaults +++ b/boards/ark/pi6x/init/rc.board_defaults @@ -42,10 +42,10 @@ then fi param set-default EKF2_MULTI_IMU 0 -param set-default EKF2_OF_CTRL 1 -param set-default EKF2_OF_N_MIN 0.05 +param set-default EKF2_OF0_CTRL 1 +param set-default EKF2_OF0_N_MIN 0.05 param set-default EKF2_RNG_A_HMAX 25 param set-default EKF2_RNG_QLTY_T 0.1 -param set-default SENS_FLOW_RATE 150 +param set-default SENS_FLOW0_RATE 150 param set-default SENS_IMU_MODE 1 diff --git a/boards/nxp/mr-tropic/nuttx-config/scripts/itcm_functions_includes.ld b/boards/nxp/mr-tropic/nuttx-config/scripts/itcm_functions_includes.ld index 148327d06bc..79de3d7fc6b 100644 --- a/boards/nxp/mr-tropic/nuttx-config/scripts/itcm_functions_includes.ld +++ b/boards/nxp/mr-tropic/nuttx-config/scripts/itcm_functions_includes.ld @@ -171,7 +171,8 @@ *(.text._ZN28MavlinkStreamGpsGlobalOrigin4sendEv) *(.text._ZN11ControlMath15bodyzToAttitudeEN6matrix7Vector3IfEEfR27vehicle_attitude_setpoint_s) *(.text._ZN4EKF217UpdateRangeSampleER17ekf2_timestamps_s) -*(.text._ZN3Ekf24controlOpticalFlowFusionERKN9estimator9imuSampleE) +*(.text._ZN17OpticalFlowAiding6updateER3EkfRKN9estimator9imuSampleE) +*(.text._ZN17OpticalFlowSource6updateER3EkfRKN9estimator9imuSampleEb) *(.text._ZN19MavlinkStreamRawRpm4sendEv) *(.text._ZN13MavlinkStream10const_rateEv) *(.text._ZN4EKF215PublishOdometryERKyRKN9estimator9imuSampleERKN6matrix7Vector3IfEE) @@ -338,7 +339,6 @@ *(.text._ZN14FlightTaskAutoD1Ev) *(.text._ZN4uORB10DeviceNode22get_initial_generationEv) *(.text._ZN3Ekf23controlGnssHeightFusionERKN9estimator10gnssSampleE) -*(.text._ZN3Ekf40updateOnGroundMotionForOpticalFlowChecksEv) *(.text._ZN6matrix6MatrixIfLj3ELj1EEC1Ev) *(.text._ZN14ZeroGyroUpdate6updateER3EkfRKN9estimator9imuSampleE) *(.text._ZN30MavlinkStreamOpenDroneIdSystem4sendEv) @@ -401,7 +401,7 @@ *(.text.nxsem_set_protocol) *(.text.write) *(.text._ZN22MavlinkStreamSysStatus4sendEv) -*(.text._ZN4EKF216UpdateFlowSampleER17ekf2_timestamps_s) +*(.text._ZN17OpticalFlowAiding13updateSamplesER3Ekf) *(.text._ZN4cdevL10cdev_ioctlEP4fileim) *(.text._ZN7Mavlink10send_bytesEPKhj) *(.text._ZNK8Failsafe17checkModeFallbackERK16failsafe_flags_sh) diff --git a/boards/nxp/tropic-community/nuttx-config/scripts/itcm_functions_includes.ld b/boards/nxp/tropic-community/nuttx-config/scripts/itcm_functions_includes.ld index e39df739da0..5e0cf3fd048 100644 --- a/boards/nxp/tropic-community/nuttx-config/scripts/itcm_functions_includes.ld +++ b/boards/nxp/tropic-community/nuttx-config/scripts/itcm_functions_includes.ld @@ -171,7 +171,8 @@ *(.text._ZN28MavlinkStreamGpsGlobalOrigin4sendEv) *(.text._ZN11ControlMath15bodyzToAttitudeEN6matrix7Vector3IfEEfR27vehicle_attitude_setpoint_s) *(.text._ZN4EKF217UpdateRangeSampleER17ekf2_timestamps_s) -*(.text._ZN3Ekf24controlOpticalFlowFusionERKN9estimator9imuSampleE) +*(.text._ZN17OpticalFlowAiding6updateER3EkfRKN9estimator9imuSampleE) +*(.text._ZN17OpticalFlowSource6updateER3EkfRKN9estimator9imuSampleEb) *(.text._ZN19MavlinkStreamRawRpm4sendEv) *(.text._ZN13MavlinkStream10const_rateEv) *(.text._ZN4EKF215PublishOdometryERKyRKN9estimator9imuSampleERKN6matrix7Vector3IfEE) @@ -338,7 +339,6 @@ *(.text._ZN14FlightTaskAutoD1Ev) *(.text._ZN4uORB10DeviceNode22get_initial_generationEv) *(.text._ZN3Ekf23controlGnssHeightFusionERKN9estimator10gnssSampleE) -*(.text._ZN3Ekf40updateOnGroundMotionForOpticalFlowChecksEv) *(.text._ZN6matrix6MatrixIfLj3ELj1EEC1Ev) *(.text._ZN14ZeroGyroUpdate6updateER3EkfRKN9estimator9imuSampleE) *(.text._ZN30MavlinkStreamOpenDroneIdSystem4sendEv) @@ -401,7 +401,7 @@ *(.text.nxsem_set_protocol) *(.text.write) *(.text._ZN22MavlinkStreamSysStatus4sendEv) -*(.text._ZN4EKF216UpdateFlowSampleER17ekf2_timestamps_s) +*(.text._ZN17OpticalFlowAiding13updateSamplesER3Ekf) *(.text._ZN4cdevL10cdev_ioctlEP4fileim) *(.text._ZN7Mavlink10send_bytesEPKhj) *(.text._ZNK8Failsafe17checkModeFallbackERK16failsafe_flags_sh) diff --git a/boards/px4/fmu-v6xrt/nuttx-config/scripts/itcm_functions_includes.ld b/boards/px4/fmu-v6xrt/nuttx-config/scripts/itcm_functions_includes.ld index 58a96d058ab..11d85e07b62 100644 --- a/boards/px4/fmu-v6xrt/nuttx-config/scripts/itcm_functions_includes.ld +++ b/boards/px4/fmu-v6xrt/nuttx-config/scripts/itcm_functions_includes.ld @@ -173,7 +173,8 @@ *(.text._ZN28MavlinkStreamGpsGlobalOrigin4sendEv) *(.text._ZN11ControlMath15bodyzToAttitudeEN6matrix7Vector3IfEEfR27vehicle_attitude_setpoint_s) *(.text._ZN4EKF217UpdateRangeSampleER17ekf2_timestamps_s) -*(.text._ZN3Ekf24controlOpticalFlowFusionERKN9estimator9imuSampleE) +*(.text._ZN17OpticalFlowAiding6updateER3EkfRKN9estimator9imuSampleE) +*(.text._ZN17OpticalFlowSource6updateER3EkfRKN9estimator9imuSampleEb) *(.text._ZN19MavlinkStreamRawRpm4sendEv) *(.text._ZN13MavlinkStream10const_rateEv) *(.text._ZN4EKF215PublishOdometryERKyRKN9estimator9imuSampleERKN6matrix7Vector3IfEE) @@ -344,7 +345,6 @@ *(.text._ZN14FlightTaskAutoD1Ev) *(.text._ZN4uORB10DeviceNode22get_initial_generationEv) *(.text._ZN3Ekf23controlGnssHeightFusionERKN9estimator10gnssSampleE) -*(.text._ZN3Ekf40updateOnGroundMotionForOpticalFlowChecksEv) *(.text._ZN6matrix6MatrixIfLj3ELj1EEC1Ev) *(.text._ZN14ZeroGyroUpdate6updateER3EkfRKN9estimator9imuSampleE) *(.text._ZN30MavlinkStreamOpenDroneIdSystem4sendEv) @@ -408,7 +408,7 @@ *(.text.nxsem_set_protocol) *(.text.write) *(.text._ZN22MavlinkStreamSysStatus4sendEv) -*(.text._ZN4EKF216UpdateFlowSampleER17ekf2_timestamps_s) +*(.text._ZN17OpticalFlowAiding13updateSamplesER3Ekf) *(.text._ZN4cdevL10cdev_ioctlEP4fileim) *(.text._ZN7Mavlink10send_bytesEPKhj) *(.text._ZNK8Failsafe17checkModeFallbackERK16failsafe_flags_sh) diff --git a/docs/en/advanced_config/tuning_the_ecl_ekf.md b/docs/en/advanced_config/tuning_the_ecl_ekf.md index 39d6bcda5c5..817a005b9ae 100644 --- a/docs/en/advanced_config/tuning_the_ecl_ekf.md +++ b/docs/en/advanced_config/tuning_the_ecl_ekf.md @@ -529,11 +529,13 @@ A good tuning is obtained as follows: [Optical flow](../sensor/optical_flow.md) data will be used if the following conditions are met: - Valid range finder data is available. -- [EKF2_OF_CTRL](../advanced_config/parameter_reference.md#EKF2_OF_CTRL) is set. -- The quality metric returned by the flow sensor is greater than the minimum requirement set by the [EKF2_OF_QMIN](../advanced_config/parameter_reference.md#EKF2_OF_QMIN) parameter. +- [EKF2_OF0_CTRL](../advanced_config/parameter_reference.md#EKF2_OF0_CTRL) is set. +- The quality metric returned by the flow sensor is greater than the minimum requirement set by the [EKF2_OF0_QMIN](../advanced_config/parameter_reference.md#EKF2_OF0_QMIN) parameter. +- For a second flow sensor [EKF2_OF1_CTRL](../advanced_config/parameter_reference.md#EKF2_OF1_CTRL) is set and the quality metric is greater than [EKF2_OF1_QMIN](../advanced_config/parameter_reference.md#EKF2_OF1_QMIN). -For better performance, set the location of the optical flow sensor as described [here](../sensor/optical_flow.md#ekf2). +Up to two optical flow sensors can be fused at the same time, each with its own set of `EKF2_OFn_*` parameters (see [Optical Flow > Multiple Optical Flow Sensors](../sensor/optical_flow.md#multiple-flow-sensors)). +For better performance, set the location of the optical flow sensor as described in [Optical Flow > EKF2](../sensor/optical_flow.md#ekf2). If a stable hover can be achieved at low altitude above ground (< 10m) but slow oscillations occur at higher altitude, consider adjusting the [optical flow scale factor](../sensor/optical_flow.md#scale-factor). ### External Vision System diff --git a/docs/en/dronecan/agam_florange.md b/docs/en/dronecan/agam_florange.md index 23a8b4c6c45..0ea473b743f 100644 --- a/docs/en/dronecan/agam_florange.md +++ b/docs/en/dronecan/agam_florange.md @@ -69,7 +69,7 @@ Twist the VCC/GND and CAN_H/CAN_L wires as pairs to reduce electromagnetic inter ### Mounting Mount the module with the sensors facing down and the X arrow on the enclosure pointing towards the front of the vehicle. -This corresponds to the default value (`0`) of the parameter [SENS_FLOW_ROT](../advanced_config/parameter_reference.md#SENS_FLOW_ROT). +This corresponds to the default value (`0`) of the parameter [SENS_FLOW0_ROT](../advanced_config/parameter_reference.md#SENS_FLOW0_ROT). Change the parameter appropriately if using a different orientation. ## Firmware Setup @@ -103,15 +103,15 @@ DroneCAN configuration in PX4 is explained in more detail in [DroneCAN > Enablin Set the following parameters in _QGroundControl_, depending on which functions of the module you use: -- Enable optical flow fusion with [EKF2_OF_CTRL](../advanced_config/parameter_reference.md#EKF2_OF_CTRL) (enabled by default). +- Enable optical flow fusion with [EKF2_OF0_CTRL](../advanced_config/parameter_reference.md#EKF2_OF0_CTRL) (enabled by default). - To optionally disable GPS aiding, set [EKF2_GPS_CTRL](../advanced_config/parameter_reference.md#EKF2_GPS_CTRL) to `0`. - Enable [UAVCAN_SUB_FLOW](../advanced_config/parameter_reference.md#UAVCAN_SUB_FLOW). - Enable [UAVCAN_SUB_RNG](../advanced_config/parameter_reference.md#UAVCAN_SUB_RNG). - Set [UAVCAN_RNG_MIN](../advanced_config/parameter_reference.md#UAVCAN_RNG_MIN) to `0.08`, the minimum working distance of the flow sensor, and [UAVCAN_RNG_MAX](../advanced_config/parameter_reference.md#UAVCAN_RNG_MAX) to `30`, the maximum range of the distance sensor. - If using the distance sensor for height aiding, enable [EKF2_RNG_CTRL](../advanced_config/parameter_reference.md#EKF2_RNG_CTRL) and set [EKF2_RNG_A_HMAX](../advanced_config/parameter_reference.md#EKF2_RNG_A_HMAX) to `10` and [EKF2_RNG_QLTY_T](../advanced_config/parameter_reference.md#EKF2_RNG_QLTY_T) to `0.2`. -- Set [SENS_FLOW_MINHGT](../advanced_config/parameter_reference.md#SENS_FLOW_MINHGT) to `0.08`, the minimum height of the flow sensor, and [SENS_FLOW_MAXHGT](../advanced_config/parameter_reference.md#SENS_FLOW_MAXHGT) to `30`, the maximum range of the distance sensor. -- Set [SENS_FLOW_MAXR](../advanced_config/parameter_reference.md#SENS_FLOW_MAXR) to `7.4` to match the PAA3905 maximum angular flow rate. -- The parameters [EKF2_OF_POS_X](../advanced_config/parameter_reference.md#EKF2_OF_POS_X), [EKF2_OF_POS_Y](../advanced_config/parameter_reference.md#EKF2_OF_POS_Y), [EKF2_OF_POS_Z](../advanced_config/parameter_reference.md#EKF2_OF_POS_Z) and [EKF2_RNG_POS_X](../advanced_config/parameter_reference.md#EKF2_RNG_POS_X), [EKF2_RNG_POS_Y](../advanced_config/parameter_reference.md#EKF2_RNG_POS_Y), [EKF2_RNG_POS_Z](../advanced_config/parameter_reference.md#EKF2_RNG_POS_Z) can be set to account for the offset of the module from the vehicle centre of gravity. +- Set [SENS_FLOW0_HMIN](../advanced_config/parameter_reference.md#SENS_FLOW0_HMIN) to `0.08`, the minimum height of the flow sensor, and [SENS_FLOW0_HMAX](../advanced_config/parameter_reference.md#SENS_FLOW0_HMAX) to `30`, the maximum range of the distance sensor. +- Set [SENS_FLOW0_MAXR](../advanced_config/parameter_reference.md#SENS_FLOW0_MAXR) to `7.4` to match the PAA3905 maximum angular flow rate. +- The parameters [SENS_FLOW0_POS_X](../advanced_config/parameter_reference.md#SENS_FLOW0_POS_X), [SENS_FLOW0_POS_Y](../advanced_config/parameter_reference.md#SENS_FLOW0_POS_Y), [SENS_FLOW0_POS_Z](../advanced_config/parameter_reference.md#SENS_FLOW0_POS_Z) and [EKF2_RNG_POS_X](../advanced_config/parameter_reference.md#EKF2_RNG_POS_X), [EKF2_RNG_POS_Y](../advanced_config/parameter_reference.md#EKF2_RNG_POS_Y), [EKF2_RNG_POS_Z](../advanced_config/parameter_reference.md#EKF2_RNG_POS_Z) can be set to account for the offset of the module from the vehicle centre of gravity. When optical flow is the only source of horizontal position/velocity, reduce the horizontal position gain [MPC_XY_P](../advanced_config/parameter_reference.md#MPC_XY_P) (for example to `0.5`) to reduce oscillations. diff --git a/docs/en/dronecan/ark_flow.md b/docs/en/dronecan/ark_flow.md index 0e0a309e3b1..0d9ab218fd6 100644 --- a/docs/en/dronecan/ark_flow.md +++ b/docs/en/dronecan/ark_flow.md @@ -49,7 +49,7 @@ The recommended mounting orientation is with the connectors on the board pointin ![ARK Flow align with Pixhawk](../../assets/hardware/sensors/optical_flow/ark_flow_orientation.png) -This corresponds to the default value (`0`) of the parameter [SENS_FLOW_ROT](../advanced_config/parameter_reference.md#SENS_FLOW_ROT). +This corresponds to the default value (`0`) of the parameter [SENS_FLOW0_ROT](../advanced_config/parameter_reference.md#SENS_FLOW0_ROT). Change the parameter appropriately if using a different orientation. The sensor can be mounted anywhere on the frame, but you will need to specify the focal point position, relative to vehicle centre of gravity, during [PX4 configuration](#px4-configuration). @@ -90,7 +90,7 @@ Then set the EKF optical flow parameters to enable fusing optical flow measureme Set the following parameters in _QGroundControl_: -- Enable optical flow fusion by setting [EKF2_OF_CTRL](../advanced_config/parameter_reference.md#EKF2_OF_CTRL). +- Enable optical flow fusion by setting [EKF2_OF0_CTRL](../advanced_config/parameter_reference.md#EKF2_OF0_CTRL). - To optionally disable GPS aiding, set [EKF2_GPS_CTRL](../advanced_config/parameter_reference.md#EKF2_GPS_CTRL) to `0`. - Enable [UAVCAN_SUB_FLOW](../advanced_config/parameter_reference.md#UAVCAN_SUB_FLOW). - Enable [UAVCAN_SUB_RNG](../advanced_config/parameter_reference.md#UAVCAN_SUB_RNG). @@ -98,10 +98,10 @@ Set the following parameters in _QGroundControl_: - Set [EKF2_RNG_QLTY_T](../advanced_config/parameter_reference.md#EKF2_RNG_QLTY_T) to `0.2`. - Set [UAVCAN_RNG_MIN](../advanced_config/parameter_reference.md#UAVCAN_RNG_MIN) to `0.08`. - Set [UAVCAN_RNG_MAX](../advanced_config/parameter_reference.md#UAVCAN_RNG_MAX) to `30`. -- Set [SENS_FLOW_MINHGT](../advanced_config/parameter_reference.md#SENS_FLOW_MINHGT) to `0.08`. -- Set [SENS_FLOW_MAXHGT](../advanced_config/parameter_reference.md#SENS_FLOW_MAXHGT) to `25`. -- Set [SENS_FLOW_MAXR](../advanced_config/parameter_reference.md#SENS_FLOW_MAXR) to `7.4` to match the PAW3902 maximum angular flow rate. -- The parameters [EKF2_OF_POS_X](../advanced_config/parameter_reference.md#EKF2_OF_POS_X), [EKF2_OF_POS_Y](../advanced_config/parameter_reference.md#EKF2_OF_POS_Y) and [EKF2_OF_POS_Z](../advanced_config/parameter_reference.md#EKF2_OF_POS_Z) can be set to account for the offset of the Ark Flow from the vehicle centre of gravity. +- Set [SENS_FLOW0_HMIN](../advanced_config/parameter_reference.md#SENS_FLOW0_HMIN) to `0.08`. +- Set [SENS_FLOW0_HMAX](../advanced_config/parameter_reference.md#SENS_FLOW0_HMAX) to `25`. +- Set [SENS_FLOW0_MAXR](../advanced_config/parameter_reference.md#SENS_FLOW0_MAXR) to `7.4` to match the PAW3902 maximum angular flow rate. +- The parameters [SENS_FLOW0_POS_X](../advanced_config/parameter_reference.md#SENS_FLOW0_POS_X), [SENS_FLOW0_POS_Y](../advanced_config/parameter_reference.md#SENS_FLOW0_POS_Y) and [SENS_FLOW0_POS_Z](../advanced_config/parameter_reference.md#SENS_FLOW0_POS_Z) can be set to account for the offset of the Ark Flow from the vehicle centre of gravity. When optical flow is the only source of horizontal position/velocity, then lowering the gain for controller response to horizontal position error [MPC_XY_P](../advanced_config/parameter_reference.md#MPC_XY_P) (e.g. to 0.5) is recommended to reduce oscillations. diff --git a/docs/en/dronecan/ark_flow_mr.md b/docs/en/dronecan/ark_flow_mr.md index ef525ff456d..34919ad098f 100644 --- a/docs/en/dronecan/ark_flow_mr.md +++ b/docs/en/dronecan/ark_flow_mr.md @@ -47,7 +47,7 @@ The recommended mounting orientation is with the connectors on the board pointin ![ARK Flow MR align with Pixhawk](../../assets/hardware/sensors/optical_flow/ark_flow_orientation.png) -This corresponds to the default value (`0`) of the parameter [SENS_FLOW_ROT](../advanced_config/parameter_reference.md#SENS_FLOW_ROT). +This corresponds to the default value (`0`) of the parameter [SENS_FLOW0_ROT](../advanced_config/parameter_reference.md#SENS_FLOW0_ROT). Change the parameter appropriately if using a different orientation. The sensor can be mounted anywhere on the frame, but you will need to specify the focal point position, relative to vehicle centre of gravity, during [PX4 configuration](#px4-configuration). @@ -87,7 +87,7 @@ You need to set the EKF optical flow parameters to enable fusing optical flow me Set the following parameters in _QGroundControl_: -- Enable optical flow fusion by setting [EKF2_OF_CTRL](../advanced_config/parameter_reference.md#EKF2_OF_CTRL). +- Enable optical flow fusion by setting [EKF2_OF0_CTRL](../advanced_config/parameter_reference.md#EKF2_OF0_CTRL). - To optionally disable GPS aiding, set [EKF2_GPS_CTRL](../advanced_config/parameter_reference.md#EKF2_GPS_CTRL) to `0`. - Enable [UAVCAN_SUB_FLOW](../advanced_config/parameter_reference.md#UAVCAN_SUB_FLOW). - Enable [UAVCAN_SUB_RNG](../advanced_config/parameter_reference.md#UAVCAN_SUB_RNG). @@ -95,10 +95,10 @@ Set the following parameters in _QGroundControl_: - Set [EKF2_RNG_QLTY_T](../advanced_config/parameter_reference.md#EKF2_RNG_QLTY_T) to `0.2`. - Set [UAVCAN_RNG_MIN](../advanced_config/parameter_reference.md#UAVCAN_RNG_MIN) to `0.08`. - Set [UAVCAN_RNG_MAX](../advanced_config/parameter_reference.md#UAVCAN_RNG_MAX) to `50`. -- Set [SENS_FLOW_MINHGT](../advanced_config/parameter_reference.md#SENS_FLOW_MINHGT) to `0.08`. -- Set [SENS_FLOW_MAXHGT](../advanced_config/parameter_reference.md#SENS_FLOW_MAXHGT) to `25`. -- Set [SENS_FLOW_MAXR](../advanced_config/parameter_reference.md#SENS_FLOW_MAXR) to `7.4` to match the PAW3902 maximum angular flow rate. -- The parameters [EKF2_OF_POS_X](../advanced_config/parameter_reference.md#EKF2_OF_POS_X), [EKF2_OF_POS_Y](../advanced_config/parameter_reference.md#EKF2_OF_POS_Y) and [EKF2_OF_POS_Z](../advanced_config/parameter_reference.md#EKF2_OF_POS_Z) can be set to account for the offset of the Ark Flow MR from the vehicle centre of gravity. +- Set [SENS_FLOW0_HMIN](../advanced_config/parameter_reference.md#SENS_FLOW0_HMIN) to `0.08`. +- Set [SENS_FLOW0_HMAX](../advanced_config/parameter_reference.md#SENS_FLOW0_HMAX) to `25`. +- Set [SENS_FLOW0_MAXR](../advanced_config/parameter_reference.md#SENS_FLOW0_MAXR) to `7.4` to match the PAW3902 maximum angular flow rate. +- The parameters [SENS_FLOW0_POS_X](../advanced_config/parameter_reference.md#SENS_FLOW0_POS_X), [SENS_FLOW0_POS_Y](../advanced_config/parameter_reference.md#SENS_FLOW0_POS_Y) and [SENS_FLOW0_POS_Z](../advanced_config/parameter_reference.md#SENS_FLOW0_POS_Z) can be set to account for the offset of the Ark Flow MR from the vehicle centre of gravity. ## Ark Flow MR Configuration diff --git a/docs/en/dronecan/index.md b/docs/en/dronecan/index.md index f85cb2a0981..51334ca0e8f 100644 --- a/docs/en/dronecan/index.md +++ b/docs/en/dronecan/index.md @@ -141,7 +141,7 @@ Instead you must enable publication or subscription to the messages associated w ::: info Sensor parameters may not exist (be visible in QGC) until you have enabled the associated DroneCAN [sensor subscription](#sensors)! -For example, [SENS_FLOW_MINHGT](../advanced_config/parameter_reference.md#SENS_FLOW_MINHGT) does not exist until [UAVCAN_SUB_FLOW](../advanced_config/parameter_reference.md#UAVCAN_SUB_FLOW) is enabled. +For example, [SENS_FLOW0_HMIN](../advanced_config/parameter_reference.md#SENS_FLOW0_HMIN) does not exist until [UAVCAN_SUB_FLOW](../advanced_config/parameter_reference.md#UAVCAN_SUB_FLOW) is enabled. ::: For example, to use a connected DroneCAN smart battery you would enable the [UAVCAN_SUB_BAT](../advanced_config/parameter_reference.md#UAVCAN_SUB_BAT) parameter, which would subscribe PX4 to receive [BatteryInfo](https://dronecan.github.io/Specification/7._List_of_standard_data_types/#batteryinfo) DroneCAN messages. @@ -262,11 +262,11 @@ PX4 DroneCAN parameters: Other PX4 parameters: -- Set [SENS_FLOW_MINHGT](../advanced_config/parameter_reference.md#SENS_FLOW_MINHGT) and [SENS_FLOW_MAXHGT](../advanced_config/parameter_reference.md#SENS_FLOW_MAXHGT), the minimum and maximum height of the flow sensor. -- Set [SENS_FLOW_MAXR](../advanced_config/parameter_reference.md#SENS_FLOW_MAXR) the maximum angular flow rate of the sensor. -- Enable optical flow fusion by setting [EKF2_OF_CTRL](../advanced_config/parameter_reference.md#EKF2_OF_CTRL). +- Set [SENS_FLOW0_HMIN](../advanced_config/parameter_reference.md#SENS_FLOW0_HMIN) and [SENS_FLOW0_HMAX](../advanced_config/parameter_reference.md#SENS_FLOW0_HMAX), the minimum and maximum height of the flow sensor. +- Set [SENS_FLOW0_MAXR](../advanced_config/parameter_reference.md#SENS_FLOW0_MAXR) the maximum angular flow rate of the sensor. +- Enable optical flow fusion by setting [EKF2_OF0_CTRL](../advanced_config/parameter_reference.md#EKF2_OF0_CTRL). - To disable GPS aiding (optional), set [EKF2_GPS_CTRL](../advanced_config/parameter_reference.md#EKF2_GPS_CTRL) to `0`. -- If the optical flow unit is not positioned at the vehicle centre of gravity you can account for the offset using [EKF2_OF_POS_X](../advanced_config/parameter_reference.md#EKF2_OF_POS_X), [EKF2_OF_POS_Y](../advanced_config/parameter_reference.md#EKF2_OF_POS_Y) and [EKF2_OF_POS_Z](../advanced_config/parameter_reference.md#EKF2_OF_POS_Z). +- If the optical flow unit is not positioned at the vehicle centre of gravity you can account for the offset using [SENS_FLOW0_POS_X](../advanced_config/parameter_reference.md#SENS_FLOW0_POS_X), [SENS_FLOW0_POS_Y](../advanced_config/parameter_reference.md#SENS_FLOW0_POS_Y) and [SENS_FLOW0_POS_Z](../advanced_config/parameter_reference.md#SENS_FLOW0_POS_Z). Optical flow sensors require rangefinder data. However the rangefinder need not be part of the same module, and if not, may not be connected via DroneCAN. diff --git a/docs/en/sensor/microstrain.md b/docs/en/sensor/microstrain.md index c987130b04f..1fab8c497df 100644 --- a/docs/en/sensor/microstrain.md +++ b/docs/en/sensor/microstrain.md @@ -106,7 +106,7 @@ To use the MicroStrain driver: - [MS_OFLW_OFF_X](../advanced_config/parameter_reference.md#MS_OFLW_OFF_X) - [MS_OFLW_OFF_Y](../advanced_config/parameter_reference.md#MS_OFLW_OFF_Y) - [MS_OFLW_OFF_Z](../advanced_config/parameter_reference.md#MS_OFLW_OFF_Z) - - [SENS_FLOW_ROT](../advanced_config/parameter_reference.md#SENS_FLOW_ROT) + - [SENS_FLOW0_ROT](../advanced_config/parameter_reference.md#SENS_FLOW0_ROT) - The uncertainty for optical flow and external magnetometer aiding must be specified using the following parameters: - [MS_EMAG_UNCERT](../advanced_config/parameter_reference.md#MS_EMAG_UNCERT) diff --git a/docs/en/sensor/optical_flow.md b/docs/en/sensor/optical_flow.md index c49c07765f1..36cf41e3da9 100644 --- a/docs/en/sensor/optical_flow.md +++ b/docs/en/sensor/optical_flow.md @@ -19,6 +19,7 @@ An Optical Flow setup requires a downward facing camera and a downward facing [d These can be combined in a single product, such as the [ARK Flow](../dronecan/ark_flow.md), [ARK Flow MR](../dronecan/ark_flow_mr.md) and [Holybro H-Flow](https://holybro.com/products/h-flow), or they may be separate sensors. The sensor(s) can be connected via MAVLink, I2C or any other bus that supports the peripheral. +Up to two optical flow sensors can be used at the same time (see [Multiple Optical Flow Sensors](#multiple-flow-sensors)). ::: info If connected to PX4 via MAVLink the Optical Flow camera sensor must publish the [OPTICAL_FLOW_RAD](https://mavlink.io/en/messages/common.html#OPTICAL_FLOW_RAD) message, and the distance sensor must publish the [DISTANCE_SENSOR](https://mavlink.io/en/messages/common.html#DISTANCE_SENSOR) message. @@ -46,7 +47,7 @@ The approach used for fusing sensor data and any offsets from the center of the ### Scale Factor For pure rotations the `OPTICAL_FLOW_RAD.integrated_xgyro` and `OPTICAL_FLOW_RAD.integrated_x` (respectively `integrated_ygyro` and `integrated_y`) have to be the same. -If this is not the case, the optical flow scale factor can be adjusted using [SENS_FLOW_SCALE](../advanced_config/parameter_reference.md#SENS_FLOW_SCALE). +If this is not the case, the optical flow scale factor can be adjusted using [SENS_FLOW0_SCALE](../advanced_config/parameter_reference.md#SENS_FLOW0_SCALE). :::tip The low resolution of common optical flow sensors can cause slow oscillations when hovering at a high altitude above ground (> 20m). @@ -102,18 +103,51 @@ Optical Flow based navigation is enabled by both [EKF2](#ekf2) and LPE (deprecat ### Extended Kalman Filter (EKF2) {#ekf2} -For optical flow fusion using EKF2, set [EKF2_OF_CTRL](../advanced_config/parameter_reference.md#EKF2_OF_CTRL). +For optical flow fusion using EKF2, set [EKF2_OF0_CTRL](../advanced_config/parameter_reference.md#EKF2_OF0_CTRL). If your optical flow sensor is offset from the vehicle centre, you can set this using the following parameters. | Parameter | Description | | -------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | -| [EKF2_OF_POS_X](../advanced_config/parameter_reference.md#EKF2_OF_POS_X) | X position of optical flow focal point in body frame (default is 0.0m). | -| [EKF2_OF_POS_Y](../advanced_config/parameter_reference.md#EKF2_OF_POS_Y) | Y position of optical flow focal point in body frame (default is 0.0m). | -| [EKF2_OF_POS_Z](../advanced_config/parameter_reference.md#EKF2_OF_POS_Z) | Z position of optical flow focal point in body frame (default is 0.0m). | +| [SENS_FLOW0_POS_X](../advanced_config/parameter_reference.md#SENS_FLOW0_POS_X) | X position of optical flow focal point in body frame (default is 0.0m). | +| [SENS_FLOW0_POS_Y](../advanced_config/parameter_reference.md#SENS_FLOW0_POS_Y) | Y position of optical flow focal point in body frame (default is 0.0m). | +| [SENS_FLOW0_POS_Z](../advanced_config/parameter_reference.md#SENS_FLOW0_POS_Z) | Z position of optical flow focal point in body frame (default is 0.0m). | See [Using PX4's Navigation Filter (EKF2) > Optical flow](../advanced_config/tuning_the_ecl_ekf.md#optical-flow) for more information. +## Multiple Optical Flow Sensors {#multiple-flow-sensors} + + + +PX4 supports up to two optical flow sensors at the same time. +A second sensor can add redundancy, or extend the usable envelope by combining sensors with different operating ranges. +Both sensors are fused, each at its own measurement rate. +A sensor that temporarily cannot be fused (for example when it leaves its operating range) keeps being processed for monitoring, and its data is used again as soon as it recovers. +A sensor whose measurements are rejected while the other sensor is still fused is considered faulty: it never resets the velocity or height above ground estimate, it is stopped and retried later. + +Each sensor is bound to a parameter "slot" `n` (`0` or `1`) using its device ID: + +- [SENS_FLOW0_ID](../advanced_config/parameter_reference.md#SENS_FLOW0_ID) and [SENS_FLOW1_ID](../advanced_config/parameter_reference.md#SENS_FLOW1_ID) record the device ID of the sensor bound to the `SENS_FLOWn_*` parameters. + While an ID parameter is `0` (default), the first unbound sensor that delivers data is bound to it, and the assignment is saved so that it remains stable across reboots. + The EKF uses the same slot numbering: `EKF2_OFn_*` parameters apply to the sensor bound to `SENS_FLOWn_ID`. +- Fusion is enabled per slot using [EKF2_OF0_CTRL](../advanced_config/parameter_reference.md#EKF2_OF0_CTRL) and [EKF2_OF1_CTRL](../advanced_config/parameter_reference.md#EKF2_OF1_CTRL). + Only slot 0 is enabled by default. + A slot can be enabled or disabled at runtime. +- When a sensor is replaced, the new sensor has a different device ID and is bound to the next free slot, which is not fused by default. + To bind the new sensor to the old slot, set its `SENS_FLOWn_ID` parameter to `0` and reboot. +- All other optical flow parameters exist once per sensor: sensor properties such as delay, rotation, and mounting position in `SENS_FLOW0_*`/`SENS_FLOW1_*`, and fusion tuning such as noise and quality thresholds in `EKF2_OF0_*`/`EKF2_OF1_*`, so each sensor can be configured independently. + +Note the following requirements and behaviour: + +- All flow sensors must be mounted facing downwards. + The sensors do not need to have the same yaw orientation (set individually using `SENS_FLOWn_ROT`), and each sensor has its own position offset (`SENS_FLOWn_POS_X` and so on). +- Flow sensors are not paired with specific [distance sensors](../sensor/rangefinders.md). + The EKF estimates a single height above ground that is used for all flow sensors, corrected for each sensor's position offset. + The minimum and maximum operating distance reported by each sensor is applied individually. +- A distance measurement provided by a flow sensor itself (as on the [ARK Flow](../dronecan/ark_flow.md)) can substitute for a missing distance sensor. + Only the measurement from the first sensor that reports a distance is used for this purpose. +- The preflight check enabled by [SYS_HAS_NUM_OF](../advanced_config/parameter_reference.md#SYS_HAS_NUM_OF) passes when at least one sensor delivers valid data. + ## Simulation Optical flow can be simulated with [SIH](../sim_sih/index.md), which computes the flow from the simulated vehicle motion instead of rendering a camera image. diff --git a/docs/en/sensor/pmw3901.md b/docs/en/sensor/pmw3901.md index 076fa66e4f5..1b7ee5fc5ca 100644 --- a/docs/en/sensor/pmw3901.md +++ b/docs/en/sensor/pmw3901.md @@ -43,12 +43,12 @@ The PX4 team mainly tested using the [Lidar Lite V3](../sensor/lidar_lite.md) on Flow modules are typically mounted near the centre of the vehicle. If mounted off-centre you will need to set offsets: [Optical Flow > EKF2](../sensor/optical_flow.md#ekf2). -The flow modules may be mounted with any yaw orientation relative to the vehicle body frame, but you must set the value used in [SENS_FLOW_ROT](../advanced_config/parameter_reference.md#SENS_FLOW_ROT). +The flow modules may be mounted with any yaw orientation relative to the vehicle body frame, but you must set the value used in [SENS_FLOW0_ROT](../advanced_config/parameter_reference.md#SENS_FLOW0_ROT). The "zero" rotation is when the sensor board and [vehicle](../getting_started/px4_basic_concepts.md#heading-and-directions) X-axes are aligned (i.e. the "front" of the vehicle and the board are in the same direction), with rotations increasing in a clockwise direction. PMW3901 modules have a small notch indicating the direction of the **back** of the board. -The diagram shows the relative board and vehicle orientations that correspond to `SENS_FLOW_ROT=0` (note the notch at the back). +The diagram shows the relative board and vehicle orientations that correspond to `SENS_FLOW0_ROT=0` (note the notch at the back). ![PMW3901 PH4 Rotation](../../assets/hardware/sensors/pmw3901/ph4-pmw3901-rotation.png) @@ -70,7 +70,7 @@ You can use the notch to find the orientation of the other boards in the same wa The PX4 configuration that is common to all PMW3901-based boards: - [Optical Flow > EKF2](../sensor/optical_flow.md#ekf2) explains how to fuse optical flow data in the EKF2 estimator and set position offsets for the mounting position of the flow sensor. -- [SENS_FLOW_ROT](../advanced_config/parameter_reference.md#SENS_FLOW_ROT) sets the orientation of the flow sensor relative to vehicle heading. +- [SENS_FLOW0_ROT](../advanced_config/parameter_reference.md#SENS_FLOW0_ROT) sets the orientation of the flow sensor relative to vehicle heading. In addition for: diff --git a/docs/en/test_cards/mc_06_optical_flow.md b/docs/en/test_cards/mc_06_optical_flow.md index 22877115e6c..719752d3ee6 100644 --- a/docs/en/test_cards/mc_06_optical_flow.md +++ b/docs/en/test_cards/mc_06_optical_flow.md @@ -10,7 +10,7 @@ Disconnect all GPS / compasses and ensure vehicle is using optical flow for navi Ensure there are no other sources of positioning besides optical flow: -- [EKF2_OF_CTRL](../advanced_config/parameter_reference.md#EKF2_OF_CTRL): `1` +- [EKF2_OF0_CTRL](../advanced_config/parameter_reference.md#EKF2_OF0_CTRL): `1` - [EKF2_GPS_CTRL](../advanced_config/parameter_reference.md#EKF2_GPS_CTRL): `0` - [EKF2_EV_CTRL](../advanced_config/parameter_reference.md#EKF2_EV_CTRL): `0` diff --git a/docs/en/test_cards/mc_07_optical_flow_low_mount.md b/docs/en/test_cards/mc_07_optical_flow_low_mount.md index 73c06f4e4a2..888cfe6b182 100644 --- a/docs/en/test_cards/mc_07_optical_flow_low_mount.md +++ b/docs/en/test_cards/mc_07_optical_flow_low_mount.md @@ -15,7 +15,7 @@ Disconnect all GPS / compasses and ensure vehicle is using optical flow for navi Ensure there are no other sources of positioning besides optical flow -- [EKF2_OF_CTRL](../advanced_config/parameter_reference.md#EKF2_OF_CTRL): `1` +- [EKF2_OF0_CTRL](../advanced_config/parameter_reference.md#EKF2_OF0_CTRL): `1` - [EKF2_GPS_CTRL](../advanced_config/parameter_reference.md#EKF2_GPS_CTRL): `0` - [EKF2_EV_CTRL](../advanced_config/parameter_reference.md#EKF2_EV_CTRL): `0` diff --git a/docs/en/test_cards/mc_09_vio.md b/docs/en/test_cards/mc_09_vio.md index 994fa9e4cf6..ac9f7eab1c5 100644 --- a/docs/en/test_cards/mc_09_vio.md +++ b/docs/en/test_cards/mc_09_vio.md @@ -12,7 +12,7 @@ Ensure that the drone can go into [Altitude](../flight_modes_mc/altitude.md) / [ Ensure there are no other sources of positioning besides VIO: -- [EKF2_OF_CTRL](../advanced_config/parameter_reference.md#EKF2_OF_CTRL): `0` +- [EKF2_OF0_CTRL](../advanced_config/parameter_reference.md#EKF2_OF0_CTRL): `0` - [EKF2_GPS_CTRL](../advanced_config/parameter_reference.md#EKF2_GPS_CTRL): `0` - [EKF2_EV_CTRL](../advanced_config/parameter_reference.md#EKF2_EV_CTRL): `15` - [SYS_HAS_MAG](../advanced_config/parameter_reference.md#SYS_HAS_MAG): `0` diff --git a/docs/en/test_cards/mc_10_optical_flow_gps_mixed.md b/docs/en/test_cards/mc_10_optical_flow_gps_mixed.md index 7cb13a1308c..48f51e3e305 100644 --- a/docs/en/test_cards/mc_10_optical_flow_gps_mixed.md +++ b/docs/en/test_cards/mc_10_optical_flow_gps_mixed.md @@ -10,7 +10,7 @@ Test that optical flow mixed with GPS works as expected Ensure there are no other sources of positioning besides optical flow -- [EKF2_OF_CTRL](../advanced_config/parameter_reference.md#EKF2_OF_CTRL): `1` +- [EKF2_OF0_CTRL](../advanced_config/parameter_reference.md#EKF2_OF0_CTRL): `1` - [EKF2_GPS_CTRL](../advanced_config/parameter_reference.md#EKF2_GPS_CTRL): `7` - [EKF2_EV_CTRL](../advanced_config/parameter_reference.md#EKF2_EV_CTRL): `0` - [SYS_HAS_MAG](../advanced_config/parameter_reference.md#SYS_HAS_MAG): `1` diff --git a/msg/VehicleOpticalFlow.msg b/msg/VehicleOpticalFlow.msg index 23472b4c97f..a79444a4692 100644 --- a/msg/VehicleOpticalFlow.msg +++ b/msg/VehicleOpticalFlow.msg @@ -19,3 +19,5 @@ float32 max_flow_rate # (radians/s) Magnitude of maximum angular which float32 min_ground_distance # (meters) Minimum distance from ground at which the optical flow sensor operates reliably float32 max_ground_distance # (meters) Maximum distance from ground at which the optical flow sensor operates reliably + +float32[3] position_offset # (meters) Position of the sensor focal point in body FRD frame, relative to the vehicle centre of gravity diff --git a/msg/versioned/VehicleCommand.msg b/msg/versioned/VehicleCommand.msg index 55230902f24..90fc4fd81c5 100644 --- a/msg/versioned/VehicleCommand.msg +++ b/msg/versioned/VehicleCommand.msg @@ -115,7 +115,7 @@ uint16 VEHICLE_CMD_EXTERNAL_WIND_ESTIMATE = 43004 uint16 VEHICLE_CMD_ESTIMATOR_SENSOR_ENABLE = 43006 # Enable/disable estimator sensor fusion. |Source (FUSION_SOURCE_*)|Sensor instance (0-based)|Enable (1) or Disable (0)|Estimator Instance (NaN: not used)|Empty|Empty|Empty| # Sensor fusion source types for VEHICLE_CMD_ESTIMATOR_SENSOR_ENABLE uint8 FUSION_SOURCE_GPS = 0 # GNSS (EKF2_GPS{i}_CTRL, use instance param) -uint8 FUSION_SOURCE_OF = 1 # Optical Flow (EKF2_OF_CTRL) +uint8 FUSION_SOURCE_OF = 1 # Optical Flow (toggles all sensors, per-slot config via EKF2_OF{i}_CTRL) uint8 FUSION_SOURCE_EV = 2 # External Vision (EKF2_EV_CTRL) uint8 FUSION_SOURCE_AGP = 3 # Auxiliary Global Position (EKF2_AGP{i}_CTRL, use instance param) uint8 FUSION_SOURCE_BARO = 4 # Barometer (EKF2_BARO_CTRL) diff --git a/posix-configs/rpi/navigator/sub.config b/posix-configs/rpi/navigator/sub.config index 20aa57d9fec..d1c49de30af 100644 --- a/posix-configs/rpi/navigator/sub.config +++ b/posix-configs/rpi/navigator/sub.config @@ -19,7 +19,7 @@ param set EKF2_BARO_CTRL 1 param set EKF2_HGT_REF 0 param set EKF2_RNG_CTRL 0 -param set EKF2_OF_CTRL 0 +param set EKF2_OF0_CTRL 0 param set EKF2_EV_CTRL 0 dataman start diff --git a/src/lib/CMakeLists.txt b/src/lib/CMakeLists.txt index d355829ad6c..a13f37bd2be 100644 --- a/src/lib/CMakeLists.txt +++ b/src/lib/CMakeLists.txt @@ -80,6 +80,7 @@ add_subdirectory(rl_tools EXCLUDE_FROM_ALL) add_subdirectory(rover_control EXCLUDE_FROM_ALL) add_subdirectory(rtl EXCLUDE_FROM_ALL) add_subdirectory(sensor_calibration EXCLUDE_FROM_ALL) +add_subdirectory(sensor_slot_binder EXCLUDE_FROM_ALL) add_subdirectory(slew_rate EXCLUDE_FROM_ALL) add_subdirectory(sticks EXCLUDE_FROM_ALL) add_subdirectory(stick_yaw EXCLUDE_FROM_ALL) diff --git a/src/lib/parameters/param_translation.cpp b/src/lib/parameters/param_translation.cpp index 40461de0828..067f0de94b0 100644 --- a/src/lib/parameters/param_translation.cpp +++ b/src/lib/parameters/param_translation.cpp @@ -210,6 +210,37 @@ param_modify_on_import_ret param_modify_on_import(bson_node_t node) } } + // 2026-08-19: translate the single-sensor optical flow params to sensor slot 0 + { + static constexpr const char *renames[][2] = { + {"EKF2_OF_CTRL", "EKF2_OF0_CTRL"}, + {"EKF2_OF_GYR_SRC", "EKF2_OF0_GYR_SRC"}, + {"EKF2_OF_N_MIN", "EKF2_OF0_N_MIN"}, + {"EKF2_OF_N_MAX", "EKF2_OF0_N_MAX"}, + {"EKF2_OF_QMIN", "EKF2_OF0_QMIN"}, + {"EKF2_OF_QMIN_GND", "EKF2_OF0_QMINGND"}, + {"EKF2_OF_GATE", "EKF2_OF0_GATE"}, + {"EKF2_OF_DELAY", "SENS_FLOW0_DELAY"}, + {"EKF2_OF_POS_X", "SENS_FLOW0_POS_X"}, + {"EKF2_OF_POS_Y", "SENS_FLOW0_POS_Y"}, + {"EKF2_OF_POS_Z", "SENS_FLOW0_POS_Z"}, + {"SENS_FLOW_MINHGT", "SENS_FLOW0_HMIN"}, + {"SENS_FLOW_MAXHGT", "SENS_FLOW0_HMAX"}, + {"SENS_FLOW_MAXR", "SENS_FLOW0_MAXR"}, + {"SENS_FLOW_ROT", "SENS_FLOW0_ROT"}, + {"SENS_FLOW_RATE", "SENS_FLOW0_RATE"}, + {"SENS_FLOW_SCALE", "SENS_FLOW0_SCALE"}, + }; + + for (const auto &rename : renames) { + if (strcmp(rename[0], node->name) == 0) { + strcpy(node->name, rename[1]); + PX4_INFO("migrating %s -> %s", rename[0], rename[1]); + return param_modify_on_import_ret::PARAM_MODIFIED; + } + } + } + // 2026-03-11: translate MOT_POLE_COUNT to per-motor DSHOT_MOT_POL1-12 { if ((node->type == bson_type_t::BSON_INT32) && (strcmp("MOT_POLE_COUNT", node->name) == 0)) { diff --git a/src/lib/sensor_slot_binder/CMakeLists.txt b/src/lib/sensor_slot_binder/CMakeLists.txt new file mode 100644 index 00000000000..b3093f4ee7b --- /dev/null +++ b/src/lib/sensor_slot_binder/CMakeLists.txt @@ -0,0 +1,35 @@ +############################################################################ +# +# Copyright (c) 2026 PX4 Development Team. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# 3. Neither the name PX4 nor the names of its contributors may be +# used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# +############################################################################ + +# header-only, SensorSlotBinder.hpp is included directly +px4_add_functional_gtest(SRC SensorSlotBinderTest.cpp LINKLIBS parameters) diff --git a/src/lib/sensor_slot_binder/SensorSlotBinder.hpp b/src/lib/sensor_slot_binder/SensorSlotBinder.hpp new file mode 100644 index 00000000000..dc2d052c895 --- /dev/null +++ b/src/lib/sensor_slot_binder/SensorSlotBinder.hpp @@ -0,0 +1,162 @@ +/**************************************************************************** + * + * Copyright (c) 2026 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +// Maps uORB instances to fixed sensor slots by device ID: an unknown sensor is bound to the +// first free slot (ID param 0) and the assignment is persisted so it stays stable across reboots. +class SensorSlotBinder +{ +public: + static constexpr uint8_t kMaxSlots = 4; + + void init(const char *id_param_format, uint8_t num_slots) + { + _num_slots = (num_slots <= kMaxSlots) ? num_slots : kMaxSlots; + + for (uint8_t slot = 0; slot < _num_slots; slot++) { + char param_name[17] {}; + snprintf(param_name, sizeof(param_name), id_param_format, static_cast(slot)); + _id_param_handles[slot] = param_find(param_name); + + if (_id_param_handles[slot] != PARAM_INVALID) { + param_get(_id_param_handles[slot], &_ids[slot]); + } + } + } + + bool isSlotBound(uint8_t slot) const { return (slot < _num_slots) && (_ids[slot] != 0); } + + int8_t slotForInstance(uint8_t instance, uint32_t device_id) + { + if (instance >= _num_slots) { + return -1; + } + + if ((_instance_slot_map[instance] < 0) || (_instance_device_id[instance] != device_id)) { + _instance_slot_map[instance] = mapToSlot(device_id); + _instance_device_id[instance] = device_id; + } + + return _instance_slot_map[instance]; + } + + // a sensor without a device ID uses the slot of its uORB instance while no other sensor is bound to it + int8_t slotForInstanceWithFallback(uint8_t instance, uint32_t device_id) + { + const int8_t slot = slotForInstance(instance, device_id); + + if ((slot < 0) && (device_id == 0) && (instance < _num_slots) && !isSlotBound(instance)) { + return instance; + } + + return slot; + } + +private: + int8_t mapToSlot(uint32_t device_id) + { + if (device_id == 0) { + return -1; + } + + for (uint8_t slot = 0; slot < _num_slots; slot++) { + if (_ids[slot] == static_cast(device_id)) { + return slot; + } + } + + for (uint8_t slot = 0; slot < _num_slots; slot++) { + if (_ids[slot] == 0) { + const int32_t id = static_cast(device_id); + + _ids[slot] = id; + + if (param_set_no_notification(_id_param_handles[slot], &id) == PX4_OK) { + PX4_INFO("device ID %" PRIu32 " bound to %s", device_id, param_name(_id_param_handles[slot])); + + } else { + PX4_WARN("device ID %" PRIu32 " bound to slot %" PRIu8 " (not persisted)", device_id, slot); + } + + return slot; + } + } + + return -1; + } + + param_t _id_param_handles[kMaxSlots] {PARAM_INVALID, PARAM_INVALID, PARAM_INVALID, PARAM_INVALID}; + int32_t _ids[kMaxSlots] {}; + int8_t _instance_slot_map[kMaxSlots] {-1, -1, -1, -1}; + uint32_t _instance_device_id[kMaxSlots] {}; + uint8_t _num_slots{0}; +}; + +// One publication per slot. uORB numbers instances in advertise order and sensors arrive in any order, +// so every lower slot is advertised first to keep the uORB instance equal to the slot. +template +class SlotPublications +{ +public: + bool publish(uint8_t slot, const T &data) + { + if (slot >= N) { + return false; + } + + for (uint8_t i = 0; i <= slot; i++) { + if (!_pubs[i].advertised()) { + _pubs[i].advertise(); + } + } + + return _pubs[slot].publish(data); + } + +private: + struct Pub : public uORB::PublicationMulti { + Pub() : uORB::PublicationMulti(Id) {} + }; + + Pub _pubs[N] {}; +}; diff --git a/src/lib/sensor_slot_binder/SensorSlotBinderTest.cpp b/src/lib/sensor_slot_binder/SensorSlotBinderTest.cpp new file mode 100644 index 00000000000..77cbfa92027 --- /dev/null +++ b/src/lib/sensor_slot_binder/SensorSlotBinderTest.cpp @@ -0,0 +1,157 @@ +/**************************************************************************** + * + * Copyright (c) 2026 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +#include +#include + +static constexpr const char *kIdParamFormat = "SENS_FLOW%u_ID"; +static constexpr uint32_t kDeviceA = 0x0A0B01; +static constexpr uint32_t kDeviceB = 0x0A0B02; +static constexpr uint32_t kDeviceC = 0x0A0B03; + +class SensorSlotBinderTest : public ::testing::Test +{ +public: + void SetUp() override + { + param_control_autosave(false); + + for (uint8_t slot = 0; slot < 2; slot++) { + param_reset(idParamHandle(slot)); + } + } + + param_t idParamHandle(uint8_t slot) + { + char param_name[17] {}; + snprintf(param_name, sizeof(param_name), kIdParamFormat, static_cast(slot)); + return param_find(param_name); + } + + int32_t idParam(uint8_t slot) + { + int32_t id = 0; + param_get(idParamHandle(slot), &id); + return id; + } + + void setIdParam(uint8_t slot, int32_t id) + { + param_set_no_notification(idParamHandle(slot), &id); + } +}; + +TEST_F(SensorSlotBinderTest, bindsUnknownSensorsInArrivalOrder) +{ + SensorSlotBinder binder; + binder.init(kIdParamFormat, 2); + + // the first sensor reporting data takes the first free slot, whatever its uORB instance + EXPECT_EQ(binder.slotForInstance(1, kDeviceA), 0); + EXPECT_EQ(binder.slotForInstance(0, kDeviceB), 1); + + // and the assignment is persisted + EXPECT_EQ(idParam(0), static_cast(kDeviceA)); + EXPECT_EQ(idParam(1), static_cast(kDeviceB)); + EXPECT_TRUE(binder.isSlotBound(0)); + EXPECT_TRUE(binder.isSlotBound(1)); +} + +TEST_F(SensorSlotBinderTest, keepsPersistedBinding) +{ + setIdParam(1, kDeviceA); + + SensorSlotBinder binder; + binder.init(kIdParamFormat, 2); + + EXPECT_EQ(binder.slotForInstance(0, kDeviceA), 1); + EXPECT_EQ(binder.slotForInstance(1, kDeviceB), 0); +} + +TEST_F(SensorSlotBinderTest, rejectsSensorWithoutDeviceId) +{ + SensorSlotBinder binder; + binder.init(kIdParamFormat, 2); + + EXPECT_EQ(binder.slotForInstance(0, 0), -1); + EXPECT_FALSE(binder.isSlotBound(0)); + EXPECT_EQ(idParam(0), 0); +} + +TEST_F(SensorSlotBinderTest, fallsBackToInstanceWithoutDeviceId) +{ + SensorSlotBinder binder; + binder.init(kIdParamFormat, 2); + + // a sensor without a device ID keeps its uORB instance as long as that slot is free + EXPECT_EQ(binder.slotForInstanceWithFallback(1, 0), 1); + EXPECT_FALSE(binder.isSlotBound(1)); + + // but never takes a slot bound to another sensor + EXPECT_EQ(binder.slotForInstanceWithFallback(0, kDeviceA), 0); + EXPECT_EQ(binder.slotForInstanceWithFallback(1, kDeviceB), 1); + EXPECT_EQ(binder.slotForInstanceWithFallback(1, 0), -1); +} + +TEST_F(SensorSlotBinderTest, followsDeviceChangeOnInstance) +{ + SensorSlotBinder binder; + binder.init(kIdParamFormat, 2); + + EXPECT_EQ(binder.slotForInstance(0, kDeviceA), 0); + EXPECT_EQ(binder.slotForInstance(0, kDeviceB), 1); + EXPECT_EQ(binder.slotForInstance(0, kDeviceA), 0); +} + +TEST_F(SensorSlotBinderTest, rejectsSensorWhenAllSlotsBound) +{ + SensorSlotBinder binder; + binder.init(kIdParamFormat, 2); + + EXPECT_EQ(binder.slotForInstance(0, kDeviceA), 0); + EXPECT_EQ(binder.slotForInstance(1, kDeviceB), 1); + EXPECT_EQ(binder.slotForInstance(0, kDeviceC), -1); + EXPECT_EQ(binder.slotForInstance(1, kDeviceB), 1); +} + +TEST_F(SensorSlotBinderTest, claimsSlotWhenBindingCannotBePersisted) +{ + // no such parameter: the binding lives in RAM only + SensorSlotBinder binder; + binder.init("NOPARAM%u_ID", 2); + + // a second sensor must not share the slot of the first one + EXPECT_EQ(binder.slotForInstance(0, kDeviceA), 0); + EXPECT_EQ(binder.slotForInstance(1, kDeviceB), 1); + EXPECT_TRUE(binder.isSlotBound(0)); +} diff --git a/src/modules/commander/HealthAndArmingChecks/checks/opticalFlowCheck.cpp b/src/modules/commander/HealthAndArmingChecks/checks/opticalFlowCheck.cpp index c01c8cf5655..2960377bed7 100644 --- a/src/modules/commander/HealthAndArmingChecks/checks/opticalFlowCheck.cpp +++ b/src/modules/commander/HealthAndArmingChecks/checks/opticalFlowCheck.cpp @@ -39,11 +39,19 @@ void OpticalFlowCheck::checkAndReport(const Context &context, Report &reporter) return; } - const bool exists = _vehicle_optical_flow_sub.advertised(); + bool exists = false; + bool valid = false; + + for (auto &sub : _vehicle_optical_flow_subs) { + if (sub.advertised()) { + exists = true; + + vehicle_optical_flow_s flow_sens; + valid |= sub.copy(&flow_sens) && (hrt_elapsed_time(&flow_sens.timestamp) < 1_s); + } + } if (exists) { - vehicle_optical_flow_s flow_sens; - const bool valid = _vehicle_optical_flow_sub.copy(&flow_sens) && (hrt_elapsed_time(&flow_sens.timestamp) < 1_s); reporter.setIsPresent(health_component_t::optical_flow); if (!valid) { diff --git a/src/modules/commander/HealthAndArmingChecks/checks/opticalFlowCheck.hpp b/src/modules/commander/HealthAndArmingChecks/checks/opticalFlowCheck.hpp index 4eaa47f1f41..647b3ea949e 100644 --- a/src/modules/commander/HealthAndArmingChecks/checks/opticalFlowCheck.hpp +++ b/src/modules/commander/HealthAndArmingChecks/checks/opticalFlowCheck.hpp @@ -35,7 +35,7 @@ #include "../Common.hpp" -#include +#include #include class OpticalFlowCheck : public HealthAndArmingCheckBase @@ -47,7 +47,7 @@ public: void checkAndReport(const Context &context, Report &reporter) override; private: - uORB::Subscription _vehicle_optical_flow_sub{ORB_ID::vehicle_optical_flow}; + uORB::SubscriptionMultiArray _vehicle_optical_flow_subs{ORB_ID::vehicle_optical_flow}; DEFINE_PARAMETERS_CUSTOM_PARENT(HealthAndArmingCheckBase, (ParamInt) _param_sys_has_num_of diff --git a/src/modules/ekf2/CMakeLists.txt b/src/modules/ekf2/CMakeLists.txt index f44b6259274..bee6befc153 100644 --- a/src/modules/ekf2/CMakeLists.txt +++ b/src/modules/ekf2/CMakeLists.txt @@ -203,6 +203,7 @@ endif() if(CONFIG_EKF2_OPTICAL_FLOW) list(APPEND EKF_SRCS + EKF/aid_sources/optical_flow/optical_flow.cpp EKF/aid_sources/optical_flow/optical_flow_control.cpp EKF/aid_sources/optical_flow/optical_flow_fusion.cpp ) diff --git a/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow.cpp b/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow.cpp new file mode 100644 index 00000000000..3b56e3d1695 --- /dev/null +++ b/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow.cpp @@ -0,0 +1,192 @@ +/**************************************************************************** + * + * Copyright (c) 2026 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +#include "ekf.h" + +#if defined(CONFIG_EKF2_OPTICAL_FLOW) && defined(MODULE_NAME) + +#include + +using namespace time_literals; +using matrix::Vector2f; +using matrix::Vector3f; + +void OpticalFlowSource::initParams() +{ + char param_name[20] {}; + snprintf(param_name, sizeof(param_name), "EKF2_OF%d_CTRL", _slot); + _param_handles.ctrl = param_find(param_name); + + snprintf(param_name, sizeof(param_name), "SENS_FLOW%d_DELAY", _slot); + _param_handles.delay = param_find(param_name); + + updateParams(); +} + +void OpticalFlowSource::updateParams() +{ + if (_param_handles.ctrl == PARAM_INVALID) { + return; + } + + param_get(_param_handles.ctrl, ¶ms.ctrl); + + // the tuning of a disabled slot stays hidden from the GCS until the slot is enabled + if (params.ctrl == 0) { + return; + } + + if (_param_handles.gyr_src == PARAM_INVALID) { + char param_name[20] {}; + + snprintf(param_name, sizeof(param_name), "EKF2_OF%d_GYR_SRC", _slot); + _param_handles.gyr_src = param_find(param_name); + + snprintf(param_name, sizeof(param_name), "EKF2_OF%d_N_MIN", _slot); + _param_handles.n_min = param_find(param_name); + + snprintf(param_name, sizeof(param_name), "EKF2_OF%d_N_MAX", _slot); + _param_handles.n_max = param_find(param_name); + + snprintf(param_name, sizeof(param_name), "EKF2_OF%d_QMIN", _slot); + _param_handles.qmin = param_find(param_name); + + snprintf(param_name, sizeof(param_name), "EKF2_OF%d_QMINGND", _slot); + _param_handles.qmin_gnd = param_find(param_name); + + snprintf(param_name, sizeof(param_name), "EKF2_OF%d_GATE", _slot); + _param_handles.gate = param_find(param_name); + } + + param_get(_param_handles.gyr_src, ¶ms.gyr_src); + param_get(_param_handles.n_min, ¶ms.n_min); + param_get(_param_handles.n_max, ¶ms.n_max); + param_get(_param_handles.qmin, ¶ms.qmin); + param_get(_param_handles.qmin_gnd, ¶ms.qmin_gnd); + param_get(_param_handles.gate, ¶ms.gate); +} + +float OpticalFlowSource::delayMs() const +{ + // read live, EKF2 checks the delays before the EKF parameters are updated + int32_t ctrl = 0; + float delay_ms = 0.f; + + if ((param_get(_param_handles.ctrl, &ctrl) == PX4_OK) && (ctrl != 0)) { + param_get(_param_handles.delay, &delay_ms); + } + + return delay_ms; +} + +bool OpticalFlowSource::updateSample(Ekf &ekf, vehicle_optical_flow_s &optical_flow) +{ + if (!_sub.update(&optical_flow)) { + return false; + } + + const float dt = 1e-6f * (float)optical_flow.integration_timespan_us; + Vector2f flow_rate; + Vector3f gyro_rate; + + if (dt > FLT_EPSILON) { + // NOTE: the EKF uses the reverse sign convention to the flow sensor. EKF assumes positive LOS rate + // is produced by a RH rotation of the image about the sensor axis. + flow_rate = Vector2f(-optical_flow.pixel_flow[0], -optical_flow.pixel_flow[1]) / dt; + gyro_rate = Vector3f(-optical_flow.delta_angle[0], -optical_flow.delta_angle[1], -optical_flow.delta_angle[2]) / dt; + + } else if (optical_flow.quality == 0) { + // handle special case of SITL and PX4Flow where dt is forced to zero when the quaity is 0 + flow_rate.zero(); + gyro_rate.zero(); + } + + estimator::flowSample flow { + .time_us = optical_flow.timestamp_sample - optical_flow.integration_timespan_us / 2, // correct timestamp to midpoint of integration interval as the data is converted to rates + .flow_rate = flow_rate, + .gyro_rate = gyro_rate, + .quality = optical_flow.quality, + .device_id = optical_flow.device_id + }; + + if (Vector2f(optical_flow.pixel_flow).isAllFinite() && optical_flow.integration_timespan_us < 1e6) { + setLimits(optical_flow.max_flow_rate, optical_flow.min_ground_distance, optical_flow.max_ground_distance); + setPositionBody(Vector3f(optical_flow.position_offset)); + setData(flow, ekf._imu_buffer_length, ekf._min_obs_interval_us, ekf._dt_ekf_avg); + } + + return true; +} + +void OpticalFlowAiding::updateParams() +{ + for (auto &source : _sources) { + source.updateParams(); + } +} + +void OpticalFlowAiding::updateSamples(Ekf &ekf) +{ + for (uint8_t slot = 0; slot < estimator::MAX_OF_INSTANCES; slot++) { + vehicle_optical_flow_s optical_flow; + + if (!_sources[slot].updateSample(ekf, optical_flow)) { + continue; + } + +#if defined(CONFIG_EKF2_RANGE_FINDER) + + if ((_range_instance < 0) && PX4_ISFINITE(optical_flow.distance_m) && (optical_flow.distance_m > 0.f)) { + _range_instance = slot; + } + + // the distance measured by the flow sensor substitutes a missing range finder + if ((slot == _range_instance) && PX4_ISFINITE(optical_flow.distance_m) + && !ekf.isNewestSampleRecent(ekf._time_last_range_sensor_data, 1_s)) { + + int8_t quality = static_cast(optical_flow.quality) / static_cast(UINT8_MAX) * 100.f; + + estimator::sensor::rangeSample range_sample { + .time_us = optical_flow.timestamp_sample, + .rng = optical_flow.distance_m, + .quality = quality, + }; + ekf.pushRangeData(range_sample); + ekf.set_rangefinder_limits(optical_flow.min_ground_distance, optical_flow.max_ground_distance); + } + +#endif // CONFIG_EKF2_RANGE_FINDER + } +} + +#endif // CONFIG_EKF2_OPTICAL_FLOW && MODULE_NAME diff --git a/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow_control.cpp b/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow_control.cpp index 523f75f4dcc..e8191dacb74 100644 --- a/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow_control.cpp +++ b/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow_control.cpp @@ -40,65 +40,242 @@ #include -void Ekf::controlOpticalFlowFusion(const imuSample &imu_delayed) +void OpticalFlowAiding::update(Ekf &ekf, const imuSample &imu_delayed) { - _fc.of.available = (_params.ekf2_of_ctrl != 0); +#if defined(MODULE_NAME) + updateSamples(ekf); +#endif // MODULE_NAME - if (!_flow_buffer || !_fc.of.intended()) { - stopFlowFusion(); + bool any_ctrl_enabled = false; + + for (uint8_t slot = 0; slot < MAX_OF_INSTANCES; slot++) { + any_ctrl_enabled |= (_sources[slot].params.ctrl != 0); + } + + ekf._fc.of.available = any_ctrl_enabled; + + for (uint8_t slot = 0; slot < MAX_OF_INSTANCES; slot++) { + bool other_slot_fusing = false; + + for (uint8_t other = 0; other < MAX_OF_INSTANCES; other++) { + other_slot_fusing |= (other != slot) && _sources[other].isFusing(ekf); + } + + _sources[slot].update(ekf, imu_delayed, other_slot_fusing); + } + + bool any_active = false; + bool any_terrain = false; + + for (uint8_t i = 0; i < MAX_OF_INSTANCES; i++) { + any_active |= _sources[i]._active; + any_terrain |= _sources[i]._terrain; + } + + ekf._control_status.flags.opt_flow = any_active; + ekf._control_status.flags.opt_flow_terrain = any_terrain; + + if (!any_active) { + ekf._fault_status.flags.bad_optflow_X = false; + ekf._fault_status.flags.bad_optflow_Y = false; + } +} + +uint8_t OpticalFlowAiding::primarySlot() const +{ + for (uint8_t i = 0; i < MAX_OF_INSTANCES; i++) { + if (_sources[i]._active) { + return i; + } + } + + for (uint8_t i = 0; i < MAX_OF_INSTANCES; i++) { + if (_sources[i]._aid_src.timestamp_sample != 0) { + return i; + } + } + + return 0; +} + +uint64_t OpticalFlowAiding::timeLastFuse() const +{ + uint64_t latest = 0; + + for (uint8_t i = 0; i < MAX_OF_INSTANCES; i++) { + latest = math::max(latest, _sources[i]._aid_src.time_last_fuse); + } + + return latest; +} + +uint64_t OpticalFlowAiding::latestSampleTimestamp() const +{ + uint64_t latest = 0; + + for (uint8_t i = 0; i < MAX_OF_INSTANCES; i++) { + latest = math::max(latest, _sources[i]._aid_src.timestamp_sample); + } + + return latest; +} + +float OpticalFlowAiding::maxActiveInnovNorm() const +{ + float innov_norm = 0.f; + + for (uint8_t i = 0; i < MAX_OF_INSTANCES; i++) { + if (_sources[i]._active) { + innov_norm = math::max(innov_norm, Vector2f(_sources[i]._aid_src.innovation).norm()); + } + } + + return innov_norm; +} + +float OpticalFlowAiding::maxActiveTestRatioFiltered() const +{ + float test_ratio = 0.f; + + for (uint8_t i = 0; i < MAX_OF_INSTANCES; i++) { + if (_sources[i]._active) { + for (const auto &test_ratio_filtered : _sources[i]._aid_src.test_ratio_filtered) { + test_ratio = math::max(test_ratio, fabsf(test_ratio_filtered)); + } + } + } + + return test_ratio; +} + +void OpticalFlowAiding::getLimits(const Ekf &ekf, float &hagl_min, float &hagl_max, float &max_rate) const +{ + // combined envelope of all sensors currently delivering data + // (sensors with different ranges hand over as the height changes) + hagl_min = INFINITY; + hagl_max = 0.f; + max_rate = 0.f; + bool any_flow_source = false; + + for (uint8_t i = 0; i < MAX_OF_INSTANCES; i++) { + if (ekf._fc.of.intended() && (_sources[i].params.ctrl != 0) + && ekf.isRecent(_sources[i]._time_last_data, (uint64_t)1e6)) { + hagl_min = math::min(hagl_min, _sources[i]._min_distance); + hagl_max = math::max(hagl_max, _sources[i]._max_distance); + max_rate = math::max(max_rate, _sources[i]._max_rate); + any_flow_source = true; + } + } + + if (!any_flow_source) { + // no flow source delivering data, fall back to the primary slot's limits + const uint8_t slot = primarySlot(); + hagl_min = _sources[slot]._min_distance; + hagl_max = _sources[slot]._max_distance; + max_rate = _sources[slot]._max_rate; + } +} + +void OpticalFlowSource::setData(const flowSample &flow, const uint8_t buffer_length, const uint64_t min_obs_interval_us, + const float dt_ekf_avg) +{ + if (params.ctrl == 0) { return; } - VectorState H; + // allocated on the first sample of an enabled slot, so that a slot can be enabled at runtime + if (_buffer == nullptr) { + _buffer = new TimestampedRingBuffer(buffer_length); + + if (_buffer == nullptr || !_buffer->valid()) { + delete _buffer; + _buffer = nullptr; + ECL_ERR("optical flow %d buffer allocation failed", _slot); + return; + } + } + + // the measurement delay is already compensated in the sample timestamp (SENS_FLOW_DELAY) + const int64_t time_us = flow.time_us + - static_cast(dt_ekf_avg * 5e5f); // seconds to microseconds divided by 2 + + // limit data rate to prevent data being lost + if (time_us >= static_cast(_buffer->get_newest().time_us + min_obs_interval_us)) { + + flowSample optflow_sample_new{flow}; + optflow_sample_new.time_us = time_us; + + _buffer->push(optflow_sample_new); + _time_last_data = optflow_sample_new.time_us; + + } else { + ECL_WARN("optical flow %d data too fast %" PRIi64 " < %" PRIu64 " + %" PRIu64, _slot, time_us, + _buffer->get_newest().time_us, min_obs_interval_us); + } +} + +bool OpticalFlowSource::isFusing(const Ekf &ekf) const +{ + return _active && !ekf.isTimedOut(_aid_src.time_last_fuse, ekf._params.no_aid_timeout_max); +} + +void OpticalFlowSource::update(Ekf &ekf, const imuSample &imu_delayed, const bool other_slot_fusing) +{ + if (!_buffer || !ekf._fc.of.intended() || (params.ctrl == 0)) { + stop(); + return; + } + + Ekf::VectorState H; // New optical flow data is available and is ready to be fused when the midpoint of the sample falls behind the fusion time horizon - if (_flow_buffer->pop_first_older_than(imu_delayed.time_us, &_flow_sample_delayed)) { + if (_buffer->pop_first_older_than(imu_delayed.time_us, &_sample_delayed)) { // flow gyro has opposite sign convention - _ref_body_rate = -(imu_delayed.delta_ang / imu_delayed.delta_ang_dt - getGyroBias()); + _ref_body_rate = -(imu_delayed.delta_ang / imu_delayed.delta_ang_dt - ekf.getGyroBias()); // ensure valid flow sample gyro rate before proceeding - switch (static_cast(_params.ekf2_of_gyr_src)) { + switch (static_cast(params.gyr_src)) { default: /* FALLTHROUGH */ case FlowGyroSource::Auto: - if (!PX4_ISFINITE(_flow_sample_delayed.gyro_rate(0)) || !PX4_ISFINITE(_flow_sample_delayed.gyro_rate(1))) { - _flow_sample_delayed.gyro_rate = _ref_body_rate; + if (!PX4_ISFINITE(_sample_delayed.gyro_rate(0)) || !PX4_ISFINITE(_sample_delayed.gyro_rate(1))) { + _sample_delayed.gyro_rate = _ref_body_rate; } - if (!PX4_ISFINITE(_flow_sample_delayed.gyro_rate(2))) { + if (!PX4_ISFINITE(_sample_delayed.gyro_rate(2))) { // Some flow modules only provide X ind Y angular rates. If this is the case, complete the vector with our own Z gyro - _flow_sample_delayed.gyro_rate(2) = _ref_body_rate(2); + _sample_delayed.gyro_rate(2) = _ref_body_rate(2); } break; case FlowGyroSource::Internal: - _flow_sample_delayed.gyro_rate = _ref_body_rate; + _sample_delayed.gyro_rate = _ref_body_rate; break; } - const flowSample &flow_sample = _flow_sample_delayed; + const flowSample &flow_sample = _sample_delayed; - const int32_t min_quality = _control_status.flags.in_air - ? _params.ekf2_of_qmin - : _params.ekf2_of_qmin_gnd; + const int32_t min_quality = ekf._control_status.flags.in_air + ? params.qmin + : params.qmin_gnd; const bool is_quality_good = (flow_sample.quality >= min_quality); bool is_tilt_good = true; #if defined(CONFIG_EKF2_RANGE_FINDER) - is_tilt_good = (_R_to_earth(2, 2) > _params.range_cos_max_tilt); + is_tilt_good = (ekf._R_to_earth(2, 2) > ekf._params.range_cos_max_tilt); #endif // CONFIG_EKF2_RANGE_FINDER - calcOptFlowBodyRateComp(flow_sample); + calcBodyRateComp(); // calculate optical LOS rates using optical flow rates that have had the body angular rate contribution removed // correct for gyro bias errors in the data used to do the motion compensation // Note the sign convention used: A positive LOS rate is a RH rotation of the scene about that axis. - const Vector3f flow_gyro_corrected = flow_sample.gyro_rate - _flow_gyro_bias; + const Vector3f flow_gyro_corrected = flow_sample.gyro_rate - _gyro_bias; const Vector2f flow_compensated = flow_sample.flow_rate - flow_gyro_corrected.xy(); // calculate the optical flow observation variance @@ -106,197 +283,194 @@ void Ekf::controlOpticalFlowFusion(const imuSample &imu_delayed) const float epsilon = 1e-3f; Vector2f innov_var; - sym::ComputeFlowXyInnovVarAndHx(_state.vector(), P, R_LOS, epsilon, &innov_var, &H); + sym::ComputeFlowXyInnovVarAndHx(ekf._state.vector(), ekf.P, R_LOS, epsilon, &innov_var, &H); + + _aid_src.device_id = flow_sample.device_id; // run the innovation consistency check and record result - updateAidSourceStatus(_aid_src_optical_flow, - flow_sample.time_us, // sample timestamp - flow_compensated, // observation - Vector2f{R_LOS, R_LOS}, // observation variance - predictFlow(flow_gyro_corrected) - flow_compensated, // innovation - innov_var, // innovation variance - math::max(_params.ekf2_of_gate, 1.f)); // innovation gate + ekf.updateAidSourceStatus(_aid_src, + flow_sample.time_us, // sample timestamp + flow_compensated, // observation + Vector2f{R_LOS, R_LOS}, // observation variance + ekf.predictFlow(_pos_body, flow_gyro_corrected) - flow_compensated, // innovation + innov_var, // innovation variance + math::max(params.gate, 1.f)); // innovation gate // logging - _flow_rate_compensated = flow_compensated; + _rate_compensated = flow_compensated; // compute the velocities in body and local frames from corrected optical flow measurement for logging only - const float range = predictFlowRange(); - _flow_vel_body(0) = -flow_compensated(1) * range; - _flow_vel_body(1) = flow_compensated(0) * range; + const float range = ekf.predictFlowRange(_pos_body); + _vel_body(0) = -flow_compensated(1) * range; + _vel_body(1) = flow_compensated(0) * range; - if (_flow_counter == 0) { - _flow_vel_body_lpf.reset(_flow_vel_body); - _flow_rate_compensated_lpf.reset(_flow_rate_compensated); - _flow_lpf_time_last_us = flow_sample.time_us; - _flow_counter = 1; + if (_counter == 0) { + _vel_body_lpf.setParameters(ekf._dt_ekf_avg, ekf._kSensorLpfTimeConstant); + _rate_compensated_lpf.setParameters(ekf._dt_ekf_avg, ekf._kSensorLpfTimeConstant); + + _vel_body_lpf.reset(_vel_body); + _rate_compensated_lpf.reset(_rate_compensated); + _lpf_time_last_us = flow_sample.time_us; + _counter = 1; } else { // the filters run once per flow sample, not once per EKF update - const uint64_t flow_dt_us = flow_sample.time_us - _flow_lpf_time_last_us; - _flow_vel_body_lpf.update(_flow_vel_body, flow_dt_us); - _flow_rate_compensated_lpf.update(_flow_rate_compensated, flow_dt_us); - _flow_lpf_time_last_us = flow_sample.time_us; - _flow_counter++; + const uint64_t flow_dt_us = flow_sample.time_us - _lpf_time_last_us; + _vel_body_lpf.update(_vel_body, flow_dt_us); + _rate_compensated_lpf.update(_rate_compensated, flow_dt_us); + _lpf_time_last_us = flow_sample.time_us; + _counter++; } // Check if we are in-air and require optical flow to control position drift - bool is_flow_required = _control_status.flags.in_air - && (_control_status.flags.inertial_dead_reckoning // is doing inertial dead-reckoning so must constrain drift urgently - || isOnlyActiveSourceOfHorizontalAiding(_control_status.flags.opt_flow)); + bool is_flow_required = ekf._control_status.flags.in_air + && (ekf._control_status.flags.inertial_dead_reckoning // is doing inertial dead-reckoning so must constrain drift urgently + || ekf.isOnlyActiveSourceOfHorizontalAiding(ekf._control_status.flags.opt_flow)); - const bool is_within_sensor_dist = (getHagl() >= _flow_min_distance) && (getHagl() <= _flow_max_distance); + const bool is_within_sensor_dist = (ekf.getHagl() >= _min_distance) && (ekf.getHagl() <= _max_distance); const bool is_magnitude_good = flow_sample.flow_rate.isAllFinite() - && !flow_sample.flow_rate.longerThan(_flow_max_rate) - && !flow_compensated.longerThan(_flow_max_rate); + && !flow_sample.flow_rate.longerThan(_max_rate) + && !flow_compensated.longerThan(_max_rate); - const bool continuing_conditions_passing = _fc.of.intended() - && _control_status.flags.tilt_align + const bool continuing_conditions_passing = ekf._fc.of.intended() && (params.ctrl != 0) + && ekf._control_status.flags.tilt_align && is_within_sensor_dist; const bool starting_conditions_passing = continuing_conditions_passing && is_quality_good && is_magnitude_good && is_tilt_good - && (_flow_counter > 10) - && (isHeightAboveGroundEstimateValid() || isHorizontalAidingActive()) - && isTimedOut(_aid_src_optical_flow.time_last_fuse, (uint64_t)2e6); // Prevent rapid switching + && (_counter > 10) + && (ekf.isHeightAboveGroundEstimateValid() || ekf.isHorizontalAidingActive()) + && ekf.isTimedOut(_aid_src.time_last_fuse, (uint64_t)2e6); // Prevent rapid switching // If the height is relative to the ground, terrain height cannot be observed. - _control_status.flags.opt_flow_terrain = _control_status.flags.opt_flow && !(_height_sensor_ref == HeightSensor::RANGE); + _terrain = _active && !(ekf._height_sensor_ref == HeightSensor::RANGE); - if (_control_status.flags.opt_flow) { + if (_active) { if (continuing_conditions_passing) { if (is_quality_good && is_magnitude_good && is_tilt_good) { - fuseOptFlow(H, _control_status.flags.opt_flow_terrain); + fuse(ekf, H, _terrain); } // handle the case when we have optical flow, are reliant on it, but have not been using it for an extended period - if (isTimedOut(_aid_src_optical_flow.time_last_fuse, _params.no_aid_timeout_max)) { - if (is_flow_required && is_quality_good && is_magnitude_good) { - resetFlowFusion(flow_sample); + // (if another flow sensor is still being fused, this one is the inconsistent one and must not reset the state) + if (ekf.isTimedOut(_aid_src.time_last_fuse, ekf._params.no_aid_timeout_max)) { + if (is_flow_required && is_quality_good && is_magnitude_good && !other_slot_fusing) { + reset(ekf); - if (_control_status.flags.opt_flow_terrain && !isTerrainEstimateValid()) { - resetTerrainToFlow(); + if (_terrain && !ekf.isTerrainEstimateValid()) { + resetTerrain(ekf); } } else { - stopFlowFusion(); + stop(); } } } else { - stopFlowFusion(); + stop(); } } else { if (starting_conditions_passing) { // If the height is relative to the ground, terrain height cannot be observed. - _control_status.flags.opt_flow_terrain = (_height_sensor_ref != HeightSensor::RANGE); + const bool terrain_observable = (ekf._height_sensor_ref != HeightSensor::RANGE); - if (isHorizontalAidingActive()) { - if (fuseOptFlow(H, _control_status.flags.opt_flow_terrain)) { - ECL_INFO("starting optical flow"); - _control_status.flags.opt_flow = true; + // another slot may have started during this update, before the aiding flags are updated + if (ekf.isHorizontalAidingActive() || other_slot_fusing) { + if (fuse(ekf, H, terrain_observable)) { + ECL_INFO("starting optical flow %d", _slot); + _active = true; - } else if (_control_status.flags.opt_flow_terrain && !_control_status.flags.rng_terrain) { - ECL_INFO("starting optical flow, resetting terrain"); - resetTerrainToFlow(); - _control_status.flags.opt_flow = true; + } else if (terrain_observable && !ekf._control_status.flags.rng_terrain && !other_slot_fusing) { + // only when no other flow sensor observes the terrain, otherwise retry on the next sample + ECL_INFO("starting optical flow %d, resetting terrain", _slot); + resetTerrain(ekf); + _active = true; } } else { - if (isHeightAboveGroundEstimateValid()) { - ECL_INFO("starting optical flow, resetting"); - resetFlowFusion(flow_sample); - _control_status.flags.opt_flow = true; + if (ekf.isHeightAboveGroundEstimateValid()) { + ECL_INFO("starting optical flow %d, resetting", _slot); + reset(ekf); + _active = true; - } else if (_control_status.flags.opt_flow_terrain) { - ECL_INFO("starting optical flow, resetting terrain"); - resetTerrainToFlow(); - _control_status.flags.opt_flow = true; + } else if (terrain_observable) { + ECL_INFO("starting optical flow %d, resetting terrain", _slot); + resetTerrain(ekf); + _active = true; } } - _control_status.flags.opt_flow_terrain = _control_status.flags.opt_flow && !(_height_sensor_ref == HeightSensor::RANGE); + _terrain = _active && terrain_observable; } } - } else if (_control_status.flags.opt_flow && isTimedOut(_flow_sample_delayed.time_us, _params.reset_timeout_max)) { - stopFlowFusion(); + + } else if (_active && ekf.isTimedOut(_sample_delayed.time_us, ekf._params.reset_timeout_max)) { + stop(); } } -void Ekf::resetFlowFusion(const flowSample &flow_sample) +bool OpticalFlowSource::fuse(Ekf &ekf, Ekf::VectorState &H, const bool update_terrain) { - ECL_INFO("reset velocity to flow"); - _information_events.flags.reset_vel_to_flow = true; - - const float flow_vel_var = sq(predictFlowRange()) * calcOptFlowMeasVar(flow_sample); - resetHorizontalVelocityTo(getFilteredFlowVelNE(), flow_vel_var); - - resetAidSourceStatusZeroInnovation(_aid_src_optical_flow); + return ekf.fuseOptFlow(_aid_src, H, update_terrain); } -void Ekf::resetTerrainToFlow() +void OpticalFlowSource::reset(Ekf &ekf) { - ECL_INFO("reset hagl to flow"); + ECL_INFO("reset velocity to flow %d", _slot); + ekf._information_events.flags.reset_vel_to_flow = true; - float new_terrain = -_gpos.altitude() + _params.ekf2_min_rng; + const float flow_vel_var = sq(ekf.predictFlowRange(_pos_body)) * calcOptFlowMeasVar(_sample_delayed); + ekf.resetHorizontalVelocityTo(ekf.getFilteredFlowVelNE(_slot), flow_vel_var); - if (isOtherSourceOfHorizontalAidingThan(_control_status.flags.opt_flow)) { + ekf.resetAidSourceStatusZeroInnovation(_aid_src); +} + +void OpticalFlowSource::resetTerrain(Ekf &ekf) +{ + ECL_INFO("reset hagl to flow %d", _slot); + + float new_terrain = -ekf._gpos.altitude() + ekf._params.ekf2_min_rng; + + if (ekf.isOtherSourceOfHorizontalAidingThan(ekf._control_status.flags.opt_flow)) { // ||vel_NE|| = ||( R * flow_body * range).xy()|| // range = ||vel_NE|| / ||P * R * flow_body|| constexpr float kProjXY[2][3] = {{1.f, 0.f, 0.f}, {0.f, 1.f, 0.f}}; const matrix::Matrix proj(kProjXY); - const Vector3f flow_body(-_flow_rate_compensated_lpf.getState()(1), _flow_rate_compensated_lpf.getState()(0), 0.f); - const float denom = Vector2f(proj * _R_to_earth * flow_body).norm(); + const Vector3f flow_body(-_rate_compensated_lpf.getState()(1), _rate_compensated_lpf.getState()(0), 0.f); + const float denom = Vector2f(proj * ekf._R_to_earth * flow_body).norm(); if (denom > 1e-6f) { - const float range = _state.vel.xy().norm() / denom; - new_terrain = -_gpos.altitude() + max(range, _params.ekf2_min_rng); + const float range = ekf._state.vel.xy().norm() / denom; + new_terrain = -ekf._gpos.altitude() + math::max(range, ekf._params.ekf2_min_rng); } } - const float delta_terrain = new_terrain - _state.terrain; - _state.terrain = new_terrain; - P.uncorrelateCovarianceSetVariance(State::terrain.idx, 100.f); - - resetAidSourceStatusZeroInnovation(_aid_src_optical_flow); - - // record the state change - if (_state_reset_status.reset_count.hagl == _state_reset_count_prev.hagl) { - _state_reset_status.hagl_change = delta_terrain; - - } else { - // there's already a reset this update, accumulate total delta - _state_reset_status.hagl_change += delta_terrain; - } - - _state_reset_status.reset_count.hagl++; + ekf.resetTerrainTo(new_terrain, 100.f); + ekf.resetAidSourceStatusZeroInnovation(_aid_src); } -void Ekf::stopFlowFusion() +void OpticalFlowSource::stop() { - if (_control_status.flags.opt_flow) { - ECL_INFO("stopping optical flow fusion"); - _control_status.flags.opt_flow = false; - _control_status.flags.opt_flow_terrain = false; + if (_active) { + ECL_INFO("stopping optical flow fusion %d", _slot); + _active = false; + _terrain = false; - _fault_status.flags.bad_optflow_X = false; - _fault_status.flags.bad_optflow_Y = false; - - _flow_counter = 0; + _counter = 0; } } -void Ekf::calcOptFlowBodyRateComp(const flowSample &flow_sample) +void OpticalFlowSource::calcBodyRateComp() { // calculate the bias estimate using a combined LPF and spike filter - _flow_gyro_bias = 0.99f * _flow_gyro_bias - + 0.01f * matrix::constrain(flow_sample.gyro_rate - _ref_body_rate, -0.1f, 0.1f); + _gyro_bias = 0.99f * _gyro_bias + + 0.01f * matrix::constrain(_sample_delayed.gyro_rate - _ref_body_rate, -0.1f, 0.1f); } diff --git a/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow_fusion.cpp b/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow_fusion.cpp index 38a5a853ece..24fee2f4bff 100644 --- a/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow_fusion.cpp +++ b/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow_fusion.cpp @@ -42,12 +42,12 @@ #include #include -bool Ekf::fuseOptFlow(VectorState &H, const bool update_terrain) +bool Ekf::fuseOptFlow(estimator_aid_source2d_s &aid_src, VectorState &H, const bool update_terrain) { const auto state_vector = _state.vector(); // if either axis fails we abort the fusion - if (_aid_src_optical_flow.innovation_rejected) { + if (aid_src.innovation_rejected) { return false; } @@ -60,12 +60,12 @@ bool Ekf::fuseOptFlow(VectorState &H, const bool update_terrain) } else if (index == 1) { // recalculate innovation variance because state covariances have changed due to previous fusion (linearise using the same initial state for all axes) - const float R_LOS = _aid_src_optical_flow.observation_variance[1]; + const float R_LOS = aid_src.observation_variance[1]; const float epsilon = 1e-3f; - sym::ComputeFlowYInnovVarAndH(state_vector, P, R_LOS, epsilon, &_aid_src_optical_flow.innovation_variance[1], &H); + sym::ComputeFlowYInnovVarAndH(state_vector, P, R_LOS, epsilon, &aid_src.innovation_variance[1], &H); } - if (_aid_src_optical_flow.innovation_variance[index] < _aid_src_optical_flow.observation_variance[index]) { + if (aid_src.innovation_variance[index] < aid_src.observation_variance[index]) { // we need to reinitialise the covariance matrix and abort this fusion step ECL_ERR("Opt flow error - covariance reset"); @@ -75,14 +75,14 @@ bool Ekf::fuseOptFlow(VectorState &H, const bool update_terrain) return false; } - VectorState Kfusion = computeKalmanGain(H, _aid_src_optical_flow.innovation_variance[index]); + VectorState Kfusion = computeKalmanGain(H, aid_src.innovation_variance[index]); if (!update_terrain) { Kfusion(State::terrain.idx) = 0.f; } - accumulateMeasurementUpdate(Kfusion, H, _aid_src_optical_flow.observation_variance[index], - _aid_src_optical_flow.innovation[index], state_correction); + accumulateMeasurementUpdate(Kfusion, H, aid_src.observation_variance[index], aid_src.innovation[index], + state_correction); } applyStateCorrection(state_correction); @@ -90,8 +90,8 @@ bool Ekf::fuseOptFlow(VectorState &H, const bool update_terrain) _fault_status.flags.bad_optflow_X = false; _fault_status.flags.bad_optflow_Y = false; - _aid_src_optical_flow.time_last_fuse = _time_delayed_us; - _aid_src_optical_flow.fused = true; + aid_src.time_last_fuse = _time_delayed_us; + aid_src.fused = true; _time_last_hor_vel_fuse = _time_delayed_us; @@ -102,10 +102,10 @@ bool Ekf::fuseOptFlow(VectorState &H, const bool update_terrain) return true; } -float Ekf::predictFlowHagl() const +float Ekf::predictFlowHagl(const Vector3f &sensor_pos_body) const { // calculate the sensor position relative to the IMU - const Vector3f pos_offset_body = _params.flow_pos_body - _params.imu_pos_body; + const Vector3f pos_offset_body = sensor_pos_body - _params.imu_pos_body; // calculate the sensor position relative to the IMU in earth frame const Vector3f pos_offset_earth = _R_to_earth * pos_offset_body; @@ -120,17 +120,18 @@ float Ekf::predictFlowHagl() const return fmaxf(height_above_gnd_est, min_hagl); } -float Ekf::predictFlowRange() const + +float Ekf::predictFlowRange(const Vector3f &sensor_pos_body) const { // calculate range from focal point to centre of image // absolute distance to the frame region in view - return predictFlowHagl() / _R_to_earth(2, 2); + return predictFlowHagl(sensor_pos_body) / _R_to_earth(2, 2); } -Vector2f Ekf::predictFlow(const Vector3f &flow_gyro) const +Vector2f Ekf::predictFlow(const Vector3f &sensor_pos_body, const Vector3f &flow_gyro) const { // calculate the sensor position relative to the IMU - const Vector3f pos_offset_body = _params.flow_pos_body - _params.imu_pos_body; + const Vector3f pos_offset_body = sensor_pos_body - _params.imu_pos_body; // calculate the velocity of the sensor relative to the imu in body frame // Note: flow gyro is the negative of the body angular velocity, thus use minus sign @@ -143,22 +144,22 @@ Vector2f Ekf::predictFlow(const Vector3f &flow_gyro) const const Vector2f vel_body = _state.quat_nominal.rotateVectorInverse(vel_rel_earth).xy(); // calculate range from focal point to centre of image - const float scale = _R_to_earth(2, 2) / predictFlowHagl(); + const float scale = _R_to_earth(2, 2) / predictFlowHagl(sensor_pos_body); return Vector2f(vel_body(1) * scale, -vel_body(0) * scale); } -float Ekf::calcOptFlowMeasVar(const flowSample &flow_sample) const +float OpticalFlowSource::calcOptFlowMeasVar(const flowSample &flow_sample) const { // calculate the observation noise variance - scaling noise linearly across flow quality range - const float R_LOS_best = fmaxf(_params.ekf2_of_n_min, 0.05f); - const float R_LOS_worst = fmaxf(_params.ekf2_of_n_max, 0.05f); + const float R_LOS_best = fmaxf(params.n_min, 0.05f); + const float R_LOS_worst = fmaxf(params.n_max, 0.05f); // calculate a weighting that varies between 1 when flow quality is best and 0 when flow quality is worst - float weighting = (255.f - (float)_params.ekf2_of_qmin); + float weighting = (255.f - (float)params.qmin); if (weighting >= 1.f) { - weighting = math::constrain((float)(flow_sample.quality - _params.ekf2_of_qmin) / weighting, 0.f, 1.f); + weighting = math::constrain((float)(flow_sample.quality - params.qmin) / weighting, 0.f, 1.f); } else { weighting = 0.0f; diff --git a/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow_source.hpp b/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow_source.hpp new file mode 100644 index 00000000000..c946b59f77c --- /dev/null +++ b/src/modules/ekf2/EKF/aid_sources/optical_flow/optical_flow_source.hpp @@ -0,0 +1,219 @@ +/**************************************************************************** + * + * Copyright (c) 2026 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +#ifndef EKF_OPTICAL_FLOW_SOURCE_HPP +#define EKF_OPTICAL_FLOW_SOURCE_HPP + +#include "../../common.h" + +#if defined(CONFIG_EKF2_OPTICAL_FLOW) + +#include +#include +#include +#include + +#if defined(MODULE_NAME) +# include +# include +# include +#endif // MODULE_NAME + +class Ekf; + +class OpticalFlowSource +{ +public: + struct Params { + int32_t ctrl{0}; + int32_t gyr_src{static_cast(estimator::FlowGyroSource::Auto)}; + float n_min{0.15f}; ///< best quality observation noise for optical flow LOS rate measurements (rad/sec) + float n_max{0.5f}; ///< worst quality observation noise for optical flow LOS rate measurements (rad/sec) + int32_t qmin{1}; ///< minimum acceptable quality integer from the flow sensor when in air + int32_t qmin_gnd{0}; ///< minimum acceptable quality integer from the flow sensor when on ground + float gate{3.0f}; ///< optical flow fusion innovation consistency gate size (STD) + }; + + Params params{}; + + ~OpticalFlowSource() { delete _buffer; } + + void setSlot(uint8_t slot) + { + _slot = slot; +#if defined(MODULE_NAME) + _sub = uORB::Subscription(ORB_ID(vehicle_optical_flow), slot); + initParams(); +#endif // MODULE_NAME + } + + void setData(const estimator::flowSample &sample, uint8_t buffer_length, uint64_t min_obs_interval_us, float dt_ekf_avg); + + void setLimits(float max_flow_rate, float min_dist, float max_dist) + { + _max_rate = max_flow_rate; + _min_distance = min_dist; + _max_distance = max_dist; + } + + void setPositionBody(const matrix::Vector3f &pos) { _pos_body = pos; } + + // other_slot_fusing: another flow sensor currently constrains the velocity drift + void update(Ekf &ekf, const estimator::imuSample &imu_delayed, bool other_slot_fusing); + + bool isFusing(const Ekf &ekf) const; + + void stop(); + +#if defined(MODULE_NAME) + // configured SENS_FLOW_DELAY, 0 while the slot is disabled + float delayMs() const; +#endif // MODULE_NAME + +private: + friend class Ekf; + friend class OpticalFlowAiding; + +#if defined(MODULE_NAME) + void initParams(); + void updateParams(); + + // buffers a new vehicle_optical_flow sample of this slot + bool updateSample(Ekf &ekf, vehicle_optical_flow_s &optical_flow); + + struct ParamHandles { + param_t ctrl{PARAM_INVALID}; + param_t delay{PARAM_INVALID}; + param_t gyr_src{PARAM_INVALID}; + param_t n_min{PARAM_INVALID}; + param_t n_max{PARAM_INVALID}; + param_t qmin{PARAM_INVALID}; + param_t qmin_gnd{PARAM_INVALID}; + param_t gate{PARAM_INVALID}; + } _param_handles{}; + + uORB::Subscription _sub{ORB_ID(vehicle_optical_flow)}; +#endif // MODULE_NAME + + bool fuse(Ekf &ekf, matrix::Vector &H, bool update_terrain); + + void reset(Ekf &ekf); + void resetTerrain(Ekf &ekf); + + void calcBodyRateComp(); + + float calcOptFlowMeasVar(const estimator::flowSample &flow_sample) const; + + TimestampedRingBuffer *_buffer{nullptr}; + uint64_t _time_last_data{0}; ///< time of the newest sample pushed to the buffer (us) + estimator::flowSample _sample_delayed{}; + + estimator_aid_source2d_s _aid_src{}; + + matrix::Vector3f _pos_body{}; ///< xyz position of the sensor focal point in body frame (m) + + matrix::Vector3f _gyro_bias{}; ///< bias errors in optical flow sensor rate gyro outputs (rad/sec) + matrix::Vector3f _ref_body_rate{}; ///< body rates from the EKF gyro data, flow sign convention (rad/s) + matrix::Vector2f _vel_body{}; ///< velocity from corrected flow measurement (body frame)(m/s) + AlphaFilter _vel_body_lpf{}; ///< filtered velocity from corrected flow measurement (body frame)(m/s) + matrix::Vector2f _rate_compensated{}; ///< measured angular rate of the image about the X and Y body axes after removal of body rotation (rad/s), RH rotation is positive + AlphaFilter _rate_compensated_lpf{}; + uint64_t _lpf_time_last_us{0}; + uint32_t _counter{0}; ///< number of flow samples read for initialization + + // Sensor limitations + float _max_rate{1.0f}; ///< maximum angular flow rate that the optical flow sensor can measure (rad/s) + float _min_distance{0.0f}; ///< minimum distance that the optical flow sensor can operate at (m) + float _max_distance{10.f}; ///< maximum distance that the optical flow sensor can operate at (m) + + bool _active{false}; + bool _terrain{false}; + + uint8_t _slot{0}; +}; + +class OpticalFlowAiding +{ +public: + OpticalFlowAiding() + { + for (uint8_t i = 0; i < estimator::MAX_OF_INSTANCES; i++) { + _sources[i].setSlot(i); + } + } + + void update(Ekf &ekf, const estimator::imuSample &imu_delayed); + + void setData(const estimator::flowSample &flow, uint8_t instance, uint8_t buffer_length, uint64_t min_obs_interval_us, + float dt_ekf_avg) + { + if (instance < estimator::MAX_OF_INSTANCES) { + _sources[instance].setData(flow, buffer_length, min_obs_interval_us, dt_ekf_avg); + } + } + + OpticalFlowSource &source(uint8_t instance) { return _sources[instance]; } + const OpticalFlowSource &source(uint8_t instance) const { return _sources[instance]; } + + // lowest slot currently fusing, otherwise lowest slot with data (for single-instance legacy consumers) + uint8_t primarySlot() const; + + // most recent fusion / sample activity across all slots + uint64_t timeLastFuse() const; + uint64_t latestSampleTimestamp() const; + + float maxActiveInnovNorm() const; + float maxActiveTestRatioFiltered() const; + + // combined limits of the slots currently delivering data, falling back to the primary slot + void getLimits(const Ekf &ekf, float &hagl_min, float &hagl_max, float &max_rate) const; + +#if defined(MODULE_NAME) + void updateParams(); +#endif // MODULE_NAME + +private: +#if defined(MODULE_NAME) + void updateSamples(Ekf &ekf); +#endif // MODULE_NAME + + OpticalFlowSource _sources[estimator::MAX_OF_INSTANCES] {}; + +#if defined(MODULE_NAME) && defined(CONFIG_EKF2_RANGE_FINDER) + int8_t _range_instance {-1}; ///< first instance providing a distance, used as range finder fallback +#endif // MODULE_NAME && CONFIG_EKF2_RANGE_FINDER +}; + +#endif // CONFIG_EKF2_OPTICAL_FLOW + +#endif // !EKF_OPTICAL_FLOW_SOURCE_HPP diff --git a/src/modules/ekf2/EKF/common.h b/src/modules/ekf2/EKF/common.h index 19b667be6b6..d864f7a8ffe 100644 --- a/src/modules/ekf2/EKF/common.h +++ b/src/modules/ekf2/EKF/common.h @@ -239,6 +239,7 @@ struct flowSample { Vector2f flow_rate{}; ///< measured angular rate of the image about the X and Y body axes (rad/s), RH rotation is positive Vector3f gyro_rate{}; ///< measured angular rate of the inertial frame about the body axes obtained from rate gyro measurements (rad/s), RH rotation is positive uint8_t quality{}; ///< quality indicator between 0 and 255 + uint32_t device_id{}; ///< unique device ID for the sensor that does not change between power cycles }; #if defined(CONFIG_EKF2_EXTERNAL_VISION) @@ -295,6 +296,7 @@ struct systemFlagUpdate { // Runtime fusion control. Populated by EKF2 module, read by EKF core. static constexpr uint8_t MAX_AGP_INSTANCES = 4; +static constexpr uint8_t MAX_OF_INSTANCES = 2; struct FusionSensor { bool enabled{false}; // runtime toggleable via MAVLink @@ -483,21 +485,6 @@ struct parameters { float ekf2_grav_noise{1.0f}; ///< accelerometer measurement gaussian noise (m/s**2) #endif // CONFIG_EKF2_GRAVITY_FUSION -#if defined(CONFIG_EKF2_OPTICAL_FLOW) - int32_t ekf2_of_ctrl {0}; - int32_t ekf2_of_gyr_src {static_cast(FlowGyroSource::Auto)}; - float ekf2_of_delay{5.0f}; ///< optical flow measurement delay relative to the IMU (mSec) - this is to the middle of the optical flow integration interval - - // optical flow fusion - float ekf2_of_n_min{0.15f}; ///< observation noise for optical flow LOS rate measurements (rad/sec) - float ekf2_of_n_max{0.5f}; ///< observation noise for optical flow LOS rate measurements when flow sensor quality is at the minimum useable (rad/sec) - int32_t ekf2_of_qmin{1}; ///< minimum acceptable quality integer from the flow sensor - int32_t ekf2_of_qmin_gnd{0}; ///< minimum acceptable quality integer from the flow sensor when on ground - float ekf2_of_gate{3.0f}; ///< optical flow fusion innovation consistency gate size (STD) - - Vector3f flow_pos_body{}; ///< xyz position of range sensor focal point in body frame (m) -#endif // CONFIG_EKF2_OPTICAL_FLOW - // XYZ offset of sensors in body axes (m) Vector3f imu_pos_body{}; ///< xyz position of IMU in body frame (m) diff --git a/src/modules/ekf2/EKF/control.cpp b/src/modules/ekf2/EKF/control.cpp index cb238138758..3fee37ca5bd 100644 --- a/src/modules/ekf2/EKF/control.cpp +++ b/src/modules/ekf2/EKF/control.cpp @@ -110,7 +110,7 @@ void Ekf::controlFusionModes(const imuSample &imu_delayed) #endif // CONFIG_EKF2_MAGNETOMETER #if defined(CONFIG_EKF2_OPTICAL_FLOW) - controlOpticalFlowFusion(imu_delayed); + _flow_aiding.update(*this, imu_delayed); #endif // CONFIG_EKF2_OPTICAL_FLOW #if defined(CONFIG_EKF2_GNSS) diff --git a/src/modules/ekf2/EKF/ekf.cpp b/src/modules/ekf2/EKF/ekf.cpp index ee51c629b5f..245d7647d03 100644 --- a/src/modules/ekf2/EKF/ekf.cpp +++ b/src/modules/ekf2/EKF/ekf.cpp @@ -459,6 +459,10 @@ void Ekf::updateParameters() _aux_global_position.paramsUpdated(); #endif // CONFIG_EKF2_AUX_GLOBAL_POSITION + +#if defined(CONFIG_EKF2_OPTICAL_FLOW) && defined(MODULE_NAME) + _flow_aiding.updateParams(); +#endif // CONFIG_EKF2_OPTICAL_FLOW && MODULE_NAME } template @@ -585,7 +589,11 @@ void Ekf::print_status() #endif // CONFIG_EKF2_MAGNETOMETER #if defined(CONFIG_EKF2_OPTICAL_FLOW) - printRingBuffer("flow buffer", _flow_buffer); + + for (uint8_t i = 0; i < MAX_OF_INSTANCES; i++) { + printRingBuffer("flow buffer", _flow_aiding.source(i)._buffer); + } + #endif // CONFIG_EKF2_OPTICAL_FLOW #if defined(CONFIG_EKF2_RANGE_FINDER) diff --git a/src/modules/ekf2/EKF/ekf.h b/src/modules/ekf2/EKF/ekf.h index 1173792872c..d394b0f64dc 100644 --- a/src/modules/ekf2/EKF/ekf.h +++ b/src/modules/ekf2/EKF/ekf.h @@ -137,20 +137,22 @@ public: #endif // CONFIG_EKF2_RANGE_FINDER #if defined(CONFIG_EKF2_OPTICAL_FLOW) - const auto &aid_src_optical_flow() const { return _aid_src_optical_flow; } + const auto &aid_src_optical_flow(uint8_t slot = 0) const { return _flow_aiding.source(slot)._aid_src; } - const Vector2f &getFlowVelBody() const { return _flow_vel_body; } - Vector2f getFlowVelNE() const { return Vector2f(_R_to_earth * Vector3f(getFlowVelBody()(0), getFlowVelBody()(1), 0.f)); } + const Vector2f &getFlowVelBody(uint8_t slot = 0) const { return _flow_aiding.source(slot)._vel_body; } + Vector2f getFlowVelNE(uint8_t slot = 0) const { return Vector2f(_R_to_earth * Vector3f(getFlowVelBody(slot)(0), getFlowVelBody(slot)(1), 0.f)); } - const Vector2f &getFilteredFlowVelBody() const { return _flow_vel_body_lpf.getState(); } - Vector2f getFilteredFlowVelNE() const { return Vector2f(_R_to_earth * Vector3f(getFilteredFlowVelBody()(0), getFilteredFlowVelBody()(1), 0.f)); } + const Vector2f &getFilteredFlowVelBody(uint8_t slot = 0) const { return _flow_aiding.source(slot)._vel_body_lpf.getState(); } + Vector2f getFilteredFlowVelNE(uint8_t slot = 0) const { return Vector2f(_R_to_earth * Vector3f(getFilteredFlowVelBody(slot)(0), getFilteredFlowVelBody(slot)(1), 0.f)); } - const Vector2f &getFlowCompensated() const { return _flow_rate_compensated; } - const Vector2f &getFlowUncompensated() const { return _flow_sample_delayed.flow_rate; } + const Vector2f &getFlowCompensated(uint8_t slot = 0) const { return _flow_aiding.source(slot)._rate_compensated; } + const Vector2f &getFlowUncompensated(uint8_t slot = 0) const { return _flow_aiding.source(slot)._sample_delayed.flow_rate; } - const Vector3f getFlowGyro() const { return _flow_sample_delayed.gyro_rate; } - const Vector3f &getFlowGyroBias() const { return _flow_gyro_bias; } - const Vector3f &getFlowRefBodyRate() const { return _ref_body_rate; } + const Vector3f getFlowGyro(uint8_t slot = 0) const { return _flow_aiding.source(slot)._sample_delayed.gyro_rate; } + const Vector3f &getFlowGyroBias(uint8_t slot = 0) const { return _flow_aiding.source(slot)._gyro_bias; } + const Vector3f &getFlowRefBodyRate(uint8_t slot = 0) const { return _flow_aiding.source(slot)._ref_body_rate; } + + uint8_t getPrimaryFlowSlot() const { return _flow_aiding.primarySlot(); } #endif // CONFIG_EKF2_OPTICAL_FLOW #if defined(CONFIG_EKF2_AUX_GLOBAL_POSITION) && defined(MODULE_NAME) @@ -488,6 +490,8 @@ public: friend class AuxGlobalPosition; friend class AgpSource; friend class EkfFlowFusionOrderTest; + friend class OpticalFlowAiding; + friend class OpticalFlowSource; private: @@ -588,22 +592,6 @@ private: estimator_aid_source1d_s _aid_src_rng_hgt {}; #endif // CONFIG_EKF2_RANGE_FINDER -#if defined(CONFIG_EKF2_OPTICAL_FLOW) - estimator_aid_source2d_s _aid_src_optical_flow {}; - - // optical flow processing - Vector3f _flow_gyro_bias{}; ///< bias errors in optical flow sensor rate gyro outputs (rad/sec) - Vector3f _ref_body_rate{}; - - Vector2f _flow_vel_body{}; ///< velocity from corrected flow measurement (body frame)(m/s) - AlphaFilter _flow_vel_body_lpf{_kSensorLpfTimeConstant}; ///< filtered velocity from corrected flow measurement (body frame)(m/s) - uint32_t _flow_counter{0}; ///< number of flow samples read for initialization - - Vector2f _flow_rate_compensated{}; ///< measured angular rate of the image about the X and Y body axes after removal of body rotation (rad/s), RH rotation is positive - AlphaFilter _flow_rate_compensated_lpf{_kSensorLpfTimeConstant}; - uint64_t _flow_lpf_time_last_us{0}; -#endif // CONFIG_EKF2_OPTICAL_FLOW - #if defined(CONFIG_EKF2_AIRSPEED) estimator_aid_source1d_s _aid_src_airspeed {}; #endif // CONFIG_EKF2_AIRSPEED @@ -836,6 +824,7 @@ private: #if defined(CONFIG_EKF2_TERRAIN) void initTerrain(); + void resetTerrainTo(float new_terrain, float var); float getTerrainVPos() const { return isTerrainEstimateValid() ? _state.terrain : _last_on_ground_posD; } void controlTerrainFakeFusion(); @@ -849,10 +838,6 @@ private: float getRngVar() const; # endif // CONFIG_EKF2_RANGE_FINDER -# if defined(CONFIG_EKF2_OPTICAL_FLOW) - void resetTerrainToFlow(); -# endif // CONFIG_EKF2_OPTICAL_FLOW - #endif // CONFIG_EKF2_TERRAIN #if defined(CONFIG_EKF2_RANGE_FINDER) @@ -864,27 +849,12 @@ private: #endif // CONFIG_EKF2_RANGE_FINDER #if defined(CONFIG_EKF2_OPTICAL_FLOW) - // control fusion of optical flow observations - void controlOpticalFlowFusion(const imuSample &imu_delayed); - void resetFlowFusion(const flowSample &flow_sample); - void stopFlowFusion(); - - void updateOnGroundMotionForOpticalFlowChecks(); - void resetOnGroundMotionForOpticalFlowChecks(); - - // calculate the measurement variance for the optical flow sensor (rad/sec)^2 - float calcOptFlowMeasVar(const flowSample &flow_sample) const; - - // calculate optical flow body angular rate compensation - void calcOptFlowBodyRateComp(const flowSample &flow_sample); - - float predictFlowHagl() const; - float predictFlowRange() const; - Vector2f predictFlow(const Vector3f &flow_gyro) const; + float predictFlowHagl(const Vector3f &sensor_pos_body) const; + float predictFlowRange(const Vector3f &sensor_pos_body) const; + Vector2f predictFlow(const Vector3f &sensor_pos_body, const Vector3f &flow_gyro) const; // fuse optical flow line of sight rate measurements - bool fuseOptFlow(VectorState &H, bool update_terrain); - + bool fuseOptFlow(estimator_aid_source2d_s &aid_src, VectorState &H, bool update_terrain); #endif // CONFIG_EKF2_OPTICAL_FLOW #if defined(CONFIG_EKF2_MAGNETOMETER) diff --git a/src/modules/ekf2/EKF/ekf_helper.cpp b/src/modules/ekf2/EKF/ekf_helper.cpp index 73d6c5da0a7..6b3cb2bc66e 100644 --- a/src/modules/ekf2/EKF/ekf_helper.cpp +++ b/src/modules/ekf2/EKF/ekf_helper.cpp @@ -342,7 +342,7 @@ void Ekf::get_ekf_vel_accuracy(float *ekf_evh, float *ekf_evv) const if (_control_status.flags.opt_flow) { float gndclearance = math::max(_params.ekf2_min_rng, 0.1f); - vel_err_conservative = math::max(getHagl(), gndclearance) * Vector2f(_aid_src_optical_flow.innovation).norm(); + vel_err_conservative = math::max(getHagl(), gndclearance) * _flow_aiding.maxActiveInnovNorm(); } #endif // CONFIG_EKF2_OPTICAL_FLOW @@ -408,9 +408,10 @@ void Ekf::get_ekf_ctrl_limits(float *vxy_max, float *vz_max, float *hagl_min, fl const bool relying_on_optical_flow = isOnlyActiveSourceOfHorizontalAiding(_control_status.flags.opt_flow); if (relying_on_optical_flow) { - // Calculate optical flow limits - float flow_hagl_min = _flow_min_distance; - float flow_hagl_max = _flow_max_distance; + float flow_hagl_min; + float flow_hagl_max; + float flow_max_rate; + _flow_aiding.getLimits(*this, flow_hagl_min, flow_hagl_max, flow_max_rate); // only limit optical flow height is dependent on range finder or terrain estimate invalid (precaution) if ((!_control_status.flags.opt_flow_terrain && _control_status.flags.rng_terrain) @@ -423,7 +424,7 @@ void Ekf::get_ekf_ctrl_limits(float *vxy_max, float *vz_max, float *hagl_min, fl const float flow_constrained_height = math::constrain(getHagl(), flow_hagl_min, flow_hagl_max); // Allow ground relative velocity to use 50% of available flow sensor range to allow for angular motion - float flow_vxy_max = 0.5f * _flow_max_rate * flow_constrained_height; + float flow_vxy_max = 0.5f * flow_max_rate * flow_constrained_height; flow_hagl_max = math::max(flow_hagl_max * 0.9f, flow_hagl_max - 1.0f); *vxy_max = flow_vxy_max; @@ -518,9 +519,7 @@ float Ekf::getHorizontalVelocityInnovationTestRatio() const #if defined(CONFIG_EKF2_OPTICAL_FLOW) if (isOnlyActiveSourceOfHorizontalAiding(_control_status.flags.opt_flow)) { - for (auto &test_ratio_filtered : _aid_src_optical_flow.test_ratio_filtered) { - test_ratio = math::max(test_ratio, fabsf(test_ratio_filtered)); - } + test_ratio = math::max(test_ratio, _flow_aiding.maxActiveTestRatioFiltered()); } #endif // CONFIG_EKF2_OPTICAL_FLOW @@ -687,10 +686,14 @@ float Ekf::getHeightAboveGroundInnovationTestRatio() const # if defined(CONFIG_EKF2_OPTICAL_FLOW) - if (_control_status.flags.opt_flow_terrain) { - hagl_sum += sqrtf(math::max(fabsf(_aid_src_optical_flow.test_ratio_filtered[0]), - _aid_src_optical_flow.test_ratio_filtered[1])); - n_hagl_sources++; + for (uint8_t i = 0; i < MAX_OF_INSTANCES; i++) { + const OpticalFlowSource &src = _flow_aiding.source(i); + + if (src._terrain) { + hagl_sum += sqrtf(math::max(fabsf(src._aid_src.test_ratio_filtered[0]), + src._aid_src.test_ratio_filtered[1])); + n_hagl_sources++; + } } # endif // CONFIG_EKF2_OPTICAL_FLOW @@ -868,13 +871,13 @@ void Ekf::updateHorizontalDeadReckoningstatus() // optical flow active if (_control_status.flags.opt_flow - && isRecent(_aid_src_optical_flow.time_last_fuse, _params.no_aid_timeout_max) + && isRecent(_flow_aiding.timeLastFuse(), _params.no_aid_timeout_max) ) { inertial_dead_reckoning = false; } else { if (!_control_status.flags.in_air && _fc.of.intended() - && isRecent(_aid_src_optical_flow.timestamp_sample, _params.no_aid_timeout_max) + && isRecent(_flow_aiding.latestSampleTimestamp(), _params.no_aid_timeout_max) ) { // currently landed, but optical flow aiding should be possible once in air aiding_expected_in_air = true; diff --git a/src/modules/ekf2/EKF/estimator_interface.cpp b/src/modules/ekf2/EKF/estimator_interface.cpp index 6520f0e8ad6..09dd6dc3c00 100644 --- a/src/modules/ekf2/EKF/estimator_interface.cpp +++ b/src/modules/ekf2/EKF/estimator_interface.cpp @@ -64,9 +64,6 @@ EstimatorInterface::~EstimatorInterface() #if defined(CONFIG_EKF2_AIRSPEED) delete _airspeed_buffer; #endif // CONFIG_EKF2_AIRSPEED -#if defined(CONFIG_EKF2_OPTICAL_FLOW) - delete _flow_buffer; -#endif // CONFIG_EKF2_OPTICAL_FLOW #if defined(CONFIG_EKF2_EXTERNAL_VISION) delete _ext_vision_buffer; #endif // CONFIG_EKF2_EXTERNAL_VISION @@ -324,6 +321,12 @@ void EstimatorInterface::setRangeData(const sensor::rangeSample &range_sample) return; } + _time_last_range_sensor_data = _time_latest_us; + pushRangeData(range_sample); +} + +void EstimatorInterface::pushRangeData(const sensor::rangeSample &range_sample) +{ // Allocate the required buffer size if not previously done if (_range_buffer == nullptr) { _range_buffer = new TimestampedRingBuffer(_obs_buffer_length); @@ -357,40 +360,13 @@ void EstimatorInterface::setRangeData(const sensor::rangeSample &range_sample) #endif // CONFIG_EKF2_RANGE_FINDER #if defined(CONFIG_EKF2_OPTICAL_FLOW) -void EstimatorInterface::setOpticalFlowData(const flowSample &flow) +void EstimatorInterface::setOpticalFlowData(const flowSample &flow, uint8_t instance) { if (!_initialised) { return; } - // Allocate the required buffer size if not previously done - if (_flow_buffer == nullptr) { - _flow_buffer = new TimestampedRingBuffer(_imu_buffer_length); - - if (_flow_buffer == nullptr || !_flow_buffer->valid()) { - delete _flow_buffer; - _flow_buffer = nullptr; - printBufferAllocationFailed("flow"); - return; - } - } - - const int64_t time_us = flow.time_us - - static_cast(_params.ekf2_of_delay * 1000) - - static_cast(_dt_ekf_avg * 5e5f); // seconds to microseconds divided by 2 - - // limit data rate to prevent data being lost - if (time_us >= static_cast(_flow_buffer->get_newest().time_us + _min_obs_interval_us)) { - - flowSample optflow_sample_new{flow}; - optflow_sample_new.time_us = time_us; - - _flow_buffer->push(optflow_sample_new); - - } else { - ECL_WARN("optical flow data too fast %" PRIi64 " < %" PRIu64 " + %d", time_us, _flow_buffer->get_newest().time_us, - _min_obs_interval_us); - } + _flow_aiding.setData(flow, instance, _imu_buffer_length, _min_obs_interval_us, _dt_ekf_avg); } #endif // CONFIG_EKF2_OPTICAL_FLOW diff --git a/src/modules/ekf2/EKF/estimator_interface.h b/src/modules/ekf2/EKF/estimator_interface.h index 9cd1c963eec..faa47ba407d 100644 --- a/src/modules/ekf2/EKF/estimator_interface.h +++ b/src/modules/ekf2/EKF/estimator_interface.h @@ -71,6 +71,10 @@ # include "aid_sources/range_finder/sensor_range_finder.hpp" #endif // CONFIG_EKF2_RANGE_FINDER +#if defined(CONFIG_EKF2_OPTICAL_FLOW) +# include "aid_sources/optical_flow/optical_flow_source.hpp" +#endif // CONFIG_EKF2_OPTICAL_FLOW + #include #include #include @@ -123,15 +127,10 @@ public: #if defined(CONFIG_EKF2_OPTICAL_FLOW) // if optical flow sensor gyro delta angles are not available, set gyro_rate vector fields to NaN and the EKF will use its internal gyro data instead - void setOpticalFlowData(const flowSample &flow); + void setOpticalFlowData(const flowSample &flow, uint8_t instance = 0); - // set sensor limitations reported by the optical flow sensor - void set_optical_flow_limits(float max_flow_rate, float min_distance, float max_distance) - { - _flow_max_rate = max_flow_rate; - _flow_min_distance = min_distance; - _flow_max_distance = max_distance; - } + OpticalFlowSource &flowSource(uint8_t instance) { return _flow_aiding.source(instance); } + const OpticalFlowSource &flowSource(uint8_t instance) const { return _flow_aiding.source(instance); } #endif // CONFIG_EKF2_OPTICAL_FLOW #if defined(CONFIG_EKF2_EXTERNAL_VISION) @@ -332,6 +331,7 @@ public: protected: EstimatorInterface() = default; + virtual ~EstimatorInterface(); virtual bool init(uint64_t timestamp) = 0; @@ -372,22 +372,18 @@ protected: #endif // CONFIG_EKF2_EXTERNAL_VISION #if defined(CONFIG_EKF2_RANGE_FINDER) + void pushRangeData(const sensor::rangeSample &range_sample); + TimestampedRingBuffer *_range_buffer {nullptr}; uint64_t _time_last_range_buffer_push{0}; + uint64_t _time_last_range_sensor_data{0}; ///< last sample from a range finder, the optical flow fallback excluded sensor::SensorRangeFinder _range_sensor{}; RangeFinderConsistencyCheck _rng_consistency_check; #endif // CONFIG_EKF2_RANGE_FINDER #if defined(CONFIG_EKF2_OPTICAL_FLOW) - TimestampedRingBuffer *_flow_buffer {nullptr}; - - flowSample _flow_sample_delayed{}; - - // Sensor limitations - float _flow_max_rate{1.0f}; ///< maximum angular flow rate that the optical flow sensor can measure (rad/s) - float _flow_min_distance{0.0f}; ///< minimum distance that the optical flow sensor can operate at (m) - float _flow_max_distance{10.f}; ///< maximum distance that the optical flow sensor can operate at (m) + OpticalFlowAiding _flow_aiding {}; #endif // CONFIG_EKF2_OPTICAL_FLOW float _air_density{atmosphere::kAirDensitySeaLevelStandardAtmos}; // air density (kg/m**3) diff --git a/src/modules/ekf2/EKF/terrain_control.cpp b/src/modules/ekf2/EKF/terrain_control.cpp index df3b88cc672..c28171e707e 100644 --- a/src/modules/ekf2/EKF/terrain_control.cpp +++ b/src/modules/ekf2/EKF/terrain_control.cpp @@ -49,6 +49,25 @@ void Ekf::initTerrain() P.uncorrelateCovarianceSetVariance(State::terrain.idx, sq(_params.ekf2_min_rng)); } +void Ekf::resetTerrainTo(const float new_terrain, const float var) +{ + const float delta_terrain = new_terrain - _state.terrain; + + _state.terrain = new_terrain; + P.uncorrelateCovarianceSetVariance(State::terrain.idx, var); + + // record the state change + if (_state_reset_status.reset_count.hagl == _state_reset_count_prev.hagl) { + _state_reset_status.hagl_change = delta_terrain; + + } else { + // there's already a reset this update, accumulate total delta + _state_reset_status.hagl_change += delta_terrain; + } + + _state_reset_status.reset_count.hagl++; +} + void Ekf::controlTerrainFakeFusion() { // If we are on ground, store the local position and time to use as a reference @@ -84,7 +103,7 @@ void Ekf::updateTerrainValidity() #if defined(CONFIG_EKF2_OPTICAL_FLOW) if (_control_status.flags.opt_flow_terrain - && isRecent(_aid_src_optical_flow.time_last_fuse, _params.hgt_fusion_timeout_max) + && isRecent(_flow_aiding.timeLastFuse(), _params.hgt_fusion_timeout_max) ) { valid_opt_flow_terrain = true; } diff --git a/src/modules/ekf2/EKF2.cpp b/src/modules/ekf2/EKF2.cpp index bd599cf1270..d6d7e74a18c 100644 --- a/src/modules/ekf2/EKF2.cpp +++ b/src/modules/ekf2/EKF2.cpp @@ -211,19 +211,6 @@ EKF2::EKF2(bool multi_mode, const px4::wq_config_t &config, bool replay_mode): _param_ekf2_ev_pos_y(_params->ev_pos_body(1)), _param_ekf2_ev_pos_z(_params->ev_pos_body(2)), #endif // CONFIG_EKF2_EXTERNAL_VISION -#if defined(CONFIG_EKF2_OPTICAL_FLOW) - _param_ekf2_of_ctrl(_params->ekf2_of_ctrl), - _param_ekf2_of_gyr_src(_params->ekf2_of_gyr_src), - _param_ekf2_of_delay(_params->ekf2_of_delay), - _param_ekf2_of_n_min(_params->ekf2_of_n_min), - _param_ekf2_of_n_max(_params->ekf2_of_n_max), - _param_ekf2_of_qmin(_params->ekf2_of_qmin), - _param_ekf2_of_qmin_gnd(_params->ekf2_of_qmin_gnd), - _param_ekf2_of_gate(_params->ekf2_of_gate), - _param_ekf2_of_pos_x(_params->flow_pos_body(0)), - _param_ekf2_of_pos_y(_params->flow_pos_body(1)), - _param_ekf2_of_pos_z(_params->flow_pos_body(2)), -#endif // CONFIG_EKF2_OPTICAL_FLOW #if defined(CONFIG_EKF2_DRAG_FUSION) _param_ekf2_drag_ctrl(_params->ekf2_drag_ctrl), _param_ekf2_drag_noise(_params->ekf2_drag_noise), @@ -385,9 +372,11 @@ void EKF2::AdvertiseTopics() #if defined(CONFIG_EKF2_OPTICAL_FLOW) - if (_param_ekf2_of_ctrl.get()) { - _estimator_optical_flow_vel_pub.advertise(); - _estimator_aid_src_optical_flow_pub.advertise(); + for (uint8_t i = 0; i < MAX_OF_INSTANCES; i++) { + if (_ekf.flowSource(i).params.ctrl) { + _optical_flow_pubs[i].aid_src.advertise(); + _optical_flow_pubs[i].vel.advertise(); + } } #endif // CONFIG_EKF2_OPTICAL_FLOW @@ -488,6 +477,7 @@ void EKF2::Run() // update parameters from storage updateParams(); + initFusionControl(); VerifyParams(); @@ -830,9 +820,6 @@ void EKF2::Run() #if defined(CONFIG_EKF2_EXTERNAL_VISION) UpdateExtVisionSample(ekf2_timestamps); #endif // CONFIG_EKF2_EXTERNAL_VISION -#if defined(CONFIG_EKF2_OPTICAL_FLOW) - UpdateFlowSample(ekf2_timestamps); -#endif // CONFIG_EKF2_OPTICAL_FLOW #if defined(CONFIG_EKF2_GNSS) UpdateGnssSample(ekf2_timestamps); # if defined(CONFIG_EKF2_GNSS_YAW) @@ -1005,8 +992,8 @@ void EKF2::VerifyParams() #if defined(CONFIG_EKF2_OPTICAL_FLOW) - if (_param_ekf2_of_delay.get() > delay_max) { - delay_max = _param_ekf2_of_delay.get(); + for (uint8_t i = 0; i < MAX_OF_INSTANCES; i++) { + delay_max = math::max(delay_max, _ekf.flowSource(i).delayMs()); } #endif // CONFIG_EKF2_OPTICAL_FLOW @@ -1217,9 +1204,13 @@ void EKF2::PublishAidSourceStatus(const hrt_abstime ×tamp) #endif // CONFIG_EKF2_AUXVEL #if defined(CONFIG_EKF2_OPTICAL_FLOW) + // optical flow - PublishAidSourceStatus(timestamp, _ekf.aid_src_optical_flow(), _status_optical_flow_pub_last, - _estimator_aid_src_optical_flow_pub); + for (uint8_t i = 0; i < MAX_OF_INSTANCES; i++) { + PublishAidSourceStatus(timestamp, _ekf.aid_src_optical_flow(i), _optical_flow_pubs[i].aid_src_last, + _optical_flow_pubs[i].aid_src); + } + #endif // CONFIG_EKF2_OPTICAL_FLOW } @@ -1461,9 +1452,9 @@ void EKF2::PublishInnovations(const hrt_abstime ×tamp) #endif // CONFIG_EKF2_AUXVEL #if defined(CONFIG_EKF2_OPTICAL_FLOW) - // Optical flow - innovations.flow[0] = _ekf.aid_src_optical_flow().innovation[0]; - innovations.flow[1] = _ekf.aid_src_optical_flow().innovation[1]; + // Optical flow (primary slot only, per-slot data is in estimator_aid_src_optical_flow) + innovations.flow[0] = _ekf.aid_src_optical_flow(_ekf.getPrimaryFlowSlot()).innovation[0]; + innovations.flow[1] = _ekf.aid_src_optical_flow(_ekf.getPrimaryFlowSlot()).innovation[1]; #endif // CONFIG_EKF2_OPTICAL_FLOW // heading @@ -1554,9 +1545,9 @@ void EKF2::PublishInnovationTestRatios(const hrt_abstime ×tamp) #endif // CONFIG_EKF2_AUXVEL #if defined(CONFIG_EKF2_OPTICAL_FLOW) - // Optical flow - test_ratios.flow[0] = _ekf.aid_src_optical_flow().test_ratio[0]; - test_ratios.flow[1] = _ekf.aid_src_optical_flow().test_ratio[1]; + // Optical flow (primary slot only, per-slot data is in estimator_aid_src_optical_flow) + test_ratios.flow[0] = _ekf.aid_src_optical_flow(_ekf.getPrimaryFlowSlot()).test_ratio[0]; + test_ratios.flow[1] = _ekf.aid_src_optical_flow(_ekf.getPrimaryFlowSlot()).test_ratio[1]; #endif // CONFIG_EKF2_OPTICAL_FLOW // heading @@ -1647,9 +1638,9 @@ void EKF2::PublishInnovationVariances(const hrt_abstime ×tamp) #endif // CONFIG_EKF2_AUXVEL #if defined(CONFIG_EKF2_OPTICAL_FLOW) - // Optical flow - variances.flow[0] = _ekf.aid_src_optical_flow().innovation_variance[0]; - variances.flow[1] = _ekf.aid_src_optical_flow().innovation_variance[1]; + // Optical flow (primary slot only, per-slot data is in estimator_aid_src_optical_flow) + variances.flow[0] = _ekf.aid_src_optical_flow(_ekf.getPrimaryFlowSlot()).innovation_variance[0]; + variances.flow[1] = _ekf.aid_src_optical_flow(_ekf.getPrimaryFlowSlot()).innovation_variance[1]; #endif // CONFIG_EKF2_OPTICAL_FLOW // heading @@ -2221,32 +2212,34 @@ void EKF2::PublishWindEstimate(const hrt_abstime ×tamp) #if defined(CONFIG_EKF2_OPTICAL_FLOW) void EKF2::PublishOpticalFlowVel(const hrt_abstime ×tamp) { - const hrt_abstime timestamp_sample = _ekf.aid_src_optical_flow().timestamp_sample; + for (uint8_t i = 0; i < MAX_OF_INSTANCES; i++) { + const hrt_abstime timestamp_sample = _ekf.aid_src_optical_flow(i).timestamp_sample; - if ((timestamp_sample != 0) && (timestamp_sample > _optical_flow_vel_pub_last)) { + if ((timestamp_sample != 0) && (timestamp_sample > _optical_flow_pubs[i].vel_last)) { - vehicle_optical_flow_vel_s flow_vel{}; - flow_vel.timestamp_sample = _ekf.aid_src_optical_flow().timestamp_sample; + vehicle_optical_flow_vel_s flow_vel{}; + flow_vel.timestamp_sample = timestamp_sample; - _ekf.getFlowVelBody().copyTo(flow_vel.vel_body); - _ekf.getFlowVelNE().copyTo(flow_vel.vel_ne); + _ekf.getFlowVelBody(i).copyTo(flow_vel.vel_body); + _ekf.getFlowVelNE(i).copyTo(flow_vel.vel_ne); - _ekf.getFilteredFlowVelBody().copyTo(flow_vel.vel_body_filtered); - _ekf.getFilteredFlowVelNE().copyTo(flow_vel.vel_ne_filtered); + _ekf.getFilteredFlowVelBody(i).copyTo(flow_vel.vel_body_filtered); + _ekf.getFilteredFlowVelNE(i).copyTo(flow_vel.vel_ne_filtered); - _ekf.getFlowUncompensated().copyTo(flow_vel.flow_rate_uncompensated); - _ekf.getFlowCompensated().copyTo(flow_vel.flow_rate_compensated); + _ekf.getFlowUncompensated(i).copyTo(flow_vel.flow_rate_uncompensated); + _ekf.getFlowCompensated(i).copyTo(flow_vel.flow_rate_compensated); - _ekf.getFlowGyro().copyTo(flow_vel.gyro_rate); + _ekf.getFlowGyro(i).copyTo(flow_vel.gyro_rate); - _ekf.getFlowGyroBias().copyTo(flow_vel.gyro_bias); - _ekf.getFlowRefBodyRate().copyTo(flow_vel.ref_gyro); + _ekf.getFlowGyroBias(i).copyTo(flow_vel.gyro_bias); + _ekf.getFlowRefBodyRate(i).copyTo(flow_vel.ref_gyro); - flow_vel.timestamp = _replay_mode ? timestamp : hrt_absolute_time(); + flow_vel.timestamp = _replay_mode ? timestamp : hrt_absolute_time(); - _estimator_optical_flow_vel_pub.publish(flow_vel); + _optical_flow_pubs[i].vel.publish(flow_vel); - _optical_flow_vel_pub_last = timestamp_sample; + _optical_flow_pubs[i].vel_last = timestamp_sample; + } } } #endif // CONFIG_EKF2_OPTICAL_FLOW @@ -2554,77 +2547,6 @@ bool EKF2::UpdateExtVisionSample(ekf2_timestamps_s &ekf2_timestamps) } #endif // CONFIG_EKF2_EXTERNAL_VISION -#if defined(CONFIG_EKF2_OPTICAL_FLOW) -bool EKF2::UpdateFlowSample(ekf2_timestamps_s &ekf2_timestamps) -{ - // EKF flow sample - bool new_optical_flow = false; - vehicle_optical_flow_s optical_flow; - - if (_vehicle_optical_flow_sub.update(&optical_flow)) { - - const float dt = 1e-6f * (float)optical_flow.integration_timespan_us; - Vector2f flow_rate; - Vector3f gyro_rate; - - if (dt > FLT_EPSILON) { - // NOTE: the EKF uses the reverse sign convention to the flow sensor. EKF assumes positive LOS rate - // is produced by a RH rotation of the image about the sensor axis. - flow_rate = Vector2f(-optical_flow.pixel_flow[0], -optical_flow.pixel_flow[1]) / dt; - gyro_rate = Vector3f(-optical_flow.delta_angle[0], -optical_flow.delta_angle[1], -optical_flow.delta_angle[2]) / dt; - - } else if (optical_flow.quality == 0) { - // handle special case of SITL and PX4Flow where dt is forced to zero when the quaity is 0 - flow_rate.zero(); - gyro_rate.zero(); - } - - flowSample flow { - .time_us = optical_flow.timestamp_sample - optical_flow.integration_timespan_us / 2, // correct timestamp to midpoint of integration interval as the data is converted to rates - .flow_rate = flow_rate, - .gyro_rate = gyro_rate, - .quality = optical_flow.quality - }; - - if (Vector2f(optical_flow.pixel_flow).isAllFinite() && optical_flow.integration_timespan_us < 1e6) { - - // Save sensor limits reported by the optical flow sensor - _ekf.set_optical_flow_limits(optical_flow.max_flow_rate, optical_flow.min_ground_distance, - optical_flow.max_ground_distance); - - _ekf.setOpticalFlowData(flow); - - new_optical_flow = true; - } - -#if defined(CONFIG_EKF2_RANGE_FINDER) - - // use optical_flow distance as range sample if distance_sensor unavailable - if (PX4_ISFINITE(optical_flow.distance_m) && (ekf2_timestamps.timestamp > _last_range_sensor_update + 1_s)) { - - int8_t quality = static_cast(optical_flow.quality) / static_cast(UINT8_MAX) * 100.f; - - estimator::sensor::rangeSample range_sample { - .time_us = optical_flow.timestamp_sample, - .rng = optical_flow.distance_m, - .quality = quality, - }; - _ekf.setRangeData(range_sample); - - // set sensor limits - _ekf.set_rangefinder_limits(optical_flow.min_ground_distance, optical_flow.max_ground_distance); - } - -#endif // CONFIG_EKF2_RANGE_FINDER - - ekf2_timestamps.optical_flow_timestamp_rel = (int16_t)((int64_t)optical_flow.timestamp / 100 - - (int64_t)ekf2_timestamps.timestamp / 100); - } - - return new_optical_flow; -} -#endif // CONFIG_EKF2_OPTICAL_FLOW - #if defined(CONFIG_EKF2_GNSS) void EKF2::UpdateGnssSample(ekf2_timestamps_s &ekf2_timestamps) { diff --git a/src/modules/ekf2/EKF2.hpp b/src/modules/ekf2/EKF2.hpp index a1fb2c67652..5e23a8cee46 100644 --- a/src/modules/ekf2/EKF2.hpp +++ b/src/modules/ekf2/EKF2.hpp @@ -113,7 +113,6 @@ #endif // CONFIG_EKF2_MAGNETOMETER #if defined(CONFIG_EKF2_OPTICAL_FLOW) -# include # include #endif // CONFIG_EKF2_OPTICAL_FLOW @@ -231,7 +230,6 @@ private: # endif // CONFIG_EKF2_GNSS_YAW #endif // CONFIG_EKF2_GNSS #if defined(CONFIG_EKF2_OPTICAL_FLOW) - bool UpdateFlowSample(ekf2_timestamps_s &ekf2_timestamps); void PublishOpticalFlowVel(const hrt_abstime ×tamp); #endif // CONFIG_EKF2_OPTICAL_FLOW #if defined(CONFIG_EKF2_MAGNETOMETER) @@ -347,12 +345,14 @@ private: #endif // CONFIG_EKF2_RANGING_BEACON #if defined(CONFIG_EKF2_OPTICAL_FLOW) - uORB::Subscription _vehicle_optical_flow_sub {ORB_ID(vehicle_optical_flow)}; - uORB::PublicationMulti _estimator_optical_flow_vel_pub{ORB_ID(estimator_optical_flow_vel)}; + struct OpticalFlowPublications { + uORB::PublicationMulti aid_src{ORB_ID(estimator_aid_src_optical_flow)}; + uORB::PublicationMulti vel{ORB_ID(estimator_optical_flow_vel)}; + hrt_abstime aid_src_last{0}; + hrt_abstime vel_last{0}; + }; - uORB::PublicationMulti _estimator_aid_src_optical_flow_pub{ORB_ID(estimator_aid_src_optical_flow)}; - hrt_abstime _status_optical_flow_pub_last{0}; - hrt_abstime _optical_flow_vel_pub_last{0}; + OpticalFlowPublications _optical_flow_pubs[MAX_OF_INSTANCES] {}; #endif // CONFIG_EKF2_OPTICAL_FLOW #if defined(CONFIG_EKF2_BAROMETER) @@ -687,32 +687,6 @@ private: (ParamExtFloat) _param_ekf2_ev_pos_z, ///< Z position of VI sensor focal point in body frame (m) #endif // CONFIG_EKF2_EXTERNAL_VISION -#if defined(CONFIG_EKF2_OPTICAL_FLOW) - // optical flow fusion - (ParamExtInt) - _param_ekf2_of_ctrl, - (ParamExtInt) - _param_ekf2_of_gyr_src, - (ParamExtFloat) - _param_ekf2_of_delay, ///< optical flow measurement delay relative to the IMU (mSec) - this is to the middle of the optical flow integration interval - (ParamExtFloat) - _param_ekf2_of_n_min, ///< best quality observation noise for optical flow LOS rate measurements (rad/sec) - (ParamExtFloat) - _param_ekf2_of_n_max, ///< worst quality observation noise for optical flow LOS rate measurements (rad/sec) - (ParamExtInt) - _param_ekf2_of_qmin, ///< minimum acceptable quality integer from the flow sensor when in air - (ParamExtInt) - _param_ekf2_of_qmin_gnd, ///< minimum acceptable quality integer from the flow sensor when on ground - (ParamExtFloat) - _param_ekf2_of_gate, ///< optical flow fusion innovation consistency gate size (STD) - (ParamExtFloat) - _param_ekf2_of_pos_x, ///< X position of optical flow sensor focal point in body frame (m) - (ParamExtFloat) - _param_ekf2_of_pos_y, ///< Y position of optical flow sensor focal point in body frame (m) - (ParamExtFloat) - _param_ekf2_of_pos_z, ///< Z position of optical flow sensor focal point in body frame (m) -#endif // CONFIG_EKF2_OPTICAL_FLOW - #if defined(CONFIG_EKF2_DRAG_FUSION) (ParamExtInt) _param_ekf2_drag_ctrl, ///< drag fusion selection // Multi-rotor drag specific force fusion diff --git a/src/modules/ekf2/params_optical_flow.yaml b/src/modules/ekf2/params_optical_flow.yaml index 8df8d5ede1f..3d7324b473e 100644 --- a/src/modules/ekf2/params_optical_flow.yaml +++ b/src/modules/ekf2/params_optical_flow.yaml @@ -1,30 +1,20 @@ +__max_num_of_instances: &max_num_of_instances 2 + module_name: ekf2 parameters: - group: EKF2 definitions: - EKF2_OF_CTRL: + EKF2_OF${i}_CTRL: description: - short: Optical flow aiding - long: Enable optical flow fusion. + short: Optical flow sensor ${i} aiding + long: Enable optical flow fusion for sensor slot ${i}. type: boolean - default: 1 - EKF2_OF_DELAY: + default: [1, 0] + num_instances: *max_num_of_instances + instance_start: 0 + EKF2_OF${i}_GATE: description: - short: Optical flow measurement delay relative to IMU measurements - long: |- - Assumes measurement is timestamped at trailing edge of integration - period. The default matches a DroneCAN flow node, whose frame reaches - the flight controller about 7 ms after its integration window closes. - type: float - default: 7 - min: 0 - max: 300 - unit: ms - reboot_required: true - decimal: 1 - EKF2_OF_GATE: - description: - short: Gate size for optical flow fusion + short: Gate size for optical flow sensor ${i} fusion long: Sets the number of standard deviations used by the innovation consistency test. type: float @@ -32,9 +22,11 @@ parameters: min: 1.0 unit: SD decimal: 1 - EKF2_OF_N_MIN: + num_instances: *max_num_of_instances + instance_start: 0 + EKF2_OF${i}_N_MIN: description: - short: Optical flow minimum noise + short: Optical flow sensor ${i} minimum noise long: Measurement noise for the optical flow sensor when it's reported quality metric is at the maximum type: float @@ -42,9 +34,11 @@ parameters: min: 0.05 unit: rad/s decimal: 2 - EKF2_OF_N_MAX: + num_instances: *max_num_of_instances + instance_start: 0 + EKF2_OF${i}_N_MAX: description: - short: Optical flow maximum noise + short: Optical flow sensor ${i} maximum noise long: Measurement noise for the optical flow sensor when it's reported quality metric is at the minimum type: float @@ -52,27 +46,33 @@ parameters: min: 0.05 unit: rad/s decimal: 2 - EKF2_OF_QMIN: + num_instances: *max_num_of_instances + instance_start: 0 + EKF2_OF${i}_QMIN: description: - short: In air optical flow minimum quality + short: In air optical flow sensor ${i} minimum quality long: Optical Flow data will only be used in air if the sensor reports a - quality metric >= EKF2_OF_QMIN + quality metric >= EKF2_OF${i}_QMIN type: int32 default: 1 min: 0 max: 255 - EKF2_OF_QMIN_GND: + num_instances: *max_num_of_instances + instance_start: 0 + EKF2_OF${i}_QMINGND: description: - short: On ground optical flow minimum quality + short: On ground optical flow sensor ${i} minimum quality long: Optical Flow data will only be used on the ground if the sensor reports - a quality metric >= EKF2_OF_QMIN_GND + a quality metric >= EKF2_OF${i}_QMINGND type: int32 default: 0 min: 0 max: 255 - EKF2_OF_GYR_SRC: + num_instances: *max_num_of_instances + instance_start: 0 + EKF2_OF${i}_GYR_SRC: description: - short: Optical flow angular rate compensation source + short: Optical flow sensor ${i} angular rate compensation source long: 'Auto: use gyro from optical flow message if available, internal gyro otherwise. Internal: always use internal gyro' type: enum @@ -80,27 +80,5 @@ parameters: 0: Auto 1: Internal default: 0 - EKF2_OF_POS_X: - description: - short: X position of optical flow focal point in body frame - long: Forward axis with origin relative to vehicle centre of gravity - type: float - default: 0.0 - unit: m - decimal: 3 - EKF2_OF_POS_Y: - description: - short: Y position of optical flow focal point in body frame - long: Forward axis with origin relative to vehicle centre of gravity - type: float - default: 0.0 - unit: m - decimal: 3 - EKF2_OF_POS_Z: - description: - short: Z position of optical flow focal point in body frame - long: Forward axis with origin relative to vehicle centre of gravity - type: float - default: 0.0 - unit: m - decimal: 3 + num_instances: *max_num_of_instances + instance_start: 0 diff --git a/src/modules/ekf2/test/CMakeLists.txt b/src/modules/ekf2/test/CMakeLists.txt index bbaf7a46418..c464042ab6f 100644 --- a/src/modules/ekf2/test/CMakeLists.txt +++ b/src/modules/ekf2/test/CMakeLists.txt @@ -44,6 +44,7 @@ px4_add_unit_gtest(SRC test_EKF_externalVision.cpp LINKLIBS ecl_EKF ecl_sensor_s px4_add_unit_gtest(SRC test_EKF_fake_pos.cpp LINKLIBS ecl_EKF ecl_sensor_sim ecl_test_helper) px4_add_unit_gtest(SRC test_EKF_flow.cpp LINKLIBS ecl_EKF ecl_sensor_sim ecl_test_helper) px4_add_unit_gtest(SRC test_EKF_flow_fusion_order.cpp LINKLIBS ecl_EKF) +px4_add_unit_gtest(SRC test_EKF_flow_multi.cpp LINKLIBS ecl_EKF ecl_sensor_sim) px4_add_unit_gtest(SRC test_EKF_flow_generated.cpp LINKLIBS ecl_EKF ecl_sensor_sim ecl_test_helper) px4_add_unit_gtest(SRC test_EKF_gen_nav.cpp LINKLIBS ecl_EKF ecl_sensor_sim gen_nav) px4_add_unit_gtest(SRC test_EKF_gyroscope.cpp LINKLIBS ecl_EKF ecl_sensor_sim) diff --git a/src/modules/ekf2/test/sensor_simulator/ekf_wrapper.cpp b/src/modules/ekf2/test/sensor_simulator/ekf_wrapper.cpp index 8bd5b821089..6a02607d805 100644 --- a/src/modules/ekf2/test/sensor_simulator/ekf_wrapper.cpp +++ b/src/modules/ekf2/test/sensor_simulator/ekf_wrapper.cpp @@ -173,15 +173,15 @@ bool EkfWrapper::isIntendingGpsHeadingFusion() const return _ekf->control_status_flags().gnss_yaw; } -void EkfWrapper::enableFlowFusion() +void EkfWrapper::enableFlowFusion(uint8_t slot) { - _ekf_params->ekf2_of_ctrl = 1; + _ekf->flowSource(slot).params.ctrl = 1; _fc->of.enabled = true; } -void EkfWrapper::disableFlowFusion() +void EkfWrapper::disableFlowFusion(uint8_t slot) { - _ekf_params->ekf2_of_ctrl = 0; + _ekf->flowSource(slot).params.ctrl = 0; } bool EkfWrapper::isIntendingFlowFusion() const @@ -189,9 +189,9 @@ bool EkfWrapper::isIntendingFlowFusion() const return _ekf->control_status_flags().opt_flow; } -void EkfWrapper::setFlowOffset(const Vector3f &offset) +void EkfWrapper::setFlowOffset(const Vector3f &offset, uint8_t slot) { - _ekf_params->flow_pos_body = offset; + _ekf->flowSource(slot).setPositionBody(offset); } void EkfWrapper::enableExternalVisionPositionFusion() diff --git a/src/modules/ekf2/test/sensor_simulator/ekf_wrapper.h b/src/modules/ekf2/test/sensor_simulator/ekf_wrapper.h index b94311cd481..44bf686fb0a 100644 --- a/src/modules/ekf2/test/sensor_simulator/ekf_wrapper.h +++ b/src/modules/ekf2/test/sensor_simulator/ekf_wrapper.h @@ -87,10 +87,10 @@ public: void disableGpsHeadingFusion(); bool isIntendingGpsHeadingFusion() const; - void enableFlowFusion(); - void disableFlowFusion(); + void enableFlowFusion(uint8_t slot = 0); + void disableFlowFusion(uint8_t slot = 0); bool isIntendingFlowFusion() const; - void setFlowOffset(const matrix::Vector3f &offset); + void setFlowOffset(const matrix::Vector3f &offset, uint8_t slot = 0); void enableExternalVisionPositionFusion(); void disableExternalVisionPositionFusion(); diff --git a/src/modules/ekf2/test/sensor_simulator/flow.cpp b/src/modules/ekf2/test/sensor_simulator/flow.cpp index 929a57a0968..e9894a572c0 100644 --- a/src/modules/ekf2/test/sensor_simulator/flow.cpp +++ b/src/modules/ekf2/test/sensor_simulator/flow.cpp @@ -5,7 +5,7 @@ namespace sensor_simulator namespace sensor { -Flow::Flow(std::shared_ptr ekf): Sensor(ekf) +Flow::Flow(std::shared_ptr ekf, uint8_t instance): Sensor(ekf), _instance(instance) { } @@ -15,8 +15,8 @@ Flow::~Flow() void Flow::send(uint64_t time) { - _flow_data.time_us = time; - _ekf->setOpticalFlowData(_flow_data); + _flow_data.time_us = time - _latency_us; + _ekf->setOpticalFlowData(_flow_data, _instance); } void Flow::setData(const flowSample &flow) diff --git a/src/modules/ekf2/test/sensor_simulator/flow.h b/src/modules/ekf2/test/sensor_simulator/flow.h index 2c0cdf94fcc..61241f453ec 100644 --- a/src/modules/ekf2/test/sensor_simulator/flow.h +++ b/src/modules/ekf2/test/sensor_simulator/flow.h @@ -48,14 +48,17 @@ namespace sensor class Flow: public Sensor { public: - Flow(std::shared_ptr ekf); + Flow(std::shared_ptr ekf, uint8_t instance = 0); ~Flow(); void setData(const flowSample &flow); + void setLatencyUs(uint64_t latency_us) { _latency_us = latency_us; } flowSample dataAtRest(); private: flowSample _flow_data; + uint8_t _instance; + uint64_t _latency_us{0}; void send(uint64_t time) override; diff --git a/src/modules/ekf2/test/sensor_simulator/sensor_simulator.cpp b/src/modules/ekf2/test/sensor_simulator/sensor_simulator.cpp index 39877fd93c8..b572a794ea5 100644 --- a/src/modules/ekf2/test/sensor_simulator/sensor_simulator.cpp +++ b/src/modules/ekf2/test/sensor_simulator/sensor_simulator.cpp @@ -5,6 +5,7 @@ SensorSimulator::SensorSimulator(std::shared_ptr ekf): _airspeed(ekf), _baro(ekf), _flow(ekf), + _flow1(ekf, 1), _gps(ekf), _gnss_yaw(ekf), _imu(ekf), @@ -130,6 +131,7 @@ void SensorSimulator::setSensorRateToDefault() _gps.setRateHz(5); _gnss_yaw.setRateHz(5); _flow.setRateHz(50); + _flow1.setRateHz(50); _rng.setRateHz(30); _vio.setRateHz(30); _airspeed.setRateHz(100); @@ -140,6 +142,7 @@ void SensorSimulator::setSensorDataToDefault() _airspeed.setData(0.0f, 0.0f); _baro.setData(122.2f); _flow.setData(_flow.dataAtRest()); + _flow1.setData(_flow1.dataAtRest()); _gps.setData(_gps.getDefaultGpsData()); _imu.setData(Vector3f{0.0f, 0.0f, -CONSTANTS_ONE_G}, Vector3f{0.0f, 0.0f, 0.0f}); _mag.setData(Vector3f{0.218f, 0.f, 0.43f}); @@ -187,6 +190,7 @@ void SensorSimulator::updateSensors() _gps.update(_time); _gnss_yaw.update(_time); _flow.update(_time); + _flow1.update(_time); _rng.update(_time); _vio.update(_time); _airspeed.update(_time); @@ -392,13 +396,15 @@ void SensorSimulator::setSensorDataFromTrajectory() } // Optical flow - if (_flow.isRunning()) { - flowSample flow_sample = _flow.dataAtRest(); - const Vector3f vel_body = R_world_to_body * vel_world; - flow_sample.flow_rate = - Vector2f(vel_body(1) / distance_to_ground, - -vel_body(0) / distance_to_ground); - _flow.setData(flow_sample); + for (Flow *flow : {&_flow, &_flow1}) { + if (flow->isRunning()) { + flowSample flow_sample = flow->dataAtRest(); + const Vector3f vel_body = R_world_to_body * vel_world; + flow_sample.flow_rate = + Vector2f(vel_body(1) / distance_to_ground, + -vel_body(0) / distance_to_ground); + flow->setData(flow_sample); + } } if (_gps.isRunning()) { diff --git a/src/modules/ekf2/test/sensor_simulator/sensor_simulator.h b/src/modules/ekf2/test/sensor_simulator/sensor_simulator.h index 6c2fe76201b..147305c3b69 100644 --- a/src/modules/ekf2/test/sensor_simulator/sensor_simulator.h +++ b/src/modules/ekf2/test/sensor_simulator/sensor_simulator.h @@ -102,6 +102,9 @@ public: void startFlow() { _flow.start(); } void stopFlow() { _flow.stop(); } + void startFlow1() { _flow1.start(); } + void stopFlow1() { _flow1.stop(); } + void startRangeFinder() { _rng.start(); } void stopRangeFinder() { _rng.stop(); } @@ -126,6 +129,7 @@ public: Airspeed _airspeed; Baro _baro; Flow _flow; + Flow _flow1; // second optical flow sensor (slot 1) Gps _gps; GnssYaw _gnss_yaw; Imu _imu; diff --git a/src/modules/ekf2/test/test_EKF_basics.cpp b/src/modules/ekf2/test/test_EKF_basics.cpp index 72f8efcc6f3..ffa00a8d355 100644 --- a/src/modules/ekf2/test/test_EKF_basics.cpp +++ b/src/modules/ekf2/test/test_EKF_basics.cpp @@ -384,7 +384,7 @@ TEST_F(EkfBasicsTest, global_position_from_opt_flow) const float max_flow_rate = 5.f; const float min_ground_distance = 0.f; const float max_ground_distance = 50.f; - _ekf->set_optical_flow_limits(max_flow_rate, min_ground_distance, max_ground_distance); + _ekf->flowSource(0).setLimits(max_flow_rate, min_ground_distance, max_ground_distance); _sensor_simulator.startFlow(); _ekf_wrapper.enableFlowFusion(); _sensor_simulator.startRangeFinder(); diff --git a/src/modules/ekf2/test/test_EKF_flow.cpp b/src/modules/ekf2/test/test_EKF_flow.cpp index f1d535f4863..3cb00a1b1d3 100644 --- a/src/modules/ekf2/test/test_EKF_flow.cpp +++ b/src/modules/ekf2/test/test_EKF_flow.cpp @@ -62,7 +62,7 @@ public: const float max_flow_rate = 5.f; const float min_ground_distance = 0.f; const float max_ground_distance = 50.f; - _ekf->set_optical_flow_limits(max_flow_rate, min_ground_distance, max_ground_distance); + _ekf->flowSource(0).setLimits(max_flow_rate, min_ground_distance, max_ground_distance); // run briefly to init, then manually set in air and at rest (default for a real vehicle) _ekf->init(0); diff --git a/src/modules/ekf2/test/test_EKF_flow_fusion_order.cpp b/src/modules/ekf2/test/test_EKF_flow_fusion_order.cpp index de8f1b769f4..651a06e2978 100644 --- a/src/modules/ekf2/test/test_EKF_flow_fusion_order.cpp +++ b/src/modules/ekf2/test/test_EKF_flow_fusion_order.cpp @@ -53,11 +53,14 @@ public: using SquareMatrixState = Ekf::SquareMatrixState; using Vector25 = Vector; + static constexpr float kGate = 3.f; + std::shared_ptr _ekf{std::make_shared()}; StateSample _x0{}; LatLonAlt _gpos0{0.0, 0.0, 0.f}; SquareMatrixState _P0{}; + estimator_aid_source2d_s _aid_src{}; void SetUp() override { @@ -66,10 +69,6 @@ public: _ekf->_control_status.flags.heading_observable = true; _ekf->_control_status.flags.mag = false; _ekf->_time_delayed_us = 1'000'000; - _ekf->_params.ekf2_of_gate = 3.f; - _ekf->_flow_gyro_bias.setZero(); - _ekf->_flow_sample_delayed.gyro_rate.setZero(); - _ekf->_flow_sample_delayed.quality = 255; } // a priori state and covariance: uncertain velocity, attitude and terrain with cross-correlations; @@ -130,7 +129,7 @@ public: const StateSample &state() const { return _ekf->_state; } const SquareMatrixState &covariance() const { return _ekf->P; } - const estimator_aid_source2d_s &flowAidSrc() const { return _ekf->_aid_src_optical_flow; } + const estimator_aid_source2d_s &flowAidSrc() const { return _aid_src; } // observation jacobians and innovation variances of both flow components at the prior void lineariseFlow(float R, VectorState &Hx, VectorState &Hy, Vector2f &innov_var) @@ -178,11 +177,11 @@ public: { restorePrior(); // PX4 convention: innovation = prediction - observation - const Vector2f observation = _ekf->predictFlow(_ekf->_flow_sample_delayed.gyro_rate) - innov; - _ekf->updateAidSourceStatus(_ekf->_aid_src_optical_flow, _ekf->_time_delayed_us, observation, Vector2f(R, R), - innov, innov_var, _ekf->_params.ekf2_of_gate); + const Vector2f observation = _ekf->predictFlow(Vector3f(), Vector3f()) - innov; + _ekf->updateAidSourceStatus(_aid_src, _ekf->_time_delayed_us, observation, Vector2f(R, R), + innov, innov_var, kGate); VectorState H = Hx; - return _ekf->fuseOptFlow(H, true); + return _ekf->fuseOptFlow(_aid_src, H, true); } // generic sequential fusion of two scalar observations through the helpers, in the given order diff --git a/src/modules/ekf2/test/test_EKF_flow_multi.cpp b/src/modules/ekf2/test/test_EKF_flow_multi.cpp new file mode 100644 index 00000000000..37bb5351e00 --- /dev/null +++ b/src/modules/ekf2/test/test_EKF_flow_multi.cpp @@ -0,0 +1,313 @@ +/**************************************************************************** + * + * Copyright (c) 2026 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/** + * Test the fusion of two optical flow sensors + */ + +#include +#include "EKF/ekf.h" +#include "sensor_simulator/sensor_simulator.h" +#include "sensor_simulator/ekf_wrapper.h" + + +class EkfFlowMultiTest : public ::testing::Test +{ +public: + using Flow = sensor_simulator::sensor::Flow; + + EkfFlowMultiTest(): ::testing::Test(), + _ekf{std::make_shared()}, + _sensor_simulator(_ekf), + _ekf_wrapper(_ekf) {}; + + std::shared_ptr _ekf; + SensorSimulator _sensor_simulator; + EkfWrapper _ekf_wrapper; + + static constexpr float kDistanceToGround = 5.f; + + void SetUp() override + { + for (uint8_t slot = 0; slot < 2; slot++) { + _ekf->flowSource(slot).setLimits(5.f, 0.f, 50.f); + } + + // run briefly to init, then manually set in air and at rest (default for a real vehicle) + _ekf->init(0); + _sensor_simulator.runSeconds(0.1); + _ekf->set_in_air_status(false); + _ekf->set_vehicle_at_rest(true); + + _sensor_simulator.runSeconds(7); + } + + // hover above the ground with the range finder fusing, flow is the only horizontal aiding source + void startHoverWithRangeFinder() + { + _sensor_simulator._trajectory[2].setCurrentPosition(-kDistanceToGround); + _sensor_simulator._rng.setData(kDistanceToGround, 100); + _sensor_simulator._rng.setLimits(0.1f, 9.f); + _sensor_simulator.startRangeFinder(); + + _ekf->set_in_air_status(true); + _ekf->set_vehicle_at_rest(false); + + _sensor_simulator.runSeconds(5.f); + } + + void startFlow(uint8_t slot) + { + Flow &flow = (slot == 0) ? _sensor_simulator._flow : _sensor_simulator._flow1; + flow.setData(flow.dataAtRest()); + _ekf_wrapper.enableFlowFusion(slot); + flow.start(); + } + + // flow measured by a sensor that disagrees with the vehicle motion (e.g. wrong scale or rotation) + void setInconsistentFlow(uint8_t slot) + { + Flow &flow = (slot == 0) ? _sensor_simulator._flow : _sensor_simulator._flow1; + flowSample flow_sample = flow.dataAtRest(); + flow_sample.flow_rate = Vector2f(1.f, 0.f); + flow.setData(flow_sample); + } +}; + +TEST_F(EkfFlowMultiTest, inconsistentSensorDoesNotResetVelocity) +{ + // GIVEN: two flow sensors fused while hovering + startHoverWithRangeFinder(); + startFlow(0); + startFlow(1); + _sensor_simulator.runSeconds(3.f); + + ASSERT_TRUE(_ekf->control_status_flags().opt_flow); + ASSERT_TRUE(_ekf->aid_src_optical_flow(0).fused); + ASSERT_TRUE(_ekf->aid_src_optical_flow(1).fused); + + const uint8_t vel_reset_count = _ekf->get_velNE_reset_count(); + + // WHEN: the second sensor starts to disagree with the vehicle motion + setInconsistentFlow(1); + _sensor_simulator.runSeconds(5.f); + + // THEN: the second sensor is rejected and never resets the velocity + // while the first one keeps constraining the drift + EXPECT_EQ(_ekf->get_velNE_reset_count(), vel_reset_count); + EXPECT_LT(Vector2f(_ekf->getVelocity()).norm(), 0.1f); + + EXPECT_TRUE(_ekf->control_status_flags().opt_flow); + EXPECT_TRUE(_ekf->aid_src_optical_flow(0).fused); + EXPECT_FALSE(_ekf->aid_src_optical_flow(1).fused); +} + +TEST_F(EkfFlowMultiTest, simultaneousStartResetsVelocityOnce) +{ + // GIVEN: no horizontal aiding, both sensors deliver their samples in the same updates + startHoverWithRangeFinder(); + const uint8_t vel_reset_count = _ekf->get_velNE_reset_count(); + + // WHEN: both sensors start + startFlow(0); + startFlow(1); + _sensor_simulator.runSeconds(2.f); + + // THEN: one sensor resets the velocity, the other one starts fusing on top of it + EXPECT_TRUE(_ekf->aid_src_optical_flow(0).fused); + EXPECT_TRUE(_ekf->aid_src_optical_flow(1).fused); + EXPECT_EQ(_ekf->get_velNE_reset_count(), vel_reset_count + 1); +} + +TEST_F(EkfFlowMultiTest, sensorStartDoesNotResetTerrain) +{ + // GIVEN: one flow sensor estimating the terrain after the range finder stopped + startHoverWithRangeFinder(); + startFlow(0); + _sensor_simulator.runSeconds(3.f); + + _sensor_simulator.stopRangeFinder(); + _sensor_simulator.runSeconds(5.f); + + ASSERT_TRUE(_ekf->control_status_flags().opt_flow_terrain); + ASSERT_FALSE(_ekf->control_status_flags().rng_terrain); + ASSERT_NEAR(_ekf->getHagl(), kDistanceToGround, 0.2f); + + const uint8_t hagl_reset_count = _ekf->get_hagl_reset_count(); + + // WHEN: a second sensor whose first measurements are rejected becomes available + startFlow(1); + setInconsistentFlow(1); + _sensor_simulator.runSeconds(3.f); + + // THEN: the terrain estimate of the first sensor is kept + EXPECT_EQ(_ekf->get_hagl_reset_count(), hagl_reset_count); + EXPECT_NEAR(_ekf->getHagl(), kDistanceToGround, 0.2f); + EXPECT_TRUE(_ekf->aid_src_optical_flow(0).fused); + EXPECT_FALSE(_ekf->aid_src_optical_flow(1).fused); +} + +TEST_F(EkfFlowMultiTest, sensorEnabledAtRuntimeIsFused) +{ + // GIVEN: two flow sensors publishing data, the second one disabled + startHoverWithRangeFinder(); + startFlow(0); + _ekf_wrapper.disableFlowFusion(1); + _sensor_simulator._flow1.setData(_sensor_simulator._flow1.dataAtRest()); + _sensor_simulator.startFlow1(); + _sensor_simulator.runSeconds(3.f); + + EXPECT_TRUE(_ekf->aid_src_optical_flow(0).fused); + EXPECT_EQ(_ekf->aid_src_optical_flow(1).timestamp_sample, 0u); + + // WHEN: the second sensor gets enabled in flight + _ekf_wrapper.enableFlowFusion(1); + _sensor_simulator.runSeconds(3.f); + + // THEN: it is fused without a reboot + EXPECT_TRUE(_ekf->aid_src_optical_flow(1).fused); + EXPECT_TRUE(_ekf->aid_src_optical_flow(0).fused); +} + +TEST_F(EkfFlowMultiTest, bothSensorsFusedInMotion) +{ + // GIVEN: two flow sensors while hovering + startHoverWithRangeFinder(); + startFlow(0); + startFlow(1); + _sensor_simulator.runSeconds(3.f); + + // WHEN: the vehicle moves horizontally + const Vector3f simulated_velocity(0.8f, -0.5f, 0.f); + _sensor_simulator.setTrajectoryTargetVelocity(simulated_velocity); + _sensor_simulator.runTrajectorySeconds(_sensor_simulator._trajectory[0].getTotalTime() + 2.f); + + // THEN: both sensors keep being fused and the velocity estimate follows + EXPECT_TRUE(_ekf->aid_src_optical_flow(0).fused); + EXPECT_TRUE(_ekf->aid_src_optical_flow(1).fused); + EXPECT_NEAR(_ekf->getVelocity()(0), simulated_velocity(0), 0.05f); + EXPECT_NEAR(_ekf->getVelocity()(1), simulated_velocity(1), 0.05f); +} + +TEST_F(EkfFlowMultiTest, handoverBetweenSensorRanges) +{ + // GIVEN: a short range (up to 3 m) and a long range sensor while hovering at 5 m + _ekf->flowSource(0).setLimits(5.f, 0.f, 3.f); + startHoverWithRangeFinder(); + startFlow(0); + startFlow(1); + _sensor_simulator.runSeconds(3.f); + + // THEN: only the long range sensor is fused + EXPECT_FALSE(_ekf->aid_src_optical_flow(0).fused); + EXPECT_TRUE(_ekf->aid_src_optical_flow(1).fused); + EXPECT_TRUE(_ekf->control_status_flags().opt_flow); + + // WHEN: descending into the range of the short range sensor + _sensor_simulator.setTrajectoryTargetVelocity(Vector3f(0.f, 0.f, 1.f)); + _sensor_simulator.runTrajectorySeconds(3.f); + _sensor_simulator.setTrajectoryTargetVelocity(Vector3f(0.f, 0.f, 0.f)); + _sensor_simulator.runTrajectorySeconds(3.f); + + // THEN: it starts being fused as well + ASSERT_LT(_ekf->getHagl(), 2.5f); + EXPECT_TRUE(_ekf->aid_src_optical_flow(0).fused); + EXPECT_TRUE(_ekf->aid_src_optical_flow(1).fused); +} + +TEST_F(EkfFlowMultiTest, disablingOneSensorKeepsTheOther) +{ + // GIVEN: two flow sensors fused while hovering + startHoverWithRangeFinder(); + startFlow(0); + startFlow(1); + _sensor_simulator.runSeconds(3.f); + + // WHEN: the second sensor is disabled + _ekf_wrapper.disableFlowFusion(1); + _sensor_simulator.runSeconds(3.f); + + // THEN: only the first one is still fused + EXPECT_TRUE(_ekf->control_status_flags().opt_flow); + EXPECT_TRUE(_ekf->aid_src_optical_flow(0).fused); + EXPECT_GT(_ekf->time_delayed_us() - _ekf->aid_src_optical_flow(1).time_last_fuse, 2'000'000u); +} + +TEST_F(EkfFlowMultiTest, fusionControlStopsAllSensors) +{ + // GIVEN: two flow sensors fused while hovering + startHoverWithRangeFinder(); + startFlow(0); + startFlow(1); + _sensor_simulator.runSeconds(3.f); + ASSERT_TRUE(_ekf->control_status_flags().opt_flow); + + // WHEN: optical flow fusion is disabled at runtime (EKF2_SENS_EN / FUSION_SOURCE_OF) + _ekf->getFusionControlHandle()->of.enabled = false; + _sensor_simulator.runSeconds(1.f); + + // THEN: no flow sensor is fused anymore + EXPECT_FALSE(_ekf->control_status_flags().opt_flow); + EXPECT_FALSE(_ekf->control_status_flags().opt_flow_terrain); + + // AND WHEN: enabled again + _ekf->getFusionControlHandle()->of.enabled = true; + _sensor_simulator.runSeconds(3.f); + + // THEN: flow fusion resumes + EXPECT_TRUE(_ekf->control_status_flags().opt_flow); +} + +TEST_F(EkfFlowMultiTest, lateSensorExtendsHeightLimit) +{ + // GIVEN: a short range sensor (up to 3 m) and a long range sensor whose samples arrive + // behind the fusion horizon, so that each sample is consumed at the next update + _ekf->flowSource(0).setLimits(5.f, 0.f, 3.f); + _sensor_simulator._flow1.setLatencyUs(150'000); + _sensor_simulator._flow1.setRateHz(10); + startHoverWithRangeFinder(); + startFlow(0); + startFlow(1); + _sensor_simulator.runSeconds(3.f); + + ASSERT_TRUE(_ekf->aid_src_optical_flow(1).fused); + + // THEN: the height limit follows the long range sensor at every update + for (int i = 0; i < 100; i++) { + _sensor_simulator.runMicroseconds(10'000); + + float vxy_max, vz_max, hagl_min, hagl_max_z, hagl_max_xy; + _ekf->get_ekf_ctrl_limits(&vxy_max, &vz_max, &hagl_min, &hagl_max_z, &hagl_max_xy); + ASSERT_GT(hagl_max_xy, kDistanceToGround) << "update " << i; + } +} diff --git a/src/modules/ekf2/test/test_EKF_fusionLogic.cpp b/src/modules/ekf2/test/test_EKF_fusionLogic.cpp index b62690e7abe..4df710ac399 100644 --- a/src/modules/ekf2/test/test_EKF_fusionLogic.cpp +++ b/src/modules/ekf2/test/test_EKF_fusionLogic.cpp @@ -181,7 +181,7 @@ TEST_F(EkfFusionLogicTest, fallbackFromGpsToFlow) const float max_flow_rate = 5.f; const float min_ground_distance = 0.f; const float max_ground_distance = 50.f; - _ekf->set_optical_flow_limits(max_flow_rate, min_ground_distance, max_ground_distance); + _ekf->flowSource(0).setLimits(max_flow_rate, min_ground_distance, max_ground_distance); _sensor_simulator.startFlow(); _sensor_simulator.startRangeFinder(); _ekf_wrapper.enableFlowFusion(); @@ -220,7 +220,7 @@ TEST_F(EkfFusionLogicTest, doFlowFusion) const float max_flow_rate = 5.f; const float min_ground_distance = 0.f; const float max_ground_distance = 50.f; - _ekf->set_optical_flow_limits(max_flow_rate, min_ground_distance, max_ground_distance); + _ekf->flowSource(0).setLimits(max_flow_rate, min_ground_distance, max_ground_distance); _sensor_simulator.startFlow(); _sensor_simulator.startRangeFinder(); _ekf->set_vehicle_at_rest(false); diff --git a/src/modules/ekf2/test/test_EKF_terrain.cpp b/src/modules/ekf2/test/test_EKF_terrain.cpp index bd52227c25d..35216c42aef 100644 --- a/src/modules/ekf2/test/test_EKF_terrain.cpp +++ b/src/modules/ekf2/test/test_EKF_terrain.cpp @@ -103,7 +103,7 @@ public: const float max_flow_rate = 5.f; const float min_ground_distance = 0.f; const float max_ground_distance = 50.f; - _ekf->set_optical_flow_limits(max_flow_rate, min_ground_distance, max_ground_distance); + _ekf->flowSource(0).setLimits(max_flow_rate, min_ground_distance, max_ground_distance); _sensor_simulator.startFlow(); _ekf->set_in_air_status(true); diff --git a/src/modules/logger/logged_topics.cpp b/src/modules/logger/logged_topics.cpp index 198056da08d..b4fc0cf6bc1 100644 --- a/src/modules/logger/logged_topics.cpp +++ b/src/modules/logger/logged_topics.cpp @@ -253,7 +253,7 @@ void LoggedTopics::add_default_topics() add_topic_multi("vehicle_imu", 500, 4); add_topic_multi("vehicle_imu_status", 1000, 4); add_optional_topic_multi("vehicle_magnetometer", 500, 4); - add_topic("vehicle_optical_flow", 500); + add_topic_multi("vehicle_optical_flow", 500); add_topic_multi("aux_global_position", 500); add_optional_topic("pps_capture"); @@ -355,7 +355,7 @@ void LoggedTopics::add_estimator_replay_topics() // current EKF2 subscriptions add_topic("airspeed"); add_topic("airspeed_validated"); - add_topic("vehicle_optical_flow"); + add_topic_multi("vehicle_optical_flow"); add_topic("sensor_combined"); add_topic("sensor_selection"); add_topic("vehicle_air_data"); diff --git a/src/modules/mavlink/streams/OPTICAL_FLOW_RAD.hpp b/src/modules/mavlink/streams/OPTICAL_FLOW_RAD.hpp index 02f368b4c31..c80bfe09899 100644 --- a/src/modules/mavlink/streams/OPTICAL_FLOW_RAD.hpp +++ b/src/modules/mavlink/streams/OPTICAL_FLOW_RAD.hpp @@ -49,47 +49,60 @@ public: unsigned get_size() override { - return _vehicle_optical_flow_sub.advertised() ? (MAVLINK_MSG_ID_OPTICAL_FLOW_RAD_LEN + MAVLINK_NUM_NON_PAYLOAD_BYTES) : - 0; + unsigned size = 0; + + for (auto &sub : _vehicle_optical_flow_subs) { + if (sub.advertised()) { + size += MAVLINK_MSG_ID_OPTICAL_FLOW_RAD_LEN + MAVLINK_NUM_NON_PAYLOAD_BYTES; + } + } + + return size; } private: explicit MavlinkStreamOpticalFlowRad(Mavlink *mavlink) : MavlinkStream(mavlink) {} - uORB::Subscription _vehicle_optical_flow_sub{ORB_ID(vehicle_optical_flow)}; + uORB::Subscription _vehicle_optical_flow_subs[2] { + {ORB_ID(vehicle_optical_flow), 0}, + {ORB_ID(vehicle_optical_flow), 1}, + }; bool send() override { - vehicle_optical_flow_s flow; + bool sent = false; - if (_vehicle_optical_flow_sub.update(&flow)) { - mavlink_optical_flow_rad_t msg{}; + for (auto &sub : _vehicle_optical_flow_subs) { + vehicle_optical_flow_s flow; - msg.time_usec = flow.timestamp_sample; - msg.sensor_id = _vehicle_optical_flow_sub.get_instance(); - msg.integration_time_us = flow.integration_timespan_us; - msg.integrated_x = flow.pixel_flow[0]; - msg.integrated_y = flow.pixel_flow[1]; - msg.integrated_xgyro = flow.delta_angle[0]; - msg.integrated_ygyro = flow.delta_angle[1]; - msg.integrated_zgyro = flow.delta_angle[2]; - // msg.temperature = 0; - msg.quality = flow.quality; - // msg.time_delta_distance_us = 0; + if (sub.update(&flow)) { + mavlink_optical_flow_rad_t msg{}; - if (PX4_ISFINITE(flow.distance_m)) { - msg.distance = flow.distance_m; + msg.time_usec = flow.timestamp_sample; + msg.sensor_id = sub.get_instance(); + msg.integration_time_us = flow.integration_timespan_us; + msg.integrated_x = flow.pixel_flow[0]; + msg.integrated_y = flow.pixel_flow[1]; + msg.integrated_xgyro = flow.delta_angle[0]; + msg.integrated_ygyro = flow.delta_angle[1]; + msg.integrated_zgyro = flow.delta_angle[2]; + // msg.temperature = 0; + msg.quality = flow.quality; + // msg.time_delta_distance_us = 0; - } else { - msg.distance = -1; + if (PX4_ISFINITE(flow.distance_m)) { + msg.distance = flow.distance_m; + + } else { + msg.distance = -1; + } + + mavlink_msg_optical_flow_rad_send_struct(_mavlink->get_channel(), &msg); + sent = true; } - - mavlink_msg_optical_flow_rad_send_struct(_mavlink->get_channel(), &msg); - - return true; } - return false; + return sent; } }; diff --git a/src/modules/replay/ReplayEkf2.cpp b/src/modules/replay/ReplayEkf2.cpp index 33cbe8817a0..c8493cfda20 100644 --- a/src/modules/replay/ReplayEkf2.cpp +++ b/src/modules/replay/ReplayEkf2.cpp @@ -235,7 +235,7 @@ ReplayEkf2::publishEkf2Topics(const ekf2_timestamps_s &ekf2_timestamps, std::ifs handle_sensor_publication(ekf2_timestamps.airspeed_timestamp_rel, _airspeed_msg_id); handle_sensor_publication(ekf2_timestamps.airspeed_validated_timestamp_rel, _airspeed_validated_msg_id); handle_multi_sensor_publication(ekf2_timestamps.distance_sensor_timestamp_rel, _distance_sensor_msg_ids); - handle_multi_sensor_publication(ekf2_timestamps.optical_flow_timestamp_rel, _optical_flow_msg_ids); + handle_multi_sensor_publication(0, _optical_flow_msg_ids); handle_sensor_publication(ekf2_timestamps.vehicle_air_data_timestamp_rel, _vehicle_air_data_msg_id); handle_sensor_publication(ekf2_timestamps.vehicle_magnetometer_timestamp_rel, _vehicle_magnetometer_msg_id); handle_sensor_publication(ekf2_timestamps.visual_odometry_timestamp_rel, _vehicle_visual_odometry_msg_id); diff --git a/src/modules/sensors/sensor_params_flow.yaml b/src/modules/sensors/sensor_params_flow.yaml index e9ebbbf141a..a6074193064 100644 --- a/src/modules/sensors/sensor_params_flow.yaml +++ b/src/modules/sensors/sensor_params_flow.yaml @@ -1,10 +1,70 @@ +__max_num_flow_instances: &max_num_flow_instances 2 + module_name: sensors parameters: - group: Sensor Calibration definitions: - SENS_FLOW_MINHGT: + SENS_FLOW${i}_ID: description: - short: Minimum height above ground when reliant on optical flow + short: Optical flow sensor ${i} ID + long: 'Device ID of the flow sensor configured by the SENS_FLOW${i}_* + parameters. Set to 0 to automatically bind the first unbound sensor + reporting data.' + type: int32 + default: 0 + reboot_required: true + num_instances: *max_num_flow_instances + instance_start: 0 + SENS_FLOW${i}_DELAY: + description: + short: Optical flow sensor ${i} measurement delay relative to IMU + long: |- + Assumes measurement is timestamped at trailing edge of integration + period. Applied to timestamp_sample of the published data. The default + matches a DroneCAN flow node, whose frame reaches the flight controller + about 7 ms after its integration window closes. + type: float + default: 7.0 + min: 0 + max: 300 + unit: ms + reboot_required: true + decimal: 1 + num_instances: *max_num_flow_instances + instance_start: 0 + SENS_FLOW${i}_POS_X: + description: + short: X position of optical flow sensor ${i} focal point in body frame + long: Forward axis with origin relative to vehicle centre of gravity + type: float + default: 0.0 + unit: m + decimal: 3 + num_instances: *max_num_flow_instances + instance_start: 0 + SENS_FLOW${i}_POS_Y: + description: + short: Y position of optical flow sensor ${i} focal point in body frame + long: Right axis with origin relative to vehicle centre of gravity + type: float + default: 0.0 + unit: m + decimal: 3 + num_instances: *max_num_flow_instances + instance_start: 0 + SENS_FLOW${i}_POS_Z: + description: + short: Z position of optical flow sensor ${i} focal point in body frame + long: Down axis with origin relative to vehicle centre of gravity + type: float + default: 0.0 + unit: m + decimal: 3 + num_instances: *max_num_flow_instances + instance_start: 0 + SENS_FLOW${i}_HMIN: + description: + short: Minimum height above ground when reliant on optical flow ${i} long: |- This parameter defines the minimum distance from ground at which the optical flow sensor operates reliably. The sensor may be usable below this height, but accuracy will progressively reduce to loss of focus. @@ -15,9 +75,11 @@ parameters: max: 1.0 increment: 0.1 decimal: 2 - SENS_FLOW_MAXHGT: + num_instances: *max_num_flow_instances + instance_start: 0 + SENS_FLOW${i}_HMAX: description: - short: Maximum height above ground when reliant on optical flow + short: Maximum height above ground when reliant on optical flow ${i} long: |- This parameter defines the maximum distance from ground at which the optical flow sensor operates reliably. The height setpoint will be limited to be no greater than this value when the navigation system @@ -30,9 +92,11 @@ parameters: max: 100.0 increment: 0.1 decimal: 2 - SENS_FLOW_MAXR: + num_instances: *max_num_flow_instances + instance_start: 0 + SENS_FLOW${i}_MAXR: description: - short: Max angular flow rate measurable by sensor + short: Max angular flow rate measurable by sensor ${i} long: |- Magnitude of maximum angular flow rate reliably measurable by the optical flow sensor @@ -44,11 +108,13 @@ parameters: unit: rad/s min: 1.0 decimal: 2 + num_instances: *max_num_flow_instances + instance_start: 0 - group: Sensors definitions: - SENS_FLOW_ROT: + SENS_FLOW${i}_ROT: description: - short: Optical flow rotation + short: Optical flow ${i} rotation long: |- This parameter defines the yaw rotation of the optical flow relative to the vehicle body frame. Zero rotation is defined as X on flow board pointing towards front of vehicle. @@ -63,9 +129,11 @@ parameters: 6: "Yaw 270\xB0" 7: "Yaw 315\xB0" default: 0 - SENS_FLOW_RATE: + num_instances: *max_num_flow_instances + instance_start: 0 + SENS_FLOW${i}_RATE: description: - short: Optical flow max rate + short: Optical flow ${i} max rate long: |- Optical flow data maximum publication rate. This is an upper bound, actual optical flow data rate is still dependent on the sensor. @@ -75,11 +143,15 @@ parameters: max: 200 unit: Hz reboot_required: true - SENS_FLOW_SCALE: + num_instances: *max_num_flow_instances + instance_start: 0 + SENS_FLOW${i}_SCALE: description: - short: Optical flow scale factor + short: Optical flow ${i} scale factor type: float default: 1.0 min: 0.5 max: 1.5 decimal: 2 + num_instances: *max_num_flow_instances + instance_start: 0 diff --git a/src/modules/sensors/sensors.cpp b/src/modules/sensors/sensors.cpp index 4d109412993..7292031b803 100644 --- a/src/modules/sensors/sensors.cpp +++ b/src/modules/sensors/sensors.cpp @@ -68,6 +68,10 @@ Sensors::Sensors(bool hil_enabled) : _vehicle_angular_velocity.Start(); #endif // CONFIG_SENSORS_VEHICLE_ANGULAR_VELOCITY +#if defined(CONFIG_SENSORS_VEHICLE_OPTICAL_FLOW) + _flow_slot_binder.init("SENS_FLOW%u_ID", VehicleOpticalFlow::MAX_FLOW_INSTANCES); +#endif // CONFIG_SENSORS_VEHICLE_OPTICAL_FLOW + param_find("SYS_FAC_CAL_MODE"); // Parameters controlling the on-board sensor thermal calibrator @@ -137,9 +141,11 @@ Sensors::~Sensors() #if defined(CONFIG_SENSORS_VEHICLE_OPTICAL_FLOW) - if (_vehicle_optical_flow) { - _vehicle_optical_flow->Stop(); - delete _vehicle_optical_flow; + for (auto &vehicle_optical_flow : _vehicle_optical_flow) { + if (vehicle_optical_flow) { + vehicle_optical_flow->Stop(); + delete vehicle_optical_flow; + } } #endif // CONFIG_SENSORS_VEHICLE_OPTICAL_FLOW @@ -433,14 +439,16 @@ void Sensors::InitializeVehicleMagnetometer() #if defined(CONFIG_SENSORS_VEHICLE_OPTICAL_FLOW) void Sensors::InitializeVehicleOpticalFlow() { - if (_vehicle_optical_flow == nullptr) { - uORB::Subscription sensor_optical_flow_sub{ORB_ID(sensor_optical_flow)}; + for (uint8_t i = 0; i < VehicleOpticalFlow::MAX_FLOW_INSTANCES; i++) { + if (_vehicle_optical_flow[i] == nullptr) { + uORB::Subscription sensor_optical_flow_sub{ORB_ID(sensor_optical_flow), i}; - if (sensor_optical_flow_sub.advertised()) { - _vehicle_optical_flow = new VehicleOpticalFlow(); + if (sensor_optical_flow_sub.advertised()) { + _vehicle_optical_flow[i] = new VehicleOpticalFlow(i, _flow_slot_binder, _vehicle_optical_flow_pubs); - if (_vehicle_optical_flow) { - _vehicle_optical_flow->Start(); + if (_vehicle_optical_flow[i]) { + _vehicle_optical_flow[i]->Start(); + } } } } @@ -669,9 +677,11 @@ int Sensors::print_status() #if defined(CONFIG_SENSORS_VEHICLE_OPTICAL_FLOW) - if (_vehicle_optical_flow) { - PX4_INFO_RAW("\n"); - _vehicle_optical_flow->PrintStatus(); + for (auto &vehicle_optical_flow : _vehicle_optical_flow) { + if (vehicle_optical_flow) { + PX4_INFO_RAW("\n"); + vehicle_optical_flow->PrintStatus(); + } } #endif // CONFIG_SENSORS_VEHICLE_OPTICAL_FLOW diff --git a/src/modules/sensors/sensors.hpp b/src/modules/sensors/sensors.hpp index a588bdee317..be7fafb385f 100644 --- a/src/modules/sensors/sensors.hpp +++ b/src/modules/sensors/sensors.hpp @@ -212,7 +212,9 @@ private: #endif // CONFIG_SENSORS_VEHICLE_GPS_POSITION #if defined(CONFIG_SENSORS_VEHICLE_OPTICAL_FLOW) - VehicleOpticalFlow *_vehicle_optical_flow {nullptr}; + VehicleOpticalFlow *_vehicle_optical_flow[VehicleOpticalFlow::MAX_FLOW_INSTANCES] {}; + SensorSlotBinder _flow_slot_binder{}; + VehicleOpticalFlow::Publications _vehicle_optical_flow_pubs{}; uint8_t _n_optical_flow{0}; #endif // CONFIG_SENSORS_VEHICLE_OPTICAL_FLOW diff --git a/src/modules/sensors/vehicle_optical_flow/VehicleOpticalFlow.cpp b/src/modules/sensors/vehicle_optical_flow/VehicleOpticalFlow.cpp index f53d94a6e7d..fe02fbfd8fd 100644 --- a/src/modules/sensors/vehicle_optical_flow/VehicleOpticalFlow.cpp +++ b/src/modules/sensors/vehicle_optical_flow/VehicleOpticalFlow.cpp @@ -43,12 +43,13 @@ using namespace time_literals; static constexpr uint32_t SENSOR_TIMEOUT{300_ms}; -VehicleOpticalFlow::VehicleOpticalFlow() : - ModuleParams(nullptr), - ScheduledWorkItem(MODULE_NAME, px4::wq_configurations::nav_and_controllers) +VehicleOpticalFlow::VehicleOpticalFlow(uint8_t instance, SensorSlotBinder &slot_binder, Publications &pubs) : + ScheduledWorkItem(MODULE_NAME, px4::wq_configurations::nav_and_controllers), + _pubs(pubs), + _sensor_flow_sub(this, ORB_ID(sensor_optical_flow), instance), + _instance(instance), + _slot_binder(slot_binder) { - _vehicle_optical_flow_pub.advertise(); - _gyro_integrator.set_reset_samples(1); } @@ -89,12 +90,86 @@ void VehicleOpticalFlow::ParametersUpdate() parameter_update_s param_update; _params_sub.copy(¶m_update); - updateParams(); - - _flow_rotation = get_rot_matrix((enum Rotation)_param_sens_flow_rot.get()); + UpdateParameters(); } } +bool VehicleOpticalFlow::UpdateParamSlot(uint32_t device_id) +{ + const int8_t slot = _slot_binder.slotForInstanceWithFallback(_instance, device_id); + + if (slot < 0) { + if (!_no_slot_warned) { + PX4_WARN("optical flow %" PRIu8 " (device ID %" PRIu32 ") ignored, no free SENS_FLOW slot", _instance, device_id); + _no_slot_warned = true; + } + + return false; + } + + if (slot == _param_slot) { + return true; + } + + _param_slot = slot; + + char param_name[20] {}; + + snprintf(param_name, sizeof(param_name), "SENS_FLOW%d_ROT", slot); + _param_handles.rot = param_find(param_name); + + snprintf(param_name, sizeof(param_name), "SENS_FLOW%d_SCALE", slot); + _param_handles.scale = param_find(param_name); + + snprintf(param_name, sizeof(param_name), "SENS_FLOW%d_HMIN", slot); + _param_handles.hmin = param_find(param_name); + + snprintf(param_name, sizeof(param_name), "SENS_FLOW%d_HMAX", slot); + _param_handles.hmax = param_find(param_name); + + snprintf(param_name, sizeof(param_name), "SENS_FLOW%d_MAXR", slot); + _param_handles.maxr = param_find(param_name); + + snprintf(param_name, sizeof(param_name), "SENS_FLOW%d_RATE", slot); + _param_handles.rate = param_find(param_name); + + snprintf(param_name, sizeof(param_name), "SENS_FLOW%d_DELAY", slot); + _param_handles.delay = param_find(param_name); + + snprintf(param_name, sizeof(param_name), "SENS_FLOW%d_POS_X", slot); + _param_handles.pos_x = param_find(param_name); + + snprintf(param_name, sizeof(param_name), "SENS_FLOW%d_POS_Y", slot); + _param_handles.pos_y = param_find(param_name); + + snprintf(param_name, sizeof(param_name), "SENS_FLOW%d_POS_Z", slot); + _param_handles.pos_z = param_find(param_name); + + UpdateParameters(); + + return true; +} + +void VehicleOpticalFlow::UpdateParameters() +{ + if (_param_handles.rot == PARAM_INVALID) { + return; + } + + param_get(_param_handles.rot, &_params.rot); + param_get(_param_handles.scale, &_params.scale); + param_get(_param_handles.hmin, &_params.hmin); + param_get(_param_handles.hmax, &_params.hmax); + param_get(_param_handles.maxr, &_params.maxr); + param_get(_param_handles.rate, &_params.rate); + param_get(_param_handles.delay, &_params.delay); + param_get(_param_handles.pos_x, &_params.pos(0)); + param_get(_param_handles.pos_y, &_params.pos(1)); + param_get(_param_handles.pos_z, &_params.pos(2)); + + _flow_rotation = get_rot_matrix((enum Rotation)_params.rot); +} + void VehicleOpticalFlow::Run() { perf_begin(_cycle_perf); @@ -109,7 +184,8 @@ void VehicleOpticalFlow::Run() sensor_optical_flow_s sensor_optical_flow; - if (_sensor_flow_sub.update(&sensor_optical_flow)) { + if (_sensor_flow_sub.update(&sensor_optical_flow) + && UpdateParamSlot(sensor_optical_flow.device_id)) { // clear data accumulation if there's a gap in data const uint64_t integration_gap_threshold_us = sensor_optical_flow.integration_timespan_us * 2; @@ -211,10 +287,10 @@ void VehicleOpticalFlow::Run() bool publish = true; - if (_param_sens_flow_rate.get() > 0) { - const float interval_us = 1e6f / _param_sens_flow_rate.get(); + if (_params.rate > 0) { + const float interval_us = 1e6f / _params.rate; - // don't allow publishing faster than SENS_FLOW_RATE + // don't allow publishing faster than SENS_FLOW_RATE if (_integration_timespan_us < interval_us) { publish = false; } @@ -226,7 +302,17 @@ void VehicleOpticalFlow::Run() vehicle_optical_flow.timestamp_sample = sensor_optical_flow.timestamp_sample; vehicle_optical_flow.device_id = sensor_optical_flow.device_id; - _flow_integral *= _param_sens_flow_scale.get(); + // SENS_FLOW_DELAY + const hrt_abstime delay_us = static_cast(_params.delay * 1000.f); + + if (vehicle_optical_flow.timestamp_sample > delay_us) { + vehicle_optical_flow.timestamp_sample -= delay_us; + } + + // SENS_FLOW_POS_* + _params.pos.copyTo(vehicle_optical_flow.position_offset); + + _flow_integral *= _params.scale; _flow_integral.copyTo(vehicle_optical_flow.pixel_flow); _delta_angle.copyTo(vehicle_optical_flow.delta_angle); @@ -241,44 +327,44 @@ void VehicleOpticalFlow::Run() vehicle_optical_flow.distance_m = NAN; } - // SENS_FLOW_MAXR + // SENS_FLOW_MAXR if (PX4_ISFINITE(sensor_optical_flow.max_flow_rate) - && (sensor_optical_flow.max_flow_rate <= _param_sens_flow_maxr.get())) { + && (sensor_optical_flow.max_flow_rate <= _params.maxr)) { vehicle_optical_flow.max_flow_rate = sensor_optical_flow.max_flow_rate; } else { - vehicle_optical_flow.max_flow_rate = _param_sens_flow_maxr.get(); + vehicle_optical_flow.max_flow_rate = _params.maxr; } - // SENS_FLOW_MINHGT + // SENS_FLOW_HMIN if (PX4_ISFINITE(sensor_optical_flow.min_ground_distance) - && (sensor_optical_flow.min_ground_distance >= _param_sens_flow_minhgt.get())) { + && (sensor_optical_flow.min_ground_distance >= _params.hmin)) { vehicle_optical_flow.min_ground_distance = sensor_optical_flow.min_ground_distance; } else { - vehicle_optical_flow.min_ground_distance = _param_sens_flow_minhgt.get(); + vehicle_optical_flow.min_ground_distance = _params.hmin; } - // SENS_FLOW_MAXHGT + // SENS_FLOW_HMAX if (PX4_ISFINITE(sensor_optical_flow.max_ground_distance) - && (sensor_optical_flow.max_ground_distance <= _param_sens_flow_maxhgt.get())) { + && (sensor_optical_flow.max_ground_distance <= _params.hmax)) { vehicle_optical_flow.max_ground_distance = sensor_optical_flow.max_ground_distance; } else { - vehicle_optical_flow.max_ground_distance = _param_sens_flow_maxhgt.get(); + vehicle_optical_flow.max_ground_distance = _params.hmax; } - // rotate (SENS_FLOW_ROT) + // rotate (SENS_FLOW_ROT) float zeroval = 0.f; - rotate_3f((enum Rotation)_param_sens_flow_rot.get(), vehicle_optical_flow.pixel_flow[0], + rotate_3f((enum Rotation)_params.rot, vehicle_optical_flow.pixel_flow[0], vehicle_optical_flow.pixel_flow[1], zeroval); vehicle_optical_flow.timestamp = hrt_absolute_time(); - _vehicle_optical_flow_pub.publish(vehicle_optical_flow); + _pubs.flow.publish(_param_slot, vehicle_optical_flow); // vehicle_optical_flow_vel if distance is available (for logging) if (_distance_sum_count > 0 && PX4_ISFINITE(_distance_sum)) { @@ -336,7 +422,7 @@ void VehicleOpticalFlow::Run() flow_vel.timestamp = hrt_absolute_time(); - _vehicle_optical_flow_vel_pub.publish(flow_vel); + _pubs.flow_vel.publish(_param_slot, flow_vel); } ClearAccumulatedData(); @@ -486,7 +572,7 @@ void VehicleOpticalFlow::ClearAccumulatedData() void VehicleOpticalFlow::PrintStatus() { - + PX4_INFO_RAW("vehicle_optical_flow: %" PRIu8 ", param slot: %d\n", _instance, _param_slot); } }; // namespace sensors diff --git a/src/modules/sensors/vehicle_optical_flow/VehicleOpticalFlow.hpp b/src/modules/sensors/vehicle_optical_flow/VehicleOpticalFlow.hpp index dd3022c7096..2930d11badd 100644 --- a/src/modules/sensors/vehicle_optical_flow/VehicleOpticalFlow.hpp +++ b/src/modules/sensors/vehicle_optical_flow/VehicleOpticalFlow.hpp @@ -42,11 +42,13 @@ #include #include #include +#include +#include #include -#include #include #include #include +#include #include #include #include @@ -62,10 +64,18 @@ namespace sensors { -class VehicleOpticalFlow : public ModuleParams, public px4::ScheduledWorkItem +class VehicleOpticalFlow : public px4::ScheduledWorkItem { public: - VehicleOpticalFlow(); + static constexpr uint8_t MAX_FLOW_INSTANCES = 2; + + // indexed by SENS_FLOW slot, shared by all instances + struct Publications { + SlotPublications flow{}; + SlotPublications flow_vel{}; + }; + + VehicleOpticalFlow(uint8_t instance, SensorSlotBinder &slot_binder, Publications &pubs); ~VehicleOpticalFlow() override; bool Start(); @@ -88,8 +98,7 @@ private: static constexpr int MAX_SENSOR_COUNT = 3; - uORB::Publication _vehicle_optical_flow_pub{ORB_ID(vehicle_optical_flow)}; - uORB::Publication _vehicle_optical_flow_vel_pub{ORB_ID(vehicle_optical_flow_vel)}; + Publications &_pubs; uORB::Subscription _params_sub{ORB_ID(parameter_update)}; @@ -97,7 +106,7 @@ private: uORB::Subscription _vehicle_attitude_sub{ORB_ID(vehicle_attitude)}; - uORB::SubscriptionCallbackWorkItem _sensor_flow_sub{this, ORB_ID(sensor_optical_flow)}; + uORB::SubscriptionCallbackWorkItem _sensor_flow_sub; uORB::SubscriptionCallbackWorkItem _sensor_gyro_sub{this, ORB_ID(sensor_gyro)}; uORB::SubscriptionCallbackWorkItem _sensor_selection_sub{this, ORB_ID(sensor_selection)}; @@ -138,13 +147,39 @@ private: RingBuffer _gyro_buffer{}; RingBuffer _range_buffer{}; - DEFINE_PARAMETERS( - (ParamInt) _param_sens_flow_rot, - (ParamFloat) _param_sens_flow_minhgt, - (ParamFloat) _param_sens_flow_maxhgt, - (ParamFloat) _param_sens_flow_maxr, - (ParamFloat) _param_sens_flow_rate, - (ParamFloat) _param_sens_flow_scale - ) + const uint8_t _instance; + + // uORB instance -> SENS_FLOW parameter slot mapping (by device ID, SENS_FLOW_ID) + SensorSlotBinder &_slot_binder; + int8_t _param_slot{-1}; + bool _no_slot_warned{false}; + + // per-sensor parameters (SENS_FLOW_*), resolved by name + struct ParamHandles { + param_t rot{PARAM_INVALID}; + param_t scale{PARAM_INVALID}; + param_t hmin{PARAM_INVALID}; + param_t hmax{PARAM_INVALID}; + param_t maxr{PARAM_INVALID}; + param_t rate{PARAM_INVALID}; + param_t delay{PARAM_INVALID}; + param_t pos_x{PARAM_INVALID}; + param_t pos_y{PARAM_INVALID}; + param_t pos_z{PARAM_INVALID}; + } _param_handles; + + struct Params { + int32_t rot{0}; + float scale{1.f}; + float hmin{0.08f}; + float hmax{100.f}; + float maxr{8.f}; + float rate{70.f}; + float delay{7.f}; + matrix::Vector3f pos{}; + } _params; + + bool UpdateParamSlot(uint32_t device_id); + void UpdateParameters(); }; }; // namespace sensors diff --git a/src/modules/sensors/vehicle_optical_flow/test/VehicleOpticalFlowTest.cpp b/src/modules/sensors/vehicle_optical_flow/test/VehicleOpticalFlowTest.cpp index a97a6ba1ee9..2d969884c21 100644 --- a/src/modules/sensors/vehicle_optical_flow/test/VehicleOpticalFlowTest.cpp +++ b/src/modules/sensors/vehicle_optical_flow/test/VehicleOpticalFlowTest.cpp @@ -66,6 +66,8 @@ public: class VehicleOpticalFlowTestable : public sensors::VehicleOpticalFlow { public: + using sensors::VehicleOpticalFlow::VehicleOpticalFlow; + void UpdateDistanceSensorPublic() { VehicleOpticalFlow::UpdateDistanceSensor(); @@ -82,6 +84,9 @@ public: uORB::Manager::initialize(); } + + SensorSlotBinder _flow_slot_binder{}; + sensors::VehicleOpticalFlow::Publications _flow_pubs{}; void TearDown() override { uORB::Manager::terminate(); @@ -96,7 +101,7 @@ TEST_F(VehicleOpticalFlowTest, CameraFacingDown) orb_advertise(ORB_ID(distance_sensor), &message); // WHEN: update distance sensor - VehicleOpticalFlowTest::VehicleOpticalFlowTestable testable; + VehicleOpticalFlowTest::VehicleOpticalFlowTestable testable{0, _flow_slot_binder, _flow_pubs}; testable.UpdateDistanceSensorPublic(); // THEN: sensor selected @@ -110,7 +115,7 @@ TEST_F(VehicleOpticalFlowTest, CameraFacingForward) orb_advertise(ORB_ID(distance_sensor), &message); // WHEN: update distance sensor - VehicleOpticalFlowTest::VehicleOpticalFlowTestable testable; + VehicleOpticalFlowTest::VehicleOpticalFlowTestable testable{0, _flow_slot_binder, _flow_pubs}; testable.UpdateDistanceSensorPublic(); // THEN: sensor is not selected diff --git a/src/modules/uxrce_dds_client/dds_topics.yaml b/src/modules/uxrce_dds_client/dds_topics.yaml index 3370235f206..99a5342340d 100644 --- a/src/modules/uxrce_dds_client/dds_topics.yaml +++ b/src/modules/uxrce_dds_client/dds_topics.yaml @@ -165,9 +165,6 @@ subscriptions: - topic: /fmu/in/obstacle_distance type: px4_msgs::msg::ObstacleDistance - - topic: /fmu/in/sensor_optical_flow - type: px4_msgs::msg::SensorOpticalFlow - - topic: /fmu/in/goto_setpoint type: px4_msgs::msg::GotoSetpoint @@ -257,3 +254,8 @@ subscriptions_multi: type: px4_msgs::msg::RtcmData route_field: device_id max_instances: 4 + + - topic: /fmu/in/sensor_optical_flow + type: px4_msgs::msg::SensorOpticalFlow + route_field: device_id + max_instances: 2