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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! The serial transport of the host, over the `serialport` crate.
//!
//! These calls block: reading waits for the port timeout and sleeping parks the thread. That is
//! harmless on the command line's single-threaded executor. A library user in a multi-threaded
//! runtime runs the flashing on a dedicated thread.

use std::boxed::Box;
use std::io::{ErrorKind, Read, Write};
use std::string::{String, ToString};
use std::time::Instant;
use std::vec::Vec;

use serde::Serialize;
use serialport::{SerialPortType, UsbPortInfo};

use crate::transport::{
    DeviceFilter, Duration, PortProvider, SerialPort, Signals, TransportError, UsbIdentity,
};

/// How often the provider looks for a device that has not appeared yet.
const POLL_INTERVAL: Duration = Duration::from_millis(100);

/// How long one write may wait for the device to accept data.
const WRITE_TIMEOUT: Duration = Duration::from_secs(1);

/// How many writes in a row may make no progress before the port is given up on.
const WRITE_STALLS: u32 = 5;

/// A serial port of the host.
pub struct NativeSerialPort {
    port: Box<dyn serialport::SerialPort>,
    path: String,
    identity: Option<UsbIdentity>,
    timeout: Duration,
}

/// A serial port found on the host.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PortInformation {
    /// The device path (`/dev/ttyACM0`, `COM3`).
    pub path: String,
    /// The USB identity, for USB ports.
    pub identity: Option<UsbIdentity>,
    /// The product name the device reports, when it does.
    pub product: Option<String>,
}

fn identity_of(information: &UsbPortInfo) -> UsbIdentity {
    UsbIdentity {
        vendor: information.vid,
        product: information.pid,
        serial_number: information.serial_number.clone(),
    }
}

fn is_disconnection(error: &std::io::Error) -> bool {
    matches!(
        error.kind(),
        ErrorKind::BrokenPipe | ErrorKind::NotConnected | ErrorKind::UnexpectedEof
    ) || matches!(error.raw_os_error(), Some(5 | 6 | 19))
}

fn io_error(path: &str, error: &std::io::Error) -> TransportError {
    if is_disconnection(error) {
        TransportError::Disconnected
    } else {
        TransportError::Io {
            message: std::format!("{path}: {error}"),
        }
    }
}

fn serial_error(path: &str, error: &serialport::Error) -> TransportError {
    match error.kind() {
        serialport::ErrorKind::NoDevice => TransportError::Disconnected,
        serialport::ErrorKind::Io(kind) if is_disconnection(&std::io::Error::from(kind)) => {
            TransportError::Disconnected
        }
        _ => TransportError::Io {
            message: std::format!("{path}: {error}"),
        },
    }
}

/// The serial ports of the host.
pub fn list_ports() -> Result<Vec<PortInformation>, TransportError> {
    let ports = serialport::available_ports().map_err(|error| TransportError::Io {
        message: std::format!("cannot list the serial ports: {error}"),
    })?;
    Ok(ports
        .into_iter()
        .map(|port| {
            let (identity, product) = match &port.port_type {
                SerialPortType::UsbPort(usb) => (Some(identity_of(usb)), usb.product.clone()),
                _ => (None, None),
            };
            PortInformation {
                path: port.port_name,
                identity,
                product,
            }
        })
        .collect())
}

impl NativeSerialPort {
    /// Opens the port at `path` with 8 data bits, no parity and one stop bit.
    pub fn open(path: &str, baud_rate: u32) -> Result<NativeSerialPort, TransportError> {
        NativeSerialPort::open_with_identity(path, baud_rate, identity_by_path(path))
    }

    fn open_with_identity(
        path: &str,
        baud_rate: u32,
        identity: Option<UsbIdentity>,
    ) -> Result<NativeSerialPort, TransportError> {
        let timeout = Duration::from_millis(100);
        let port = serialport::new(path, baud_rate)
            .timeout(timeout)
            .open()
            .map_err(|error| serial_error(path, &error))?;
        Ok(NativeSerialPort {
            port,
            path: path.to_string(),
            identity,
            timeout,
        })
    }

