-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUartManager.h
106 lines (88 loc) · 2.31 KB
/
UartManager.h
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#pragma once
/* toolchain */
#include <cassert>
/* third-party */
#include "hardware/uart.h"
/* internal */
#include "common/buffer/FullDuplexBuffer.h"
#include "common/buffer/PcBuffer.h"
namespace Project81
{
template <size_t tx_depth, size_t rx_depth>
class UartManager : public FullDuplexBuffer<tx_depth, rx_depth>
{
using FdBuffer = FullDuplexBuffer<tx_depth, rx_depth>;
public:
UartManager(uart_inst_t *_uart, bool _echo = true,
bool _add_carriage_return = true)
: FdBuffer(), uart(_uart), echo(_echo),
add_carriage_return(_add_carriage_return)
{
}
void putc_block(uint8_t data)
{
switch (data)
{
case '\n':
/* If we should add carriage returns, add it first. */
if (add_carriage_return)
{
putc_block('\r');
}
break;
}
this->tx_buffer.push_blocking(data);
}
void flush(void)
{
this->tx_buffer.flush();
/* Wait for UART to be completely empty. */
uart_tx_wait_blocking(uart);
}
bool getc_nonblocking(uint8_t &data)
{
return this->rx_buffer.pop(data);
}
protected:
uart_inst_t *uart;
bool echo;
bool add_carriage_return;
void service_tx(FdBuffer::TxBuffer *buf)
{
uint8_t data;
while (uart_is_writable(uart) and !buf->empty())
{
assert(buf->pop(data));
uart_get_hw(uart)->dr = data;
}
}
void service_rx(FdBuffer::RxBuffer *buf)
{
uint8_t data;
while (uart_is_readable(uart) and !buf->full())
{
data = uart_getc(uart);
assert(buf->push(data));
if (echo)
{
switch (data)
{
case '\r':
putc_block('\n');
/*
* If carriage returns are getting added automatically,
* the '\n' put will already add one.
*/
if (add_carriage_return)
{
break;
}
[[fallthrough]];
default:
putc_block(data);
}
}
}
}
};
}; // namespace Project81