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
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
//! Basic HAL functions for communicating with the radio device

use core::fmt::Debug;

use log::{trace, error};

use embedded_hal::blocking::delay::{DelayMs, DelayUs};
use embedded_hal::blocking::spi::Transactional;

use driver_pal::{Reset, Busy, Ready, PinState, PrefixRead, PrefixWrite};
use driver_pal::{Error as SpiError};

use crate::{Error};
use crate::device::*;

/// Hal implementation can be generic over SPI or UART connections
pub trait Hal<
    CommsError: Debug + Sync + Send, 
    PinError: Debug + Sync + Send,
    DelayError: Debug + Sync + Send,
    > {

    /// Reset the device
    fn reset(&mut self) -> Result<(), Error<CommsError, PinError, DelayError>>;

    /// Fetch radio device busy pin value
    fn get_busy(&mut self) -> Result<PinState, Error<CommsError, PinError, DelayError>>;

    /// Fetch radio device ready / irq (DIO) pin value
    fn get_dio(&mut self) -> Result<PinState, Error<CommsError, PinError, DelayError>>;

    /// Delay for the specified time
    fn try_delay_ms(&mut self, ms: u32)-> Result<(), DelayError>;

    /// Delay for the specified time
    fn try_delay_us(&mut self, us: u32)-> Result<(), DelayError>;

    /// Write the specified command and data
    fn write_cmd(&mut self, command: u8, data: &[u8]) -> Result<(), Error<CommsError, PinError, DelayError>>;
    /// Read the specified command and data
    fn read_cmd(&mut self, command: u8, data: &mut [u8]) -> Result<(), Error<CommsError, PinError, DelayError>>;
    
    /// Write to the specified register
    fn write_regs(&mut self, reg: u16, data: &[u8]) -> Result<(), Error<CommsError, PinError, DelayError>>;
    /// Read from the specified register
    fn read_regs(&mut self, reg: u16, data: &mut [u8]) -> Result<(), Error<CommsError, PinError, DelayError>>;
    
    /// Write to the specified buffer
    fn write_buff(&mut self, offset: u8, data: &[u8]) -> Result<(), Error<CommsError, PinError, DelayError>>;
    /// Read from the specified buffer
    fn read_buff(&mut self, offset: u8, data: &mut [u8]) -> Result<(), Error<CommsError, PinError, DelayError>>;

    /// Wait on radio device busy
    fn wait_busy(&mut self) -> Result<(), Error<CommsError, PinError, DelayError>> {
        // TODO: timeouts here
        let mut timeout = 0;
        while self.get_busy()? == PinState::High {
            self.try_delay_ms(1).map_err(Error::Delay)?;
            timeout += 1;

            if timeout > BUSY_TIMEOUT_MS {
                error!("Busy timeout after {} ms", BUSY_TIMEOUT_MS);
                return Err(Error::BusyTimeout)
            }
        }

        Ok(())
    }

    /// Read a single u8 value from the specified register
    fn read_reg(&mut self, reg: u16) -> Result<u8, Error<CommsError, PinError, DelayError>> {
        let mut incoming = [0u8; 1];
        self.read_regs(reg.into(), &mut incoming)?;
        Ok(incoming[0])
    }

    /// Write a single u8 value to the specified register
    fn write_reg(&mut self, reg: u16, value: u8) -> Result<(), Error<CommsError, PinError, DelayError>> {
        self.write_regs(reg.into(), &[value])?;
        Ok(())
    }

    /// Update the specified register with the provided value & mask
    fn update_reg(&mut self, reg: u16, mask: u8, value: u8) -> Result<u8, Error<CommsError, PinError, DelayError>> {
        let existing = self.read_reg(reg)?;
        let updated = (existing & !mask) | (value & mask);
        self.write_reg(reg, updated)?;
        Ok(updated)
    }
}

