#include "serial.h"

#include "stm32f4xx_usart.h"

#include "tinystdio.h"

/** Data to track a serial device connection. */
struct SSerialDev {
    /** The file descriptor for the open serial device. */
    int fd;
};


bool serialRead(SerialDev *dev, uint8_t *buffer, size_t n) {
    while(n) {
    	size_t result = 0;
    	unsigned int retries = 0;

        while ((USART_GetFlagStatus(USARTn, USART_FLAG_RXNE) == RESET) &&
        		(retries++ < MAX_READ_RETRIES)) {
        }
        if(retries >= MAX_READ_RETRIES) {
        	printf("Read error\r\n");
        	return false;
        }

        *buffer = USART_ReceiveData(USARTn);
        //printf("Rx: 0x%X\r\n", *buffer);
        result++;

		buffer += result;
		n -= result;
    }

    return true;
}

bool serialWrite(SerialDev *dev, const uint8_t *buffer, size_t n) {
    while(n) {
       	size_t result = 0;

    	while(USART_GetFlagStatus(USARTn, USART_FLAG_TXE) == RESET)
    		;
    	USART_SendData(USARTn, *buffer);
    	//printf("Tx: 0x%X\r\n", *buffer);
		result++;

		buffer += result;
		n -= result;
    }

    return true;
}
