/*******************************************************************************
 *  emeter-communication.h -
 *
 *  Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ 
 *  ALL RIGHTS RESERVED
 * 
*/

/* We either start with a simple MAX_UART_PORT value, and map this to the
   individual enabled UARTs, or we start with the individual enabled UART
   defines, and work out the value of MAX_UART_PORT. */
#if !defined(MAX_UART_PORT)
    #if defined(UART_3_SUPPORT)
        #define MAX_UART_PORT 4
    #elif defined(UART_2_SUPPORT)
        #define MAX_UART_PORT 3
    #elif defined(UART_1_SUPPORT)
        #define MAX_UART_PORT 2
    #elif defined(UART_0_SUPPORT)
        #define MAX_UART_PORT 1
    #endif
#endif

#define MAX_SERIAL_MESSAGE_LEN      82

#if defined(UART_0_SUPPORT)  ||  defined(UART_1_SUPPORT)  ||  defined(UART_2_SUPPORT)  ||  defined(UART_3_SUPPORT)
    #define SERIAL_COMMS_SUPPORT 1
#endif
#if defined(UART_0_DLT645_SUPPORT)  ||  defined(UART_1_DLT645_SUPPORT)  ||  defined(UART_2_DLT645_SUPPORT)  ||  defined(UART_3_DLT645_SUPPORT)
    #define DLT645_SUPPORT 1
#endif
#if defined(UART_0_IEC62056_SUPPORT)  ||  defined(UART_1_IEC62056_SUPPORT)  ||  defined(UART_2_IEC62056_SUPPORT)  ||  defined(UART_3_IEC62056_SUPPORT)
    #define IEC62056_SUPPORT 1
    #define DLMS_SUPPORT 1
#endif

typedef union
{
    uint8_t uint8[MAX_SERIAL_MESSAGE_LEN];
    uint16_t uint16[MAX_SERIAL_MESSAGE_LEN >> 1];
} serial_msg_t;

/* Incoming or outgoing serial message buffer */
typedef struct
{
    serial_msg_t buf;
    uint8_t ptr;
    uint8_t len;
    uint8_t inter_char_timeout;
} serial_msg_buf_t;

struct uart_port_s
{
#if defined(COMMON_RX_TX_BUFFER_SUPPORT)
    union
    {
        serial_msg_buf_t tx_msg;
        serial_msg_buf_t rx_msg;
    };
#else
    serial_msg_buf_t tx_msg;
    serial_msg_buf_t rx_msg;
#endif
    int8_t tx_in_progress;
    int8_t rx_frame_pending;
};

extern struct uart_port_s ports[MAX_UART_PORT];


int serial_configure(int port, int mode, uint32_t bit_rate);

int serial_write(int port, const uint8_t buf[], int len);

int is_calibration_enabled(void);
