ch32rv 0.49.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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
//! en: `isp` (docs/cli.ja.md §4.7): the chip's factory ISP bootloader over USB or a UART.
//! `list` / `info` / `flash` / `verify` / `erase` / `reset`; the rest of the namespace stays
//! reserved.
//! ja: `isp`。チップの factory ISP bootloader を USB か UART で使う。

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

use ch32rv_contract::policy::{EraseMode, ImageFormat};
use ch32rv_contract::{ErrorKind, ResultEnvelope, Warning};
use ch32rv_isp::{Identity, IspConfig, IspDevice, IspError, OptionFields};
use ch32rv_usb::UsbDeviceInfo;

use ch32rv_dmi::{DmiError, ResetMode, TargetAccess};

use crate::args::{
    Cli, IspArgs, IspCmd, IspConfigCmd, IspEntry, IspReset, IspTransport, IspVerify, IspVia,
};
use crate::cmd_probe::fail;

const CODE_FLASH_START: u32 = 0x0800_0000;

pub fn isp(cli: &Cli, args: &IspArgs) -> ExitCode {
    match &args.cmd {
        IspCmd::List => list(cli),
        IspCmd::Info => info(cli, args),
        IspCmd::Flash {
            file,
            erase,
            verify,
            reset,
            unprotect,
        } => flash(cli, args, file, *erase, *verify, *reset, *unprotect),
        IspCmd::Verify { file } => verify_only(cli, args, file),
        IspCmd::Erase => erase_only(cli, args),
        IspCmd::Reset => reset(cli, args),
        IspCmd::Enter { via: IspVia::Probe } => enter(cli, args),
        IspCmd::Config(IspConfigCmd::Get) => config_get(cli, args),
        IspCmd::Config(IspConfigCmd::Set { kv }) => config_set(cli, args, kv),
    }
}

/// A connected bootloader with what it said about itself.
struct Opened {
    dev: IspDevice,
    /// USB ID and position; `None` over a UART.
    usb: Option<String>,
    topology: Option<String>,
    /// Where it was reached: `topology:<bus>-<ports>` or `uart:<port>`.
    at: String,
    id: Identity,
    cfg: IspConfig,
}

/// en: Pick the one ISP device (at the position `--device` names, or the only one present), waiting
/// up to `--wait` for it to appear, then Identify and ReadConfig it.
/// ja: ISP device を 1 台選び(`--device` の位置か唯一の 1 台)、`--wait` まで待ち、Identify と
/// ReadConfig をする。
fn open(cli: &Cli, cmd: &str, args: &IspArgs) -> Result<Opened, ExitCode> {
    open_with(cli, cmd, args, args.entry)
}

fn open_with(cli: &Cli, cmd: &str, args: &IspArgs, entry: IspEntry) -> Result<Opened, ExitCode> {
    // en: The IDE's waiting port: no device named, nothing asked of a running sketch, the user
    // puts the chip in its bootloader - unless the chip has no USB peripheral (the DB says), so no
    // factory USB ISP, which is refused before any wait (a software-USB HID bootloader such as
    // rv003usb is `boot hid flash`'s, not this). ja: 待つポート。USB の周辺の無いチップ(工場の
    // USB ISP が無い)は待つ前に断る。ソフトウェア USB の HID は boot hid flash の側。
    let waiting = match args.device.as_deref().and_then(wait_for_boot) {
        Some(Err(m)) => return Err(fail(cli, cmd, ErrorKind::Usage, m, None)),
        Some(Ok(())) => true,
        None => false,
    };
    if waiting {
        if args.transport == IspTransport::Uart {
            return Err(fail(
                cli,
                cmd,
                ErrorKind::Usage,
                format!(
                    "{BOOTLOADER_SCHEME}{WAIT_FOR_BOOT} waits for a USB bootloader, not a UART"
                ),
                None,
            ));
        }
        if let Some(chip) = cli.chip.as_deref()
            && ch32rv_target::Db::builtin().chip_has_usb(chip) == Some(false)
        {
            return Err(fail(
                cli,
                cmd,
                ErrorKind::CapabilityUnsupported,
                format!(
                    "{chip} has no USB peripheral, so it has no factory USB ISP bootloader to wait for"
                ),
                Some(
                    "pick the port of the debug probe the board is wired to (wchlink:// or oep://); a board with a software-USB HID bootloader (rv003usb, UIAPduino) is written by `boot hid flash`",
                ),
            ));
        }
        return open_usb(cli, cmd, args, IspEntry::None, None, None, true);
    }
    if args.transport == IspTransport::Uart {
        return open_uart(cli, cmd, args, entry);
    }
    // en: `--device` names a position - the bootloader's (`ch32rv-isp://`, discovery's), or either
    // the bootloader's or the application's (`topology:`; the bootloader comes up where the
    // application was) - or the running application (its serial port, `ch32rv-app://`,
    // `VID:PID`), found now so that only the ISP device at its position is taken. An application
    // that is not there is looked for no further ([`Miss::app_gone`]): the ISP device is picked as
    // without `--device`, and an entry asked for fails on it only when no ISP device is up.
    // ja: `--device` は位置(bootloader の `ch32rv-isp://`、どちらでもよい `topology:`)か、走っている
    // アプリ。アプリは今引いて、その位置の ISP device だけを使う。アプリが居なければ `--device` 無しと
    // 同じに選び、ISP device も居ないときだけ entry がアプリの不在で止まる。
    let mut app = None;
    let want = match args.device.as_deref() {
        None => None,
        Some(d) => match position(d) {
            Some(Ok(t)) => Some(t.to_owned()),
            Some(Err(())) => {
                return Err(fail(
                    cli,
                    cmd,
                    ErrorKind::Usage,
                    format!("--device `{d}`: no position"),
                    Some("--device topology:<bus>-<ports> or ch32rv-isp://<bus>-<ports>"),
                ));
            }
            None => match find_usb_device(d) {
                Ok(a) => {
                    let t = a.dev.topology();
                    app = Some(a);
                    Some(t)
                }
                Err(m) if m.app_gone() => None,
                Err(m) => return Err(m.fail(cli, cmd)),
            },
        },
    };
    open_usb(cli, cmd, args, entry, app, want, false)
}

/// en: The ISP device over USB: at `want` (a position) or the only one, after asking `app` (or the
/// probe) to enter when `entry` says so, waiting up to `--wait` - at least [`BOOT_WAIT`] for the
/// IDE's waiting port (`waiting`), whose user puts the chip in its bootloader by hand.
/// ja: USB の ISP device。待つポートでは少なくとも [`BOOT_WAIT`] 待ち、入り方と残り時間を出す。
#[allow(clippy::too_many_arguments)]
fn open_usb(
    cli: &Cli,
    cmd: &str,
    args: &IspArgs,
    entry: IspEntry,
    app: Option<AppDevice>,
    mut want: Option<String>,
    waiting: bool,
) -> Result<Opened, ExitCode> {
    let present = |want: &Option<String>| {
        ch32rv_isp::list().is_ok_and(|v| {
            v.iter()
                .any(|d| want.as_deref().is_none_or(|t| d.topology() == t))
        })
    };
    let mut wait = Duration::from_secs(args.wait);
    let mut waiting = waiting;
    if waiting {
        wait = wait.max(BOOT_WAIT);
    }
    let mut entered = false;
    let mut via_app = false;
    if entry != IspEntry::None && !ch32rv_usb::replay::active() && !present(&want) {
        let via = match entry {
            IspEntry::Probe => Via::Probe,
            _ => match enter_via_app(cli, cmd, args, entry, app)? {
                AppEntry::Sent(at) => {
                    // The bootloader comes up where the application was (same USB port).
                    want.get_or_insert(at);
                    Via::App
                }
                AppEntry::Unanswered(_) if cli.probe.is_some() => Via::Probe,
                // The user brings it up with BOOT: wait as the IDE's waiting port does (the BOOT
                // key with a reset or a replug brings it up on the same USB port).
                AppEntry::Unanswered(at) => {
                    want.get_or_insert(at);
                    waiting = true;
                    wait = wait.max(BOOT_WAIT);
                    Via::Nothing
                }
                AppEntry::Nothing if entry == IspEntry::Auto && cli.probe.is_some() => Via::Probe,
                AppEntry::Nothing => Via::Nothing,
            },
        };
        if via == Via::Probe {
            enter_via_probe(cli, cmd)?;
        }
        if via != Via::Nothing {
            entered = true;
            wait = wait.max(ENTER_WAIT);
        }
        via_app = via == Via::App;
    }
    let mut deadline = Instant::now() + wait;
    let mut asked_again = false;
    let mut told = false;
    let mut countdown = Countdown::new(deadline);
    let dev = loop {
        let found = match ch32rv_isp::list() {
            Ok(v) => v,
            Err(e) => {
                return Err(fail(
                    cli,
                    cmd,
                    ErrorKind::DeviceOpenFailed,
                    e.to_string(),
                    None,
                ));
            }
        };
        let mut found: Vec<UsbDeviceInfo> = found
            .into_iter()
            .filter(|d| want.as_deref().is_none_or(|t| d.topology() == t))
            .collect();
        if found.len() > 1 {
            let at: Vec<serde_json::Value> = found
                .iter()
                .map(|d| serde_json::json!(format!("topology:{}", d.topology())))
                .collect();
            return Err(crate::cmd_probe::fail_with_candidates(
                cli,
                cmd,
                ErrorKind::DeviceAmbiguous,
                format!("{} ISP devices are connected", found.len()),
                Some(
                    "pick one with --device ch32rv-isp://<bus>-<ports> (the IDE's ch32rv-isp:// port)",
                ),
                at,
            ));
        }
        if let Some(d) = found.pop() {
            break d;
        }
        // en: Asked, but no bootloader came and the application is still there: it did not take
        // the request (an application still coming up after its previous restart, measured once
        // in six uploads 3 s apart on a busy host). Ask once more and wait again.
        // ja: 頼んだのに bootloader が来ず、アプリがまだ居る: 依頼を受け損ねた(前の再起動から立ち
        // 上がりきっていないアプリ。忙しい host で 3 秒おきの書き込み 6 回に 1 回)。もう 1 度頼んで待つ。
        if via_app
            && !asked_again
            && Instant::now() >= deadline
            && want.as_deref().is_some_and(app_still_at)
        {
            asked_again = true;
            if !cli.json {
                println!("no bootloader yet and the application is still there: asking it again");
            }
            if let AppEntry::Sent(_) = enter_via_app(cli, cmd, args, entry, None)? {
                deadline = Instant::now() + ENTER_WAIT;
                countdown = Countdown::new(deadline);
                continue;
            }
        }
        if ch32rv_usb::replay::active() || Instant::now() >= deadline {
            return Err(fail(
                cli,
                cmd,
                ErrorKind::DeviceNotFound,
                match (&want, entered) {
                    (_, true) => format!(
                        "the chip was sent to its bootloader, but no ISP device appeared{} within {} s",
                        want.as_deref()
                            .map(|t| format!(" at topology:{t}"))
                            .unwrap_or_default(),
                        wait.as_secs()
                    ),
                    (Some(t), false) => format!("no ISP device at topology:{t}"),
                    (None, false) => "no ISP device (1a86:55e0 / 4348:55e0) was found".to_owned(),
                },
                Some(if entered {
                    "is the chip's own USB (D+/D-) connected to this host? the bootloader returns to the application after ~10 s unattended"
                } else {
                    ENTRY_HINT
                }),
            ));
        }
        // en: After an entry over the debug wire the device is simply on its way; otherwise say
        // how to get it there, once (also under `--progress none`: an IDE shows only stderr).
        // ja: debug 線で入れた後は来るのを待つだけ。それ以外は入り方を 1 回出す。
        if !told && !entered {
            told = true;
            if waiting {
                eprintln!(
                    "waiting up to {} s for the board's USB bootloader (ISP, 1a86:55e0) ...",
                    wait.as_secs()
                );
                eprintln!(
                    "  put the chip in its bootloader now: hold BOOT and reset it (or plug in USB with BOOT held)"
                );
            } else {
                eprintln!(
                    "waiting up to {} s for an ISP device (1a86:55e0) ...",
                    wait.as_secs()
                );
                eprintln!("  {ENTRY_HINT}");
            }
        }
        countdown.tick();
        std::thread::sleep(Duration::from_millis(200));
    };
    if told && !cli.json {
        println!("ISP device found at topology:{}", dev.topology());
    }
    let usb = dev.usb_id();
    let topology = dev.topology();
    // en: A bootloader that has just enumerated is often not ours yet: udev applies the rule's mode
    // and ACL a moment later (access denied), and a system service may look at it first (busy).
    // Both pass, so they are waited out for a short while; a missing rule still fails after it.
    // Measured: 1 of 3 back-to-back DFU_DETACH entries failed with EACCES on a host with the rule
    // (ArduinoCore-CH32RV's usb-upload test, CH32X035).
    // ja: 列挙されたばかりの bootloader はすぐには開けない。udev がルールの mode と ACL を付けるのが
    // 少し遅れ(access denied)、システムのサービスが先に見ることもある(busy)。少し待つ。ルールが
    // 無ければその後も失敗する。ルールのある host で、続けて 3 回のうち 1 回が EACCES だった。
    let open_until = Instant::now() + OPEN_RETRY;
    let mut isp = loop {
        match IspDevice::open(&dev) {
            Ok(i) => break i,
            Err(ch32rv_isp::IspError::Usb(
                ch32rv_usb::UsbError::AccessDenied(_) | ch32rv_usb::UsbError::Busy(_),
            )) if Instant::now() < open_until => std::thread::sleep(Duration::from_millis(100)),
            Err(e) => return Err(isp_fail(cli, cmd, e)),
        }
    };
    if let Some(s) = cli.timeout {
        isp.set_timeout(Duration::from_secs(s));
    }
    let id = isp.identify().map_err(|e| isp_fail(cli, cmd, e))?;
    let cfg = isp.read_config().map_err(|e| isp_fail(cli, cmd, e))?;
    Ok(Opened {
        dev: isp,
        usb: Some(usb),
        at: format!("topology:{topology}"),
        topology: Some(topology),
        id,
        cfg,
    })
}

