-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuart_impl.h
79 lines (58 loc) · 1.44 KB
/
uart_impl.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
#pragma once
#include <cstdint>
#include <mutex>
#include <utility>
#include "uart_api.h"
namespace UART
{
class Impl
{
UART_ID _id;
UartConfig _cfg;
bool initialised = false;
public:
mutable std::mutex mutx{};
Impl() = delete;
Impl(UART_ID uart_id, UartConfig uart_config)
: _id{uart_id}, _cfg{uart_config}
{
initialised = init();
}
~Impl()
{
if (initialised)
deinit();
}
bool init()
{
std::scoped_lock lock(mutx);
return api_uart_init();
}
bool deinit()
{
std::scoped_lock lock(mutx);
return api_uart_deinit();
}
template <class T>
bool send(std::span<const T> data)
{
const uint16_t len = data.size_bytes() <= UINT16_MAX ?
static_cast<uint16_t>(data.size_bytes()) : 0;
if (not len)
return false;
std::scoped_lock lock(mutx);
return api_uart_send(_id, reinterpret_cast<const uint8_t*>(data.data()), len);
}
template <class T>
bool receive(std::span<T> data)
{
uint16_t len = std::min(data.size_bytes(), UINT16_MAX);
if (not len)
return false;
std::scoped_lock lock(mutx);
return api_uart_receive(_id, reinterpret_cast<uint8_t*>(data.data()), &len);
}
UART_ID id() const { return _id; }
UartConfig config() const { return _cfg; }
};
} // namespace UART