/*
* Copyright (c) 2017 Texas Instruments Incorporated
*
* All rights reserved not granted herein.
* Limited License.
*
* Texas Instruments Incorporated grants a world-wide, royalty-free,
* non-exclusive license under copyrights and patents it now or hereafter
* owns or controls to make, have made, use, import, offer to sell and sell ("Utilize")
* this software subject to the terms herein.  With respect to the foregoing patent
* license, such license is granted  solely to the extent that any such patent is necessary
* to Utilize the software alone.  The patent license shall not apply to any combinations which
* include this software, other than combinations with devices manufactured by or for TI ("TI Devices").
* No hardware patent is licensed hereunder.
*
* Redistributions must preserve existing copyright notices and reproduce this license (including the
* above copyright notice and the disclaimer and (if applicable) source code license limitations below)
* in the documentation and/or other materials provided with the distribution
*
* Redistribution and use in binary form, without modification, are permitted provided that the following
* conditions are met:
*
*             * No reverse engineering, decompilation, or disassembly of this software is permitted with respect to any
*               software provided in binary form.
*             * any redistribution and use are licensed by TI for use only with TI Devices.
*             * Nothing shall obligate TI to provide you with source code for the software licensed and provided to you in object code.
*
* If software source code is provided to you, modification and redistribution of the source code are permitted
* provided that the following conditions are met:
*
*   * any redistribution and use of the source code, including any resulting derivative works, are licensed by
*     TI for use only with TI Devices.
*   * any redistribution and use of any object code compiled from the source code and any resulting derivative
*     works, are licensed by TI for use only with TI Devices.
*
* Neither the name of Texas Instruments Incorporated nor the names of its suppliers may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* DISCLAIMER.
*
* THIS SOFTWARE IS PROVIDED BY TI AND TI'S LICENSORS "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 TI AND TI'S LICENSORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __DEMO_H__
#define __DEMO_H__

#include <ti/common/mmwave_error.h>
#include <ti/drivers/soc/soc.h>
#include <ti/drivers/uart/UART.h>
#include <ti/drivers/pinmux/pinmux.h>
#include <ti/drivers/esm/esm.h>
#include <ti/drivers/soc/soc.h>
#include <ti/drivers/mailbox/mailbox.h>
#include <ti/drivers/adcbuf/ADCBuf.h>
#include <ti/drivers/hwa/hwa.h>
#include <ti/drivers/edma/edma.h>
#include <ti/control/mmwave/mmwave.h>
#include <ti/control/mmwavelink/include/rl_sensor.h>

#include <ti/sysbios/knl/Semaphore.h>
#include <ti/common/sys_common_xwr14xx.h>

#include "demo_common.h"

#define PI_ 3.14159265

#define HWAUTIL_NUM_PARAM_SETS_1D 6
#define HWAUTIL_NUM_PARAM_SETS_CFAR 1

#ifdef DEBUG
#define demo_printf(...) //System_printf(__VA_ARGS__)
#else
#define demo_printf(...) //
#endif

#define DEMO_RUN_MEASUREMENT 0
#define DEMO_RUN_CALIBRATION 1
#define DEMO_GOOD_CAL_RESULT 0x17fe

//Choose one configurations defined below
// #define DEMO_CONFIG15
// #define DEMO_CONFIG_TEST

// #define DEMO_CONFIG_5m 5
// #define DEMO_CONFIG_8m 8
#define DEMO_CONFIG_35m 30
// #define DEMO_CONFIG_150m 150

/* Define chirp configurations for the demo */

#ifdef DEMO_CONFIG0                //these are the mmwave demo parameters                           \
                                   //Description: Short range with good resolution. Low processing. \
                                   //max range: 4.5m                                                \
                                   //range resolution: 4cm
#define DEMOCFG_SAMPLE_RATE 4500   /* 4.5Msps */
#define DEMOCFG_FREQ_SLOPE 1408    /* x 48.28kHz/us = 68Mhz/us */
#define DEMOCFG_IDLE_TIME 700      /* 7us */
#define DEMOCFG_ADC_START_TIME 700 /* 7us */
#define DEMOCFG_RAMP_END_TIME 5800 /* 58us */
#define DEMOCFG_RANGE_RES 0.038787879
#define DEMOCFG_NUM_ADC_SAMPLES 225
#define DEMOCFG_FFT_SIZE 256
#endif

