ch32rv 0.48.0

Flashing and debugging tool for WCH CH32 RISC-V microcontrollers
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
//! en: The HID serial (`monitor --source hid`): a serial over the board's own USB as 64-byte HID
//! feature reports carrying dmseq-like frames, found by usage page 0xFF32 / usage 0x52. The device
//! side may be USB done in software (ArduinoCore-CH32RV's SerialSoftUSB on a V003) or a USB
//! peripheral; the host sees the same frames. The convention is ArduinoCore-CH32RV's "HID Serial"
//! (docs/hid-serial.md).
//!
//! Frame (both directions, 64 bytes, no report ID):
//!   byte0  bit6 D, bit5 S (this frame's number), bit4 A (the last number taken from the other
//!          side), bit3 SYN, bit2 CMD (reserved); the host sends D = SYN = 0
//!   byte1  len (0..=59; more is invalid)
//!   byte2  the device: room in its receive buffer (the most the host may send next); the host: 0
//!   byte3..62  payload
//!   byte62..64 CRC-16 (USB's: poly 0xA001 reflected, init 0xFFFF, inverted) over bytes 0..62, LE
//!
//! A poll is SET_REPORT(feature) (the host's frame: its payload and its ack) then GET_REPORT
//! (feature). Only a SET moves the device on; a GET answers the same frame until it is acked, so a
//! failed GET is just tried again.
//! ja: HID のシリアル(`monitor --source hid`)。board 自身の USB の 64 byte の HID feature 報告で dmseq
//! に似たフレームを運ぶ。usage page 0xFF32 / usage 0x52 で探す。device 側はソフトの USB(V003 の
//! SerialSoftUSB)でも USB の周辺でもよく、host からは同じ。約束事は ArduinoCore-CH32RV の「HID シリアル」(docs/hid-serial.ja.md)。

use std::time::{Duration, Instant};

use ch32rv_contract::ErrorKind;

use crate::args::Cli;
use crate::cmd_probe::fail;
use crate::source::{self, Sink};

pub(crate) const REPORT: usize = 64;
const PAYLOAD: usize = 59;
const BIT_D: u8 = 1 << 6;
const BIT_S: u8 = 1 << 5;
const BIT_A: u8 = 1 << 4;
const BIT_SYN: u8 = 1 << 3;
/// The prototype's usage page / usage ("CH32" / "R").
const USAGE_PAGE: u16 = 0xFF32;
const USAGE: u16 = 0x52;

pub(crate) fn crc16(b: &[u8]) -> u16 {
    let mut crc: u16 = 0xffff;
    for &x in b {
        crc ^= u16::from(x);
        for _ in 0..8 {
            crc = if crc & 1 != 0 {
                (crc >> 1) ^ 0xa001
            } else {
                crc >> 1
            };
        }
    }
    !crc
}

/// A device frame that passed its checks.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct DevFrame<'a> {
    pub s: bool,
    pub a: bool,
    pub d: bool,
    pub syn: bool,
    pub room: usize,
    pub payload: &'a [u8],
}

pub(crate) fn parse(f: &[u8]) -> Option<DevFrame<'_>> {
    if f.len() != REPORT {
        return None;
    }
    let len = usize::from(f[1]);
    if len > PAYLOAD || crc16(&f[..62]) != u16::from_le_bytes([f[62], f[63]]) {
        return None;
    }
    Some(DevFrame {
        s: f[0] & BIT_S != 0,
        a: f[0] & BIT_A != 0,
        d: f[0] & BIT_D != 0,
        syn: f[0] & BIT_SYN != 0,
        room: usize::from(f[2]).min(PAYLOAD),
        payload: &f[3..3 + len],
    })
}

/// What one valid device frame gave.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct Taken {
    /// The device discarded output before this payload (D on a new frame).
    pub discarded: bool,
    pub data: Vec<u8>,
}

