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
use core::convert::TryInto;
use crate::{
bindings,
error::{Error, SentinelError},
smart_port::{smart_port_type, DeviceType},
};
pub struct Serial(u8);
impl Serial {
pub unsafe fn new(port: u8, baudrate: i32) -> Result<Self, Error> {
bindings::serial_enable(port).check()?;
while smart_port_type(port) != DeviceType::Serial {}
bindings::serial_set_baudrate(port, baudrate).check()?;
Ok(Self(port))
}
#[inline]
pub fn set_baudrate(&mut self, baudrate: i32) -> Result<(), Error> {
unsafe { bindings::serial_set_baudrate(self.0, baudrate) }.check()?;
Ok(())
}
#[inline]
pub fn get_read_avail(&self) -> Result<usize, Error> {
Ok(unsafe { bindings::serial_get_read_avail(self.0) }
.check()?
.try_into()?)
}
#[inline]
pub fn get_write_free(&self) -> Result<usize, Error> {
Ok(unsafe { bindings::serial_get_write_free(self.0) }
.check()?
.try_into()?)
}
#[inline]
pub fn peek_byte(&self) -> Result<u8, Error> {
Ok(unsafe { bindings::serial_peek_byte(self.0) }
.check()?
.try_into()?)
}
#[inline]
pub fn read_byte(&mut self) -> Result<u8, Error> {
Ok(unsafe { bindings::serial_read_byte(self.0) }
.check()?
.try_into()?)
}
#[inline]
pub fn write_byte(&mut self, byte: u8) -> Result<(), Error> {
unsafe { bindings::serial_write_byte(self.0, byte) }.check()?;
Ok(())
}
#[inline]
pub fn read(&mut self, buffer: &mut [u8]) -> Result<usize, Error> {
Ok(
unsafe { bindings::serial_read(self.0, buffer.as_mut_ptr(), buffer.len().try_into()?) }
.check()?
.try_into()?,
)
}
#[inline]
pub fn write(&mut self, buffer: &[u8]) -> Result<usize, Error> {
Ok(unsafe {
bindings::serial_write(self.0, buffer.as_ptr() as *mut _, buffer.len().try_into()?)
}
.check()?
.try_into()?)
}
#[inline]
pub fn flush(&mut self) -> Result<(), Error> {
unsafe { bindings::serial_flush(self.0) }.check()?;
Ok(())
}
}