#ifdef DEMO_CONFIG_5m
//自己弄着玩儿的,测距范围0~5米
#define DEMOCFG_SAMPLE_RATE 2000           //  profileCfg->digOutSampleRate
#define DEMOCFG_FREQ_SLOPE 1243            //  profileCfg->freqSlopeConst
#define DEMOCFG_ADC_START_TIME 700         //  profileCfg->adcStartTimeConst
#define DEMOCFG_IDLE_TIME 291600           //  profileCfg->idleTimeConst
#define DEMOCFG_NUM_ADC_SAMPLES 100        //  profileCfg->numAdcSamples
#define DEMOCFG_RAMP_END_TIME 6600         //  profileCfg->rampEndTime
#define DEMOCFG_FFT_SIZE 4096              //  dataPathObj->numRangeBins
#define DEMOCFG_NUMLOOPS 1                 //  frameCfg->numLoops
#define DEMOCFG_START_FREQCONST 1435384036 //  profileCfg->startFreqConst
#define DEMOCFG_RxLNAGAIN 30               //  profileCfg->rxGain
#define DEMOCFG_NONCOHERENT_COMBINING 2    //  future parameter, average last FFT s
#define DEMOCFG_RANGE_RES 0.0027           //  dataPathObj->rangeRx`esolution
#define DEMOCFG_ZOOMFFT 0                  //  future parameter
#define DEMOCFG_TXUSED 1                   //  2^(value - 1) - value is a mask, value is antenna# 1,2,3
#define DEMOCFG_RXUSED 1                   //  2^(value - 1) - value is a mask, value is antenna# 1,2,3,4
#define DEMOCFG_TxBackoff 0                //  value is numdb, and used Tx, bit7.0Tx1, bit15.8Tx2, bit23.16 Tx3
#endif

#ifdef DEMO_CONFIG_8m
//自己弄着玩儿的,测距范围0~8.1976米
#define DEMOCFG_SAMPLE_RATE 2000           //  profileCfg->digOutSampleRate
#define DEMOCFG_FREQ_SLOPE 758             //  profileCfg->freqSlopeConst
#define DEMOCFG_ADC_START_TIME 700         //  profileCfg->adcStartTimeConst
#define DEMOCFG_IDLE_TIME 291600           //  profileCfg->idleTimeConst
#define DEMOCFG_NUM_ADC_SAMPLES 196        //  profileCfg->numAdcSamples
#define DEMOCFG_RAMP_END_TIME 10923        //  profileCfg->rampEndTime
#define DEMOCFG_FFT_SIZE 4096              //  dataPathObj->numRangeBins
#define DEMOCFG_NUMLOOPS 1                 //  frameCfg->numLoops
#define DEMOCFG_START_FREQCONST 1435384036 //  profileCfg->startFreqConst
#define DEMOCFG_RxLNAGAIN 30               //  profileCfg->rxGain
#define DEMOCFG_RANGE_RES 0.0027           //  dataPathObj->rangeRx`esolution
#define DEMOCFG_ZOOMFFT 0                  //  future parameter
#define DEMOCFG_TXUSED 1                   //  2^(value - 1) - value is a mask, value is antenna# 1,2,3
#define DEMOCFG_RXUSED 1                   //  2^(value - 1) - value is a mask, value is antenna# 1,2,3,4
#define DEMOCFG_TxBackoff 0                //  value is numdb, and used Tx, bit7.0Tx1, bit15.8Tx2, bit23.16 Tx3
#endif

#ifdef DEMO_CONFIG_11m
//自己弄着玩儿的,测距范围0~11.1658米
#define DEMOCFG_SAMPLE_RATE 5209           //  profileCfg->digOutSampleRate
#define DEMOCFG_FREQ_SLOPE 1449            //  profileCfg->freqSlopeConst
#define DEMOCFG_ADC_START_TIME 700         //  profileCfg->adcStartTimeConst
#define DEMOCFG_IDLE_TIME 291600           //  profileCfg->idleTimeConst
#define DEMOCFG_NUM_ADC_SAMPLES 256        //  profileCfg->numAdcSamples
#define DEMOCFG_RAMP_END_TIME 5714         //  profileCfg->rampEndTime
#define DEMOCFG_FFT_SIZE 4096              //  dataPathObj->numRangeBins
#define DEMOCFG_NUMLOOPS 1                 //  frameCfg->numLoops
#define DEMOCFG_START_FREQCONST 1435384036 //  profileCfg->startFreqConst
#define DEMOCFG_RxLNAGAIN 30               //  profileCfg->rxGain
#define DEMOCFG_NONCOHERENT_COMBINING 2    //  future parameter, average last FFT s
#define DEMOCFG_RANGE_RES 0.0027           //  dataPathObj->rangeResolution
#define DEMOCFG_ZOOMFFT 0                  //  future parameter
#define DEMOCFG_TXUSED 1                   //  2^(value - 1) - value is a mask, value is antenna# 1,2,3
#define DEMOCFG_RXUSED 1                   //  2^(value - 1) - value is a mask, value is antenna# 1,2,3,4
#define DEMOCFG_TxBackoff 0                //  value is numdb, and used Tx, bit7.0Tx1, bit15.8Tx2, bit23.16 Tx3
#endif

