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

use embedded_hal::blocking::spi;

use futures::prelude::*;

use crate::common::*;
use crate::error::Error;
use super::{Mux, Requester};

#[derive(Clone)]
pub struct Spi {
    device: String,
    mux: Mux,
}


impl Spi {
    pub (crate) fn new(device: String, mux: Mux) -> Self {
        Spi{device, mux}
    }
}

impl Drop for Spi {
    fn drop(&mut self) {
        self.mux.do_request(&self.device, RequestKind::SpiDisconnect).wait().unwrap();
    }
}

impl spi::Transfer<u8> for Spi {
    type Error = Error;

    fn transfer<'w>(&mut self, data: &'w mut [u8]) -> Result<&'w [u8], Error> {
        debug!("spi transfer request {}", self.device);
        let resp = self.mux.do_request(&self.device, RequestKind::SpiTransfer{write_data: Data{data: data.to_vec()}}).wait()?;
        debug!("spi transfer response");
        match resp {
            ResponseKind::SpiTransfer(d) => {
                data.clone_from_slice(&d);
                Ok(data)
            },
            _ => Err(Error::InvalidResponse(resp)),
        }
    }
}

impl spi::Write<u8> for Spi {
    type Error = Error;

    fn write(&mut self, data: &[u8]) -> Result<(), Error> {
        let resp = self.mux.do_request(&self.device, RequestKind::SpiWrite{write_data: Data{data: data.to_vec()}}).wait()?;
        match resp {
            ResponseKind::Ok => Ok(()),
            _ => Err(Error::InvalidResponse(resp)),
        }
    }
}