/// en: The bootloader on `--port` (`--baud`, default 115200). An entry asked for is made first,
/// then Identify is retried until `--wait` (at least the entry's settling time) runs out: a UART
/// has no arrival to watch for.
/// ja: `--port` の bootloader。entry を指定されたら先に入れ、UART には「現れる」が無いので
/// `--wait` の間 Identify を繰り返す。
fn open_uart(cli: &Cli, cmd: &str, args: &IspArgs, entry: IspEntry) -> Result<Opened, ExitCode> {
    let Some(port) = args.port.as_deref() else {
        return Err(fail(
            cli,
            cmd,
            ErrorKind::Usage,
            "--transport uart needs --port <serial port>".to_owned(),
            Some("the serial port wired to the chip's bootloader USART (e.g. /dev/ttyUSB0)"),
        ));
    };
    let baud = args.baud.unwrap_or(ch32rv_isp::UART_BAUD);
    let mut wait = Duration::from_secs(args.wait);
    match entry {
        IspEntry::None => {}
        IspEntry::Probe => {
            enter_via_probe(cli, cmd)?;
            wait = wait.max(ENTER_WAIT);
        }
        _ => {
            let via_app = matches!(
                enter_via_app(cli, cmd, args, entry, None)?,
                AppEntry::Sent(_)
            );
            if !via_app && entry == IspEntry::Auto && cli.probe.is_some() {
                enter_via_probe(cli, cmd)?;
            }
            wait = wait.max(ENTER_WAIT);
        }
    }
    let deadline = Instant::now() + wait;
    let mut isp = IspDevice::open_serial(port, baud).map_err(|e| isp_fail(cli, cmd, e))?;
    isp.set_timeout(Duration::from_millis(500));
    let id = loop {
        match isp.identify() {
            Ok(id) => break id,
            Err(e @ ch32rv_isp::IspError::NotFactoryIsp(_)) => return Err(isp_fail(cli, cmd, e)),
            Err(e) if Instant::now() >= deadline => {
                return Err(fail(
                    cli,
                    cmd,
                    ErrorKind::DeviceNotFound,
                    format!("no ISP bootloader answered on {port} at {baud} bps ({e})"),
                    Some(ENTRY_HINT),
                ));
            }
            Err(_) => std::thread::sleep(Duration::from_millis(200)),
        }
    };
    isp.set_timeout(
        cli.timeout
            .map_or(Duration::from_secs(5), Duration::from_secs),
    );
    let cfg = isp.read_config().map_err(|e| isp_fail(cli, cmd, e))?;
    Ok(Opened {
        dev: isp,
        usb: None,
        topology: None,
        at: format!("uart:{port}"),
        id,
        cfg,
    })
}

const ENTRY_HINT: &str = "put the chip in its bootloader: CH32X03x - plug in USB with the BOOT/DOWNLOAD key (PC17 = D+ high) held, or `--entry probe` over a debug probe; BOOT0 parts - BOOT0 high at reset";

/// en: Why the bootloader's USB device may not open, per OS: Windows - a driver that is neither
/// WinUSB nor WCH's CH375-class one; elsewhere - permissions (no udev rule).
/// ja: bootloader の USB device が開けない理由(OS ごと)。Windows は WinUSB でも WCH の CH375 系
/// でもないドライバ、他は権限(udev のルール)。
const OPEN_HINT: &str = if cfg!(windows) {
    "the bootloader's USB device (1a86:55e0) has a driver ch32rv cannot use: WinUSB (e.g. installed with Zadig) and WCH's own driver work; check it in Device Manager"
} else {
    "check permissions for the device: the udev rule for 1a86:55e0 / 4348:55e0 (`ch32rv doctor --emit-udev`)"
};

fn isp_fail(cli: &Cli, cmd: &str, e: IspError) -> ExitCode {
    let (kind, hint) = match &e {
        IspError::Usb(ch32rv_usb::UsbError::Open(_) | ch32rv_usb::UsbError::AccessDenied(_)) => {
            (ErrorKind::DeviceOpenFailed, Some(OPEN_HINT))
        }
        IspError::Serial(_) => (ErrorKind::DeviceOpenFailed, None),
        IspError::Usb(_)
        | IspError::ShortWrite { .. }
        | IspError::UnexpectedReply { .. }
        | IspError::SerialTimeout
        | IspError::Checksum { .. } => (ErrorKind::TransferFailed, None),
        IspError::NotFactoryIsp(_) => (
            ErrorKind::CapabilityUnsupported,
            Some("a WCH-Link in IAP mode uses the same USB ID: see `ch32rv probe firmware`"),
        ),
        IspError::KeyMismatch { .. } | IspError::Status { .. } | IspError::NoKey => {
            (ErrorKind::TransferFailed, None)
        }
        IspError::VerifyMismatch(_) => (ErrorKind::VerifyMismatch, None),
        IspError::ImageTooLarge { .. } => (ErrorKind::Usage, None),
    };
    fail(cli, cmd, kind, e.to_string(), hint)
}

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

fn series(id: Identity) -> String {
    ch32rv_isp::series_name(id.device_type).map_or_else(
        || format!("unknown (0x{:02x})", id.device_type),
        str::to_owned,
    )
}

/// en: The part the bootloader's Identify names (narrowed by a part-number `chip`), if one.
/// ja: bootloader の Identify が指す型番(型番の `chip` で絞る)。
fn isp_part(chip: Option<&str>, id: Identity) -> Option<crate::cmd_target::FlashedPart> {
    let db = ch32rv_target::Db::builtin();
    match db.resolve_isp(ch32rv_isp::db_families(id.device_type), id.chip_id, chip) {
        ch32rv_target::Resolution::Sku(s) => Some(crate::cmd_target::FlashedPart {
            sku: s.sku.clone(),
            flash_bytes: s.flash_bytes,
            sram_bytes: s.sram_bytes,
        }),
        _ => None,
    }
}

/// en: `--chip` against the bootloader's Identify, fail-closed where the device type maps to DB
/// families: a name in none of them, or a part number whose device id is another chip, stops the
/// command before it writes (an image built for a larger part must not go to a smaller one). A
/// device type the DB has no families for is not checked.
/// ja: `--chip` と Identify の照合。device type が DB の family に結びつくときだけ fail-closed で、
/// family が違う名前、別の chip の型番なら書く前に止める。結びつかない type は照合しない。
fn check_chip(cli: &Cli, cmd: &str, id: Identity) -> Result<(), ExitCode> {
    let Some(chip) = cli.chip.as_deref() else {
        return Ok(());
    };
    let families = ch32rv_isp::db_families(id.device_type);
    if families.is_empty() {
        return Ok(());
    }
    let db = ch32rv_target::Db::builtin();
    let named = db.families_for_chip_name(chip);
    let conflict = if !named
        .iter()
        .any(|n| families.iter().any(|f| f.eq_ignore_ascii_case(n)))
    {
        Some(series(id))
    } else {
        let want = db
            .skus()
            .iter()
            .find(|s| s.sku.eq_ignore_ascii_case(chip))
            .and_then(|s| s.device_id);
        match want {
            Some(d) if (d >> 16) as u8 != id.chip_id => Some(isp_part(None, id).map_or_else(
                || format!("{} chip 0x{:02x}", series(id), id.chip_id),
                |p| p.sku,
            )),
            _ => None,
        }
    };
    match conflict {
        Some(other) => Err(fail(
            cli,
            cmd,
            ErrorKind::TargetAmbiguous,
            format!(
                "--chip {chip} conflicts with the bootloader's {other} (chip 0x{:02x}, type 0x{:02x})",
                id.chip_id, id.device_type
            ),
            Some("pass the correct --chip, or omit it"),
        )),
        None => Ok(()),
    }
}