    #[cfg(all(test, unix))]
    fn from_port(port: Box<dyn serialport::SerialPort>, path: &str) -> NativeSerialPort {
        NativeSerialPort {
            port,
            path: path.to_string(),
            identity: None,
            timeout: Duration::from_millis(100),
        }
    }

    fn set_timeout(&mut self, timeout: Duration) -> Result<(), TransportError> {
        if timeout != self.timeout {
            self.port
                .set_timeout(timeout)
                .map_err(|error| serial_error(&self.path, &error))?;
            self.timeout = timeout;
        }
        Ok(())
    }

    /// The path the port was opened with.
    pub fn path(&self) -> &str {
        &self.path
    }
}

/// Looks the identity up by path, after resolving links such as `/dev/serial/by-id/...`.
fn identity_by_path(path: &str) -> Option<UsbIdentity> {
    let ports = serialport::available_ports().ok()?;
    let wanted = std::fs::canonicalize(path).ok();
    ports.into_iter().find_map(|port| {
        let SerialPortType::UsbPort(usb) = &port.port_type else {
            return None;
        };
        // Names such as `COM3` cannot be canonicalized: compare them as written.
        let same = match (&wanted, std::fs::canonicalize(&port.port_name)) {
            (Some(wanted), Ok(candidate)) => *wanted == candidate,
            _ => port.port_name == path,
        };
        same.then(|| identity_of(usb))
    })
}

impl SerialPort for NativeSerialPort {
    async fn read(
        &mut self,
        buffer: &mut [u8],
        timeout: Duration,
    ) -> Result<usize, TransportError> {
        self.set_timeout(timeout)?;
        // An interrupted call is retried, bounded like a stalled write.
        let mut interruptions = 0;
        loop {
            match self.port.read(buffer) {
                Ok(count) => return Ok(count),
                Err(error) if error.kind() == ErrorKind::TimedOut => return Ok(0),
                Err(error) if error.kind() == ErrorKind::Interrupted => {
                    interruptions += 1;
                    if interruptions >= WRITE_STALLS {
                        return Err(io_error(&self.path, &error));
                    }
                }
                Err(error) => return Err(io_error(&self.path, &error)),
            }
        }
    }

    async fn write(&mut self, data: &[u8]) -> Result<(), TransportError> {
        // The timeout of the last read must not cut a large write short.
        self.set_timeout(WRITE_TIMEOUT)?;
        let mut rest = data;
        let mut stalls = 0;
        while !rest.is_empty() {
            match self.port.write(rest) {
                Ok(0) => {
                    return Err(TransportError::Io {
                        message: std::format!("{}: the port accepted no data", self.path),
                    });
                }
                Ok(count) => {
                    rest = rest.get(count..).unwrap_or_default();
                    stalls = 0;
                }
                Err(error)
                    if matches!(error.kind(), ErrorKind::TimedOut | ErrorKind::Interrupted) =>
                {
                    stalls += 1;
                    if stalls >= WRITE_STALLS {
                        return Err(io_error(&self.path, &error));
                    }
                }
                Err(error) => return Err(io_error(&self.path, &error)),
            }
        }
        self.port
            .flush()
            .map_err(|error| io_error(&self.path, &error))
    }

    async fn set_baud_rate(&mut self, baud_rate: u32) -> Result<(), TransportError> {
        self.port
            .set_baud_rate(baud_rate)
            .map_err(|error| serial_error(&self.path, &error))
    }

    async fn set_signals(&mut self, signals: Signals) -> Result<(), TransportError> {
        // DTR first, then RTS: Windows only propagates DTR on a change of RTS.
        self.port
            .write_data_terminal_ready(signals.dtr)
            .map_err(|error| serial_error(&self.path, &error))?;
        self.port
            .write_request_to_send(signals.rts)
            .map_err(|error| serial_error(&self.path, &error))
    }