/// en: The host's side, the dmseq host rules over a 1-bit number each way.
/// ja: host 側。dmseq の host の規則を、向きごとの 1 bit の番号で行う。
#[derive(Debug, Default)]
pub(crate) struct Host {
    synced: bool,
    /// The S of the last device frame taken (sent back as A).
    last_s: bool,
    last_syn: bool,
    /// This host's frame number; the frame is delivered once the device's A equals it.
    s: bool,
    pending: Vec<u8>,
    /// en: What the device last said it can take. It only grows until the device takes a frame
    /// (it reads its buffer, nothing else fills it), so a frame of this size always fits whole.
    /// ja: device が最後に知らせた受けの空き。フレームを取るまでは増える一方なので、この大きさなら丸ごと入る。
    room: usize,
    /// en: A pending payload given back on a resync: the restarted device may have less room.
    /// ja: 再同期で戻した送りかけ(再起動した device の空きは小さいかもしれない)。
    requeue: Vec<u8>,
}

impl Host {
    /// The frame to SET now: the unacked payload (or the next one from `out`), and the ack.
    pub(crate) fn frame(&mut self, out: &mut Vec<u8>) -> [u8; REPORT] {
        if !self.requeue.is_empty() {
            out.splice(..0, self.requeue.drain(..));
        }
        if self.pending.is_empty() && self.synced {
            let n = out.len().min(self.room);
            self.pending = out.drain(..n).collect();
        }
        let mut f = [0u8; REPORT];
        f[0] = if self.s { BIT_S } else { 0 } | if self.last_s { BIT_A } else { 0 };
        f[1] = self.pending.len() as u8;
        f[3..3 + self.pending.len()].copy_from_slice(&self.pending);
        let crc = crc16(&f[..62]);
        f[62..].copy_from_slice(&crc.to_le_bytes());
        f
    }

    /// en: Whether the host may SET yet: before the first valid GET its numbers are unknown, and
    /// a SET with stale numbers is taken as a duplicate (or acks a frame never read).
    /// ja: SET してよいか。最初の有効な GET の前は番号が分からない。
    pub(crate) fn synced(&self) -> bool {
        self.synced
    }

    /// A valid device frame from a GET.
    pub(crate) fn take(&mut self, f: &DevFrame<'_>) -> Taken {
        let dup = self.synced && f.s == self.last_s && (!f.syn || self.last_syn);
        if !dup && (!self.synced || f.syn) {
            // en: Resync (dmseq host rule 3): count this frame as new; our next frame must not
            // look like the one the device last took, and what we had pending is sent again
            // (split anew to the room the device has now).
            // ja: 再同期。このフレームを新しいものとし、host の番号は device の A の反対にする。
            self.last_s = !f.s;
            self.s = !f.a;
            self.synced = true;
            self.requeue = std::mem::take(&mut self.pending);
        }
        let mut t = Taken::default();
        if f.s != self.last_s {
            t.discarded = f.d && !f.payload.is_empty();
            t.data = f.payload.to_vec();
            self.last_s = f.s;
            self.last_syn = f.syn;
        }
        if !self.pending.is_empty() && f.a == self.s {
            self.pending.clear();
            self.s = !self.s;
        }
        self.room = f.room;
        t
    }
}

/// en: The serial's HID feature reports: through hidraw (hidapi), or - Linux, where the hidraw node
/// does not open (no udev rule for it) - as class control requests on the USB node.
/// ja: シリアルの HID feature 報告。hidraw(hidapi)か、hidraw が開けない Linux では USB ノードの
/// class の制御要求で。
enum Port {
    Hid(hidapi::HidDevice),
    Usb(ch32rv_usb::hid::HidControl),
}

impl Port {
    /// One GET: `Ok(None)` for a report of another length.
    fn get(&self) -> Result<Option<[u8; REPORT]>, String> {
        match self {
            Port::Hid(d) => {
                let mut b = [0u8; REPORT + 1];
                let n = d.get_feature_report(&mut b).map_err(|e| e.to_string())?;
                Ok(if n == REPORT + 1 {
                    b[1..].try_into().ok()
                } else {
                    None
                })
            }
            Port::Usb(h) => {
                let v = h.get_feature(REPORT as u16).map_err(|e| e.to_string())?;
                Ok(v.as_slice().try_into().ok())
            }
        }
    }

    fn set(&self, f: &[u8; REPORT]) -> Result<(), String> {
        match self {
            Port::Hid(d) => {
                let mut b = [0u8; REPORT + 1];
                b[1..].copy_from_slice(f);
                d.send_feature_report(&b).map_err(|e| e.to_string())
            }
            Port::Usb(h) => h.set_feature(f).map_err(|e| e.to_string()),
        }
    }
}

