nanoflash 0.1.2

Lay out the flash of ESP32 and Arduino boards and write firmware to them through their bootloaders, natively or in the browser over Web Serial.
Documentation
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! Choosing the boards of a manifest that suit a device.

use alloc::string::ToString;
use alloc::vec::Vec;

use crate::error::Error;
use crate::manifest::{Board, Manifest, Protocol, ResetSequence};
use crate::transport::UsbIdentity;

/// The Arduino AVR boards by USB identity, as `boards.txt` of ArduinoCore-avr (11b9130) lists
/// them under `vid.N` and `pid.N`: the Arduino vendors `0x2341` and `0x2A03` (a pair
/// `boards.txt` does not list is left out, so `2A03:0242` is not here) and the SparkFun, LilyPad
/// and Adafruit vendors. Other Arduino products run SAM-BA.
const ARDUINO_AVR: &[(u16, u16, Protocol)] = &[
    // `uno`: Optiboot.
    (0x2341, 0x0043, Protocol::Stk500v1),
    (0x2341, 0x0001, Protocol::Stk500v1),
    (0x2A03, 0x0043, Protocol::Stk500v1),
    (0x2341, 0x0243, Protocol::Stk500v1),
    (0x2341, 0x006A, Protocol::Stk500v1),
    // `unomini`.
    (0x2341, 0x0062, Protocol::Stk500v1),
    // `mega` (the wiring bootloader).
    (0x2341, 0x0010, Protocol::Stk500v2),
    (0x2341, 0x0042, Protocol::Stk500v2),
    (0x2A03, 0x0010, Protocol::Stk500v2),
    (0x2A03, 0x0042, Protocol::Stk500v2),
    (0x2341, 0x0210, Protocol::Stk500v2),
    (0x2341, 0x0242, Protocol::Stk500v2),
    // `megaADK`.
    (0x2341, 0x003F, Protocol::Stk500v2),
    (0x2341, 0x0044, Protocol::Stk500v2),
    (0x2A03, 0x003F, Protocol::Stk500v2),
    (0x2A03, 0x0044, Protocol::Stk500v2),
    // Caterina boards: `leonardo` 0036/8036, `micro` 0037/8037 and 0237/8237 (2341 only).
    (0x2341, 0x0036, Protocol::Avr109),
    (0x2341, 0x8036, Protocol::Avr109),
    (0x2341, 0x0037, Protocol::Avr109),
    (0x2341, 0x8037, Protocol::Avr109),
    (0x2A03, 0x0036, Protocol::Avr109),
    (0x2A03, 0x8036, Protocol::Avr109),
    (0x2A03, 0x0037, Protocol::Avr109),
    (0x2A03, 0x8037, Protocol::Avr109),
    (0x2341, 0x0237, Protocol::Avr109),
    (0x2341, 0x8237, Protocol::Avr109),
    // `leonardoeth`, `yunmini` and `chiwawa` (Industrial 101): 2A03 only.
    (0x2A03, 0x0040, Protocol::Avr109),
    (0x2A03, 0x8040, Protocol::Avr109),
    (0x2A03, 0x0050, Protocol::Avr109),
    (0x2A03, 0x8050, Protocol::Avr109),
    (0x2A03, 0x0056, Protocol::Avr109),
    (0x2A03, 0x8056, Protocol::Avr109),
    // `yun` 0041/8041, `esplora` 003C/803C, `robotControl` 0038/8038, `robotMotor` 0039/8039.
    (0x2341, 0x0041, Protocol::Avr109),
    (0x2341, 0x8041, Protocol::Avr109),
    (0x2341, 0x003C, Protocol::Avr109),
    (0x2341, 0x803C, Protocol::Avr109),
    (0x2341, 0x0038, Protocol::Avr109),
    (0x2341, 0x8038, Protocol::Avr109),
    (0x2341, 0x0039, Protocol::Avr109),
    (0x2341, 0x8039, Protocol::Avr109),
    (0x2A03, 0x0041, Protocol::Avr109),
    (0x2A03, 0x8041, Protocol::Avr109),
    (0x2A03, 0x003C, Protocol::Avr109),
    (0x2A03, 0x803C, Protocol::Avr109),
    (0x2A03, 0x0038, Protocol::Avr109),
    (0x2A03, 0x8038, Protocol::Avr109),
    (0x2A03, 0x0039, Protocol::Avr109),
    (0x2A03, 0x8039, Protocol::Avr109),
    // `circuitplay32u4cat` (Adafruit), `LilyPadUSB` (SparkFun) and the SparkFun Pro Micro.
    (0x239A, 0x8011, Protocol::Avr109),
    (0x1B4F, 0x9207, Protocol::Avr109),
    (0x1B4F, 0x9208, Protocol::Avr109),
    (0x1B4F, 0x9203, Protocol::Avr109),
    (0x1B4F, 0x9204, Protocol::Avr109),
    (0x1B4F, 0x9205, Protocol::Avr109),
    (0x1B4F, 0x9206, Protocol::Avr109),
];

