serial-core-0.4.0/Cargo.toml01006440000765000002400000001776131260451060014100 0ustar0000000000000000# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "serial-core" version = "0.4.0" authors = ["David Cuddeback "] description = "Rust abstractions for serial ports." homepage = "https://github.com/dcuddeback/serial-rs" documentation = "https://dcuddeback.github.io/serial-rs/serial-core/" readme = "README.md" keywords = ["serial", "hardware", "system", "RS232"] categories = ["hardware-support"] license = "MIT" repository = "https://github.com/dcuddeback/serial-rs" [dependencies.libc] version = "0.2" serial-core-0.4.0/Cargo.toml.orig01006440000765000002400000000752131260451060015030 0ustar0000000000000000[package] name = "serial-core" version = "0.4.0" authors = ["David Cuddeback "] description = "Rust abstractions for serial ports." homepage = "https://github.com/dcuddeback/serial-rs" repository = "https://github.com/dcuddeback/serial-rs" documentation = "https://dcuddeback.github.io/serial-rs/serial-core/" license = "MIT" readme = "README.md" keywords = ["serial", "hardware", "system", "RS232"] categories = ["hardware-support"] [dependencies] libc = "0.2" serial-core-0.4.0/LICENSE01006440000765000002400000002043127073112130013140 0ustar0000000000000000Copyright (c) 2015 David Cuddeback Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. serial-core-0.4.0/README.md01006440000765000002400000015516131260451060013424 0ustar0000000000000000# Serial Core The `serial-core` crate provides abstract types used to interface with and implement serial ports. They can be used to write code that functions generically over all serial port types and to implement new serial port types that work with generic code. * [Documentation](http://dcuddeback.github.io/serial-rs/serial_core/) ## Usage Add `serial-core` as a dependency in `Cargo.toml`: ```toml [dependencies] serial-core = "0.4" ``` ### Interfacing with an Open Serial Port Import the `serial-core` crate and everything from the `serial_core::prelude` module. The traits in the `serial_core::prelude` module are useful to have in scope to resolve trait methods when working with serial ports, and they are unlikely to conflict with other crates. ```rust extern crate serial_core as serial; use std::io; use std::time::Duration; use std::io::prelude::*; use serial::prelude::*; ``` #### Configuration and I/O Interfacing with a serial port is done through the `SerialPort`, `std::io::Read`, and `std::io::Write` traits, which provide methods for configuration, I/O, and control signals. ```rust fn probe(port: &mut P) -> io::Result<()> { let mut buf: Vec = (0..255).collect(); // configuration try!(port.reconfigure(&|settings| { try!(settings.set_baud_rate(serial::Baud9600)); settings.set_char_size(serial::Bits8); settings.set_parity(serial::ParityNone); settings.set_stop_bits(serial::Stop1); settings.set_flow_control(serial::FlowNone); Ok(()) })); // I/O try!(port.set_timeout(Duration::from_millis(100))); try!(port.write(&buf[..])); try!(port.read(&mut buf[..])); // control signals try!(port.set_dtr(true)); try!(port.read_dsr()); Ok(()) } ``` For details on using an open serial port, refer to the documentation for the [`SerialPort` trait](http://dcuddeback.github.io/serial-rs/serial-core/trait.SerialPort.html). #### Taking Ownership of a Serial Port Often times, you'll want to implement a higher-level protocol over a serial port, in which case you'll probably want a handle object that owns the serial port and provides an interface specific to the higher-level protocol. To implement a handle for generic serial ports without requiring a proliferation of generics, one can define the higher-level protocol in a trait: ```rust struct Handle { port: P, } impl Handle

{ fn new(port: P) -> Self { Handle { port: port } } } impl Greet for Handle