/// How `monitor --source hid` picks the device.
pub(crate) enum Which {
    /// The one with the serial's usage page / usage.
    Usage,
    /// `--port VID:PID` (the first listed).
    UsbId(u16, u16),
    /// `--port <path>` as hidapi lists it.
    Path(String),
    /// The one at a USB position (`ch32rv-hid://<topology>`).
    At(String),
}

impl std::fmt::Display for Which {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Which::Usage => write!(
                f,
                "no HID device with usage page {USAGE_PAGE:#06x} / usage {USAGE:#04x} (or more than one)"
            ),
            Which::UsbId(v, p) => write!(f, "no HID device {v:04x}:{p:04x}"),
            Which::Path(p) => write!(f, "no HID device at {p}"),
            Which::At(t) => write!(f, "no HID serial at USB position {t}"),
        }
    }
}

/// What a listed HID interface is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Kind {
    /// An application with the HID serial (usage page 0xFF32 / usage 0x52).
    App,
    /// An rv003usb-style HID bootloader, by its report descriptor
    /// (`ch32rv_boot::is_bootloader_descriptor`).
    Bootloader,
}

/// A HID serial or HID bootloader as listed: where it is and what it is.
pub(crate) struct Found {
    pub path: String,
    pub vid: u16,
    pub pid: u16,
    pub kind: Kind,
    /// Its USB position, where it can be told (see [`list`]).
    pub topology: Option<String>,
}

/// en: The HID serials (usage page / usage) and the HID bootloaders known by their report
/// descriptor connected, each with its USB position: on Linux the USB device whose sysfs holds
/// its hidraw node (the deepest, as the hubs above list it too); elsewhere the one USB device with
/// its VID:PID when exactly one listed interface has that VID:PID (two alike boards cannot be
/// told apart there).
/// ja: 接続された HID シリアル(usage で)と、記述子で分かる HID bootloader、その USB の位置。Linux は
/// hidraw を持つ USB device(いちばん深いもの)、ほかの OS は同じ VID:PID のものが 1 台ずつのときだけ。
pub(crate) fn list() -> Vec<Found> {
    if ch32rv_usb::replay::active() {
        return Vec::new();
    }
    let Ok(api) = hidapi::HidApi::new() else {
        return Vec::new();
    };
    let found: Vec<(String, u16, u16, Kind)> = api
        .device_list()
        .filter_map(|d| {
            let kind = if d.usage_page() == USAGE_PAGE && d.usage() == USAGE {
                Kind::App
            } else if ch32rv_boot::is_bootloader_descriptor(d.usage_page(), d.usage(), d.path()) {
                Kind::Bootloader
            } else {
                return None;
            };
            Some((
                d.path().to_string_lossy().into_owned(),
                d.vendor_id(),
                d.product_id(),
                kind,
            ))
        })
        .collect();
    let devs = ch32rv_usb::device::enumerate().unwrap_or_default();
    found
        .iter()
        .map(|(path, vid, pid, kind)| {
            let topology = if cfg!(target_os = "linux") {
                devs.iter()
                    .filter(|d| d.hidraw_nodes().contains(path))
                    .max_by_key(|d| d.topology().len())
                    .map(|d| d.topology())
            } else {
                let same = |v: u16, p: u16| v == *vid && p == *pid;
                let mut usb = devs.iter().filter(|d| same(d.vid(), d.pid()));
                match (usb.next(), usb.next()) {
                    (Some(d), None) if found.iter().filter(|f| same(f.1, f.2)).count() == 1 => {
                        Some(d.topology())
                    }
                    _ => None,
                }
            };
            Found {
                path: path.clone(),
                vid: *vid,
                pid: *pid,
                kind: *kind,
                topology,
            }
        })
        .collect()
}

