lager-net 0.8.0

First-class Rust client for Lager box nets: drive power supplies, batteries, e-loads, GPIO, ADC, DAC, SPI, I2C, UART and more from cargo tests.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
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
//! Debug-probe nets (J-Link / OpenOCD): flash, erase, reset, memory reads,
//! and RTT log streaming.
//!
//! Unlike the instrument nets, debug talks to the box's dedicated **debug
//! service on port 8765** (published on the box host), not the port-9000
//! server. A [`crate::LagerBox`] transparently reaches both: the debug
//! service lives on the same host, and the crate resolves the debug net's
//! full saved record from `:9000/nets/list` to hand to the service.
//!
//! ```no_run
//! # #[cfg(feature = "blocking")]
//! # fn demo() -> lager::Result<()> {
//! use lager::LagerBox;
//!
//! let lager = LagerBox::from_env()?;
//! let debug = lager.debug("debug1");
//!
//! debug.connect()?;
//! debug.erase()?;
//! debug.flash("firmware.hex")?;
//! debug.reset(false)?;
//! let vector_table = debug.read_memory(0x0800_0000, 16)?;
//! println!("{vector_table:02x?}");
//! # Ok(())
//! # }
//! # fn main() {}
//! ```

use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use serde_json::{json, Value};

use crate::error::{Error, Result};
use crate::wire::{
    self, DebugConnection, DebugInfo, DebugStatus, EraseReport, FlashReport, Timeout,
};

/// Base64-encode bytes with the standard alphabet (with padding). Kept
/// in-crate so firmware upload adds no extra dependency (also used by
/// [`crate::nets::dfu`]).
pub(crate) fn base64_encode(input: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
    for chunk in input.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = *chunk.get(1).unwrap_or(&0) as u32;
        let b2 = *chunk.get(2).unwrap_or(&0) as u32;
        let n = (b0 << 16) | (b1 << 8) | b2;
        out.push(ALPHABET[(n >> 18 & 0x3F) as usize] as char);
        out.push(ALPHABET[(n >> 12 & 0x3F) as usize] as char);
        out.push(if chunk.len() > 1 {
            ALPHABET[(n >> 6 & 0x3F) as usize] as char
        } else {
            '='
        });
        out.push(if chunk.len() > 2 {
            ALPHABET[(n & 0x3F) as usize] as char
        } else {
            '='
        });
    }
    out
}

/// Decode standard-alphabet base64 (padding optional, ASCII whitespace
/// ignored). `None` on any other byte or a truncated final group. Used for
/// the webcam snapshot ([`crate::nets::webcam`]).
pub(crate) fn base64_decode(input: &str) -> Option<Vec<u8>> {
    fn sextet(c: u8) -> Option<u32> {
        match c {
            b'A'..=b'Z' => Some((c - b'A') as u32),
            b'a'..=b'z' => Some((c - b'a' + 26) as u32),
            b'0'..=b'9' => Some((c - b'0' + 52) as u32),
            b'+' => Some(62),
            b'/' => Some(63),
            _ => None,
        }
    }
    let digits: Vec<u8> = input.bytes().filter(|b| !b.is_ascii_whitespace()).collect();
    let digits = match digits.iter().position(|&b| b == b'=') {
        Some(pad) if digits[pad..].iter().all(|&b| b == b'=') && digits.len() - pad <= 2 => {
            &digits[..pad]
        }
        Some(_) => return None,
        None => &digits[..],
    };
    if digits.len() % 4 == 1 {
        return None;
    }
    let mut out = Vec::with_capacity(digits.len() * 3 / 4);
    for chunk in digits.chunks(4) {
        let mut n = 0u32;
        for (i, &c) in chunk.iter().enumerate() {
            n |= sextet(c)? << (18 - 6 * i);
        }
        out.push((n >> 16) as u8);
        if chunk.len() > 2 {
            out.push((n >> 8) as u8);
        }
        if chunk.len() > 3 {
            out.push(n as u8);
        }
    }
    Some(out)
}

/// Firmware image kind, inferred from the file extension by
/// [`DebugNet::flash`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FirmwareKind {
    /// Intel HEX (`.hex`).
    Hex,
    /// ELF (`.elf`).
    Elf,
    /// Raw binary (`.bin`), flashed at a base address.
    Bin,
}

impl FirmwareKind {
    fn from_path(path: &Path) -> Result<Self> {
        match path
            .extension()
            .and_then(|e| e.to_str())
            .map(str::to_ascii_lowercase)
        {
            Some(ext) if ext == "hex" => Ok(FirmwareKind::Hex),
            Some(ext) if ext == "elf" => Ok(FirmwareKind::Elf),
            Some(ext) if ext == "bin" => Ok(FirmwareKind::Bin),
            _ => Err(Error::Config(format!(
                "cannot infer firmware type from '{}'; use flash_with to set it explicitly",
                path.display()
            ))),
        }
    }
}

