Serialport 1.0.0 - Cross-platform serial port library supporting enumeration

I've been working on serialport-rs which has a different API that I think is easier to use and also supports port enumeration. The API is very similar to that used by QSerialPort as part of the Qt library. Both a cross-platform API (through the SerialPort trait) as well as Windows and POSIX-specific APIs exist. I developed this as part of my work on the serial terminal gattii, where I needed some specific API features and port enumeration.

Notable features:

  • Cross-platform API
  • Platform-specific API with additional functionality
  • Blocking I/O
  • Serial port enumeration

There is additional work on async I/O through companion libraries (not being developed by me): mio-serial and tokio-serial (both on crates.io), These only work for Linux currently but I believe the eventual goal is to flesh them out onto all platforms.

The examples/ folder has some small example programs, like reading data from a port specific as a command line argument:

extern crate argparse;
extern crate serialport;

use std::io::{self, Write};

use argparse::{ArgumentParser, Store};

fn main() {
    let mut port_name = "".to_string();
    {
        let mut ap = ArgumentParser::new();
        ap.set_description("Read from the given serial port at 9600 baud");
        ap.refer(&mut port_name)
            .add_argument("port", Store, "Port name")
            .required();
        ap.parse_args_or_exit();
    }

    if let Ok(mut port) = serialport::open(&port_name) {
        let mut serial_buf: Vec<u8> = vec![0; 1000];
        println!("Receiving data on {} at 9600 baud:", &port_name);
        loop {
            if let Ok(t) = port.read(serial_buf.as_mut_slice()) {
                io::stdout().write_all(&serial_buf[..t]).unwrap();
            }
        }
    } else {
        println!("Error: Port '{}' not available", &port_name);
    }
}

and enumerating serial ports looks like:

extern crate serialport;

fn main() {

    if let Ok(ports) = serialport::available_ports() {
        match ports.len() {
            0 => println!("No ports found."),
            1 => println!("Found 1 port:"),
            n => println!("Found {} ports:", n),
        };
        for p in ports {
            println!("  {}", p.port_name);
        }
    } else {
        print!("Error listing serial ports");
    }

}
12 Likes