/// en: Open the one device `which` names. `Ok(None)`: none (or, by usage, more than one).
/// ja: `which` の device を開く。`Ok(None)`: 無い(usage では 2 台以上も)。
fn open(which: &Which) -> Result<Option<Port>, String> {
    let api = hidapi::HidApi::new().map_err(|e| e.to_string())?;
    let at_path = match which {
        Which::At(t) => match list()
            .into_iter()
            .find(|f| f.kind == Kind::App && f.topology.as_deref() == Some(t))
        {
            Some(f) => Some(f.path),
            None => return Ok(None),
        },
        _ => None,
    };
    let mut found = api.device_list().filter(|d| match which {
        Which::Usage => d.usage_page() == USAGE_PAGE && d.usage() == USAGE,
        Which::UsbId(v, p) => d.vendor_id() == *v && d.product_id() == *p,
        Which::Path(p) => d.path().to_string_lossy() == p.as_str(),
        Which::At(_) => Some(d.path().to_string_lossy().into_owned()) == at_path,
    });
    let info = match (found.next(), found.next(), which) {
        (Some(i), None, _) => i,
        (Some(i), Some(_), Which::UsbId(..) | Which::Path(_) | Which::At(_)) => i,
        _ => return Ok(None),
    };
    let hid_err = match info.open_device(&api) {
        Ok(d) => return Ok(Some(Port::Hid(d))),
        Err(e) => e,
    };
    // en: The USB device that owns this hidraw node (one VID:PID may be on several): the deepest
    // one listing it, as the hubs above it list it too.
    // ja: この hidraw の USB device(上のハブも配下として持つので、いちばん深いもの)。
    let node = info.path().to_string_lossy().into_owned();
    let number = u8::try_from(info.interface_number()).unwrap_or(0);
    let devs = ch32rv_usb::device::enumerate().map_err(|e| e.to_string())?;
    let Some(dev) = devs
        .iter()
        .filter(|d| d.hidraw_nodes().contains(&node))
        .max_by_key(|d| d.topology().len())
    else {
        return Err(format!("opening the HID serial failed: {hid_err}"));
    };
    ch32rv_usb::hid::HidControl::open(dev, number)
        .map(|h| Some(Port::Usb(h)))
        .map_err(|e| format!("opening the HID serial failed: {hid_err}; {e}"))
}

/// What one poll gave.
pub(crate) struct Step {
    /// What the device sent (a newline first where it discarded output mid-line).
    pub data: Vec<u8>,
    /// Nothing either way: the caller may wait a little before the next poll.
    pub idle: bool,
}

/// en: An open HID serial: the port and the host's side of the frames, polled one SET + GET at a
/// time (the CLI's monitor and the IDE's alike).
/// ja: 開いた HID シリアル。1 回の poll(SET と GET)ずつ進める(CLI と IDE の monitor が共に使う)。
pub(crate) struct Link {
    port: Port,
    host: Host,
    mid_line: bool,
    last_ok: Instant,
    trace: bool,
    started: Instant,
    polls: u64,
    set_err: u64,
    get_err: u64,
    bad: u64,
}

/// How long a HID serial may give no valid frame before it counts as gone.
const SILENT_LIMIT: Duration = Duration::from_secs(3);

impl Link {
    pub(crate) fn open(which: &Which) -> Result<Option<Link>, String> {
        Ok(open(which)?.map(|port| Link {
            port,
            host: Host::default(),
            mid_line: false,
            last_ok: Instant::now(),
            trace: std::env::var_os("CH32RV_HID_TRACE").is_some(),
            started: Instant::now(),
            polls: 0,
            set_err: 0,
            get_err: 0,
            bad: 0,
        }))
    }

    /// Over the USB node (the kernel's HID driver detached until this is dropped).
    pub(crate) fn over_usb_node(&self) -> bool {
        matches!(self.port, Port::Usb(_))
    }

