// ***********************************************************************
// USART - HEADER
// ***********************************************************************

#ifndef USART_H_
#define USART_H_

// ______________________ C o n s t a n t s___________________ //

#define ENABLED				1
#define DISABLED			0

// USART Transmitter buffer
#define TX_BUFFER_SIZE      16

//USART Receiver buffer
#define RX_BUFFER_SIZE      16

// Must be synchronized with Li_Balancer program !!!
typedef enum t_rxCmds 
{//	0			    1			   2				 3					 4
	CMD_SET_SW_OFF, CMD_SET_SW_ON, CMD_READ_SW_DROP, CMD_READ_SW_STATUS, CMD_ENUM_COUNT
} t_rxCmds;

typedef enum t_rxBufPos {
	BUF_POS_ADDR, BUF_POS_DATALEN, BUF_POS_CMD, BUF_POS_ARGL, BUF_POS_ARGH,  BUF_POS_CRCL, BUF_POS_CRCH, BUF_POS_TRASH, BUF_POS_ENUM_COUNT
} t_rxBufPos;

typedef enum t_rxFlgs {
	USART_FLG_NO_DATA, USART_FLG_RX_COMPLETED, USART_FLG_ENUM_COUNT
} t_rxFlgs;

// ______________________ C o n t r o l_______________________ //

#define USART_TIMOUT_START()	TCB0_CTRLA |= TCB_ENABLE_bm
#define USART_TIMOUT_STOP()		TCB0_CTRLA &= ~TCB_ENABLE_bm
#define USART_TIMOUT_RST()		TCB0_CNT = 0
#define USART_TIMOUT_FLG_CLR()	TCB0_INTFLAGS |= (TCB_CAPT_bm)

#define USART_MPCM_ON()			USART0_CTRLB |= USART_MPCM_bm
#define USART_MPCM_OFF()		USART0_CTRLB &= ~USART_MPCM_bm

#define USART_DREI_ON()			USART0_CTRLA |= USART_DREIE_bm
#define USART_DREI_OFF()		USART0_CTRLA &= ~USART_DREIE_bm

#define USART_TX(val)			USART0_TXDATAH = 0, USART0_TXDATAL = val

#define USART_RX_ADDR			( USART0_RXDATAH & 1 )
#define USART_RX_FLAGS			( USART0_RXDATAH & (USART_BUFOVF_bm | USART_FERR_bm | USART_PERR_bm) )
#define USART_RX_DATA			USART0_RXDATAL

// _________________________ I N I T _________________________ //

// Communication speed 19200 Bd
// Asynchronous Mode, No Parity, 1 Stop bit, 9-bit frame (High byte first)
// Open Drain Mode, Enable Rx, Tx, Normal Rx Mode, Multiprocessor mode
// Interrupt on RX Complete, Tx Data Register Empty, Rx and Tx internally connected
#define USART_INIT()			USART0_BAUD = 2083, \
								USART0_CTRLC = (USART_CMODE_ASYNCHRONOUS_gc | USART_SBMODE_1BIT_gc | USART_CHSIZE_9BITH_gc), \
								USART0_CTRLB = (USART_RXEN_bm | USART_TXEN_bm | USART_ODME_bm | USART_RXMODE_NORMAL_gc | USART_MPCM_bm), \
								USART0_CTRLA = (USART_RXCIE_bm | USART_LBME_bm)
								
// Timer period 800 us
// Timeout Mode
// Clock from TCA = 10 MHz / 16. Check before import to another program.
// Interrupt enable
#define USART_TIMOUT_TIM_INIT()	TCB0_CCMP = 500, \
								TCB0_CTRLB = TCB_CNTMODE_INT_gc, \
								TCB0_CTRLA = TCB_CLKSEL_CLKTCA_gc, \
								TCB0_INTCTRL = TCB_CAPT_bm

/*_____ D E C L A R A T I O N ______________________________________________*/

extern uint8_t device_id;

extern uint8_t tx_buffer[];
extern uint8_t rx_buffer[];
extern t_rxFlgs rx_flags;
extern uint8_t repeater;

extern void usart_txStart( uint8_t );

#endif /* USART_H_ */