/// Options for [`DebugNet::connect_with`].
#[derive(Debug, Clone)]
pub struct ConnectOptions {
    /// SWD/JTAG speed (e.g. `"4000"` kHz or `"adaptive"`). `None` uses the
    /// service default (`adaptive`).
    pub speed: Option<String>,
    /// Force a fresh backend start even if one is already running.
    pub force: bool,
    /// Halt the target on connect. This is reset-then-halt (the box runs
    /// OpenOCD's `reset halt` / J-Link's halting connect), which pulses
    /// nRESET and re-enters through the reset vector — on a part executing
    /// in place out of QSPI that re-runs the bootloader. On J-Link a
    /// halt-first script via [`ConnectOptions::jlink_script`] halts without
    /// a reset. Honored on the OpenOCD backend by box >= 0.43.0
    /// (older boxes pinned it to `false` on that backend; J-Link always
    /// honored it).
    pub halt: bool,
    /// Start a GDB server (needed for reset/read_memory on some backends).
    pub gdb: bool,
    /// Contents of a `.JLinkScript` to run for this connection (J-Link
    /// backend only; ignored by OpenOCD). Rides base64-encoded in the
    /// request and takes precedence over a script saved on the net.
    pub jlink_script: Option<Vec<u8>>,
    /// Contents of an OpenOCD `.cfg` for this connection (OpenOCD backend
    /// only; ignored by J-Link). Must be a *complete* cfg that selects the
    /// adapter driver — lager still appends its own `ftdi channel <N>` for
    /// a net with a probe channel, and that command dies at startup unless
    /// a cfg has selected the ftdi adapter first. Takes precedence over a
    /// config saved on the net.
    pub openocd_config: Option<Vec<u8>>,
    /// GDB protocol port for this connection, in place of the probe slot's
    /// default (box >= 0.45.0 range-checks it; 400 when out of range).
    pub gdb_port: Option<u16>,
    /// SWO output port (J-Link only).
    pub swo_port: Option<u16>,
    /// Telnet I/O port (J-Link only).
    pub telnet_port: Option<u16>,
    /// RTT telnet port.
    pub rtt_telnet_port: Option<u16>,
}

impl Default for ConnectOptions {
    fn default() -> Self {
        ConnectOptions {
            speed: None,
            force: false,
            halt: false,
            gdb: true,
            jlink_script: None,
            openocd_config: None,
            gdb_port: None,
            swo_port: None,
            telnet_port: None,
            rtt_telnet_port: None,
        }
    }
}

/// Default per-operation timeouts, matching the Python `DebugServiceClient`.
const CONNECT_TIMEOUT: Timeout = Timeout::After(Duration::from_secs(30));
const FLASH_TIMEOUT: Timeout = Timeout::After(Duration::from_secs(180));
const ERASE_TIMEOUT: Timeout = Timeout::After(Duration::from_secs(120));
const RESET_TIMEOUT: Timeout = Timeout::After(Duration::from_secs(10));
const MEMRD_TIMEOUT: Timeout = Timeout::After(Duration::from_secs(30));
const QUICK_TIMEOUT: Timeout = Timeout::After(Duration::from_secs(10));

/// Options for [`DebugNet::rtt`] / RTT streaming (one-way and interactive).
#[derive(Debug, Clone, Copy, Default)]
pub struct RttOptions {
    /// RTT channel (0 or 1).
    pub channel: u32,
    /// RAM start address for the RTT control-block search (advanced).
    pub search_addr: Option<u64>,
    /// Size of the RAM region to search, in bytes (advanced).
    pub search_size: Option<u64>,
    /// Read chunk size on the box side (J-Link only, advanced).
    pub chunk_size: Option<u64>,
}

/// Build the JSON body for a debug op: the full net record plus extra params.
pub(crate) fn debug_body(net_record: &Value, extra: Value) -> Value {
    let mut obj = serde_json::Map::new();
    obj.insert("net".to_string(), net_record.clone());
    if let Value::Object(map) = extra {
        obj.extend(map);
    }
    Value::Object(obj)
}

/// Shared request-body builders, used by both the blocking and async handles
/// so the two cannot diverge.
pub(crate) mod ops {
    use super::*;

