/**
  ******************************************************************************
  * @author  泽耀科技 ASHINING
  * @version V3.0
  * @date    2016-10-08
  * @brief   NRF24L01配置C文件
  ******************************************************************************
  * @attention
  *
  * 官网  :   http://www.ashining.com
  * 淘宝  :   https://shop105912646.taobao.com
  * 阿里巴巴:   https://cdzeyao.1688.com
  *************************************************************************
*/
//#define 	SI24R1
#include "RF24L01.h"
#include "platform.h"
#include "function.h"
#include "base_core_user.h"
#include "function_interface.h"
#include "HW_MCUIO.h"

#ifdef SI24R1

//hardware 200s RF modual silk screen:J2-J3-J1-J4
HW_GPIO_PortDef const rf_cs_port[4]={GPIOD,GPIOB,GPIOD,GPIOC};
uint16_t const rf_cs_pin[4] ={GPIO_PIN_13,GPIO_PIN_4,GPIO_PIN_3,GPIO_PIN_6};

//isr
HW_GPIO_PortDef const rf_it_port[4]={GPIOD,GPIOD,GPIOD,GPIOC};
uint16_t const rf_it_pin[4] ={GPIO_PIN_14,GPIO_PIN_5,GPIO_PIN_4,GPIO_PIN_7};

//用于设置开关中断
const unsigned char rf_it_pin_nbr[]={14,5,4,7};


//TX PA 5.8G 	//cc2500 RF_LNA
HW_GPIO_PortDef const rf_paTX_port[4]={GPIOD,GPIOD,GPIOD,GPIOC};
uint16_t const rf_paTX_pin[4] ={GPIO_PIN_11,GPIO_PIN_6,GPIO_PIN_1,GPIO_PIN_4};

//RX PA 5.8G   //cc2500-RF_PA_EN
HW_GPIO_PortDef const rf_ce_port[4]={GPIOD,GPIOD,GPIOD,GPIOC};
uint16_t const rf_ce_pin[4] ={GPIO_PIN_12,GPIO_PIN_7,GPIO_PIN_2,GPIO_PIN_5};


#define RF24L01_SET_CS_HIGH(id)     HW_GPIO_SetPin(rf_cs_port[id],rf_cs_pin[id])
#define RF24L01_SET_CS_LOW(id)      HW_GPIO_ResetPin(rf_cs_port[id],rf_cs_pin[id])
#define RF24L01_SET_CE_HIGH(id)     HW_GPIO_SetPin(rf_ce_port[id],rf_ce_pin[id])
#define RF24L01_SET_CE_LOW(id)      HW_GPIO_ResetPin(rf_ce_port[id],rf_ce_pin[id])
#define RF24L01_SET_PATX_HIGH(id)   HW_GPIO_SetPin(rf_paTX_port[id],rf_paTX_pin[id])
#define RF24L01_SET_PATX_LOW(id)    HW_GPIO_ResetPin(rf_paTX_port[id],rf_paTX_pin[id])

//#define RF24L01_SET_CE_HIGH( )  HAL_GPIO_WritePin(RF_PORT,RF_PA, GPIO_PIN_SET)
//#define RF24L01_SET_CE_LOW( )   HAL_GPIO_WritePin(RF_PORT,RF_PA, GPIO_PIN_RESET)
//#define RF24L01_SET_CS_HIGH( )  HAL_GPIO_WritePin(RF_PORT,RF_CS, GPIO_PIN_SET)
//#define RF24L01_SET_CS_LOW( )   HAL_GPIO_WritePin(RF_PORT,RF_CS, GPIO_PIN_RESET)
//#define RF24L01_SET_PATX_HIGH( )  HAL_GPIO_WritePin(RF_PORT,RF_LNA,GPIO_PIN_SET)
//#define RF24L01_SET_PATX_LOW( )   HAL_GPIO_WritePin(RF_PORT,RF_LNA,GPIO_PIN_RESET)

#ifdef C100
#define OPEN_MISO(id)		{}
#define CLOSE_MISO(id)  {}

#else
// miso control
GPIO_TypeDef* const miso_ctrl_port[4]={GPIOE,GPIOB,GPIOE,GPIOE};
uint16_t const miso_ctrl_pin[4] ={GPIO_PIN_8,GPIO_PIN_7,GPIO_PIN_9,GPIO_PIN_10};

#define OPEN_MISO(id)		HAL_GPIO_WritePin(miso_ctrl_port[id],miso_ctrl_pin[id], GPIO_PIN_SET)	
#define CLOSE_MISO(id)	HAL_GPIO_WritePin(miso_ctrl_port[id],miso_ctrl_pin[id], GPIO_PIN_RESET)	
#endif 

//#define	SIM_SPI
/*
*/
//extern SPI_HandleTypeDef hspi1;
static unsigned char drv_spi_read_write_byte( unsigned char TxData,unsigned char rf_seq )
{
	#ifdef SIM_SPI
		#define SPI1_BREAK   200
    unsigned short retry = 0;
    while( ( SPI1->SR & 1 << 1 ) == 0 ){ // 等待发送空闲   
			retry++;
			if( retry > SPI1_BREAK )       
				return 0;       
    }
    SPI1->DR = TxData;        //发送

    retry = 0;
    while( ( SPI1->SR & 1 << 0 ) == 0 ){ //等待接收完成    
			retry++;
			if( retry > SPI1_BREAK )       
			 return 0;       
    }
    return SPI1->DR;          //返回接收到的数据	
#else	
	
		uint8_t rlst;
		unsigned char rx_data;
		OPEN_MISO(rf_seq);
		rlst =HW_RF_SPI_TransmitReceive(&TxData,&rx_data,1);//HAL_SPI_TransmitReceive(&hspi1,&TxData,&rx_data,1, 100);
//		CLOSE_MISO(rf_seq);
		if(rlst == 0x00U)
			return rx_data;
		else 
			return 0;
#endif 	
}

