diff --git a/boards/ark/can-flow-mr/init/rc.board_sensors b/boards/ark/can-flow-mr/init/rc.board_sensors index 131d5d58a82..58d211c26a6 100644 --- a/boards/ark/can-flow-mr/init/rc.board_sensors +++ b/boards/ark/can-flow-mr/init/rc.board_sensors @@ -7,10 +7,6 @@ param set-default IMU_GYRO_RATEMAX 1000 param set-default SENS_FLOW_RATE 150 param set-default SENS_IMU_CLPNOTI 0 -param set-default SENS_AFBR_S_RATE 25 -param set-default SENS_AFBR_L_RATE 5 -param set-default SENS_AFBR_MODE 1 - # Internal SPI paa3905 -s start -Y 180 diff --git a/boards/ark/dist/init/rc.board_sensors b/boards/ark/dist/init/rc.board_sensors index 16a809054c1..4945848d980 100644 --- a/boards/ark/dist/init/rc.board_sensors +++ b/boards/ark/dist/init/rc.board_sensors @@ -3,12 +3,6 @@ # board sensors init #------------------------------------------------------------------------------ -param set-default SENS_AFBR_S_RATE 25 -param set-default SENS_AFBR_L_RATE 5 -param set-default SENS_AFBR_MODE 1 -param set-default SENS_AFBR_THRESH 2 -param set-default SENS_AFBR_HYSTER 1 - param set-default MAV_SYS_ID 158 param set-default MAV_COMP_ID 158 diff --git a/docs/en/releases/1.18.md b/docs/en/releases/1.18.md index 1372f7b538d..fe727abf381 100644 --- a/docs/en/releases/1.18.md +++ b/docs/en/releases/1.18.md @@ -84,6 +84,8 @@ For users upgrading from v1.17, please take a moment to review the following bef 11. **Update AFBR-S50 startup scripts.** The `-r` command-line rotation flag is removed; set the mounting orientation via [SENS_AFBR_ROT](../advanced_config/parameter_reference.md#SENS_AFBR_ROT) instead. ([PX4-Autopilot#27385](https://github.com/PX4/PX4-Autopilot/pull/27385)) + `SENS_AFBR_S_RATE`, `SENS_AFBR_L_RATE`, `SENS_AFBR_THRESH` and `SENS_AFBR_HYSTER` are removed with the distance-based range switching; rate and dual frequency mode are now set per module by [SENS_AFBR_PROF](../advanced_config/parameter_reference.md#SENS_AFBR_PROF), or explicitly with [SENS_AFBR_RATE](../advanced_config/parameter_reference.md#SENS_AFBR_RATE) and [SENS_AFBR_DFM](../advanced_config/parameter_reference.md#SENS_AFBR_DFM). + ([PX4-Autopilot#28454](https://github.com/PX4/PX4-Autopilot/pull/28454)) ## Hardware Support diff --git a/src/drivers/distance_sensor/broadcom/afbrs50/AFBRS50.cpp b/src/drivers/distance_sensor/broadcom/afbrs50/AFBRS50.cpp index 7f5ec6663e7..6202cad5d19 100644 --- a/src/drivers/distance_sensor/broadcom/afbrs50/AFBRS50.cpp +++ b/src/drivers/distance_sensor/broadcom/afbrs50/AFBRS50.cpp @@ -33,21 +33,48 @@ #include "AFBRS50.hpp" #include "s2pi.h" +#include "timer.h" #include -#include -#include +#include + +#include +#include +#include using namespace time_literals; -AFBRS50 *g_dev{nullptr}; +ModuleBase::Descriptor AFBRS50::desc{AFBRS50::task_spawn, AFBRS50::custom_command, AFBRS50::print_usage}; + +constexpr AFBRS50::RateDfmProfile AFBRS50::kProfilesLv[]; +constexpr AFBRS50::RateDfmProfile AFBRS50::kProfilesLx[]; + +namespace +{ +// Range offset in meters to the API's Q0.15 meter format, clamped to [-1, 1). +q0_15_t metersToQ0_15(float meters) +{ + if (!PX4_ISFINITE(meters)) { + return 0; + } + + float scaled = roundf(meters * 32768.f); + + if (scaled > 32767.f) { scaled = 32767.f; } + + if (scaled < -32768.f) { scaled = -32768.f; } + + return (q0_15_t)scaled; +} +} // namespace AFBRS50::AFBRS50(): ModuleParams(nullptr), - ScheduledWorkItem(MODULE_NAME, px4::wq_configurations::hp_default), - // ScheduledWorkItem(MODULE_NAME, px4::wq_configurations::SPI6), _px4_rangefinder(0, distance_sensor_s::ROTATION_DOWNWARD_FACING) { + px4_sem_init(&_wake_sem, 0, 0); + px4_sem_setprotocol(&_wake_sem, SEM_PRIO_NONE); + int32_t rotation = _p_sens_afbr_rot.get(); // Valid orientations from distance_sensor_s: ROTATION_YAW_* (0-7), ROTATION_UPWARD_FACING (24), ROTATION_DOWNWARD_FACING (25). @@ -73,46 +100,100 @@ AFBRS50::AFBRS50(): AFBRS50::~AFBRS50() { - ScheduleClear(); + if (_hnd != nullptr) { + Argus_StopMeasurementTimer(_hnd); + // Argus_Deinit aborts any ongoing transfer and drains it synchronously: + // the library polls the S2PI layer until the (possibly deferred, see + // s2pi.cpp) abort completion has run. + Argus_Deinit(_hnd); - Argus_StopMeasurementTimer(_hnd); - Argus_Deinit(_hnd); - Argus_DestroyHandle(_hnd); + // The library binds the DRDY interrupt callback in ADS_Init and never + // clears it: detach the EXTI handler and the stored callback so a stray + // edge after teardown cannot dispatch into the destroyed handle. + px4_arch_gpiosetevent(BROADCOM_AFBR_S50_S2PI_IRQ, false, false, false, nullptr, nullptr); + S2PI_SetIrqCallback(BROADCOM_AFBR_S50_S2PI_SPI_BUS, nullptr, nullptr); + + // Same for the API's periodic timer: its hrt callout is the last + // path that could still reach measurementReadyCallback. + Timer_SetInterval(0, nullptr); + + Argus_DestroyHandle(_hnd); + } + + px4_sem_destroy(&_wake_sem); perf_free(_sample_perf); perf_free(_callback_error); perf_free(_process_measurement_error); perf_free(_status_not_ready_perf); perf_free(_trigger_fail_perf); + perf_free(_recovery_perf); + perf_free(_quality_gated_perf); + perf_free(_loop_perf); } status_t AFBRS50::measurementReadyCallback(status_t status, argus_hnd_t *hnd) { - // Called from the SPI comms thread context - STATE state = STATE::COLLECT; + // Called from the SPI bus work queue, or from an hrt callout on the + // API's internal timeout paths. ModuleBase deletes the instance before it + // clears the pointer, so the destructor's teardown order (drain, detach + // EXTI and timer) is what keeps a late completion out of freed memory; + // the null check only covers the window before the task has started. + AFBRS50 *dev = get_instance(desc); - if (up_interrupt_context()) { - // We cannot be in interrupt context - g_dev->recordCallbackError(); - status = ERROR_FAIL; - state = STATE::TRIGGER; + if (dev == nullptr) { + return ERROR_FAIL; } - if ((g_dev == nullptr) || (status != STATUS_OK)) { - g_dev->recordCallbackError(); - status = ERROR_FAIL; - state = STATE::TRIGGER; + if (status != STATUS_OK) { + dev->recordCallbackError(); } - g_dev->schedule(state); + // Always collect, error or not: Argus_EvaluateData is what releases the + // API's raw data buffer, and after two unreleased buffers the API refuses + // to start measurements and rejects configuration writes. COLLECT reports + // the non-OK result and publishes it as out of range. + dev->wake(STATE::COLLECT); return status; } -void AFBRS50::schedule(STATE state) +void AFBRS50::wake(STATE state) { + // A stale completion (an abort issued by recoverFromTriggerStall, or a + // frame that was in flight when the calibration finished) must not pull + // the state machine out of a reconfiguration. + if (_state == STATE::CONFIGURE) { + return; + } + _state = state; - ScheduleNow(); + px4_sem_post(&_wake_sem); +} + +void AFBRS50::waitForWake(hrt_abstime delay) +{ + if (delay == 0) { + return; + } + + struct timespec ts; + + px4_clock_gettime(CLOCK_REALTIME, &ts); + + abstime_to_ts(&ts, ts_to_abstime(&ts) + delay); + + // Times out or returns on a post; both are handled the same way. + px4_sem_timedwait(&_wake_sem, &ts); +} + +void AFBRS50::request_stop() +{ + // A calibration that has not started yet must not start now: the vendor + // sequence cannot be interrupted and outlives ModuleBase's stop deadline. + _calibration_requested.store(false); + ModuleBase::request_stop(); + px4_sem_post(&_wake_sem); } void AFBRS50::recordCallbackError() @@ -143,11 +224,40 @@ int AFBRS50::init() static constexpr uint32_t SPI_BAUD_RATE = 5000000; S2PI_Init(BROADCOM_AFBR_S50_S2PI_SPI_BUS, SPI_BAUD_RATE); - // Initialize device with initial mode - status_t status = Argus_InitMode(_hnd, BROADCOM_AFBR_S50_S2PI_SPI_BUS, argusModeFromParameter()); + // A negative mode parameter selects the module's default measurement mode + // as defined by the API; a mode the API rejects falls back to it as well. + int32_t mode_param = _p_sens_afbr_mode.get(); + + if (mode_param > 4) { + PX4_ERR("Invalid SENS_AFBR_MODE %ld, using module default mode", (long)mode_param); + mode_param = -1; + } + + status_t status; + + if (mode_param < 0) { + status = Argus_Init(_hnd, BROADCOM_AFBR_S50_S2PI_SPI_BUS); + + } else { + status = Argus_InitMode(_hnd, BROADCOM_AFBR_S50_S2PI_SPI_BUS, argusModeFromParameter()); + + if (status != STATUS_OK) { + PX4_ERR("Argus_InitMode %ld failed: %ld, falling back to module default mode", (long)mode_param, (long)status); + Argus_Deinit(_hnd); + Argus_DestroyHandle(_hnd); + _hnd = Argus_CreateHandle(); + + if (_hnd == nullptr) { + PX4_ERR("Handle not initialized"); + return PX4_ERROR; + } + + status = Argus_Init(_hnd, BROADCOM_AFBR_S50_S2PI_SPI_BUS); + } + } if (status != STATUS_OK) { - PX4_ERR("Argus_InitMode failed: %ld", status); + PX4_ERR("Argus_Init failed: %ld", (long)status); return PX4_ERROR; } @@ -162,57 +272,74 @@ int AFBRS50::init() PX4_INFO("AFBR-S50 Chip ID: %u, API Version: v%d.%d.%d.%u (%s)", (uint)id, a, b, c, api_version_patch, build != nullptr ? build : ARGUS_API_VERSION_BUILD); - char module_string[20] = {}; - argus_module_version_t mv = Argus_GetModuleVersion(_hnd); + _module = Argus_GetModuleVersion(_hnd); float min_distance = 0.f; float max_distance = 30.f; float fov_degrees = 6.f; - switch (mv) { + switch (_module) { case AFBR_S50MV85G_V1: case AFBR_S50MV85G_V2: case AFBR_S50MV85G_V3: max_distance = 10.f; fov_degrees = 6.f; - snprintf(module_string, sizeof(module_string), "AFBR-S50MV85G"); break; - case AFBR_S50LV85D_V1: + case AFBR_S50MX85G_V1: max_distance = 30.f; fov_degrees = 6.f; - snprintf(module_string, sizeof(module_string), "AFBR-S50LV85D"); + break; + + // Tx beam width 2x2 deg per datasheet. + case AFBR_S50LV85D_V1: + max_distance = 30.f; + fov_degrees = 2.f; break; case AFBR_S50LX85D_V1: + min_distance = 0.1f; max_distance = 50.f; - fov_degrees = 6.f; - snprintf(module_string, sizeof(module_string), "AFBR-S50LX85D"); + fov_degrees = 2.f; break; case AFBR_S50MV68B_V1: max_distance = 10.f; fov_degrees = 1.f; - snprintf(module_string, sizeof(module_string), "AFBR-S50MV68B"); + break; + + case AFBR_S50MX68B_V1: + max_distance = 30.f; + fov_degrees = 1.f; break; case AFBR_S50MV85I_V1: max_distance = 5.f; fov_degrees = 6.f; - snprintf(module_string, sizeof(module_string), "AFBR-S50MV85I"); + break; + + case AFBR_S50MX85I_V1: + max_distance = 15.f; + fov_degrees = 6.f; break; case AFBR_S50SV85K_V1: max_distance = 10.f; fov_degrees = 4.f; - snprintf(module_string, sizeof(module_string), "AFBR-S50SV85K"); + break; + + case AFBR_S50SX85K_V1: + max_distance = 30.f; + fov_degrees = 4.f; break; default: + PX4_WARN("Unknown module version: %d", (int)_module); break; } - PX4_INFO("Module: %s", module_string); + PX4_INFO("Module: %s", Argus_GetModuleName(_hnd)); + _min_distance = min_distance; _max_distance = max_distance; _px4_rangefinder.set_min_distance(min_distance); _px4_rangefinder.set_max_distance(max_distance); @@ -220,175 +347,412 @@ int AFBRS50::init() _state = STATE::CONFIGURE; // Initialization Time is 300ms - ScheduleDelayed(350_ms); + _wake_delay = 350_ms; return PX4_OK; } -void AFBRS50::Run() +void AFBRS50::run() { - perf_end(_loop_perf); - perf_begin(_loop_perf); + while (!should_exit()) { + waitForWake(_wake_delay); - if (_parameter_update_sub.updated()) { - parameter_update_s param_update; - _parameter_update_sub.copy(¶m_update); - ModuleParams::updateParams(); - } - - switch (_state) { - case STATE::CONFIGURE: { - _current_rate = (uint32_t)_p_sens_afbr_s_rate.get(); - status_t status = setRateAndDfm(_current_rate, DFM_MODE_OFF); - - if (status != STATUS_OK) { - PX4_ERR("CONFIGURE status not okay: %i", (int)status); - ScheduleDelayed(350_ms); - return; - } - - status = Argus_SetConfigurationSmartPowerSaveEnabled(_hnd, false); - - if (status != STATUS_OK) { - PX4_ERR("Argus_SetConfigurationSmartPowerSaveEnabled status not okay: %i", (int)status); - // TODO: delay? - ScheduleNow(); - return; - } - - // Enable interrupt on falling edge - px4_arch_configgpio(BROADCOM_AFBR_S50_S2PI_IRQ); - - _state = STATE::TRIGGER; - ScheduleDelayed(_measurement_inverval); + if (should_exit()) { + break; } - break; - case STATE::TRIGGER: { - if (Argus_GetStatus(_hnd) != STATUS_IDLE) { - perf_count(_status_not_ready_perf); - ScheduleDelayed(_measurement_inverval / 4); - return; - } + perf_end(_loop_perf); + perf_begin(_loop_perf); - _trigger_time = hrt_absolute_time(); - status_t status = Argus_TriggerMeasurement(_hnd, measurementReadyCallback); - - if (status != STATUS_OK) { - perf_count(_trigger_fail_perf); - _state = STATE::TRIGGER; - ScheduleDelayed(1_ms); // Try again immediately - } - - // We don't reschedule, the trigger callback will schedule a collect + if (_parameter_update_sub.updated()) { + parameter_update_s param_update; + _parameter_update_sub.copy(¶m_update); + ModuleParams::updateParams(); } - break; - case STATE::COLLECT: { - if (processMeasurement()) { - updateMeasurementRateFromRange(); - } + switch (_state) { + case STATE::CONFIGURE: + run_state_configure(); + break; - _state = STATE::TRIGGER; + case STATE::TRIGGER: + run_state_trigger(); + break; - auto elapsed = hrt_elapsed_time(&_trigger_time); + case STATE::COLLECT: + run_state_collect(); + break; - if (elapsed > _measurement_inverval) { - ScheduleNow(); + case STATE::CALIBRATE: + run_state_calibrate(); + break; - } else { - ScheduleDelayed(_measurement_inverval - elapsed); - } + default: + break; } - break; - - default: - break; } } -bool AFBRS50::processMeasurement() +// Shipped configuration (SENS_AFBR_MODE = -1, SENS_AFBR_RATE = 0, +// SENS_AFBR_DFM = -1): +// LV85D: Long Range mode @ 20 Hz, DFM 4X (50 m unambiguous range) +// LX85D: Long Range mode @ 15 Hz, DFM 4X (~100 m unambiguous range) +// other modules: the API's mode defaults +// +// Frame time is the exposure budget: the dynamic configuration adaption +// raises integration depth until the frame is full, so radiometric reach +// scales inversely with rate, down to the API's 200 ms frame time cap. +void AFBRS50::run_state_configure() +{ + // A raw buffer left behind by an aborted or lost frame blocks every + // configuration write until it has been evaluated. + for (unsigned i = 0; (i < 2) && Argus_IsDataEvaluationPending(_hnd); i++) { + argus_results_t res{}; + Argus_EvaluateData(_hnd, &res); + } + + if (_configure_failures >= kMaxConfigureFailures) { + // Argus_GetStatus reports a sticky error (TIMEOUT, NOT_CONNECTED) + // as its status, and Argus_Abort is not documented to clear it, so + // awaitIdle() alone cannot make progress: re-initialize the device + // in its current mode and apply the configuration from scratch. + _configure_failures = 0; + PX4_ERR("CONFIGURE failed %u times, reinitializing device", (uint)kMaxConfigureFailures); + status_t reinit_status = Argus_ReinitMode(_hnd, (argus_mode_t)0); + + if (reinit_status != STATUS_OK) { + PX4_ERR("Argus_ReinitMode failed: %i", (int)reinit_status); + _wake_delay = 350_ms; + return; + } + } + + status_t status = STATUS_OK; + const int32_t dfm_param = _p_sens_afbr_dfm.get(); + + if (dfm_param >= 0 && dfm_param <= DFM_MODE_8X) { + status = setDfm(static_cast(dfm_param)); + + } else if (dfm_param > DFM_MODE_8X) { + // Parameter metadata is not enforced at set time: degrade to the + // mode default instead of failing. + PX4_ERR("Invalid SENS_AFBR_DFM %ld, keeping mode default", (long)dfm_param); + + } else { + const int dfm_default = defaultDfm(); + + if (dfm_default >= 0) { + status = setDfm(static_cast(dfm_default)); + } + } + + if (status == STATUS_OK) { + const int32_t rate_param = _p_sens_afbr_rate.get(); + uint32_t rate_hz = (rate_param > 0) ? (uint32_t)rate_param : defaultRate(); + + if (rate_hz > 0) { + // Below kMinRateHz the API rejects the configuration outright + // and CONFIGURE would retry the same invalid value forever. + if (rate_hz < kMinRateHz) { + PX4_WARN("SENS_AFBR_RATE %u Hz is below the API's 5 Hz floor, clamping", (uint)rate_hz); + rate_hz = kMinRateHz; + } + + status = setRate(rate_hz); + + } else { + // Uncharacterized module: keep the measurement mode's frame time. + uint32_t frame_time_us = 0; + status = Argus_GetConfigurationFrameTime(_hnd, &frame_time_us); + + if ((status == STATUS_OK) && (frame_time_us == 0)) { + status = ERROR_FAIL; + } + + if (status == STATUS_OK) { + _measurement_inverval = frame_time_us; + } + } + } + + if (status != STATUS_OK) { + PX4_ERR("CONFIGURE status not okay: %i", (int)status); + configureFailed(); + return; + } + + status = Argus_SetConfigurationSmartPowerSaveEnabled(_hnd, false); + + if (status != STATUS_OK) { + PX4_ERR("Argus_SetConfigurationSmartPowerSaveEnabled status not okay: %i", (int)status); + configureFailed(); + return; + } + + int32_t snm_mode = _p_sens_afbr_snm.get(); + + if (snm_mode < 0 || snm_mode > SNM_MODE_DYNAMIC_PLUS) { + PX4_ERR("Invalid SENS_AFBR_SNM %ld, using dynamic plus", (long)snm_mode); + snm_mode = SNM_MODE_DYNAMIC_PLUS; + } + + status = Argus_SetConfigurationShotNoiseMonitorMode(_hnd, static_cast(snm_mode)); + + if (status != STATUS_OK) { + PX4_ERR("Argus_SetConfigurationShotNoiseMonitorMode status not okay: %i", (int)status); + configureFailed(); + return; + } + + // Apply the stored range offset calibration on top of the factory + // calibration loaded at init. Zero means "not calibrated": leave the + // factory global offsets untouched. The smallest representable offset is + // 1/32768 m, so the epsilon separates a real calibration from 0.0. + const float ofs_lo = _p_sens_afbr_ofs_lo.get(); + const float ofs_hi = _p_sens_afbr_ofs_hi.get(); + + if ((fabsf(ofs_lo) > 1e-6f) || (fabsf(ofs_hi) > 1e-6f)) { + // Non-fatal: a rejected offset write must not block measurements. + if (Argus_SetCalibrationGlobalRangeOffsets(_hnd, metersToQ0_15(ofs_lo), + metersToQ0_15(ofs_hi)) != STATUS_OK) { + PX4_ERR("Argus_SetCalibrationGlobalRangeOffsets failed"); + + } else { + PX4_INFO("applied stored range offsets: low=%.4f m high=%.4f m", (double)ofs_lo, (double)ofs_hi); + } + } + + // Enable interrupt on falling edge + px4_arch_configgpio(BROADCOM_AFBR_S50_S2PI_IRQ); + + updateMaxDistanceFromApi(); + printConfiguration(); + + _configure_failures = 0; + _state = STATE::TRIGGER; + _wake_delay = _measurement_inverval; +} + +void AFBRS50::configureFailed() +{ + _configure_failures++; + _wake_delay = 350_ms; +} + +void AFBRS50::run_state_trigger() +{ + // A calibration request takes priority over the next measurement. + // Intercept here, before triggering, so no measurement/callback is + // in flight when the (blocking) calibration sequence runs. + if (_calibration_requested.load()) { + _state = STATE::CALIBRATE; + _wake_delay = 0; + return; + } + + if (Argus_GetStatus(_hnd) != STATUS_IDLE) { + perf_count(_status_not_ready_perf); + + if (++_trigger_retry_count >= kMaxTriggerRetries) { + recoverFromTriggerStall("device not idle"); + + } else { + _wake_delay = _measurement_inverval / 4; + } + + return; + } + + _trigger_time = hrt_absolute_time(); + status_t status = Argus_TriggerMeasurement(_hnd, measurementReadyCallback); + + if (status != STATUS_OK) { + perf_count(_trigger_fail_perf); + + if (++_trigger_retry_count >= kMaxTriggerRetries) { + recoverFromTriggerStall("trigger rejected"); + return; + } + + _state = STATE::TRIGGER; + _wake_delay = _measurement_inverval / 4; + + } else { + _trigger_retry_count = 0; + // The measurement callback normally wakes the task into COLLECT + // well before this expires; if the callback is lost the state + // machine re-enters TRIGGER, where the status gate keeps it polling. + _wake_delay = 4 * _measurement_inverval; + } +} + +void AFBRS50::run_state_collect() { perf_count(_sample_perf); argus_results_t res{}; status_t evaluate_status = Argus_EvaluateData(_hnd, &res); + // Every frame is published so a receiver can tell "online, invalid + // readings" from "dropped off the bus"; signal_quality 0 marks the + // invalid ones. The distance carried alongside matters because collision + // prevention ignores quality: it enters anything at or beyond + // max_distance as free space and discards anything at or below + // min_distance. So only the device's own "nothing in range" verdict goes + // out beyond max_distance (READING_TYPE_TOO_FAR over DroneCAN); errors + // (STALLED, TIMEOUT, integrity faults) carry min_distance, which every + // consumer drops and DroneCAN encodes as READING_TYPE_UNDEFINED; a gated + // frame keeps its measured distance, since a weak return is still a + // return, with the quality floored to invalid. if ((evaluate_status != STATUS_OK) || (res.Status != STATUS_OK)) { perf_count(_process_measurement_error); - return 0; + recordMeasurementError((evaluate_status != STATUS_OK) ? evaluate_status : res.Status); + + const bool no_object = (evaluate_status == STATUS_OK) && (res.Status == STATUS_ARGUS_NO_OBJECT); + _px4_rangefinder.update(hrt_absolute_time(), no_object ? (_max_distance + 1.0f) : _min_distance, 0); + + } else { + uint32_t result_mm = res.Bin.Range / (Q9_22_ONE / 1000); + float distance = static_cast(result_mm) / 1000.f; + int8_t quality = res.Bin.SignalQuality; + + if ((_p_sens_afbr_qmin.get() > 0) && (quality < _p_sens_afbr_qmin.get())) { + perf_count(_quality_gated_perf); + quality = 0; + } + + // max_distance is the module's rated reach, which DFM's unambiguous + // range can exceed: a return this far out is a real object beyond + // the rated range, not an error, so report it as too far. + if (distance > _max_distance * 1.5f) { + distance = _max_distance + 1.0f; + quality = 0; + } + + _current_distance = distance; + _px4_rangefinder.update(((res.TimeStamp.sec * 1000000ULL) + res.TimeStamp.usec), distance, quality); } - uint32_t result_mm = res.Bin.Range / (Q9_22_ONE / 1000); - float distance = static_cast(result_mm) / 1000.f; - int8_t quality = res.Bin.SignalQuality; + _state = STATE::TRIGGER; - // Signal quality indicates 100% for good signals, 50% and lower for weak signals. - // 1% is an errored signal (not reliable). Signal Quality of 0% is unknown. - if (quality == 1) { - quality = 0; - } + auto elapsed = hrt_elapsed_time(&_trigger_time); - if (distance > _max_distance * 1.5f) { - distance = 0.0; - quality = 0; - } - - _current_distance = distance; - _current_quality = quality; - _px4_rangefinder.update(((res.TimeStamp.sec * 1000000ULL) + res.TimeStamp.usec), distance, quality); - return 1; + _wake_delay = (elapsed > _measurement_inverval) ? 0 : (_measurement_inverval - elapsed); } -// TODO: Require 3 consecutive readings on same side of fence to mode switch -void AFBRS50::updateMeasurementRateFromRange() +void AFBRS50::recoverFromTriggerStall(const char *reason) { - bool valid_distance = (_current_distance > 0) && (_current_quality > 0); - bool switch_allowed = hrt_elapsed_time(&_last_rate_switch) > 1_s; + // The 4x frame-time watchdog recovers a lost completion callback, but a + // device or library wedged out of IDLE would keep the TRIGGER state + // polling forever: abort whatever is stuck and run a full reconfigure. + perf_count(_recovery_perf); + PX4_ERR("no trigger progress after %u attempts (%s), aborting and reconfiguring", + (uint)kMaxTriggerRetries, reason); - if (valid_distance && switch_allowed) { + // Enter CONFIGURE before aborting so the abort completion, whether it + // arrives synchronously or once the in-flight SPI exchange drains, is + // dropped by wake() instead of restarting the trigger loop. + _trigger_retry_count = 0; + _state = STATE::CONFIGURE; - bool above_threshold = _current_distance >= (_p_sens_afbr_thresh.get() + _p_sens_afbr_hyster.get()); - bool in_long_range_mode = _current_rate == _p_sens_afbr_l_rate.get(); + status_t status = Argus_Abort(_hnd); - bool below_threshold = _current_distance <= (_p_sens_afbr_thresh.get() - _p_sens_afbr_hyster.get()); - bool in_short_range_mode = _current_rate == _p_sens_afbr_s_rate.get(); + if (status != STATUS_OK) { + PX4_ERR("Argus_Abort failed: %i", (int)status); + } - if (above_threshold && !in_long_range_mode) { + _wake_delay = 350_ms; +} - _current_rate = _p_sens_afbr_l_rate.get(); - auto status = setRateAndDfm(_current_rate, DFM_MODE_8X); +void AFBRS50::recordMeasurementError(status_t status) +{ + _last_error_status = status; + _last_error_time = hrt_absolute_time(); - if (status != STATUS_OK) { - PX4_ERR("set_rate status not okay: %ld", status); - - } else { - PX4_INFO("switched to long range rate: %d", _current_rate); - _last_rate_switch = hrt_absolute_time(); - } - - } else if (below_threshold && !in_short_range_mode) { - - _current_rate = _p_sens_afbr_s_rate.get(); - auto status = setRateAndDfm(_current_rate, DFM_MODE_OFF); - - if (status != STATUS_OK) { - PX4_ERR("set_rate status not okay: %ld", status); - - } else { - PX4_INFO("switched to short range rate: %d", _current_rate); - _last_rate_switch = hrt_absolute_time(); - } + for (auto &slot : _error_status_counts) { + if ((slot.count == 0) || (slot.status == status)) { + slot.status = status; + slot.count++; + return; } } + + _error_status_other++; } -status_t AFBRS50::setRateAndDfm(uint32_t rate_hz, argus_dfm_mode_t dfm_mode) +const char *AFBRS50::argusStatusName(status_t status) { - while (Argus_GetStatus(_hnd) != STATUS_IDLE) { + switch (status) { + case STATUS_ARGUS_NO_OBJECT: return "NO_OBJECT"; + + case ERROR_ARGUS_STALLED: return "STALLED"; + + case ERROR_ARGUS_BIAS_VOLTAGE_REINIT: return "BIAS_VOLTAGE_REINIT"; + + case ERROR_ARGUS_LASER_MONITOR_INACTIVE: return "LASER_MONITOR_INACTIVE"; + + case ERROR_ARGUS_BGL_EXCEEDANCE: return "BGL_EXCEEDANCE"; + + case ERROR_ARGUS_XTALK_AMPLITUDE_EXCEEDANCE: return "XTALK_AMPLITUDE_EXCEEDANCE"; + + case ERROR_ARGUS_LASER_FAILURE: return "LASER_FAILURE"; + + case ERROR_ARGUS_DATA_INTEGRITY_LOST: return "DATA_INTEGRITY_LOST"; + + case STATUS_ARGUS_PLL_NOT_LOCKED: return "PLL_NOT_LOCKED"; + + case ERROR_ARGUS_BUFFER_EMPTY: return "BUFFER_EMPTY"; + + case ERROR_TIMEOUT: return "TIMEOUT"; + + case ERROR_ABORTED: return "ABORTED"; + + case ERROR_FAIL: return "FAIL"; + + default: return "?"; + } +} + +const char *AFBRS50::argusModeName(argus_mode_t mode) +{ + switch (mode) { + case ARGUS_MODE_SHORT_RANGE: return "Short Range"; + + case ARGUS_MODE_LONG_RANGE: return "Long Range"; + + case ARGUS_MODE_HIGH_SPEED_SHORT_RANGE: return "High Speed Short Range"; + + case ARGUS_MODE_HIGH_SPEED_LONG_RANGE: return "High Speed Long Range"; + + case ARGUS_MODE_HIGH_PRECISION_SHORT_RANGE: return "High Precision Short Range"; + + default: return "?"; + } +} + +status_t AFBRS50::awaitIdle() +{ + // Bounded wait; only used while configuring, before measurements run. + for (int i = 0; i < 100; i++) { + if (Argus_GetStatus(_hnd) == STATUS_IDLE) { + return STATUS_OK; + } + px4_usleep(1_ms); } - status_t status = Argus_SetConfigurationDFMMode(_hnd, dfm_mode); + return ERROR_TIMEOUT; +} + +status_t AFBRS50::setDfm(argus_dfm_mode_t dfm_mode) +{ + status_t status = awaitIdle(); + + if (status != STATUS_OK) { + PX4_ERR("setDfm: device not idle: %i", (int)status); + return status; + } + + status = Argus_SetConfigurationDFMMode(_hnd, dfm_mode); if (status != STATUS_OK) { PX4_ERR("Argus_SetConfigurationDFMMode status not okay: %i", (int)status); @@ -404,7 +768,19 @@ status_t AFBRS50::setRateAndDfm(uint32_t rate_hz, argus_dfm_mode_t dfm_mode) } if (result_mode != dfm_mode) { - PX4_ERR("Argus_SetConfigurationDFMMode failed: %i", (int)status); + PX4_ERR("DFM mode not applied: requested %i, got %i", (int)dfm_mode, (int)result_mode); + return ERROR_FAIL; + } + + return STATUS_OK; +} + +status_t AFBRS50::setRate(uint32_t rate_hz) +{ + status_t status = awaitIdle(); + + if (status != STATUS_OK) { + PX4_ERR("setRate: device not idle: %i", (int)status); return status; } @@ -415,18 +791,80 @@ status_t AFBRS50::setRateAndDfm(uint32_t rate_hz, argus_dfm_mode_t dfm_mode) return status; } - uint32_t current_rate; - status = Argus_GetConfigurationFrameTime(_hnd, ¤t_rate); + uint32_t frame_time_us; + status = Argus_GetConfigurationFrameTime(_hnd, &frame_time_us); if (status != STATUS_OK) { PX4_ERR("Argus_GetConfigurationFrameTime status not okay: %i", (int)status); return status; - - } else { - _measurement_inverval = current_rate; } - return status; + if (frame_time_us == 0) { + PX4_ERR("Argus_GetConfigurationFrameTime returned 0"); + return ERROR_FAIL; + } + + _measurement_inverval = frame_time_us; + + if (frame_time_us != (1000000 / rate_hz)) { + PX4_WARN("Requested %u Hz, API set %u Hz", (uint)rate_hz, (uint)(1000000 / frame_time_us)); + } + + return STATUS_OK; +} + +const AFBRS50::RateDfmProfile *AFBRS50::profile() const +{ + int32_t index = _p_sens_afbr_prof.get(); + + if ((index < 0) || (index >= (int32_t)kProfileCount)) { + index = 0; + } + + switch (_module) { + case AFBR_S50LV85D_V1: + return &kProfilesLv[index]; + + case AFBR_S50LX85D_V1: + return &kProfilesLx[index]; + + default: + return nullptr; + } +} + +int AFBRS50::defaultDfm() const +{ + // -1: the measurement mode's own DFM default stands. + const RateDfmProfile *p = profile(); + return (p != nullptr) ? (int)p->dfm : -1; +} + +uint32_t AFBRS50::defaultRate() const +{ + // 0: the measurement mode's own frame time stands. + const RateDfmProfile *p = profile(); + return (p != nullptr) ? p->rate_hz : 0; +} + +void AFBRS50::updateMaxDistanceFromApi() +{ + uint32_t range_mm = 0; + + if (Argus_GetConfigurationUnambiguousRange(_hnd, &range_mm) != STATUS_OK || range_mm == 0) { + return; + } + + // The unambiguous range follows the measurement mode and DFM setting and + // can exceed the module's radiometric reach; the module table value from + // init() stays the upper bound. + const float api_max = static_cast(range_mm) / 1000.f; + + if (api_max < _max_distance) { + PX4_INFO("max distance limited to %.1f m by the unambiguous range", (double)api_max); + _max_distance = api_max; + _px4_rangefinder.set_max_distance(api_max); + } } argus_mode_t AFBRS50::argusModeFromParameter() @@ -434,7 +872,7 @@ argus_mode_t AFBRS50::argusModeFromParameter() int32_t mode_param = _p_sens_afbr_mode.get(); argus_mode_t mode = ARGUS_MODE_SHORT_RANGE; - if (mode_param < 0 || mode_param > 3) { + if (mode_param < 0 || mode_param > 4) { PX4_ERR("Invalid mode parameter: %li", mode_param); return mode; } @@ -456,6 +894,10 @@ argus_mode_t AFBRS50::argusModeFromParameter() mode = ARGUS_MODE_HIGH_SPEED_LONG_RANGE; break; + case 4: + mode = ARGUS_MODE_HIGH_PRECISION_SHORT_RANGE; + break; + default: break; } @@ -463,128 +905,222 @@ argus_mode_t AFBRS50::argusModeFromParameter() return mode; } -void AFBRS50::printInfo() +int AFBRS50::print_status() { perf_print_counter(_sample_perf); perf_print_counter(_callback_error); perf_print_counter(_process_measurement_error); perf_print_counter(_status_not_ready_perf); perf_print_counter(_trigger_fail_perf); + perf_print_counter(_recovery_perf); + perf_print_counter(_quality_gated_perf); perf_print_counter(_loop_perf); + + if (_last_error_status != STATUS_OK) { + PX4_INFO_RAW("last invalid result: %d (%s), %.1fs ago\n", + (int)_last_error_status, argusStatusName(_last_error_status), + (double)hrt_elapsed_time(&_last_error_time) / 1e6); + + for (const auto &slot : _error_status_counts) { + if (slot.count > 0) { + PX4_INFO_RAW(" status %d (%s): %lu\n", (int)slot.status, + argusStatusName(slot.status), (unsigned long)slot.count); + } + } + + if (_error_status_other > 0) { + PX4_INFO_RAW(" other statuses: %lu\n", (unsigned long)_error_status_other); + } + } + + PX4_INFO_RAW("profile: %ld quality gate: %ld\n", + (long)_p_sens_afbr_prof.get(), (long)_p_sens_afbr_qmin.get()); PX4_INFO_RAW("distance: %.3fm\n", (double)_current_distance); PX4_INFO_RAW("rate: %u Hz\n", (uint)(1000000 / _measurement_inverval)); + + return 0; } -namespace afbrs50 +void AFBRS50::printConfiguration() { - -static int start() -{ - if (g_dev != nullptr) { - PX4_ERR("already started"); - return PX4_ERROR; + if (_hnd == nullptr) { + return; } - g_dev = new AFBRS50(); + PX4_INFO_RAW("===== AFBR-S50 Configuration =====\n"); - if (g_dev == nullptr) { - PX4_ERR("object instantiate failed"); - return PX4_ERROR; + argus_mode_t mode; + + if (Argus_GetMeasurementMode(_hnd, &mode) == STATUS_OK) { + PX4_INFO_RAW("Measurement Mode: %s (0x%02X)\n", argusModeName(mode), (uint)mode); } - if (g_dev->init() != PX4_OK) { - PX4_ERR("driver start failed"); - delete g_dev; - g_dev = nullptr; - return PX4_ERROR; + uint32_t frame_time_us = 0; + + if (Argus_GetConfigurationFrameTime(_hnd, &frame_time_us) == STATUS_OK && frame_time_us > 0) { + PX4_INFO_RAW("Frame Time: %u us (%u Hz)\n", + (uint)frame_time_us, (uint)(1000000 / frame_time_us)); } - return PX4_OK; + argus_dfm_mode_t dfm; + + if (Argus_GetConfigurationDFMMode(_hnd, &dfm) == STATUS_OK) { + const char *s = (dfm == DFM_MODE_OFF) ? "OFF" : + (dfm == DFM_MODE_4X) ? "4X" : + (dfm == DFM_MODE_8X) ? "8X" : "?"; + PX4_INFO_RAW("DFM Mode: %s\n", s); + } + + bool sps_enabled = false; + + if (Argus_GetConfigurationSmartPowerSaveEnabled(_hnd, &sps_enabled) == STATUS_OK) { + PX4_INFO_RAW("Smart Power Save: %s\n", sps_enabled ? "enabled" : "disabled"); + } + + argus_snm_mode_t snm; + + if (Argus_GetConfigurationShotNoiseMonitorMode(_hnd, &snm) == STATUS_OK) { + const char *s = (snm == SNM_MODE_STATIC_INDOOR) ? "Static Indoor" : + (snm == SNM_MODE_STATIC_OUTDOOR) ? "Static Outdoor" : + (snm == SNM_MODE_DYNAMIC) ? "Dynamic" : + (snm == SNM_MODE_DYNAMIC_PLUS) ? "Dynamic Plus" : "?"; + PX4_INFO_RAW("Shot Noise Monitor: %s\n", s); + } + + argus_cfg_dca_t dca{}; + + if (Argus_GetConfigurationDynamicAdaption(_hnd, &dca) == STATUS_OK) { + const char *en = (dca.Enabled == DCA_ENABLE_DYNAMIC) ? "DYNAMIC" : + (dca.Enabled == DCA_ENABLE_STATIC) ? "STATIC" : + (dca.Enabled == DCA_ENABLE_OFF) ? "OFF" : "?"; + const char *pwr = (dca.Power == DCA_POWER_LOW) ? "LOW" : + (dca.Power == DCA_POWER_HIGH) ? "HIGH" : + (dca.Power == DCA_POWER_AUTO) ? "AUTO" : "?"; + PX4_INFO_RAW("DCA: %s, Power=%s, PowerSavingRatio=%u/255\n", + en, pwr, (uint)dca.PowerSavingRatio); + PX4_INFO_RAW("DCA Depth (Q10.6): Nom=%u Min(LP)=%u Min(HP)=%u Max=%u\n", + (uint)dca.DepthNom, (uint)dca.DepthMin_LowPower, + (uint)dca.DepthMin_HighPower, (uint)dca.DepthMax); + PX4_INFO_RAW("DCA Gain: Nom=%u Min=%u Max=%u\n", + (uint)dca.GainNom, (uint)dca.GainMin, (uint)dca.GainMax); + PX4_INFO_RAW("DCA Amplitude (Q12.4): Target=%u Low=%u High=%u\n", + (uint)dca.Atarget, (uint)dca.AthLow, (uint)dca.AthHigh); + } + + uint32_t uar_mm = 0; + + if (Argus_GetConfigurationUnambiguousRange(_hnd, &uar_mm) == STATUS_OK) { + PX4_INFO_RAW("Unambiguous Range: %u mm\n", (uint)uar_mm); + } + + PX4_INFO_RAW("Published Range: %.2f m\n", (double)_max_distance); + PX4_INFO_RAW("==================================\n"); } -static int status() +int AFBRS50::task_spawn(int argc, char *argv[]) { - if (g_dev == nullptr) { - PX4_ERR("driver not running"); - return PX4_ERROR; + // Argus_EvaluateData and the calibration sequence run here. + static constexpr int kStackSize = PX4_STACK_ADJUSTED(6000); + + int task_id = px4_task_spawn_cmd("afbrs50", SCHED_DEFAULT, SCHED_PRIORITY_SLOW_DRIVER, kStackSize, + (px4_main_t)&run_trampoline, (char *const *)argv); + + if (task_id < 0) { + desc.task_id = -1; + return -errno; } - g_dev->printInfo(); + desc.task_id = task_id; - return PX4_OK; + // instantiate() brings the device up, so a missing sensor fails 'start'. + if (wait_until_running(desc, 3000) < 0) { + return -1; + } + + return 0; } -static int stop() +int AFBRS50::run_trampoline(int argc, char *argv[]) { - if (g_dev == nullptr) { - PX4_ERR("driver not running"); - return PX4_ERROR; - } - - if (g_dev != nullptr) { - delete g_dev; - g_dev = nullptr; - } - - PX4_INFO("driver stopped"); - return PX4_OK; + return ModuleBase::run_trampoline_impl(desc, [](int ac, char *av[]) -> ModuleBase * { + return AFBRS50::instantiate(ac, av); + }, argc, argv); } -static int usage() +AFBRS50 *AFBRS50::instantiate(int argc, char *argv[]) { + AFBRS50 *instance = new AFBRS50(); + + if (instance == nullptr) { + PX4_ERR("alloc failed"); + return nullptr; + } + + if (instance->init() != PX4_OK) { + delete instance; + return nullptr; + } + + return instance; +} + +int AFBRS50::custom_command(int argc, char *argv[]) +{ + if (argc >= 1 && !strcmp(argv[0], "cal")) { + AFBRS50 *instance = get_instance(desc); + + if (instance == nullptr) { + PX4_ERR("driver not running"); + return PX4_ERROR; + } + + return instance->calibrationCommand(argc - 1, argv + 1); + } + + return print_usage("unknown command"); +} + +int AFBRS50::print_usage(const char *reason) +{ + if (reason) { + PX4_WARN("%s\n", reason); + } + PRINT_MODULE_DESCRIPTION( R"DESCR_STR( ### Description -Driver for the Broadcom AFBRS50. +Driver for the Broadcom AFBR-S50 time-of-flight rangefinder. ### Examples -Attempt to start driver on a specified serial device. $ afbrs50 start -Stop driver $ afbrs50 stop + +Run an absolute range offset calibration against a flat target at a known +distance (in meters), then check the result. Offsets persist to +SENS_AFBR_OFS_LO/HI and are re-applied at startup. +$ afbrs50 cal start 0.3 +$ afbrs50 cal status )DESCR_STR"); PRINT_MODULE_USAGE_NAME("afbrs50", "driver"); PRINT_MODULE_USAGE_SUBCATEGORY("distance_sensor"); - PRINT_MODULE_USAGE_COMMAND_DESCR("start", "Start driver"); - PRINT_MODULE_USAGE_PARAM_STRING('d', nullptr, nullptr, "Serial device", false); - PRINT_MODULE_USAGE_COMMAND_DESCR("stop", "Stop driver"); + PRINT_MODULE_USAGE_COMMAND("start"); + PRINT_MODULE_USAGE_COMMAND_DESCR("cal", "Range offset calibration: cal start | status | stop"); + PRINT_MODULE_USAGE_DEFAULT_COMMANDS(); return PX4_OK; } -} // namespace - extern "C" __EXPORT int afbrs50_main(int argc, char *argv[]) { - const char *myoptarg = nullptr; - - int ch = 0; - int myoptind = 1; - - while ((ch = px4_getopt(argc, argv, "d:", &myoptind, &myoptarg)) != EOF) { - switch (ch) { - default: - PX4_WARN("Unknown option"); - return afbrs50::usage(); - } + // ModuleBase::stop_command deletes the task after 5 s regardless, and the + // vendor calibration sequence blocks longer than that while the API holds + // pointers into this task's stack. Refuse the stop instead. + if ((argc > 1) && !strcmp(argv[1], "stop") && AFBRS50::calibrationRunning()) { + PX4_ERR("calibration running, retry once 'afbrs50 cal status' reports it finished"); + return PX4_ERROR; } - if (myoptind >= argc) { - return afbrs50::usage(); - } - - if (!strcmp(argv[myoptind], "start")) { - return afbrs50::start(); - - } else if (!strcmp(argv[myoptind], "status")) { - return afbrs50::status(); - - } else if (!strcmp(argv[myoptind], "stop")) { - return afbrs50::stop(); - - } - - return afbrs50::usage(); + return ModuleBase::main(AFBRS50::desc, argc, argv); } diff --git a/src/drivers/distance_sensor/broadcom/afbrs50/AFBRS50.hpp b/src/drivers/distance_sensor/broadcom/afbrs50/AFBRS50.hpp index f79aece5a11..750eeaf2511 100644 --- a/src/drivers/distance_sensor/broadcom/afbrs50/AFBRS50.hpp +++ b/src/drivers/distance_sensor/broadcom/afbrs50/AFBRS50.hpp @@ -38,75 +38,203 @@ #include #include #include +#include #include +#include #include #include -#include +#include +#include #include #include -class AFBRS50 : public ModuleParams, public px4::ScheduledWorkItem +// Runs in its own task: the API's configuration calls block on SPI +// transfers that complete on the bus work queue (s2pi.cpp), and the +// measurement completion callback wakes the task through a semaphore. +class AFBRS50 : public ModuleBase, public ModuleParams { public: AFBRS50(); ~AFBRS50() override; + static Descriptor desc; + + static int task_spawn(int argc, char *argv[]); + static AFBRS50 *instantiate(int argc, char *argv[]); + static int custom_command(int argc, char *argv[]); + static int print_usage(const char *reason = nullptr); + static int run_trampoline(int argc, char *argv[]); + + void run() override; + int print_status() override; + void request_stop() override; + + // 'afbrs50 stop' is refused while the blocking calibration sequence runs. + static bool calibrationRunning() + { + AFBRS50 *instance = get_instance(desc); + return (instance != nullptr) && instance->calibrationInProgress(); + } + enum class STATE : uint8_t { CONFIGURE, TRIGGER, COLLECT, + CALIBRATE, }; - int init(); - void printInfo(); + // 'afbrs50 cal ...' (AFBRS50_Calibration.cpp), runs on the caller's thread. + int calibrationCommand(int argc, char *argv[]); private: - void Run() override; + int init(); + + void run_state_configure(); + void run_state_trigger(); + void run_state_collect(); + + // The CALIBRATE state runs the blocking vendor sequence on this task + // (AFBRS50_Calibration.cpp). + void run_state_calibrate(); + void runCalibration(); + void requestCalibration(float target_range_m); + void cancelCalibration(); + void printCalInfo(); + bool calibrationInProgress() const { return _cal_state == CalState::RUNNING; } void recordCallbackError(); - void schedule(STATE state); - bool processMeasurement(); - void updateMeasurementRateFromRange(); + + // Called from the completion callback: move to `state` and wake the task. + void wake(STATE state); + + // Block until the completion callback or a stop request wakes the task, + // or `delay` elapses. + void waitForWake(hrt_abstime delay); + + void recoverFromTriggerStall(const char *reason); + void configureFailed(); static status_t measurementReadyCallback(status_t status, argus_hnd_t *hnd); - status_t setRateAndDfm(uint32_t rate_hz, argus_dfm_mode_t dfm_mode); + status_t awaitIdle(); + status_t setDfm(argus_dfm_mode_t dfm_mode); + status_t setRate(uint32_t rate_hz); + uint32_t defaultRate() const; + int defaultDfm() const; argus_mode_t argusModeFromParameter(); + void updateMaxDistanceFromApi(); + void printConfiguration(); + + void recordMeasurementError(status_t status); + static const char *argusStatusName(status_t status); + static const char *argusModeName(argus_mode_t mode); -private: argus_hnd_t *_hnd {nullptr}; STATE _state{STATE::CONFIGURE}; - PX4Rangefinder _px4_rangefinder; + px4_sem_t _wake_sem; - hrt_abstime _last_rate_switch{0}; + // Delay before the next state handler runs, set by the handlers; 0 runs + // the next state immediately. + hrt_abstime _wake_delay{0}; + + argus_module_version_t _module{MODULE_NONE}; + + // Absolute range offset calibration state (AFBRS50_Calibration.cpp). + enum class CalState : uint8_t { IDLE, REQUESTED, RUNNING, DONE, FAILED }; + px4::atomic_bool _calibration_requested{false}; + q9_22_t _calibration_target_range{0}; // Q9.22 meter + CalState _cal_state{CalState::IDLE}; + status_t _cal_result_status{STATUS_OK}; + q0_15_t _cal_offset_low{0}; // last applied offsets, Q0.15 meter + q0_15_t _cal_offset_high{0}; + + PX4Rangefinder _px4_rangefinder; perf_counter_t _sample_perf{perf_alloc(PC_COUNT, MODULE_NAME": sample count")}; perf_counter_t _callback_error{perf_alloc(PC_COUNT, MODULE_NAME": callback error")}; perf_counter_t _process_measurement_error{perf_alloc(PC_COUNT, MODULE_NAME": process measure error")}; perf_counter_t _status_not_ready_perf{perf_alloc(PC_COUNT, MODULE_NAME": not ready")}; perf_counter_t _trigger_fail_perf{perf_alloc(PC_COUNT, MODULE_NAME": trigger fail")}; + perf_counter_t _recovery_perf{perf_alloc(PC_COUNT, MODULE_NAME": pipeline recovery")}; + perf_counter_t _quality_gated_perf{perf_alloc(PC_COUNT, MODULE_NAME": quality gated")}; perf_counter_t _loop_perf{perf_alloc(PC_ELAPSED, MODULE_NAME": loop interval")}; + // Distribution of non-OK measurement results (the Argus_EvaluateData + // return or res.Status), dumped by 'afbrs50 status': the raw codes are the + // only clue to why frames go invalid in the field. + static constexpr unsigned kErrorStatusSlots = 8; + struct ErrorStatusCount { + status_t status{STATUS_OK}; + uint32_t count{0}; + }; + ErrorStatusCount _error_status_counts[kErrorStatusSlots] {}; + uint32_t _error_status_other{0}; + status_t _last_error_status{STATUS_OK}; + hrt_abstime _last_error_time{0}; float _current_distance{0}; - int8_t _current_quality{0}; + float _min_distance{0.f}; float _max_distance{30.f}; - int _current_rate{0}; hrt_abstime _trigger_time{0}; + // Consecutive failed trigger cycles (device not idle or trigger rejected), + // polled at a quarter frame time: 20 retries = 5 frame times without + // progress before recoverFromTriggerStall() aborts and reconfigures. + static constexpr uint32_t kMaxTriggerRetries = 20; + uint32_t _trigger_retry_count{0}; + + // Consecutive CONFIGURE failures (350 ms apart) before the device is + // re-initialized instead of retried. + static constexpr uint32_t kMaxConfigureFailures = 10; + uint32_t _configure_failures{0}; + + // The API rejects frame times above 200 ms (Argus_Dev_CheckCfg) with + // ERROR_ARGUS_INVALID_CFG, so 5 Hz is a hard rate floor. + static constexpr uint32_t kMinRateHz = 5; + + // SENS_AFBR_PROF on the two characterized modules. Frame rate is the + // dominant range knob on both: reliable range is flat across a band of + // rates and falls off above it, so Range sits at the top of that band and + // Fast at the module's native rate. DFM 4X beat the mode-default 8X on + // validity, spread and wrong-window returns at every rate flown. + struct RateDfmProfile { + uint8_t rate_hz; + uint8_t dfm; + }; + + static constexpr unsigned kProfileCount = 2; + + // LV85D: 12-20 Hz reach the same holds, 25 Hz loses ~4 m. + static constexpr RateDfmProfile kProfilesLv[kProfileCount] { + {20, DFM_MODE_4X}, // 0: Range + {50, DFM_MODE_4X}, // 1: Fast + }; + + // LX85D: 5-15 Hz reach the same holds, 25 Hz loses 3-6 m. + static constexpr RateDfmProfile kProfilesLx[kProfileCount] { + {15, DFM_MODE_4X}, // 0: Range + {25, DFM_MODE_4X}, // 1: Fast + }; + + // Selected profile for the detected module, nullptr when uncharacterized. + const RateDfmProfile *profile() const; + uORB::Subscription _parameter_update_sub{ORB_ID(parameter_update)}; uint32_t _measurement_inverval {1000000 / 50}; // 50Hz DEFINE_PARAMETERS( - (ParamInt) _p_sens_afbr_mode, - (ParamInt) _p_sens_afbr_s_rate, - (ParamInt) _p_sens_afbr_l_rate, - (ParamInt) _p_sens_afbr_thresh, - (ParamInt) _p_sens_afbr_hyster, - (ParamInt) _p_sens_afbr_rot + (ParamInt) _p_sens_afbr_mode, + (ParamInt) _p_sens_afbr_rate, + (ParamInt) _p_sens_afbr_dfm, + (ParamInt) _p_sens_afbr_snm, + (ParamInt) _p_sens_afbr_rot, + (ParamInt) _p_sens_afbr_prof, + (ParamInt) _p_sens_afbr_qmin, + (ParamFloat) _p_sens_afbr_ofs_lo, + (ParamFloat) _p_sens_afbr_ofs_hi ); }; diff --git a/src/drivers/distance_sensor/broadcom/afbrs50/AFBRS50_Calibration.cpp b/src/drivers/distance_sensor/broadcom/afbrs50/AFBRS50_Calibration.cpp new file mode 100644 index 00000000000..3ac86734793 --- /dev/null +++ b/src/drivers/distance_sensor/broadcom/afbrs50/AFBRS50_Calibration.cpp @@ -0,0 +1,276 @@ +/**************************************************************************** + * + * Copyright (c) 2025 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. + * + ****************************************************************************/ + +// AFBRS50 absolute range offset calibration (vendor sequence +// Argus_ExecuteAbsoluteRangeOffsetCalibrationSequence), driven from NSH: +// +// afbrs50 cal start flat target, perpendicular to the optical +// afbrs50 cal status axis, at a measured distance; offsets +// persist to SENS_AFBR_OFS_LO/HI and are +// re-applied at every boot (CONFIGURE). +// +// One run at a single known distance derives the global range offsets for BOTH +// laser power stages (low/high) plus the per-pixel relative offsets; the API has +// no multi-distance procedure. Motivating case: LX85D units bias low at short +// range; calibrate against a short-range target (0.3-1 m works well). +// +// This file holds every calibration-related AFBRS50 member so the main driver +// file stays measurement-oriented. + +#include "AFBRS50.hpp" + +#include +#include + +#include +#include +#include + +using namespace time_literals; + +void AFBRS50::run_state_calibrate() +{ + _calibration_requested.store(false); + _cal_state = CalState::RUNNING; + + // The sequence blocks this task for several seconds and its ADS_AwaitIdle + // loops do not yield. SCHED_PRIORITY_SLOW_DRIVER already sits below the + // work queues, so drop to SCHED_PRIORITY_DEFAULT to get out of the way of + // commander, navigator and the other application tasks too. Nothing is + // in flight: TRIGGER intercepts the request before starting a measurement. + struct sched_param param {}; + sched_getparam(0, ¶m); + const int task_priority = param.sched_priority; + param.sched_priority = SCHED_PRIORITY_DEFAULT; + sched_setparam(0, ¶m); + + runCalibration(); + + param.sched_priority = task_priority; + sched_setparam(0, ¶m); + + _state = STATE::CONFIGURE; + _wake_delay = 0; +} + +void AFBRS50::runCalibration() +{ + // Runs on the driver task in the CALIBRATE state, so nothing else touches + // the device for the duration of the sequence. + + // Make sure the device is idle and no measurement is pending. Bounded so + // a wedged device fails the calibration instead of hanging the task + // forever (a RUNNING calibration also blocks 'afbrs50 stop'). + const hrt_abstime wait_start = hrt_absolute_time(); + + while (Argus_GetStatus(_hnd) != STATUS_IDLE) { + if (hrt_elapsed_time(&wait_start) > 1_s) { + _cal_result_status = ERROR_TIMEOUT; + _cal_state = CalState::FAILED; + PX4_ERR("calibration failed: device not idle"); + return; + } + + px4_usleep(1_ms); + } + + // The absolute sequence rewrites the per-pixel relative offset tables as + // well as the two global offsets, but only the globals can be persisted: + // these boards have no NVM for the API and 64 values do not belong in + // params. Restore the factory pixel tables afterwards so the sensor runs + // in the same state CONFIGURE re-creates from the params at the next boot. + argus_cal_offset_table_t factory_pixel_offsets{}; + const bool have_pixel_offsets = (Argus_GetCalibrationPixelRangeOffsets(_hnd, &factory_pixel_offsets) == STATUS_OK); + + auto restore_pixel_offsets = [&]() { + if (!have_pixel_offsets) { + PX4_WARN("factory pixel offsets were not read, the calibrated tables stay until reboot"); + + } else if (Argus_SetCalibrationPixelRangeOffsets(_hnd, &factory_pixel_offsets) != STATUS_OK) { + PX4_WARN("could not restore the factory pixel offsets, the calibrated tables stay until reboot"); + } + }; + + const float target_m = (float)_calibration_target_range / Q9_22_ONE; + PX4_INFO("running absolute range offset calibration at %.3f m (takes a few seconds)...", (double)target_m); + + status_t status = Argus_ExecuteAbsoluteRangeOffsetCalibrationSequence(_hnd, _calibration_target_range); + + if (status < STATUS_OK) { + _cal_result_status = status; + _cal_state = CalState::FAILED; + PX4_ERR("calibration start failed: %i", (int)status); + return; + } + + // The sequence runs asynchronously (driven by background measurement + // frames); poll until it returns to idle, matching the vendor reference + // flow. Bounded by a timeout so a stalled sequence can't hold the device + // forever. + const hrt_abstime cal_start = hrt_absolute_time(); + + do { + status = Argus_GetStatus(_hnd); + px4_usleep(1_ms); + + if (should_exit()) { + Argus_Abort(_hnd); + restore_pixel_offsets(); + _cal_result_status = ERROR_ABORTED; + _cal_state = CalState::FAILED; + PX4_WARN("calibration aborted by stop"); + return; + } + + if (hrt_elapsed_time(&cal_start) > 30_s) { + restore_pixel_offsets(); + _cal_result_status = ERROR_TIMEOUT; + _cal_state = CalState::FAILED; + PX4_ERR("calibration timed out"); + return; + } + } while (status > STATUS_IDLE); + + restore_pixel_offsets(); + _cal_result_status = status; + + if (status < STATUS_OK) { + _cal_state = CalState::FAILED; + PX4_ERR("calibration failed: %i", (int)status); + return; + } + + // Read back the offsets the API applied, then persist them (as meters) to + // params so the CONFIGURE state re-applies them on the next boot. + Argus_GetCalibrationGlobalRangeOffsets(_hnd, &_cal_offset_low, &_cal_offset_high); + + _p_sens_afbr_ofs_lo.commit_no_notification((float)_cal_offset_low / 32768.f); + _p_sens_afbr_ofs_hi.commit_no_notification((float)_cal_offset_high / 32768.f); + + _cal_state = CalState::DONE; + PX4_INFO("calibration done, offsets persisted: low=%.4f m high=%.4f m", + (double)((float)_cal_offset_low / 32768.f), + (double)((float)_cal_offset_high / 32768.f)); +} + +void AFBRS50::requestCalibration(float target_range_m) +{ + _calibration_target_range = (q9_22_t)(target_range_m * Q9_22_ONE); + _cal_result_status = STATUS_OK; + _cal_state = CalState::REQUESTED; + _calibration_requested.store(true); +} + +void AFBRS50::cancelCalibration() +{ + _calibration_requested.store(false); + + // Only meaningful if it has not started yet; a running sequence is + // blocking and cannot be interrupted from here. + if (_cal_state == CalState::REQUESTED) { + _cal_state = CalState::IDLE; + } +} + +void AFBRS50::printCalInfo() +{ + const char *state_str = "IDLE"; + + switch (_cal_state) { + case CalState::IDLE: state_str = "IDLE"; break; + + case CalState::REQUESTED: state_str = "REQUESTED"; break; + + case CalState::RUNNING: state_str = "RUNNING"; break; + + case CalState::DONE: state_str = "DONE"; break; + + case CalState::FAILED: state_str = "FAILED"; break; + } + + PX4_INFO_RAW("calibration: %s\n", state_str); + PX4_INFO_RAW(" target: %.3f m\n", (double)((float)_calibration_target_range / Q9_22_ONE)); + PX4_INFO_RAW(" last status: %i\n", (int)_cal_result_status); + PX4_INFO_RAW(" offset_low: %.4f m\n", (double)((float)_cal_offset_low / 32768.f)); + PX4_INFO_RAW(" offset_high: %.4f m\n", (double)((float)_cal_offset_high / 32768.f)); + PX4_INFO_RAW(" stored (params, applied at boot): low=%.4f m high=%.4f m\n", + (double)_p_sens_afbr_ofs_lo.get(), (double)_p_sens_afbr_ofs_hi.get()); +} + +int AFBRS50::calibrationCommand(int argc, char *argv[]) +{ + if (argc < 1) { + PX4_ERR("usage: afbrs50 cal start | status | stop"); + return PX4_ERROR; + } + + if (!strcmp(argv[0], "start")) { + if (argc < 2) { + PX4_ERR("usage: afbrs50 cal start "); + return PX4_ERROR; + } + + if (calibrationInProgress()) { + PX4_ERR("calibration already in progress"); + return PX4_ERROR; + } + + float range_m = strtof(argv[1], nullptr); + + if (!(range_m > 0.f) || (range_m > 50.f)) { + PX4_ERR("invalid distance: %s", argv[1]); + return PX4_ERROR; + } + + requestCalibration(range_m); + PX4_INFO("calibration requested at %.3f m; poll with 'afbrs50 cal status'", (double)range_m); + return PX4_OK; + + } else if (!strcmp(argv[0], "status")) { + printCalInfo(); + return PX4_OK; + + } else if (!strcmp(argv[0], "stop")) { + if (calibrationInProgress()) { + PX4_ERR("sequence already running; it cannot be interrupted"); + return PX4_ERROR; + } + + cancelCalibration(); + PX4_INFO("calibration request cancelled"); + return PX4_OK; + } + + PX4_ERR("unknown cal subcommand: %s", argv[0]); + return PX4_ERROR; +} diff --git a/src/drivers/distance_sensor/broadcom/afbrs50/API/Src/s2pi.cpp b/src/drivers/distance_sensor/broadcom/afbrs50/API/Src/s2pi.cpp index ca3ce1857ec..e2186260d28 100644 --- a/src/drivers/distance_sensor/broadcom/afbrs50/API/Src/s2pi.cpp +++ b/src/drivers/distance_sensor/broadcom/afbrs50/API/Src/s2pi.cpp @@ -7,6 +7,7 @@ #include +#include #include #include @@ -15,6 +16,7 @@ #include #include +#include /*! A structure to hold all internal data required by the S2PI module. */ typedef struct { @@ -41,6 +43,17 @@ typedef struct { uint8_t *spi_rx_data; size_t spi_frame_size; + /*! Incremented by S2PI_Abort to invalidate a transfer that is already + * in flight on the work queue. */ + volatile uint8_t Generation; + + /*! Set while the work queue thread is inside the SPI exchange. */ + volatile bool InFlight; + + /*! Callback of an aborted in-flight transfer, invoked with ERROR_ABORTED + * once the exchange physically completes. */ + s2pi_callback_t AbortedCallback; + /*! The mapping of the GPIO blocks and pins for this device. */ const uint32_t GPIOs[ S2PI_IRQ + 1 ]; } @@ -59,7 +72,7 @@ static perf_counter_t irq_perf = NULL; class AFBRS50_SPI : public px4::ScheduledWorkItem { public: - AFBRS50_SPI(); + explicit AFBRS50_SPI(const px4::wq_config_t &wq_config); void schedule_now(); void schedule_clear(); @@ -69,42 +82,61 @@ private: }; -AFBRS50_SPI::AFBRS50_SPI(): - // WARNING: SPI0 only exists for nxp and raspberry pi, so we hijack it here - - // NOTE: we use SPI0 WQ since it is the 2nd highest priority thread (behind rate_ctrl). - // TODO: we should fix how SPI comms work. Async SPI comms is - // undesirable. We should use SPI TX DMA complete callback - // instead of relying on a high priority thread. - ScheduledWorkItem(MODULE_NAME, px4::wq_configurations::SPI0) +AFBRS50_SPI::AFBRS50_SPI(const px4::wq_config_t &wq_config): + // Transfers can be requested from interrupt context (the API's periodic + // timer runs on an hrt callout), so the blocking exchange is deferred to + // the work queue of the bus the sensor sits on. Since API v1.6.6 the + // library recovers a data-ready interrupt that fires before the transfer + // callback has run, so the callback is no longer deadline-critical and + // needs no elevated thread priority. + ScheduledWorkItem(MODULE_NAME, wq_config) { - // Anything to do? } void AFBRS50_SPI::Run() { + IRQ_LOCK(); + + if (s2pi_.Status != STATUS_BUSY) { + // Transfer was aborted before it started. + IRQ_UNLOCK(); + return; + } + + const uint8_t generation = s2pi_.Generation; + uint8_t *tx_data = s2pi_.spi_tx_data; + uint8_t *rx_data = s2pi_.spi_rx_data; + const size_t frame_size = s2pi_.spi_frame_size; + s2pi_.InFlight = true; + + IRQ_UNLOCK(); + px4_arch_gpiowrite(s2pi_.GPIOs[S2PI_CS], 0); - SPI_EXCHANGE(s2pi_.spidev, s2pi_.spi_tx_data, s2pi_.spi_rx_data, s2pi_.spi_frame_size); + SPI_EXCHANGE(s2pi_.spidev, tx_data, rx_data, frame_size); px4_arch_gpiowrite(s2pi_.GPIOs[S2PI_CS], 1); - //// WARNING! - // After the last SPI TX we have ~60us to execute the below - // callback otherwise the IRQ will fire and we're screwed. - // The proper way to solve this problem is to either fix - // the API or to configure SPI TX DMA callback complete - // to execute the below callback immediately. - - - // If we are pre-empted here and the IRQ fires before the - // callback has been invoked -- we're screwed. - IRQ_LOCK(); - s2pi_.Status = STATUS_IDLE; + s2pi_.InFlight = false; - if (s2pi_.Callback != 0) { - s2pi_callback_t callback = s2pi_.Callback; - s2pi_.Callback = 0; - callback(STATUS_OK, s2pi_.CallbackData); + if (s2pi_.Generation == generation) { + s2pi_.Status = STATUS_IDLE; + + if (s2pi_.Callback != 0) { + s2pi_callback_t callback = s2pi_.Callback; + s2pi_.Callback = 0; + callback(STATUS_OK, s2pi_.CallbackData); + } + + } else { + // Aborted mid-exchange: the bus only now became free, so complete + // the abort here (see S2PI_Abort). + s2pi_.Status = STATUS_IDLE; + + if (s2pi_.AbortedCallback != 0) { + s2pi_callback_t callback = s2pi_.AbortedCallback; + s2pi_.AbortedCallback = 0; + callback(ERROR_ABORTED, s2pi_.CallbackData); + } } IRQ_UNLOCK(); @@ -137,8 +169,6 @@ static AFBRS50_SPI *_spi_iface = nullptr; *****************************************************************************/ status_t S2PI_Init(s2pi_slave_t defaultSlave, uint32_t baudRate_Bps) { - (void)defaultSlave; - px4_arch_configgpio(BROADCOM_AFBR_S50_S2PI_CS); s2pi_.spidev = px4_spibus_initialize(BROADCOM_AFBR_S50_S2PI_SPI_BUS); @@ -159,9 +189,17 @@ status_t S2PI_Init(s2pi_slave_t defaultSlave, uint32_t baudRate_Bps) // has been configured. This prevents erroneous interrupts from occuring. px4_arch_gpiosetevent(BROADCOM_AFBR_S50_S2PI_IRQ, false, true, false, callback, NULL); - irq_perf = perf_alloc(PC_ELAPSED, MODULE_NAME": irq callback"); + if (irq_perf == NULL) { + irq_perf = perf_alloc(PC_ELAPSED, MODULE_NAME": irq callback"); + } - _spi_iface = new AFBRS50_SPI(); + if (_spi_iface == nullptr) { + device::Device::DeviceId device_id{}; + device_id.devid_s.bus_type = device::Device::DeviceBusType::DeviceBusType_SPI; + device_id.devid_s.bus = defaultSlave; + + _spi_iface = new AFBRS50_SPI(px4::device_bus_to_wq(device_id.devid)); + } return S2PI_SetBaudRate(baudRate_Bps); } @@ -448,18 +486,42 @@ status_t S2PI_Abort(s2pi_slave_t slave) { (void)slave; - status_t status = s2pi_.Status; + IRQ_LOCK(); /* Check if something is ongoing. */ - if (status == STATUS_IDLE) { + if (s2pi_.Status != STATUS_BUSY) { + IRQ_UNLOCK(); return STATUS_OK; } - /* Abort SPI transfer. */ - if (status == STATUS_BUSY) { + s2pi_.Generation++; + + if (s2pi_.InFlight) { + /* The exchange is physically on the wires and cannot be stopped + * (and must not be waited on: abort may run in interrupt context). + * Keep the status BUSY so nobody touches the bus and defer the + * ERROR_ABORTED completion to the work item's tail. A repeated + * abort leaves the already-stashed callback in place. */ + if (s2pi_.Callback != 0) { + s2pi_.AbortedCallback = s2pi_.Callback; + s2pi_.Callback = 0; + } + + } else { + /* Not started yet: cancel the pending work item and complete. */ _spi_iface->schedule_clear(); + s2pi_.Status = STATUS_IDLE; + + s2pi_callback_t callback = s2pi_.Callback; + s2pi_.Callback = 0; + + if (callback != 0) { + callback(ERROR_ABORTED, s2pi_.CallbackData); + } } + IRQ_UNLOCK(); + return STATUS_OK; } diff --git a/src/drivers/distance_sensor/broadcom/afbrs50/CMakeLists.txt b/src/drivers/distance_sensor/broadcom/afbrs50/CMakeLists.txt index 362cae9daed..58892470d4e 100644 --- a/src/drivers/distance_sensor/broadcom/afbrs50/CMakeLists.txt +++ b/src/drivers/distance_sensor/broadcom/afbrs50/CMakeLists.txt @@ -45,6 +45,7 @@ px4_add_module( Inc SRCS AFBRS50.cpp + AFBRS50_Calibration.cpp AFBRS50.hpp API/Src/irq.c API/Src/s2pi.cpp diff --git a/src/drivers/distance_sensor/broadcom/afbrs50/parameters.yaml b/src/drivers/distance_sensor/broadcom/afbrs50/parameters.yaml index ab3023cff29..8c54704547d 100644 --- a/src/drivers/distance_sensor/broadcom/afbrs50/parameters.yaml +++ b/src/drivers/distance_sensor/broadcom/afbrs50/parameters.yaml @@ -4,58 +4,73 @@ parameters: definitions: SENS_AFBR_MODE: description: - short: AFBR Rangefinder Mode - long: This parameter defines the mode of the AFBR Rangefinder. + short: AFBR Rangefinder Measurement Mode + long: |- + Auto selects the module's default measurement mode as defined by the + AFBR-S50 API (LV85D/LX85D: Long Range). A mode the API rejects for + the detected module falls back to the module default. type: enum values: + -1: Auto (module default) 0: Short Range Mode 1: Long Range Mode 2: High Speed Short Range Mode 3: High Speed Long Range Mode + 4: High Precision Short Range Mode + default: -1 + reboot_required: true + min: -1 + max: 4 + SENS_AFBR_RATE: + description: + short: AFBR Rangefinder Measurement Rate + long: |- + 0 selects the per-module default: on the LV85D and LX85D the rate of + the SENS_AFBR_PROF profile, on other modules the measurement mode's + default frame time. Lower rates increase the exposure budget per + frame and thus the radiometric range. The API limits the frame time + to 200 ms, so values below 5 Hz are clamped to 5 Hz. + type: int32 default: 0 + unit: Hz + reboot_required: true + min: 0 + max: 100 + SENS_AFBR_DFM: + description: + short: AFBR Rangefinder Dual Frequency Mode + long: |- + Dual frequency mode multiplies the module's base unambiguous range + (LV85D 12.5 m, LX85D 25 m) by 4 or 8, at the cost of frame time and, + at low signal, of wrong-window returns when the subframes disagree. + Auto selects DFM 4X on the LV85D and LX85D, which measured better + than the mode-default 8X on validity, spread and wrong-window returns + at every rate flown, and the measurement mode's default elsewhere. + type: enum + values: + -1: Auto + 0: DFM Off + 1: DFM 4X + 2: DFM 8X + default: -1 + reboot_required: true + min: -1 + max: 2 + SENS_AFBR_SNM: + description: + short: AFBR Rangefinder Shot Noise Monitor Mode + long: This parameter defines the mode of the AFBR Rangefinder's shot noise + monitor. + type: enum + values: + 0: Static Indoor Mode + 1: Static Outdoor Mode + 2: Dynamic Mode + 3: Dynamic Plus Mode + default: 3 reboot_required: true min: 0 max: 3 - SENS_AFBR_S_RATE: - description: - short: AFBR Rangefinder Short Range Rate - long: This parameter defines measurement rate of the AFBR Rangefinder in short - range mode. - type: int32 - default: 50 - min: 1 - max: 100 - SENS_AFBR_L_RATE: - description: - short: AFBR Rangefinder Long Range Rate - long: This parameter defines measurement rate of the AFBR Rangefinder in long - range mode. - type: int32 - default: 25 - min: 1 - max: 100 - SENS_AFBR_THRESH: - description: - short: AFBR Rangefinder Short/Long Range Threshold - long: |- - This parameter defines the threshold for switching between short and long range mode. - The mode will switch from short to long range when the distance is greater than the threshold plus the hysteresis. - The mode will switch from long to short range when the distance is less than the threshold minus the hysteresis. - type: int32 - default: 4 - unit: m - min: 1 - max: 50 - SENS_AFBR_HYSTER: - description: - short: AFBR Rangefinder Short/Long Range Threshold Hysteresis - long: This parameter defines the hysteresis for switching between short and - long range mode. - type: int32 - default: 1 - unit: m - min: 1 - max: 10 SENS_AFBR_ROT: description: short: AFBR Rangefinder Orientation @@ -76,3 +91,59 @@ parameters: reboot_required: true min: 0 max: 25 + SENS_AFBR_PROF: + description: + short: AFBR Rangefinder Performance Profile + long: |- + Trades detection range against update rate on the LV85D and LX85D; + other modules ignore it. Range: the highest rate that does not cost + reliable range (LV85D 20 Hz, LX85D 15 Hz). Fast: the module's native + rate (LV85D 50 Hz, LX85D 25 Hz) for optical flow and terrain + following near the ground; costs a few metres of reliable range in + bright light, none in low ambient light. Both profiles use DFM 4X. + An explicit SENS_AFBR_RATE or SENS_AFBR_DFM overrides the profile. + type: enum + values: + 0: Range + 1: Fast + default: 0 + reboot_required: true + min: 0 + max: 1 + SENS_AFBR_QMIN: + description: + short: AFBR Rangefinder Minimum Signal Quality + long: |- + Measurements with a signal quality below this value are published + with signal quality 0 (invalid) so consumers drop them but still see + the sensor alive. Raising it rejects unreliable readings but also the + weak long-range returns, since those are the low quality ones. + 0 publishes every measurement with its reported quality. + type: int32 + default: 0 + min: 0 + max: 100 + SENS_AFBR_OFS_LO: + description: + short: AFBR Rangefinder Range Offset (low power) + long: |- + Global range offset for the low laser power stage, applied on top of + the factory calibration at startup. Written by 'afbrs50 cal'. + 0 leaves the factory offset unchanged. + type: float + default: 0.0 + unit: m + decimal: 5 + reboot_required: true + SENS_AFBR_OFS_HI: + description: + short: AFBR Rangefinder Range Offset (high power) + long: |- + Global range offset for the high laser power stage, applied on top of + the factory calibration at startup. Written by 'afbrs50 cal'. + 0 leaves the factory offset unchanged. + type: float + default: 0.0 + unit: m + decimal: 5 + reboot_required: true