mcp4x/
device_impl.rs

1//! Device implementation
2
3use crate::{ic, interface, private, Channel, Command, Error, Mcp4x};
4use core::marker::PhantomData;
5
6#[doc(hidden)]
7pub trait CheckChannel<CommE>: private::Sealed {
8    fn check_if_channel_is_appropriate(channel: Channel) -> Result<(), Error<CommE>>;
9}
10
11impl<CommE> CheckChannel<CommE> for ic::Mcp41x {
12    fn check_if_channel_is_appropriate(channel: Channel) -> Result<(), Error<CommE>> {
13        if channel == Channel::Ch0 || channel == Channel::All {
14            Ok(())
15        } else {
16            Err(Error::WrongChannel)
17        }
18    }
19}
20
21impl<CommE> CheckChannel<CommE> for ic::Mcp42x {
22    fn check_if_channel_is_appropriate(_: Channel) -> Result<(), Error<CommE>> {
23        Ok(())
24    }
25}
26
27impl<DI, IC, CommE> Mcp4x<DI, IC>
28where
29    DI: interface::WriteCommand<Error = Error<CommE>>,
30    IC: CheckChannel<CommE>,
31{
32    /// Set a channel to a position.
33    ///
34    /// Will return `Error::WrongChannel` if the channel provided is not available
35    /// on the device.
36    pub fn set_position(&mut self, channel: Channel, position: u8) -> Result<(), Error<CommE>> {
37        IC::check_if_channel_is_appropriate(channel)?;
38        let cmd = Command::SetPosition(channel, position);
39        self.iface
40            .write_command(cmd.get_command_byte(), cmd.get_data_byte())
41    }
42
43    /// Shutdown a channel.
44    ///
45    /// Will return `Error::WrongChannel` if the channel provided is not available
46    /// on the device.
47    pub fn shutdown(&mut self, channel: Channel) -> Result<(), Error<CommE>> {
48        IC::check_if_channel_is_appropriate(channel)?;
49        let cmd = Command::Shutdown(channel);
50        self.iface
51            .write_command(cmd.get_command_byte(), cmd.get_data_byte())
52    }
53}
54
55impl<SPI> Mcp4x<interface::SpiInterface<SPI>, ic::Mcp41x> {
56    /// Create new MCP41x device instance
57    pub fn new_mcp41x(spi: SPI) -> Self {
58        Mcp4x {
59            iface: interface::SpiInterface { spi },
60            _ic: PhantomData,
61        }
62    }
63
64    /// Destroy driver instance, return SPI bus instance and CS output pin.
65    pub fn destroy_mcp41x(self) -> SPI {
66        self.iface.spi
67    }
68}
69
70impl<SPI> Mcp4x<interface::SpiInterface<SPI>, ic::Mcp42x> {
71    /// Create new MCP42x device instance
72    pub fn new_mcp42x(spi: SPI) -> Self {
73        Mcp4x {
74            iface: interface::SpiInterface { spi },
75            _ic: PhantomData,
76        }
77    }
78
79    /// Destroy driver instance, return SPI bus instance and CS output pin.
80    pub fn destroy_mcp42x(self) -> SPI {
81        self.iface.spi
82    }
83}