    async fn sleep(&mut self, duration: Duration) {
        std::thread::sleep(duration);
    }

    fn identity(&self) -> Option<UsbIdentity> {
        self.identity.clone()
    }
}

/// Remembers `error` in `failure`, unless it only says that the device is not there (yet) or
/// left: the next try may find it, and the user needs the error that does not go away.
fn keep(failure: &mut Option<TransportError>, error: TransportError) {
    if !matches!(
        error,
        TransportError::NotFound { .. } | TransportError::Disconnected
    ) {
        *failure = Some(error);
    }
}

/// Opens the first of `ports` that `filter` selects and `open` accepts. The error of a port that
/// matches but does not open (no permission, for example) goes to `failure`. When no port is
/// selected, the device is gone: `failure` is cleared, so that the wait ends with `NotFound`, not
/// with the error of a port that is no longer there.
fn open_matching<T>(
    ports: &[PortInformation],
    filter: &DeviceFilter,
    failure: &mut Option<TransportError>,
    mut open: impl FnMut(&PortInformation) -> Result<T, TransportError>,
) -> Option<T> {
    let mut any_selected = false;
    for port in ports {
        let selected = port
            .identity
            .as_ref()
            .is_some_and(|identity| filter.matches(identity));
        if !selected {
            continue;
        }
        any_selected = true;
        match open(port) {
            Ok(opened) => return Some(opened),
            Err(error) => keep(failure, error),
        }
    }
    if !any_selected {
        *failure = None;
    }
    None
}

/// Finds ports of the host by their USB identity.
#[derive(Default)]
pub struct NativePortProvider;

impl PortProvider for NativePortProvider {
    type Port = NativeSerialPort;

