/*
 * Copyright (c) 2019 Nordic Semiconductor ASA
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <zephyr.h>
#include <string.h>
#include <stdio.h>

#define UART_INTERFACE 0
#include <port/miniport/uart/nrf52840_uart.h>
#include <port/miniport/uart/generic_uart.h>


// per interface configuration
typedef struct nrf52840_uart_interface
{
	union
	{
		NRF_UART_Type * reg;
		NRF_UARTE_Type * reg_dma;
	};

	union
	{
		UART_PSEL_Type pin_select;
		UARTE_PSEL_Type pin_select_dma;
	};

	nrf52840_uart_state * state;
	fn_uart_abort abort;
	uint32_t baud_rate;
	uint16_t int_number;
	uint8_t use_int;
	uint8_t use_dma;
} nrf52840_uart_interface;

extern nrf52840_uart_interface nrf52840_uart_interfaces[];
int i;


void main(void)
{
#if 1
	//-nrf52840_uart_interfaces[UART_INTERFACE].use_int = 0;
	struct uart_api * uart = uart_open(UART_INTERFACE);

	if (!uart)
	{
		printk("uart_open  failed\n");

		return;
	}

	uart->config.int_priority = 4;

	// UART init code
	if (OK != uart->init(uart))
	{
		printk("uart->init  FAILED\n");
		return;
	}

#if 0
	char test[] = "*** UART test *** xxx xxx\r\n";
	char msg[256];
	int count = 0;
	int i = 0;
	UNUSED_PARAM(msg);
	UNUSED_PARAM(count);

	while (1)
	{
#if 0
		if (i == 5000)
		{
			test[0] = '+';
			IntDisable();
		}
		if (i == 10000)
		{
			test[0] = '*';
			IntEnable();
		}
		if (!((i + 1) % 2000))
		{
			TaskSleep(2 | SEC);
}
#endif

		test[18] = '0' + (i / 100000) % 10;
		test[19] = '0' + (i / 10000) % 10;
		test[20] = '0' + (i / 1000) % 10;
		test[22] = '0' + (i / 100) % 10;
		test[23] = '0' + (i / 10) % 10;
		test[24] = '0' + i % 10;
		i++;
		count = uart->send(uart, test, sizeof(test) - 1);

		if (count != (sizeof(test) - 1))
		{
			test[0] = '!';
		}
	}

#else
	char title[] = "\r\n\r\n*** UART test loopback ***\r\n\r\n";
	char msg[256];
	int fault = 0;
	int count_rx = 0;
	int count_tx = 0;
	UNUSED_PARAM(fault);

	count_tx = uart->send(uart, title, sizeof(title) - 1);

	while (1)
	{
		count_rx = uart->recv(uart, msg, sizeof(msg));
		count_tx = uart->send(uart, msg, count_rx);

		if (count_tx != count_rx)
		{
			fault = 1;
		}
	}
#endif

#endif

	printk("test\n");
}
