//*********************************************//
//   i-87120 for LinPAC series test program    //
//   with Send / Receive message               //
//                                             //
//*********************************************//


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "msw.h"
#include "I87KCAN.h"

typedef struct {
  unsigned char Mode;
  unsigned char RTR;
  unsigned char DataLen;
  unsigned char Data[8];
  unsigned long MsgID;
}PacketStruct;


int main(void)
{ 
  PacketStruct RxMsg;
  char Mode=1,RTR=0,DataLen=8,Data[8]={0x12,0x23,0x34,0x45,0x56,0x67,0x78,0x89};
  int Ret,i,cnt,SlotNo;
  long MsgID=0x12345678L;
  
  //Open COM 1
  Ret = Open_Slot(0);
  if (Ret > 0) {
    printf("open Slot failed!\n");
    return (-1);
  }
		
  Ret = Open_Com(COM1, 115200, Data8Bit, NonParity, OneStopBit);
  if (Ret > 0) {
    printf("open port failed!\n");
    return (-1);
  }
  
  //Select the slot where the I-87KCAN is plugged.
  printf("Input the slot (1~7) where the I-87KCAN is plugged: ");
  scanf("%d",&SlotNo);
  if (SlotNo<1 || SlotNo>7){
    printf("Slot number error, default to slot 1.\n");
    SlotNo=1;
  }
  printf("Baud is set to 1000K\n");
  ChangeToSlot(SlotNo);
  
  //Initiate the I-87KCAN module
  Ret=I87KCANInit(SlotNo,1000000L,0,0,0x00000000L,0xffffffffL,0,0);
  if (Ret){
    printf("Init error Code=%d\n",Ret);
    return (-1);	
  }
  printf("Start to send and receive CAN messages.\n");
  
  cnt = 10;
  while(cnt--){
    Ret=SendCANMsg(SlotNo,Mode,MsgID,RTR,DataLen,Data);
    if (Ret){
      printf("Send Message Error, Error Code=%d.\n",Ret);
      break;
    }
    sleep(1);
    
    Ret=GetCANMsg(SlotNo,&RxMsg.Mode,&RxMsg.MsgID,&RxMsg.RTR,&RxMsg.DataLen,RxMsg.Data);
    if (Ret){
      if (Ret!=CAN87K_FIFO_EMPTY){
      	printf("Receive Message Error, Error Code=%d.\n",Ret);
      	break;
      }	
    }
    else{
      if (RxMsg.RTR){
      	printf("%s,ID=%lx,RTR=%d,Dlen=%d\n",
               RxMsg.Mode?"2.0B":"2.0A",RxMsg.MsgID,RxMsg.RTR,RxMsg.DataLen);
      }
      else{
        printf("%s,ID=%lx,RTR=%d,Dlen=%d",
               RxMsg.Mode?"2.0B":"2.0A",RxMsg.MsgID,RxMsg.RTR,RxMsg.DataLen);
        if (RxMsg.DataLen>0){
          printf(",Data=");
          for (i=0;i<RxMsg.DataLen;i++){
            printf("%02X",RxMsg.Data[i]);
            if (i!=RxMsg.DataLen-1) printf(",");
          }
        }
        printf("\n");
      }
    }
  }   
    
  //Recover the COM 0 setting
  Close_Com(COM1);
  Close_SlotAll();
  printf("Exit Program.\n\r");
  return 0;
}