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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
//! What every flashing backend offers: connect, erase, write, verify and reset, with progress.
use alloc::string::String;
use alloc::vec::Vec;
use core::convert::Infallible;
use core::marker::PhantomData;
use serde::Serialize;
#[cfg(feature = "avr")]
use crate::avr::{AvrBackend, AvrOptions};
use crate::error::Error;
#[cfg(feature = "espressif")]
use crate::espressif::{EspressifBackend, EspressifOptions};
use crate::manifest::{Protocol, ResetSequence};
#[cfg(feature = "samba")]
use crate::samba::{SambaBackend, SambaOptions};
use crate::transport::{DeviceFilter, PortProvider, UsbIdentity};
/// One image to write: its name for messages, where it goes and its bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Segment<'a> {
/// The name of the image, for messages and progress.
pub label: &'a str,
/// The flash offset of its first byte.
pub offset: u64,
/// Its bytes.
pub data: &'a [u8],
}
/// A range of flash.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Region {
/// The flash offset of the first byte.
pub offset: u64,
/// The number of bytes.
pub size: u64,
}
/// What a backend is doing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Stage {
/// Resetting into the bootloader and detecting the chip.
Connecting,
/// Erasing flash.
Erasing,
/// Writing images.
Writing,
/// Checking what was written.
Verifying,
/// Resetting into the application.
Resetting,
}
/// How far a stage has gone.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct ProgressEvent {
/// The stage.
pub stage: Stage,
/// The flash offset the stage works on.
pub offset: u64,
/// The bytes done so far.
pub done: u64,
/// The bytes the stage handles in all.
pub total: u64,
}
/// Receives progress events and messages from a backend.
pub trait Progress {
/// A stage moved on.
fn report(&mut self, event: ProgressEvent);
/// Something the user may want to know, such as a setting the backend could not apply.
fn message(&mut self, text: &str) {
let _ = text;
}
}
impl Progress for () {
fn report(&mut self, _event: ProgressEvent) {}
}
impl<F: FnMut(ProgressEvent)> Progress for F {
fn report(&mut self, event: ProgressEvent) {
self(event);
}
}
/// What `connect` found out about the board.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ChipInformation {
/// The protocol the backend speaks.
pub protocol: Protocol,
/// The chip, such as `esp32-s3`.
pub chip: String,
/// The size of the flash in bytes, when the backend could read it.
pub flash_size: Option<u64>,
/// Whether the chip only accepts the commands of the secure download mode.
pub secure_download_mode: bool,
/// The USB identity of the port, when it has one.
pub usb: Option<UsbIdentity>,
/// The lowest flash offset the bootloader writes, when it protects the flash below it
/// (SAM-BA bootloaders protect themselves); `None` when the whole flash is writable.
pub writable_from: Option<u64>,
/// The end of the flash the bootloader writes, when it sits at the top of the flash (AVR
/// bootloaders); `None` when the flash up to `flash_size` is writable.
pub writable_to: Option<u64>,
/// Whether the bootloader erases from an offset to the end of flash, never a region alone
/// (the SAMD21's SAM-BA bootloader): every erase must then end at the end of flash.
pub erases_to_end: bool,
}
/// A flashing backend.
// Futures are not Send: browser APIs are single-threaded
// (docs/src/explanation/design-decisions.md, Constraints).
#[allow(async_fn_in_trait)]
pub trait Backend {
/// Resets the board into its bootloader and detects the chip.
async fn connect(&mut self) -> Result<ChipInformation, Error>;
/// Erases `region`, reporting through `progress` how far it went when the backend can tell.
async fn erase(&mut self, region: Region, progress: &mut dyn Progress) -> Result<(), Error>;
/// Writes `segments`, in order.
async fn write(
&mut self,
segments: &[Segment<'_>],
progress: &mut dyn Progress,
) -> Result<(), Error>;
/// Checks that the flash holds `segments`.
async fn verify(
&mut self,
segments: &[Segment<'_>],
progress: &mut dyn Progress,
) -> Result<(), Error>;
/// Leaves the bootloader and starts the application.
async fn reset_to_application(&mut self) -> Result<(), Error>;
/// Checks, after `connect` and before anything is erased or written, a whole flash as
/// [`flash`](crate::flash::flash) sends it: `erase_all` (`--erase-all`), then `erases` in
/// order, then `segments` in order, one `write` each. A backend whose bootloader only takes
/// erases and writes in some order (the Mega 2560's) refuses here a flash it would refuse
/// part-way; the others accept any, and check each call again.
fn check_plan(
&self,
erase_all: Option<Region>,
erases: &[Region],
segments: &[Segment<'_>],
) -> Result<(), Error> {
let _ = (erase_all, erases, segments);
Ok(())
}
}
/// How every backend connects.
#[derive(Debug, Clone, Default)]
pub struct BackendOptions {
/// The baud rate to switch to after connecting; `None` lets the backend choose. The
/// Espressif backend then uses 460800 through a USB-to-UART bridge, and 115200 on
/// USB-Serial-JTAG and the ESP32-C2, which keep 115200 whatever is requested. On STK500v1
/// and STK500v2, the rate of the bootloader (by default 115200, then 57600 on STK500v1);
/// ignored on AVR109.
pub baud_rate: Option<u32>,
/// The USB identities the board shows in its bootloader, for resets that re-enumerate;
/// `flash` fills it from the manifest when empty.
pub bootloader_devices: Vec<DeviceFilter>,
}
/// The backends compiled in, chosen by protocol.
pub enum Backends<'p, P: PortProvider> {
/// The Espressif ROM loader.
#[cfg(feature = "espressif")]
Espressif(EspressifBackend<'p, P>),
/// Arduino's SAM-BA bootloaders.
#[cfg(feature = "samba")]
Samba(SambaBackend<'p, P>),
/// The STK500v1, STK500v2 and AVR109 bootloaders of Arduino's AVR boards.
#[cfg(feature = "avr")]
Avr(AvrBackend<'p, P>),
/// No backend: keeps the type parameters used when every backend is left out.
#[doc(hidden)]
Unavailable(Infallible, PhantomData<&'p mut P>),
}
impl<'p, P: PortProvider> Backends<'p, P> {
/// The backend of `protocol` over `port`, which `provider` can reopen; `reset` is the reset
/// sequence of the board, or `None` to let the backend choose from the port.
pub fn new(
protocol: Protocol,
port: P::Port,
provider: &'p mut P,
reset: Option<ResetSequence>,
options: &BackendOptions,
) -> Result<Self, Error> {
match protocol {
#[cfg(feature = "espressif")]
Protocol::Espressif => {
let options = EspressifOptions {
baud_rate: options.baud_rate,
..EspressifOptions::default()
};
EspressifBackend::new(port, provider, reset, options).map(Backends::Espressif)
}
#[cfg(feature = "samba")]
Protocol::Samba => {
let options = SambaOptions {
bootloader_devices: options.bootloader_devices.clone(),
baud_rate: options.baud_rate,
};
SambaBackend::new(port, provider, reset, options).map(Backends::Samba)
}
#[cfg(feature = "avr")]
Protocol::Stk500v1 | Protocol::Stk500v2 | Protocol::Avr109 => {
let options = AvrOptions {
baud_rate: options.baud_rate,
bootloader_devices: options.bootloader_devices.clone(),
};
AvrBackend::new(protocol, port, provider, reset, options).map(Backends::Avr)
}
// With every backend compiled in, every protocol is matched above and this arm would
// be unreachable.
#[cfg(not(all(feature = "espressif", feature = "samba", feature = "avr")))]
protocol => {
let _ = (port, provider, reset, options);
Err(Error::ProtocolNotEnabled { protocol })
}
}
}
/// Resets the board into its bootloader and detects the chip, reporting through `progress`
/// the settings the backend could not apply.
pub async fn connect(&mut self, progress: &mut dyn Progress) -> Result<ChipInformation, Error> {
match self {
#[cfg(feature = "espressif")]
Backends::Espressif(backend) => backend.connect(progress).await,
#[cfg(feature = "samba")]
Backends::Samba(backend) => backend.connect(progress).await,
#[cfg(feature = "avr")]
Backends::Avr(backend) => backend.connect(progress).await,
Backends::Unavailable(never, _) => {
let _ = progress;
match *never {}
}
}
}
/// Resets the board into its bootloader and detects the chip, without changing the baud
/// rate: enough to tell the chip.
pub async fn identify(
&mut self,
progress: &mut dyn Progress,
) -> Result<ChipInformation, Error> {
match self {
#[cfg(feature = "espressif")]
Backends::Espressif(backend) => backend.identify(progress).await,
// SAM-BA changes no baud rate: identifying is connecting.
#[cfg(feature = "samba")]
Backends::Samba(backend) => backend.connect(progress).await,
// The AVR backend keeps the rate its bootloader answered at: identifying is connecting.
#[cfg(feature = "avr")]
Backends::Avr(backend) => backend.connect(progress).await,
Backends::Unavailable(never, _) => {
let _ = progress;
match *never {}
}
}
}
}
impl<P: PortProvider> Backend for Backends<'_, P> {
async fn connect(&mut self) -> Result<ChipInformation, Error> {
Backends::connect(self, &mut ()).await
}
async fn erase(&mut self, region: Region, progress: &mut dyn Progress) -> Result<(), Error> {
match self {
#[cfg(feature = "espressif")]
Backends::Espressif(backend) => backend.erase(region, progress).await,
#[cfg(feature = "samba")]
Backends::Samba(backend) => backend.erase(region, progress).await,
#[cfg(feature = "avr")]
Backends::Avr(backend) => backend.erase(region, progress).await,
Backends::Unavailable(never, _) => {
let _ = (region, progress);
match *never {}
}
}
}
async fn write(
&mut self,
segments: &[Segment<'_>],
progress: &mut dyn Progress,
) -> Result<(), Error> {
match self {
#[cfg(feature = "espressif")]
Backends::Espressif(backend) => backend.write(segments, progress).await,
#[cfg(feature = "samba")]
Backends::Samba(backend) => backend.write(segments, progress).await,
#[cfg(feature = "avr")]
Backends::Avr(backend) => backend.write(segments, progress).await,
Backends::Unavailable(never, _) => {
let _ = (segments, progress);
match *never {}
}
}
}
async fn verify(
&mut self,
segments: &[Segment<'_>],
progress: &mut dyn Progress,
) -> Result<(), Error> {
match self {
#[cfg(feature = "espressif")]
Backends::Espressif(backend) => backend.verify(segments, progress).await,
#[cfg(feature = "samba")]
Backends::Samba(backend) => backend.verify(segments, progress).await,
#[cfg(feature = "avr")]
Backends::Avr(backend) => backend.verify(segments, progress).await,
Backends::Unavailable(never, _) => {
let _ = (segments, progress);
match *never {}
}
}
}
async fn reset_to_application(&mut self) -> Result<(), Error> {
match self {
#[cfg(feature = "espressif")]
Backends::Espressif(backend) => backend.reset_to_application().await,
#[cfg(feature = "samba")]
Backends::Samba(backend) => backend.reset_to_application().await,
#[cfg(feature = "avr")]
Backends::Avr(backend) => backend.reset_to_application().await,
Backends::Unavailable(never, _) => match *never {},
}
}
fn check_plan(
&self,
erase_all: Option<Region>,
erases: &[Region],
segments: &[Segment<'_>],
) -> Result<(), Error> {
match self {
#[cfg(feature = "espressif")]
Backends::Espressif(backend) => backend.check_plan(erase_all, erases, segments),
#[cfg(feature = "samba")]
Backends::Samba(backend) => backend.check_plan(erase_all, erases, segments),
#[cfg(feature = "avr")]
Backends::Avr(backend) => backend.check_plan(erase_all, erases, segments),
Backends::Unavailable(never, _) => {
let _ = (erase_all, erases, segments);
match *never {}
}
}
}
}