    /// en: One poll: SET what `out` holds (as much as the device has room for), GET. `Err` once
    /// the device has given no valid frame for [`SILENT_LIMIT`].
    /// ja: 1 回の poll。`out` から(device の空きだけ)SET して GET。有効なフレームが 3 秒無ければ `Err`。
    pub(crate) fn step(&mut self, out: &mut Vec<u8>) -> Result<Step, String> {
        self.polls += 1;
        if self.host.synced() {
            let f = self.host.frame(out);
            let r = self.port.set(&f);
            if self.trace {
                eprintln!("SET {} {}", if r.is_ok() { "ok" } else { "err" }, hex(&f));
            }
            if r.is_err() {
                self.set_err += 1;
            }
        }
        let r = self.port.get();
        if self.trace {
            match &r {
                Ok(Some(b)) => eprintln!("GET {} {}", self.started.elapsed().as_millis(), hex(b)),
                Ok(None) => eprintln!("GET short"),
                Err(_) => eprintln!("GET err"),
            }
        }
        let mut data = Vec::new();
        match r {
            Ok(Some(buf)) => match parse(&buf) {
                Some(f) => {
                    self.last_ok = Instant::now();
                    let t = self.host.take(&f);
                    if t.discarded && self.mid_line {
                        data.push(b'\n');
                    }
                    if let Some(&last) = t.data.last() {
                        self.mid_line = last != b'\n';
                    }
                    data.extend_from_slice(&t.data);
                }
                None => self.bad += 1,
            },
            Ok(None) => self.bad += 1,
            Err(_) => self.get_err += 1,
        }
        if self.last_ok.elapsed() > SILENT_LIMIT {
            return Err("the HID serial stopped answering for 3 s".to_owned());
        }
        // en: Only a poll with nothing either way leaves time for the device's own work: data that
        // came in, or still to go out (pending, unacked), polls again at once.
        // ja: どちらにも何も無い poll の後だけ待ってよい。受けたばかり・送りかけがあればすぐ次を poll する。
        let idle = data.is_empty()
            && out.is_empty()
            && self.host.pending.is_empty()
            && self.host.requeue.is_empty();
        Ok(Step { data, idle })
    }

    fn stats(&self) -> String {
        format!(
            "hid: {} polls in {:.1} s, SET errors {}, GET errors {}, bad frames {}",
            self.polls,
            self.started.elapsed().as_secs_f64(),
            self.set_err,
            self.get_err,
            self.bad
        )
    }
}

/// en: `monitor --source hid [--port VID:PID|<path>]`.
/// ja: `monitor --source hid [--port VID:PID|<path>]`。
pub(crate) fn run(cli: &Cli, which: Which, deadline: Option<Instant>) -> ExitCode {
    const CMD: &str = "monitor";
    let mut link = match Link::open(&which) {
        Ok(Some(d)) => d,
        Ok(None) => return fail(cli, CMD, ErrorKind::DeviceNotFound, which.to_string(), None),
        Err(e) => return fail(cli, CMD, ErrorKind::DeviceNotFound, e, None),
    };
    if !cli.json {
        eprintln!("monitor: HID serial (feature reports) (Ctrl-C to stop)");
    }
    let mut sink = Sink::new(cli, "hid");
    let input = source::spawn_reader(std::io::stdin());
    let mut out = Vec::new();
    // en: Over the USB node the kernel's HID driver is detached while we run and put back when
    // the port is dropped; a Ctrl-C (or SIGTERM) that killed the process would leave the device
    // without its hidraw node - and this command unable to find it again until it is re-plugged.
    // So both end the loop instead.
    // ja: USB ノード経由ではカーネルの HID ドライバを外して走り、port を落とすと戻す。Ctrl-C で
    // プロセスが死ぬと hidraw が無いまま残り(挿し直すまで次の monitor が見つけられない)ので、
    // Ctrl-C / SIGTERM はループを終えるだけにする。
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    if link.over_usb_node() {
        let s = std::sync::Arc::clone(&stop);
        let _ = ctrlc::set_handler(move || s.store(true, std::sync::atomic::Ordering::Relaxed));
    }
    loop {
        if stop.load(std::sync::atomic::Ordering::Relaxed)
            || deadline.is_some_and(|dl| Instant::now() >= dl)
        {
            break;
        }
        source::drain_input(&input, &mut out);
        match link.step(&mut out) {
            Ok(st) => {
                sink.write(&st.data);
                if st.idle {
                    std::thread::sleep(Duration::from_millis(2));
                }
            }
            Err(e) => {
                sink.finish();
                return fail(cli, CMD, ErrorKind::TransferFailed, e, None);
            }
        }
    }
    sink.finish();
    if std::env::var_os("CH32RV_HID_STATS").is_some() {
        eprintln!("{}", link.stats());
    }
    ExitCode::SUCCESS
}

use std::process::ExitCode;

