#include "main.h"
#include "ad0x0_usart.h"
#include <string.h>
//#include "stm8s_delay.h"
    
//#define ADQ_USART_TX_ENABLE 	USART1->CR1|= (USART_CR1_TE | USART_CR1_TCIE);
//#define ADQ_USART_EV_ENABLE 	I2C2->CR2 |= (I2C_CR2_ITEVTEN|I2C_CR2_ITBUFEN);

//void ad0x0_i2c_err_cb(void);
//struct ad0x0_i2c_cmd_s ad0x0_i2c_fifo[AD0X0_FIFO_COUNT];
//volatile struct ad0x0_i2c_cmd_s *ad0x0_pcurhwi=0,*ad0x0_pcurswi=0;
volatile u8 ad0x0_usart_rbuf[16],ad0x0_usart_rbuf_count=0;
volatile u8 ad0x0_usart_inint=0;
volatile u8 *ad0x0_usart_pbuf_cur,*ad0x0_usart_pbuf=0,ad0x0_usart_pbuf_counter=0,txstr=0;

bool	ad0x0_usart_isReady(void){
	return (!ad0x0_usart_pbuf_counter) && (!txstr);
}

void	ad0x0_usart_init(void){
	USART1->CR1=0;
	USART1->CR1|=USART_CR1_UE;	
	USART1->CR1|= (USART_CR1_RE | USART_CR1_RXNEIE);// | USART_CR1_TXEIE);
	USART1->CR1|= (USART_CR1_TE | USART_CR1_TCIE);
	memset((void*)ad0x0_usart_rbuf,0,ad0x0_usart_rbuf_count);
}

void	ad0x0_usart_txbuf(void *pbuf,int8_t bytes_count){
	if(!ad0x0_usart_isReady()){
		__asm("nop");
	}
	ad0x0_usart_pbuf=pbuf;
	ad0x0_usart_pbuf_cur=ad0x0_usart_pbuf;
	if(bytes_count>0)ad0x0_usart_pbuf_counter=bytes_count;else txstr=1;
	USART1->DR = *ad0x0_usart_pbuf_cur++;ad0x0_usart_pbuf_counter--;
}

void	ad0x0_usart_txstr(u8 *pstr){
	if(!ad0x0_usart_isReady()){
		__asm("nop");
	}
	ad0x0_usart_pbuf_cur=pstr;
	txstr=1;
	USART1->DR = *ad0x0_usart_pbuf_cur;
	if(!(*ad0x0_usart_pbuf_cur))txstr=0;
}

void 		ad0x0_usart_irq(void){
	u32 sr=USART1->SR;
	if(sr & USART_SR_RXNE){//получили
		//USART1->CR1|= (USART_CR1_TXEIE|USART_CR1_TCIE|USART_CR1_TE);
		uint8_t d = USART1->DR; // 
		ad0x0_usart_rbuf[ad0x0_usart_rbuf_count++]=d;
		if(ad0x0_usart_rbuf_count==16)ad0x0_usart_rbuf_count=0;
		USART1->DR = d; // 
	}
	if(sr & (USART_SR_TC)){//отправили
		__asm("nop");
		
		if(ad0x0_usart_pbuf_counter){
			USART1->DR = *ad0x0_usart_pbuf_cur++;ad0x0_usart_pbuf_counter--;
		}
		if(txstr){
			if(*ad0x0_usart_pbuf_cur){
				ad0x0_usart_pbuf_cur++;				
			}else txstr=0;
			USART1->DR = *ad0x0_usart_pbuf_cur;
		}
		USART1->SR&= ~USART_SR_TC;		
	}
	
}