#define 	SPI_WR_N	1		//add by Gavin20211023

static unsigned char drv_spi_read_write_byte_N( unsigned char *TxData,unsigned char *RxData,unsigned char len,unsigned char rf_seq )
{
	#ifdef SIM_SPI
		#define SPI1_BREAK   200
    unsigned short retry = 0;
    while( ( SPI1->SR & 1 << 1 ) == 0 ){ // 等待发送空闲   
			retry++;
			if( retry > SPI1_BREAK )       
				return 0;       
    }
    SPI1->DR = TxData;        //发送

    retry = 0;
    while( ( SPI1->SR & 1 << 0 ) == 0 ){ //等待接收完成    
			retry++;
			if( retry > SPI1_BREAK )       
			 return 0;       
    }
    return SPI1->DR;          //返回接收到的数据	
#else	
	
		uint8_t rlst;
		//unsigned char rx_data;
		//OPEN_MISO(rf_seq);
		rlst =HW_RF_SPI_TransmitReceive(TxData,RxData,len);//HAL_SPI_TransmitReceive(&hspi1,TxData,RxData,len, 500);
//		CLOSE_MISO(rf_seq);
		if(rlst == 0x00U)
			return 1;
		else 
			return 0;
#endif 	
}


/*
2019.12.04 实测 delay(500) =500us;
环境：主频168MHz,关闭中断,IO取反用示波器测试!!	
由于GPIO无法响应 delayus(1)，所以实际测试delay(500) =500us	*/
static void _24R1_delay_us( unsigned short time )
{
    unsigned short i = 0;
    while( time-- ){
			i = 30; 
			while( i-- ) ;
    }
}

/*
*/
static void DelayUs( unsigned short time )
{
//    unsigned short i = 0;
//    while( time-- ){
//      i = 6; //16M=2
//      while( i-- ) ;
//    }
		_24R1_delay_us(10);//(10);
}





/**
  * @brief :NRF24L01读寄存器
  * @param :
           @Addr:寄存器地址
  * @note  :地址在设备中有效
  * @retval:读取的数据
  */
static uint8_t NRF24L01_Read_Reg( uint8_t RegAddr,unsigned char rf_seq )
{
    uint8_t btmp;
    RF24L01_SET_CS_LOW(rf_seq );          //片选

    drv_spi_read_write_byte( NRF_READ_REG | RegAddr,rf_seq );  //读命令 地址
    btmp = drv_spi_read_write_byte( 0xFF ,rf_seq);             //读数据

    RF24L01_SET_CS_HIGH(rf_seq );         //取消片选

    return btmp;
}

/**
  * @brief :NRF24L01读指定长度的数据
  * @param :
  *         @reg:地址
  *         @pBuf:数据存放地址
  *         @len:数据长度
  * @note  :数据长度不超过255，地址在设备中有效
  * @retval:读取状态
  */
void NRF24L01_Read_Buf( uint8_t RegAddr, uint8_t* pBuf, uint8_t len ,unsigned char rf_seq)
{
    uint8_t btmp;

    RF24L01_SET_CS_LOW(rf_seq );          //片选

    drv_spi_read_write_byte( NRF_READ_REG | RegAddr ,rf_seq);  //读命令 地址
		#if (SPI_WR_N)
		{
			unsigned char tmp[256];
			drv_spi_read_write_byte_N(tmp,pBuf,len,rf_seq);
		}
		#else
    for( btmp = 0; btmp < len; btmp ++ )
    {
        *( pBuf + btmp ) = drv_spi_read_write_byte( 0xFF ,rf_seq); //读数据
    }
		#endif
    RF24L01_SET_CS_HIGH(rf_seq );     //取消片选
}

/**
  * @brief :NRF24L01写寄存器
  * @param :无
  * @note  :地址在设备中有效
  * @retval:读写状态
  */
static void NRF24L01_Write_Reg( uint8_t RegAddr, uint8_t Value ,unsigned char rf_seq)
{
	
//		if(rf_seq !=1)
//		rf_seq=1;
		
    RF24L01_SET_CE_LOW(rf_seq); //pei只能在standby模式下修改!!
    RF24L01_SET_CS_LOW(rf_seq);      //片选

    drv_spi_read_write_byte( NRF_WRITE_REG | RegAddr ,rf_seq); //写命令 地址
    drv_spi_read_write_byte( Value ,rf_seq);           //写数据

    RF24L01_SET_CS_HIGH( rf_seq);     //取消片选
}

/**
  * @brief :NRF24L01写指定长度的数据
  * @param :
  *         @reg:地址
  *         @pBuf:写入的数据地址
  *         @len:数据长度
  * @note  :数据长度不超过255，地址在设备中有效
  * @retval:写状态
  */
static void NRF24L01_Write_Buf( uint8_t RegAddr, uint8_t* pBuf, uint8_t len ,unsigned char rf_seq)
{
    uint8_t i;

    RF24L01_SET_CS_LOW(rf_seq );      //片选

    drv_spi_read_write_byte( NRF_WRITE_REG | RegAddr ,rf_seq); //写命令 地址
		#if (SPI_WR_N)
		{
			unsigned char tmp[256];
			drv_spi_read_write_byte_N(pBuf,tmp,len,rf_seq);
		}
		#else	
    for( i = 0; i < len; i ++ )
    {
        drv_spi_read_write_byte( *( pBuf + i ) ,rf_seq);       //写数据
    }
		#endif
    RF24L01_SET_CS_HIGH( rf_seq);     //取消片选
}


