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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#![no_std]
extern crate  embedded_hal as hal;
use core::cell::RefCell;
/// embedded hal spy implemnets call backs for used traits
///
/// Intended use is chaining over an existing embedded_hal
/// implementation sniffing all the data. Useful when preparing
/// for a refacforing and want to collect actual data for unit
/// test case.
///

/// Blocking SPI API
/// hal::blocking::spi::Transfer will return
/// DataWord::First at start of transfer, all data sent in DataWord::Byte(u8)
/// DataWord::Response to indicate where transmit ends and response begins
/// all recived bytes in DataWord::Byte(u8) ending with DataWord::Last
///
/// Usage:
/// ```
///    extern crate embedded_hal_spy;
///    use embedded_hal_spy::DataWord;
/// #   use linux_embedded_hal::Spidev;
/// #   use linux_embedded_hal::Pin;
///
/// #   if let Ok(spi) = Spidev::open("/dev/spidev0.0"){
///    let mut spix = embedded_hal_spy::new(spi,
///             |w|{
///                 match w {
///                     DataWord::First => {
///                         print!("data = [");
///                     },
///                     DataWord::Last =>  {println!("],"); },
///                     DataWord::Response =>  { print!("],\r\n       ["); },
///
///                     DataWord::Byte(num) => {
///                         print!("{:x},",num);
///                         },
///                     _other => {},
///                 }
///             }
///      );
/// #     }
/// ```
pub struct Spy<T,F>
where F:Fn(DataWord)
{
    /// object implementing emedded hal
    s: RefCell<T>,
    /// Callback
    f: RefCell<F>,
}
/// Chain existing embedded_hal trait implementation to
/// embedded_hal_spy
pub fn new<T,F>(s: T, f: F)-> Spy<T,F>
where F:Fn(DataWord)
{
    Spy{s:RefCell::new(s), f:RefCell::new(f)}
}


/// Call back data is encapulated in enum DataWord
/// First and Last are provided from some transation
/// oriented traits to indicate first and last
pub enum DataWord {
    None,
    /// Encapsulate data
    Byte(u8),
    /// indicates first byte in transaction when used it
    /// will be followd by last after the last byte
    First,
    /// When used it is sent after last byte in transaction
    Last,
    /// Indicate beggining of response from a tranasction based class
    Response,
    /// embedded_hal call have failed and will report error
    Failed,
    /// hal::digital::ToggleableOutput return value
    Toggle,
}

use hal::spi::FullDuplex;
extern crate nb;
/// FullDuplex will return every data sent and read in DataWord::Byte(u8)
///
impl<T,F> FullDuplex<u8> for Spy<T,F>
where T:FullDuplex<u8>,
      F: Fn(DataWord),
{
    type Error = T::Error;
    fn read (&mut self) -> Result<u8, nb::Error<Self::Error>>{
        let mut s = self.s.borrow_mut();
        let ans = s.read();
        match &ans {
            Ok(w) => {(self.f.borrow_mut())(DataWord::Byte(w.clone()));},
            _other => {},
        }
        ans
    }
    fn send(&mut self, w: u8) -> Result<(), nb::Error<Self::Error>>{
        (self.f.borrow_mut())(DataWord::Byte(w));
        let mut s = self.s.borrow_mut();
        s.send(w)
    }
}

impl<T,F> hal::blocking::spi::Transfer<u8> for Spy<T,F>
where T: hal::blocking::spi::Transfer<u8>,
      F:Fn(DataWord)
{
    type Error = T::Error;
    /// Sends `Word` to the slave. Returns the `Word` received from the slave
    fn transfer<'w>(&mut self, words: &'w mut [u8]) -> Result<&'w [u8], Self::Error>{
        (self.f.borrow_mut())(DataWord::First);
        for w in words.iter(){
            (self.f.borrow_mut())(DataWord::Byte(*w));
        }
        (self.f.borrow_mut())(DataWord::Response);
        let ans = (self.s.borrow_mut()).transfer(words)?;
        for w in ans.iter(){
            (self.f.borrow_mut())(DataWord::Byte(*w));
        }
        (self.f.borrow_mut())(DataWord::Last);

        Ok(ans)
    }
}

