#include <stdio.h>
#include <ntcan.h>
#include <string.h>

#if __linux__ 
#include <unistd.h>
#endif

#if _WIN32 
#include <windows.h>
#endif 

/*
* This example demonstrates how the NTCAN-API can be used to open a handle,
* set a Classical CAN bitrate and transmit Classical CAN messages at a certain
* point of time in the future using the Timestamped TX feature with a
* non-blocking request. The example code acquires the current timestamp and
* starts transmission of 10 frames after 1000 ms with a time difference of 100
* ms between each frame. Finally all proper cleanup operations are performed
*/
void main()
{
    NTCAN_HANDLE m_hCan;
    uint64_t timestampFreq, timestamp;
    CMSG_T msgT[10];
    NTCAN_RESULT rc;
    int32_t len;
    int i;
    uint16_t can_id=0;

    /* Open CAN handle for net 0 */
    rc = canOpen(0, NTCAN_MODE_TIMESTAMPED_TX, 100, 100, 1000, 1000, &m_hCan);
    if (rc != NTCAN_SUCCESS) {
        printf("Opening handle failed with %d\n", rc);
        return;
    }
    /* Request timestamp/tick frequency of interface */
    rc = canIoctl(m_hCan, NTCAN_IOCTL_GET_TIMESTAMP_FREQ, &timestampFreq);
    if (rc != NTCAN_SUCCESS) {
        printf("Gathering timestamp frequency failed with %d\n", rc);
        (void)canClose(m_hCan);
        return;
    }
    /* Set baudrate to 1M Bit/s */
    rc = canSetBaudrate(m_hCan, NTCAN_BAUD_1000);
    if (rc != NTCAN_SUCCESS) {
        printf("Configuration CAN bit rate failed with %d\n", rc);
        (void)canClose(m_hCan);
        return;
    }
    /* Request timestamp/tick frequency of interface */
    rc = canIoctl(m_hCan, NTCAN_IOCTL_GET_TIMESTAMP, &timestamp);
    if (rc != NTCAN_SUCCESS) {
        printf("Gathering timestamp failed with %d\n", rc);
        (void)canClose(m_hCan);
        return;
    }
    // Start transmission in one second from now
    timestamp += timestampFreq;
    /*
    * Setup the Tx object with the given CAN-ID and initialize the message.
    */
    memset(msgT, 0, sizeof(msgT));
    len = sizeof(msgT) / sizeof(*msgT);
    for (i = 0; i < len; i++) {
        msgT[i].id = (int32_t)(can_id + i);
        msgT[i].len = NTCAN_DATASIZE_TO_DLC(8);
        msgT[i].timestamp = timestamp;
        strcpy((char *)msgT[i].data, "Hello !!");
        timestamp += timestampFreq / 10; /* Next transmission in 100 ms */
    }
    /*
    * Non-blocking call to schedule message transmission.
    */
    rc = canSendT(m_hCan, msgT, &len);
    if (rc != NTCAN_SUCCESS) {
        printf("canSendT() failed with %d\n", rc);
    }
    /*
    * NOTE: All frames which are not transmitted before the handle is closed
    * will be aborted !!!
    */
    // SLEEP(3000); /* OS specific delay for 3 seconds !!! */

#if __linux__ 
	sleep(5); /* OS specific delay for 5 seconds !!! */
#endif /* unix */

#if _WIN32 
	Sleep(5000); /* OS specific delay for 5 seconds !!! */
#endif 

    (void)canClose(m_hCan);
}