aboutsummaryrefslogtreecommitdiff
path: root/examples/std/src/serial_port.rs
diff options
context:
space:
mode:
authorDario Nieuwenhuis <[email protected]>2021-06-02 01:30:07 +0200
committerDario Nieuwenhuis <[email protected]>2021-06-02 01:32:19 +0200
commitdff03ecfc74d6af716637888338ebfa99ab7a027 (patch)
treec06bf2b0a2e6657c3427c956dbd27a4e45211aaa /examples/std/src/serial_port.rs
parenta0c5f7137fe0c45b8db0aad2a116aea91e6a93f7 (diff)
Move examples to a subdirectory
Diffstat (limited to 'examples/std/src/serial_port.rs')
-rw-r--r--examples/std/src/serial_port.rs71
1 files changed, 71 insertions, 0 deletions
diff --git a/examples/std/src/serial_port.rs b/examples/std/src/serial_port.rs
new file mode 100644
index 000000000..7ac1b1edb
--- /dev/null
+++ b/examples/std/src/serial_port.rs
@@ -0,0 +1,71 @@
1use nix::fcntl::OFlag;
2use nix::sys::termios;
3use nix::Error;
4use std::io;
5use std::os::unix::io::{AsRawFd, RawFd};
6
7pub struct SerialPort {
8 fd: RawFd,
9}
10
11impl SerialPort {
12 pub fn new<'a, P: ?Sized + nix::NixPath>(
13 path: &P,
14 baudrate: termios::BaudRate,
15 ) -> io::Result<Self> {
16 let fd = nix::fcntl::open(
17 path,
18 OFlag::O_RDWR | OFlag::O_NOCTTY | OFlag::O_NONBLOCK,
19 nix::sys::stat::Mode::empty(),
20 )
21 .map_err(to_io_error)?;
22
23 let mut cfg = termios::tcgetattr(fd).map_err(to_io_error)?;
24 cfg.input_flags = termios::InputFlags::empty();
25 cfg.output_flags = termios::OutputFlags::empty();
26 cfg.control_flags = termios::ControlFlags::empty();
27 cfg.local_flags = termios::LocalFlags::empty();
28 termios::cfmakeraw(&mut cfg);
29 cfg.input_flags |= termios::InputFlags::IGNBRK;
30 cfg.control_flags |= termios::ControlFlags::CREAD;
31 //cfg.control_flags |= termios::ControlFlags::CRTSCTS;
32 termios::cfsetospeed(&mut cfg, baudrate).map_err(to_io_error)?;
33 termios::cfsetispeed(&mut cfg, baudrate).map_err(to_io_error)?;
34 termios::cfsetspeed(&mut cfg, baudrate).map_err(to_io_error)?;
35 // Set VMIN = 1 to block until at least one character is received.
36 cfg.control_chars[termios::SpecialCharacterIndices::VMIN as usize] = 1;
37 termios::tcsetattr(fd, termios::SetArg::TCSANOW, &cfg).map_err(to_io_error)?;
38 termios::tcflush(fd, termios::FlushArg::TCIOFLUSH).map_err(to_io_error)?;
39
40 Ok(Self { fd })
41 }
42}
43
44impl AsRawFd for SerialPort {
45 fn as_raw_fd(&self) -> RawFd {
46 self.fd
47 }
48}
49
50impl io::Read for SerialPort {
51 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
52 nix::unistd::read(self.fd, buf).map_err(to_io_error)
53 }
54}
55
56impl io::Write for SerialPort {
57 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
58 nix::unistd::write(self.fd, buf).map_err(to_io_error)
59 }
60
61 fn flush(&mut self) -> io::Result<()> {
62 Ok(())
63 }
64}
65
66fn to_io_error(e: Error) -> io::Error {
67 match e {
68 Error::Sys(errno) => errno.into(),
69 e => io::Error::new(io::ErrorKind::InvalidInput, e),
70 }
71}