#ifdef DEMO_CONFIG_35m
//IWR1443的ADC最大复采样速率，18.75MhZ
//自己弄着玩儿的,测距范围0~30米
#define DEMOCFG_SAMPLE_RATE 14000          //  profileCfg->digOutSampleRate
#define DEMOCFG_FREQ_SLOPE 1225            //  profileCfg->freqSlopeConst
#define DEMOCFG_ADC_START_TIME 700         //  profileCfg->adcStartTimeConst
#define DEMOCFG_IDLE_TIME 2916             //  profileCfg->idleTimeConst
#define DEMOCFG_NUM_ADC_SAMPLES 806        //  profileCfg->numAdcSamples
#define DEMOCFG_RAMP_END_TIME 6763         //  profileCfg->rampEndTime
#define DEMOCFG_FFT_SIZE 4096              //  dataPathObj->numRangeBins
#define DEMOCFG_NUMLOOPS 1                 //  frameCfg->numLoops
#define DEMOCFG_START_FREQCONST 1435384036 //  profileCfg->startFreqConst
#define DEMOCFG_RxLNAGAIN 30               //  profileCfg->rxGain
#define DEMOCFG_NONCOHERENT_COMBINING 2    //  future parameter, average last FFT s
#define DEMOCFG_RANGE_RES 0.0087           //  dataPathObj->rangeResolution
#define DEMOCFG_ZOOMFFT 0                  //  future parameter
#define DEMOCFG_TXUSED 1                   //  2^(value - 1) - value is a mask, value is antenna# 1,2,3
#define DEMOCFG_RXUSED 1                   //  2^(value - 1) - value is a mask, value is antenna# 1,2,3,4
#define DEMOCFG_TxBackoff 0                //  value is numdb, and used Tx, bit7.0Tx1, bit15.8Tx2, bit23.16 Tx3
#endif

#ifdef DEMO_CONFIG_150m
//IWR1443的ADC最大复采样速率，18.75MhZ
//自己弄着玩儿的,测距范围0~30米
#define DEMOCFG_SAMPLE_RATE 14000          //  profileCfg->digOutSampleRate
#define DEMOCFG_FREQ_SLOPE 289             //  profileCfg->freqSlopeConst
#define DEMOCFG_ADC_START_TIME 700         //  profileCfg->adcStartTimeConst
#define DEMOCFG_IDLE_TIME 29160            //  profileCfg->idleTimeConst
#define DEMOCFG_NUM_ADC_SAMPLES 3873       //  profileCfg->numAdcSamples
#define DEMOCFG_RAMP_END_TIME 28667        //  profileCfg->rampEndTime
#define DEMOCFG_FFT_SIZE 4096              //  dataPathObj->numRangeBins
#define DEMOCFG_NUMLOOPS 1                 //  frameCfg->numLoops
#define DEMOCFG_START_FREQCONST 1435384036 //  profileCfg->startFreqConst
#define DEMOCFG_RxLNAGAIN 30               //  profileCfg->rxGain
#define DEMOCFG_NONCOHERENT_COMBINING 2    //  future parameter, average last FFT s
#define DEMOCFG_RANGE_RES 0.0369           //  dataPathObj->rangeResolution
#define DEMOCFG_ZOOMFFT 0                  //  future parameter
#define DEMOCFG_TXUSED 1                   //  2^(value - 1) - value is a mask, value is antenna# 1,2,3
#define DEMOCFG_RXUSED 1                   //  2^(value - 1) - value is a mask, value is antenna# 1,2,3,4
#define DEMOCFG_TxBackoff 0                //  value is numdb, and used Tx, bit7.0Tx1, bit15.8Tx2, bit23.16 Tx3
#endif

//AG: New set of configs from Joe's Master Spreadsheet.

#define DEMO_CAL_FREQ_LOW 770
#define DEMO_CAL_FREQ_HIGH 810
#define DEMO_CAL_FLASH_OFFSET 0x100000
#define DEMO_CAL_FLASH_LEN (sizeof(rlCalDataStore_t) * RL_MAX_CALIB_DATA_CHUNK)

#define DEMOCFG_RANGE_BINS (DEMOCFG_NUM_ADC_SAMPLES / 2)

#define DEMOCFG_NUM_CHIRPS 1    /* number of collected chirps to process */
#define DEMOCFG_NUM_CHIRP_CFG 1 /* number of different chirp configs */

#define HWAUTIL_NUM_PARAM_SETS_1D 4
#define HWAUTIL_NUM_PARAM_SETS_2D 8
#define HWAUTIL_NUM_PARAM_SETS_CFAR 1

#define DEMOCFG_SPEED_OF_LIGHT_IN_METERS (3.0e8)

#define SOC_AR14XX_MSS_L3RAM_SIZE 0x40000
#define PI 3.14159265
#define ONE_Q17 (1U << 17)
#define MMW_HWA_START_POS_PARAMSETS_1D 0
#define MMW_HWA_WINDOWRAM_1D_OFFSET 0 //In samples

#define EDMA_SHADOW_LNK_PARAM_BASE_ID EDMA_NUM_DMA_CHANNELS