fn describe(o: &Opened) -> serde_json::Value {
    serde_json::json!({
        "usb": o.usb,
        "topology": o.topology,
        "at": o.at,
        "series": ch32rv_isp::series_name(o.id.device_type),
        "sku": isp_part(None, o.id).map(|p| p.sku),
        "chip_id": format!("0x{:02x}", o.id.chip_id),
        "device_type": format!("0x{:02x}", o.id.device_type),
        "btver": o.cfg.btver_text(),
        "uid": hex(&o.cfg.uid),
        "read_protected": o.cfg.read_protected(),
        "config": hex(&o.cfg.config),
        "flash_bytes": ch32rv_isp::flash_size(o.id),
    })
}

fn list(cli: &Cli) -> ExitCode {
    const CMD: &str = "isp.list";
    let devs = match ch32rv_isp::list() {
        Ok(v) => v,
        Err(e) => return fail(cli, CMD, ErrorKind::DeviceOpenFailed, e.to_string(), None),
    };
    let mut rows = Vec::new();
    for d in &devs {
        // Ask each to Identify: a factory bootloader answers, a WCH-Link in IAP mode does not.
        let answer = IspDevice::open(d).and_then(|mut i| {
            i.set_timeout(Duration::from_secs(1));
            i.identify()
        });
        rows.push(match answer {
            Ok(id) => serde_json::json!({
                "usb": d.usb_id(), "topology": d.topology(), "kind": "factory-isp",
                "series": ch32rv_isp::series_name(id.device_type),
                "chip_id": format!("0x{:02x}", id.chip_id),
                "device_type": format!("0x{:02x}", id.device_type),
            }),
            Err(e) => serde_json::json!({
                "usb": d.usb_id(), "topology": d.topology(), "kind": "unknown",
                "error": e.to_string(),
            }),
        });
    }
    if cli.json {
        let mut env = ResultEnvelope::success(CMD);
        env.result = Some(serde_json::json!({ "devices": rows }));
        return crate::print_envelope(&env);
    }
    if rows.is_empty() {
        println!("no ISP device");
    }
    for r in &rows {
        let s = |k: &str| r[k].as_str().unwrap_or("-").to_owned();
        if s("kind") == "factory-isp" {
            println!(
                "topology:{:<14} {}  {} chip 0x{} type {}",
                s("topology"),
                s("usb"),
                s("series"),
                s("chip_id").trim_start_matches("0x"),
                s("device_type")
            );
        } else {
            println!(
                "topology:{:<14} {}  not a factory bootloader ({})",
                s("topology"),
                s("usb"),
                s("error")
            );
        }
    }
    ExitCode::SUCCESS
}

fn info(cli: &Cli, args: &IspArgs) -> ExitCode {
    const CMD: &str = "isp.info";
    let o = match open(cli, CMD, args) {
        Ok(o) => o,
        Err(c) => return c,
    };
    if cli.json {
        let mut env = ResultEnvelope::success(CMD);
        env.result = Some(describe(&o));
        return crate::print_envelope(&env);
    }
    match &o.usb {
        Some(usb) => println!("usb:      {usb} at {}", o.at),
        None => println!("port:     {}", o.at),
    }
    match isp_part(cli.chip.as_deref(), o.id) {
        Some(p) => println!(
            "chip:     {} ({}, chip 0x{:02x}, type 0x{:02x}; {} KiB flash, {} KiB SRAM)",
            p.sku,
            series(o.id),
            o.id.chip_id,
            o.id.device_type,
            p.flash_bytes / 1024,
            p.sram_bytes / 1024
        ),
        None => println!(
            "chip:     {} (chip 0x{:02x}, type 0x{:02x})",
            series(o.id),
            o.id.chip_id,
            o.id.device_type
        ),
    }
    if let Some(n) = ch32rv_isp::flash_size(o.id) {
        println!("flash:    {} KiB", n / 1024);
    }
    println!("btver:    {}", o.cfg.btver_text());
    println!("uid:      {}", hex(&o.cfg.uid));
    println!(
        "protect:  {}",
        if o.cfg.read_protected() {
            "read-protected"
        } else {
            "off"
        }
    );
    println!("config:   {}", hex(&o.cfg.config));
    ExitCode::SUCCESS
}

/// en: The image (bin / Intel HEX / ELF) as one block from the start of code flash (`0xff` in
/// gaps), for a bootloader, which addresses flash by offset (the ISP and the HID one alike).
/// ja: code flash 先頭からの 1 塊にした image(ISP と HID の bootloader が使う)。
pub(crate) fn load_image(
    cli: &Cli,
    cmd: &str,
    file: &std::path::Path,
) -> Result<Vec<u8>, ExitCode> {
    let bytes = std::fs::read(file).map_err(|e| {
        fail(
            cli,
            cmd,
            ErrorKind::Usage,
            format!("read {}: {e}", file.display()),
            None,
        )
    })?;
    let image =
        crate::cmd_flash::parse_image(&bytes, ImageFormat::Auto, file, None, CODE_FLASH_START)
            .map_err(|e| fail(cli, cmd, ErrorKind::Usage, e.to_string(), None))?;
    let mut flat = Vec::new();
    for s in &image.segments {
        // Low alias (0x0000_0000) and the physical address both count from the start of flash.
        let base = if s.addr >= CODE_FLASH_START {
            s.addr - CODE_FLASH_START
        } else {
            s.addr
        };
        if base >= 0x0010_0000 {
            return Err(fail(
                cli,
                cmd,
                ErrorKind::Usage,
                format!(
                    "segment at 0x{:08x} is outside code flash; the bootloader writes code flash only",
                    s.addr
                ),
                None,
            ));
        }
        let end = base as usize + s.data.len();
        if flat.len() < end {
            flat.resize(end, 0xff);
        }
        flat[base as usize..end].copy_from_slice(&s.data);
    }
    if flat.is_empty() {
        return Err(fail(cli, cmd, ErrorKind::Usage, "image is empty", None));
    }
    Ok(flat)
}

/// en: One line on the chip the bootloader answers for, before anything is done to it: the part,
/// the bootloader's version and the protection, so that a refusal or a failure that follows can
/// be read against it. ja: bootloader が答えた chip の状態を 1 行(型番、bootloader の版、保護)。
fn say_state(cli: &Cli, o: &Opened) {
    if cli.json {
        return;
    }
    let part = isp_part(cli.chip.as_deref(), o.id)
        .map(|p| format!("{} ", p.sku))
        .unwrap_or_default();
    let wrpr = ch32rv_isp::OptionFields::from_config(&o.cfg.config).wrpr;
    println!(
        "chip: {part}({}, chip 0x{:02x}, type 0x{:02x}), bootloader {}, read-protect {}, write-protect 0x{:08x}",
        series(o.id),
        o.id.chip_id,
        o.id.device_type,
        o.cfg.btver_text(),
        if o.cfg.read_protected() { "on" } else { "off" },
        !wrpr,
    );
}

/// en: A read-protected chip: refused before anything is written, or with `--unprotect` the
/// protection turned off and the bootloader opened again. Its bootloader takes the program frames
/// but the flash does not change while protected, and the failure only showed at the verify
/// ("verify mismatch in the chunk at offset 0x000000", a CH32X035 on Windows). Turning it off
/// erases code flash, and it takes effect only at the chip's next reset (measured: written in the
/// same session, the verify still failed on a CH32X035G8U6, bootloader 2.60), so the bootloader
/// is left (the chip resets) and the user brings it up again (BOOT), waited for at the same place.
/// ja: 読み出し保護された chip。書く前に断るか、`--unprotect` なら保護を外して bootloader を開き直す。
/// 保護中は書き込みを受けても flash は変わらない。外すと code flash は消え、効くのは次の reset から
/// (同じ session で書くと照合がまた失敗した。CH32X035G8U6、bootloader 2.60)。なので bootloader を
/// 抜け(chip は reset)、利用者に BOOT で入れ直してもらい、同じ場所で待つ。
fn settle_protection(
    cli: &Cli,
    cmd: &str,
    args: &IspArgs,
    mut o: Opened,
    unprotect: bool,
) -> Result<Opened, ExitCode> {
    if !o.cfg.read_protected() {
        return Ok(o);
    }
    if !unprotect {
        // en: The part and bootloader named in the error itself: an IDE merges stdout and stderr
        // as they arrive, so the `chip:` line on stdout may come after it (flushing first does
        // not order two pipes). ja: エラーの文そのものに型番と版を入れる(IDE は 2 本を届いた順に
        // 混ぜるので、stdout の `chip:` の行が後に出ることがある)。
        let part = isp_part(cli.chip.as_deref(), o.id)
            .map(|p| p.sku)
            .unwrap_or_else(|| series(o.id));
        return Err(fail(
            cli,
            cmd,
            ErrorKind::TargetProtected,
            format!(
                "the chip ({part}, bootloader {}) is read-protected: its bootloader does not write code flash while it is",
                o.cfg.btver_text()
            ),
            Some(
                "turn it off with `ch32rv isp config set read-protect=off` (this erases code flash), or write with --unprotect",
            ),
        ));
    }
    if !cli.json {
        println!("read protection on: turning it off (this erases all of code flash)");
    }
    let mut want = OptionFields::from_config(&o.cfg.config);
    want.rdpr = ch32rv_isp::RDPR_OFF;
    if let Err(e) = o.dev.write_config(&want.to_config()) {
        return Err(isp_fail(cli, cmd, e));
    }
    match o.dev.read_config() {
        Ok(c) if !c.read_protected() => {}
        Ok(_) => {
            return Err(fail(
                cli,
                cmd,
                ErrorKind::TargetProtected,
                "read protection is still on after turning it off",
                Some("over a debug probe: `ch32rv recover --method unprotect`"),
            ));
        }
        Err(e) => return Err(isp_fail(cli, cmd, e)),
    }
    // Leave the bootloader: the chip resets, and the protection is off from then on.
    let topology = o.topology.clone();
    let _ = o.dev.end(true);
    // en: The user must act (stderr, which an IDE always shows); the wait that follows is the
    // waiting port's, whose one line says how (BOOT), rather than the general entry hint.
    // ja: 利用者がすること(stderr)。続く待ちは待つポートのもので、その 1 行が入り方(BOOT)を言う。
    eprintln!("read protection is off; it takes effect at the chip's reset");
    let again = IspArgs {
        cmd: crate::args::IspCmd::Reset,
        transport: args.transport,
        port: args.port.clone(),
        baud: args.baud,
        device: match (&topology, args.transport) {
            (Some(_), IspTransport::Usb) => Some(format!("{BOOTLOADER_SCHEME}{WAIT_FOR_BOOT}")),
            _ => None,
        },
        wait: BOOT_WAIT.as_secs().max(args.wait),
        entry: IspEntry::None,
    };
    // Give the chip a moment to leave before the bootloader is looked for again.
    std::thread::sleep(Duration::from_millis(500));
    let o = open(cli, cmd, &again)?;
    say_state(cli, &o);
    if o.cfg.read_protected() {
        return Err(fail(
            cli,
            cmd,
            ErrorKind::TargetProtected,
            "the chip is still read-protected after it was turned off and reset",
            Some("over a debug probe: `ch32rv recover --method unprotect`"),
        ));
    }
    Ok(o)
}