    pub(crate) fn connect(net: &Value, opts: &ConnectOptions) -> (String, Value, Timeout) {
        let mut extra = json!({
            "force": opts.force,
            "halt": opts.halt,
            "gdb": opts.gdb,
        });
        if let Some(speed) = &opts.speed {
            extra["speed"] = json!(speed);
        }
        if let Some(script) = &opts.jlink_script {
            extra["jlink_script"] = json!(base64_encode(script));
        }
        if let Some(cfg) = &opts.openocd_config {
            extra["openocd_config"] = json!(base64_encode(cfg));
        }
        for (key, port) in [
            ("gdb_port", opts.gdb_port),
            ("swo_port", opts.swo_port),
            ("telnet_port", opts.telnet_port),
            ("rtt_telnet_port", opts.rtt_telnet_port),
        ] {
            if let Some(port) = port {
                extra[key] = json!(port);
            }
        }
        (
            "/debug/connect".into(),
            debug_body(net, extra),
            CONNECT_TIMEOUT,
        )
    }

    pub(crate) fn disconnect(net: &Value, keep_running: bool) -> (String, Value, Timeout) {
        (
            "/debug/disconnect".into(),
            debug_body(net, json!({ "keep_jlink_running": keep_running })),
            QUICK_TIMEOUT,
        )
    }

    pub(crate) fn reset(net: &Value, halt: bool) -> (String, Value, Timeout) {
        (
            "/debug/reset".into(),
            debug_body(net, json!({ "halt": halt })),
            RESET_TIMEOUT,
        )
    }

    /// Stop the core where it is, without touching nRESET (OpenOCD only).
    pub(crate) fn halt(net: &Value) -> (String, Value, Timeout) {
        (
            "/debug/halt".into(),
            debug_body(net, json!({})),
            RESET_TIMEOUT,
        )
    }

    pub(crate) fn erase(net: &Value) -> (String, Value, Timeout) {
        (
            "/debug/erase".into(),
            debug_body(net, json!({})),
            ERASE_TIMEOUT,
        )
    }

    /// Erase only `size` bytes from `start` (box >= 0.50.0, which lists
    /// `erase_range` in its `/health` features; an older box ignores the
    /// fields and erases the whole chip, so callers check first).
    pub(crate) fn erase_range(net: &Value, start: u64, size: u64) -> (String, Value, Timeout) {
        (
            "/debug/erase".into(),
            debug_body(net, json!({ "erase_start": start, "erase_size": size })),
            ERASE_TIMEOUT,
        )
    }

    pub(crate) fn read_memory(
        net: &Value,
        address: u64,
        length: usize,
        no_reset: bool,
    ) -> (String, Value, Timeout) {
        let mut extra = json!({ "start_addr": address, "length": length });
        if no_reset {
            extra["no_reset"] = json!(true);
        }
        ("/debug/memrd".into(), debug_body(net, extra), MEMRD_TIMEOUT)
    }

    /// `probe` asks the box to read the target to settle `target_attached`
    /// (box >= 0.44.0; about a second slower).
    pub(crate) fn info(net: &Value, probe: bool) -> (String, Value, Timeout) {
        let extra = if probe {
            json!({ "probe": true })
        } else {
            json!({})
        };
        ("/debug/info".into(), debug_body(net, extra), QUICK_TIMEOUT)
    }

    pub(crate) fn status(net: &Value, probe: bool) -> (String, Value, Timeout) {
        let extra = if probe {
            json!({ "probe": true })
        } else {
            json!({})
        };
        (
            "/debug/status".into(),
            debug_body(net, extra),
            QUICK_TIMEOUT,
        )
    }

    /// Build the flash body. `kind` picks the payload field; `address` is
    /// only used for [`FirmwareKind::Bin`].
    pub(crate) fn flash(
        net: &Value,
        contents: &[u8],
        kind: FirmwareKind,
        address: Option<u32>,
    ) -> (String, Value, Timeout) {
        let b64 = base64_encode(contents);
        let payload = match kind {
            FirmwareKind::Hex => json!({ "hexfile": { "content": b64 } }),
            FirmwareKind::Elf => json!({ "elffile": { "content": b64 } }),
            FirmwareKind::Bin => json!({
                "binfile": { "content": b64, "address": address.unwrap_or(0x0800_0000) }
            }),
        };
        (
            "/debug/flash".into(),
            debug_body(net, payload),
            FLASH_TIMEOUT,
        )
    }

    /// Build the RTT body. RTT streaming is blocking-only (the async client
    /// exposes no `rtt()`), so this is unused in async-only builds.
    #[cfg(feature = "blocking")]
    pub(crate) fn rtt_body(net: &Value, opts: &RttOptions) -> Value {
        let mut extra = json!({ "channel": opts.channel, "timeout": Value::Null });
        if let Some(a) = opts.search_addr {
            extra["search_addr"] = json!(a);
        }
        if let Some(s) = opts.search_size {
            extra["search_size"] = json!(s);
        }
        if let Some(c) = opts.chunk_size {
            extra["chunk_size"] = json!(c);
        }
        debug_body(net, extra)
    }
}

