/*
 * Copyright (c) 2019-2023 Beijing Hanwei Innovation Technology Ltd. Co. and
 * its subsidiaries and affiliates (collectly called MKSEMI).
 *
 * 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, except as embedded into an MKSEMI
 *    integrated circuit in a product or a software update for such product,
 *    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 of MKSEMI nor the names of its contributors may be used
 *    to endorse or promote products derived from this software without
 *    specific prior written permission.
 *
 * 4. This software, with or without modification, must only be used with a
 *    MKSEMI integrated circuit.
 *
 * 5. Any software provided in binary form under this license must not be
 *    reverse engineered, decompiled, modified and/or disassembled.
 *
 * THIS SOFTWARE IS PROVIDED BY MKSEMI "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL MKSEMI 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 "mk_trace.h"
#include "mk_clock.h"
#include "mk_uwb.h"
#include "mk_calib.h"
#include "mk_misc.h"
#include "ranging_custom.h"
#include "lib_aoa.h"
#include "lib_ranging.h"
#if KF_EN
#include "lib_kf.h"
#endif
#if PDOA_3D_EN
#include "lib_pdoa_3d.h"
#endif
#include "board.h"

#define PRINT_PAYLOAD_EN 0
#define PRINT_PDOA_IQ_EN 0

#ifdef SE_DEMO_EN
uint8_t master_apdu_send_status;
uint8_t slave_apdu_resp_send_status;
extern void master_process_apdu(const uint8_t *ptr, uint16_t rx_len_tmp);
extern void slave_process_apdu(const uint8_t *ptr, uint16_t rx_len_tmp, uint8_t ack);
#endif

#if FILTER_EN
static void ranging_result_filter(uint16_t *distance, int16_t *azimuth, int16_t *elevation)
{
    if ((distance == NULL) || (azimuth == NULL) || (elevation == NULL))
    {
        return;
    }

#if KF_EN
    float post_range, post_azimuth, post_elevation;
    float azimuth_meas = mk_q7_to_f32(*azimuth);
    float elevation_meas = mk_q7_to_f32(*elevation);
    float range_meas = (float)*distance / 100;
    // call filter
    uint16_t target_addr = uwbs_peer_short_addr_get();
    uint8_t mac_addr[8];
    memset(mac_addr, 0, 8);
    mac_addr[0] = target_addr & 0xff;
    mac_addr[1] = (target_addr >> 8) & 0xff;
    loc_kf_filter(range_meas, KF_DATA_TYPE_RANGING, mac_addr, &post_range);
    if (uwb_app_config.session_param.aoa_result_req)
    {
        loc_kf_filter(azimuth_meas, KF_DATA_TYPE_AZIMUTH, mac_addr, &post_azimuth);
        loc_kf_filter(elevation_meas, KF_DATA_TYPE_ELEVATION, mac_addr, &post_elevation);
    }
    else
    {
        post_azimuth = azimuth_meas;
        post_elevation = elevation_meas;
    }
    // update distance
    *distance = (uint16_t)(post_range * 100);
    // update angle
    *azimuth = mk_f32_to_q7(post_azimuth);
    *elevation = mk_f32_to_q7(post_elevation);

    // LOG_INFO(TRACE_MODULE_APP, "$%u %u %d %d %d %d;\r\n", (uint16_t)(range_meas*100),(uint16_t)(post_range*100),(int16_t)azimuth_meas,(int16_t)post_azimuth,
    // (int16_t)elevation_meas, (int16_t)post_elevation);
#else
    float post_range, post_azimuth;
    int azimuth_meas = mk_q7_to_s16(*azimuth);
    float range_meas = (float)*distance;
    // call filter
    loc_post_filter(0, range_meas, azimuth_meas, &post_range, &post_azimuth);
    // update distance
    *distance = (uint16_t)(post_range);
    // update angle
    *azimuth = mk_f32_to_q7(post_azimuth);

    // LOG_INFO(TRACE_MODULE_APP, "$%u %u %d %d;\r\n", (uint16_t)(range_meas*100), (uint16_t)(post_range*100),(int16_t)azimuth_meas, (int16_t)post_azimuth);
#endif
}
#endif

/*************************************************************************************************/
/*!
 *  \brief  WSF event handler for ranging task.
 *
 *  \param  event   WSF event mask.
 *  \param  msg    WSF message.
 *
 *  \return None.
 */