/* 1D */
#define MMW_HWA_1D_ADCBUF_INP (&gMmwHwaMemBuf[0])

/* 1D -ping */
#define MMW_HWA_DMA_TRIGGER_SOURCE_1D_PING 0
#define MMW_HWA_DMA_DEST_CHANNEL_1D_PING 0
#define MMW_HWA_1D_OUT_PING (&gMmwHwaMemBuf[3])
#define MMW_HWA_1D_OUT_PING_M0_M2 (&gMmwHwaMemBuf[2]) //4Kstitching
#define MMW_HWA_1D_OUT_PING_M2_M3 (&gMmwHwaMemBuf[3]) //4Kstitching
#define MMW_EDMA_1D_PING_CH_ID EDMA_TPCC0_REQ_HWACC_0
#define MMW_EDMA_1D_PING_SHADOW_LINK_CH_ID EDMA_SHADOW_LNK_PARAM_BASE_ID
#define MMW_EDMA_1D_PING_CHAIN_CH_ID EDMA_TPCC0_REQ_FREE_0
#define MMW_EDMA_1D_PING_ONE_HOT_SHADOW_LINK_CH_ID (EDMA_SHADOW_LNK_PARAM_BASE_ID + 2)

/* 1D - pong */
#define MMW_HWA_DMA_TRIGGER_SOURCE_1D_PONG 1
#define MMW_HWA_DMA_DEST_CHANNEL_1D_PONG 1
#define MMW_HWA_1D_OUT_PONG (&gMmwHwaMemBuf[2])
#define MMW_HWA_1D_OUT_PONG_M1_M3 (&gMmwHwaMemBuf[3]) //4K stitching
#define MMW_HWA_1D_OUT_PONG_M3_M2 (&gMmwHwaMemBuf[2]) //4K stitching
#define MMW_EDMA_1D_PONG_CH_ID EDMA_TPCC0_REQ_HWACC_1
#define MMW_EDMA_1D_PONG_SHADOW_LINK_CH_ID (EDMA_SHADOW_LNK_PARAM_BASE_ID + 1)
#define MMW_EDMA_1D_PONG_CHAIN_CH_ID EDMA_TPCC0_REQ_FREE_1
#define MMW_EDMA_1D_PONG_ONE_HOT_SHADOW_LINK_CH_ID (EDMA_SHADOW_LNK_PARAM_BASE_ID + 3)

#define DEMO_EDMA_TRANSFER_COMPLETION_CODE_1D_DONE MMW_EDMA_1D_PING_CHAIN_CH_ID

/* CFAR */
#define MMW_HWA_DMA_TRIGGER_SOURCE_CFAR 4
#define MMW_HWA_DMA_DEST_CHANNEL_CFAR 4
#define MMW_HWA_CFAR_INP (&gMmwHwaMemBuf[0])
#define MMW_HWA_CFAR_OUT (&gMmwHwaMemBuf[2])
#define MMW_EDMA_CFAR_INP_CH_ID EDMA_TPCC0_REQ_FREE_8
#define MMW_EDMA_CFAR_INP_SHADOW_LINK_CH_ID1 (EDMA_SHADOW_LNK_PARAM_BASE_ID + 12)
#define MMW_EDMA_CFAR_INP_CHAIN_CH_ID EDMA_TPCC0_REQ_FREE_9
#define MMW_EDMA_CFAR_INP_SHADOW_LINK_CH_ID2 (EDMA_SHADOW_LNK_PARAM_BASE_ID + 13)
#define MMW_EDMA_CFAR_OUT_CH_ID EDMA_TPCC0_REQ_HWACC_4
#define MMW_EDMA_CFAR_OUT_SHADOW_LINK_CH_ID1 (EDMA_SHADOW_LNK_PARAM_BASE_ID + 14)
#define MMW_EDMA_CFAR_OUT_CHAIN_CH_ID EDMA_TPCC0_REQ_HWACC_4

#define MMWDEMO_EDMA_TRANSFER_COMPLETION_CODE_CFAR_DONE MMW_EDMA_CFAR_OUT_CHAIN_CH_ID

#define MMW_MAX_OBJ_OUT 1023

#define MMW_HWA_START_POS_PARAMSETS_1D 0
#define MMW_HWA_START_POS_PARAMSETS_CFAR (MMW_HWA_START_POS_PARAMSETS_2D + HWAUTIL_NUM_PARAM_SETS_CFAR)

#define MMW_HWA_WINDOWRAM_1D_OFFSET 0 //In samples

#define MMW_HWA_MAX_CFAR_DET_OBJ_LIST_SIZE (SOC_XWR14XX_MSS_HWA_MEM_SIZE / MMW_HWA_NUM_MEM_BUFS) / sizeof(cfarDetOutput_t)

#define MMW_HWA_NUM_MEM_BUFS 4

/* FFT Window */
/*! Hanning window */
#define MMW_WIN_HANNING 0
/*! Blackman window */
#define MMW_WIN_BLACKMAN 1
/*! Rectangular window */
#define MMW_WIN_RECT 2

