Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add optional support for embedded-hal traits #59

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion .github/workflows/build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,15 @@ jobs:
command: build
args: --target=${{ inputs.target }}

- name: Build | build library with all features
uses: actions-rs/cargo@v1
with:
command: build
args: --target=${{ inputs.target }} --all-features

- name: Build | build examples
if: ${{ inputs.disable_extra_builds == false }}
run: cargo build --examples --target=${{ inputs.target }}
run: cargo build --examples --target=${{ inputs.target }} --all-features

- name: Build | build tests
if: ${{ inputs.disable_extra_builds == false }}
Expand Down
8 changes: 8 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,17 @@ features = [

[dependencies]
serde = { version = "1.0", features = ["derive"], optional = true }
embedded-hal = { version = "=1.0.0-alpha.9", optional = true }
embedded-hal-nb = { version = "=1.0.0-alpha.1", optional = true }
nb = { version = "1", optional = true }

[dev-dependencies]
clap = "3.1.6"

[features]
default = ["libudev"]
embedded = ["embedded-hal", "embedded-hal-nb", "nb"]

[[example]]
name = "embedded_hal"
required-features = ["embedded"]
24 changes: 24 additions & 0 deletions examples/embedded_hal.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//! This example does not actually do anything, but it shows that a serialport
//! instance can be passed to functions / drivers that expect a type that
//! implements the embedded-hal traits.

fn take_nonblocking_reader<R: embedded_hal_nb::serial::Read<u8>>(_r: &R) {
// do nothing, but things should typecheck
}

fn take_nonblocking_writer<W: embedded_hal_nb::serial::Write<u8>>(_w: &W) {
// do nothing, but things should typecheck
}

fn take_blocking_writer<W: embedded_hal::serial::Write<u8>>(_w: &W) {
// do nothing, but things should typecheck
}

fn main() {
let port = serialport::new("/dev/null", 9600)
.open()
.expect("This example isn't meant for running. It just demonstrates compatibility with embedded-hal on a type level.");
take_nonblocking_reader(&port);
take_nonblocking_writer(&port);
take_blocking_writer(&port);
}
87 changes: 87 additions & 0 deletions src/embedded.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
//! Opt-in support for embedded-hal traits.
//!
//! Can be enabled with the "embedded" cargo feature.

use std::io;

use embedded_hal::serial::{ErrorType, ErrorKind};

use crate::SerialPort;

#[derive(Debug, Copy, Clone)]
pub struct SerialError {
kind: io::ErrorKind,
}

impl embedded_hal::serial::Error for SerialError {
fn kind(&self) -> ErrorKind {
#[allow(clippy::match_single_binding)]
match self.kind {
_ => ErrorKind::Other,
}
}
}

impl From<io::Error> for SerialError {
fn from(e: io::Error) -> Self {
SerialError {
kind: e.kind(),
}
}
}

impl ErrorType for Box<dyn SerialPort> {
type Error = SerialError;
}


mod nonblocking {
use super::*;
use embedded_hal_nb::serial;

fn io_error_to_nb(err: io::Error) -> nb::Error<SerialError> {
match err.kind() {
io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted => nb::Error::WouldBlock,
other => nb::Error::Other(SerialError { kind: other }),
}
}

impl serial::Read<u8> for Box<dyn SerialPort> {
fn read(&mut self) -> nb::Result<u8, Self::Error> {
let mut buffer = [0; 1];
let bytes_read = io::Read::read(self, &mut buffer).map_err(io_error_to_nb)?;
if bytes_read > 0 {
Ok(buffer[0])
} else {
Err(nb::Error::WouldBlock)
}
}
}

impl serial::Write<u8> for Box<dyn SerialPort> {
fn write(&mut self, word: u8) -> nb::Result<(), Self::Error> {
io::Write::write(self, &[word])
.map_err(io_error_to_nb)
.map(|_| ())
}

fn flush(&mut self) -> nb::Result<(), Self::Error> {
io::Write::flush(self).map_err(io_error_to_nb)
}
}
}

mod blocking {
use super::*;
use embedded_hal::serial;

impl serial::Write<u8> for Box<dyn SerialPort> {
fn write(&mut self, buffer: &[u8]) -> Result<(), Self::Error> {
Ok(io::Write::write_all(self, buffer)?)
}

fn flush(&mut self) -> Result<(), Self::Error> {
Ok(io::Write::flush(self)?)
}
}
}
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ mod windows;
#[cfg(windows)]
pub use windows::COMPort;

#[cfg(feature = "embedded")]
mod embedded;

/// A type for results generated by interacting with serial ports
///
/// The `Err` type is hard-wired to [`serialport::Error`](struct.Error.html).
Expand Down