/**
  * @brief :清空TX缓冲区
  * @param :无
  * @note  :无
  * @retval:无
  */
static void NRF24L01_Flush_Tx_Fifo( unsigned char rf_seq)
{
    RF24L01_SET_CS_LOW( rf_seq);      //片选

    drv_spi_read_write_byte( FLUSH_TX ,rf_seq);    //清TX FIFO命令

    RF24L01_SET_CS_HIGH(rf_seq );     //取消片选
}

/**
  * @brief :清空RX缓冲区
  * @param :无
  * @note  :无
  * @retval:无
  */
static void NRF24L01_Flush_Rx_Fifo( unsigned char rf_seq)
{
    RF24L01_SET_CS_LOW(rf_seq );      //片选

    drv_spi_read_write_byte( FLUSH_RX ,rf_seq);    //清RX FIFO命令

    RF24L01_SET_CS_HIGH( rf_seq);     //取消片选
}

/**
  * @brief :重新使用上一包数据
  * @param :无
  * @note  :无
  * @retval:无
  */
//static void NRF24L01_Reuse_Tx_Payload( void )
//{
//    RF24L01_SET_CS_LOW( );      //片选

//    drv_spi_read_write_byte( REUSE_TX_PL );     //重新使用上一包命令

//    RF24L01_SET_CS_HIGH( );     //取消片选
//}

/**
  * @brief :NRF24L01空操作
  * @param :无
  * @note  :无
  * @retval:无
  */
//static void NRF24L01_Nop( void )
//{
//    RF24L01_SET_CS_LOW( );      //片选

//    drv_spi_read_write_byte( NOP );     //空操作命令

//    RF24L01_SET_CS_HIGH( );     //取消片选
//}

/**
  * @brief :NRF24L01读状态寄存器
  * @param :无
  * @note  :无
  * @retval:RF24L01状态
  */
static uint8_t NRF24L01_Read_Status_Register( unsigned char rf_seq )
{
    uint8_t Status;

    RF24L01_SET_CS_LOW( rf_seq);      //片选

    Status = drv_spi_read_write_byte( NRF_READ_REG + STATUS ,rf_seq);  //读状态寄存器

    RF24L01_SET_CS_HIGH( rf_seq);     //取消片选

    return Status;
}

/**
  * @brief :NRF24L01清中断
  * @param :
           @IRQ_Source:中断源
  * @note  :无
  * @retval:清除后状态寄存器的值
  */
static uint8_t NRF24L01_Clear_IRQ_Flag( uint8_t IRQ_Source ,unsigned char rf_seq)
{
    uint8_t btmp = 0;

    IRQ_Source &= ( 1 << RX_DR ) | ( 1 << TX_DS ) | ( 1 << MAX_RT );    //中断标志处理
    btmp = NRF24L01_Read_Status_Register( rf_seq);            //读状态寄存器

    RF24L01_SET_CS_LOW( rf_seq);          //片选
    drv_spi_read_write_byte( NRF_WRITE_REG + STATUS ,rf_seq);  //写状态寄存器命令
    drv_spi_read_write_byte( IRQ_Source | btmp ,rf_seq);       //清相应中断标志
    RF24L01_SET_CS_HIGH( rf_seq);         //取消片选

    return ( NRF24L01_Read_Status_Register( rf_seq) );        //返回状态寄存器状态
}

/**
  * @brief :读RF24L01中断状态
  * @param :无
  * @note  :无
  * @retval:中断状态
  */
//static uint8_t RF24L01_Read_IRQ_Status( void )
//{
//    return ( NRF24L01_Read_Status_Register( ) & ( ( 1 << RX_DR ) | ( 1 << TX_DS ) | ( 1 << MAX_RT ) ) ); //返回中断状态
//}

/**
 * @brief :读FIFO中数据宽度
 * @param :无
 * @note  :无
 * @retval:数据宽度
 */
static uint8_t NRF24L01_Read_Top_Fifo_Width( unsigned char rf_seq )
{
    uint8_t btmp;

    RF24L01_SET_CS_LOW( rf_seq);      //片选

    drv_spi_read_write_byte( R_RX_PL_WID ,rf_seq); //读FIFO中数据宽度命令
    btmp = drv_spi_read_write_byte( 0xFF ,rf_seq); //读数据

    RF24L01_SET_CS_HIGH( rf_seq);     //取消片选

    return btmp;
}

/**
 * @brief :读接收到的数据
 * @param :无
 * @note  :无
 * @retval:
          @pRxBuf:数据存放地址首地址
 */
