aboutsummaryrefslogtreecommitdiff
path: root/src/components/uart/simple_uart.c
blob: 1528a7044dec454027d32541c4082635354f1be6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdio.h>
#include <gran/uart/simple_uart.h>

struct simple_uart {
	struct component component;

	struct component *send;
	struct packet pkt;
	bool busy;
};

static stat simple_uart_clock(struct simple_uart *uart)
{
	if (!uart->busy)
		return OK;

	stat r = SEND(uart, uart->send, uart->pkt);
	if (r == EBUSY)
		return OK;

	uart->busy = false;
	return OK;
}

static stat simple_uart_receive(struct simple_uart *uart, struct component *from, struct packet pkt)
{
	if (uart->busy)
		return EBUSY;

	uart->busy = true;
	uart->send = from;
	uart->pkt = response(pkt);

	size_t size = packet_convsize(&pkt);
	if (size != 1) {
		set_flags(&uart->pkt, PACKET_ERROR);
		return OK;
	}

	putchar(packet_convu8(&pkt));
	set_flags(&uart->pkt, PACKET_DONE);
	return OK;
}

struct component *create_simple_uart()
{
	struct simple_uart *uart = calloc(1, sizeof(struct simple_uart));
	if (!uart)
		return NULL;

	uart->component.receive = (receive_callback)simple_uart_receive;
	uart->component.clock = (clock_callback)simple_uart_clock;
	return (struct component *)uart;
}