#define I_WANT_USE_THIS_WIN MMW_WIN_RECT
#define I_DO_NOT_WANT_USE_WIN

// #define TEST_MODE
#define FFT_FAR 1
#define CFAR_FAR 1
#define FFT_NEAR 1
#define TRANSMIT 1
#define SPIRAMBUFLEN 16U

#define MAX_INTERVAL 10
#define SPI_MULT_ICOUNT_SUPPORT

#define MAX_EFFECTIVE_ECHO_POINT 1024
#define MAX_BLIND_AREA 1
#define NORMALIZATION_AMPLITUDE 65535U
#define EFFECTIVE_THREASHOLD 512
#define MAX_TIME_VARY_GAIN_WIN_NUM 1023
#define MAX_TIME_VARY_GAIN_ALPHA_ABS 10
#define FFTNUM 4096
#define ENVIRONMENT_MODE_DEFULT 0x55

#define PEAK_THRESHOLD_MAX 40
#define PEAK_THRESHOLD_MIN 5
#define CURVE_THRESHOLD_MAX 7
#define CURVE_THRESHOLD_MIN 1

#define FFT_ABS_START_OFFSET (0x00000000U)
#define CFAR_REF_LEVEL_FAR_OFFSET (0x00004000U)
#define CFAR_RESULT_INDEX_OFFSET (0x00006000U)

#define ENCODE_CURVE_OFFSET (0x0000a000U)
#define TIME_VARY_GAIN_OFFSET (0x0000b000U)
#define ENVIRONMENT_USE_OFFSET (0x0000c000U)
#define CFAR_NEAR_RESULT_OFFSET (0x00010000U)

#define FFT_PROCESS_OFFSET (0x00040000U)
#define FFT_PROCESS_16b_OFFSET (0x00044000U)
#define FFT_ORIGINAL_OFFSET (0x00046000U)

#define PARAM_NEED_TO_SAVE_OFFSET (0x00050000U)
#define RF_PARAM_OFFSET (0x00050000U + sizeof(ParamNeedSave_t))
//L3地址，0x51000000~0x51060000
#define MY_OWN_BASE_ADDRESS(offset) (0x51000000U + (offset))

#define CONFIG_FROM_MCU_SAVE2FLASH_OFFSET (0x007f0000U)
#define TIME_GAIN_BASE_SAVE2FLASH_OFFSET (0x007f1000U)
#define TIME_VARY_GAIN_SAVE2FLASH_OFFSET (0x007f2000U)
#define CONFIG_DEFULT_SAVE2FLASH_OFFSET (0x007f3000U)
#define ENVIRONMENT_ECHO_SAVE2FLASH_OFFSET (0x007f8000U)

#define OFFSET_4K_BYTE (0x1000U)

#define JUST_PLAY

typedef struct RF_Param_type
{
    uint16_t RxLNAGAIN;
    uint16_t SAMPLE_RATE;
    uint16_t FREQ_SLOPE;
    uint16_t ADC_START_TIME;
    uint16_t NUM_ADC_SAMPLES;
    uint16_t FFT_SIZE;
    uint32_t RAMP_END_TIME;
    uint32_t START_FREQCONST;
    uint32_t IDLE_TIME;
    float RANGE_RES;
    float Range_Max;
} RF_Param_t;

typedef struct DataAndDistance_type
{
    uint16_t Data;
    uint16_t Noise;
    float Distance;
} DataAndDistance_t;

typedef struct DataAndIndex_type
{
    uint16_t Data;
    uint16_t Index;
} DataAndIndex_t;

typedef struct SendMessage2MCU_type
{
    uint16_t a;
    uint16_t size;
    uint16_t group;
    uint32_t max;

} SendMessage2MCU_t;

typedef struct EchoPrefix_type
{
    uint16_t size;
    uint16_t group;
    uint32_t max;
} EchoPrefix_t;

typedef struct Environment_param_type
{
    uint16_t start_index;
    uint16_t end_index;
    uint16_t amplitude;
    int8_t mode;

} Environment_param_t;

typedef struct ZeroEcho_type
{
    float position;
    float range;
    float delete_start;
    float delete_end;
    uint16_t amplitude;
    uint16_t mode;

} ZeroEcho_t;

typedef struct ZeroEchoIndex_type
{
    uint16_t position;
    uint16_t range;
    uint16_t delete_start;
    uint16_t delete_end;

} ZeroEchoIdx_t;

typedef struct ParamFromMcu_type
{
    uint8_t Medium;
    uint8_t Agitatedsurface;
    uint8_t Foaming;
    uint8_t Powder_dust;

    uint8_t Large_angle_repose;
    uint8_t First_echo;
    uint8_t Position_detect;
    uint8_t Transmit_Waveform;

    uint8_t Peak_Threshold;
    uint8_t Curve_Threshold;
    uint8_t Signal_gain_level;
    uint8_t Zero_echo_open_flag;

    float Range;
    float Blind_areas;
    float Echo_learning;
    float DK;

    ZeroEcho_t Zero_echo_dist;
} ParamFromMcu_t;