impl<T, CommsError, PinError, DelayError> Hal<CommsError, PinError, DelayError> for T
where
    T: Transactional<u8, Error=SpiError<CommsError, PinError, DelayError>> + PrefixRead<Error=SpiError<CommsError, PinError, DelayError>> + PrefixWrite<Error=SpiError<CommsError, PinError, DelayError>>,
    T: Reset<Error=SpiError<CommsError, PinError, DelayError>>,
    T: Busy<Error=SpiError<CommsError, PinError, DelayError>>,
    T: Ready<Error=SpiError<CommsError, PinError, DelayError>>,
    T: DelayMs<u32, Error=DelayError> + DelayUs<u32, Error=DelayError>,
    CommsError: Debug + Sync + Send,
    PinError: Debug + Sync + Send,
    DelayError: Debug + Sync + Send,
{    
    /// Reset the radio
    fn reset(&mut self) -> Result<(), Error<CommsError, PinError, DelayError>> {
        self.try_delay_ms(20).map_err(Error::Delay)?;
        self.set_reset(PinState::Low).map_err(|e| Error::from(e) )?;
        self.try_delay_ms(50).map_err(Error::Delay)?;
        self.set_reset(PinState::High).map_err(|e| Error::from(e) )?;
        self.try_delay_ms(20).map_err(Error::Delay)?;

        Ok(())
    }

    fn get_busy(&mut self) -> Result<PinState, Error<CommsError, PinError, DelayError>> {
        let busy = self.get_busy()?;
        Ok(busy)
    }

    fn get_dio(&mut self) -> Result<PinState, Error<CommsError, PinError, DelayError>> {
        let dio = self.get_ready()?;
        Ok(dio)
    }


    /// Delay for the specified time
    fn try_delay_ms(&mut self, ms: u32) -> Result<(), DelayError> {
        DelayMs::try_delay_ms(self, ms)
    }

    /// Delay for the specified time
    fn try_delay_us(&mut self, ms: u32) -> Result<(), DelayError> {
        DelayUs::try_delay_us(self, ms)
    }

    /// Write the specified command and data
    fn write_cmd(&mut self, command: u8, data: &[u8]) -> Result<(), Error<CommsError, PinError, DelayError>> {
        // Setup register write command
        let out_buf: [u8; 1] = [command as u8];
        
        trace!("write_cmd cmd: {:02x?} data: {:02x?}", out_buf, data);

        self.wait_busy()?;
        let r = self.try_prefix_write(&out_buf, data).map_err(|e| e.into() );
        self.wait_busy()?;
        r
    }

    /// Read the specified command and data
    fn read_cmd<'a>(&mut self, command: u8, data: &mut [u8]) -> Result<(), Error<CommsError, PinError, DelayError>> {
        // Setup register read command
        let out_buf: [u8; 2] = [command as u8, 0x00];
        
        self.wait_busy()?;
        let r = self.try_prefix_read(&out_buf, data).map(|_| () ).map_err(|e| e.into() );
        self.wait_busy()?;

        trace!("read_cmd cmd: {:02x?} data: {:02x?}", out_buf, data);

        r
    }

    /// Write to the specified register
    fn write_regs(&mut self, reg: u16, data: &[u8]) -> Result<(), Error<CommsError, PinError, DelayError>> {
        // Setup register write command
        let out_buf: [u8; 3] = [
            Commands::WiteRegister as u8,
            ((reg & 0xFF00) >> 8) as u8,
            (reg & 0x00FF) as u8,
        ];

        trace!("write_regs cmd: {:02x?} data: {:02x?}", out_buf, data);

        self.wait_busy()?;
        let r = self.try_prefix_write(&out_buf, data).map_err(|e| e.into() );
        self.wait_busy()?;
        r
    }

    /// Read from the specified register
    fn read_regs<'a>(&mut self, reg: u16, data: &mut [u8]) -> Result<(), Error<CommsError, PinError, DelayError>> {
        // Setup register read command
        let out_buf: [u8; 4] = [
            Commands::ReadRegister as u8,
            ((reg & 0xFF00) >> 8) as u8,
            (reg & 0x00FF) as u8,
            0,
        ];

        self.wait_busy()?;
        let r = self.try_prefix_read(&out_buf, data).map(|_| () ).map_err(|e| e.into() );
        self.wait_busy()?;

        trace!("read_regs cmd: {:02x?} data: {:02x?}", out_buf, data);
        
        r
    }

    /// Write to the specified buffer
    fn write_buff(&mut self, offset: u8, data: &[u8]) -> Result<(), Error<CommsError, PinError, DelayError>> {
        // Setup register write command
        let out_buf: [u8; 2] = [
            Commands::WriteBuffer as u8,
            offset,
        ];
        
        trace!("write_buff cmd: {:02x?}", out_buf);

        self.wait_busy()?;
        let r = self.try_prefix_write(&out_buf, data).map_err(|e| e.into() );
        self.wait_busy()?;
        r
    }

    /// Read from the specified buffer
    fn read_buff<'a>(&mut self, offset: u8, data: &mut [u8]) -> Result<(), Error<CommsError, PinError, DelayError>> {
        // Setup register read command
        let out_buf: [u8; 3] = [
            Commands::ReadBuffer as u8,
            offset,
            0
        ];
        trace!(" data: {:02x?}", out_buf);
        self.wait_busy()?;
        let r = self.try_prefix_read(&out_buf, data).map(|_| () ).map_err(|e| e.into() );
        self.wait_busy()?;

        trace!("read_buff cmd: {:02x?} data: {:02x?}", out_buf, data);

        r
    }
}