/// Find the saved record for a debug net by name in a raw nets list.
pub(crate) fn find_debug_record(records: Vec<Value>, name: &str) -> Result<Value> {
    let mut wrong_role = false;
    for rec in records {
        if rec.get("name").and_then(Value::as_str) == Some(name) {
            if rec.get("role").and_then(Value::as_str) == Some("debug") {
                return Ok(rec);
            }
            wrong_role = true;
        }
    }
    Err(Error::Box {
        status: 404,
        message: if wrong_role {
            format!("net '{name}' exists but is not a debug net")
        } else {
            format!("debug net '{name}' not found on this box")
        },
    })
}

/// Read a firmware file and infer its kind from the extension.
pub(crate) fn read_firmware(path: &Path) -> Result<(Vec<u8>, FirmwareKind)> {
    let kind = FirmwareKind::from_path(path)?;
    let bytes = std::fs::read(path)
        .map_err(|e| Error::Config(format!("cannot read firmware '{}': {e}", path.display())))?;
    Ok((bytes, kind))
}

// ---------------------------------------------------------------------------
// Blocking handle
// ---------------------------------------------------------------------------

/// Handle for a debug-probe net (blocking).
///
/// Created via [`crate::LagerBox::debug`]. Cheap to construct; the net's
/// saved record is fetched from the box on first use and cached on the
/// handle (clones share the cache), so back-to-back debug ops pay for
/// `/nets/list` once instead of per call. The cache is invalidated when an
/// operation fails, so a re-saved net record is picked up on retry.
#[cfg(feature = "blocking")]
#[derive(Clone)]
pub struct DebugNet<'a> {
    pub(crate) client: &'a crate::client::LagerBox,
    pub(crate) name: String,
    pub(crate) record: Arc<Mutex<Option<Value>>>,
}