typedef struct ParamNeedSave_type
{
    ParamFromMcu_t ParamFromMcu;

    uint16_t Range_index;
    uint16_t Blind_areas_index;
    uint16_t Echo_learning_index;

    ZeroEchoIdx_t Zero_echo_index;

} ParamNeedSave_t;

/*  */
typedef struct FlagAboutMCU_type
{
    float Time_varying_gain_alpha;
    int8_t Environment_echo_exist_flag;
    int8_t Working_mode;
    int8_t Save_param_flag;
    int8_t Transmit_Wave_change;
    int8_t Transmit_Curve2Mcu_flag;
    int8_t Start_Measuring_flag;
    int8_t Skip_Environment;
    int8_t Send_Next_SpiFrame;
    uint16_t Echo_learning_index_last;
    Environment_param_t Environment_param;

} FlagAboutMCU_t;

typedef struct CFAR_Config_type
{
    float thresholdScale;
    uint8_t refLen;
    uint8_t guardLen;
    uint8_t noiseDiv;
    uint8_t peakGroup;
    uint8_t cycleMode;
    uint8_t averangeMode;
    uint8_t outputMode;
} CFAR_Config_t;

typedef struct
{
    uint8_t buf[SOC_XWR14XX_MSS_HWA_MEM_SIZE / MMW_HWA_NUM_MEM_BUFS];
} mmwHwaBuf_t;

/*! simple memory pool structure for flexible partitioning of L3 RAM */
typedef struct
{
    /*! base address of memory */
    uint8_t *base;

    /*! size of memory in bytes */
    uint32_t size;

    /*! index into the pool to track where is next free */
    uint32_t indx;
} DemoMemPool_t;

#ifdef RANGE_DC_CALIBRATION
/**
 * @brief
 *  Millimeter Wave Demo DC range signature compensation
 *
 * @details
 *  The structure contains the DC range antenna signature removeal configuration used in data path
 */
typedef struct Demo_CalibDcRangeSigCfg_t
{
    /*! @brief    enabled flag:  1-enabled 0-disabled */
    uint16_t enabled;

    /*! @brief    maximum negative range bin (1D FFT index) to be compensated */
    int16_t negativeBinIdx;

    /*! @brief    maximum positive range bin (1D FFT index) to be compensated */
    int16_t positiveBinIdx;

    /*! @brief    number of chirps in the averaging phase */
    uint16_t numAvgChirps;

} Demo_CalibDcRangeSigCfg;
#endif

/*!
 *  @brief    Detected object parameters filled by HWA CFAR
 *
 */
// typedef volatile struct cfarDetOutput
// {
//     uint32_t   noise;           /*!< Noise energy in CFAR cell */
//     uint32_t   rangeIdx : 12;   /*!< Range index */
//     uint32_t   dopplerIdx : 20; /*!< Doppler index */
// } cfarDetOutput_t;
typedef struct cfarDetOutput_type
{
    uint32_t noise; /*!< Noise energy in CFAR cell */
    uint32_t index; /*!< Range index */
} cfarDetOutput_t;

/*!
 *  @brief      Data path mode
 *
 *  This enum defines if the data path chain is running standalone (such as in a unit test)
 *  or if it is running as part of a demo (integrated with ADC buffer)
 */
typedef enum
{
    /*!
      *  Data path running standalone
      */
    DATA_PATH_STANDALONE,
    /*!
      *  Data path integrated with ADC buffer
      */
    DATA_PATH_WITH_ADCBUF
} DataPath_mode;

typedef struct Demo_ADCBufCfg_t
{
    /*! ADCBUF out format:
        0-Complex,
        1-Real */
    uint8_t adcFmt;

    /*! ADCBUF IQ swap selection:
        0-I in LSB, Q in MSB,
        1-Q in LSB, I in MSB */
    uint8_t iqSwapSel;

    /*! ADCBUF channel interleave configuration:
        0-interleaved(not supported on XWR16xx),
        1- non-interleaved */
    uint8_t chInterleave;

    /**
     * @brief   Chirp Threshold configuration used for ADCBUF buffer
     */
    uint8_t chirpThreshold;
} Demo_ADCBufCfg;

/**
 * @brief
 *  Millimeter Wave Demo Data Path Information.
 *
 * @details
 *  The structure is used to hold all the relevant information for
 *  the data path.
 */