/*************************************************************************************************/
void ranging_handler(wsfEventMask_t event, const void *param)
{
    const wsfMsgHdr_t *msg = (const wsfMsgHdr_t *)param;

    if (msg != NULL)
    {
        switch (msg->event)
        {
            case RANGING_DAEMON_TIMER_MSG:
            {
                uint8_t count = ranging_count_get();
                if (count == ranging_env.count_last)
                {
                    LOG_INFO(TRACE_MODULE_APP, "Ranging was suspended %u\r\n", count);
                    ranging_restart();
                }
                else
                {
                    // LOG_INFO(TRACE_MODULE_APP, "Ranging count %u %u\r\n", ranging_env.count_last, count);
                    ranging_env.count_last = count;
                }
            }
            break;

            case UWB_PKT_TX_DONE_MSG:
            {
                const struct UWB_PKT_TX_DONE_IND_T *ind = (const struct UWB_PKT_TX_DONE_IND_T *)param;
                if (ind->ranging_stage == RANGING_POLL)
                {
                    uint16_t seq_num = READ_SHORT(&ind->tx_data[2]);

#ifdef SE_DEMO_EN
                    if (ind->tx_len > (MSG_HEADER_LEN + MSG_POLL_USER_DATA_IDX))
                    {
                        master_apdu_send_status = 1;
                    }
#endif

                    LOG_INFO(TRACE_MODULE_APP | TRACE_NO_OPTION, "\r\n");
                    if (uwb_app_config.ranging_flow_mode == (uint8_t)RANGING_FLOW_CONTENTION)
                    {
                        LOG_INFO(TRACE_MODULE_APP, "Custom DS-TWR Contention Initiator SEQ NUM %u\r\n", seq_num);
                    }
                    else
                    {
                        LOG_INFO(TRACE_MODULE_APP, "Custom DS-TWR Initiator SEQ NUM %u\r\n", seq_num);
                    }
                    LOG_INFO(TRACE_MODULE_APP, "[TX][%u] Poll %s\r\n", ind->tx_len, ind->status == UWB_TX_OK ? "" : "TX Fail");
                }
                else if (ind->ranging_stage == RANGING_RESPONSE)
                {
#ifdef SE_DEMO_EN
                    if (ind->tx_len > (MSG_HEADER_LEN + MSG_RESPONSE_USER_DATA_IDX))
                    {
                        slave_apdu_resp_send_status = 1;
                    }
#endif
                    LOG_INFO(TRACE_MODULE_APP, "[TX][%u] Response %s\r\n", ind->tx_len, ind->status == UWB_TX_OK ? "" : "TX Fail");
                }
                else if (ind->ranging_stage == RANGING_FINAL)
                {
                    LOG_INFO(TRACE_MODULE_APP, "[TX][%u] Final\r\n", ind->tx_len);

                    // calculate_first_tap_power(1, 1);
                    // print_preamble_chest(1, 1);
                    // print_sts_ch_taps(1);
                }
                else if (ind->ranging_stage == RANGING_RESULT)
                {
                    LOG_INFO(TRACE_MODULE_APP, "[TX][%u] Result\r\n", ind->tx_len);
                }

#if PRINT_PAYLOAD_EN
                if (ind->tx_len)
                {
                    LOG_INFO(TRACE_MODULE_APP, " ");
                    for (uint8_t i = 0; i < ind->tx_len; i++)
                    {
                        LOG_INFO(TRACE_NO_OPTION | TRACE_MODULE_APP, "%02x ", ind->tx_data[i]);
                    }
                    LOG_INFO(TRACE_NO_OPTION | TRACE_MODULE_APP, "\r\n");
                }
#endif
            }
            break;

            case UWB_PKT_RX_DONE_MSG:
            {
                const struct UWB_PKT_RX_DONE_IND_T *ind = (const struct UWB_PKT_RX_DONE_IND_T *)param;
                if (ind->status == UWB_RX_OK)
                {
                    const struct RANGING_USER_PKT_T *usr_pkt = (const struct RANGING_USER_PKT_T *)ind->rx_data;
                    if ((ind->ranging_stage == RANGING_POLL) && ranging_env.synced)
                    {
                        ranging_env.range_data.sequence_num = usr_pkt->seq_num;
                        LOG_INFO(TRACE_MODULE_APP | TRACE_NO_OPTION, "\r\n");
                        if (uwb_app_config.ranging_flow_mode == (uint8_t)RANGING_FLOW_CONTENTION)
                        {
                            LOG_INFO(TRACE_MODULE_APP, "Custom DS-TWR Contention Responder SEQ NUM %u\r\n", ranging_env.range_data.sequence_num);
                        }
                        else
                        {
                            LOG_INFO(TRACE_MODULE_APP, "Custom DS-TWR Responder SEQ NUM %u\r\n", ranging_env.range_data.sequence_num);
                        }
                        LOG_INFO(TRACE_MODULE_APP, "[RX][%u][%d] Poll\r\n", ind->rx_len, ranging_env.main_ant_id);
                        // LOG_INFO(TRACE_MODULE_APP, "[RX]Peer Tx Power Level %d\r\n", usr_pkt->msg.poll_msg[MSG_POLL_TX_PWR_IDX]);

                        int32_t freq_offset = phy_freq_offset_get();
                        int32_t freq_offset_filter = average_filter(freq_offset);
                        LOG_INFO(TRACE_MODULE_APP, "CH Freq Offset %d\r\n", freq_offset_filter);
#if XTAL_AUTO_TUNE_EN
                        int32_t ppm = freq_offset_filter / (int32_t)(ch_center_freq_map[uwb_app_config.ppdu_params.ch_num] * 1e-6);
                        calib_xtal38m4_load_cap_auto_tune(ppm);
#endif
#if USER_DEFINED_DATA_REPORT_EN
                        uint8_t user_data_len = (uint8_t)(ind->rx_len - MSG_HEADER_LEN - MSG_POLL_USER_DATA_IDX);
                        if (user_data_len)
                        {
                            uwbapi_report_user_defined_data(user_data_len, &usr_pkt->msg.poll_msg[MSG_POLL_USER_DATA_IDX]);
                        }
#endif

#ifdef SE_DEMO_EN
                        uint8_t se_poll_data_len = (uint8_t)(ind->rx_len - MSG_HEADER_LEN - MSG_POLL_USER_DATA_IDX);
                        if (se_poll_data_len)
                        {
                            slave_process_apdu(&usr_pkt->msg.poll_msg[MSG_POLL_USER_DATA_IDX], se_poll_data_len, 0);
                        }
#endif

#if RSSI_EN
                        LOG_INFO(TRACE_MODULE_APP, "RSSI: %ddBm, SNR: %ddB \r\n", ind->rssi, ind->snr);
#endif

#if CSI_EN
                        struct RANGING_TAPS_INF_T taps_inf;
                        ranging_taps_inf_get(&taps_inf);
                        ranging_env.frame[0].NLoS = taps_inf.NLoS;
                        ranging_env.frame[0].fom = taps_inf.FoM;
                        LOG_INFO(TRACE_MODULE_APP, "NLoS %u FoM %u\r\n", taps_inf.NLoS, taps_inf.FoM);
#else
                        ranging_fom_get(&ranging_env.frame[0].NLoS, &ranging_env.frame[0].fom);
#endif
                    }
                    else if (ind->ranging_stage == RANGING_RESPONSE)
                    {
                        uint16_t responder_addr = READ_SHORT(&usr_pkt->msg.response_msg[MSG_RESPONSE_RESPONDER_ID_IDX]);
                        uint8_t responder_idx = ranging_responder_idx_get(responder_addr);

                        LOG_INFO(TRACE_MODULE_APP, "[RX][%u] Response\r\n", ind->rx_len);
                        // LOG_INFO(TRACE_MODULE_APP, "[RX]Peer Tx Power Level %d\r\n", usr_pkt->msg.response_msg[MSG_RESPONSE_TX_PWR_IDX]);
#ifdef SE_DEMO_EN
                        uint8_t se_resp_data_len = (uint8_t)(ind->rx_len - MSG_HEADER_LEN - MSG_RESPONSE_USER_DATA_IDX);
                        // Must call master_process_apdu when se_data_len == 0
                        master_process_apdu(&usr_pkt->msg.response_msg[MSG_RESPONSE_USER_DATA_IDX], se_resp_data_len);
#endif

#if RSSI_EN
                        LOG_INFO(TRACE_MODULE_APP, "RSSI: %ddBm, SNR: %ddB\r\n", ind->rssi, ind->snr);
#endif

#if CSI_EN
                        struct RANGING_TAPS_INF_T taps_inf;
                        ranging_taps_inf_get(&taps_inf);
                        ranging_env.frame[responder_idx].NLoS = taps_inf.NLoS;
                        ranging_env.frame[responder_idx].fom = taps_inf.FoM;
                        LOG_INFO(TRACE_MODULE_APP, "NLoS %u FoM %u\r\n", taps_inf.NLoS, taps_inf.FoM);
#else
                        ranging_fom_get(&ranging_env.frame[responder_idx].NLoS, &ranging_env.frame[responder_idx].fom);
#endif
                    }
                    else if (ind->ranging_stage == RANGING_FINAL)
                    {
                        LOG_INFO(TRACE_MODULE_APP, "[RX][%u][%d] Final\r\n", ind->rx_len, ranging_env.main_ant_id);

                        int64_t Tround1 = 0;
                        int64_t Tround2 = 0;
                        int64_t Treply1 = 0;
                        int64_t Treply2 = 0;

                        if (ranging_env.responder_final_flag)
                        {
                            Tround2 = ranging_tround(DEV_ROLE_RESPONDER, 0);
                            Treply1 = ranging_treply(DEV_ROLE_RESPONDER, 0);

                            // Ttotal
                            for (int i = 4; i >= 0; i--)
                            {
                                Treply2 = (Treply2 << 8) | usr_pkt->msg.final_msg[MSG_FINAL_TREPLY_IDX + i];
                            }

                            // Tround1
                            for (int i = 4; i >= 0; i--)
                            {
                                Tround1 = (Tround1 << 8) | usr_pkt->msg.final_msg[MSG_FINAL_TROUND_IDX(ranging_env.responder_slot_idx) + i];
                            }

                            // Treply2
                            Treply2 = Treply2 - Tround1;
                        }

                        // LOG_INFO(TRACE_MODULE_APP, "Tround1 %u Treply1 %u Tround2 %u Treply2 %u\r\n", (uint32_t)Tround1, (uint32_t)Treply1,
                        // (uint32_t)Tround2, (uint32_t)Treply2);

                        if ((Tround1) && (Treply1) && (Tround2) && (Treply2))
                        {
                            int64_t tof_i = (Tround1 * Tround2 - Treply1 * Treply2) / (Tround1 + Tround2 + Treply1 + Treply2);
                            // outlier filter
                            if (tof_i < 0)
                            {
                                tof_i = 0;
                            }
                            ranging_env.tof = (uint32_t)tof_i;

                            double tof_f = (double)TIMESTAMP_UNIT_TO_NS(ranging_env.tof);
                            uint32_t distance = (uint32_t)(tof_f * 0.299702547 * VP_VAL - RANGING_CORR);

                            // update distance result
                            struct RANGING_MEASUREMENT_T *range_result = &ranging_env.range_data.measurements[0];
                            range_result->status = STATUS_OK;
                            range_result->distance = (uint16_t)distance;

                            if (uwb_app_config.session_param.aoa_result_req)
                            {
#if AOA_EN
                                // update PDoA IQ and calculate AoA angles (depends on aoa_aux_cfg)
                                aoa_calculate(&range_result->aoa_elevation, &range_result->aoa_azimuth);
                                aoa_fom_get(&range_result->aoa_elevation_fom, &range_result->aoa_azimuth_fom);
#elif PDOA_3D_EN
                                // calculate PDoA angles
                                pdoa_3d_calculate(range_result->mac_addr, &range_result->aoa_elevation, &range_result->aoa_azimuth);
                                pdoa_fom_get(&range_result->aoa_elevation_fom, &range_result->aoa_azimuth_fom);
#endif

#if PRINT_PDOA_IQ_EN
#if AOA_EN || PDOA_3D_EN
                                float *iq = sts_first_path_iq_get();
#else
                                float *iq = NULL;
                                pdoa_iq_get(&iq);
#endif
                                ////////// need to increase slot duration for log printing
                                if (RX_ANT_PORTS_NUM == 2)
                                {
                                    LOG_INFO(TRACE_MODULE_APP, "ANT IQ: %f %f\r\n", iq[0], iq[1]);
                                    LOG_INFO(TRACE_MODULE_APP, "ANT IQ: %f %f\r\n", iq[2], iq[3]);
                                }
                                else if (RX_ANT_PORTS_NUM == 3)
                                {
                                    LOG_INFO(TRACE_MODULE_APP, "ANT IQ: %f %f\r\n", iq[0], iq[1]);
                                    LOG_INFO(TRACE_MODULE_APP, "ANT IQ: %f %f\r\n", iq[2], iq[3]);
                                    LOG_INFO(TRACE_MODULE_APP, "ANT IQ: %f %f\r\n", iq[4], iq[5]);
                                }
                                else if (RX_ANT_PORTS_NUM == 4)
                                {
                                    LOG_INFO(TRACE_MODULE_APP, "ANT IQ: %f %f\r\n", iq[0], iq[1]);
                                    LOG_INFO(TRACE_MODULE_APP, "ANT IQ: %f %f\r\n", iq[2], iq[3]);
                                    LOG_INFO(TRACE_MODULE_APP, "ANT IQ: %f %f\r\n", iq[4], iq[5]);
                                    LOG_INFO(TRACE_MODULE_APP, "ANT IQ: %f %f\r\n", iq[6], iq[7]);
                                }

                                // float pdoa[3];
                                // pdoa[0] = pdoa_select_get(0, 3);
                                // pdoa[1] = pdoa_select_get(1, 3);
                                // pdoa[2] = pdoa_select_get(2, 3);
                                // LOG_INFO(TRACE_MODULE_APP, "PDOA: %f %f %f\r\n", pdoa[0], pdoa[1], pdoa[2]);

                                // float *sts_rssi = sts_rssi_output_get();
                                // LOG_INFO(TRACE_MODULE_APP, "STS RSSI: %f %f %f %f\r\n", sts_rssi[0], sts_rssi[1], sts_rssi[2], sts_rssi[3]);
#endif
                            }
                            else
                            {
                                range_result->aoa_azimuth = 0;
                                range_result->aoa_elevation = 0;
                            }

#if FILTER_EN
                            if (uwb_app_config.filter_en)
                            {
                                // filter process
                                ranging_result_filter(&range_result->distance, &range_result->aoa_azimuth, &range_result->aoa_elevation);
                            }
#endif

                            if (uwb_app_config.session_param.aoa_result_req)
                            {
                                board_ranging_result_correct(&range_result->distance, &range_result->aoa_azimuth, &range_result->aoa_elevation);
                            }

#ifdef UWB_UCI_TEST_EN
#if AOA_EN
                            LOG_INFO(TRACE_MODULE_APP, "Distance %ucm, AoA Azimuth %d Elevation %d Azimuth FoM %u\r\n", distance,
                                     mk_q7_to_s16(range_result->aoa_azimuth), mk_q7_to_s16(range_result->aoa_elevation), range_result->aoa_azimuth_fom);
#elif PDOA_3D_EN
                            LOG_INFO(TRACE_MODULE_APP, "Distance %ucm, PDoA Azimuth %d Elevation %d Azimuth FoM %u\r\n", distance,
                                     mk_q7_to_s16(range_result->aoa_azimuth), mk_q7_to_s16(range_result->aoa_elevation), range_result->aoa_azimuth_fom);

#else
                            LOG_INFO(TRACE_MODULE_APP, "Distance %ucm\r\n", distance);
#endif
#endif

                            struct RANGE_DATA_T *range_data = &ranging_env.range_data;
                            range_data->measurements_num = 1;
                            uint16_t target_addr = uwbs_peer_short_addr_get();
                            range_result->mac_addr[0] = target_addr & 0xff;
                            range_result->mac_addr[1] = (target_addr >> 8) & 0xff;
                            range_result->slot_idx = ranging_env.responder_slot_idx;

#if CSI_EN
                            // need to increase slot duration for log printing
                            struct RANGING_TAPS_INF_T taps_inf;
                            ranging_taps_inf_get(&taps_inf);
                            ranging_env.frame[1].NLoS = taps_inf.NLoS;
                            ranging_env.frame[1].fom = taps_inf.FoM;
                            LOG_INFO(TRACE_MODULE_APP, "NLoS %u FoM %u\r\n", taps_inf.NLoS, taps_inf.FoM);

                            // LOG_INFO(TRACE_MODULE_APP, "fap: %d, %f\r\n", taps_inf.fap_loc, taps_inf.fap_pow);
                            // LOG_INFO(TRACE_MODULE_APP, "tap1: %d, %f\r\n", taps_inf.tap1_loc, taps_inf.tap1_pow);
                            // LOG_INFO(TRACE_MODULE_APP, "tap2: %d, %f\r\n", taps_inf.tap2_loc, taps_inf.tap2_pow);
                            // LOG_INFO(TRACE_MODULE_APP, "tap3: %d, %f\r\n", taps_inf.tap3_loc, taps_inf.tap3_pow);

                            // float chtaps_re[128];
                            // float chtaps_im[128];
                            // ranging_multi_taps_iq_get(chtaps_re, chtaps_im, 128);
                            // for (uint8_t i = 0; i < 128; i++)
                            // {
                            //     LOG_INFO(TRACE_NO_OPTION | TRACE_MODULE_APP, "%f, %f\r\n", chtaps_re[i], chtaps_im[i]);
                            // }
#else
                            ranging_fom_get(&ranging_env.frame[1].NLoS, &ranging_env.frame[1].fom);
#endif

                            // Retrieve Response-FoM and Response-NLoS from final packet
                            uint8_t FoM = usr_pkt->msg.final_msg[MSG_FINAL_FOM_IDX(ranging_env.responder_slot_idx)];
                            uint8_t NLoS = usr_pkt->msg.final_msg[MSG_FINAL_NLOS_IDX(ranging_env.responder_slot_idx)];
#if RANGING_FOM_FILTER_EN
                            uint8_t fap_valid = usr_pkt->msg.final_msg[MSG_FINAL_FAP_VALID_IDX(ranging_env.responder_slot_idx)];
                            uint8_t gaps_num = usr_pkt->msg.final_msg[MSG_FINAL_GAPS_NUM_IDX(ranging_env.responder_slot_idx)];
                            uint8_t gaps[CIR_LEN / CE_WIN - 1];
                            memcpy(gaps, &usr_pkt->msg.final_msg[MSG_FINAL_GAPS_IDX(ranging_env.responder_slot_idx)], (CIR_LEN / CE_WIN - 1));
                            debug_csi.ranging_fom = ranging_fom_calculate(&debug_csi, fap_valid, gaps, gaps_num);
#endif

                            LOG_INFO(TRACE_MODULE_APP, "Poll-FoM %d, Response-FoM %d Final-FoM %d, Poll-NLoS %d, Response-NLoS %d Final-NLoS %d\r\n",
                                     ranging_env.frame[0].fom, FoM, ranging_env.frame[1].fom, ranging_env.frame[0].NLoS, NLoS, ranging_env.frame[1].NLoS);

                            range_result->NLoS = MAX(NLoS, MAX(ranging_env.frame[0].NLoS, ranging_env.frame[1].NLoS));

                            // output result
                            uwbapi_report_ranging_data(range_data);

                            // int8_t expected_rssi = ranging_expected_rssi_get(ranging_tx_power_get(), range_result->distance, 2, 0);
                            // LOG_INFO(TRACE_MODULE_APP, "Expected RSSI: %ddBm\r\n", expected_rssi);
                        }
                        else
                        {
                            LOG_INFO(TRACE_MODULE_APP, "Timestamp error\r\n");
                        }
#ifdef SE_DEMO_EN
                        slave_process_apdu(NULL, 0, 1);
#endif
#if RSSI_EN
                        LOG_INFO(TRACE_MODULE_APP, "RSSI: %ddBm, SNR: %ddB \r\n", ind->rssi, ind->snr);
#endif

                        // calculate_first_tap_power(2, 2);
                        // print_preamble_chest(2, 2);
                        // print_sts_ch_taps(2);
                    }
#if RANGING_RESULT_REPORT_EN
                    else if (ind->ranging_stage == RANGING_RESULT)
                    {
                        LOG_INFO(TRACE_MODULE_APP, "[RX][%u][%d] Result\r\n", ind->rx_len, ranging_env.main_ant_id);

                        uint16_t responder_addr = READ_SHORT(&usr_pkt->msg.result_msg[MSG_RESPONSE_RESPONDER_ID_IDX]);
                        uint8_t responder_idx = ranging_responder_idx_get(responder_addr);

                        if (ranging_env.initiator_result_flag & (1 << responder_idx))
                        {
                            uint16_t distance = READ_SHORT(&usr_pkt->msg.result_msg[2]);
                            LOG_INFO(TRACE_MODULE_APP,
                                     "Address %X, Distance %ucm, Poll-FoM %d, Response-FoM %d Final-FoM %d, Poll-NLoS %d, Response-NLoS %d Final-NLoS %d\r\n",
                                     responder_addr, distance, usr_pkt->msg.result_msg[4], ranging_env.frame[responder_idx].fom, usr_pkt->msg.result_msg[6],
                                     usr_pkt->msg.result_msg[5], ranging_env.frame[responder_idx].NLoS, usr_pkt->msg.result_msg[7]);
                        }
                    }
#endif

#if PRINT_PAYLOAD_EN
                    if (ind->rx_len)
                    {
                        LOG_INFO(TRACE_MODULE_APP, " ");
                        for (uint8_t i = 0; i < ind->rx_len; i++)
                        {
                            LOG_INFO(TRACE_NO_OPTION | TRACE_MODULE_APP, "%02x ", ind->rx_data[i]);
                        }
                        LOG_INFO(TRACE_NO_OPTION | TRACE_MODULE_APP, "\r\n");
                    }
#endif
                }
                else
                {
                    LOG_INFO(TRACE_MODULE_APP, "UWB RX fail  0x%04x\r\n", ind->status);
                }
            }
            break;

            default:
                break;
        }
    }
    // Handle events
    else if (event)
    {
    }
}