aboutsummaryrefslogtreecommitdiff
path: root/embassy-embedded-hal/src/adapter.rs
blob: 169aad5e376c6d9b5de47f3613e4c9d6ea578a70 (plain)
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
//! Adapters between embedded-hal traits.

use embassy_futures::yield_now;
use embedded_hal_02::{blocking, serial};

/// Wrapper that implements async traits using blocking implementations.
///
/// This allows driver writers to depend on the async traits while still supporting embedded-hal peripheral implementations.
///
/// BlockingAsync will implement any async trait that maps to embedded-hal traits implemented for the wrapped driver.
///
/// Driver users are then free to choose which implementation that is available to them.
pub struct BlockingAsync<T> {
    wrapped: T,
}

impl<T> BlockingAsync<T> {
    /// Create a new instance of a wrapper for a given peripheral.
    pub fn new(wrapped: T) -> Self {
        Self { wrapped }
    }
}

//
// I2C implementations
//
impl<T, E> embedded_hal_1::i2c::ErrorType for BlockingAsync<T>
where
    E: embedded_hal_1::i2c::Error + 'static,
    T: blocking::i2c::WriteRead<Error = E> + blocking::i2c::Read<Error = E> + blocking::i2c::Write<Error = E>,
{
    type Error = E;
}

impl<T, E> embedded_hal_async::i2c::I2c for BlockingAsync<T>
where
    E: embedded_hal_1::i2c::Error + 'static,
    T: blocking::i2c::WriteRead<Error = E> + blocking::i2c::Read<Error = E> + blocking::i2c::Write<Error = E>,
{
    async fn read(&mut self, address: u8, read: &mut [u8]) -> Result<(), Self::Error> {
        self.wrapped.read(address, read)
    }

    async fn write(&mut self, address: u8, write: &[u8]) -> Result<(), Self::Error> {
        self.wrapped.write(address, write)
    }

    async fn write_read(&mut self, address: u8, write: &[u8], read: &mut [u8]) -> Result<(), Self::Error> {
        self.wrapped.write_read(address, write, read)
    }

    async fn transaction(
        &mut self,
        address: u8,
        operations: &mut [embedded_hal_1::i2c::Operation<'_>],
    ) -> Result<(), Self::Error> {
        let _ = address;
        let _ = operations;
        todo!()
    }
}

//
// SPI implementatinos
//

impl<T, E> embedded_hal_async::spi::ErrorType for BlockingAsync<T>
where
    E: embedded_hal_1::spi::Error,
    T: blocking::spi::Transfer<u8, Error = E> + blocking::spi::Write<u8, Error = E>,
{
    type Error = E;
}

impl<T, E> embedded_hal_async::spi::SpiBus<u8> for BlockingAsync<T>
where
    E: embedded_hal_1::spi::Error + 'static,
    T: blocking::spi::Transfer<u8, Error = E> + blocking::spi::Write<u8, Error = E>,
{
    async fn transfer<'a>(&'a mut self, read: &'a mut [u8], write: &'a [u8]) -> Result<(), Self::Error> {
        // Ensure we write the expected bytes
        for i in 0..core::cmp::min(read.len(), write.len()) {
            read[i] = write[i].clone();
        }
        self.wrapped.transfer(read)?;
        Ok(())
    }

    async fn transfer_in_place<'a>(&'a mut self, _: &'a mut [u8]) -> Result<(), Self::Error> {
        todo!()
    }
}

impl<T, E> embedded_hal_async::spi::SpiBusFlush for BlockingAsync<T>
where
    E: embedded_hal_1::spi::Error + 'static,
    T: blocking::spi::Transfer<u8, Error = E> + blocking::spi::Write<u8, Error = E>,
{
    async fn flush(&mut self) -> Result<(), Self::Error> {
        Ok(())
    }
}

impl<T, E> embedded_hal_async::spi::SpiBusWrite<u8> for BlockingAsync<T>
where
    E: embedded_hal_1::spi::Error + 'static,
    T: blocking::spi::Transfer<u8, Error = E> + blocking::spi::Write<u8, Error = E>,
{
    async fn write(&mut self, data: &[u8]) -> Result<(), Self::Error> {
        self.wrapped.write(data)?;
        Ok(())
    }
}