typedef struct Demo_DataPathObj_t
{
    /*! @brief   Number of receive channels */
    uint32_t numRxAntennas;

    /*! @brief   Element size (in number of bytes) used to configure DMA channel */
    uint16_t dmaElemSize;

    /*! @brief   Frame count used to configure DMA channel */
    uint8_t dmaFrameCnt;

    /*! @brief   Counter which tracks the number of chirps detected */
    uint32_t chirpInterruptCounter;

    /*! @brief   ADCBUF handle. */
    ADCBuf_Handle adcbufHandle;

    /*! @brief   Handle of the EDMA driver. */
    EDMA_Handle edmaHandle;

    /*! @brief   EDMA error Information when there are errors like missing events */
    EDMA_errorInfo_t EDMA_errorInfo;

    /*! @brief EDMA transfer controller error information. */
    EDMA_transferControllerErrorInfo_t EDMA_transferControllerErrorInfo;

    /*! @brief Semaphore handle for 1D EDMA completion. */
    Semaphore_Handle EDMA_1Ddone_semHandle;

    /*! @brief Semaphore handle for CFAR EDMA completion. */
    Semaphore_Handle EDMA_CFARdone_semHandle;

    /*! @brief Handle to hardware accelerator driver. */
    HWA_Handle hwaHandle;

    /*! @brief Semaphore handle for Hardware accelerator completion. */
    Semaphore_Handle HWA_done_semHandle;

    /*! @brief Hardware accelerator Completion Isr count for debug purposes. */
    uint32_t hwaDoneIsrCounter;

    /*! @brief Semaphore handle for Frame start indication. */
    //    Semaphore_Handle frameStart_semHandle;

    /*! @brief Hardware accelerator Completion Isr count for debug purposes. */
    //    uint32_t frameStartIntCounter;

    /*! @brief  Used for checking that inter frame processing finshed on time */
    //    int32_t interFrameProcToken;

    /*! @brief noise energy */
    uint32_t noiseEnergy;

    /*! @brief Pointer to Radar Cube memory in L3 RAM */
    uint32_t *radarCube;

    // /*! @brief Pointer to range-doppler log magnitude matrix memory in L3 RAM */
    // uint16_t *rangeDopplerLogMagMatrix;

    /*! @brief pointer to CFAR detection output in L3 RAM */
    cfarDetOutput_t *cfarDetectionOut;

    /*! @brief Number of CFAR detections by Hardware accelerator for debug purposes. */
    uint32_t numHwaCfarDetections;

    /*! @brief number of transmit antennas */
    uint32_t numTxAntennas;

    /*! @brief number of virtual antennas */
    uint32_t numVirtualAntennas;

    /*! @brief number of virtual azimuth antennas */
    uint32_t numVirtualAntAzim;

    /*! @brief number of virtual elevation antennas */
    uint32_t numVirtualAntElev;

    /*! @brief number of ADC samples */
    uint32_t numAdcSamples;

    /*! @brief number of range bins */
    uint32_t numRangeBins;

    /*! @brief number of chirps per frame */
    uint32_t numChirpsPerFrame;

    /*! @brief number of doppler bins */
    uint32_t numDopplerBins;

    /*! @brief range resolution in meters */
    float rangeResolution;

    /*! @brief Data path mode */
    DataPath_mode dataPathMode;

    /*! @brief status of boot calibration */
    uint32_t calibrationStatus;

#ifdef RANGE_DC_CALIBRATION
    /*! @brief   Calibrate DC (zero) range signiture */
    Demo_CalibDcRangeSigCfg calibDcRangeSigCfg;

    /*! @brief Pointer to DC range signature compensation buffer */
    cmplx32ImRe_t *dcRangeSigMean;

    /*! @brief DC range signature calibration counter */
    uint32_t dcRangeSigCalibCntr;

    /*! @brief log2 of number of averaged chirps */
    uint32_t log2NumAvgChirps;
#endif

    /*! @brief Semaphore handle for Hardware accelerator completion. */
    Semaphore_Handle frameStart_semHandle;

} Demo_DataPathObj;

/** @brief Configures ParameterSet for Range FFT on ADC samples from DFE
 *
 *   @param[in] handle                  HWA driver handle
 *
 *   @param[in] paramSetStartIdx        HWA parameter set start index
 *
 *   @param[in] numAdcSamples           Number of ADC samples
 *
 *   @param[in] numRangeBins            Number of range bins (1st D FFT size)
 *
 *   @param[in] numRxAnt                Number of Rx antennas
 *
 *   @param[in] windowOffsetBytes       Window offset in bytes (for pre-FFT windowing)
 *
 *   @param[in] dmaTriggerSourcePing    DMA trigger source channel for Ping param sets
 *
 *   @param[in] dmaTriggerSourcePong    DMA trigger source channel for Pong param sets
 *
 *   @param[in] dmaDestChannelPing      DMA destination channel for Ping param sets
 *
 *   @param[in] dmaDestChannelPong      DMA destination channel for Pong param sets
 *
 *   @param[in] hwaMemAdcBufOffset      HWA memory offset ADC buffer
 *
 *   @param[in] hwaMemDestPingOffset    HWA memory offset for Ping destination
 *
 *   @param[in] hwaMemDestPongOffset    HWA memory offset for Pong destination
 *
 */
