Skip to main content

usb_dfu_target/
lib.rs

1#![no_std]
2
3use consts::{DfuRequest, DfuStatus};
4#[cfg(feature = "defmt")]
5use defmt::{debug, error, info};
6
7pub mod consts;
8
9/// Internal State used to keep track of DFU State
10enum InternalState {
11    Idle,
12    DownloadBusy(DownloadState),
13    Download(DownloadState),
14    Upload { offset: usize },
15    Error,
16}
17
18impl Into<consts::State> for &InternalState {
19    fn into(self) -> consts::State {
20        use consts::State;
21
22        match self {
23            InternalState::Idle => State::DfuIdle,
24            InternalState::DownloadBusy(_) => State::DownloadBusy,
25            InternalState::Download(_) => State::DownloadIdle,
26            InternalState::Upload { .. } => State::UploadIdle,
27            InternalState::Error => State::Error,
28        }
29    }
30}
31
32/// Internal state for download offset bookkeeping
33struct DownloadState {
34    offset: usize,
35}
36
37/// This is the trait the user of this library should implement
38/// to handle the specifics of the hardware programming.
39/// i.e. writing to flash
40pub trait DfuHandler {
41    /// This function should not block for extended period of time
42    fn write_data(&mut self, offset: usize, data: &[u8]);
43    /// Return if the previous write is done
44    fn is_write_complete(&self) -> bool {
45        true
46    }
47
48    /// Callback to complete a download request.
49    /// Corresponds to the manifest stage of USB DFU.
50    fn complete_download(&mut self);
51
52    /// Read bytes into buffer from offset, return the number of bytes read.
53    fn upload(&self, buffer: &mut [u8], offset: usize) -> usize;
54}
55
56/// USB Device in DFU mode
57pub struct UsbDfuDevice<'a> {
58    state: InternalState,
59    handler: &'a mut dyn DfuHandler,
60}
61
62impl<'a> UsbDfuDevice<'a> {
63    pub fn new(handler: &'a mut dyn DfuHandler) -> Self {
64        UsbDfuDevice {
65            state: InternalState::Idle,
66            handler,
67        }
68    }
69
70    fn handle_download(
71        &mut self,
72        DownloadState { offset }: DownloadState,
73        buf: &[u8],
74    ) -> (InternalState, Result<(), ()>) {
75        if buf.len() == 0 {
76            return (InternalState::Idle, Ok(()));
77        }
78
79        self.handler.write_data(offset, buf);
80        return (
81            InternalState::DownloadBusy(DownloadState {
82                offset: offset + buf.len(),
83            }),
84            Ok(()),
85        );
86    }
87
88    pub fn handle_control_out(&mut self, req: DfuRequest, data: &[u8]) -> Result<(), ()> {
89        let (state, response) = match core::mem::replace(&mut self.state, InternalState::Error) {
90            InternalState::Idle => match req {
91                DfuRequest::Dnload => self.handle_download(DownloadState { offset: 0 }, data),
92                DfuRequest::Abort => (InternalState::Idle, Ok(())),
93                r => {
94                    #[cfg(feature = "defmt")]
95                    error!("received {} at state idle", r as u8);
96                    // TODO: set this to error state
97                    (InternalState::Idle, Err(()))
98                }
99            },
100            InternalState::Download(download_state) => match req {
101                DfuRequest::Dnload => self.handle_download(download_state, data),
102                DfuRequest::Abort => (InternalState::Idle, Ok(())),
103                r => {
104                    #[cfg(feature = "defmt")]
105                    error!("received {} at state download", r as u8);
106                    (InternalState::Error, Err(()))
107                }
108            },
109            state => {
110                #[cfg(feature = "defmt")]
111                error!("received {} for control out", req as u8);
112
113                (state, Err(()))
114            }
115        };
116        self.state = state;
117        response
118    }
119
120    pub fn handle_control_in<'b>(
121        &mut self,
122        req: DfuRequest,
123        buf: &'b mut [u8],
124    ) -> Result<&'b [u8], ()> {
125        match req {
126            DfuRequest::GetState => {
127                buf[0] = Into::<consts::State>::into(&self.state) as u8;
128                Ok(&buf[0..1])
129            }
130            DfuRequest::GetStatus => {
131                let (next_state, status) =
132                    match core::mem::replace(&mut self.state, InternalState::Error) {
133                        InternalState::DownloadBusy(download_state) => {
134                            match self.handler.is_write_complete() {
135                                true => (InternalState::Download(download_state), DfuStatus::Ok),
136                                false => {
137                                    (InternalState::DownloadBusy(download_state), DfuStatus::Ok)
138                                }
139                            }
140                        }
141                        InternalState::Error => (InternalState::Error, DfuStatus::ErrUnknown),
142                        state => (state, DfuStatus::Ok),
143                    };
144                self.state = next_state;
145                let next_state = Into::<consts::State>::into(&self.state);
146                buf[0] = status as u8; // bStatus
147
148                // This is cursed.... basically the highest byte is overriden by the next line
149                buf[1..5].copy_from_slice(&(250_u32.to_le_bytes())); // [1..4] bwPoolTimeout
150                buf[4] = next_state as u8; // bstate
151                buf[5] = 0; // iString
152
153                Ok(&buf[0..6])
154            }
155            req => {
156                let (state, response): (InternalState, Result<&'a [u8], ()>) =
157                    match core::mem::replace(&mut self.state, InternalState::Error) {
158                        InternalState::Idle => todo!(),
159                        InternalState::DownloadBusy(download_state) => todo!(),
160                        InternalState::Download(download_state) => todo!(),
161                        InternalState::Upload { offset } => todo!(),
162                        InternalState::Error => todo!(),
163                    };
164            }
165        }
166    }
167}