static uint8_t NRF24L01_Read_Rx_Payload( uint8_t* pRxBuf ,unsigned char rf_seq)
{
    uint8_t volatile Width, PipeNum;

    PipeNum = ( NRF24L01_Read_Reg( STATUS ,rf_seq) >> 1 ) & 0x07;  //读接收状态
    //Width= NRF24L01_Read_Reg(RX_PW_P0);//读出为0
    Width = NRF24L01_Read_Top_Fifo_Width(rf_seq );        //读接收数据个数
    if( Width > 32 ) //pei--好像出现不了
    {
        NRF24L01_Flush_Rx_Fifo( rf_seq);
        return 0;
    }

    RF24L01_SET_CS_LOW(rf_seq );      //片选
    drv_spi_read_write_byte( RD_RX_PLOAD ,rf_seq);         //读有效数据命令
		#if (SPI_WR_N)
		{
			unsigned char tmp[256];
			drv_spi_read_write_byte_N(tmp,pRxBuf,Width,rf_seq);
		}
		#else	
    for( PipeNum = 0; PipeNum < Width; PipeNum ++ )
    {
        *( pRxBuf + PipeNum ) = drv_spi_read_write_byte( 0xFF ,rf_seq);        //读数据
    }
		#endif
    RF24L01_SET_CS_HIGH( rf_seq);     //取消片选

    NRF24L01_Flush_Rx_Fifo( rf_seq);  //清空RX FIFO  --出现过读出是上一包情况后加---确实能模拟出现
    //Width = NRF24L01_Read_Top_Fifo_Width( );//即使清除FIFO读出还是原来的值
    //NRF24L01_Clear_IRQ_Flag( IRQ_ALL );//可以避免中断响应中又接收一包后模块不再产生中断，因为中断没清除标志
    return Width;
}

/**
 * @brief :发送数据（带应答）
 * @param :
 *         @pTxBuf:发送数据地址
 *         @len:长度
 * @note  :一次不超过32个字节
 * @retval:无
 */
//static void NRF24L01_Write_Tx_Payload_Ack( uint8_t* pTxBuf, uint8_t len )
//{
//    uint8_t btmp;
//    uint8_t length = ( len > 32 ) ? 32 : len;       //数据长达大约32 则只发送32个

//    NRF24L01_Flush_Tx_Fifo( );      //清TX FIFO

//    RF24L01_SET_CS_LOW( );          //片选
//    drv_spi_read_write_byte( WR_TX_PLOAD ); //发送命令

//    for( btmp = 0; btmp < length; btmp ++ )
//    {
//        drv_spi_read_write_byte( *( pTxBuf + btmp ) );  //发送数据
//    }
//    RF24L01_SET_CS_HIGH( );         //取消片选
//}

/**
 * @brief :发送数据（不带应答）
 * @param :
 *         @pTxBuf:发送数据地址
 *         @len:长度
 * @note  :一次不超过32个字节
 * @retval:无
 */
static void NRF24L01_Write_Tx_Payload_NoAck( uint8_t* pTxBuf, uint8_t len ,unsigned char rf_seq)
{
    if( len > 32 || len == 0 )
    {
        return ;        //数据长度大于32 或者等于0 不执行
    }

    RF24L01_SET_CS_LOW( rf_seq);  //片选
    drv_spi_read_write_byte( WR_TX_PLOAD_NACK ,rf_seq);    //发送命令
		#if (SPI_WR_N)
		{
			unsigned char tmp[256];
			drv_spi_read_write_byte_N(pTxBuf,tmp,len,rf_seq);
		}
		#else			
    while( len-- )
    {
        drv_spi_read_write_byte( *pTxBuf ,rf_seq);         //发送数据
        pTxBuf++;
    }
		#endif
    RF24L01_SET_CS_HIGH(rf_seq );     //取消片选
}

/**
 * @brief :在接收模式下向TX FIFO写数据(带ACK)
 * @param :
 *         @pData:数据地址
 *         @len:长度
 * @note  :一次不超过32个字节
 * @retval:无
 */
//static void NRF24L01_Write_Tx_Payload_InAck( uint8_t* pData, uint8_t len )
//{
//    uint8_t btmp;

//    len = ( len > 32 ) ? 32 : len;      //数据长度大于32个则只写32个字节

//    RF24L01_SET_CS_LOW( );          //片选
//    drv_spi_read_write_byte( W_ACK_PLOAD );     //命令
//    for( btmp = 0; btmp < len; btmp ++ )
//    {
//        drv_spi_read_write_byte( *( pData + btmp ) );   //写数据
//    }
//    RF24L01_SET_CS_HIGH( );         //取消片选
//}

/**
 * @brief :设置发送地址
 * @param :
 *         @pAddr:地址存放地址
 *         @len:长度
 * @note  :无
 * @retval:无
 */
static void NRF24L01_Set_TxAddr( uint8_t* pAddr, uint8_t len ,unsigned char rf_seq)
{
    len = ( len > 5 ) ? 5 : len;                    //地址不能大于5个字节
    NRF24L01_Write_Buf( TX_ADDR, pAddr, len ,rf_seq);  //写地址
}

/**
 * @brief :设置接收通道地址
 * @param :
 *         @PipeNum:通道
 *         @pAddr:地址存肥着地址
 *         @Len:长度
 * @note  :通道不大于5 地址长度不大于5个字节
 * @retval:无
 */
static void NRF24L01_Set_RxAddr( uint8_t PipeNum, uint8_t* pAddr, uint8_t Len ,unsigned char rf_seq)
{
    Len = ( Len > 5 ) ? 5 : Len;
    PipeNum = ( PipeNum > 5 ) ? 5 : PipeNum;        //通道不大于5 地址长度不大于5个字节

    NRF24L01_Write_Buf( RX_ADDR_P0 + PipeNum, pAddr, Len ,rf_seq); //写入地址
}

/**
 * @brief :设置通信速度
 * @param :
 *         @Speed:速度
 * @note  :无
 * @retval:无
 */
static void NRF24L01_Set_Speed( nRf24l01SpeedType Speed ,unsigned char rf_seq)
{
    uint8_t btmp = 0;

    btmp = NRF24L01_Read_Reg( RF_SETUP ,rf_seq);
    btmp &= ~( ( 1 << 5 ) | ( 1 << 3 ) );

    if( Speed == SPEED_250K )       //250K
    {
        btmp |= ( 1 << 5 );
    }
    else if( Speed == SPEED_1M )   //1M
    {
        btmp &= ~( ( 1 << 5 ) | ( 1 << 3 ) );
    }
    else if( Speed == SPEED_2M )   //2M
    {
        btmp |= ( 1 << 3 );
    }

    NRF24L01_Write_Reg( RF_SETUP, btmp ,rf_seq);
}


