1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use core::fmt;
use command::{ReadRxPayloadWidth, ReadRxPayload};
use registers::FifoStatus;
use device::Device;
use standby::StandbyMode;
use payload::Payload;
use config::Configuration;

/// Represents **RX Mode**
pub struct RxMode<D: Device> {
    device: D,
}

impl<D: Device> fmt::Debug for RxMode<D> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "RxMode")
    }
}

impl<D: Device> RxMode<D> {
    /// Relies on everything being set up by `StandbyMode::rx()`, from
    /// which it is called
    pub(crate) fn new(device: D) -> Self {
        RxMode { device }
    }

    /// Disable `CE` so that you can switch into TX mode.
    pub fn standby(self) -> StandbyMode<D> {
        StandbyMode::from_rx_tx(self.device)
    }

    /// Is there any incoming data to read? Return the pipe number.
    pub fn can_read(&mut self) -> Result<Option<u8>, D::Error> {
        self.device.read_register::<FifoStatus>().map(
            |(status, fifo_status)| {
                if ! fifo_status.rx_empty() {
                    Some(status.rx_p_no())
                } else {
                    None
                }
            },
        )
    }

    /// Is the RX queue empty?
    pub fn is_empty(&mut self) -> Result<bool, D::Error> {
        self.device.read_register::<FifoStatus>()
            .map(|(_, fifo_status)| fifo_status.rx_empty())
    }

    /// Is the RX queue full?
    pub fn is_full(&mut self) -> Result<bool, D::Error> {
        self.device.read_register::<FifoStatus>().map(
            |(_, fifo_status)| fifo_status.rx_full()
        )
    }

    /// Read the next received packet
    pub fn read(&mut self) -> Result<Payload, D::Error> {
        let (_, payload_width) =
            self.device.send_command(&ReadRxPayloadWidth)?;
        let (_, payload) =
            self.device.send_command(&ReadRxPayload::new(payload_width as usize))?;
        Ok(payload)
    }
}

impl<D: Device> Configuration for RxMode<D> {
    type Inner = D;
    fn device(&mut self) -> &mut Self::Inner {
        &mut self.device
    }
}