/**
  ******************************************************************************
  **说明：003项目写码程序
  **功能：答题卡写码
  **作者：Bruce
  **日期：2017.6.8
  ******************************************************************************
**/ 

/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
#include "printf.h"
#include "USART2.h"
#include "LED.h"
#include "delay.h"
#include "nrf24L01.h"
#include "DataProc.h"
#include "tim.h"
#include "flash.h"
#include "LCD.h"



/* Functions ---------------------------------------------------------*/
void RCC_Configuration(void);
void NVIC_Configuration(void);

void IWDG_Init(u8 prer,u16 rlr);
void IWDG_Feed(void);

extern unsigned char txBuf[32];
extern u8 protocol_config_flg;
extern u8 first_clear_flag;

#if defined (STM32F10X_LD_VL) || (defined STM32F10X_MD_VL) || (defined STM32F10X_HD_VL)

#define SYSCLK_FREQ_24MHz  24000000
#else
#define SYSCLK_FREQ_72MHz  72000000
#endif

/** @addtogroup STM32F10x_StdPeriph_Template
  * @{
  */

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
#if 1
#define SCAN_ADDRESS         (unsigned char*)"\x34\x43\x10\x10\x01"
#define SCAN_SETUPVALUE      0x07
#define SCAN_TX_ADR_WIDTH    (5)       //3???????
#define SCAN_RX_ADR_WIDTH    (5)       //3???????
#define SCAN_RX_PLOAD_WIDTH  (10)    //32?????????
#define SCAN_TX_PLOAD_WIDTH  (10)      //32?????????
#define SCAN_RF_CRC          (0x00)
#define SCAN_RF_ENAA         (0x01)
#define  SCAN_TX_CHNL       (40)      //??????1
#define  SCAN_RX_CHNL       (40)      //??????2
#define  SCAN_DYNPD         (0x01)
#define  SCAN_FEATURE       (0x07)

void NRF24L01_TELPO_RX_Mode(SPIType spiNum,unsigned char* addr,
                             unsigned char addrlen,
                             unsigned char rf_channel,
                             unsigned char rf_setup,
                             unsigned char rf_crc,
                             unsigned char rf_enaa,  
                             unsigned char len,
                             unsigned char dynpd,
                             unsigned char feature)
{
    NRF24L01_Write_Reg(spiNum,NRF_WRITE_REG+SETUP_AW,addrlen - 2);//???? --3??
    NRF24L01_Write_Buf(spiNum,NRF_WRITE_REG+RX_ADDR_P0,(u8*)addr,addrlen);//?RX???? 
    NRF24L01_Write_Buf(spiNum,NRF_WRITE_REG+TX_ADDR,(u8*)addr,addrlen);//?TX???? 

   
    NRF24L01_Write_Reg(spiNum,NRF_WRITE_REG+EN_AA,rf_enaa);    //????0?????    

    NRF24L01_Write_Reg(spiNum,NRF_WRITE_REG+EN_RXADDR,0x01);//????0?????    

    NRF24L01_Write_Reg(spiNum,NRF_WRITE_REG+RF_CH,rf_channel);        //??RF????
                                                   
    NRF24L01_Write_Reg(spiNum,NRF_WRITE_REG+RF_SETUP,rf_setup);//??TX????,0db??,1Mbps,???????     
    
    NRF24L01_Write_Reg(spiNum,NRF_WRITE_REG+RX_PW_P0,len);//????0??????? 
    

    NRF24L01_Write_Reg(spiNum,NRF_WRITE_REG+CONFIG, (0x3b | rf_crc));//???????????;PWR_UP,EN_CRC,16BIT_CRC,???? 
    NRF24L01_Write_Reg(spiNum,NRF_WRITE_REG+DYNPD,dynpd);

    NRF24L01_Write_Reg(spiNum,NRF_WRITE_REG+FEATURF,feature);  
    NRF24L01_Write_Reg(spiNum,NRF_WRITE_REG+STATUS,0x70);       //??TX_DS?MAX_RT????
    NRF24L01_Write_Reg(spiNum,FLUSH_RX,0xff);   //??RX FIFO???  
}  