    async fn open(
        &mut self,
        filter: &DeviceFilter,
        baud_rate: u32,
        timeout: Duration,
    ) -> Result<NativeSerialPort, TransportError> {
        // A timeout too large for the clock means no deadline.
        let deadline = Instant::now().checked_add(timeout);
        // The last error that is not a missing or a vanished device.
        let mut failure = None;
        loop {
            // Listing and opening errors are retried: the device may still be appearing.
            match list_ports() {
                Ok(ports) => {
                    let opened = open_matching(&ports, filter, &mut failure, |port| {
                        NativeSerialPort::open_with_identity(
                            &port.path,
                            baud_rate,
                            port.identity.clone(),
                        )
                    });
                    if let Some(opened) = opened {
                        return Ok(opened);
                    }
                }
                Err(error) => keep(&mut failure, error),
            }
            let pause = match deadline {
                Some(deadline) => {
                    let now = Instant::now();
                    if now >= deadline {
                        return Err(failure.unwrap_or_else(|| TransportError::NotFound {
                            filter: filter.to_string(),
                        }));
                    }
                    POLL_INTERVAL.min(deadline - now)
                }
                None => POLL_INTERVAL,
            };
            std::thread::sleep(pause);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn identity_of_a_usb_port() {
        let information = serialport::UsbPortInfo {
            vid: 0x303a,
            pid: 0x1001,
            serial_number: Some("ab".into()),
            manufacturer: None,
            product: None,
        };
        assert_eq!(
            identity_of(&information),
            crate::transport::UsbIdentity {
                vendor: 0x303a,
                product: 0x1001,
                serial_number: Some("ab".into())
            }
        );
    }

    fn usb_port(path: &str, vendor: u16, product: u16) -> PortInformation {
        PortInformation {
            path: path.to_string(),
            identity: Some(UsbIdentity {
                vendor,
                product,
                serial_number: None,
            }),
            product: None,
        }
    }

    #[test]
    fn a_port_that_does_not_open_keeps_its_error() {
        let filter = DeviceFilter {
            vendor: 0x2341,
            product: Some(0x805a),
            serial_number: None,
        };
        let ports = [
            usb_port("/dev/ttyUSB0", 0x10c4, 0xea60),
            usb_port("/dev/ttyACM0", 0x2341, 0x805a),
        ];
        let mut failure = None;
        let mut tried = Vec::new();
        let opened = open_matching(&ports, &filter, &mut failure, |port| {
            tried.push(port.path.clone());
            Err::<(), _>(TransportError::Io {
                message: "/dev/ttyACM0: Permission denied".to_string(),
            })
        });
        assert_eq!(opened, None);
        // A port that the filter does not select is not opened.
        assert_eq!(tried, ["/dev/ttyACM0"]);
        assert_eq!(
            failure,
            Some(TransportError::Io {
                message: "/dev/ttyACM0: Permission denied".to_string()
            })
        );
    }

    #[test]
    fn an_error_of_a_port_that_is_gone_is_forgotten() {
        let filter = DeviceFilter {
            vendor: 0x2341,
            product: None,
            serial_number: None,
        };
        let mut failure = None;
        // First poll: the port is there and does not open yet (udev has not set its rights).
        let ports = [usb_port("/dev/ttyACM0", 0x2341, 0x805a)];
        open_matching(&ports, &filter, &mut failure, |_| {
            Err::<(), _>(TransportError::Io {
                message: "/dev/ttyACM0: Permission denied".to_string(),
            })
        });
        assert!(failure.is_some());
        // Next poll: the device left. The wait then ends with NotFound, not with the old error.
        open_matching(&[], &filter, &mut failure, |_| Ok(()));
        assert_eq!(failure, None);
    }

    #[test]
    fn a_vanished_port_is_not_an_error_to_report() {
        let filter = DeviceFilter {
            vendor: 0x2341,
            product: None,
            serial_number: None,
        };
        let ports = [usb_port("/dev/ttyACM0", 0x2341, 0x805a)];
        let mut failure = None;
        let opened = open_matching(&ports, &filter, &mut failure, |_| {
            Err::<(), _>(TransportError::Disconnected)
        });
        assert_eq!(opened, None);
        assert_eq!(failure, None);
    }

    #[test]
    fn opening_a_missing_port_names_it() {
        let error = NativeSerialPort::open("/dev/nanoflash-missing", 115200).err();
        match error {
            Some(crate::transport::TransportError::Io { message }) => {
                assert!(message.contains("/dev/nanoflash-missing"), "{message}")
            }
            other => panic!("unexpected {other:?}"),
        }
    }

    #[cfg(unix)]
    #[test]
    fn a_pseudo_terminal_pair_round_trips() {
        let (master, slave) = serialport::TTYPort::pair().expect("a pty pair");
        let mut a = NativeSerialPort::from_port(Box::new(master), "master");
        let mut b = NativeSerialPort::from_port(Box::new(slave), "slave");
        pollster::block_on(async {
            a.write(&[1, 2, 3]).await.expect("write");
            let mut buffer = [0u8; 8];
            let mut received = 0;
            let deadline = Instant::now() + Duration::from_secs(2);
            while received < 3 && Instant::now() < deadline {
                received += b
                    .read(&mut buffer[received..], Duration::from_millis(100))
                    .await
                    .expect("read");
            }
            assert_eq!(&buffer[..received], &[1, 2, 3]);
            assert_eq!(b.read(&mut buffer, Duration::from_millis(50)).await, Ok(0));
            // A large write after a short read timeout is not cut short.
            let big = std::vec![7u8; 4096];
            let writer = std::thread::spawn(move || pollster::block_on(a.write(&big)).map(|()| a));
            let mut total = 0;
            let deadline = Instant::now() + Duration::from_secs(5);
            while total < 4096 && Instant::now() < deadline {
                total += b
                    .read(&mut buffer, Duration::from_millis(50))
                    .await
                    .expect("read");
            }
            assert_eq!(total, 4096);
            assert!(writer.join().expect("writer").is_ok());
            assert_eq!(b.identity(), None);
        });
    }
}