1 //! Duplex example
2 //!
3 //! This example tests the ability to clone a serial port. It works by creating
4 //! a new file descriptor, and therefore a new `SerialPort` object that's safe
5 //! to send to a new thread.
6 //!
7 //! This example selects the first port on the system, clones the port into a child
8 //! thread that writes data to the port every second. While this is running the parent
9 //! thread continually reads from the port.
10 //!
11 //! To test this, have a physical or virtual loopback device connected as the
12 //! only port in the system.
13
14 use std::io::Write;
15 use std::time::Duration;
16 use std::{io, thread};
17
main()18 fn main() {
19 // Open the first serialport available.
20 let port_name = &serialport::available_ports().expect("No serial port")[0].port_name;
21 let mut port = serialport::new(port_name, 9600)
22 .open()
23 .expect("Failed to open serial port");
24
25 // Clone the port
26 let mut clone = port.try_clone().expect("Failed to clone");
27
28 // Send out 4 bytes every second
29 thread::spawn(move || loop {
30 clone
31 .write_all(&[5, 6, 7, 8])
32 .expect("Failed to write to serial port");
33 thread::sleep(Duration::from_millis(1000));
34 });
35
36 // Read the four bytes back from the cloned port
37 let mut buffer: [u8; 1] = [0; 1];
38 loop {
39 match port.read(&mut buffer) {
40 Ok(bytes) => {
41 if bytes == 1 {
42 println!("Received: {:?}", buffer);
43 }
44 }
45 Err(ref e) if e.kind() == io::ErrorKind::TimedOut => (),
46 Err(e) => eprintln!("{:?}", e),
47 }
48 }
49 }
50