/****************************************************************************
* 文 件 名: main.c
* 描    述: 读写RFID
****************************************************************************/
//如果使用彩屏，请定义此宏
//#define OLED_1331


#include <ioCC2530.h>
#include <string.h>
#include "mfrc522.h"

#ifdef OLED_1331
#include "LCD1331.h"
#else
#include "LCD.h"
typedef unsigned char uchar;
typedef unsigned int  uint;
#endif


typedef unsigned char uint8;
typedef unsigned long ulong;


#define ON 0
#define OFF 1
#define LED1 P1_0 //定义P1.0口为LED1控制端
#define LED2 P1_1 //定义P1.1口为LED2控制端
#define LED3 P1_4 //定义P1.4口为LED3控制端

#define BUZZER_PIN  P0_7   //蜂鸣器控制脚


#define KEY1  0x01
#define KEY2  0x02

//M1卡的某一块写为如下格式，则该块为钱包，可接收扣款和充值命令
//4字节金额（低字节在前）＋4字节金额取反＋4字节金额＋1字节块地址＋1字节块地址取反＋1字节块地址＋1字节块地址取反 
unsigned char data2[4]  = {0x12,0,0,0};
unsigned char DefaultKey[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; 
unsigned char g_ucTempbuf[20];    
unsigned char MLastSelectedSnr[4];
unsigned char RevBuffer[30];  
unsigned char SerBuffer[20]; 
unsigned char CmdValid; 
unsigned char waitCommData=1;
int data_len=0;
int data_index=0;

/****************************************************************************
* 名    称: InitLed()
* 功    能: 设置LED灯相应的IO口
* 入口参数: 无
* 出口参数: 无
****************************************************************************/
void InitLed(void)
{
  P1DIR |= 0x13; //P1.0、P1.1、p1.4定义为输出
  LED1 = 1; //默认LED灯为熄灭状态
  LED2 = 1;
  LED3 = 1;
  
  P0_7=1;
}

void InitUart0(void)
{
    PERCFG  &= ~ 0x01;           //外设控制寄存器 USART 0的IO位置:0为P0口位置1 
    P0SEL = 0x0c;            //P0_2,P0_3用作串口（外设功能）
    P2DIR &= ~0xC0;          //P0优先作为UART0
    
    U0CSR |= 0x80;           //设置为UART方式
    U0GCR |= 11;				       
    U0BAUD |= 216;           //波特率设为115200

    UTX0IF = 0;              //UART0 TX中断标志初始置位0
    U0CSR |= 0x40;           //允许接收 
    IEN0 |= 0x84;            //开总中断允许接收中断  
}


/****************************************************************************
* 名    称: UART0_ISR(void) 串口中断处理函数 
* 描    述: 当串口0产生接收中断，将收到的数据保存在RxBuf中
****************************************************************************/
#pragma vector = URX0_VECTOR 
__interrupt void UART0_ISR(void) 
{
  unsigned char bbb=U0DBUF;
  
  URX0IF=0;
  if(waitCommData>0)
  {
    waitCommData=0;
    data_len=U0DBUF;
    data_index=0;
    memset(RevBuffer, 0, sizeof(RevBuffer));
  }
  else
  {
    RevBuffer[data_index]=U0DBUF;
    data_index++;
    
    if(data_len==data_index)
    {
      U0CSR &= ~0x40;                    //禁止接收 
      CmdValid=1;      
      waitCommData=1;
      U0CSR |= 0x40;
    }
  }
}


void Uart0SendString(char *Data, int len)
{
  uint i;
  for(i=0; i<len; i++)
  {
    U0DBUF = *Data++;
    while(UTX0IF == 0);
    UTX0IF = 0;
  }
}


void InitClockTo32M(void)
{   
  CLKCONCMD &= ~0x40;              //设置系统时钟源为 32MHZ晶振
  while(CLKCONSTA & 0x40);         //等待晶振稳定 
  CLKCONCMD &= ~0x47;              //设置系统主时钟频率为 32MHZ
}

void iccardcode()
{	     
  unsigned char cmd;
  unsigned char status;
  
  cmd = RevBuffer[0];
  switch(cmd)
  {
    case 1:     // Halt the card     //终止卡的操作
      status= PcdHalt();;			
      RevBuffer[0]=1;
      RevBuffer[1]=status;
      break;			
    case 2:     // Request,Anticoll,Select,return CardType(2 bytes)+CardSerialNo(4 bytes)
                // 寻卡，防冲突，选择卡    返回卡类型（2 bytes）+ 卡系列号(4 bytes)
      status= PcdRequest(RevBuffer[1],&RevBuffer[2]);
      if(status!=0)
      {
              status= PcdRequest(RevBuffer[1],&RevBuffer[2]);
              if(status!=0)				
              {
                      RevBuffer[0]=1;	
                      RevBuffer[1]=status;
                      break;
              }
      }  
      RevBuffer[0]=3;	
      RevBuffer[1]=status;
      break;
            
    case 3:                         // 防冲突 读卡的系列号 MLastSelectedSnr
      status = PcdAnticoll(&RevBuffer[2]);
      if(status!=0)
      {
              RevBuffer[0]=1;	
              RevBuffer[1]=status;
              break;
      }
      memcpy(MLastSelectedSnr,&RevBuffer[2],4);
      RevBuffer[0]=5;
      RevBuffer[1]=status;
      break;	
    case 4:		                    // 选择卡 Select Card
      status=PcdSelect(MLastSelectedSnr);
      if(status!=MI_OK)
      {
        RevBuffer[0]=1;	
        RevBuffer[1]=status;
        break;
      }
      RevBuffer[0]=3;
      RevBuffer[1]=status;			
      break;
    case 5:	    // Key loading into the MF RC500's EEPROM
      status = PcdAuthState(RevBuffer[1], RevBuffer[3], DefaultKey, MLastSelectedSnr);// 校验卡密码
      RevBuffer[0]=1;
      RevBuffer[1]=status;			
      break;							
    case 6: 
      RevBuffer[0]=1;
      RevBuffer[1]=status;			
      break;				
    case 7:     
      RevBuffer[0]=1;
      RevBuffer[1]=status;			
      break;
    case 8:     // Read the mifare card
                // 读卡
      status=PcdRead(RevBuffer[1],&RevBuffer[2]);
      if(status==0)
      {RevBuffer[0]=17;}
      else
      {RevBuffer[0]=1;}
      RevBuffer[1]=status;			
      break;
    case 9:     // Write the mifare card
                // 写卡  下载密码
      status=PcdWrite(RevBuffer[1],&RevBuffer[2]);
      RevBuffer[0]=1;
      RevBuffer[1]=status;			
      break;
    case 10:
      PcdValue(RevBuffer[1],RevBuffer[2],&RevBuffer[3]);
      RevBuffer[0]=1;	
      RevBuffer[1]=status;
      break;
    case 12:    // 参数设置
      PcdBakValue(RevBuffer[1], RevBuffer[2]);
      RevBuffer[0]=1;	//contact
      RevBuffer[1]=0;
      break;		
  }
}


/////////////////////////////////////////////////////////////////////
//系统初始化
/////////////////////////////////////////////////////////////////////
void InitializeSystem()
{
  //P0_4、P0_5、P0_6、p1_0和p1_1用于控制RFID
  //P0_7用于控制蜂鸣器  

  P0DIR |= 0xF0; //P0_4、P0_5、P0_6、P0_7定义为输出
  P1DIR |= 0x03;//p1_0、p1_1输出
  
  P0 |= 0xF0; //P0_4、P0_5、P0_6、P0_7输出1
  P1 |= 0x03; //P1_0输出高电平

  //MISO 即P06为输入
  P0DIR &=~ 0x40;
  P0_6=0;
  
  
  CmdValid=0; 
  
  PcdReset();
  DelayMS(10);
  PcdAntennaOff(); 
  DelayMS(10);
  PcdAntennaOn();  
  DelayMS(10);
  M500PcdConfigISOType( 'A' );
  
  delay_10ms(10);
  LED2=OFF;
  delay_10ms(10);
}

//BCD码转成ASC码
char NumberToLetter(unsigned char number)
{
  char buff[]="0123456789ABCDEF";

  if(number>15) return 0;

  return buff[number];

}
//蜂鸣器响两声
void buzzerOn()
{
      P0_7=0;

}
void buzzerOff()
{
      P0_7=1;

}

void main(void)
{
  uint8 SendBuf[10]={0};
  uint8 error=0;    

  InitLed();
  InitializeSystem();
  InitClockTo32M();
  InitUart0();
  LCD_Init();
  LCD_P6x8Str(20, 0, "SZ_YY RFID");

  //周期地在寻卡
  while (1)
  {
    //寻卡命令
    RevBuffer[0]=0x02;
    RevBuffer[1]=0x26;

     // 寻卡
    iccardcode();
    
    error=0;
    if(RevBuffer[1]==0)//寻卡成功
    {
      //读卡命令
      SendBuf[0]=RevBuffer[2];  //data
      SendBuf[1]=RevBuffer[3];  //data        

      //找到卡
      //读卡
      RevBuffer[0]=0x03;
      iccardcode();

      if(RevBuffer[1]==0)
      {
        //读卡成功
        //记录卡ID
        SendBuf[2]=RevBuffer[2];  //data
        SendBuf[3]=RevBuffer[3];  //data
        SendBuf[4]=RevBuffer[4];  //data
        SendBuf[5]=RevBuffer[5];  //data
      }
      else
      {
        error=1;
      }
    }
    else
    {
      error=1;
    }        

    if(error==0)
    {
      char card_buff[20]={0};
      
      //各种卡的含义
      //                0x4400 = Mifare_UltraLight
      //                0x0400 = Mifare_One(S50)
      //                0x0200 = Mifare_One(S70)
      //                0x0800 = Mifare_Pro(X)
      //                0x4403 = Mifare_DESFire
  
      if(SendBuf[0]==0x44 && SendBuf[1]==0x00)
      {
          LCD_P6x8Str(0, 2, "Mifare_UltraLight");
          Uart0SendString((uint8 *)"Mifare_UltraLight", strlen("Mifare_UltraLight"));
      }
      else if(SendBuf[0]==0x04 && SendBuf[1]==0x00)
      {
          LCD_P6x8Str(0, 2, "Mifare_One(S50)");
          Uart0SendString((uint8 *)"Mifare_One(S50)", strlen("Mifare_One(S50)"));
      }
      else if(SendBuf[0]==0x02 && SendBuf[1]==0x00)
      {
          LCD_P6x8Str(0, 2, "Mifare_One(S70)");
          Uart0SendString((uint8 *)"Mifare_One(S70)", strlen("Mifare_One(S70)"));
      }
      else if(SendBuf[0]==0x08 && SendBuf[1]==0x00)
      {
          LCD_P6x8Str(0, 2, "Mifare_One(X)");
          Uart0SendString((uint8 *)"Mifare_One(X)", strlen("Mifare_One(X)"));
      }
      else if(SendBuf[0]==0x44 && SendBuf[1]==0x03)
      {
          LCD_P6x8Str(0, 2, "Mifare_DESFire");
          Uart0SendString((uint8 *)"Mifare_DESFire", strlen("Mifare_DESFire"));
      }
      else
      {
          error=1;
          LCD_P6x8Str(0, 2, "");
          LCD_P6x8Str(0, 4, "");
          Uart0SendString((uint8 *)"find error", strlen("find error"));
      }
      Uart0SendString((uint8 *)"\r\n", 2);
  
  
      
      card_buff[0]='I';
      card_buff[1]='D';
      card_buff[2]=':';
      
      //BCD转ASC码
      //ID轮换
      for(int i=0; i<4; i++)
      {
          unsigned char temp= SendBuf[2+i];
          card_buff[3+i*2]=NumberToLetter((temp>>4)&0x0f);
          card_buff[3+i*2+1]=NumberToLetter(temp&0x0f);
      }
      //card_buff[ID:345678910]
      //LCD显示ID
      LCD_P6x8Str(0, 4,card_buff);

      //串口输出ID
      Uart0SendString(card_buff, strlen(card_buff));
      Uart0SendString((uint8 *)"\r\n", 2);
      if(card_buff[3]=='C' && card_buff[4]=='1' && card_buff[5]=='2')buzzerOff();
      else buzzerOn();
    }
    else
    {
      //寻不到卡
      LCD_P6x8Str(0, 2,"                ");
      LCD_P6x8Str(0, 4,"                ");
      buzzerOff();
    }
    
    DelayMS(500);
  }    
}