/// The protocol the USB identity speaks, when it is known: an AVR board of the table, else the
/// protocol of its vendor.
pub fn protocol_for_identity(identity: &UsbIdentity) -> Option<Protocol> {
    if let Some((_, _, protocol)) = ARDUINO_AVR
        .iter()
        .find(|(vendor, product, _)| *vendor == identity.vendor && *product == identity.product)
    {
        return Some(*protocol);
    }
    match identity.vendor {
        0x303a => Some(Protocol::Espressif),
        0x2341 => Some(Protocol::Samba),
        _ => None,
    }
}

/// The boards that may be the device.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Selection<'m> {
    /// The protocol every board speaks.
    pub protocol: Protocol,
    /// The candidate boards, in manifest order.
    pub boards: Vec<&'m Board>,
    /// The reset the boards share, when they all agree.
    pub reset: Option<ResetSequence>,
}

/// Whether a board without a USB identity may sit behind a serial bridge.
fn suits_bridge(board: &Board) -> bool {
    matches!(
        board.reset,
        None | Some(ResetSequence::EspressifClassic)
            | Some(ResetSequence::None)
            | Some(ResetSequence::Custom(_))
    ) && board.application_devices.is_empty()
        && board.bootloader_devices.is_empty()
}

/// Selects the boards of `manifest` for a device.
///
/// With `board_identifier`, exactly that board. Otherwise the boards that list the device, or,
/// when none does or the device has no identity, the boards that suit a serial bridge.
pub fn select<'m>(
    manifest: &'m Manifest,
    identity: Option<&UsbIdentity>,
    board_identifier: Option<&str>,
) -> Result<Selection<'m>, Error> {
    let boards: Vec<&Board> = match board_identifier {
        Some(identifier) => {
            let board = manifest
                .boards
                .iter()
                .find(|board| board.identifier == identifier)
                .ok_or_else(|| Error::UnknownBoard {
                    identifier: identifier.to_string(),
                    known: manifest
                        .boards
                        .iter()
                        .map(|board| board.identifier.clone())
                        .collect(),
                })?;
            alloc::vec![board]
        }
        None => {
            let listed: Vec<&Board> = match identity {
                Some(identity) => manifest
                    .boards
                    .iter()
                    .filter(|board| {
                        board
                            .application_devices
                            .iter()
                            .chain(&board.bootloader_devices)
                            .any(|filter| filter.matches(identity))
                    })
                    .collect(),
                None => Vec::new(),
            };
            if listed.is_empty() {
                manifest
                    .boards
                    .iter()
                    .filter(|board| suits_bridge(board))
                    .collect()
            } else {
                listed
            }
        }
    };
    let Some(first) = boards.first() else {
        return Err(Error::NoMatchingBoard {
            identity: identity.cloned(),
        });
    };
    let mut protocols: Vec<Protocol> = boards.iter().map(|board| board.protocol).collect();
    protocols.sort();
    protocols.dedup();
    if protocols.len() > 1 {
        return Err(Error::SeveralProtocols { protocols });
    }
    let reset = if boards.iter().all(|board| board.reset == first.reset) {
        first.reset.clone()
    } else {
        None
    };
    Ok(Selection {
        protocol: first.protocol,
        boards,
        reset,
    })
}