#[cfg(feature = "blocking")]
impl DebugNet<'_> {
    /// Name of the net this handle drives.
    pub fn name(&self) -> &str {
        &self.name
    }

    fn net_record(&self) -> Result<Value> {
        if let Some(rec) = self.record.lock().unwrap().clone() {
            return Ok(rec);
        }
        let rec = self.client.debug_net_record(&self.name)?;
        *self.record.lock().unwrap() = Some(rec.clone());
        Ok(rec)
    }

    fn call(&self, path: &str, body: Value, timeout: Timeout) -> Result<Value> {
        let req = wire::debug_request(path, body, timeout);
        let result = self
            .client
            .execute_debug(&req)
            .and_then(|(status, resp)| wire::parse_debug(status, resp));
        if result.is_err() {
            // The failure may be a stale record (net re-saved, probe
            // reassigned); re-resolve on the next call.
            *self.record.lock().unwrap() = None;
        }
        result
    }

    /// Connect to the probe with default options (starts a GDB server).
    pub fn connect(&self) -> Result<DebugConnection> {
        self.connect_with(&ConnectOptions::default())
    }

    /// Connect to the probe with explicit options.
    pub fn connect_with(&self, opts: &ConnectOptions) -> Result<DebugConnection> {
        let net = self.net_record()?;
        let (path, body, timeout) = ops::connect(&net, opts);
        let resp = self.call(&path, body, timeout)?;
        serde_json::from_value(resp).map_err(Into::into)
    }

    /// Disconnect. If `keep_running` is true the gdbserver is left running so
    /// an external GDB client can stay attached.
    pub fn disconnect(&self, keep_running: bool) -> Result<()> {
        let net = self.net_record()?;
        let (path, body, timeout) = ops::disconnect(&net, keep_running);
        self.call(&path, body, timeout).map(|_| ())
    }

    /// Reset the target, optionally halting at the reset vector.
    pub fn reset(&self, halt: bool) -> Result<()> {
        let net = self.net_record()?;
        let (path, body, timeout) = ops::reset(&net, halt);
        self.call(&path, body, timeout).map(|_| ())
    }

    /// Halt the core where it is, without a reset (box >= 0.60.0,
    /// OpenOCD nets only).
    ///
    /// Unlike `reset(true)`, which resets and then halts at the reset
    /// vector, this never pulses nRESET, which matters on a part executing
    /// in place out of QSPI. Checks the debug service's features first and
    /// fails with [`Error::UnsupportedByBox`] on a box without the route.
    /// A J-Link net fails with [`Error::Box`] (HTTP 400): J-Link has no
    /// halt-in-place primitive, so connect with a halt-first `.JLinkScript`
    /// instead. So does a net with no running debugger connection.
    pub fn halt(&self) -> Result<()> {
        let (status, health) = self.client.execute_debug(&wire::debug_health_request())?;
        wire::require_debug_feature(status, health, "halt", ">= 0.60.0")?;
        let net = self.net_record()?;
        let (path, body, timeout) = ops::halt(&net);
        self.call(&path, body, timeout).map(|_| ())
    }

    /// Erase the target flash: the whole chip, or the part family's default
    /// range on parts where the box defines one (DA1469x, nRF5340). The
    /// report says which range was erased (box >= 0.50.0).
    pub fn erase(&self) -> Result<EraseReport> {
        let net = self.net_record()?;
        let (path, body, timeout) = ops::erase(&net);
        let resp = self.call(&path, body, timeout)?;
        serde_json::from_value(resp).map_err(Into::into)
    }

    /// Erase only `size` bytes of flash starting at `start` (box >= 0.50.0).
    ///
    /// Checks the debug service's features first and fails with
    /// [`Error::UnsupportedByBox`] on an older box, which would ignore the
    /// range and erase the whole chip. The box refuses (HTTP 400) a range
    /// outside what it can erase on the part.
    pub fn erase_range(&self, start: u64, size: u64) -> Result<EraseReport> {
        let (status, health) = self.client.execute_debug(&wire::debug_health_request())?;
        wire::require_debug_feature(status, health, "erase_range", ">= 0.50.0")?;
        let net = self.net_record()?;
        let (path, body, timeout) = ops::erase_range(&net, start, size);
        let resp = self.call(&path, body, timeout)?;
        serde_json::from_value(resp).map_err(Into::into)
    }

    /// Flash a firmware file, inferring the type from its extension
    /// (`.hex`, `.elf`, `.bin`). `.bin` is flashed at `0x08000000`; use
    /// [`DebugNet::flash_bin`] to choose the address.
    ///
    /// Fails with [`Error::FlashFailed`] when the box reports that nothing
    /// was programmed (box >= 0.51.0).
    pub fn flash(&self, firmware_path: impl AsRef<Path>) -> Result<FlashReport> {
        let path = firmware_path.as_ref();
        let (contents, kind) = read_firmware(path)?;
        self.flash_bytes(&contents, kind, None)
    }

    /// Flash a raw binary at an explicit base address.
    pub fn flash_bin(&self, firmware_path: impl AsRef<Path>, address: u32) -> Result<FlashReport> {
        let contents = std::fs::read(firmware_path.as_ref())
            .map_err(|e| Error::Config(format!("cannot read firmware: {e}")))?;
        self.flash_bytes(&contents, FirmwareKind::Bin, Some(address))
    }

    /// Flash raw firmware bytes of a known kind.
    pub fn flash_bytes(
        &self,
        contents: &[u8],
        kind: FirmwareKind,
        address: Option<u32>,
    ) -> Result<FlashReport> {
        let net = self.net_record()?;
        let (path, body, timeout) = ops::flash(&net, contents, kind, address);
        let resp = self.call(&path, body, timeout)?;
        let report = wire::parse_flash(resp);
        if report.is_err() {
            *self.record.lock().unwrap() = None;
        }
        report
    }

    /// Read `length` bytes of target memory starting at `address`.
    pub fn read_memory(&self, address: u64, length: usize) -> Result<Vec<u8>> {
        self.read_memory_inner(address, length, false)
    }

    /// Like [`DebugNet::read_memory`], but asks the box not to reset or halt
    /// the target first (OpenOCD), so a running target keeps running.
    pub fn read_memory_no_reset(&self, address: u64, length: usize) -> Result<Vec<u8>> {
        self.read_memory_inner(address, length, true)
    }

    fn read_memory_inner(&self, address: u64, length: usize, no_reset: bool) -> Result<Vec<u8>> {
        let net = self.net_record()?;
        let (path, body, timeout) = ops::read_memory(&net, address, length, no_reset);
        let resp = self.call(&path, body, timeout)?;
        wire::debug_memory_bytes(&resp)
    }

    /// Probe/target information (device, arch, backend, server state).
    /// `target_attached` is `None` unless the box already knows the attach
    /// failed; see [`DebugNet::info_probed`].
    pub fn info(&self) -> Result<DebugInfo> {
        self.info_inner(false)
    }

    /// Like [`DebugNet::info`], but the box reads the target to settle
    /// `target_attached` (box >= 0.44.0; about a second slower).
    pub fn info_probed(&self) -> Result<DebugInfo> {
        self.info_inner(true)
    }

    fn info_inner(&self, probe: bool) -> Result<DebugInfo> {
        let net = self.net_record()?;
        let (path, body, timeout) = ops::info(&net, probe);
        let resp = self.call(&path, body, timeout)?;
        serde_json::from_value(resp).map_err(Into::into)
    }

    /// Whether a gdbserver/daemon is running for this probe, and whether
    /// the target is known to be attached; see [`DebugNet::status_probed`].
    pub fn status(&self) -> Result<DebugStatus> {
        self.status_inner(false)
    }

    /// Like [`DebugNet::status`], but the box reads the target to settle
    /// `target_attached` (box >= 0.44.0; about a second slower).
    pub fn status_probed(&self) -> Result<DebugStatus> {
        self.status_inner(true)
    }

    fn status_inner(&self, probe: bool) -> Result<DebugStatus> {
        let net = self.net_record()?;
        let (path, body, timeout) = ops::status(&net, probe);
        let resp = self.call(&path, body, timeout)?;
        serde_json::from_value(resp).map_err(Into::into)
    }

    /// Open an RTT log stream on channel 0.
    ///
    /// Returns a reader that yields the target's RTT output as raw bytes
    /// until the connection closes or the reader is dropped. Wrap it in a
    /// [`std::io::BufReader`] to read lines.
    pub fn rtt(&self) -> Result<RttStream> {
        self.rtt_with(&RttOptions::default())
    }

    /// Open an RTT log stream with explicit options.
    pub fn rtt_with(&self, opts: &RttOptions) -> Result<RttStream> {
        let net = self.net_record()?;
        let body = ops::rtt_body(&net, opts);
        let req = wire::debug_request("/debug/rtt", body, Timeout::Unbounded);
        let reader = self.client.stream_debug(&req)?;
        Ok(RttStream { reader })
    }

    /// Open a bi-directional RTT session on channel 0 (feature `rtt`,
    /// box software >= 0.35.0).
    ///
    /// Unlike [`DebugNet::rtt`], the returned session can also **write** to
    /// the target's RTT down-channel, so firmware that reads commands over
    /// RTT can be driven from a test:
    ///
    /// ```no_run
    /// # #[cfg(all(feature = "blocking", feature = "rtt"))]
    /// # fn demo() -> lager::Result<()> {
    /// use std::time::Duration;
    /// use lager::LagerBox;
    ///
    /// let lager = LagerBox::from_env()?;
    /// let debug = lager.debug("debug1");
    /// debug.connect()?;                       // gdbserver must be up first
    ///
    /// let mut rtt = debug.rtt_interactive()?;
    /// rtt.write_str("self_test\n")?;
    /// rtt.wait_for(b"self_test: pass", Duration::from_secs(5))?;
    /// # Ok(())
    /// # }
    /// # fn main() {}
    /// ```
    ///
    /// Two prerequisites (see [`crate::nets::rtt`] for the full story): the
    /// gdbserver must already be running — call [`DebugNet::connect`] first —
    /// and writing needs a firmware-declared RTT **down** buffer on the
    /// channel (`defmt-rtt` alone only provides the up buffer; without one
    /// the target silently discards writes).
    #[cfg(feature = "rtt")]
    pub fn rtt_interactive(&self) -> Result<crate::nets::rtt::RttSession> {
        self.rtt_interactive_with(&RttOptions::default())
    }

    /// Open a bi-directional RTT session with explicit options
    /// (feature `rtt`). `opts.channel` selects the RTT channel in both
    /// directions.
    #[cfg(feature = "rtt")]
    pub fn rtt_interactive_with(&self, opts: &RttOptions) -> Result<crate::nets::rtt::RttSession> {
        crate::nets::rtt::RttSession::open(
            self.client.base_url(),
            self.name.clone(),
            opts,
            self.client.current_token(),
        )
    }
}

