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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use crate::{
hw::mcu::kinetis::peripheral::uart::{Uart, UartRx, UartTx},
io,
task::WakerSet,
};
use core::{
future::{poll_fn, Future},
task::Poll,
};
#[derive(Debug)]
#[non_exhaustive]
pub enum SerialError {
NotEnabled,
PinInUse,
PortInUse,
UartInUse,
SimInUse,
}
pub struct Serial<M, T, R, const N: usize>(
pub(crate) Option<Uart<M, T, R, N>>,
pub(crate) Option<&'static WakerSet>,
);
impl<M, T, R, const N: usize> io::Read for Serial<M, T, R, N>
where
M: 'static,
T: 'static,
R: UartRx<M, N> + 'static,
{
type Error = SerialError;
type Future<'a> = impl Future<Output = Result<usize, Self::Error>> + 'a;
fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Self::Future<'a> {
poll_fn(move |ctx| {
if buf.len() == 0 {
return Poll::Ready(Ok(0));
}
let mut count = 0;
let uart = self.0.as_mut().ok_or(SerialError::NotEnabled)?;
while let Some(byte) = uart.read_data() {
buf[count] = byte;
count += 1;
if count >= buf.len() {
break;
}
}
if count > 0 {
Poll::Ready(Ok(count))
} else {
if let Some(wakers) = self.1.as_ref() {
wakers.add(ctx.waker().clone());
}
uart.enable_rx_intr();
Poll::Pending
}
})
}
}
impl<M, T, R, const N: usize> io::Write for Serial<M, T, R, N>
where
M: 'static,
T: UartTx<M, N> + 'static,
R: 'static,
{
type Error = SerialError;
type Future<'a> = impl Future<Output = Result<usize, Self::Error>> + 'a;
type FlushFuture<'a> = impl Future<Output = Result<(), Self::Error>> + 'a;
fn write<'a>(&'a mut self, buf: &'a [u8]) -> Self::Future<'a> {
poll_fn(move |ctx| {
if buf.len() == 0 {
return Poll::Ready(Ok(0));
}
let mut count = 0;
let mut buf = buf;
let uart = self.0.as_mut().ok_or(SerialError::NotEnabled)?;
while let Some(_) = uart.write_data(buf[0]) {
count += 1;
buf = &buf[1..];
if buf.len() == 0 {
break;
}
}
if count > 0 {
Poll::Ready(Ok(count))
} else {
if let Some(wakers) = self.1.as_ref() {
wakers.add(ctx.waker().clone());
}
uart.enable_tx_intr();
Poll::Pending
}
})
}
fn flush<'a>(&'a mut self) -> Self::FlushFuture<'a> {
poll_fn(move |ctx| {
let uart = self.0.as_mut().ok_or(SerialError::NotEnabled)?;
if uart.is_transmit_complete() {
Poll::Ready(Ok(()))
} else {
if let Some(wakers) = self.1.as_ref() {
wakers.add(ctx.waker().clone());
}
uart.enable_complete_intr();
Poll::Pending
}
})
}
}
impl<M, T, R, const N: usize> Serial<M, T, R, N> {
pub const fn new() -> Self {
Self(None, None)
}
}