/**
 * @brief :设置频率
 * @param :
 *         @FreqPoint:频率设置参数
 * @note  :值不大于127
 * @retval:无
 */
static void RF24L01_Chan( uint8_t FreqPoint ,unsigned char rf_seq)
{
    NRF24L01_Write_Reg( RF_CH, FreqPoint & 0x7F ,rf_seq);
}

/**
  * @brief :NRF24L01检测
  * @param :无
  * @note  :无
  * @retval:无
  */
unsigned char NRF24L01_check( unsigned char rf_seq )
{
    uint8_t i;
    uint8_t buf[5] = { 0X11, 0X22, 0XA3, 0XA4, 0XA5 };
    uint8_t read_buf[ 5 ] = { 0 };

    NRF24L01_Write_Buf( TX_ADDR, buf, 5 ,rf_seq);          //写入5个字节的地址
    NRF24L01_Read_Buf( TX_ADDR, read_buf, 5 ,rf_seq);      //读出写入的地址

    for( i = 0; i < 5; i++ ){
			if( buf[ i ] != read_buf[ i ] )
				return 0;
    }
		return 1;
}

/**
 * @brief :设置模式
 * @param :
 *         @Mode:模式发送模式或接收模式
 * @note  :无
 * @retval:无
 */
static void RF24L01_Set_Mode( nRf24l01ModeType Mode ,unsigned char rf_seq)
{
    uint8_t controlreg = 0;
    controlreg = NRF24L01_Read_Reg( CONFIG ,rf_seq);

    if( Mode == MODE_TX )
    {
        controlreg &= ~( 1 << PRIM_RX );
    }
    else
    {
        if( Mode == MODE_RX )
        {
            controlreg |= ( 1 << PRIM_RX );
        }
    }

    NRF24L01_Write_Reg( CONFIG, controlreg ,rf_seq);
}

/**
  * @brief :NRF24L01发送一次数据
  * @param :
  *         @txbuf:待发送数据首地址
  *         @Length:发送数据长度
  * @note  :无
  * @retval:
  *         MAX_TX：达到最大重发次数
  *         TX_OK：发送完成
  *         0xFF:其他原因
  */
//static uint8_t NRF24L01_TxPacket( uint8_t* txbuf, uint8_t Length )
//{
////    uint8_t l_Status = 0;
////    uint16_t l_MsTimes = 0;

//    RF24L01_SET_CS_LOW( );      //片选
//    drv_spi_read_write_byte( FLUSH_TX );
//    RF24L01_SET_CS_HIGH( );

//    RF24L01_SET_CE_LOW( );
//    NRF24L01_Write_Buf( WR_TX_PLOAD, txbuf, Length );   //写数据到TX BUF 32字节  TX_PLOAD_WIDTH
//    RF24L01_SET_CE_HIGH( );         //启动发送

//    return 0xFF;    //其他原因发送失败
//}

/**
  * @brief :NRF24L01接收数据
  * @param :
  *         @rxbuf:接收数据存放地址
  * @note  :无
  * @retval:接收的数据个数
  */
//static uint8_t NRF24L01_RxPacket( uint8_t* rxbuf )
//{
//    uint8_t l_Status = 0, l_RxLength = 0;//, l_100MsTimes = 0;

//    l_Status = NRF24L01_Read_Reg( STATUS );     //读状态寄存器
//    NRF24L01_Write_Reg( STATUS, l_Status );     //清中断标志
//    if( l_Status & RX_OK )  //接收到数据
//    {
//        l_RxLength = NRF24L01_Read_Reg( R_RX_PL_WID );      //读取接收到的数据个数
//        NRF24L01_Read_Buf( RD_RX_PLOAD, rxbuf, l_RxLength ); //接收到数据
//        NRF24L01_Write_Reg( FLUSH_RX, 0xff );               //清除RX FIFO
//        return l_RxLength;
//    }

//    return 0;               //没有收到数据
//}



//#define 	NRF24L01
static void NRF24L01_SetPA( unsigned char level ,unsigned char rf_seq)
{
    uint8_t btmp;
level =0;
#ifdef NRF24L01
    btmp = NRF24L01_Read_Reg( RF_SETUP ) & ~0x06;
    btmp |= ( (level<<1) & 6 ) |0x01;
    NRF24L01_Write_Reg( RF_SETUP, btmp );
#else		
    btmp = NRF24L01_Read_Reg( RF_SETUP ,rf_seq) & ~0x07;
    btmp |= ( level & 7 );
    NRF24L01_Write_Reg( RF_SETUP, btmp ,rf_seq);
#endif 	
	
}

//切换到接收模式
static void RF24L01_RxOn(unsigned char rf_seq)
{
    RF24L01_SET_CE_LOW(rf_seq);//standby才能设置

    RF24L01_Set_Mode( MODE_RX ,rf_seq);
    RF24L01_SET_CE_HIGH(rf_seq);
}



//清除接收中断标志位，解除芯片接收死机
static void RF24L01_ClrIRQ(unsigned char rf_seq)
{
    NRF24L01_Clear_IRQ_Flag( IRQ_ALL ,rf_seq);
}









//------------------------------------------------------------------------------------------------