impl<'m> Selection<'m> {
    /// The board whose chip is `chip`, as the backend detected it.
    pub fn pick(&self, chip: &str) -> Result<&'m Board, Error> {
        let mut matching = self
            .boards
            .iter()
            .copied()
            .filter(|board| board.matches_chip(chip));
        let Some(first) = matching.next() else {
            return Err(Error::WrongChip {
                detected: chip.to_string(),
                expected: self.boards.iter().map(|board| board.chip.clone()).collect(),
            });
        };
        if matching.next().is_none() {
            return Ok(first);
        }
        Err(Error::SeveralBoards {
            chip: chip.to_string(),
            boards: self
                .boards
                .iter()
                .filter(|board| board.matches_chip(chip))
                .map(|board| board.identifier.clone())
                .collect(),
        })
    }
}

#[cfg(all(test, feature = "testing", feature = "json"))]
mod tests {
    use super::*;

    const WEB_TOOLS: &str = include_str!("../../tests/boards/esp-web-tools.json");

    fn identity(vendor: u16, product: u16) -> UsbIdentity {
        UsbIdentity {
            vendor,
            product,
            serial_number: None,
        }
    }

    fn two_boards() -> Manifest {
        Manifest::from_toml(
            r#"
[[board]]
identifier = "s3"
protocol = "espressif"
chip = "esp32-s3"
application-devices = [{ vendor = 0x303a, product = 0x1001 }]
[[board.image]]
offset = 0
path = "a.bin"

[[board]]
identifier = "samba"
protocol = "samba"
chip = "samd21"
bootloader-devices = [{ vendor = 0x2341, product = 0x805a }]
[[board.image]]
offset = 0
path = "a.bin"
"#,
        )
        .unwrap()
    }

    #[test]
    fn usb_identity_picks_the_board() {
        let manifest = two_boards();
        let selection = select(&manifest, Some(&identity(0x303a, 0x1001)), None).unwrap();
        assert_eq!(selection.protocol, Protocol::Espressif);
        assert_eq!(selection.boards.len(), 1);
        assert_eq!(selection.boards[0].identifier, "s3");
        let selection = select(&manifest, Some(&identity(0x2341, 0x805a)), None).unwrap();
        assert_eq!(selection.protocol, Protocol::Samba);
    }

    #[test]
    fn bridges_fall_back_to_classic_boards() {
        let manifest = Manifest::from_toml(
            r#"
[[board]]
identifier = "classic"
protocol = "espressif"
chip = "esp32"
reset = "espressif-classic"
[[board.image]]
offset = 0
path = "a.bin"

[[board]]
identifier = "unset"
protocol = "espressif"
chip = "esp32-s3"
[[board.image]]
offset = 0
path = "a.bin"

[[board]]
identifier = "jtag"
protocol = "espressif"
chip = "esp32-c3"
reset = "espressif-usb-serial-jtag"
[[board.image]]
offset = 0
path = "a.bin"

[[board]]
identifier = "listed"
protocol = "espressif"
chip = "esp32-c6"
application-devices = [{ vendor = 0x303a }]
[[board.image]]
offset = 0
path = "a.bin"
"#,
        )
        .unwrap();
        let selection = select(&manifest, Some(&identity(0x10c4, 0xea60)), None).unwrap();
        let identifiers: Vec<&str> = selection
            .boards
            .iter()
            .map(|board| board.identifier.as_str())
            .collect();
        assert_eq!(identifiers, ["classic", "unset"]);
        assert_eq!(selection.reset, None);
        let without = select(&manifest, None, None).unwrap();
        assert_eq!(without.boards.len(), 2);
        let only = select(&manifest, None, Some("classic")).unwrap();
        assert_eq!(only.reset, Some(ResetSequence::EspressifClassic));
        let error = select(&manifest, None, Some("nope")).unwrap_err();
        assert!(matches!(error, Error::UnknownBoard { ref known, .. } if known.len() == 4));
    }

