Skip to main content

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    ///
164    /// Returns `Some(Self)` if the device stayed on the bus (manifestation tolerant, no USB reset
165    /// occurred) or `None` if a USB reset was performed.
166    pub async fn download_from_slice(self, slice: &[u8]) -> Result<Option<Self>, IO::Error> {
167        let length = slice.len();
168        let cursor = Cursor::new(slice);
169        self.download(
170            cursor,
171            u32::try_from(length).map_err(|_| Error::OutOfCapabilities)?,
172        )
173        .await
174    }
175
176    /// Download a firmware into the device from a reader.
177    ///
178    /// Returns `Some(Self)` if the device stayed on the bus (manifestation tolerant, no USB reset
179    /// occurred) or `None` if a USB reset was performed.
180    pub async fn download<R: AsyncReadExt + Unpin>(
181        mut self,
182        reader: R,
183        length: u32,
184    ) -> Result<Option<Self>, IO::Error> {
185        let transfer_size = self.io.functional_descriptor().transfer_size as usize;
186        let mut reader = Buffer::new(transfer_size, reader);
187        let buffer = reader.fill_buf().await?;
188        if buffer.is_empty() {
189            return Ok(Some(self));
190        }
191
192        macro_rules! wait_status {
193            ($cmd:expr) => {{
194                let mut cmd = $cmd;
195                loop {
196                    cmd = match cmd.next() {
197                        get_status::Step::Break(cmd) => break cmd,
198                        get_status::Step::Wait(cmd, poll_timeout) => {
199                            self.io
200                                .sleep(std::time::Duration::from_millis(poll_timeout))
201                                .await;
202                            let (cmd, mut control) = cmd.get_status(&mut self.buffer);
203                            let n = control.execute_async(&self.io).await?;
204                            cmd.chain(&self.buffer[..n as usize])??
205                        }
206                    };
207                }
208            }};
209        }
210
211        let cmd = self.dfu.download(self.io.protocol(), length)?;
212        let (cmd, mut control) = cmd.get_status(&mut self.buffer);
213        let n = control.execute_async(&self.io).await?;
214        let (cmd, control) = cmd.chain(&self.buffer[..n])?;
215        if let Some(control) = control {
216            control.execute_async(&self.io).await?;
217        }
218        let (cmd, mut control) = cmd.get_status(&mut self.buffer);
219        let n = control.execute_async(&self.io).await?;
220        let mut download_loop = cmd.chain(&self.buffer[..n])??;
221
222        loop {
223            download_loop = match download_loop.next() {
224                download::Step::Break => break Ok(Some(self)),
225                download::Step::Erase(cmd) => {
226                    let (cmd, control) = cmd.erase()?;
227                    control.execute_async(&self.io).await?;
228                    wait_status!(cmd)
229                }
230                download::Step::SetAddress(cmd) => {
231                    let (cmd, control) = cmd.set_address();
232                    control.execute_async(&self.io).await?;
233                    wait_status!(cmd)
234                }
235                download::Step::DownloadChunk(cmd) => {
236                    let chunk = reader.fill_buf().await?;
237                    let (cmd, control) = cmd.download(chunk)?;
238                    let n = control.execute_async(&self.io).await?;
239                    reader.consume(n);
240                    wait_status!(cmd)
241                }
242                download::Step::UsbReset => {
243                    log::trace!("Device reset");
244                    self.io.usb_reset().await?;
245                    break Ok(None);
246                }
247            }
248        }
249    }
250
251    /// Download a firmware into the device.
252    ///
253    /// The length is inferred from the reader. Returns `Some(Self)` if the device stayed on the
254    /// bus (manifestation tolerant, no USB reset occurred) or `None` if a USB reset was performed.
255    pub async fn download_all<R: AsyncReadExt + Unpin + AsyncSeek>(
256        self,
257        mut reader: R,
258    ) -> Result<Option<Self>, IO::Error> {
259        let length = u32::try_from(reader.seek(std::io::SeekFrom::End(0)).await?)
260            .map_err(|_| Error::MaximumTransferSizeExceeded)?;
261        reader.seek(std::io::SeekFrom::Start(0)).await?;
262        self.download(reader, length).await
263    }
264
265    /// Send a Detach request to the device
266    pub async fn detach(&self) -> Result<(), IO::Error> {
267        self.dfu.detach().execute_async(&self.io).await?;
268        Ok(())
269    }
270
271    /// Reset the USB device
272    pub async fn usb_reset(self) -> Result<IO::Reset, IO::Error> {
273        self.io.usb_reset().await
274    }
275
276    /// Returns whether the device will detach if requested
277    pub fn will_detach(&self) -> bool {
278        self.io.functional_descriptor().will_detach
279    }
280
281    /// Returns whether the device is manifestation tolerant
282    pub fn manifestation_tolerant(&self) -> bool {
283        self.io.functional_descriptor().manifestation_tolerant
284    }
285}