//static void rf_io_init( void )
//{
//    SPI_InitTypeDef  SPI_InitStructure;
//    GPIO_InitTypeDef GPIO_InitStructure;
//    EXTI_InitTypeDef   EXTI_InitStructure;
//    NVIC_InitTypeDef   NVIC_InitStructure;

//		RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE );
//    /* Enable SPI1 clocks */ //¿ªÊ¼³õÊ¼»¯SPI
//    RCC_APB2PeriphClockCmd( RCC_APB2Periph_SPI1, ENABLE );

//    /* Configure SPI1 pins: NSS, SCK, MISO and MOSI */
//    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7; //no NSS
//    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
//    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
//    GPIO_Init( GPIOA, &GPIO_InitStructure );
//	
//    GPIO_InitStructure.GPIO_Pin = RF_CS;
//    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
//    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
//    GPIO_Init( RF_PORT, &GPIO_InitStructure );
//    GPIO_SetBits( RF_PORT, RF_CS );

//    /* SPI1 configuration */
//    SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
//    SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
//    SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
//#ifndef SI24R1
//    SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
//    SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
//#else
//    SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;      //¿ÕÏÐ×´Ì¬ÎªµÍµçÆ½
//    SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;    //µÚÒ»¸ö±ßÑØ²É¼¯Êý¾Ý
//#endif
//    SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;        //Èí¼þ¿ØÖÆCS½Å
//    SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;//SPI_SPEED ;
//    SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
//    SPI_InitStructure.SPI_CRCPolynomial = 7;
//    SPI_Init( SPI1, &SPI_InitStructure );
//    SPI_Cmd( SPI1, ENABLE ); //Ê¹ÄÜSPI

//    //2,初始化 PA LNA io
//    GPIO_InitStructure.GPIO_Pin = RF_PA | RF_LNA;
//    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
//    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
//    GPIO_Init( RF_PAPORT, &GPIO_InitStructure );
//    GPIO_ResetBits( RF_PAPORT, RF_PA );
//    GPIO_ResetBits( RF_PAPORT, RF_LNA );


//    //3，设置IO输入模式用于检测rf的中断
//    /* Configure PA.3 pin as input floating */
//    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
//    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
//    GPIO_Init( GPIOA, &GPIO_InitStructure );
//    /* Connect EXTI3 Line to PA.3 pin */
//    GPIO_EXTILineConfig( GPIO_PortSourceGPIOA, GPIO_PinSource3 );

//    /* Configure EXTI3 line */
//    EXTI_InitStructure.EXTI_Line = EXTI_Line3;
//    EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
//    EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;  //ÏÂÌøÑØ
//    EXTI_InitStructure.EXTI_LineCmd = ENABLE;
//    EXTI_Init( &EXTI_InitStructure );

//    /* Enable and set EXTI3 Interrupt priority */
//    NVIC_InitStructure.NVIC_IRQChannel = EXTI3_IRQn;
//    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
//    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;//2;
//    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
//    NVIC_Init( &NVIC_InitStructure );
//    
//		NVIC_DisableIRQ( EXTI3_IRQn );		
//}





/*
设置频率点
*/
void rf_setfreq(unsigned char freq,unsigned char rf_seq)
{

    PLATFORM_DISABLE_IRQ();//CLI();
    RF24L01_Chan( freq ,rf_seq);
    RF24L01_RxOn(rf_seq);//设置频率后切换到接收模式
    PLATFORM_ENABLE_IRQ();//SEI();
}



/*
设置同步码
*/
#if (SUPPORT_HS6621_SOC)
void rf_set_syncode(unsigned short sync,unsigned char sync_cnt,unsigned char rf_seq)
{
    uint8_t addr[5] = {INIT_ADDR};	//#define INIT_ADDR           0x19,0x98,0xA4,0x25,0x01
    addr[2] = sync>>8;
    addr[3] = sync; 		//修改无线地址码，缺省A425
    NRF24L01_Set_TxAddr( addr, sync_cnt ,rf_seq);         //设置TX地址
    NRF24L01_Set_RxAddr( 0,addr, sync_cnt ,rf_seq);      //设置RX地址 通道0	
}
#else
void rf_set_syncode(unsigned short sync,unsigned char rf_seq)
{
    uint8_t addr[5] = {INIT_ADDR};	//#define INIT_ADDR           0x19,0x98,0xA4,0x25,0x01
    addr[2] = sync>>8;
    addr[3] = sync; 		//修改无线地址码，缺省A425
    NRF24L01_Set_TxAddr( addr, 4 ,rf_seq);         //设置TX地址
    NRF24L01_Set_RxAddr( 0,addr, 4 ,rf_seq);      //设置RX地址 通道0	
}
#endif


//基站设置功率，放在频点初始化函数里面
void rf_set_PA_Mode( unsigned char mode ,unsigned char rf_seq)
{
	//#ifdef FASTMATCH_LOWERPA
	if(check_fastmatch_lowerPA())
		NRF24L01_SetPA( PWR_7DB ,rf_seq);
	else
	//#endif 
	{	
			switch( mode )
			{
				case 1:
						NRF24L01_SetPA( PWR_F4DB ,rf_seq);			
						break;
				case 2:
						NRF24L01_SetPA( PWR_F6DB ,rf_seq);
						break;
				case 3:
						NRF24L01_SetPA( PWR_F12DB ,rf_seq);
						break;
				default:
						NRF24L01_SetPA( PWR_0DB ,rf_seq);
						break;		
			}
		}
}