fn hex(b: &[u8]) -> String {
    b.iter().map(|x| format!("{x:02x}")).collect()
}

const BIT_CMD: u8 = 1 << 2;

/// en: The frame that asks the application to enter its bootloader (CMD with payload 'B'), numbered
/// as a resync from the device frame `f`: S = not its A, A = not its S, so the device takes it
/// as new whatever it last took.
/// ja: bootloader へ入れと頼むフレーム(CMD、中身 'B')。番号は `f` からの再同期(S は A の反対、
/// A は S の反対)なので、device は直前に何を取っていても新しいものとして受ける。
pub(crate) fn boot_command(f: &DevFrame<'_>) -> [u8; REPORT] {
    let mut out = [0u8; REPORT];
    out[0] = BIT_CMD | if f.a { 0 } else { BIT_S } | if f.s { 0 } else { BIT_A };
    out[1] = 1;
    out[3] = b'B';
    let crc = crc16(&out[..62]);
    out[62..].copy_from_slice(&crc.to_le_bytes());
    out
}

/// en: Ask the one application with the HID serial (usage page / usage) to enter its
/// bootloader: GET to learn its numbers, SET the CMD 'B' frame, then one more GET (the application
/// reboots on it when the SET's status-stage ACK was lost). An application with a bootloader that
/// knows the RAM mark (ArduinoCore-CH32RV's) shows up as 1209:b803 0.3-0.6 s later; a factory
/// bootloader does not stay, so the caller keeps its RESET hint. `Ok(false)`: none (or more than
/// one) to ask. Replay never asks.
/// ja: HID のシリアルのアプリ(1 台だけ)に bootloader へ入れと頼む。GET で番号を知り、CMD 'B'
/// を SET、もう 1 回 GET(SET のステータス段の ACK が失われたときはそれで再起動する)。RAM の印を
/// 知る bootloader なら 0.3〜0.6 秒で 1209:b803 が出る。出荷時の bootloader は留まらない。
pub(crate) fn request_bootloader(at: Option<&str>) -> Result<bool, String> {
    if ch32rv_usb::replay::active() {
        return Ok(false);
    }
    let which = at.map_or(Which::Usage, |t| Which::At(t.to_owned()));
    let Some(port) = open(&which)? else {
        return Ok(false);
    };
    exchange(|| port.get().ok().flatten(), |f| port.set(f))
}