impl<T, E> embedded_hal_async::spi::SpiBusRead<u8> for BlockingAsync<T>
where
    E: embedded_hal_1::spi::Error + 'static,
    T: blocking::spi::Transfer<u8, Error = E> + blocking::spi::Write<u8, Error = E>,
{
    async fn read(&mut self, data: &mut [u8]) -> Result<(), Self::Error> {
        self.wrapped.transfer(data)?;
        Ok(())
    }
}

// Uart implementatinos
impl<T, E> embedded_hal_1::serial::ErrorType for BlockingAsync<T>
where
    T: serial::Read<u8, Error = E>,
    E: embedded_hal_1::serial::Error + 'static,
{
    type Error = E;
}

/// NOR flash wrapper
use embedded_storage::nor_flash::{ErrorType, NorFlash, ReadNorFlash};
use embedded_storage_async::nor_flash::{NorFlash as AsyncNorFlash, ReadNorFlash as AsyncReadNorFlash};

impl<T> ErrorType for BlockingAsync<T>
where
    T: ErrorType,
{
    type Error = T::Error;
}

impl<T> AsyncNorFlash for BlockingAsync<T>
where
    T: NorFlash,
{
    const WRITE_SIZE: usize = <T as NorFlash>::WRITE_SIZE;
    const ERASE_SIZE: usize = <T as NorFlash>::ERASE_SIZE;

    async fn write(&mut self, offset: u32, data: &[u8]) -> Result<(), Self::Error> {
        self.wrapped.write(offset, data)?;
        yield_now().await;
        Ok(())
    }

    async fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
        for from in (from..to).step_by(T::ERASE_SIZE) {
            let to = core::cmp::min(from + T::ERASE_SIZE as u32, to);
            self.wrapped.erase(from, to)?;
            yield_now().await;
        }
        Ok(())
    }
}

impl<T> AsyncReadNorFlash for BlockingAsync<T>
where
    T: ReadNorFlash,
{
    const READ_SIZE: usize = <T as ReadNorFlash>::READ_SIZE;
    async fn read(&mut self, address: u32, data: &mut [u8]) -> Result<(), Self::Error> {
        self.wrapped.read(address, data)
    }

    fn capacity(&self) -> usize {
        self.wrapped.capacity()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    extern crate std;

    #[derive(Default)]
    struct FakeFlash(Vec<(u32, u32)>);

    impl embedded_storage::nor_flash::ErrorType for FakeFlash {
        type Error = std::convert::Infallible;
    }

    impl embedded_storage::nor_flash::ReadNorFlash for FakeFlash {
        const READ_SIZE: usize = 1;

        fn read(&mut self, _offset: u32, _bytes: &mut [u8]) -> Result<(), Self::Error> {
            unimplemented!()
        }

        fn capacity(&self) -> usize {
            unimplemented!()
        }
    }

    impl embedded_storage::nor_flash::NorFlash for FakeFlash {
        const WRITE_SIZE: usize = 4;
        const ERASE_SIZE: usize = 128;

        fn write(&mut self, _offset: u32, _bytes: &[u8]) -> Result<(), Self::Error> {
            unimplemented!()
        }

        fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
            self.0.push((from, to));
            Ok(())
        }
    }

    #[futures_test::test]
    async fn can_erase() {
        let fake = FakeFlash::default();
        let mut yielding = BlockingAsync::new(fake);

        yielding.erase(0, 256).await.unwrap();

        let fake = yielding.wrapped;
        assert_eq!(2, fake.0.len());
        assert_eq!((0, 128), fake.0[0]);
        assert_eq!((128, 256), fake.0[1]);
    }

    #[futures_test::test]
    async fn can_erase_wrong_erase_size() {
        let fake = FakeFlash::default();
        let mut yielding = BlockingAsync::new(fake);

        yielding.erase(0, 257).await.unwrap();

        let fake = yielding.wrapped;
        assert_eq!(3, fake.0.len());
        assert_eq!((0, 128), fake.0[0]);
        assert_eq!((128, 256), fake.0[1]);
        assert_eq!((256, 257), fake.0[2]);
    }
}