//---------------------------------------------------------------
//初始化
void rf_initial(unsigned char rf_seq)	
{
		//test only
		NRF24L01_check(rf_seq);//Gavin 		
				
    NRF24L01_Clear_IRQ_Flag( IRQ_ALL ,rf_seq);

#if DYNAMIC_PACKET == 1
    NRF24L01_Write_Reg( DYNPD, ( 1 << 0 ) ,rf_seq);    //使能通道0动态数据长度
    //NRF24L01_Write_Reg( FEATRUE, 0x07 );
    NRF24L01_Write_Reg( FEATRUE,
                        ( 1 << EN_DPL ) |       //动态长度
                        //( 1 << EN_ACK_PAY ) |   //带负载数据的ACK包, 允许无应答，
                        ( 1 << EN_DYN_ACK ) ,rf_seq);  //带负载应答: 关闭
    NRF24L01_Read_Reg( DYNPD ,rf_seq);
    NRF24L01_Read_Reg( FEATRUE ,rf_seq);
#elif DYNAMIC_PACKET == 0
    //L01_WriteSingleReg( L01REG_RX_PW_P0, FIXED_PACKET_LEN ); //固定数据长度
    NRF24L01_Write_Reg( FEATRUE,
                        //( 1 << EN_DPL ) |       //动态长度
                        //( 1 << EN_ACK_PAY ) |   //带负载数据的ACK包, 允许无应答，
                        ( 1 << EN_DYN_ACK ) ,rf_seq);  //带负载应答: 关闭	
		NRF24L01_Write_Reg(RX_PW_P0,FIXED_PACKET_LEN,rf_seq);	
#endif  //DYNAMIC_PACKET

    NRF24L01_Write_Reg( CONFIG,
                        //( 1<<MASK_RX_DR ) | //屏蔽接收中断
                        //( 1<<MASK_TX_DS ) | //屏蔽发送中断
                        ( 1 << MASK_MAX_RT ) | //屏蔽重发次数中断
                        ( 1 << EN_CRC ) |     //使能CRC  -- 处理与nRF52832通讯兼容问题  csyxj@180424
                        ( 1 << CRCO ) |       //CRC 2字节  -- 处理与nRF52832通讯兼容问题  csyxj@180424
                        ( 1 << PWR_UP ) ,rf_seq);    //开启设备

    //NRF24L01_Write_Reg( EN_AA, ( 1 << ENAA_P0 ) );        //通道0自动应答
    NRF24L01_Write_Reg( EN_AA, 0 ,rf_seq); //关闭所有通道自动应答
    NRF24L01_Write_Reg( EN_RXADDR, ( 1 << ERX_P0 ) ,rf_seq);       //开通道0接收
		#if	(SUPPORT_HS6621_SOC)
		NRF24L01_Write_Reg( SETUP_AW, AW_5BYTES ,rf_seq);              //地址宽度 5个字节
		#else		
    NRF24L01_Write_Reg( SETUP_AW, AW_4BYTES ,rf_seq);              //地址宽度 4个字节
		#endif
		//set rf speed 
		if( function.rf_speed_set==1)
			NRF24L01_Set_Speed( SPEED_1M ,rf_seq);//rf_speed =SPEED_1M;
		else if( function.rf_speed_set==2)
			NRF24L01_Set_Speed( SPEED_2M ,rf_seq);//rf_speed =SPEED_2M;
		else 
			NRF24L01_Set_Speed( SPEED_250K ,rf_seq);//rf_speed =SPEED_250K;
	
		//set PA
    NRF24L01_SetPA( PWR_0DB ,rf_seq);

		//set sync
		#if	(SUPPORT_HS6621_SOC)
		rf_set_syncode(0xA455,5,rf_seq);
		#else		
		rf_set_syncode(0xA425,rf_seq);
		#endif
    NRF24L01_Flush_Tx_Fifo(rf_seq);
    NRF24L01_Flush_Rx_Fifo(rf_seq);//!!!否则有时上电接收不到数据？
    RF24L01_RxOn(rf_seq);
		
		//rf_setfreq(19);
//		NVIC_EnableIRQ( EXTI3_IRQn );
}






//发送数据
void rf_SendPacket( uint8_t* txbuf, uint8_t Length ,unsigned char rf_seq)
{
    //return;
    RF24L01_SET_CE_LOW(rf_seq);  //先回standby
    RF24L01_Set_Mode( MODE_TX ,rf_seq);

    RF24L01_SET_CS_LOW( rf_seq);      //片选
    drv_spi_read_write_byte( FLUSH_TX ,rf_seq);
    RF24L01_SET_CS_HIGH( rf_seq);
    if( Length > 32 )   
        Length = 32;
		
		//#ifdef FASTMATCH_LOWERPA//add by Gavin  
		if(check_fastmatch_lowerPA())
			RF24L01_SET_PATX_LOW(rf_seq);
		else
			RF24L01_SET_PATX_HIGH(rf_seq); 
		//#endif
		#if	(SUPPORT_HS6621_SOC)
		Length =FIXED_PACKET_LEN;
		#endif		
    NRF24L01_Write_Tx_Payload_NoAck( txbuf, Length ,rf_seq);
    RF24L01_SET_CE_HIGH(rf_seq);         //启动发送
    DelayUs( 50 ); //10us就可以启动发送	
//    _24R1_delay_us(100);        
    RF24L01_SET_CE_LOW(rf_seq);
}