    #[test]
    fn several_protocols_need_an_identifier() {
        let manifest = Manifest::from_toml(
            r#"
[[board]]
identifier = "a"
protocol = "espressif"
chip = "esp32"
[[board.image]]
offset = 0
path = "a.bin"

[[board]]
identifier = "b"
protocol = "samba"
chip = "samd21"
reset = "none"
[[board.image]]
offset = 0
path = "a.bin"
"#,
        )
        .unwrap();
        assert_eq!(
            select(&manifest, None, None).unwrap_err(),
            Error::SeveralProtocols {
                protocols: alloc::vec![Protocol::Espressif, Protocol::Samba]
            }
        );
        assert!(select(&manifest, None, Some("a")).is_ok());
        assert_eq!(
            select(&two_boards(), Some(&identity(0x0483, 0xdf11)), None).unwrap_err(),
            Error::NoMatchingBoard {
                identity: Some(identity(0x0483, 0xdf11))
            }
        );
    }

    #[test]
    fn pick_by_detected_chip() {
        let manifest = Manifest::from_json(WEB_TOOLS).unwrap();
        let selection = select(&manifest, None, None).unwrap();
        assert_eq!(selection.boards.len(), 2);
        assert_eq!(selection.pick("esp32-s3").unwrap().chip, "esp32-s3");
        let error = selection.pick("esp32-c6").unwrap_err();
        assert_eq!(
            error,
            Error::WrongChip {
                detected: "esp32-c6".into(),
                expected: alloc::vec!["esp32".into(), "esp32-s3".into()],
            }
        );
        assert_eq!(error.class(), crate::ErrorClass::Device);
        let duplicated = Manifest::from_toml(
            r#"
[[board]]
identifier = "a"
protocol = "espressif"
chip = "esp32"
[[board.image]]
offset = 0
path = "a.bin"
[[board]]
identifier = "b"
protocol = "espressif"
chip = "ESP32"
[[board.image]]
offset = 0
path = "a.bin"
"#,
        )
        .unwrap();
        assert_eq!(
            select(&duplicated, None, None)
                .unwrap()
                .pick("esp32")
                .unwrap_err(),
            Error::SeveralBoards {
                chip: "esp32".into(),
                boards: alloc::vec!["a".into(), "b".into()],
            }
        );
    }

    #[test]
    fn identity_table() {
        assert_eq!(
            protocol_for_identity(&identity(0x303a, 0x1001)),
            Some(Protocol::Espressif)
        );
        assert_eq!(
            protocol_for_identity(&identity(0x2341, 0x805a)),
            Some(Protocol::Samba)
        );
        assert_eq!(protocol_for_identity(&identity(0x0483, 0xdf11)), None);
    }

    #[test]
    fn arduino_avr_identities_pick_their_protocol() {
        for (vendor, product, protocol) in [
            (0x2341, 0x0043, Some(Protocol::Stk500v1)),
            (0x2a03, 0x0042, Some(Protocol::Stk500v2)),
            (0x2341, 0x8036, Some(Protocol::Avr109)),
            (0x1b4f, 0x9206, Some(Protocol::Avr109)),
            (0x2341, 0x805a, Some(Protocol::Samba)),
            (0x2341, 0x006a, Some(Protocol::Stk500v1)),
            (0x2341, 0x0062, Some(Protocol::Stk500v1)),
            (0x2341, 0x0044, Some(Protocol::Stk500v2)),
            (0x2a03, 0x003f, Some(Protocol::Stk500v2)),
            (0x2341, 0x0041, Some(Protocol::Avr109)),
            (0x2a03, 0x8056, Some(Protocol::Avr109)),
            (0x239a, 0x8011, Some(Protocol::Avr109)),
            (0x1b4f, 0x9207, Some(Protocol::Avr109)),
            // Pairs boards.txt does not list: the vendor decides.
            (0x2a03, 0x0242, None),
            (0x2a03, 0x0001, None),
            (0x2a03, 0x0057, None),
            (0x2341, 0x0040, Some(Protocol::Samba)),
            (0x1a86, 0x7523, None),
        ] {
            assert_eq!(
                protocol_for_identity(&identity(vendor, product)),
                protocol,
                "{vendor:04x}:{product:04x}"
            );
        }
    }
}