/// en: GET until a valid frame, SET the CMD 'B' frame numbered from it, one more GET.
/// ja: 有効なフレームまで GET、それから番号を合わせた CMD 'B' を SET、もう 1 回 GET。
fn exchange(
    mut get: impl FnMut() -> Option<[u8; REPORT]>,
    mut set: impl FnMut(&[u8; REPORT]) -> Result<(), String>,
) -> Result<bool, String> {
    let cmd = (0..5)
        .find_map(|_| get().and_then(|g| parse(&g).map(|f| boot_command(&f))))
        .ok_or_else(|| "the HID serial gave no valid frame".to_owned())?;
    let mut last = Ok(());
    for _ in 0..5 {
        last = set(&cmd);
        if last.is_ok() {
            break;
        }
    }
    last.map_err(|e| format!("sending the bootloader request failed: {e}"))?;
    let _ = get();
    Ok(true)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used)]

    use super::*;

    #[test]
    fn boot_command_resyncs_from_the_device_frame() {
        for (s, a) in [(false, false), (false, true), (true, false), (true, true)] {
            let d = dev(s, a, false, false, b"");
            let f = parse(&d).expect("valid");
            let c = boot_command(&f);
            // [core]'s bootcmd.py: byte0 = 0x04 | (!A << 5) | (!S << 4), len 1, 'B'.
            assert_eq!(c[0], 0x04 | u8::from(!a) << 5 | u8::from(!s) << 4);
            assert_eq!((c[1], c[2], c[3]), (1, 0, b'B'));
            assert_eq!(crc16(&c[..62]), u16::from_le_bytes([c[62], c[63]]));
            assert!(c[4..62].iter().all(|&b| b == 0));
        }
    }

    fn dev(s: bool, a: bool, d: bool, syn: bool, payload: &[u8]) -> [u8; REPORT] {
        let mut f = [0u8; REPORT];
        f[0] = u8::from(d) << 6 | u8::from(s) << 5 | u8::from(a) << 4 | u8::from(syn) << 3;
        f[1] = payload.len() as u8;
        f[2] = 28;
        f[3..3 + payload.len()].copy_from_slice(payload);
        let crc = crc16(&f[..62]);
        f[62..].copy_from_slice(&crc.to_le_bytes());
        f
    }

    fn take(h: &mut Host, f: [u8; REPORT]) -> Taken {
        let p = parse(&f).expect("valid frame");
        h.take(&p)
    }

    #[test]
    fn crc_is_usbs() {
        // CRC-16/USB check value
        assert_eq!(crc16(b"123456789"), 0xb4c8);
    }

    #[test]
    fn invalid_frames_are_refused() {
        let mut f = dev(false, false, false, false, b"hi");
        f[5] ^= 1;
        assert!(parse(&f).is_none());
        let mut f = dev(false, false, false, false, b"");
        f[1] = 60;
        let crc = crc16(&f[..62]);
        f[62..].copy_from_slice(&crc.to_le_bytes());
        assert!(parse(&f).is_none());
        assert!(parse(&[0xff; REPORT]).is_none());
    }

    #[test]
    fn the_first_frame_is_taken_and_numbers_follow_the_device() {
        let mut h = Host::default();
        assert!(!h.synced());
        // a frame left from an earlier connection: taken, not dropped as a duplicate
        assert_eq!(
            take(&mut h, dev(true, true, false, false, b"abc")).data,
            b"abc"
        );
        let mut out = b"xy".to_vec();
        let f = h.frame(&mut out);
        // our S is the device's A inverted (not a duplicate), our A acks its S
        assert_eq!(f[0], BIT_A);
        assert_eq!(&f[1..5], &[2, 0, b'x', b'y']);
        // a GET before the device saw the SET: same frame, a duplicate
        assert!(
            take(&mut h, dev(true, true, false, false, b"abc"))
                .data
                .is_empty()
        );
        // the next frame acks ours (A = 0)
        assert_eq!(
            take(&mut h, dev(false, false, false, false, b"d")).data,
            b"d"
        );
        let f = h.frame(&mut out);
        assert_eq!(f[0] & BIT_S, BIT_S);
        assert_eq!(f[1], 0);
    }

    #[test]
    fn an_unacked_frame_is_sent_again() {
        let mut h = Host::default();
        take(&mut h, dev(false, true, false, false, b""));
        let mut out = b"0123456789012345678901234567890123".to_vec();
        let f1 = h.frame(&mut out);
        assert_eq!(f1[1], 28);
        take(&mut h, dev(false, true, false, false, b""));
        assert_eq!(h.frame(&mut out), f1);
        take(&mut h, dev(true, false, false, false, b""));
        let f2 = h.frame(&mut out);
        assert_eq!(&f2[3..9], b"890123");
    }

    #[test]
    fn d_marks_a_discard_on_a_new_data_frame() {
        let mut h = Host::default();
        take(&mut h, dev(false, false, false, false, b"a"));
        let t = take(&mut h, dev(true, false, true, false, b"b"));
        assert!(t.discarded);
        // a resent frame keeps its D but is a duplicate
        assert_eq!(
            take(&mut h, dev(true, false, true, false, b"b")),
            Taken::default()
        );
    }

    #[test]
    fn a_device_restart_resyncs_and_sends_pending_again() {
        let mut h = Host::default();
        take(&mut h, dev(false, false, false, false, b""));
        let mut out = b"q".to_vec();
        let f = h.frame(&mut out);
        assert_eq!(f[0] & BIT_S, BIT_S);
        // the device restarted (SYN) without taking it; its A happens to differ from our S
        assert_eq!(
            take(&mut h, dev(false, false, false, true, b"hello")).data,
            b"hello"
        );
        let f = h.frame(&mut out);
        assert_eq!(f[0] & BIT_S, BIT_S);
        assert_eq!(&f[1..4], &[1, 0, b'q']);
        // its SYN resent: a duplicate
        assert!(
            take(&mut h, dev(false, false, false, true, b"hello"))
                .data
                .is_empty()
        );
    }
}