From aebcf0f785ef7ce667e37768edfe6f06e22d6fab Mon Sep 17 00:00:00 2001 From: Andrew Walbran Date: Sun, 4 Feb 2024 20:43:58 +0000 Subject: [PATCH] Implement Display and std::error::Error for DeviceError if possible. --- embedded-hal-bus/README.md | 3 ++- embedded-hal-bus/src/spi/mod.rs | 14 +++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/embedded-hal-bus/README.md b/embedded-hal-bus/README.md index 9fc8aaae0..ce71eec92 100644 --- a/embedded-hal-bus/README.md +++ b/embedded-hal-bus/README.md @@ -30,7 +30,8 @@ provides mechanisms to obtain multiple `I2c` instances out of a single `I2c` ins ## Optional Cargo features -- **`std`**: enable shared bus implementations using `std::sync::Mutex`. +- **`std`**: enable shared bus implementations using `std::sync::Mutex`, and implement + `std::error::Error` for `DeviceError`. - **`async`**: enable `embedded-hal-async` support. - **`defmt-03`**: Derive `defmt::Format` from `defmt` 0.3 for enums and structs. diff --git a/embedded-hal-bus/src/spi/mod.rs b/embedded-hal-bus/src/spi/mod.rs index 8b51242d8..d408bd92f 100644 --- a/embedded-hal-bus/src/spi/mod.rs +++ b/embedded-hal-bus/src/spi/mod.rs @@ -1,6 +1,6 @@ //! `SpiDevice` implementations. -use core::fmt::Debug; +use core::fmt::{self, Debug, Display, Formatter}; use embedded_hal::spi::{Error, ErrorKind}; mod exclusive; @@ -29,6 +29,18 @@ pub enum DeviceError { Cs(CS), } +impl Display for DeviceError { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match self { + Self::Spi(bus) => write!(f, "SPI bus error: {}", bus), + Self::Cs(cs) => write!(f, "SPI CS error: {}", cs), + } + } +} + +#[cfg(feature = "std")] +impl std::error::Error for DeviceError {} + impl Error for DeviceError where BUS: Error + Debug,