#ifndef __USART_H
#define __USART_H
#include "stdio.h"	
#include "includes.h" 

/*端口号*/
enum {
	UART1_ID = 0,
	UART2_ID = 1,
	UART3_ID = 2,
	UART4_ID = 3,
	UART5_ID = 4,

	UART_DEBUG = UART1_ID,
	UART_ME3616 = UART3_ID,
        UART_MAX = 5
};

#define RS485_UART USART2

#ifndef FALSE
#define FALSE			0
#endif
#ifndef TRUE
#define TRUE			1
#endif

#define UART_RCV_TEMPBUF_LEN	1024
#define UART_RCV_PROCBUF_LEN	1024

#define OTP_PACK_ALIGN(x) __attribute__((packed, aligned(x)))
typedef int (*uart_rcv_func)(u8 uartid, void *arg, u8 *pbuf, u16 len, u8 version);

/*定义串口处理的一些标志*/
typedef struct _uart_buf_flag
{
	u8 rsvd:7;
	u8 bufof:1;/*暂存表溢出*/
} OTP_PACK_ALIGN(1)uart_buf_flag;

/*暂存缓冲区*/
typedef struct _uart_rcv_tempbuf
{
	u16	pinput; 	/*接收缓冲输入的指针值*/
	u16	poutput;	/*接收缓冲输出的指针值*/
	u8	buf[UART_RCV_TEMPBUF_LEN];
}OTP_PACK_ALIGN(1)uart_rcv_tempbuf;

/*接收处理缓冲区*/
typedef struct _uart_rcv_procbuf
{
	u16	outcnt;		/*处理的字节数*/
	u16	pktlen;		/*协议报文的长度*/
	u16	datalen;	/*缓冲区的长度*/
	u8	pdata[UART_RCV_PROCBUF_LEN];		/*缓冲区指针*/
	uart_rcv_func	rcv;	/*接收报文处理函数*/
}OTP_PACK_ALIGN(1)uart_rcv_procbuf;

typedef struct _uart_rcv_info
{
	u32		rtime;	/*接收时间定义，记录上次字节接收时间*/
	uart_buf_flag   	flag;
	uart_rcv_tempbuf 	rtbuf;	/*暂存缓冲区信息*/
	uart_rcv_procbuf 	rproc;	/*报文处理缓冲区*/
	u16		errpkt;		/*接收错误报文计数*/
#ifdef INCLUDE_OPTTYPE
	uart_opttype_buf	opttype;
#endif	
}uart_rcv_info;

/*发送缓冲区*/
typedef struct _uart_send_info
{
	int		sending;	/*表示是否开始发送缓冲区数据*/
	u16 	pinput;		/*接收缓冲输入的指针值;范围0~datalen-1*/
	u16 	poutput;	/*接收缓冲输入的指针值;范围0~datalen-1*/
	u16		datalen;	/*缓冲区的长度*/
	u8		pdata[1024];		/*缓冲区指针*/
	uart_buf_flag   flag;
}uart_send_info;

typedef struct _uart_info
{
	uart_rcv_info 	rinfo;
	uart_send_info	sinfo;
	u8 		uartid;
	void	*arg;		/*自定义指针*/
}uart_info;

/*接口配置数据结构*/
typedef struct _uart_config_struct
{
	GPIO_TypeDef * rx_port;
	u16 rx_pin;
	
	GPIO_TypeDef * tx_port;
	u16 tx_pin;	
	
	u32	remap;
	u8 irq_no;
	USART_TypeDef * uart_def;
	u32 uart_clk;
	u32 gpio_clk;	
} uart_config_struct;

void uart_init(u8 uartid, u32 baud, u16 wordlen, u16 parity);
int uart_msg_send(u8 uartid, const char *buf, u32 buflen);
int uart_blocking_read(char *buffer, u8 uartid, u32 timeout);
int uart_rs232_init(u8 uartid, uart_rcv_func rcv);
int uart_rcv_process(u8 uartid);
extern int uart_blocking_read_len(char *buffer, u8 uartid);
#endif