{ fn get_name(&mut self) -> serial::Result { let mut name = String::new(); try!(self.port.write("What is your name? ")); try!(self.port.read_to_string(&mut name)); Ok(name) } fn say_hello(&mut self, name: &String) -> serial::Result<()> { try!(writeln!(&mut self.port, "Hello, {}!", name)); Ok(()) } } fn greet(greeter: &mut Greet) -> serial::Result<()> { let name = try!(greeter.get_name()); greeter.say_hello(name) } ``` Note that in the above example, the `greet()` function can interact with the `Handle` struct via the `Greet` trait without caring what type of `SerialPort` it's talking to. Alternatively, since `SerialPort` is object-safe, it can be boxed inside of the handle. However, this approach may introduce an extra pointer indirection: ```rust struct Handle { port: Box, } impl Handle { fn new(port: P) -> Self { Handle { port: Box::new(port) } } fn get_name(&mut self) -> serial::Result { // ... } fn say_hello(&mut self, name: &String) -> serial::Result<()> { // ... } } ``` ### Implementing a Custom Serial Port The serial port crates are designed to be extensible, allowing third parties to define custom serial port types. Reasons for implementing a custom serial port type may include bridging a serial port to a TCP socket or other I/O device, providing a fake implementation for testing, or integrating with custom hardware. To define a custom serial port type, start by importing the `serial_core` crate: ```rust extern crate serial_core as serial; use std::io; use std::time::Duration; ``` Next, define a type that will implement the new serial port and optionally a type for its settings: ```rust struct CustomSerialPort { // ... } struct CustomSerialPortSettings { // ... } ``` Implement [`SerialDevice`](http://dcuddeback.github.io/serial-rs/serial-core/trait.SerialDevice.html), `std::io::Read`, and `std::io::Write` for the new serial port type: ```rust impl serial::SerialDevice for CustomSerialPort { type Settings = CustomSerialPortSettings; fn read_settings(&self) -> serial::Result { ... } fn write_settings(&mut self, settings: &Self::Settings) -> serial::Result<()> { ... } fn timeout(&self) -> Duration { ... } fn set_timeout(&mut self, timeout: Duration) -> serial::Result<()> { ... } fn set_rts(&mut self, level: bool) -> serial::Result<()> { ... } fn set_dtr(&mut self, level: bool) -> serial::Result<()> { ... } fn read_cts(&mut self) -> serial::Result { ... } fn read_dsr(&mut self) -> serial::Result { ... } fn read_ri(&mut self) -> serial::Result { ... } fn read_cd(&mut self) -> serial::Result { ... } } impl io::Read for CustomSerialPort { fn read(&mut self, buf: &mut [u8]) -> io::Result { ... } } impl io::Write for CustomSerialPort { fn write(&mut self, buf: &[u8]) -> io::Result { ... } fn flush(&mut self) -> io::Result<()> { ... } } ``` If a custom settings type is not needed, then the [`PortSettings` struct](http://dcuddeback.github.io/serial-rs/serial-core/struct.PortSettings.html) can be used for the `SerialDevice::Settings` associated type. Otherwise, the `Settings` type must implement [`SerialPortSettings`](http://dcuddeback.github.io/serial-rs/serial-core/trait.SerialPortSettings.html): ```rust impl serial::SerialPortSettings for CustomSerialPortSettings { fn baud_rate(&self) -> Option { ... } fn char_size(&self) -> Option { ... } fn parity(&self) -> Option { ... } fn stop_bits(&self) -> Option { ... } fn flow_control(&self) -> Option { ... } fn set_baud_rate(&mut self, baud_rate: BaudRate) -> serial::Result<()> { ... } fn set_char_size(&mut self, char_size: CharSize) { ... } fn set_parity(&mut self, parity: Parity) { ... } fn set_stop_bits(&mut self, stop_bits: StopBits) { ... } fn set_flow_control(&mut self, flow_control: FlowControl) { ... } } ``` For details on implementing a new serial port type, refer to the documentation for the [`SerialDevice` trait](http://dcuddeback.github.io/serial-rs/serial-core/trait.SerialDevice.html). ## License Copyright © 2015 David Cuddeback Distributed under the [MIT License](LICENSE). serial-core-0.4.0/src/lib.rs01006440000765000002400000064706131260451060014055 0ustar0000000000000000use std::error::Error as StdError; use std::fmt; use std::io; use std::time::Duration; pub use BaudRate::*; pub use CharSize::*; pub use Parity::*; pub use StopBits::*; pub use FlowControl::*; /// A module that exports traits that are useful to have in scope. /// /// It is intended to be glob imported: /// /// ```no_run /// use serial_core::prelude::*; /// ``` pub mod prelude { pub use {SerialPort, SerialPortSettings}; } /// A type for results generated by interacting with serial ports. /// /// The `Err` type is hard-wired to [`serial_core::Error`](struct.Error.html). pub type Result = std::result::Result; /// Categories of errors that can occur when interacting with serial ports. /// /// This list is intended to grow over time and it is not recommended to exhaustively match against /// it. #[derive(Debug,Clone,Copy,PartialEq,Eq)] pub enum ErrorKind { /// The device is not available. /// /// This could indicate that the device is in use by another process or was disconnected while /// performing I/O. NoDevice, /// A parameter was incorrect. InvalidInput, /// An I/O error occured. /// /// The type of I/O error is determined by the inner `io::ErrorKind`. Io(io::ErrorKind), } /// An error type for serial port operations. #[derive(Debug)] pub struct Error { kind: ErrorKind, description: String, } impl Error { pub fn new>(kind: ErrorKind, description: T) -> Self { Error { kind: kind, description: description.into(), } } /// Returns the corresponding `ErrorKind` for this error. pub fn kind(&self) -> ErrorKind { self.kind } } impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> std::result::Result<(), fmt::Error> { fmt.write_str(&self.description) } } impl StdError for Error { fn description(&self) -> &str { &self.description } } impl From for Error { fn from(io_error: io::Error) -> Error { Error::new(ErrorKind::Io(io_error.kind()), format!("{}", io_error)) } } impl From for io::Error { fn from(error: Error) -> io::Error { let kind = match error.kind { ErrorKind::NoDevice => io::ErrorKind::NotFound, ErrorKind::InvalidInput => io::ErrorKind::InvalidInput, ErrorKind::Io(kind) => kind, }; io::Error::new(kind, error.description) } } /// Serial port baud rates. /// /// ## Portability /// /// The `BaudRate` variants with numeric suffixes, e.g., `Baud9600`, indicate standard baud rates /// that are widely-supported on many systems. While non-standard baud rates can be set with /// `BaudOther`, their behavior is system-dependent. Some systems may not support arbitrary baud /// rates. Using the standard baud rates is more likely to result in portable applications. #[derive(Debug,Copy,Clone,PartialEq,Eq)] pub enum BaudRate { /// 110 baud. Baud110, /// 300 baud. Baud300, /// 600 baud. Baud600, /// 1200 baud. Baud1200, /// 2400 baud. Baud2400, /// 4800 baud. Baud4800, /// 9600 baud. Baud9600, /// 19,200 baud. Baud19200, /// 38,400 baud. Baud38400, /// 57,600 baud. Baud57600, /// 115,200 baud. Baud115200, /// Non-standard baud rates. /// /// `BaudOther` can be used to set non-standard baud rates by setting its member to be the /// desired baud rate. /// /// ```no_run /// serial_core::BaudOther(4_000_000); // 4,000,000 baud /// ``` /// /// Non-standard baud rates may not be supported on all systems. BaudOther(usize), } impl BaudRate { /// Creates a `BaudRate` for a particular speed. /// /// This function can be used to select a `BaudRate` variant from an integer containing the /// desired baud rate. /// /// ## Example /// /// ``` /// # use serial_core::BaudRate; /// assert_eq!(BaudRate::Baud9600, BaudRate::from_speed(9600)); /// assert_eq!(BaudRate::Baud115200, BaudRate::from_speed(115200)); /// assert_eq!(BaudRate::BaudOther(4000000), BaudRate::from_speed(4000000)); /// ``` pub fn from_speed(speed: usize) -> BaudRate { match speed { 110 => BaudRate::Baud110, 300 => BaudRate::Baud300, 600 => BaudRate::Baud600, 1200 => BaudRate::Baud1200, 2400 => BaudRate::Baud2400, 4800 => BaudRate::Baud4800, 9600 => BaudRate::Baud9600, 19200 => BaudRate::Baud19200, 38400 => BaudRate::Baud38400, 57600 => BaudRate::Baud57600, 115200 => BaudRate::Baud115200, n => BaudRate::BaudOther(n), } } /// Returns the baud rate as an integer. /// /// ## Example /// /// ``` /// # use serial_core::BaudRate; /// assert_eq!(9600, BaudRate::Baud9600.speed()); /// assert_eq!(115200, BaudRate::Baud115200.speed()); /// assert_eq!(4000000, BaudRate::BaudOther(4000000).speed()); /// ``` pub fn speed(&self) -> usize { match *self { BaudRate::Baud110 => 110, BaudRate::Baud300 => 300, BaudRate::Baud600 => 600, BaudRate::Baud1200 => 1200, BaudRate::Baud2400 => 2400, BaudRate::Baud4800 => 4800, BaudRate::Baud9600 => 9600, BaudRate::Baud19200 => 19200, BaudRate::Baud38400 => 38400, BaudRate::Baud57600 => 57600, BaudRate::Baud115200 => 115200, BaudRate::BaudOther(n) => n, } } } /// Number of bits per character. #[derive(Debug,Copy,Clone,PartialEq,Eq)] pub enum CharSize { /// 5 bits per character. Bits5, /// 6 bits per character. Bits6, /// 7 bits per character. Bits7, /// 8 bits per character. Bits8, } /// Parity checking modes. /// /// When parity checking is enabled (`ParityOdd` or `ParityEven`) an extra bit is transmitted with /// each character. The value of the parity bit is arranged so that the number of 1 bits in the /// character (including the parity bit) is an even number (`ParityEven`) or an odd number /// (`ParityOdd`). /// /// Parity checking is disabled by setting `ParityNone`, in which case parity bits are not /// transmitted. #[derive(Debug,Copy,Clone,PartialEq,Eq)] pub enum Parity { /// No parity bit. ParityNone, /// Parity bit sets odd number of 1 bits. ParityOdd, /// Parity bit sets even number of 1 bits. ParityEven, } /// Number of stop bits. /// /// Stop bits are transmitted after every character. #[derive(Debug,Copy,Clone,PartialEq,Eq)] pub enum StopBits { /// One stop bit. Stop1, /// Two stop bits. Stop2, } /// Flow control modes. #[derive(Debug,Copy,Clone,PartialEq,Eq)] pub enum FlowControl { /// No flow control. FlowNone, /// Flow control using XON/XOFF bytes. FlowSoftware, /// Flow control using RTS/CTS signals. FlowHardware, } /// A trait for implementing serial devices. /// /// This trait is meant to be used to implement new serial port devices. To use a serial port /// device, the [`SerialPort`](trait.SerialPort.html) trait should be used instead. Any type that /// implements the `SerialDevice` trait will automatically implement the `SerialPort` trait as /// well. /// /// To implement a new serial port device, it's necessary to define a type that can manipulate the /// serial port device's settings (baud rate, parity mode, etc). This type is defined by the /// `Settings` associated type. The current settings should be determined by reading from the /// hardware or operating system for every call to `read_settings()`. The settings can then be /// manipulated in memory before being commited to the device with `write_settings()`. /// /// Types that implement `SerialDevice` must also implement `std::io::Read` and `std::io::Write`. /// The `read()` and `write()` operations of these traits should honor the timeout that has been /// set with the most recent successful call to `set_timeout()`. This timeout value should also be /// accessible by calling the `timeout()` method. /// /// A serial port device should also provide access to some basic control signals: RTS, DTR, CTS, /// DSR, RI, and CD. The values for the control signals are represented as boolean values, with /// `true` indicating the the control signal is active. /// /// Lastly, types that implement `SerialDevice` should release any acquired resources when dropped. pub trait SerialDevice: io::Read + io::Write { /// A type that implements the settings for the serial port device. /// /// The `Settings` type is used to retrieve and modify the serial port's settings. This type /// should own any native structures used to manipulate the device's settings, but it should /// not cause any changes in the underlying hardware until written to the device with /// `write_settings()`. type Settings: SerialPortSettings; /// Returns the device's current settings. /// /// This function attempts to read the current settings from the hardware. The hardware's /// current settings may not match the settings that were most recently written to the hardware /// with `write_settings()`. /// /// ## Errors /// /// This function returns an error if the settings could not be read from the underlying /// hardware: /// /// * `NoDevice` if the device was disconnected. /// * `Io` for any other type of I/O error. fn read_settings(&self) -> ::Result; /// Applies new settings to the serial device. /// /// This function attempts to apply all settings to the serial device. Some settings may not be /// supported by the underlying hardware, in which case the result is dependent on the /// implementation. A successful return value does not guarantee that all settings were /// appliied successfully. To check which settings were applied by a successful write, /// applications should use the `read_settings()` method to obtain the latest configuration /// state from the device. /// /// ## Errors /// /// This function returns an error if the settings could not be applied to the underlying /// hardware: /// /// * `NoDevice` if the device was disconnected. /// * `InvalidInput` if a setting is not compatible with the underlying hardware. /// * `Io` for any other type of I/O error. fn write_settings(&mut self, settings: &Self::Settings) -> ::Result<()>; /// Returns the current timeout. fn timeout(&self) -> Duration; /// Sets the timeout for future I/O operations. fn set_timeout(&mut self, timeout: Duration) -> ::Result<()>; /// Sets the state of the RTS (Request To Send) control signal. /// /// Setting a value of `true` asserts the RTS control signal. `false` clears the signal. /// /// ## Errors /// /// This function returns an error if the RTS control signal could not be set to the desired /// state on the underlying hardware: /// /// * `NoDevice` if the device was disconnected. /// * `Io` for any other type of I/O error. fn set_rts(&mut self, level: bool) -> ::Result<()>; /// Sets the state of the DTR (Data Terminal Ready) control signal. /// /// Setting a value of `true` asserts the DTR control signal. `false` clears the signal. /// /// ## Errors /// /// This function returns an error if the DTR control signal could not be set to the desired /// state on the underlying hardware: /// /// * `NoDevice` if the device was disconnected. /// * `Io` for any other type of I/O error. fn set_dtr(&mut self, level: bool) -> ::Result<()>; /// Reads the state of the CTS (Clear To Send) control signal. /// /// This function returns a boolean that indicates whether the CTS control signal is asserted. /// /// ## Errors /// /// This function returns an error if the state of the CTS control signal could not be read /// from the underlying hardware: /// /// * `NoDevice` if the device was disconnected. /// * `Io` for any other type of I/O error. fn read_cts(&mut self) -> ::Result; /// Reads the state of the DSR (Data Set Ready) control signal. /// /// This function returns a boolean that indicates whether the DSR control signal is asserted. /// /// ## Errors /// /// This function returns an error if the state of the DSR control signal could not be read /// from the underlying hardware: /// /// * `NoDevice` if the device was disconnected. /// * `Io` for any other type of I/O error. fn read_dsr(&mut self) -> ::Result; /// Reads the state of the RI (Ring Indicator) control signal. /// /// This function returns a boolean that indicates whether the RI control signal is asserted. /// /// ## Errors /// /// This function returns an error if the state of the RI control signal could not be read from /// the underlying hardware: /// /// * `NoDevice` if the device was disconnected. /// * `Io` for any other type of I/O error. fn read_ri(&mut self) -> ::Result; /// Reads the state of the CD (Carrier Detect) control signal. /// /// This function returns a boolean that indicates whether the CD control signal is asserted. /// /// ## Errors /// /// This function returns an error if the state of the CD control signal could not be read from /// the underlying hardware: /// /// * `NoDevice` if the device was disconnected. /// * `Io` for any other type of I/O error. fn read_cd(&mut self) -> ::Result; } /// A trait for serial port devices. /// /// Serial port input and output is implemented through the `std::io::Read` and `std::io::Write` /// traits. A timeout can be set with the `set_timeout()` method and applies to all subsequent I/O /// operations. /// /// The `SerialPort` trait exposes several common control signals. Each control signal is /// represented as a boolean, where `true` indicates that the signal is asserted. /// /// The serial port will be closed when the value is dropped. pub trait SerialPort: io::Read + io::Write { /// Returns the current timeout. fn timeout(&self) -> Duration; /// Sets the timeout for future I/O operations. fn set_timeout(&mut self, timeout: Duration) -> ::Result<()>; /// Configures a serial port device. /// /// ## Errors /// /// This function returns an error if the settings could not be applied to the underlying /// hardware: /// /// * `NoDevice` if the device was disconnected. /// * `InvalidInput` if a setting is not compatible with the underlying hardware. /// * `Io` for any other type of I/O error. fn configure(&mut self, settings: &PortSettings) -> ::Result<()>; /// Alter the serial port's configuration. /// /// This method expects a function, which takes a mutable reference to the serial port's /// configuration settings. The serial port's current settings, read from the device, are /// yielded to the provided function. After the function returns, any changes made to the /// settings object will be written back to the device. /// /// ## Errors /// /// This function returns an error if the `setup` function returns an error or if there was an /// error while reading or writing the device's configuration settings: /// /// * `NoDevice` if the device was disconnected. /// * `InvalidInput` if a setting is not compatible with the underlying hardware. /// * `Io` for any other type of I/O error. /// * Any error returned by the `setup` function. /// /// ## Example /// /// The following is a function that toggles a serial port's settings between one and two stop /// bits: /// /// ```no_run /// use std::io; /// use serial_core::prelude::*; /// /// fn toggle_stop_bits(port: &mut T) -> serial_core::Result<()> { /// port.reconfigure(&|settings| { /// let stop_bits = match settings.stop_bits() { /// Some(serial_core::Stop1) => serial_core::Stop2, /// Some(serial_core::Stop2) | None => serial_core::Stop1, /// }; /// /// settings.set_stop_bits(stop_bits); /// Ok(()) /// }) /// } /// ``` fn reconfigure(&mut self, setup: &Fn(&mut SerialPortSettings) -> ::Result<()>) -> ::Result<()>; /// Sets the state of the RTS (Request To Send) control signal. /// /// Setting a value of `true` asserts the RTS control signal. `false` clears the signal. /// /// ## Errors /// /// This function returns an error if the RTS control signal could not be set to the desired /// state on the underlying hardware: /// /// * `NoDevice` if the device was disconnected. /// * `Io` for any other type of I/O error. fn set_rts(&mut self, level: bool) -> ::Result<()>; /// Sets the state of the DTR (Data Terminal Ready) control signal. /// /// Setting a value of `true` asserts the DTR control signal. `false` clears the signal. /// /// ## Errors /// /// This function returns an error if the DTR control signal could not be set to the desired /// state on the underlying hardware: /// /// * `NoDevice` if the device was disconnected. /// * `Io` for any other type of I/O error. fn set_dtr(&mut self, level: bool) -> ::Result<()>; /// Reads the state of the CTS (Clear To Send) control signal. /// /// This function returns a boolean that indicates whether the CTS control signal is asserted. /// /// ## Errors /// /// This function returns an error if the state of the CTS control signal could not be read /// from the underlying hardware: /// /// * `NoDevice` if the device was disconnected. /// * `Io` for any other type of I/O error. fn read_cts(&mut self) -> ::Result; /// Reads the state of the DSR (Data Set Ready) control signal. /// /// This function returns a boolean that indicates whether the DSR control signal is asserted. /// /// ## Errors /// /// This function returns an error if the state of the DSR control signal could not be read /// from the underlying hardware: /// /// * `NoDevice` if the device was disconnected. /// * `Io` for any other type of I/O error. fn read_dsr(&mut self) -> ::Result; /// Reads the state of the RI (Ring Indicator) control signal. /// /// This function returns a boolean that indicates whether the RI control signal is asserted. /// /// ## Errors /// /// This function returns an error if the state of the RI control signal could not be read from /// the underlying hardware: /// /// * `NoDevice` if the device was disconnected. /// * `Io` for any other type of I/O error. fn read_ri(&mut self) -> ::Result; /// Reads the state of the CD (Carrier Detect) control signal. /// /// This function returns a boolean that indicates whether the CD control signal is asserted. /// /// ## Errors /// /// This function returns an error if the state of the CD control signal could not be read from /// the underlying hardware: /// /// * `NoDevice` if the device was disconnected. /// * `Io` for any other type of I/O error. fn read_cd(&mut self) -> ::Result; } impl SerialPort for T where T: SerialDevice { fn timeout(&self) -> Duration { T::timeout(self) } fn set_timeout(&mut self, timeout: Duration) -> ::Result<()> { T::set_timeout(self, timeout) } fn configure(&mut self, settings: &PortSettings) -> ::Result<()> { let mut device_settings = try!(T::read_settings(self)); try!(device_settings.set_baud_rate(settings.baud_rate)); device_settings.set_char_size(settings.char_size); device_settings.set_parity(settings.parity); device_settings.set_stop_bits(settings.stop_bits); device_settings.set_flow_control(settings.flow_control); T::write_settings(self, &device_settings) } fn reconfigure(&mut self, setup: &Fn(&mut SerialPortSettings) -> ::Result<()>) -> ::Result<()> { let mut device_settings = try!(T::read_settings(self)); try!(setup(&mut device_settings)); T::write_settings(self, &device_settings) } fn set_rts(&mut self, level: bool) -> ::Result<()> { T::set_rts(self, level) } fn set_dtr(&mut self, level: bool) -> ::Result<()> { T::set_dtr(self, level) } fn read_cts(&mut self) -> ::Result { T::read_cts(self) } fn read_dsr(&mut self) -> ::Result { T::read_dsr(self) } fn read_ri(&mut self) -> ::Result { T::read_ri(self) } fn read_cd(&mut self) -> ::Result { T::read_cd(self) } } /// A trait for objects that implement serial port configurations. pub trait SerialPortSettings { /// Returns the current baud rate. /// /// This function returns `None` if the baud rate could not be determined. This may occur if /// the hardware is in an uninitialized state. Setting a baud rate with `set_baud_rate()` /// should initialize the baud rate to a supported value. fn baud_rate(&self) -> Option; /// Returns the character size. /// /// This function returns `None` if the character size could not be determined. This may occur /// if the hardware is in an uninitialized state or is using a non-standard character size. /// Setting a baud rate with `set_char_size()` should initialize the character size to a /// supported value. fn char_size(&self) -> Option; /// Returns the parity-checking mode. /// /// This function returns `None` if the parity mode could not be determined. This may occur if /// the hardware is in an uninitialized state or is using a non-standard parity mode. Setting /// a parity mode with `set_parity()` should initialize the parity mode to a supported value. fn parity(&self) -> Option; /// Returns the number of stop bits. /// /// This function returns `None` if the number of stop bits could not be determined. This may /// occur if the hardware is in an uninitialized state or is using an unsupported stop bit /// configuration. Setting the number of stop bits with `set_stop-bits()` should initialize the /// stop bits to a supported value. fn stop_bits(&self) -> Option; /// Returns the flow control mode. /// /// This function returns `None` if the flow control mode could not be determined. This may /// occur if the hardware is in an uninitialized state or is using an unsupported flow control /// mode. Setting a flow control mode with `set_flow_control()` should initialize the flow /// control mode to a supported value. fn flow_control(&self) -> Option; /// Sets the baud rate. /// /// ## Errors /// /// If the implementation does not support the requested baud rate, this function may return an /// `InvalidInput` error. Even if the baud rate is accepted by `set_baud_rate()`, it may not be /// supported by the underlying hardware. fn set_baud_rate(&mut self, baud_rate: BaudRate) -> ::Result<()>; /// Sets the character size. fn set_char_size(&mut self, char_size: CharSize); /// Sets the parity-checking mode. fn set_parity(&mut self, parity: Parity); /// Sets the number of stop bits. fn set_stop_bits(&mut self, stop_bits: StopBits); /// Sets the flow control mode. fn set_flow_control(&mut self, flow_control: FlowControl); } /// A device-indepenent implementation of serial port settings. #[derive(Debug,Copy,Clone,PartialEq,Eq)] pub struct PortSettings { /// Baud rate. pub baud_rate: BaudRate, /// Character size. pub char_size: CharSize, /// Parity checking mode. pub parity: Parity, /// Number of stop bits. pub stop_bits: StopBits, /// Flow control mode. pub flow_control: FlowControl, } impl SerialPortSettings for PortSettings { fn baud_rate(&self) -> Option { Some(self.baud_rate) } fn char_size(&self) -> Option { Some(self.char_size) } fn parity(&self) -> Option { Some(self.parity) } fn stop_bits(&self) -> Option { Some(self.stop_bits) } fn flow_control(&self) -> Option { Some(self.flow_control) } fn set_baud_rate(&mut self, baud_rate: BaudRate) -> ::Result<()> { self.baud_rate = baud_rate; Ok(()) } fn set_char_size(&mut self, char_size: CharSize) { self.char_size = char_size; } fn set_parity(&mut self, parity: Parity) { self.parity = parity; } fn set_stop_bits(&mut self, stop_bits: StopBits) { self.stop_bits = stop_bits; } fn set_flow_control(&mut self, flow_control: FlowControl) { self.flow_control = flow_control; } } #[cfg(test)] mod tests { use super::*; fn default_port_settings() -> PortSettings { PortSettings { baud_rate: BaudRate::Baud9600, char_size: CharSize::Bits8, parity: Parity::ParityNone, stop_bits: StopBits::Stop1, flow_control: FlowControl::FlowNone, } } #[test] fn port_settings_manipulates_baud_rate() { let mut settings: PortSettings = default_port_settings(); settings.set_baud_rate(Baud115200).unwrap(); assert_eq!(settings.baud_rate(), Some(Baud115200)); } #[test] fn port_settings_manipulates_char_size() { let mut settings: PortSettings = default_port_settings(); settings.set_char_size(Bits7); assert_eq!(settings.char_size(), Some(Bits7)); } #[test] fn port_settings_manipulates_parity() { let mut settings: PortSettings = default_port_settings(); settings.set_parity(ParityEven); assert_eq!(settings.parity(), Some(ParityEven)); } #[test] fn port_settings_manipulates_stop_bits() { let mut settings: PortSettings = default_port_settings(); settings.set_stop_bits(Stop2); assert_eq!(settings.stop_bits(), Some(Stop2)); } #[test] fn port_settings_manipulates_flow_control() { let mut settings: PortSettings = default_port_settings(); settings.set_flow_control(FlowSoftware); assert_eq!(settings.flow_control(), Some(FlowSoftware)); } }