• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! Pseudo terminal example.
2 
3 #[cfg(unix)]
main()4 fn main() {
5     use std::io::{Read, Write};
6     use std::os::unix::prelude::*;
7     use std::str;
8     use std::thread;
9     use std::time;
10 
11     use serialport::{SerialPort, TTYPort};
12 
13     let (mut master, mut slave) = TTYPort::pair().expect("Unable to create pseudo-terminal pair");
14 
15     // Master ptty has no associated path on the filesystem.
16     println!(
17         "Master ptty fd: {}, path: {:?}",
18         master.as_raw_fd(),
19         master.name()
20     );
21     println!(
22         "Slave  ptty fd: {}, path: {:?}",
23         slave.as_raw_fd(),
24         slave.name()
25     );
26 
27     // Receive buffer.
28     let mut buf = [0u8; 512];
29 
30     println!("Sending 5 messages from master to slave.");
31 
32     // Send 5 messages.
33     for x in 1..6 {
34         let msg = format!("Message #{}", x);
35 
36         // Send the message on the master
37         assert_eq!(master.write(msg.as_bytes()).unwrap(), msg.len());
38 
39         // Receive on the slave
40         let bytes_recvd = slave.read(&mut buf).unwrap();
41         assert_eq!(bytes_recvd, msg.len());
42 
43         let msg_recvd = str::from_utf8(&buf[..bytes_recvd]).unwrap();
44         assert_eq!(msg_recvd, msg);
45 
46         println!("Slave Rx:  {}", msg_recvd);
47         thread::sleep(time::Duration::from_secs(1));
48     }
49 }
50 
51 #[cfg(not(unix))]
main()52 fn main() {}
53