/* 
* classRs485.cpp
*
* Created: 10/02/2020 20:06:44
* Author: Ledo
*/


#include "classRs485.h"

// default constructor
classRs485::classRs485()
{
} //classRs485

// default destructor
classRs485::~classRs485()
{
} //~classRs485


/**
 * \brief Configure USART in normal (serial rs232) mode, asynchronous,
 * 8 bits, 1 stop bit, no parity, 38400 bauds and enable its transmitter
 * and receiver.
 */
void classRs485::configure_usart0(void)
{

	/* Enable the peripheral clock in the PMC. */
	sysclk_enable_peripheral_clock(ID_USART0);

	/* Configure USART in serial mode. */
	usart_init_rs232(USART0, &usart_console_settings,
			sysclk_get_peripheral_hz());

	/* Disable all the interrupts. */
	usart_disable_interrupt(USART0, 0xffffffff);

	/* Enable the receiver and transmitter. */
	usart_enable_tx(USART0);
	usart_enable_rx(USART0);

	/* Configure and enable interrupt of USART. */
	usart_enable_interrupt(USART0, US_IER_RXRDY);
	NVIC_EnableIRQ(USART0_IRQn);
}

/*********************************************************
* USART Send n Bytes
*********************************************************/
void classRs485::Usart0_sendBytes(uint8_t bytes)
{
	uint32_t status;
	for(int i=0;i<bytes;i++)
	{
		while (!(USART0->US_CSR & US_CSR_TXRDY))
		{
			;
		}

		USART0->US_THR = US_THR_TXCHR(rs4_txbuffer[i]);
		//delay_us(208);
	}
	
}

void classRs485::Rs4_transmit(void)
{
	Puerto.set_pin_high(PIOA, RS4_DE_PIN);
	Insert_check_sum(RS4_TXBUFFER_LENGHT);
	Usart0_sendBytes(RS4_TXBUFFER_LENGHT);
	rs4_rx_index = 0;
	while (!(USART0->US_CSR & US_CSR_TXEMPTY))
	{
		;
	}
	Puerto.set_pin_low(PIOA, RS4_DE_PIN);
}

void classRs485::Insert_check_sum(uint8_t bytes)
{
	uint16_t cksum = 0;
	for(int i=0;i<bytes -2;i++)
	cksum += rs4_txbuffer[i];
	rs4_txbuffer[bytes-2] = (unsigned char) (cksum % 256);
	rs4_txbuffer[bytes-1] = (unsigned char) (cksum >> 8);
	
}

bool classRs485::cksum(void)
{
	uint16_t sum = 0;
	for(int i=0;i<RS4_RXBUFFER_LENGHT-2;i++)
	sum += rs4_rxbuffer[i];
	if((sum % 256) != rs4_rxbuffer[RS4_RXBUFFER_LENGHT-2])
	return false;
	if((sum >> 8) == rs4_rxbuffer[RS4_RXBUFFER_LENGHT-1])
	return true;
	else
	return false;
}