/// A live RTT byte stream (blocking). Implements [`std::io::Read`], so it can
/// be wrapped in a [`std::io::BufReader`] and read line by line.
#[cfg(feature = "blocking")]
pub struct RttStream {
    reader: Box<dyn std::io::Read + Send + Sync>,
}

#[cfg(feature = "blocking")]
impl std::io::Read for RttStream {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.reader.read(buf)
    }
}

// ---------------------------------------------------------------------------
// Async handle
// ---------------------------------------------------------------------------

/// Handle for a debug-probe net (async).
///
/// The net's saved record is cached after first use exactly like the
/// blocking [`DebugNet`] (invalidated when an operation fails).
///
/// RTT streaming is not provided on the async client yet; use the blocking
/// [`DebugNet::rtt`] for log streaming.
#[cfg(feature = "async")]
#[derive(Clone)]
pub struct AsyncDebugNet<'a> {
    pub(crate) client: &'a crate::async_client::AsyncLagerBox,
    pub(crate) name: String,
    pub(crate) record: Arc<Mutex<Option<Value>>>,
}

#[cfg(feature = "async")]
impl AsyncDebugNet<'_> {
    /// Name of the net this handle drives.
    pub fn name(&self) -> &str {
        &self.name
    }

    async fn net_record(&self) -> Result<Value> {
        if let Some(rec) = self.record.lock().unwrap().clone() {
            return Ok(rec);
        }
        let rec = self.client.debug_net_record(&self.name).await?;
        *self.record.lock().unwrap() = Some(rec.clone());
        Ok(rec)
    }

    async fn call(&self, path: &str, body: Value, timeout: Timeout) -> Result<Value> {
        let req = wire::debug_request(path, body, timeout);
        let result = match self.client.execute_debug(&req).await {
            Ok((status, resp)) => wire::parse_debug(status, resp),
            Err(e) => Err(e),
        };
        if result.is_err() {
            // The failure may be a stale record (net re-saved, probe
            // reassigned); re-resolve on the next call.
            *self.record.lock().unwrap() = None;
        }
        result
    }

    /// Connect to the probe with default options (starts a GDB server).
    pub async fn connect(&self) -> Result<DebugConnection> {
        self.connect_with(&ConnectOptions::default()).await
    }

    /// Connect to the probe with explicit options.
    pub async fn connect_with(&self, opts: &ConnectOptions) -> Result<DebugConnection> {
        let net = self.net_record().await?;
        let (path, body, timeout) = ops::connect(&net, opts);
        let resp = self.call(&path, body, timeout).await?;
        serde_json::from_value(resp).map_err(Into::into)
    }

    /// Disconnect. If `keep_running` is true the gdbserver is left running.
    pub async fn disconnect(&self, keep_running: bool) -> Result<()> {
        let net = self.net_record().await?;
        let (path, body, timeout) = ops::disconnect(&net, keep_running);
        self.call(&path, body, timeout).await.map(|_| ())
    }

    /// Reset the target, optionally halting at the reset vector.
    pub async fn reset(&self, halt: bool) -> Result<()> {
        let net = self.net_record().await?;
        let (path, body, timeout) = ops::reset(&net, halt);
        self.call(&path, body, timeout).await.map(|_| ())
    }

    /// Halt the core without a reset. See [`DebugNet::halt`].
    pub async fn halt(&self) -> Result<()> {
        let (status, health) = self
            .client
            .execute_debug(&wire::debug_health_request())
            .await?;
        wire::require_debug_feature(status, health, "halt", ">= 0.60.0")?;
        let net = self.net_record().await?;
        let (path, body, timeout) = ops::halt(&net);
        self.call(&path, body, timeout).await.map(|_| ())
    }

    /// Erase the target flash. See [`DebugNet::erase`].
    pub async fn erase(&self) -> Result<EraseReport> {
        let net = self.net_record().await?;
        let (path, body, timeout) = ops::erase(&net);
        let resp = self.call(&path, body, timeout).await?;
        serde_json::from_value(resp).map_err(Into::into)
    }

    /// Erase only `size` bytes from `start`. See [`DebugNet::erase_range`].
    pub async fn erase_range(&self, start: u64, size: u64) -> Result<EraseReport> {
        let (status, health) = self
            .client
            .execute_debug(&wire::debug_health_request())
            .await?;
        wire::require_debug_feature(status, health, "erase_range", ">= 0.50.0")?;
        let net = self.net_record().await?;
        let (path, body, timeout) = ops::erase_range(&net, start, size);
        let resp = self.call(&path, body, timeout).await?;
        serde_json::from_value(resp).map_err(Into::into)
    }

    /// Flash a firmware file, inferring type from extension. See
    /// [`DebugNet::flash`].
    pub async fn flash(&self, firmware_path: impl AsRef<Path>) -> Result<FlashReport> {
        let (contents, kind) = read_firmware(firmware_path.as_ref())?;
        self.flash_bytes(&contents, kind, None).await
    }

    /// Flash a raw binary at an explicit base address.
    pub async fn flash_bin(
        &self,
        firmware_path: impl AsRef<Path>,
        address: u32,
    ) -> Result<FlashReport> {
        let contents = std::fs::read(firmware_path.as_ref())
            .map_err(|e| Error::Config(format!("cannot read firmware: {e}")))?;
        self.flash_bytes(&contents, FirmwareKind::Bin, Some(address))
            .await
    }

    /// Flash raw firmware bytes of a known kind.
    pub async fn flash_bytes(
        &self,
        contents: &[u8],
        kind: FirmwareKind,
        address: Option<u32>,
    ) -> Result<FlashReport> {
        let net = self.net_record().await?;
        let (path, body, timeout) = ops::flash(&net, contents, kind, address);
        let resp = self.call(&path, body, timeout).await?;
        let report = wire::parse_flash(resp);
        if report.is_err() {
            *self.record.lock().unwrap() = None;
        }
        report
    }

    /// Read `length` bytes of target memory starting at `address`.
    pub async fn read_memory(&self, address: u64, length: usize) -> Result<Vec<u8>> {
        self.read_memory_inner(address, length, false).await
    }

    /// See [`DebugNet::read_memory_no_reset`].
    pub async fn read_memory_no_reset(&self, address: u64, length: usize) -> Result<Vec<u8>> {
        self.read_memory_inner(address, length, true).await
    }

    async fn read_memory_inner(
        &self,
        address: u64,
        length: usize,
        no_reset: bool,
    ) -> Result<Vec<u8>> {
        let net = self.net_record().await?;
        let (path, body, timeout) = ops::read_memory(&net, address, length, no_reset);
        let resp = self.call(&path, body, timeout).await?;
        wire::debug_memory_bytes(&resp)
    }

    /// Probe/target information. See [`DebugNet::info`].
    pub async fn info(&self) -> Result<DebugInfo> {
        self.info_inner(false).await
    }

    /// See [`DebugNet::info_probed`].
    pub async fn info_probed(&self) -> Result<DebugInfo> {
        self.info_inner(true).await
    }

    async fn info_inner(&self, probe: bool) -> Result<DebugInfo> {
        let net = self.net_record().await?;
        let (path, body, timeout) = ops::info(&net, probe);
        let resp = self.call(&path, body, timeout).await?;
        serde_json::from_value(resp).map_err(Into::into)
    }

    /// See [`DebugNet::status`].
    pub async fn status(&self) -> Result<DebugStatus> {
        self.status_inner(false).await
    }

    /// See [`DebugNet::status_probed`].
    pub async fn status_probed(&self) -> Result<DebugStatus> {
        self.status_inner(true).await
    }

    async fn status_inner(&self, probe: bool) -> Result<DebugStatus> {
        let net = self.net_record().await?;
        let (path, body, timeout) = ops::status(&net, probe);
        let resp = self.call(&path, body, timeout).await?;
        serde_json::from_value(resp).map_err(Into::into)
    }
}

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

    #[test]
    fn base64_matches_reference() {
        assert_eq!(base64_encode(b""), "");
        assert_eq!(base64_encode(b"f"), "Zg==");
        assert_eq!(base64_encode(b"fo"), "Zm8=");
        assert_eq!(base64_encode(b"foo"), "Zm9v");
        assert_eq!(base64_encode(b"foob"), "Zm9vYg==");
        assert_eq!(base64_encode(b"fooba"), "Zm9vYmE=");
        assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
        assert_eq!(base64_encode(&[0x00, 0xff, 0x10]), "AP8Q");
    }

    #[test]
    fn base64_round_trips_and_rejects_garbage() {
        for input in [
            &b""[..],
            b"f",
            b"fo",
            b"foo",
            b"foob",
            b"fooba",
            b"foobar",
            &[0, 255, 16],
        ] {
            assert_eq!(base64_decode(&base64_encode(input)).unwrap(), input);
        }
        assert_eq!(base64_decode("Zm9v\nYmFy").unwrap(), b"foobar");
        assert_eq!(base64_decode("Zg").unwrap(), b"f");
        assert!(base64_decode("Zm9v!").is_none());
        assert!(base64_decode("Z").is_none());
        assert!(base64_decode("Zg==Zg==").is_none());
    }

    #[test]
    fn firmware_kind_from_extension() {
        assert_eq!(
            FirmwareKind::from_path(Path::new("a/b/fw.hex")).unwrap(),
            FirmwareKind::Hex
        );
        assert_eq!(
            FirmwareKind::from_path(Path::new("FW.ELF")).unwrap(),
            FirmwareKind::Elf
        );
        assert!(FirmwareKind::from_path(Path::new("fw.txt")).is_err());
    }

    #[test]
    fn debug_body_wraps_net_and_params() {
        let net = json!({"name": "debug1", "role": "debug", "pin": "nrf52"});
        let body = debug_body(&net, json!({"halt": true}));
        assert_eq!(body["net"]["name"], "debug1");
        assert_eq!(body["halt"], true);
    }
}