fn check_size(cli: &Cli, cmd: &str, o: &Opened, image: &[u8]) -> Result<(), ExitCode> {
    match ch32rv_isp::flash_size(o.id) {
        Some(limit) if image.len() > limit => Err(isp_fail(
            cli,
            cmd,
            IspError::ImageTooLarge {
                actual: image.len(),
                limit,
            },
        )),
        _ => Ok(()),
    }
}

fn progress(cli: &Cli, phase: &'static str, total: usize) -> impl FnMut(usize) {
    let show =
        !cli.json && cli.progress.is_none() && std::io::IsTerminal::is_terminal(&std::io::stderr());
    let mut last = 0usize;
    move |done| {
        if show && (done - last >= 4096 || done == total) {
            last = done;
            eprint!("\r{phase}: {done}/{total} bytes");
            if done == total {
                eprintln!();
            }
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn flash(
    cli: &Cli,
    args: &IspArgs,
    file: &std::path::Path,
    erase: EraseMode,
    verify: IspVerify,
    reset: IspReset,
    unprotect: bool,
) -> ExitCode {
    const CMD: &str = "isp.flash";
    let image = match load_image(cli, CMD, file) {
        Ok(i) => i,
        Err(c) => return c,
    };
    let store = std::fs::read(file)
        .ok()
        .and_then(|b| ch32rv_flash::store_region(&b, CODE_FLASH_START));
    let o = match open(cli, CMD, args) {
        Ok(o) => o,
        Err(c) => return c,
    };
    say_state(cli, &o);
    if let Err(c) = check_chip(cli, CMD, o.id) {
        return c;
    }
    let mut o = match settle_protection(cli, CMD, args, o, unprotect) {
        Ok(o) => o,
        Err(c) => return c,
    };
    if let Err(c) = check_size(cli, CMD, &o, &image) {
        return c;
    }
    let cfg = o.cfg.clone();
    if let Err(e) = o.dev.set_key(&cfg) {
        return isp_fail(cli, CMD, e);
    }
    let erased = match isp_erase_plan(erase, image.len(), store, ch32rv_isp::flash_size(o.id)) {
        Ok(p) => p,
        Err(m) => {
            return fail(
                cli,
                CMD,
                ErrorKind::CapabilityUnsupported,
                m,
                Some("use --erase sector or keep-store, or erase first with `isp erase`"),
            );
        }
    };
    if let Some(n) = erased
        && let Err(e) = o.dev.erase_exact(n)
    {
        return isp_fail(cli, CMD, e);
    }
    if let Err(e) = o.dev.program(&image, progress(cli, "program", image.len())) {
        return isp_fail(cli, CMD, e);
    }
    let verified = verify == IspVerify::On;
    if verified && let Err(e) = o.dev.verify(&image, progress(cli, "verify", image.len())) {
        return isp_fail(cli, CMD, e);
    }
    let running = reset == IspReset::Run;
    let summary = describe(&o);
    let part = isp_part(cli.chip.as_deref(), o.id);
    if let Err(e) = o.dev.end(running) {
        return isp_fail(cli, CMD, e);
    }
    if cli.json {
        let mut env = ResultEnvelope::success(CMD);
        env.result = Some(serde_json::json!({
            "flash": {
                "bytes": image.len(),
                "programmer": "isp",
                "family": summary["series"],
                "sku": part.as_ref().map(|p| p.sku.clone()),
                "usb": summary["usb"],
                "chip_id": summary["chip_id"],
                "erased_sectors": erased,
                // Not verified (`--verify off`) is null; a mismatch fails the command.
                "verified": verified.then_some(true),
                // Left in the bootloader: the application does not run.
                "running": running,
                "skipped": false,
                "scope": erase.as_str(),
            },
            "device": summary,
        }));
        if erase == EraseMode::KeepStore
            && let Some(r) = env.result.as_mut()
        {
            // The sectors erased stop below the STORE (isp_erase_plan): it is never touched.
            r["flash"]["store"] = crate::cmd_flash::store_json(store, "untouched");
        }
        crate::print_envelope(&env)
    } else {
        println!(
            "flashed {} byte(s) through the ISP bootloader ({} at {}){}{}",
            image.len(),
            crate::cmd_target::flashed_to(&series(o.id), part.as_ref(), cli.chip.as_deref()),
            o.at,
            if verified { ", verified" } else { "" },
            if running {
                ", application started"
            } else {
                ", left in the bootloader"
            }
        );
        ExitCode::SUCCESS
    }
}

/// en: The 1 KiB sectors `isp flash` has the bootloader erase from the start of code flash
/// (`None`: no erase) for `--erase`. `chip`: all of code flash (`flash_size` must be known).
/// `sector`: the image's sectors, at least the bootloader's minimum of 8. `keep-store`: the same,
/// but when the minimum would reach into the STORE, only the image's own sectors. `none`: none.
/// ja: `isp flash` が消す sector の数。keep-store は最小の 8 が STORE に届くとき、image の分だけ。
fn isp_erase_plan(
    erase: EraseMode,
    image_len: usize,
    store: Option<ch32rv_flash::StoreRegion>,
    flash_size: Option<usize>,
) -> Result<Option<u32>, String> {
    let covered = ch32rv_isp::sectors_for(image_len);
    Ok(match erase {
        EraseMode::None => None,
        EraseMode::Chip => match flash_size {
            Some(size) => Some(ch32rv_isp::sectors_for(size)),
            None => {
                return Err(
                    "the code flash size of this chip is not known, so --erase chip cannot be sized"
                        .to_owned(),
                );
            }
        },
        EraseMode::Sector => Some(ch32rv_isp::erase_count(covered)),
        EraseMode::KeepStore => {
            let n = ch32rv_isp::erase_count(covered);
            let reaches = store.is_some_and(|s| {
                let store_off = u64::from(s.addr.saturating_sub(CODE_FLASH_START));
                u64::from(n) * ch32rv_isp::SECTOR as u64 > store_off
            });
            Some(if reaches { covered } else { n })
        }
    })
}

fn verify_only(cli: &Cli, args: &IspArgs, file: &std::path::Path) -> ExitCode {
    const CMD: &str = "isp.verify";
    let image = match load_image(cli, CMD, file) {
        Ok(i) => i,
        Err(c) => return c,
    };
    let o = match open(cli, CMD, args) {
        Ok(o) => o,
        Err(c) => return c,
    };
    say_state(cli, &o);
    if let Err(c) = check_chip(cli, CMD, o.id) {
        return c;
    }
    let mut o = match settle_protection(cli, CMD, args, o, false) {
        Ok(o) => o,
        Err(c) => return c,
    };
    if let Err(c) = check_size(cli, CMD, &o, &image) {
        return c;
    }
    let cfg = o.cfg.clone();
    if let Err(e) = o.dev.set_key(&cfg) {
        return isp_fail(cli, CMD, e);
    }
    if let Err(e) = o.dev.verify(&image, progress(cli, "verify", image.len())) {
        return isp_fail(cli, CMD, e);
    }
    if cli.json {
        let mut env = ResultEnvelope::success(CMD);
        env.result = Some(serde_json::json!({ "bytes": image.len(), "verified": true }));
        crate::print_envelope(&env)
    } else {
        println!("verified {} byte(s): match", image.len());
        ExitCode::SUCCESS
    }
}

fn erase_only(cli: &Cli, args: &IspArgs) -> ExitCode {
    const CMD: &str = "isp.erase";
    let mut o = match open(cli, CMD, args) {
        Ok(o) => o,
        Err(c) => return c,
    };
    say_state(cli, &o);
    let Some(size) = ch32rv_isp::flash_size(o.id) else {
        return fail(
            cli,
            CMD,
            ErrorKind::CapabilityUnsupported,
            format!(
                "code flash size of {} is not known; nothing was erased",
                series(o.id)
            ),
            None,
        );
    };
    if let Err(m) = crate::cmd_probe::confirm_destructive(cli, "erase all of code flash?") {
        return fail(cli, CMD, ErrorKind::Usage, m, None);
    }
    let sectors = ch32rv_isp::sectors_for(size);
    if let Err(e) = o.dev.erase(sectors) {
        return isp_fail(cli, CMD, e);
    }
    if cli.json {
        let mut env = ResultEnvelope::success(CMD);
        env.result = Some(serde_json::json!({ "erased_sectors": sectors }));
        crate::print_envelope(&env)
    } else {
        println!("erased {sectors} sector(s) (all of code flash)");
        ExitCode::SUCCESS
    }
}

fn reset(cli: &Cli, args: &IspArgs) -> ExitCode {
    const CMD: &str = "isp.reset";
    let o = match open(cli, CMD, args) {
        Ok(o) => o,
        Err(c) => return c,
    };
    if let Err(e) = o.dev.end(true) {
        return isp_fail(cli, CMD, e);
    }
    if cli.json {
        crate::print_envelope(&ResultEnvelope::success(CMD))
    } else {
        println!("left the bootloader; application started");
        ExitCode::SUCCESS
    }
}

/// How long a chip put in its bootloader over the debug wire takes to enumerate, at most.
const ENTER_WAIT: Duration = Duration::from_secs(5);
/// How long a just-enumerated bootloader's permission / busy refusal is waited out.
const OPEN_RETRY: Duration = Duration::from_secs(2);

const FLASH_KEYR: u32 = 0x4002_2004;
const FLASH_STATR: u32 = 0x4002_200c;
const FLASH_BOOT_MODEKEYR: u32 = 0x4002_2028;
const FLASH_KEY1: u32 = 0x4567_0123;
const FLASH_KEY2: u32 = 0xcdef_89ab;
pub(crate) const FLASH_OBR: u32 = 0x4002_201c;
/// `FLASH_OBR.RDPRT`: read protection is in force.
pub(crate) const OBR_RDPRT: u32 = 1 << 1;
/// en: Why `--entry probe` refuses a read-protected chip: measured on CH32X035F8U6 (BTVER 2.60,
/// 2026-10-14), the factory bootloader does not run while read protection is on - entered over the
/// debug wire, or from the application after a debugger-free power-up, it stops at PC 0 and never
/// enumerates. ja: 保護中は factory bootloader が走らない(debug 線から入れても、debugger 無しの電源
/// 投入後に app から入れても、PC 0 で止まり列挙されない。X035 実測)。
fn protected(cli: &Cli, cmd: &str) -> ExitCode {
    fail(
        cli,
        cmd,
        ErrorKind::TargetProtected,
        "the chip is read-protected, and its factory bootloader does not run while it is",
        Some(
            "clear the protection over the debug wire: `ch32rv recover --method unprotect` (erases code flash)",
        ),
    )
}

/// `FLASH_STATR.BOOT_MODE`: boot from the BOOT area after the next system reset.
const STATR_BOOT_MODE: u32 = 1 << 14;

/// en: Families whose boot area is chosen in software (`FLASH_STATR.BOOT_MODE`) and holds the
/// factory ISP bootloader; ch32rv has entered it this way on CH32X035 (2026-10-13). CH32H417's
/// reference manual (46.4) gives the same registers and key (BOOT_MODEKEYR 0x40022028,
/// FLASH_STATR bit 14); its ROM opens USB download on USBFS (PA11 / PA12) only while the USER
/// option bit USBFSDLEN is set.
/// ja: BOOT 領域をソフトウェアで選べ、そこに factory ISP がある系列。H417 も RM 46.4 で同じ(USBFS の
/// ダウンロードは USER の USBFSDLEN が立っているときだけ)。
fn boot_mode_family(family: &str) -> bool {
    matches!(
        family.to_ascii_uppercase().as_str(),
        "CH32X035" | "CH32X033" | "CH32H417"
    )
}

/// en: Over the debug wire: reset the hart and catch it at the reset vector (whatever is in flash
/// must not run first - it may touch the flash keys and lock them until the next reset), unlock
/// the boot-mode key, set `BOOT_MODE`, and reset into the bootloader.
/// ja: debug 線で、hart を reset vector で捕まえ(flash の中身を先に走らせない。鍵を触って次の reset
/// までロックしうる)、boot mode の鍵を外し、`BOOT_MODE` を立てて bootloader へ reset する。
fn set_boot_mode<T: TargetAccess + ?Sized>(t: &mut T) -> Result<(), DmiError> {
    t.reset(ResetMode::HaltAtReset)?;
    t.write_words(FLASH_KEYR, &[FLASH_KEY1])?;
    t.write_words(FLASH_KEYR, &[FLASH_KEY2])?;
    t.write_words(FLASH_BOOT_MODEKEYR, &[FLASH_KEY1])?;
    t.write_words(FLASH_BOOT_MODEKEYR, &[FLASH_KEY2])?;
    let statr = t.read_words(FLASH_STATR, 1)?[0];
    t.write_words(FLASH_STATR, &[statr | STATR_BOOT_MODE])?;
    let statr = t.read_words(FLASH_STATR, 1)?[0];
    if statr & STATR_BOOT_MODE == 0 {
        return Err(DmiError::OperationFailed(format!(
            "BOOT_MODE did not stick (FLASH_STATR = 0x{statr:08x})"
        )));
    }
    t.reset(ResetMode::Run).map(|_| ())
}

/// en: `--entry probe` / `isp enter --via probe`: through `--probe` (an OEP probe; a WCH-Link is
/// not wired up yet), set the boot mode and reset. The caller then waits for the device.
/// ja: `--probe`(OEP の probe)で boot mode を立てて reset する。device を待つのは呼び出し側。
fn enter_via_probe(cli: &Cli, cmd: &str) -> Result<(), ExitCode> {
    let a = match crate::oep::addr(cli, cmd) {
        Ok(Some(a)) => a,
        Ok(None) => return enter_via_wchlink(cli, cmd),
        Err(c) => return Err(c),
    };
    let mut outcome = Ok(());
    let code = crate::oep::with_attached(cli, cmd, &a, true, |x| {
        let family = x.family.clone().unwrap_or_default();
        if !boot_mode_family(&family) {
            return fail(
                cli,
                cmd,
                ErrorKind::CapabilityUnsupported,
                format!(
                    "{} has no software-selected boot mode ch32rv knows; nothing was changed",
                    if family.is_empty() {
                        "this chip"
                    } else {
                        &family
                    }
                ),
                Some(ENTRY_HINT),
            );
        }
        match x.t.read_words(FLASH_OBR, 1) {
            Ok(v) if v[0] & OBR_RDPRT != 0 => {
                outcome = Err(());
                return protected(cli, cmd);
            }
            _ => {}
        }
        if let Err(e) = set_boot_mode(&mut x.t) {
            outcome = Err(());
            return fail(
                cli,
                cmd,
                ErrorKind::TransferFailed,
                format!("entering the bootloader: {e}"),
                None,
            );
        }
        ExitCode::SUCCESS
    });
    if code != ExitCode::SUCCESS || outcome.is_err() {
        return Err(code);
    }
    if !cli.json {
        println!("reset into the bootloader over the debug wire");
    }
    Ok(())
}

/// en: `--entry probe` through a WCH-Link: the same steps as on an OEP probe, with the hart caught
/// by the DMI reset-halt (`ndmreset` + `haltreq`) and the final reset the probe's own system
/// reset, which keeps `BOOT_MODE`.
/// ja: WCH-Link での `--entry probe`。hart は DMI の reset-halt で捕まえ、最後は probe の system
/// reset(`BOOT_MODE` は残る)。
fn enter_via_wchlink(cli: &Cli, cmd: &str) -> Result<(), ExitCode> {
    let mut session = crate::cmd_probe::attach(cli, cmd)?;
    let family = crate::cmd_target::db_family_of(&mut session);
    if !boot_mode_family(&family) {
        return Err(fail(
            cli,
            cmd,
            ErrorKind::CapabilityUnsupported,
            format!(
                "{family} has no software-selected boot mode ch32rv knows; nothing was changed"
            ),
            Some(ENTRY_HINT),
        ));
    }
    let step = |r: Result<(), DmiError>| {
        r.map_err(|e| {
            fail(
                cli,
                cmd,
                ErrorKind::TransferFailed,
                format!("entering the bootloader: {e}"),
                None,
            )
        })
    };
    {
        let mut dm = session.dm();
        if dm.read_mem32(FLASH_OBR).is_ok_and(|v| v & OBR_RDPRT != 0) {
            return Err(protected(cli, cmd));
        }
        step(dm.reset_halt())?;
        for (addr, key) in [
            (FLASH_KEYR, FLASH_KEY1),
            (FLASH_KEYR, FLASH_KEY2),
            (FLASH_BOOT_MODEKEYR, FLASH_KEY1),
            (FLASH_BOOT_MODEKEYR, FLASH_KEY2),
        ] {
            step(dm.write_mem32(addr, key))?;
        }
        let statr = dm.read_mem32(FLASH_STATR);
        step(statr.and_then(|v| dm.write_mem32(FLASH_STATR, v | STATR_BOOT_MODE)))?;
        let statr = dm.read_mem32(FLASH_STATR);
        step(statr.and_then(|v| {
            if v & STATR_BOOT_MODE == 0 {
                Err(DmiError::OperationFailed(format!(
                    "BOOT_MODE did not stick (FLASH_STATR = 0x{v:08x})"
                )))
            } else {
                Ok(())
            }
        }))?;
    }
    crate::cmd_flash::soft_reset_and_run(&mut session).map_err(|m| {
        fail(
            cli,
            cmd,
            ErrorKind::TransferFailed,
            format!("entering the bootloader: {m}"),
            None,
        )
    })?;
    if !cli.json {
        println!("reset into the bootloader over the debug wire");
    }
    Ok(())
}

fn enter(cli: &Cli, args: &IspArgs) -> ExitCode {
    const CMD: &str = "isp.enter";
    let o = match open_with(cli, CMD, args, IspEntry::Probe) {
        Ok(o) => o,
        Err(c) => return c,
    };
    if cli.json {
        let mut env = ResultEnvelope::success(CMD);
        env.result = Some(describe(&o));
        crate::print_envelope(&env)
    } else {
        println!(
            "in the bootloader: {} (chip 0x{:02x}) at {}, btver {}",
            series(o.id),
            o.id.chip_id,
            o.at,
            o.cfg.btver_text()
        );
        ExitCode::SUCCESS
    }
}

#[derive(PartialEq, Eq)]
enum Via {
    Probe,
    App,
    Nothing,
}

/// en: The position in a `--device` that names one: `ch32rv-isp://<t>` or `topology:<t>` (`Err`
/// when `<t>` is empty). None for a form that names a device another way.
/// ja: `--device` の位置(`ch32rv-isp://` か `topology:`)。ほかの形は None。
fn position(d: &str) -> Option<Result<&str, ()>> {
    d.strip_prefix(ISP_SCHEME)
        .or_else(|| d.strip_prefix("topology:"))
        .map(|t| if t.is_empty() { Err(()) } else { Ok(t) })
}

/// The application's USB device named by `--device`, and the serial port it was named by.
pub(crate) struct AppDevice {
    pub(crate) dev: UsbDeviceInfo,
    pub(crate) port: Option<String>,
}

/// en: An IDE port address in `--device`, told apart by its shape (a URL such as
/// `ch32rv-app://...`, or a serial port's path such as `/dev/ttyACM0` / `COM3`).
/// ja: `--device` の IDE の port の住所(形で見分ける)。
fn ide_address(s: &str) -> Option<&str> {
    let com = s.len() > 3
        && s[..3].eq_ignore_ascii_case("com")
        && s[3..].chars().all(|c| c.is_ascii_digit());
    let url = ch32rv_usb::selector::ADDRESS_SCHEMES
        .iter()
        .any(|scheme| s.starts_with(scheme));
    (url || s.starts_with('/') || s.starts_with("\\\\.\\") || com).then_some(s)
}

/// en: Resolve a `--device` that names a USB device (`isp`'s application, `boot dfu`'s device):
/// an IDE port address (a serial port's path - the USB device behind it - or
/// `ch32rv-app://<id>`), `topology:<bus>-<ports>`, or `VID:PID[:SERIAL]`. Exactly one device or an
/// error. A bootloader's own address that the caller does not write (`ch32rv-hid://`,
/// `ch32rv-isp://`) is a usage error. ja: `--device` の USB device を解く。ちょうど 1 台か、エラー。
pub(crate) fn usb_device(cli: &Cli, cmd: &str, sel: &str) -> Result<AppDevice, ExitCode> {
    find_usb_device(sel).map_err(|m| m.fail(cli, cmd))
}

/// en: Why a `--device` found no one USB device. ja: `--device` が 1 台に決まらなかった理由。
struct Miss {
    kind: ErrorKind,
    msg: String,
    hint: Option<String>,
    candidates: Vec<serde_json::Value>,
}

impl Miss {
    fn new(kind: ErrorKind, msg: String, hint: Option<String>) -> Self {
        Miss {
            kind,
            msg,
            hint,
            candidates: Vec::new(),
        }
    }

    fn fail(self, cli: &Cli, cmd: &str) -> ExitCode {
        crate::cmd_probe::fail_with_candidates(
            cli,
            cmd,
            self.kind,
            self.msg,
            self.hint.as_deref(),
            self.candidates,
        )
    }

    /// en: Whether `isp` goes on without the application: it is not there (or not one), which is
    /// what the IDE's application port looks like once the chip is already in its bootloader
    /// (the port stays selected after a failed upload). The ISP device is then picked as without
    /// `--device`; a malformed address or a USB failure still stops.
    /// ja: アプリが居ない(1 台に決まらない)なら、`--device` 無しと同じに ISP device を選ぶ。チップが
    /// もう bootloader に居ると IDE のアプリの port はこう見える。形の誤りと USB の失敗は止める。
    fn app_gone(&self) -> bool {
        matches!(
            self.kind,
            ErrorKind::DeviceNotFound | ErrorKind::DeviceAmbiguous
        )
    }
}

fn find_usb_device(sel: &str) -> Result<AppDevice, Miss> {
    for (scheme, what) in [
        (crate::cmd_boot::HID_SCHEME, "boot hid flash"),
        (ISP_SCHEME, "isp"),
        (BOOTLOADER_SCHEME, "isp flash"),
    ] {
        if sel.starts_with(scheme) {
            return Err(Miss::new(
                ErrorKind::Usage,
                format!("--device `{sel}` names a bootloader this command does not write"),
                Some(format!("`{what} --device {sel}` writes it")),
            ));
        }
    }
    // The discovery's own address (`ch32rv-app://<id>`): found again by its id, then by position.
    let usb_sel;
    let sel = match ide_address(sel).and_then(|a| a.strip_prefix(APP_SCHEME)) {
        Some(id) => {
            let dev = find_app(id).map_err(|(kind, m)| Miss::new(kind, m, None))?;
            usb_sel = format!("topology:{}", dev.topology());
            usb_sel.as_str()
        }
        None => sel,
    };
    let all = ch32rv_usb::enumerate()
        .map_err(|e| Miss::new(ErrorKind::DeviceOpenFailed, e.to_string(), None))?;
    let canon = |p: &str| {
        std::fs::canonicalize(p)
            .map(|c| c.to_string_lossy().into_owned())
            .unwrap_or_else(|_| p.to_owned())
    };
    let (mut found, port): (Vec<UsbDeviceInfo>, Option<String>) =
        if let Some(path) = ide_address(sel) {
            let want = canon(path);
            let mut found: Vec<UsbDeviceInfo> = all
                .into_iter()
                .filter(|d| d.serial_ports().iter().any(|p| canon(p) == want))
                .collect();
            // en: On Linux the hubs above the device see its tty in their sysfs subtree too;
            // the device is the one no other match sits below.
            // ja: Linux では上流の hub も sysfs の下に tty を持つ。他の一致の下に居ないものが本体。
            let tops: Vec<String> = found.iter().map(UsbDeviceInfo::topology).collect();
            found.retain(|d| {
                let t = d.topology();
                !tops
                    .iter()
                    .any(|o| o.len() > t.len() && o.starts_with(&format!("{t}.")))
            });
            (found, Some(path.to_owned()))
        } else if let Some(t) = sel.strip_prefix("topology:") {
            (
                all.into_iter().filter(|d| d.topology() == t).collect(),
                None,
            )
        } else {
            let mut parts = sel.splitn(3, ':');
            let num = |s: Option<&str>| {
                s.and_then(|v| u16::from_str_radix(v.trim_start_matches("0x"), 16).ok())
            };
            let (Some(vid), Some(pid)) = (num(parts.next()), num(parts.next())) else {
                return Err(Miss::new(
                    ErrorKind::Usage,
                    format!("invalid --device `{sel}`"),
                    Some(
                        "use the serial port's path, topology:<bus>-<ports> or VID:PID[:SERIAL]"
                            .to_owned(),
                    ),
                ));
            };
            let serial = parts.next().filter(|s| !s.is_empty());
            let found = all
                .into_iter()
                .filter(|d| {
                    d.vid() == vid && d.pid() == pid && serial.is_none_or(|s| d.serial() == Some(s))
                })
                .collect();
            (found, None)
        };
    match found.len() {
        0 => Err(Miss::new(
            ErrorKind::DeviceNotFound,
            format!("no USB device matches --device `{sel}`"),
            None,
        )),
        1 => {
            let dev = found.remove(0);
            let port = port.or_else(|| dev.serial_ports().into_iter().next());
            Ok(AppDevice { dev, port })
        }
        n => Err(Miss {
            candidates: found
                .iter()
                .map(|d| serde_json::json!(format!("topology:{}", d.topology())))
                .collect(),
            ..Miss::new(
                ErrorKind::DeviceAmbiguous,
                format!("{n} USB devices match --device `{sel}`"),
                Some("name it by position: --device topology:<bus>-<ports>".to_owned()),
            )
        }),
    }
}

/// en: Ask the running application to reboot into the bootloader: DFU_DETACH to its DFU run-time
/// interface, or the 1200 bps touch on its serial port (`auto` tries them in that order).
/// Returns the application's USB position (where the bootloader will appear), or `None` when
/// `auto` found nothing to ask. A touch goes only to a device named by `--device`, so another
/// board's serial port is never reset; `dfu-detach` alone may pick the one DFU run-time device
/// present, since that interface is the device's own offer to detach. Only the request is DFU:
/// nothing is downloaded over DFU, the bootloader that comes up is WCH's factory ISP.
/// ja: DFU なのは再起動の依頼だけで、DFU では何も書かない。現れるのは WCH の factory ISP。
/// ja: 走っている app に bootloader への再起動を頼む。DFU run-time への DFU_DETACH か、serial
/// port への 1200 bps touch(`auto` はこの順)。app の USB の位置(bootloader が現れる所)を返す。
/// touch は `--device` で名指しされた device にだけ送る(他の板の serial を reset しない)。
/// `resolved` is the application `--device` already named, if the caller looked it up.
/// Whether a CH32RV application is (still) at the USB position `at`.
fn app_still_at(at: &str) -> bool {
    ch32rv_usb::enumerate().is_ok_and(|v| v.iter().any(|d| d.topology() == at && is_ch32rv_app(d)))
}

/// What asking the application to reboot into its bootloader came to.
enum AppEntry {
    /// Asked; the bootloader comes up at this position.
    Sent(String),
    /// Nothing to ask (`auto` found no application, nor a way in).
    Nothing,
    /// en: The application did not take the request (its serial port does not open: a sketch that
    /// stopped servicing USB); the user is told to bring the bootloader up with BOOT, at this
    /// position. ja: アプリが依頼を受けなかった。BOOT で入れるよう案内し、この位置で待つ。
    Unanswered(String),
}

fn enter_via_app(
    cli: &Cli,
    cmd: &str,
    args: &IspArgs,
    entry: IspEntry,
    resolved: Option<AppDevice>,
) -> Result<AppEntry, ExitCode> {
    // en: The IDE's port may be the bootloader itself (discovery's `ch32rv-isp://`): nothing to
    // ask, just use the ISP device there. ja: IDE の port が bootloader そのものなら頼む相手は無い。
    if let Some(t) = args
        .device
        .as_deref()
        .and_then(|d| d.strip_prefix(ISP_SCHEME))
    {
        return Ok(AppEntry::Sent(t.to_owned()));
    }
    let app = match (resolved, args.device.as_deref()) {
        (Some(a), _) => Some(a),
        // en: A position: whatever is there is asked; nothing there is for `auto` nothing to ask.
        // ja: 位置: そこに居るものに頼む。居なければ `auto` では頼む相手が無い。
        (None, Some(d)) if d.starts_with("topology:") => {
            let t = &d["topology:".len()..];
            let all = ch32rv_usb::enumerate()
                .map_err(|e| fail(cli, cmd, ErrorKind::DeviceOpenFailed, e.to_string(), None))?;
            match all.into_iter().find(|dev| dev.topology() == t) {
                Some(dev) => {
                    let port = dev.serial_ports().into_iter().next();
                    Some(AppDevice { dev, port })
                }
                None if entry == IspEntry::Auto => None,
                None => {
                    return Err(fail(
                        cli,
                        cmd,
                        ErrorKind::DeviceNotFound,
                        format!("no USB device at topology:{t}"),
                        None,
                    ));
                }
            }
        }
        (None, Some(sel)) => Some(find_usb_device(sel).map_err(|mut m| {
            if m.app_gone() {
                m.hint = Some(format!(
                    "the application is not connected and no ISP device is up; pick the board's port as it is now (ch32rv-isp://… once the chip is in its bootloader){}",
                    m.hint.map(|h| format!(" ({h})")).unwrap_or_default()
                ));
            }
            m.fail(cli, cmd)
        })?),
        (None, None) if entry == IspEntry::DfuDetach => {
            let all = ch32rv_usb::enumerate()
                .map_err(|e| fail(cli, cmd, ErrorKind::DeviceOpenFailed, e.to_string(), None))?;
            let mut dfu: Vec<UsbDeviceInfo> = all.into_iter().filter(is_ch32rv_app).collect();
            match dfu.len() {
                0 => {
                    return Err(fail(
                        cli,
                        cmd,
                        ErrorKind::DeviceNotFound,
                        format!(
                            "no USB device offers a DFU run-time interface named `{APP_ENTRY_NAME}`"
                        ),
                        Some("name the application with --device"),
                    ));
                }
                1 => Some(AppDevice {
                    dev: dfu.remove(0),
                    port: None,
                }),
                n => {
                    return Err(crate::cmd_probe::fail_with_candidates(
                        cli,
                        cmd,
                        ErrorKind::DeviceAmbiguous,
                        format!(
                            "{n} USB devices offer a DFU run-time interface named `{APP_ENTRY_NAME}`"
                        ),
                        Some("name the application with --device topology:<bus>-<ports>"),
                        dfu.iter()
                            .map(|d| serde_json::json!(format!("topology:{}", d.topology())))
                            .collect(),
                    ));
                }
            }
        }
        (None, None) if entry == IspEntry::Touch1200 => {
            return Err(fail(
                cli,
                cmd,
                ErrorKind::Usage,
                "--entry touch1200 needs the application's serial port",
                Some("--device <serial port>"),
            ));
        }
        (None, None) => None,
    };
    let Some(app) = app else {
        return Ok(AppEntry::Nothing);
    };
    let at = app.dev.topology();
    let dfu = app.dev.dfu_runtime_interface();
    let use_dfu = match entry {
        IspEntry::DfuDetach => true,
        IspEntry::Auto => dfu.is_some(),
        _ => false,
    };
    if use_dfu {
        let Some(intf) = dfu else {
            return Err(fail(
                cli,
                cmd,
                ErrorKind::CapabilityUnsupported,
                format!("the device at topology:{at} has no DFU run-time interface"),
                Some("use --entry touch1200 for an application with a serial port"),
            ));
        };
        // en: The application may drop off the bus before the status stage completes (seen as a
        // stall on Linux); it still detaches, so the error is only reported.
        // ja: status stage の前に bus から消えることがある(Linux では stall)が、detach はするので報告だけ。
        match app.dev.dfu_detach(intf, DETACH_TIMEOUT_MS) {
            Ok(()) => {}
            // en: The interface could not be opened, so nothing was sent: on Windows the DFU
            // run-time interface has no WinUSB driver unless the application names one ("Could not
            // find DeviceInterfaceGUIDs in registry", measured). With `auto` and a serial port,
            // the 1200 bps touch is the way in instead (below); otherwise say it and wait.
            // ja: interface が開けず何も送っていない(Windows では、アプリが WinUSB を名乗らない
            // DFU run-time にはドライバが付かない。実測)。`auto` で serial port があれば、代わりに
            // 1200 bps のタッチで入れる(下)。無ければ言って待つ。
            Err(
                e @ (ch32rv_usb::UsbError::Open(_)
                | ch32rv_usb::UsbError::AccessDenied(_)
                | ch32rv_usb::UsbError::Busy(_)),
            ) if entry == IspEntry::Auto && app.port.is_some() => {
                // en: Expected on Windows, and the touch that follows gets it there: not a warning
                // (an IDE shows stderr in red), a progress line under --verbose.
                // ja: Windows では毎回で、続くタッチで入れるので warning にしない(IDE は stderr を
                // 赤で出す)。--verbose のときだけ経過として出す。
                if cli.verbose > 0 && !cli.json {
                    println!(
                        "DFU_DETACH not sent ({e}); touching the serial port at 1200 bps instead"
                    );
                }
                return touch_into_bootloader(
                    cli,
                    cmd,
                    entry,
                    app.port.as_deref().unwrap_or(""),
                    &at,
                );
            }
            Err(e) => {
                crate::warn(
                    "dfu-detach",
                    format!("{e} (waiting for the bootloader anyway)"),
                );
            }
        }
        if !cli.json {
            println!("sent DFU_DETACH to topology:{at} (interface {intf})");
        }
        return Ok(AppEntry::Sent(at));
    }
    let Some(port) = app.port else {
        return match entry {
            IspEntry::Auto => Ok(AppEntry::Nothing),
            _ => Err(fail(
                cli,
                cmd,
                ErrorKind::CapabilityUnsupported,
                format!("the device at topology:{at} has no serial port to touch"),
                None,
            )),
        };
    };
    touch_into_bootloader(cli, cmd, entry, &port, &at)
}

/// The 1200 bps touch on the application's `port`, reported; `at` is where the bootloader comes up.
/// en: With `auto`, a port that does not open (the application stopped servicing USB: Windows
/// answered "the device attached to the system is not functioning", measured) is not the end:
/// the user brings the bootloader up with BOOT instead, and it is waited for.
/// ja: `auto` では、port が開かない(アプリが USB を止めた。Windows で実測)ときも終わりにせず、
/// BOOT で入れてもらい、それを待つ。
fn touch_into_bootloader(
    cli: &Cli,
    cmd: &str,
    entry: IspEntry,
    port: &str,
    at: &str,
) -> Result<AppEntry, ExitCode> {
    match touch1200(port) {
        Ok(()) => {}
        Err(e) if entry == IspEntry::Auto => {
            // The user must act: stderr, which an IDE always shows.
            eprintln!(
                "the application did not take the request to reboot (1200 bps touch on {port}: {e})"
            );
            return Ok(AppEntry::Unanswered(at.to_owned()));
        }
        Err(e) => {
            return Err(fail(
                cli,
                cmd,
                ErrorKind::DeviceOpenFailed,
                format!("1200 bps touch on {port}: {e}"),
                None,
            ));
        }
    }
    if !cli.json {
        println!("1200 bps touch on {port} (topology:{at})");
    }
    Ok(AppEntry::Sent(at.to_owned()))
}

/// The `wDetachTimeOut` sent with DFU_DETACH (ms).
const DETACH_TIMEOUT_MS: u16 = 1000;

/// en: The Arduino convention: open the port at 1200 bps and close it with DTR low; the
/// application takes that as the request to reboot into its bootloader.
/// ja: Arduino の約束: 1200 bps で開き、DTR を落として閉じる。
fn touch1200(port: &str) -> Result<(), serialport::Error> {
    let mut p = serialport::new(port, 1200)
        .timeout(Duration::from_millis(100))
        .open()?;
    let _ = p.write_data_terminal_ready(false);
    drop(p);
    Ok(())
}

/// en: The DB family whose option layout a bootloader's series has, by Identify's device type.
/// The CH32F parts share their reference manual with the CH32V ones (CH32FV103, CH32FV2x_V3x).
/// CH32V00x names several parts whose USER fields differ in the DB, so it has no DB family; its
/// EVT options are the same on all of them (CH32V003 and the CH32V00X EVT), taken from CH32V006.
/// ja: Identify の device type から、option の配置を持つ DB family。CH32V00x は部品で DB の
/// field が違うので DB family は無いが、EVT の option はどれも同じ(V006 のものを使う)。
fn option_layout(id: Identity) -> (Option<&'static str>, crate::optbytes::Layout) {
    let db = match id.device_type {
        0x14 | 0x15 => Some("CH32V103"),
        0x17 => Some("CH32V307"),
        0x18 | 0x19 => Some("CH32V20x"),
        0x23 => Some("CH32X035"),
        0x24 => Some("CH32L103"),
        _ => None,
    };
    let label = series(id);
    let layout = match db {
        Some(f) => crate::optbytes::Layout {
            label,
            ..crate::optbytes::Layout::of(f)
        },
        None => crate::optbytes::Layout {
            semantics: matches!(id.device_type, 0x20 | 0x21 | 0x25)
                .then(|| ch32rv_target::option_semantics("CH32V006"))
                .flatten(),
            user_fields: Vec::new(),
            label,
        },
    };
    (db, layout)
}

/// en: The `config get` result (crate::optbytes::result), plus its warnings.
/// ja: `config get` の result と警告。
fn options_result(o: &Opened, cfg: &[u8; 12]) -> (serde_json::Value, Vec<Warning>) {
    let (db, layout) = option_layout(o.id);
    let warnings = layout
        .interim_warning()
        .map(|msg| Warning {
            code: "option-decode-interim".to_owned(),
            msg,
        })
        .into_iter()
        .collect();
    let v = crate::optbytes::result(
        ch32rv_isp::series_name(o.id.device_type),
        db,
        &hex(cfg),
        &layout,
        OptionFields::from_config(cfg),
    );
    (v, warnings)
}

fn config_get(cli: &Cli, args: &IspArgs) -> ExitCode {
    const CMD: &str = "isp.config.get";
    let o = match open(cli, CMD, args) {
        Ok(o) => o,
        Err(c) => return c,
    };
    let (v, warnings) = options_result(&o, &o.cfg.config);
    if cli.json {
        let mut env = ResultEnvelope::success(CMD);
        env.result = Some(v);
        env.warnings = warnings;
        crate::print_envelope(&env)
    } else {
        crate::optbytes::print(&v);
        for w in &warnings {
            eprintln!("warning[{}]: {}", w.code, w.msg);
        }
        ExitCode::SUCCESS
    }
}

fn config_set(cli: &Cli, args: &IspArgs, kv: &[String]) -> ExitCode {
    const CMD: &str = "isp.config.set";
    let mut o = match open(cli, CMD, args) {
        Ok(o) => o,
        Err(c) => return c,
    };
    let before = OptionFields::from_config(&o.cfg.config);
    let mut want = before;
    let (_, layout) = option_layout(o.id);
    let rdp_changed = match crate::optbytes::apply(&layout, &mut want, kv, 0x00) {
        Ok(a) => a.read_protect.is_some(),
        Err(m) => {
            return fail(
                cli,
                CMD,
                ErrorKind::Usage,
                m,
                Some(&format!("keys for {}: {}", layout.label, layout.keys())),
            );
        }
    };
    if rdp_changed {
        let what = if want.rdpr == ch32rv_isp::RDPR_OFF {
            "turn read protection off? the chip erases all of code flash"
        } else {
            "turn read protection on? the debug port can no longer read flash, the factory bootloader stops working (measured on CH32X035), and only `recover --method unprotect` over a debug probe turns it off again, erasing code flash"
        };
        if let Err(m) = crate::cmd_probe::confirm_destructive(cli, what) {
            return fail(cli, CMD, ErrorKind::Usage, m, None);
        }
    }
    if want != before
        && let Err(e) = o.dev.write_config(&want.to_config())
    {
        return isp_fail(cli, CMD, e);
    }
    // Read back what the bootloader now reports.
    let after_cfg = match o.dev.read_config() {
        Ok(c) => c.config,
        Err(e) => return isp_fail(cli, CMD, e),
    };
    let after = OptionFields::from_config(&after_cfg);
    if after != want {
        return fail(
            cli,
            CMD,
            ErrorKind::VerifyMismatch,
            format!(
                "the option bytes read back as {} after writing {}",
                hex(&after.to_config()),
                hex(&want.to_config())
            ),
            Some("some option changes take effect only after a reset; check with `isp config get`"),
        );
    }
    let (mut v, warnings) = options_result(&o, &after_cfg);
    if cli.json {
        v["changed"] = serde_json::json!(want != before);
        let mut env = ResultEnvelope::success(CMD);
        env.result = Some(v);
        env.warnings = warnings;
        crate::print_envelope(&env)
    } else {
        if want == before {
            println!("no change");
        }
        crate::optbytes::print(&v);
        for w in &warnings {
            eprintln!("warning[{}]: {}", w.code, w.msg);
        }
        ExitCode::SUCCESS
    }
}

/// en: The iInterface ArduinoCore-CH32RV gives its DFU run-time interface by default
/// (`CH32RV_USB_DFU_RUNTIME_NAME`). The application's VID:PID is the sketch's (by default
/// pid.codes' test PID) and its serial is free too, so this name is what marks a running CH32RV
/// application that can be sent to its bootloader; a sketch that renames it is not discovered,
/// and is not picked by `--entry dfu-detach` without `--device` (DFU_DETACH still works when
/// it is named). ja: ArduinoCore-CH32RV が DFU run-time interface に既定で付ける名前。VID:PID も
/// serial も自由なので、CH32RV のアプリだと分かる印はこれだけ。変えたスケッチは discovery に出ない。
pub(crate) const APP_ENTRY_NAME: &str = "CH32RV";
/// Discovery address schemes: a running CH32RV application, and a factory ISP bootloader.
pub(crate) const APP_SCHEME: &str = "ch32rv-app://";
pub(crate) const ISP_SCHEME: &str = "ch32rv-isp://";

/// en: The IDE port that is always listed (docs/freeze-decisions.ja.md §2): no device yet, the
/// board's own bootloader awaited - the factory USB ISP (`isp flash`) or, on a board with a HID
/// bootloader, that one (`boot hid flash`; boards.txt picks the tool). The user puts the chip in
/// its bootloader (BOOT and reset) after pressing Upload. ja: いつも一覧にある、ボードの
/// ブートローダーを待つポート。どちらの経路かは boards.txt の道具で決まる。
pub(crate) const BOOTLOADER_SCHEME: &str = "ch32rv-bootloader://";
pub(crate) const WAIT_FOR_BOOT: &str = "WAIT_FOR_BOOT";
/// How long the waiting port waits for the bootloader, at least (`--wait` may make it longer).
pub(crate) const BOOT_WAIT: Duration = Duration::from_secs(60);

/// en: Whether `d` is the waiting port: `Some(Ok)` for `ch32rv-bootloader://WAIT_FOR_BOOT` (case
/// aside), `Some(Err)` for anything else after that scheme, `None` for another form.
/// ja: 待つポートか。`ch32rv-bootloader://` の後ろが WAIT_FOR_BOOT 以外ならエラー。
pub(crate) fn wait_for_boot(d: &str) -> Option<Result<(), String>> {
    let rest = d.strip_prefix(BOOTLOADER_SCHEME)?;
    Some(if rest.eq_ignore_ascii_case(WAIT_FOR_BOOT) {
        Ok(())
    } else {
        Err(format!(
            "--device `{d}`: {BOOTLOADER_SCHEME} takes only {WAIT_FOR_BOOT} (the IDE's waiting port)"
        ))
    })
}

/// en: While waiting for a bootloader: the remaining time every 10 s, on stderr (an IDE shows only
/// that, and cannot easily cancel). ja: 待つ間、10 秒ごとに残り時間を stderr に出す。
pub(crate) struct Countdown {
    deadline: Instant,
    next: Instant,
}

impl Countdown {
    pub(crate) fn new(deadline: Instant) -> Self {
        Self {
            deadline,
            next: Instant::now() + Duration::from_secs(10),
        }
    }

    pub(crate) fn tick(&mut self) {
        let now = Instant::now();
        if now >= self.next && now < self.deadline {
            self.next = now + Duration::from_secs(10);
            eprintln!("  ... {} s left", (self.deadline - now).as_secs() + 1);
        }
    }
}

/// en: The id in a `ch32rv-app://<id>` address: the device's USB serial (ArduinoCore-CH32RV's
/// default is derived from the chip's UID, so it stays the same on another USB port), or
/// `usb-<bus>-<ports>` when it has none or shares it with another connected application (a
/// sketch may set any serial). The same rule as `wchlink://`. `apps` = the applications present.
/// ja: `ch32rv-app://<id>` の id。USB serial(既定はチップの UID 由来で、挿し直しても変わらない)、
/// 無いか他のアプリと重なるなら `usb-<位置>`。`wchlink://` と同じ規則。
pub(crate) fn app_id(d: &UsbDeviceInfo, apps: &[UsbDeviceInfo]) -> String {
    match d.serial().filter(|s| !s.is_empty()) {
        Some(s) if apps.iter().filter(|o| o.serial() == Some(s)).count() == 1 => s.to_owned(),
        _ => format!("usb-{}", d.topology()),
    }
}

/// en: The CH32RV application a `ch32rv-app://<id>` address names, now. ja: その id のアプリ。
pub(crate) fn find_app(id: &str) -> Result<UsbDeviceInfo, (ErrorKind, String)> {
    let apps: Vec<UsbDeviceInfo> = ch32rv_usb::enumerate()
        .map_err(|e| (ErrorKind::DeviceOpenFailed, e.to_string()))?
        .into_iter()
        .filter(is_ch32rv_app)
        .collect();
    let mut hits: Vec<&UsbDeviceInfo> = apps
        .iter()
        .filter(|d| match id.strip_prefix("usb-") {
            Some(t) => d.topology() == t,
            None => d.serial() == Some(id),
        })
        .collect();
    match hits.len() {
        0 => Err((
            ErrorKind::DeviceNotFound,
            format!("no CH32RV application {APP_SCHEME}{id} is connected"),
        )),
        1 => {
            let found = hits.remove(0).topology();
            apps.into_iter().find(|d| d.topology() == found).ok_or((
                ErrorKind::DeviceNotFound,
                format!("{APP_SCHEME}{id} went away"),
            ))
        }
        n => Err((
            ErrorKind::DeviceAmbiguous,
            format!("{n} CH32RV applications have the serial {id}; pick the port by position"),
        )),
    }
}

/// A device with a DFU run-time interface named [`APP_ENTRY_NAME`].
/// en: Whether `port` is a serial port of a running CH32RV application (not an OEP probe's).
/// ja: `port` が走っている CH32RV のアプリの serial port か(OEP の probe のものではない)。
pub(crate) fn is_app_port(port: &str) -> bool {
    // en: A symbolic link (`/dev/serial/by-id/...`, a udev name) is resolved as the selector does:
    // compared as written it was taken for an OEP probe's port and its broker never started.
    // ja: シンボリックリンク(`/dev/serial/by-id/...` など)は selector と同じく解決する。
    let want = ch32rv_usb::selector::normalize_port(port);
    ch32rv_usb::enumerate().is_ok_and(|devs| {
        devs.iter().any(|d| {
            !crate::oep::is_oep_device(d)
                && is_ch32rv_app(d)
                && d.serial_ports()
                    .iter()
                    .any(|p| ch32rv_usb::selector::normalize_port(p) == want)
        })
    })
}

/// en: `flash --probe <the application's serial port>`: `isp flash --entry auto --device <port>`
/// with the flash's erase / verify / reset (a halt leaves it in the bootloader).
/// ja: アプリの serial port への `flash`。`isp flash --entry auto --device <port>` で書く。
pub(crate) fn flash_through_app(cli: &Cli, f: &crate::args::FlashArgs, port: &str) -> ExitCode {
    use crate::args::{IspReset, IspTransport, IspVerify};
    use ch32rv_contract::policy::{ResetPolicy, VerifyMode};
    if !cli.json {
        if [APP_SCHEME, ISP_SCHEME, BOOTLOADER_SCHEME]
            .iter()
            .any(|s| port.starts_with(s))
        {
            println!(
                "{port} is a USB bootloader route, not a debug probe: writing through it (isp flash --entry auto --device {port})"
            );
        } else {
            println!(
                "{port} is a CH32RV application's serial port: writing through its USB bootloader (isp flash --entry auto)"
            );
        }
    }
    let args = IspArgs {
        cmd: crate::args::IspCmd::Flash {
            file: f.file.clone(),
            erase: f.erase,
            verify: match f.verify {
                VerifyMode::None => IspVerify::None,
                _ => IspVerify::On,
            },
            reset: match f.reset {
                ResetPolicy::Run => IspReset::Run,
                _ => IspReset::None,
            },
            unprotect: f.unprotect,
        },
        transport: IspTransport::Usb,
        port: None,
        baud: None,
        device: Some(port.to_owned()),
        wait: 0,
        entry: IspEntry::Auto,
    };
    isp(cli, &args)
}

pub(crate) fn is_ch32rv_app(d: &UsbDeviceInfo) -> bool {
    d.dfu_runtime_interface().is_some_and(|n| {
        d.interface_names()
            .iter()
            .any(|(i, name)| *i == n && name == APP_ENTRY_NAME)
    })
}

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

    #[test]
    fn isp_erase_plan_per_mode() {
        let k = 1024;
        assert_eq!(isp_erase_plan(EraseMode::None, 4 * k, None, None), Ok(None));
        assert_eq!(
            isp_erase_plan(EraseMode::Sector, 4 * k, None, None),
            Ok(Some(8))
        );
        assert_eq!(
            isp_erase_plan(EraseMode::Chip, 4 * k, None, Some(62 * k)),
            Ok(Some(62))
        );
        assert!(isp_erase_plan(EraseMode::Chip, 4 * k, None, None).is_err());
        // keep-store with no STORE: the same as sector.
        assert_eq!(
            isp_erase_plan(EraseMode::KeepStore, 4 * k, None, None),
            Ok(Some(8))
        );
        // A STORE well above the minimum: the minimum stays.
        let high = StoreRegion {
            addr: CODE_FLASH_START + 61 * k as u32,
            len: k as u32,
        };
        assert_eq!(
            isp_erase_plan(EraseMode::KeepStore, 4 * k, Some(high), None),
            Ok(Some(8))
        );
        // A STORE the minimum of 8 sectors would reach: only the image's own sectors.
        let low = StoreRegion {
            addr: CODE_FLASH_START + 7 * k as u32,
            len: k as u32,
        };
        assert_eq!(
            isp_erase_plan(EraseMode::KeepStore, 4 * k, Some(low), None),
            Ok(Some(4))
        );
    }
}