#![doc = include_str!("../README.md")]
#![forbid(missing_docs)]
#![forbid(unsafe_code)]
#![no_std]
pub trait Error: core::fmt::Debug {
fn kind(&self) -> ErrorKind;
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum ErrorKind {
Peripheral,
InvalidSpeed,
Other,
}
impl Error for ErrorKind {
#[inline]
fn kind(&self) -> ErrorKind {
*self
}
}
impl core::fmt::Display for ErrorKind {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Peripheral => {
write!(f, "An error occured on the underlying peripheral")
}
Self::InvalidSpeed => {
write!(f, "Fan is not capable of operating at the requested speed")
}
Self::Other => write!(
f,
"A different error occurred. The original error may contain more information"
),
}
}
}
pub trait ErrorType {
type Error: Error;
}
impl<T: ErrorType + ?Sized> ErrorType for &mut T {
type Error = T::Error;
}
impl Error for core::convert::Infallible {
#[inline]
fn kind(&self) -> ErrorKind {
match *self {}
}
}
pub trait Fan: ErrorType {
fn max_rpm(&self) -> u16;
fn min_rpm(&self) -> u16;
fn min_start_rpm(&self) -> u16;
fn set_speed_rpm(&mut self, rpm: u16) -> Result<u16, Self::Error>;
#[inline]
fn set_speed_percent(&mut self, percent: u8) -> Result<u16, Self::Error> {
debug_assert!((0..=100).contains(&percent));
self.set_speed_rpm(((u32::from(self.max_rpm()) * u32::from(percent)) / 100) as u16)
}
#[inline]
fn set_speed_max(&mut self) -> Result<(), Self::Error> {
self.set_speed_rpm(self.max_rpm())?;
Ok(())
}
#[inline]
fn start(&mut self) -> Result<(), Self::Error> {
self.set_speed_rpm(self.min_start_rpm())?;
Ok(())
}
#[inline]
fn stop(&mut self) -> Result<(), Self::Error> {
self.set_speed_rpm(0)?;
Ok(())
}
}
impl<T: Fan + ?Sized> Fan for &mut T {
#[inline]
fn max_rpm(&self) -> u16 {
T::max_rpm(self)
}
#[inline]
fn min_rpm(&self) -> u16 {
T::min_rpm(self)
}
#[inline]
fn min_start_rpm(&self) -> u16 {
T::min_start_rpm(self)
}
#[inline]
fn set_speed_rpm(&mut self, rpm: u16) -> Result<u16, Self::Error> {
T::set_speed_rpm(self, rpm)
}
#[inline]
fn set_speed_percent(&mut self, percent: u8) -> Result<u16, Self::Error> {
T::set_speed_percent(self, percent)
}
#[inline]
fn set_speed_max(&mut self) -> Result<(), Self::Error> {
T::set_speed_max(self)
}
#[inline]
fn stop(&mut self) -> Result<(), Self::Error> {
T::stop(self)
}
}
pub trait RpmSense: ErrorType {
fn rpm(&mut self) -> Result<u16, Self::Error>;
}
impl<T: RpmSense + ?Sized> RpmSense for &mut T {
#[inline]
fn rpm(&mut self) -> Result<u16, Self::Error> {
T::rpm(self)
}
}