void NRF24L01_RX_TelPo_CONFIG1(SPIType spiNum)
{
	if(spiNum == SPI_PORT1){
		SPI1_CE =0;
	}else{
		SPI2_CE=0;	
	}	
        NRF24L01_TELPO_RX_Mode(spiNum,SCAN_ADDRESS,SCAN_RX_ADR_WIDTH,SCAN_RX_CHNL,
                         SCAN_SETUPVALUE,SCAN_RF_CRC,SCAN_RF_ENAA,
                         SCAN_RX_PLOAD_WIDTH,SCAN_DYNPD,SCAN_FEATURE); 
   	if(spiNum == SPI_PORT1){     //CE为高,进入接收模式
		SPI1_CE =1;
	}else{
		SPI2_CE=1;	
	}     
}	 
#endif
u8 NRF24L01_RxPacket1(SPIType spiNum,u8 *rxbuf,unsigned char rxLen)
{
  u8 sta;                  
    SPI_SetSpeed(spiNum,SPI_BaudRatePrescaler_16);
  //SPI_SetSpeed(spiNum,SPI_BaudRatePrescaler_8); //spi???9Mhz(24L01???SPI???10Mhz)   
  sta=NRF24L01_Read_Reg(spiNum,STATUS);  //?????????       
  
  if(sta&RX_OK)//?????
  {
      

    NRF24L01_Read_Buf(spiNum,RD_RX_PLOAD,rxbuf,rxLen);  //????
    NRF24L01_Write_Reg(spiNum,FLUSH_RX,0xff);  //??RX FIFO??? 
      NRF24L01_Write_Reg(spiNum,NRF_WRITE_REG+STATUS,sta); //??TX_DS?MAX_RT????  
    delay_5us(20);
    return 0; 
  }     
  return 1;//???????
}   


int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32f10x_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32f10x.c file
     */     
    //SCB->VTOR = FLASH_BASE | 0x10000; /* Vector Table Relocation in Internal FLASH. */

    RCC_Configuration();    //系统时钟设置
    
    NVIC_Configuration();   //中断向量配置
    
    IWDG_Init(4,625);   //(4*2^4)*625/40 ms = 1s 看门狗定时1s
    IWDG_Feed();
    
    TIM3_Int_Init(9,7199);
    
    led_init();             //LED IO配置
#if LCD
    lcd_init();             //LCD 配置
    AttenuatorConfig();     //衰减器配置
#endif
    
	USART_Configuration();  //串口1、3初始化配置  串口1波特率为115200 串口3波特率为4800
    
    USART2_Init(115200);    //串口2初始化 波特率为115200 Debug
    
    NRF24L01_Init();        //24L01 IO配置
    
    IWDG_Feed();
//    while(NRF24L01_Check(SPI_REV)){	    //检测NRF24L01 1是否存在
//		printf("The 2.4G Error!");
//	}
#if 1    
    while(NRF24L01_Check(SPI_SEND)){	    //检测NRF24L01 2是否存在
		printf("The 2.4G Error!");
	}
#endif    
    Data_Init();   //包数据初始化
    
    IWDG_Feed();
    led0=~led0;
    delay_ms(200);
    led0=~led0;
    
    DegugPrintf("123456",6);
    SendUSART2Str("\n");
                        
    IWDG_Feed();
#if 0	
while(1)
{	  
	  NRF24L01_RX_TelPo_CONFIG1(SPI_SEND);
	  while(1)
	  {	 
        u8 Rx_Buffer[32] = {0};
		
        if (!NRF24L01_RxPacket1(SPI_SEND,Rx_Buffer,sizeof(Rx_Buffer)))
        {
            break;
        }
		
		IWDG_Feed();        
	  }
	  IWDG_Feed(); 
}
#endif
	printf("\nPC对码软件通用版本V2.4-20190906\n");
