#include <stdio.h>
#include "ntcan.h"
#include <unistd.h>
/*
* This example demonstrates how the NTCAN-API can be used to open a handle,
* set a baudrate and transmitting a CAN frame.
* Finally all proper cleanup operations are performed
*/
int main()
{
  int net=0; /* logical net number (here: 0) */
  uint32_t mode=0; /* mode used for canOpen() */
  int32_t txqueuesize=8; /* size of transmit queue */
  int32_t rxqueuesize=8; /* size of receive queue */
  int32_t txtimeout=100; /* timeout for transmit operations in ms */
  int32_t rxtimeout=1000; /* timeout for receive operations in ms */
  NTCAN_HANDLE txhandle; /* can handle returned by canOpen() */
  NTCAN_RESULT retvalue; /* return values of NTCAN API calls */
  uint32_t baud=2; /* configured CAN baudrate (here: 500 kBit/s.) */
  CMSG cmsg[8]; /* can message buffer */
  int rtr=0; /* rtr bit */
  int i; /* loop counter */
  int32_t len; /* # of CAN messages */
/* ############################################################### */
  retvalue = canOpen(net,
                     mode,
                     txqueuesize,
                     rxqueuesize,
                     txtimeout,
                     rxtimeout,
                     &txhandle);

  if (retvalue != NTCAN_SUCCESS)
  {
    printf("canOpen() failed with error %d!\n", retvalue);
    return(-1);
  }

  printf("function canOpen() returned OK !\n");
/* ############################################################### */
  retvalue = canSetBaudrate(txhandle, baud);

  if (retvalue != 0)
  {
    printf("canSetBaudrate() failed with error %d!\n", retvalue);
    canClose(txhandle);
    return(-1);
  }

  printf("function canSetBaudrate() returned OK !\n");
/* ############################################################### */
//suppose you want to send a CAN msg with 29-bit ID (0x1f000606)
//cmsg[0].id=0x3f000606;
  cmsg[0].id=0x1f000606 | NTCAN_20B_BASE;
  cmsg[0].len=0x08; 
  cmsg[0].data[0]=0x2f;
  cmsg[0].data[1]=0x50;
  cmsg[0].data[2]=0x22;
  cmsg[0].data[3]=0x01;  
  cmsg[0].data[4]=0xff;  
  cmsg[0].data[5]=0x00;
  cmsg[0].data[6]=0x00;
  cmsg[0].data[7]=0x00;
  len=1; /* Number of valid messages in cmsg buffer*/
  retvalue = canWrite(txhandle, &cmsg[0], &len, NULL);
  if (retvalue != NTCAN_SUCCESS)
    printf("canWrite failed() with error %d!\n", retvalue);
  else
    printf("function canWrite() returned OK !\n");
/* ############################################################### */
  retvalue = canClose (txhandle);
  if (retvalue != NTCAN_SUCCESS)
    printf("canClose failed with error %d!\n", retvalue);
  else
    printf("canClose() returned OK !\n");
/* ############################################################### */
  return(0);
}
