dfu_core/
asynchronous.rs

1use futures::{io::Cursor, AsyncRead, AsyncReadExt, AsyncSeek, AsyncSeekExt};
2
3use super::*;
4use core::future::Future;
5use std::convert::TryFrom;
6use std::prelude::v1::*;
7
8/// Trait to implement lower level communication with a USB device.
9pub trait DfuAsyncIo {
10    /// Return type after calling [`Self::read_control`].
11    type Read;
12    /// Return type after calling [`Self::write_control`].
13    type Write;
14    /// Return type after calling [`Self::usb_reset`].
15    type Reset;
16    /// Error type.
17    type Error: From<Error>;
18    /// Dfuse Memory layout type
19    type MemoryLayout: AsRef<memory_layout::mem>;
20
21    /// Read data using control transfer.
22    fn read_control(
23        &self,
24        request_type: u8,
25        request: u8,
26        value: u16,
27        buffer: &mut [u8],
28    ) -> impl Future<Output = Result<Self::Read, Self::Error>> + Send;
29
30    /// Write data using control transfer.
31    fn write_control(
32        &self,
33        request_type: u8,
34        request: u8,
35        value: u16,
36        buffer: &[u8],
37    ) -> impl Future<Output = Result<Self::Write, Self::Error>> + Send;
38
39    /// Triggers a USB reset.
40    fn usb_reset(&self) -> impl Future<Output = Result<Self::Reset, Self::Error>> + Send;
41
42    /// Sleep for this duration of time.
43    fn sleep(&self, duration: std::time::Duration) -> impl Future<Output = ()> + Send;
44
45    /// Returns the protocol of the device
46    fn protocol(&self) -> &DfuProtocol<Self::MemoryLayout>;
47
48    /// Returns the functional descriptor of the device.
49    fn functional_descriptor(&self) -> &functional_descriptor::FunctionalDescriptor;
50}
51
52impl UsbReadControl<'_> {
53    /// Execute usb write using io
54    pub async fn execute_async<IO: DfuAsyncIo>(&mut self, io: &IO) -> Result<IO::Read, IO::Error> {
55        io.read_control(self.request_type, self.request, self.value, self.buffer)
56            .await
57    }
58}
59
60impl<D> UsbWriteControl<D>
61where
62    D: AsRef<[u8]>,
63{
64    /// Execute usb write using io
65    pub async fn execute_async<IO: DfuAsyncIo>(&self, io: &IO) -> Result<IO::Write, IO::Error> {
66        io.write_control(
67            self.request_type,
68            self.request,
69            self.value,
70            self.buffer.as_ref(),
71        )
72        .await
73    }
74}
75
76struct Buffer<R: AsyncRead + Unpin> {
77    reader: R,
78    buf: Box<[u8]>,
79    level: usize,
80}
81
82impl<R: AsyncRead + Unpin> Buffer<R> {
83    fn new(size: usize, reader: R) -> Self {
84        Self {
85            reader,
86            buf: vec![0; size].into_boxed_slice(),
87            level: 0,
88        }
89    }
90
91    async fn fill_buf(&mut self) -> Result<&[u8], std::io::Error> {
92        while self.level < self.buf.len() {
93            let dst = &mut self.buf[self.level..];
94            let r = self.reader.read(dst).await?;
95            if r == 0 {
96                break;
97            } else {
98                self.level += r;
99            }
100        }
101        Ok(&self.buf[0..self.level])
102    }
103
104    fn consume(&mut self, amt: usize) {
105        if amt >= self.level {
106            self.level = 0;
107        } else {
108            self.buf.copy_within(amt..self.level, 0);
109            self.level -= amt;
110        }
111    }
112}
113
114/// Generic asynchronous implementation of DFU.
115#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
116pub struct DfuASync<IO, E>
117where
118    IO: DfuAsyncIo<Read = usize, Write = usize, Reset = (), Error = E>,
119    E: From<std::io::Error> + From<Error>,
120{
121    io: IO,
122    dfu: DfuSansIo,
123    buffer: Vec<u8>,
124}
125
126impl<IO, E> DfuASync<IO, E>
127where
128    IO: DfuAsyncIo<Read = usize, Write = usize, Reset = (), Error = E>,
129    E: From<std::io::Error> + From<Error>,
130{
131    /// Create a new instance of a generic synchronous implementation of DFU.
132    pub fn new(io: IO) -> Self {
133        let transfer_size = io.functional_descriptor().transfer_size as usize;
134        let descriptor = *io.functional_descriptor();
135
136        Self {
137            io,
138            dfu: DfuSansIo::new(descriptor),
139            buffer: vec![0x00; transfer_size],
140        }
141    }
142
143    /// Override the address onto which the firmware is downloaded.
144    ///
145    /// This address is only used if the device uses the DfuSe protocol.
146    pub fn override_address(&mut self, address: u32) -> &mut Self {
147        self.dfu.set_address(address);
148        self
149    }
150
151    /// Consume the object and return its [`DfuIo`]
152    pub fn into_inner(self) -> IO {
153        self.io
154    }
155}
156
157impl<IO, E> DfuASync<IO, E>
158where
159    IO: DfuAsyncIo<Read = usize, Write = usize, Reset = (), Error = E>,
160    E: From<std::io::Error> + From<Error>,
161{
162    /// Download a firmware into the device from a slice.
163    pub async fn download_from_slice(&mut self, slice: &[u8]) -> Result<(), IO::Error> {
164        let length = slice.len();
165        let cursor = Cursor::new(slice);
166
167        self.download(
168            cursor,
169            u32::try_from(length).map_err(|_| Error::OutOfCapabilities)?,
170        )
171        .await
172    }
173
174    /// Download a firmware into the device from a reader.
175    pub async fn download<R: AsyncReadExt + Unpin>(
176        &mut self,
177        reader: R,
178        length: u32,
179    ) -> Result<(), IO::Error> {
180        let transfer_size = self.io.functional_descriptor().transfer_size as usize;
181        let mut reader = Buffer::new(transfer_size, reader);
182        let buffer = reader.fill_buf().await?;
183        if buffer.is_empty() {
184            return Ok(());
185        }
186
187        macro_rules! wait_status {
188            ($cmd:expr) => {{
189                let mut cmd = $cmd;
190                loop {
191                    cmd = match cmd.next() {
192                        get_status::Step::Break(cmd) => break cmd,
193                        get_status::Step::Wait(cmd, poll_timeout) => {
194                            self.io
195                                .sleep(std::time::Duration::from_millis(poll_timeout))
196                                .await;
197                            let (cmd, mut control) = cmd.get_status(&mut self.buffer);
198                            let n = control.execute_async(&self.io).await?;
199                            cmd.chain(&self.buffer[..n as usize])??
200                        }
201                    };
202                }
203            }};
204        }
205
206        let cmd = self.dfu.download(self.io.protocol(), length)?;
207        let (cmd, mut control) = cmd.get_status(&mut self.buffer);
208        let n = control.execute_async(&self.io).await?;
209        let (cmd, control) = cmd.chain(&self.buffer[..n])?;
210        if let Some(control) = control {
211            control.execute_async(&self.io).await?;
212        }
213        let (cmd, mut control) = cmd.get_status(&mut self.buffer);
214        let n = control.execute_async(&self.io).await?;
215        let mut download_loop = cmd.chain(&self.buffer[..n])??;
216
217        loop {
218            download_loop = match download_loop.next() {
219                download::Step::Break => break,
220                download::Step::Erase(cmd) => {
221                    let (cmd, control) = cmd.erase()?;
222                    control.execute_async(&self.io).await?;
223                    wait_status!(cmd)
224                }
225                download::Step::SetAddress(cmd) => {
226                    let (cmd, control) = cmd.set_address();
227                    control.execute_async(&self.io).await?;
228                    wait_status!(cmd)
229                }
230                download::Step::DownloadChunk(cmd) => {
231                    let chunk = reader.fill_buf().await?;
232                    let (cmd, control) = cmd.download(chunk)?;
233                    let n = control.execute_async(&self.io).await?;
234                    reader.consume(n);
235                    wait_status!(cmd)
236                }
237                download::Step::UsbReset => {
238                    log::trace!("Device reset");
239                    self.io.usb_reset().await?;
240                    break;
241                }
242            }
243        }
244
245        Ok(())
246    }
247
248    /// Download a firmware into the device.
249    ///
250    /// The length is guess from the reader.
251    pub async fn download_all<R: AsyncReadExt + Unpin + AsyncSeek>(
252        &mut self,
253        mut reader: R,
254    ) -> Result<(), IO::Error> {
255        let length = u32::try_from(reader.seek(std::io::SeekFrom::End(0)).await?)
256            .map_err(|_| Error::MaximumTransferSizeExceeded)?;
257        reader.seek(std::io::SeekFrom::Start(0)).await?;
258        self.download(reader, length).await
259    }
260
261    /// Send a Detach request to the device
262    pub async fn detach(&self) -> Result<(), IO::Error> {
263        self.dfu.detach().execute_async(&self.io).await?;
264        Ok(())
265    }
266
267    /// Reset the USB device
268    pub async fn usb_reset(&self) -> Result<IO::Reset, IO::Error> {
269        self.io.usb_reset().await
270    }
271
272    /// Returns whether the device is will detach if requested
273    pub fn will_detach(&self) -> bool {
274        self.io.functional_descriptor().will_detach
275    }
276
277    /// Returns whether the device is manifestation tolerant
278    pub fn manifestation_tolerant(&self) -> bool {
279        self.io.functional_descriptor().manifestation_tolerant
280    }
281}