void HWAutil_configRangeFFT(HWA_Handle handle,
                            uint32_t paramSetStartIdx,
                            uint32_t numAdcSamples,
                            uint32_t numRangeBins,
                            uint8_t numRxAnt,
                            uint32_t windowOffsetBytes,

                            uint8_t dmaTriggerSourcePing,
                            uint8_t dmaTriggerSourcePong,

                            uint8_t dmaDestChannelPing,
                            uint8_t dmaDestChannelPong,

                            uint16_t hwaMemAdcBufOffset,

                            // uint16_t hwaMemDestPingOffset,
                            //    uint16_t hwaMemDestPongOffset,
                            uint8_t hwaTriggerMode,
                            uint8_t windowEn);
/** @brief Configures ParameterSet for CFAR detection (The CFAR detection runs along range bins).
 *
 *   @param[in] handle              HWA driver handle
 *
 *   @param[in] paramSetStartIdx    HWA parameter set start index
 *
 *   @param[in] numRangeBins        Number of range bins
 *
 *   @param[in] numDopplerBins      NUmber of Doppler bins
 *
 *   @param[in] winLen              window length in CFAR
 *
 *   @param[in] guardLen            guard length in CFAR
 *
 *   @param[in] noiseDivRightShift  noiseDiv factor expressed as right shift in CFAR
 *
 *   @param[in] peakGrouping        peakGrouping flag in CFAR
 *
 *   @param[in] cyclicMode          cyclic mode in CFAR
 *
 *   @param[in] nAvgMode            noise averaging mode in CFAR
 *
 *   @param[in] detObjectListSize   maximum size of list of detected objects
 *
 *   @param[in] dmaTriggerSource    DMA trigger source channel
 *
 *   @param[in] dmaDestChannel      DMA destination channel
 *
 *   @param[in] hwaSourceBufOffset  HWA memory offset with input data:
 *                                  log magnitude 2nd D FFT matrix
 *
 *   @param[in] hwaDestBufOffset    HWA memory offset with CFAR output results:
 *                                  List of detected objects as array of structures
 *                                  cfarDetOutput_t
 *
 */
void HWAutil_configCFAR(HWA_Handle handle,
                        uint32_t paramSetStartIdx,
                        uint32_t numRangeBins,
                        uint32_t numDopplerBins,
                        uint32_t winLen,
                        uint32_t guardLen,
                        uint32_t noiseDivRightShift,
                        uint8_t peakGrouping,
                        uint8_t cyclicMode,
                        uint8_t nAvgMode,
                        uint16_t detObjectListSize,
                        uint8_t dmaTriggerSource,
                        uint8_t dmaDestChannel,
                        uint16_t hwaSourceBufOffset,
                        uint16_t hwaDestBufOffset);

/**
 * @brief
 *  Industrial Level Sensing Demo MCB
 *
 * @details
 *  The structure is used to hold all the relevant information for the
 *  Industrial Level Sensing demo.
 */
typedef struct LSDemo_MCB_t
{
    /*! * @brief   Handle to the SOC Module */
    SOC_Handle socHandle;

    /*! @brief   This is the mmWave control handle which is used
     * to configure the BSS. */
    MMWave_Handle ctrlHandle;

    /*! @brief   mmWave Control Configuration. */
    MMWave_CtrlCfg ctrlCfg;

    /*! @brief   mmWave Open Configuration. */
    MMWave_OpenCfg openCfg;

    /*! @brief   mmWave Profile Configuration. */
    rlProfileCfg_t profileCfg;

    /*! @brief   mmWave Chirp Configuration. */
    MMWave_ChirpHandle chirpHandle;
    rlChirpCfg_t chirpCfg;

    /*! @brief   mmWave Calibration Configuration. */
    MMWave_CalibrationCfg calCfg;

    /*! @brief   ADCBuf Configuration. */
    Demo_ADCBufCfg adcbufCfg;

    /*! @brief   Data Path object */
    Demo_DataPathObj dataPathObj;

    // /*! @brief      UART Command Rx/Tx Handle */
    // UART_Handle                 commandUartHandle;
} LSDemo_MCB;

void Communicate_With_Jingbo(UArg arg0, UArg arg1);

void demo_dataPathInit(Demo_DataPathObj *obj);
void demo_dataPathOpen(Demo_DataPathObj *obj);
void demo_dataPathConfig(void);
void demo_dataPathConfigCommon(Demo_DataPathObj *obj);

void demo_dataPathTask(UArg arg0, UArg arg1);
void demo_mmWaveCtrlTask(UArg arg0, UArg arg1);
void demo_calibrationTask(UArg arg0, UArg arg1);
// #define MmwDemo_debugAssert(expression) {                                      \
//                                          _MmwDemo_debugAssert(expression,      \
//                                                   __FILE__, __LINE__);         \
//                                          DebugP_assert(expression);             \
//                                         }

#endif // __DEMO_H__