extern void rf_modual__tx_interrupt_counter(unsigned char id);
volatile  unsigned char tx_ok_flag;
void set_tx_ok_flag(unsigned char flag)
{
	tx_ok_flag = flag;
}
unsigned char get_tx_ok_flag(void)
{
	return tx_ok_flag;
}
uint16_t waitok_cnt = 500;
void waitfor_tx_ok(void)
{
    while (waitok_cnt)
    {
        if (get_tx_ok_flag())
            return;
        _24R1_delay_us(100);//DelayUs( 100 );// Upgrade_DelayUs(2);
        waitok_cnt--;
    }
}
//无线中断响应
void rf_Irq(unsigned char rf_seq)
{
    unsigned char Status,tmp[64+1];
#ifdef DEBUG_IO	
	HW_DEBUG_1_L;
	HW_DEBUG_1_H;
#endif
    Status = NRF24L01_Read_Reg( STATUS ,rf_seq);       //读状态寄存器
//    DelayUs( 200 ); //供示波器观察
		NRF24L01_Write_Reg( STATUS, Status ,rf_seq);       //清中断标志---里面CE置低导致不再接收

		if( Status & RX_OK ){ //接收到数据   				
//			tmp[0]  = NRF24L01_Read_Rx_Payload(&tmp[1] ,rf_seq);
//			keypad_rf_data_save(tmp);		
			//Note:用tmp[0]记录数据来源那个无线模块,在主程序轮询时解释此信息
			tmp[0] = rf_seq;	//record数据来源!!
			tmp[1]  = NRF24L01_Read_Rx_Payload(&tmp[2] ,rf_seq);			
			
			base_core.rf_data_fifo_in(tmp); //keypad_rf_data_save(tmp);				
		}
			
		if( Status & TX_OK ){
			set_tx_ok_flag(1);
#ifdef RF_MODUAL_MONITOR
      rf_modual__tx_interrupt_counter(rf_seq);
#endif
		}
			 
		RF24L01_SET_PATX_LOW(rf_seq);//lower PA in fast match
		
    RF24L01_ClrIRQ(rf_seq);//排除接收死机的情况			
		RF24L01_RxOn(rf_seq);
#ifdef DEBUG_IO	
	HW_DEBUG_1_L;
#endif
}












//------------------------------------------------- FCCCE -----------------------------------------------------------------
/*
Gavin 20180629  FCCCE
1,关闭 向键盘定时发送信标 --timer2.5ms中
2，屏蔽 主程序循环中的应用；
3，将和pc通信的函数移动usb中断里直接处理，实现：
	a，用sdk来切换各种测试模式
	b,利用sdk修改频点和基站本身的DFU
4,
*/

#ifdef FCCCE

/*
* 特殊处理模式1-- 30ms执行一次发送
*/
unsigned char mode1_flag=0;
void fcc_mode1(void)
{
	if( mode1_flag ){
		unsigned char tmp[32];
		for(unsigned char i=0;i<32;i++)
			tmp[i] = i;	
		rf_SendPacket(tmp,32,3);
	}
}



#define  SEI	PLATFORM_ENABLE_IRQ
#define  CLI	PLATFORM_DISABLE_IRQ
/*
*input:mode 
		//FCC认证需要的特殊测试模式
		//1 连续发射模式（带调制）  -需要定时发送
		//2 连续收信模式（带调制）
		//3 无调制 连续发信模式		-只需执行一次即可
		//4 无调制 连续收信模式
	test chan
		//测试频率点
*/
void FCC_test_enter(unsigned char mode,unsigned char base_test_chan)
{
	unsigned char i;
	unsigned char rf_seq =3;//模块编号
	
	mode1_flag=0;	
	
	RF24L01_Chan( base_test_chan ,rf_seq);	//set channel 

	
	i=NRF24L01_Read_Reg(RF_SETUP,rf_seq);
	i &=~(1<<CONT_WAVE);	
	NRF24L01_Write_Reg(RF_SETUP,i,rf_seq);
	
  switch (mode){

	case 1://连续MSK输出
		CLI();		
		i=NRF24L01_Read_Reg(RF_SETUP,rf_seq);		
		i &=~( (1<<CONT_WAVE)|(1<<PLL_LOCK));
		NRF24L01_Write_Reg(RF_SETUP,i,rf_seq);	
		SEI();
		mode1_flag=1;
		break;

	case 2://连续MSK接收
		CLI();
		RF24L01_SET_CE_LOW(rf_seq );
		NRF24L01_Flush_Rx_Fifo(rf_seq);
		RF24L01_Set_Mode(MODE_RX,rf_seq);
		RF24L01_SET_CE_HIGH(rf_seq);
		SEI();
		break;	  

	case 3://连续载波输出，无调制
		CLI();
		//无线模块测试
		RF24L01_SET_CE_LOW(rf_seq);//切换模式前,CE=1		
		NRF24L01_Set_Speed(SPEED_1M,rf_seq);
		//NRF24L01_SetPA(2,rf_seq);//RF24L01_PA_Mode(2);//NRF24L01_Set_Power(POWER_4DBM); //modify By Gavin
		i=NRF24L01_Read_Reg(RF_SETUP,rf_seq);
		i |= (1<<CONT_WAVE)|(1<<PLL_LOCK);	
		NRF24L01_Write_Reg(RF_SETUP,i,rf_seq);
		RF24L01_Set_Mode(MODE_TX,rf_seq);//TX mode
		NRF24L01_Flush_Tx_Fifo(rf_seq);//清空TX FIFO
		RF24L01_SET_CE_HIGH(rf_seq);	//启动发送
		SEI();
		break;

	case 4://连续载波模式接收，无调制	
		CLI();
		RF24L01_SET_CE_LOW(rf_seq);
		NRF24L01_Flush_Rx_Fifo(rf_seq);
		RF24L01_Set_Mode(MODE_RX,rf_seq);
		RF24L01_SET_CE_HIGH(rf_seq);
		SEI();  
		break;	

	default:break;
   }//sw
}


#endif //FCCCE



#endif

