#include <zephyr.h>
#include <sys/printk.h>
#include <drivers/uart.h>

#define UART_DEV_NAME DT_LABEL(DT_NODELABEL(uart0))
#define UART_BUF_SIZE 64
#define UART_WAIT_FOR_RX 10
#define UART_WAIT_FOR_BUF_DELAY = 10

static K_MEM_SLAB_DEFINE(uart_slab, UART_BUF_SIZE, 3, 4);

static uint8_t uart_buf[UART_BUF_SIZE];
static void uart_cb(const struct device * uart, 
					struct uart_event * evt, 
					void * user_data)
{
	struct uart_data_event * event = user_data;
	int err;
	
	switch (evt->type) {
	case UART_RX_RDY:
		printk("Received data %d bytes\n", evt->data.rx.len);
		break;
	case UART_RX_BUF_REQUEST:
	{
		uint8_t *buf;

		err = k_mem_slab_alloc(&uart_slab, (void **)&buf, K_NO_WAIT);
		__ASSERT(err == 0, "Failed to allocate slab\n");

		err = uart_rx_buf_rsp(uart, buf, UART_BUF_SIZE);
		__ASSERT(err == 0, "Failed to provide new buffer\n");
		break;
	}
	case UART_RX_BUF_RELEASED:
		k_mem_slab_free(&uart_slab, (void **)&evt->data.rx_buf.buf);
		break;

	case UART_RX_DISABLED:
		break;

	case UART_RX_STOPPED:
		break;
	default:
		break;
	}
}

void main(void)
{
    printk("UART sample start\n");    
	
	

	const struct device *uart = device_get_binding(UART_DEV_NAME);
	if (!uart) {
		printk("Unable to get device binding\n");
	}
	

	int err = uart_callback_set(uart, uart_cb, NULL);
	if (err) {
		printk("uart_callback_set error: %d\n", err);
	}
	uart_rx_enable(uart, uart_buf, sizeof(uart_buf), 10);
	//while (1) {
	//	k_cpu_idle();
	//}
}