//    SendUartData("123456",6,USART2);
//    printf("System Clock = %d\r\n",SystemCoreClock);

    NRF24L01_RX_Mode(SPI_SEND);
//    NRF24L01_RX_Mode_NOACK(SPI_SEND);
//while(1)
//{
//	 RF24_CarrierTest(SPI_SEND,32);
//	delay_ms(100);
//	 IWDG_Feed();
//}

 #if 1
    Readpara_from_flash();  //读出数据并打印出来
    protocol_config_flg = Save_Buffer[2*0];
	switch(protocol_config_flg)
	{
		case 0:
		{			
			printf("江西协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"JIANGXI",7);
#endif
			break;
		}
		case 1:
		{
			printf("天波协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"TELPO",5);
#endif
			break;
		}
		case 2:
		{
			printf("云南协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"YUNNAN",6);
#endif
			break;
		}
		case 3:
		{
			printf("贵州协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"GUIZHOU",7);
#endif
			break;
		}
		case 4:
		{
			printf("四川协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"SICHUAN",7);
#endif
			break;
		}
		case 5:
		{
			printf("内蒙古协议\r\n"); 
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"NEIMENGGU",9);
#endif
			break;
		}
		case 6:
		{
			printf("安徽协议\r\n"); 
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"ANHUI",5);
#endif
			break;
		}
		case 7:
		{
			printf("山西鑫诺协议\r\n"); 
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"SHANXI",6);
#endif
			break;
		}
		case 8:
		{
			printf("VCOM测试\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"VCOM",4);
#endif
			break;
		}
		case 9:
		{
			printf("辽宁电信\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"LIAONING.DIAN",13);
#endif
			break;
		}
		case 10:
		{
			printf("辽宁移动\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"LIAONING.YI",11);
#endif
			break;
		}
		case 11:
		{
			printf("Tp专用协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"TP",2);
#endif
			break;
		}
		case 12:
		{
			printf("内蒙古移动协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"NEIMENGGU.YI",12);
#endif
			break;
		}
		case 13:
		{
			printf("广西移动协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"GUANGXI.YI",10);
#endif
			break;
		}
		case 14:
		{
			printf("四川电信协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"SICHUN.DIAN",11);
#endif
			break;
		}
		case 15:
		{
			printf("福建真灼协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"FUJIANZHENZHUO",14);
#endif
			break;
		}
		case 16:
		{
			printf("苏州木兰协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"SUZHOUMULANG",10);
#endif
			break;
		}
		case 17:
		{
			printf("重庆移动协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"CHONGQIN.YI",11);
#endif
			break;
		}
		case 18:
		{
			printf("山西移动协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"SHANXI.YI",9);
#endif
			break;
		}
		case 19:
		{
			printf("甘肃移动协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"GANSU.YI",9);
#endif
			break;
		}
		case 20:
		{
			printf("信达丰协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"XDF",3);
#endif
			break;
		}
		case 21:
		{
			printf("德海协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"DH",2);
#endif
			break;
		}
		case 22:
		{
			printf("安徽电信协议\r\n");
#if LCD
			vDispClearLine(1);
			vDispStr(1,1,"AHDX",4);
#endif
			break;
		}		
	}
 #endif
	
#if 0
  NRF24L01_RX_TelPo_CONFIG1(SPI_SEND);
while(1)
{
   
        u8 Rx_Buffer[32] = {0};
        if (!NRF24L01_RxPacket(SPI_SEND,Rx_Buffer))
        {
            break;
        }
        
}	
	
#endif
	
	
	
	
  /* Infinite loop */
    //SendConsoleByte(protocol_config_flg);   //回显，返回给PC端
    //NRF24L01_RX_Mode_NOACK_VCOM(SPI_SEND);
    first_clear_flag = 1;
    delay_ms(50);
    while (1)
    {
        
//		while(1)   //
//        {                      
//            if(DataProc_A4_nrf())
//            break;
//        }
        DataProc_1356();        //13.56M数据处理
 #if LCD       
        DataProc_RecNrf24L01();
 #endif
        
        DataProc_USART1();      //串口1数据处理，与PC端软件通信
        
//        DataProc_Nrf24l01_SPI2();
    }
}



void RCC_Configuration(void)
{
#if 0
	ErrorStatus HSEStartUpStatus;                   //枚举变量，定义高速时钟的启动状态
	RCC_DeInit();                                   //RCC系统重置，用于Debug
	RCC_HSEConfig(RCC_HSE_ON);                      //使能高速时钟源HSE  
	HSEStartUpStatus = RCC_WaitForHSEStartUp();     //等待HSE稳定
	if(HSEStartUpStatus == SUCCESS)
	{	
		RCC_HCLKConfig(RCC_SYSCLK_Div1);            // HCLK = SYSCLK
		RCC_PCLK2Config(RCC_HCLK_Div1);             // PCLK2 = HCLK
		RCC_PCLK1Config(RCC_HCLK_Div2);             // PCLK1 = HCLK/2
		
		RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);
		RCC_PLLCmd(ENABLE);
		while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET){}
		
		RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
		while(RCC_GetSYSCLKSource() != 0x08){}
	}
	RCC_APB2PeriphClockCmd( RCC_APB2Periph_USART1 |RCC_APB2Periph_GPIOA |RCC_APB2Periph_AFIO |RCC_APB2Periph_GPIOB , ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
#else
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB |RCC_APB2Periph_AFIO | RCC_APB2Periph_USART1, ENABLE); 
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);

	/* Select AHB clock(HCLK) as SysTick clock source */
	SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK);

	/* SysTick interrupt each 10ms with HCLK equal to 72MHz */
	SysTick_Config(240000); 

#endif
}

void NVIC_Configuration(void)
{              
	NVIC_InitTypeDef NVIC_InitStructure;   
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);

	NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;           //设置串口2中断
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;   //抢占优先级1
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;          //子优先级2
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;             //使能中断
	NVIC_Init(&NVIC_InitStructure);
    
    NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;           //设置串口3中断
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;   //抢占优先级1
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;          //子优先级1
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;             //使能中断
	NVIC_Init(&NVIC_InitStructure);
    
    NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;           //设置串口1中断
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;   //抢占优先级0
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;          //子优先级1
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;             //使能中断
	NVIC_Init(&NVIC_InitStructure);
    
    NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;             //设置定时器3全局中断
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;   //抢占优先级0
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;          //子优先级为0
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;             //使能
	NVIC_Init(&NVIC_InitStructure);
    
}

/*
*看门狗初始化函数
*prer:分频数：0-7，低3位有效
*分频因子：4*2^prer，最大256
*rlr:重装载寄存器值，低11位有效
*Tout=((4*2^prer)*rlr)/40 (ms)
*/
void IWDG_Init(u8 prer,u16 rlr)
{
    IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable); // 使能对寄存器IWDG_PR和IWDG_RLR的操作
    IWDG_SetPrescaler(prer);    //设置IWDG预分频值:prer
    IWDG_SetReload(rlr);        //设置IWDG重载值
    IWDG_ReloadCounter();       //按照设置值，重载IWDG计数器
    IWDG_Enable();              //使能IWDG
}

/**
 * 喂狗
 */
void IWDG_Feed(void)
{
    IWDG_ReloadCounter();    /*reload*/
}

#ifdef  USE_FULL_ASSERT

/**
  * @brief  Reports the name of the source file and the source line number
  *   where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t* file, uint32_t line)
{ 
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif

/**
  * @}
  */


/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