/// Blocking write
impl<T,F> hal::blocking::spi::Write<u8> for Spy<T,F>
where T: hal::blocking::spi::Write<u8>,
      F: Fn(DataWord)
 {
    type Error = T::Error;
    /// Sends `words` to the slave, ignoring all the incoming words
    fn write(&mut self, words: &[u8]) -> Result<(), Self::Error>{
        for w in words.iter(){
            (self.f.borrow_mut())(DataWord::Byte(*w));
        }
        (self.s.borrow_mut()).write(words)
    }
}
#[cfg(feature = "embedded_hal_digital_io_legacy_v1")]
/// Legacy traits
/// Digital InputPin
impl<T,F> hal::digital::v1::InputPin for Spy<T,F>
where T: hal::digital::v1::InputPin,
      F: Fn(DataWord)
 {
    fn is_high(&self) -> bool{
        let state = (self.s.borrow_mut()).is_high();

        (self.f.borrow_mut())(DataWord::Byte(state as u8));
        state
    }
    fn is_low(&self) -> bool{
        let state = (self.s.borrow_mut()).is_low();
        (self.f.borrow_mut())(DataWord::Byte((!state) as u8));
        state
    }
}
#[cfg(feature = "embedded_hal_digital_io_legacy_v1")]
/// Digital OutputPin
impl<T,F> hal::digital::v1::OutputPin for Spy<T,F>
where T: hal::digital::v1::OutputPin,
      F: Fn(DataWord)
 {
    fn set_high(&mut self){
        (self.f.borrow_mut())(DataWord::Byte(1));
        (self.s.borrow_mut()).set_high()
    }
    fn set_low(&mut self){
        (self.f.borrow_mut())(DataWord::Byte(0));
        (self.s.borrow_mut()).set_low()
    }
}
#[cfg(feature = "embedded_hal_digital_io_legacy_v1")]
impl<T,F> hal::digital::v1::ToggleableOutputPin for Spy<T,F>
where T: hal::digital::v1::ToggleableOutputPin,
      F: Fn(DataWord)
 {
    fn toggle(&mut self){
        (self.f.borrow_mut())(DataWord::Toggle);
        (self.s.borrow_mut()).toggle()
    }
}

#[cfg(feature = "embedded_hal_digital_io_legacy_v1")]
impl<T,F> hal::digital::v1::StatefulOutputPin for Spy<T,F>
where T: hal::digital::v1::StatefulOutputPin,
      F: Fn(DataWord)
{
    fn is_set_high(&self) -> bool{
        let state = (self.s.borrow_mut()).is_set_high();

        (self.f.borrow_mut())(DataWord::Byte(state as u8));
        state
    }
    fn is_set_low(&self) -> bool{
        let state = (self.s.borrow_mut()).is_set_low();
        (self.f.borrow_mut())(DataWord::Byte((!state) as u8));
        state
    }
}

#[cfg(not(feature = "embedded_hal_digital_io_legacy_v1"))]
// V2 traits
/// Digital InputPin
impl<T,F> hal::digital::v2::InputPin for Spy<T,F>
where T: hal::digital::v2::InputPin,
      F: Fn(DataWord)
 {
    type Error = T::Error;
    fn is_high(&self) -> Result<bool,Self::Error>{
        let state = (self.s.borrow_mut()).is_high()?;
        (self.f.borrow_mut())(DataWord::Byte(state as u8));
        Ok(state)
    }
    fn is_low(&self) -> Result<bool,Self::Error>{
        let state = (self.s.borrow_mut()).is_low()?;
        (self.f.borrow_mut())(DataWord::Byte((!state) as u8));
        Ok(state)
    }
}
#[cfg(not(feature = "embedded_hal_digital_io_legacy_v1"))]
/// Digital OutputPin
impl<T,F> hal::digital::v2::OutputPin for Spy<T,F>
where T: hal::digital::v2::OutputPin,
      F: Fn(DataWord)
 {
    type Error = T::Error;
    fn set_high(&mut self)->Result<(),T::Error>{
        (self.f.borrow_mut())(DataWord::Byte(1));
        (self.s.borrow_mut()).set_high()
    }
    fn set_low(&mut self)->Result<(),T::Error>{
        (self.f.borrow_mut())(DataWord::Byte(0));
        (self.s.borrow_mut()).set_low()
    }
}
#[cfg(not(feature = "embedded_hal_digital_io_legacy_v1"))]
impl<T,F> hal::digital::v2::ToggleableOutputPin for Spy<T,F>
where T: hal::digital::v2::ToggleableOutputPin,
      F: Fn(DataWord)
 {
    type Error = T::Error;
    fn toggle(&mut self)->Result<(),T::Error>{
        (self.f.borrow_mut())(DataWord::Toggle);
        (self.s.borrow_mut()).toggle()
    }
}

#[cfg(not(feature = "embedded_hal_digital_io_legacy_v1"))]
impl<T,F> hal::digital::v2::StatefulOutputPin for Spy<T,F>
where T: hal::digital::v2::StatefulOutputPin,
      F: Fn(DataWord)
{
    //type Error = T::Error;
    fn is_set_high(&self) -> Result<bool,T::Error>{
        let state = (self.s.borrow_mut()).is_set_high()?;

        (self.f.borrow_mut())(DataWord::Byte(state as u8));
        Ok(state)
    }
    fn is_set_low(&self) -> Result<bool,T::Error>{
        let state = (self.s.borrow_mut()).is_set_low()?;
        (self.f.borrow_mut())(DataWord::Byte((!state) as u8));
        Ok(state)
    }
}