modem-device 0.2.0

The seam between the zenoh-modem driver and a physical or simulated medium
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
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
//! The seam between the driver and a medium.
//!
//! This crate deliberately does not depend on `zenoh`, and CI holds that with a
//! dependency-graph guard. The driver moves opaque batches and the medium moves
//! opaque SDUs; the moment either could parse a key expression, the second
//! policy plane the architecture forbids would exist
//! (`docs/architecture.md` I1, §4.8).
//!
//! Everything here describes a medium in terms a modem vendor would recognise —
//! how big an SDU may be, whether it can transmit and receive at once, whether
//! delivery is ordered and loss-free. Nothing here describes Zenoh.
//!
//! Two traits since #117, split along the planes of
//! `docs/design/device-planes.md`: [`Device`] is what the management plane
//! serves — a report, events, a lifecycle, and later a configuration plane —
//! and [`Medium`]`: Device` is the SDU data plane on top of it. A device whose
//! data plane is the kernel's is a [`Netdev`]`: Device` — named, served on the
//! management plane, and never seen by the lanes.

use std::fmt;

pub mod action;
pub mod config;
pub mod conformance;
pub use action::Actions;
pub use config::Configure;

/// Zenoh's own framing on the data path: a two-byte little-endian length
/// before every batch, which the driver strips before the medium and re-adds
/// after (`docs/architecture.md` §4.1). Stated here because a batch of N
/// bytes puts N - 2 on the medium, and every document that names a
/// `max_batch_size` has to add it back — the contract's `Capabilities` does.
pub const LENGTH_PREFIX: usize = 2;

/// One service data unit: exactly what the medium carries in one transmission.
///
/// The driver has already stripped Zenoh's two-byte length prefix by the time an
/// SDU reaches a backend, and re-adds it on the way back
/// (`docs/architecture.md` §4.1). Contents are never inspected.
pub type Sdu = Vec<u8>;

/// A remote endpoint reachable over the medium.
///
/// Opaque to the driver and to Zenoh alike. It is a name from configuration —
/// `"peer-b"`, `"auv-03"`, an IMEI — and per invariant I5 it is an *addressing*
/// identifier, never a proof of identity.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EndpointId(String);

impl EndpointId {
    /// Wrap a configured endpoint name.
    pub fn new(name: impl Into<String>) -> Self {
        Self(name.into())
    }

    /// The configured name, for logging and for keying medium-side tables.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for EndpointId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// The driver's view of one QoS lane.
///
/// Under decision D1 a lane is a socket, and its properties come from the
/// locator metadata Zenoh was configured with (`?rel=1;prio=0-2`) — resolved
/// once, at startup, into this. A backend schedules lanes; it is never told what
/// a Zenoh priority is, which is what keeps [`Sdu`] traffic and Zenoh semantics
/// on opposite sides of this crate boundary.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LaneKey {
    /// Which remote this lane reaches.
    pub endpoint: EndpointId,
    /// Whether this lane promises ordered, loss-free delivery.
    ///
    /// Per invariant I2 this is a claim about the *medium*, not a request. A
    /// backend that cannot honour it must not be configured behind a lane that
    /// asserts it: Zenoh will not notice the lie, because `verify_sn` accepts a
    /// forward sequence gap silently — the failure mode is lost data, not a
    /// fault.
    pub reliable: bool,
    /// Scheduling rank; lower is more urgent.
    ///
    /// Derived at configuration time from the lane's declared priority range.
    /// Rank 0 sorts first. The numbering happens to mirror Zenoh's, where
    /// `Control` is 0, but nothing here depends on that.
    pub rank: u8,
}

impl fmt::Display for LaneKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}/{}#{}",
            self.endpoint,
            if self.reliable { "rel" } else { "be" },
            self.rank
        )
    }
}

/// Whether the medium can transmit and receive simultaneously.
///
/// Only the two variants that change behaviour exist. The withdrawn ICD series
/// carried five, three of which had no consequence anywhere in the
/// specification; new variants are added here when something acts on them.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
// Deliberately *not* `#[non_exhaustive]` (#97): a new duplex mode changes what
// every scheduler and simulator must do, so it should break their builds, and
// the contract's own `Duplex` maps this one variant for variant.
pub enum Duplex {
    /// Transmit and receive are independent.
    #[default]
    Full,
    /// Transmitting blocks receiving and vice versa, as on a shared RF channel.
    Half,
}

/// What a medium can do, as the medium itself would describe it.
///
/// Transmit and receive limits are separate because real media are asymmetric:
/// Iridium SBD carries 340 bytes up and 270 down. Collapsing them to their
/// minimum — as the withdrawn design did — silently wasted 21% of every paid
/// uplink message (`docs/architecture.md` §4.9).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Capabilities {
    /// Largest SDU the medium will transmit, in bytes.
    ///
    /// `u16` because Zenoh's own `BatchSize` is `u16`, so a larger value could
    /// never be filled.
    pub tx_max_sdu: u16,
    /// Largest SDU the medium will deliver, in bytes.
    ///
    /// **A promise this backend makes, and the driver checks it** (#75). An
    /// arrival larger than this counts `rx_oversize_total` and is logged as a
    /// contract violation; it is still delivered, because the batch is Zenoh's
    /// to judge and discarding it here would be the driver deciding a question
    /// I1 gives to Zenoh.
    ///
    /// It is **not** what stops a peer sending too much, and the distinction
    /// matters on an asymmetric bearer. `batch_size` is node-global and Zenoh
    /// negotiates the minimum of the two ends, so a pair configured
    /// inconsistently produces a *small* effective batch — 21% of a paid
    /// uplink slot wasted on SBD — never an oversized arrival. What an
    /// operator does with this number is size the *far* node's `batch_size`,
    /// which is why `Driver::start` logs it as `peer_max_batch_size` (#82).
    pub rx_max_sdu: u16,
    /// Whether transmit and receive contend.
    pub duplex: Duplex,
    /// Whether the medium delivers in order and without loss.
    ///
    /// Per invariant I2 this must be the truth about the hardware, not an
    /// aspiration. A lane may only assert [`LaneKey::reliable`] over a medium
    /// that reports `true` here.
    pub reliable: bool,
}

/// Counters a medium exposes for telemetry.
///
/// Deliberately minimal: these are the quantities the driver can assert on in a
/// test. Radio-specific figures such as RSSI belong on the management plane
/// (`docs/architecture.md` §4.6), not in the data-path interface.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Metrics {
    /// SDUs handed to the medium and accepted.
    pub tx_sdus: u64,
    /// Bytes across those SDUs.
    pub tx_bytes: u64,
    /// SDUs delivered by the medium.
    pub rx_sdus: u64,
    /// Bytes across those SDUs.
    pub rx_bytes: u64,
    /// SDUs the medium accepted and then lost, where it can tell.
    ///
    /// A medium that cannot distinguish loss from delivery leaves this at zero;
    /// per the architecture's telemetry rule, absence means unknown and must not
    /// be read as none.
    pub dropped: u64,
}

/// What a device says about itself, as far as it knows.
///
/// `Capabilities` is what the medium *can* carry and is read once; `Metrics` is
/// what the driver counted and is what a test asserts on. This is the third
/// thing, and the one that fell off the edge: what the hardware knows about its
/// own condition. `modem-device` named the gap years before it had a shape —
/// "radio-specific figures such as RSSI belong on the management plane" — and
/// then never built the other side of it (#49).
///
/// **Every field is `Option`, and that is load-bearing twice over.** A device
/// that cannot answer says `None` rather than zero, because a zeroed counter is
/// a claim and absence is not. And five of this crate's eight implementors are
/// decorators wrapping another `Medium`; a decorator that forgets to forward
/// this method inherits the default, whose every field is `None` — the same
/// answer as "I do not know", rather than a confident wrong number belonging to
/// the medium underneath.
///
/// `#[non_exhaustive]` because #49 lists eleven quantities and hardware will
/// suggest twenty more. As fields on one struct behind one defaulted method,
/// adding `signal.rssi_dbm` later touches the backend that fills it and the
/// publisher that reads it — as methods, each would be an eight-implementor
/// event for ever.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Report {
    /// How long ago this snapshot was taken.
    ///
    /// [`Device::report`] is sync, so a backend cannot do I/O in it and
    /// must answer from a cache. A cache with no age is a lie the moment the
    /// modem stops answering, which is exactly when an operator is reading it —
    /// so the age rides along, and a report older than a consumer's tolerance is
    /// published as absent rather than as current.
    pub age_ms: Option<u64>,

    /// Cumulative channel occupancy, in milliseconds.
    ///
    /// What the medium has actually spent on the air. On a service billed in
    /// airtime this is the bill; `lease-tuning-in-a-cell.md` is the measurement
    /// that made the distinction between this and a message count matter.
    pub time_on_air_ms: Option<u64>,

    /// Transmissions made only because an earlier attempt was lost.
    ///
    /// The medium's own ARQ, which `rf-arq-requirement.md` makes a hardware
    /// selection requirement. Counted by every simulator in the tree today and
    /// reachable through none of them.
    pub retransmits: Option<u64>,

    /// Slot bytes paid for and not used.
    ///
    /// A per-message service charges for the whole slot; M2 measured 9.4%
    /// utilisation at the defaults. This is the same figure from the medium's
    /// side, for a deployment rather than for a measurement.
    pub bytes_wasted: Option<u64>,

    /// Frames the medium received and could not accept: FIFO overrun,
    /// collision, CRC or header failure.
    ///
    /// **Distinct from [`Metrics::dropped`]**, which is accepted-then-lost on
    /// *transmit*. #49 describes these as conflated; they are not — no shipped
    /// medium puts receive-side errors into `dropped` — but they are counted
    /// (`sim.rs`'s `lost_attempts`, `cell.rs`'s `collisions` and `overruns`) and
    /// have had no way out of the crate at all.
    pub rx_errors: Option<u64>,

    /// Whether the medium may transmit now, and how long until it may.
    pub duty_cycle: Option<DutyCycle>,

    /// Received signal strength, on the device's own 0–5 scale.
    ///
    /// **Bars, not dBm, and the distinction is the point.** An Iridium ISU
    /// answers `AT+CSQF` with an integer 0–5 and has no dBm to give; an
    /// SX1262 reads a dBm out of a packet-status register and has no bars.
    /// A field spelled `rssi_dbm` would force one of them to invent a number,
    /// which is the failure `Report`'s all-`Option` shape exists to
    /// avoid — a device says what it knows and stays quiet about the rest. A
    /// dBm field arrives with the backend that measures one (#49, #76).
    pub signal_bars: Option<u8>,

    // --- The IP-bearer vocabulary (#123). Names carry no unit suffix: the
    // registry's `unit` is where a unit lives, and a name-and-field pair is
    // two places to drift. Fixed-point, because this type is `Copy + Eq`:
    // milli-units cover RSRQ's and SNR's half-dB steps exactly.
    /// Received signal strength, milli-dBm (ModemManager `Modem.Signal`,
    /// an SX1262's packet status).
    pub rssi: Option<i32>,
    /// Reference signal received power, milli-dBm (LTE, NR).
    pub rsrp: Option<i32>,
    /// Reference signal received quality, milli-dB.
    pub rsrq: Option<i32>,
    /// Signal-to-noise ratio, milli-dB.
    pub snr: Option<i32>,
    /// Error rate, milli-percent.
    pub error_rate: Option<i32>,
    /// Current receive data rate, bit/s (DLEP, RFC 8175 §13 — session level;
    /// per-destination metrics are not device-level and are not here).
    pub rx_rate: Option<u64>,
    /// Current transmit data rate, bit/s.
    pub tx_rate: Option<u64>,
    /// Maximum receive data rate, bit/s.
    pub rx_max_rate: Option<u64>,
    /// Maximum transmit data rate, bit/s.
    pub tx_max_rate: Option<u64>,
    /// Latency, microseconds.
    pub latency: Option<u64>,
    /// Resources available on the link, milli-percent.
    pub resources: Option<i32>,
    /// Relative receive link quality, milli-percent.
    pub rx_quality: Option<i32>,
    /// Relative transmit link quality, milli-percent.
    pub tx_quality: Option<i32>,
    /// Network registration, for a bearer that registers with one.
    pub registration: Option<Registration>,
    /// The access technology the bearer is on.
    pub access_technology: Option<AccessTechnology>,
}

impl Report {
    /// An empty report — the same thing [`Device::report`]'s default
    /// returns, and the starting point for a backend that fills some of it.
    ///
    /// The setters below take and return `self` so a backend names only what it
    /// knows: `Report::new().retransmits(n).rx_errors(m)`. That shape is
    /// what makes `#[non_exhaustive]` free rather than annoying — this type is
    /// implemented from *outside* this crate, so a struct literal would make
    /// every new field a breaking change, which is exactly the churn #49's
    /// eleven-and-counting quantities would cause.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// How old this snapshot is. See [`Report::age_ms`].
    #[must_use]
    pub fn age_ms(mut self, ms: u64) -> Self {
        self.age_ms = Some(ms);
        self
    }

    /// Cumulative channel occupancy.
    #[must_use]
    pub fn time_on_air_ms(mut self, ms: u64) -> Self {
        self.time_on_air_ms = Some(ms);
        self
    }

    /// Transmissions made only because an earlier attempt was lost.
    #[must_use]
    pub fn retransmits(mut self, n: u64) -> Self {
        self.retransmits = Some(n);
        self
    }

    /// Slot bytes paid for and not used.
    #[must_use]
    pub fn bytes_wasted(mut self, n: u64) -> Self {
        self.bytes_wasted = Some(n);
        self
    }

    /// Frames received and not accepted.
    #[must_use]
    pub fn rx_errors(mut self, n: u64) -> Self {
        self.rx_errors = Some(n);
        self
    }

    /// Whether the medium may transmit now.
    #[must_use]
    pub fn duty_cycle(mut self, duty: DutyCycle) -> Self {
        self.duty_cycle = Some(duty);
        self
    }

    /// Signal strength on the device's own 0–5 scale.
    #[must_use]
    pub fn signal_bars(mut self, bars: u8) -> Self {
        self.signal_bars = Some(bars);
        self
    }

    /// Received signal strength, milli-dBm.
    #[must_use]
    pub fn rssi(mut self, milli_dbm: i32) -> Self {
        self.rssi = Some(milli_dbm);
        self
    }

    /// Reference signal received power, milli-dBm.
    #[must_use]
    pub fn rsrp(mut self, milli_dbm: i32) -> Self {
        self.rsrp = Some(milli_dbm);
        self
    }

    /// Reference signal received quality, milli-dB.
    #[must_use]
    pub fn rsrq(mut self, milli_db: i32) -> Self {
        self.rsrq = Some(milli_db);
        self
    }

    /// Signal-to-noise ratio, milli-dB.
    #[must_use]
    pub fn snr(mut self, milli_db: i32) -> Self {
        self.snr = Some(milli_db);
        self
    }

    /// Error rate, milli-percent.
    #[must_use]
    pub fn error_rate(mut self, milli_percent: i32) -> Self {
        self.error_rate = Some(milli_percent);
        self
    }

    /// Current receive data rate, bit/s.
    #[must_use]
    pub fn rx_rate(mut self, bps: u64) -> Self {
        self.rx_rate = Some(bps);
        self
    }

    /// Current transmit data rate, bit/s.
    #[must_use]
    pub fn tx_rate(mut self, bps: u64) -> Self {
        self.tx_rate = Some(bps);
        self
    }

    /// Maximum receive data rate, bit/s.
    #[must_use]
    pub fn rx_max_rate(mut self, bps: u64) -> Self {
        self.rx_max_rate = Some(bps);
        self
    }

    /// Maximum transmit data rate, bit/s.
    #[must_use]
    pub fn tx_max_rate(mut self, bps: u64) -> Self {
        self.tx_max_rate = Some(bps);
        self
    }

    /// Latency, microseconds.
    #[must_use]
    pub fn latency(mut self, us: u64) -> Self {
        self.latency = Some(us);
        self
    }

    /// Resources available on the link, milli-percent.
    #[must_use]
    pub fn resources(mut self, milli_percent: i32) -> Self {
        self.resources = Some(milli_percent);
        self
    }

    /// Relative receive link quality, milli-percent.
    #[must_use]
    pub fn rx_quality(mut self, milli_percent: i32) -> Self {
        self.rx_quality = Some(milli_percent);
        self
    }

    /// Relative transmit link quality, milli-percent.
    #[must_use]
    pub fn tx_quality(mut self, milli_percent: i32) -> Self {
        self.tx_quality = Some(milli_percent);
        self
    }

    /// Network registration.
    #[must_use]
    pub fn registration(mut self, r: Registration) -> Self {
        self.registration = Some(r);
        self
    }

    /// The access technology the bearer is on.
    #[must_use]
    pub fn access_technology(mut self, t: AccessTechnology) -> Self {
        self.access_technology = Some(t);
        self
    }
}

/// Where a bearer stands with its network (ModemManager's 3GPP registration
/// states; #123). A device that registers with nothing — a point-to-point
/// radio — reports none.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Registration {
    /// Not registered, not searching.
    Idle,
    /// Registered on the home network.
    Home,
    /// Searching for a network.
    Searching,
    /// Registration denied.
    Denied,
    /// Registered, roaming.
    Roaming,
    /// The device cannot say.
    Unknown,
}

impl Registration {
    /// The wire spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Idle => "idle",
            Self::Home => "home",
            Self::Searching => "searching",
            Self::Denied => "denied",
            Self::Roaming => "roaming",
            Self::Unknown => "unknown",
        }
    }
}

impl fmt::Display for Registration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The access technology a bearer is on (#123). Closed and
/// `#[non_exhaustive]`: a value is added when a device produces it, and a
/// reader that sees one it does not know treats it as text.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AccessTechnology {
    Gsm,
    Gprs,
    Edge,
    Umts,
    Hspa,
    Lte,
    Nr5g,
    /// Iridium's own air interface — an SBD terminal.
    Iridium,
}

impl AccessTechnology {
    /// The wire spelling: ModemManager's, lowercase.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Gsm => "gsm",
            Self::Gprs => "gprs",
            Self::Edge => "edge",
            Self::Umts => "umts",
            Self::Hspa => "hspa",
            Self::Lte => "lte",
            Self::Nr5g => "5gnr",
            Self::Iridium => "iridium",
        }
    }
}

impl fmt::Display for AccessTechnology {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Why a medium is not transmitting, when the answer is "not yet".
///
/// The case #49 calls sharpest, and the reason it is in v1 rather than deferred
/// with the rest: a compliant EU868 backend must **block** in `send` for up to
/// ~99 s, and an operator watching `queue_depth` climb cannot tell
/// "duty-cycle limited" from "radio dead". `SimMedium::slide_to_contact` already
/// blocks for exactly this reason and `ContactWindow::wait_at` already computes
/// the number, so this is a producer that exists rather than a keyspace row
/// waiting for hardware.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct DutyCycle {
    /// Whether the medium would take an SDU right now.
    pub available: bool,
    /// Milliseconds until it would, when it would not.
    ///
    /// Zero while [`available`](Self::available) is false means the medium is
    /// blocked and does not know for how long, which is a different answer from
    /// "blocked for 0 ms" and a real state for a device that can say it is busy
    /// without saying when it will not be.
    pub next_available_in_ms: u64,
}

impl DutyCycle {
    /// The medium would take an SDU now.
    #[must_use]
    pub fn ready() -> Self {
        Self {
            available: true,
            next_available_in_ms: 0,
        }
    }

    /// The medium would not, and this is how long until it would.
    ///
    /// Two named constructors rather than one taking `(bool, u64)`, because the
    /// two states are what a caller is choosing between and a boolean argument
    /// at a call site says nothing about which way round it goes.
    #[must_use]
    pub fn wait_ms(ms: u64) -> Self {
        Self {
            available: false,
            next_available_in_ms: ms,
        }
    }
}

/// Something the medium wants to say when nobody is calling [`Medium::send`].
///
/// The gap #51 names: every `DeviceError` is the return value of a data-path
/// call, so a radio that loses registration, overheats, or drops off the bus is
/// silent until the next transmission — which on a store-and-forward link may
/// be an hour away, and on a dead one is never.
///
/// A plain struct rather than a channel, and that is the whole reason this
/// works. `modem-device` has three dependencies — `async-trait`, `thiserror`,
/// optional `serde` — and **no tokio**. Putting a `watch::Receiver` or a
/// `broadcast::Receiver` on the trait would drag a runtime into a crate whose
/// entire job is to be the seam, to obtain a channel type. An `async fn`
/// mirroring [`Medium::recv`] needs nothing, is dyn-compatible through the
/// `async-trait` already here, and has a default whose meaning is exactly
/// "this medium never says anything".
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DeviceEvent {
    /// The lane it concerns, if it concerns one.
    ///
    /// `None` for a device-wide condition — registration lost, over
    /// temperature, duty-cycle budget exhausted — which is most of them.
    pub lane: Option<LaneKey>,
    /// Whether this is the medium becoming unhappy or becoming happy again.
    ///
    /// Edge-triggered by contract. A backend that repeated `Raised` while a
    /// condition persisted would produce a stream no `rate` declaration could
    /// honestly cover, and the consumer's job is to publish these, not to
    /// deduplicate somebody else's.
    pub edge: Edge,
    /// The device's own words.
    ///
    /// Carried verbatim to the management plane, which is the point: until #51
    /// a `DeviceError::Device(String)` reached a `warn!` and was discarded, so
    /// `+CME ERROR 3` — the one thing that says what is actually wrong — never
    /// left the process.
    pub detail: String,
}

impl DeviceEvent {
    /// A condition beginning.
    #[must_use]
    pub fn raised(detail: impl Into<String>) -> Self {
        Self {
            lane: None,
            edge: Edge::Raised,
            detail: detail.into(),
        }
    }

    /// A condition ending.
    #[must_use]
    pub fn cleared(detail: impl Into<String>) -> Self {
        Self {
            lane: None,
            edge: Edge::Cleared,
            detail: detail.into(),
        }
    }

    /// Attribute this event to one lane.
    #[must_use]
    pub fn on_lane(mut self, lane: LaneKey) -> Self {
        self.lane = Some(lane);
        self
    }
}

/// Which way a condition just went.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Edge {
    /// It started.
    Raised,
    /// It stopped.
    Cleared,
}

/// Why a medium refused or failed an SDU.
///
/// `#[non_exhaustive]`: both consumers on the data path already match with a
/// catch-all (`sched.rs`'s retry arm, `lanes.rs`'s receive loop), so this costs
/// nothing today and leaves room for the variants a real device will need. The
/// alternative is discovering later that adding one is a breaking change to a
/// crate whose whole job is to be implemented from outside.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DeviceError {
    /// The SDU is larger than the medium can carry.
    ///
    /// Invariant I4: the driver never splits a batch to make it fit. An SDU that
    /// does not fit is a configuration error — Zenoh's `batch_size` was set
    /// above what this medium can carry — and it is reported, loudly, as one.
    #[error(
        "sdu of {got} bytes exceeds the medium's tx_max_sdu of {max}: \
         lower zenoh's batch_size to at most {} (architecture I4, §4.5)", *max as usize + 2
    )]
    SduTooLarge { got: usize, max: u16 },

    /// No such lane is configured on this medium.
    #[error("unknown lane {0} (architecture §4.1)")]
    UnknownLane(LaneKey),

    /// The medium is up but cannot transmit right now, and says so rather than
    /// waiting.
    ///
    /// For hardware whose API refuses instead of blocking — a half-duplex
    /// medium mid-reception, on a device that reports rather than queues.
    ///
    /// **A contact window is still not an instance of this.** A satellite
    /// terminal out of coverage *blocks*, because that is what a
    /// store-and-forward service does. See
    /// `docs/measurements/contact-windows.md`.
    ///
    /// What returning it costs, exactly: on a **reliable** lane the scheduler
    /// holds the batch and offers it again with a backoff, for as long as the
    /// medium keeps refusing (#40) — so this trades a stall for a delay, never
    /// for lost data, and the stall reaches Zenoh as ordinary backpressure. On
    /// a **best-effort** lane the batch is dropped and counted, which is what
    /// best-effort means. Either way the refusal appears on
    /// `DriverMetrics::tx_failed`.
    ///
    /// Earlier versions of this note warned that the scheduler dropped the
    /// batch on both lane classes. It did, silently, and that was #40.
    #[error("medium cannot transmit at present")]
    TxUnavailable,

    /// The medium is gone: closed, unplugged, or failed.
    #[error("medium is closed")]
    Closed,

    /// Anything hardware-specific, in the backend's own words.
    ///
    /// Handled exactly as [`DeviceError::TxUnavailable`]: held and retried on
    /// a reliable lane, dropped and counted on a best-effort one. Return it
    /// for a failure the medium expects to survive — `+CME ERROR`, an SPI
    /// timeout, an MO status of "no network". A device that is *gone* should
    /// say [`DeviceError::Closed`] instead, which stops the driver rather
    /// than retrying into it.
    ///
    /// The string reaches the management plane verbatim. `sched::transmit`
    /// raises a [`DeviceEvent`] carrying it, the driver's event stream carries
    /// that, and it is published as `events/modem/device_fault/<ulid>` with the
    /// text in `detail` (#51). Write it for an operator, not for a log grep:
    /// it is the only place a device speaks in its own words.
    #[error("medium error: {0}")]
    Device(String),
}

/// RFC 2863's operational status — the states something here produces.
///
/// `dormant`, `testing` and `lowerLayerDown` are not declared, deliberately: a
/// state is added when a device produces it. Linux's operstate documentation
/// defines dormant as "L1 up, but waiting for an external event", and a
/// coverage gap is L1 down — so a terminal out of coverage is [`Down`] with
/// [`OperStatus::recoverable`] set, never dormant (#121).
///
/// [`Down`]: OperState::Down
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum OperState {
    /// Passing traffic.
    Up,
    /// Not passing traffic; [`OperStatus::recoverable`] says whether it
    /// expects to again without help.
    Down,
    /// The device node is gone: a serial port unplugged, an interface
    /// removed. Distinct from `Down` because no amount of waiting fixes it.
    NotPresent,
    /// The device has not said, and nothing else can tell. The default.
    Unknown,
}

impl OperState {
    /// The wire spelling: RFC 2863's own, so `notPresent` keeps its case.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Up => "up",
            Self::Down => "down",
            Self::NotPresent => "notPresent",
            Self::Unknown => "unknown",
        }
    }
}

impl fmt::Display for OperState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// RFC 2863's administrative status: what was asked of the device.
///
/// Exists so that radio silence is expressible and distinguishable from a
/// failure — an operator who ordered EMCON reads `admin: down, status: down`
/// and knows nothing broke. Ordering it is a hot configuration group (#126).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AdminState {
    /// Asked to carry traffic.
    #[default]
    Up,
    /// Asked to be silent.
    Down,
}

impl AdminState {
    /// The wire spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Up => "up",
            Self::Down => "down",
        }
    }
}

impl fmt::Display for AdminState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// What a device says about whether it is working (#121).
///
/// Sync and cached, like [`Report`]: the management plane polls it, and a
/// device that needs I/O to answer keeps a snapshot. Every field is a fact
/// the device has; a device that has none returns [`OperStatus::unknown`],
/// which is the default and is honest. It cannot be derived from
/// [`DeviceEvent`], whose detail is free text.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct OperStatus {
    /// The operational status.
    pub status: OperState,
    /// The administrative status.
    pub admin: AdminState,
    /// Why, in the device's words, when it is not up.
    pub reason: Option<String>,
    /// Whether the device expects to come back on its own. `false` is the
    /// one value that means something — a dead medium — and is what a
    /// supervisor reads before deciding to restart (#96). A coverage gap is
    /// `true`; so are `up` and `unknown`, because neither is a reason to
    /// restart.
    pub recoverable: bool,
    /// When the status last changed, on the device's clock.
    pub since: Option<std::time::SystemTime>,
}

impl Default for OperStatus {
    fn default() -> Self {
        Self::unknown()
    }
}

impl OperStatus {
    fn with(status: OperState, reason: Option<String>, recoverable: bool) -> Self {
        Self {
            status,
            admin: AdminState::Up,
            reason,
            recoverable,
            since: None,
        }
    }

    /// The device has not said. The default.
    #[must_use]
    pub fn unknown() -> Self {
        Self::with(OperState::Unknown, None, true)
    }

    /// Passing traffic.
    #[must_use]
    pub fn up() -> Self {
        Self::with(OperState::Up, None, true)
    }

    /// Not passing traffic, with the reason and whether it expects to again.
    #[must_use]
    pub fn down(reason: impl Into<String>, recoverable: bool) -> Self {
        Self::with(OperState::Down, Some(reason.into()), recoverable)
    }

    /// The device node is gone.
    #[must_use]
    pub fn not_present(reason: impl Into<String>) -> Self {
        Self::with(OperState::NotPresent, Some(reason.into()), false)
    }

    /// When this status began, on the device's clock.
    #[must_use]
    pub fn since(mut self, at: std::time::SystemTime) -> Self {
        self.since = Some(at);
        self
    }

    /// With the administrative status.
    #[must_use]
    pub fn admin(mut self, admin: AdminState) -> Self {
        self.admin = admin;
        self
    }

    /// Whether the device is passing traffic.
    #[must_use]
    pub fn is_up(&self) -> bool {
        self.status == OperState::Up
    }
}

/// What a device is, with RFC 8348's field names (#122).
///
/// Every field optional and the type `#[non_exhaustive]`: a device says what
/// it knows, and a field arrives when a device produces it. **Subscriber
/// identifiers never appear here** — an IMSI, an ICCID, an MSISDN identifies
/// a person's subscription, not equipment (invariant I5). The equipment
/// identifier does, because the gateway keys its endpoints by it; it is an
/// addressing identifier, never a proof of identity.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Identity {
    /// Who made it.
    pub mfg_name: Option<String>,
    /// What it is, in the maker's words.
    pub model_name: Option<String>,
    /// The maker's serial number.
    pub serial_num: Option<String>,
    /// Hardware revision.
    pub hardware_rev: Option<String>,
    /// Firmware revision.
    pub firmware_rev: Option<String>,
    /// Software revision, where it is distinct from the firmware's.
    pub software_rev: Option<String>,
    /// The bearer's equipment identifier — an IMEI.
    pub imei: Option<String>,
}

impl Identity {
    /// A device that knows nothing about itself.
    #[must_use]
    pub fn unknown() -> Self {
        Self::default()
    }

    /// Whether the device said anything at all.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        *self == Self::default()
    }

    fn set(mut self, field: fn(&mut Self) -> &mut Option<String>, v: impl Into<String>) -> Self {
        *field(&mut self) = Some(v.into());
        self
    }

    /// With the maker's name.
    #[must_use]
    pub fn mfg_name(self, v: impl Into<String>) -> Self {
        self.set(|i| &mut i.mfg_name, v)
    }

    /// With the model name.
    #[must_use]
    pub fn model_name(self, v: impl Into<String>) -> Self {
        self.set(|i| &mut i.model_name, v)
    }

    /// With the serial number.
    #[must_use]
    pub fn serial_num(self, v: impl Into<String>) -> Self {
        self.set(|i| &mut i.serial_num, v)
    }

    /// With the hardware revision.
    #[must_use]
    pub fn hardware_rev(self, v: impl Into<String>) -> Self {
        self.set(|i| &mut i.hardware_rev, v)
    }

    /// With the firmware revision.
    #[must_use]
    pub fn firmware_rev(self, v: impl Into<String>) -> Self {
        self.set(|i| &mut i.firmware_rev, v)
    }

    /// With the software revision.
    #[must_use]
    pub fn software_rev(self, v: impl Into<String>) -> Self {
        self.set(|i| &mut i.software_rev, v)
    }

    /// With the equipment identifier.
    #[must_use]
    pub fn imei(self, v: impl Into<String>) -> Self {
        self.set(|i| &mut i.imei, v)
    }
}

/// A device: anything the driver serves on the management plane.
///
/// The core and introspection planes of `docs/design/device-planes.md`, and
/// nothing about how bytes move — that is [`Medium`] for an SDU device, and
/// a netdev's is the kernel's. Every method is defaulted, because a device
/// that says nothing about itself is a legitimate device and every simulator
/// was one until #49; the split from the old `Backend` (#117) changed no
/// behaviour, only which trait a method belongs to.
#[async_trait::async_trait]
pub trait Device: Send + Sync {
    /// What this device says about itself.
    ///
    /// Defaulted to "nothing", because a medium that knows nothing about its
    /// own condition is a legitimate medium and every simulator was one until
    /// #49. Sync rather than `async` **on purpose**: the driver calls this from
    /// `mgmt/telemetry.rs`'s five-second publish loop, and an `async` signature
    /// would invite a backend to put an AT-command round trip there. A device
    /// that needs I/O to answer keeps atomics and a cached snapshot, and says
    /// how old the snapshot is through [`Report::age_ms`].
    ///
    /// **Decorators must forward this.** Seven of this crate's implementors wrap
    /// another `Medium`, and one that inherits the default answers `None` to
    /// everything — which reads as "unknown" rather than as a wrong number, but
    /// is still a lie about the medium underneath. The conformance kit's
    /// [`conformance::medium_decorator_forwards`] is what catches it, and it
    /// covers the whole trait rather than this method alone — which is new: the
    /// check this comment named for three issues asserted `report` and
    /// nothing else, and `close`, `configure_lanes` and `next_event` had gone
    /// unforwarded behind the claim (#50, #51, #52).
    fn report(&self) -> Report {
        Report::default()
    }

    /// Whether this device is working, as RFC 2863 has it (#121).
    ///
    /// Sync and cached, for [`report`](Device::report)'s reason. Defaulted to
    /// [`OperStatus::unknown`]: a device that cannot tell says so, and the
    /// plane publishes that rather than a guess. A medium that has *failed*
    /// need not report it here — the driver knows, and overlays `down` with
    /// `recoverable: false` on whatever the device says. What a device does
    /// know that the driver cannot is the recoverable kind of down: a
    /// coverage gap, a closed contact window, a carrier that dropped.
    ///
    /// **Decorators must forward this**, like everything else here.
    fn oper(&self) -> OperStatus {
        OperStatus::default()
    }

    /// What this device is (#122): RFC 8348's fields and the bearer's
    /// equipment identifier, as much of it as the device knows.
    ///
    /// Sync and cached, for [`report`](Device::report)'s reason: a modem
    /// reads its model, firmware and IMEI once, at open, and answers from
    /// that. Defaulted to [`Identity::unknown`], which is a legitimate
    /// answer — the management plane publishes it as a document with only
    /// the device's name, and a reader knows the device was asked. The plane
    /// polls it and raises `identity_change` when it differs: a terminal
    /// swapped, or its firmware updated, under a running driver.
    ///
    /// **Never a subscriber identifier** (I5). **Decorators must forward
    /// this**, like everything else here.
    fn identity(&self) -> Identity {
        Identity::default()
    }

    /// Wait for the next thing the medium wants to say.
    ///
    /// Mirrors [`recv`](Medium::recv) deliberately: a driver drains this in
    /// its own task, so a backend may block here for as long as it likes and a
    /// medium with nothing to report simply never resolves. The default is
    /// exactly that, which is why every medium in this workspace needs no
    /// implementation.
    ///
    /// **Edge-triggered.** One event when a condition starts and one when it
    /// stops, not a repeat while it persists — see [`Edge`]. A backend that
    /// repeated itself would produce a rate the `events` keyspace cannot
    /// honestly declare, and the driver deduplicating on its behalf would be
    /// guessing at which repeats meant something.
    async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
        std::future::pending().await
    }

    /// Stop, cleanly.
    ///
    /// Called once, on the way down, after every lane task has been aborted and
    /// before the process exits. The default does nothing, because an
    /// in-process medium has nothing to release.
    ///
    /// **A real device does (#50).** Teardown used to be: `Driver::shutdown`
    /// aborts its tasks, the `Arc<dyn Medium>` is dropped, and anything a
    /// radio needed to be told happened in `Drop` with no `async` available. A
    /// radio left keyed, or a modem left in binary-write mode, is the
    /// observable consequence — and neither is visible while a simulator is the
    /// only implementor, because a simulator never needs telling.
    ///
    /// Errors are reported and not propagated: the process is going away, and
    /// there is nothing a caller could do differently. Say what failed.
    async fn close(&self) -> Result<(), DeviceError> {
        Ok(())
    }

    /// This device's configuration plane, if it has one (#125).
    ///
    /// `None` is the honest default: a device with nothing to configure
    /// declares no resource, and the management plane serves none for it.
    fn configuration(&self) -> Option<&dyn Configure> {
        None
    }

    /// The operator actions this device offers (#129): explicit, costed,
    /// never scheduled — an operator deciding, once, now. `None` for a
    /// device with none. There is no `reset` and there will not be one
    /// (architecture §4.11): recovery is a restart, of the device (the
    /// driver's own `reopen` action) or of the daemon (#96).
    fn actions(&self) -> Option<&dyn Actions> {
        None
    }
}

/// A physical or simulated medium: the SDU data plane of a [`Device`].
///
/// Implementations own everything below the driver: framing on the air, vendor
/// APIs, contact scheduling, radio state. They own nothing above it — no
/// routing, no retransmission the hardware does not already provide, and no
/// knowledge of what the bytes mean. `Medium: Device`, so an `Arc<dyn Medium>`
/// upcasts to `Arc<dyn Device>` and the management plane serves it like any
/// other device.
#[async_trait::async_trait]
pub trait Medium: Device {
    /// What this medium can carry. Read once at startup to size lanes.
    fn capabilities(&self) -> Capabilities;

    /// Transmit one SDU on one lane.
    ///
    /// Returns once the medium has taken ownership — which is *not* a delivery
    /// receipt. Implementations must apply backpressure by not returning, rather
    /// than by accepting into an unbounded queue: invariant I3 exists because a
    /// hidden backlog between Zenoh's congestion control and the radio defeats
    /// the whole design.
    async fn send(&self, lane: &LaneKey, sdu: &[u8]) -> Result<(), DeviceError>;

    /// Wait for the next SDU the medium delivers.
    ///
    /// Returns the lane it arrived on, so the driver can route it back to the
    /// matching socket without inspecting the payload.
    async fn recv(&self) -> Result<(LaneKey, Sdu), DeviceError>;

    /// A snapshot of this medium's counters.
    fn metrics(&self) -> Metrics;

    /// Tell the medium which lanes this driver will serve.
    ///
    /// Called once, from `Driver::start`, before anything moves. The default
    /// does nothing, because a medium that was given its topology at
    /// construction has nothing to learn — which is every medium in this
    /// workspace, and was every medium there was when the trait was written.
    ///
    /// **A real backend needs this and had no way to get it (#52).** `recv`
    /// returns a `LaneKey`, and hardware receives bytes with no lane in them:
    /// the endpoint can be recovered from on-air framing, but `reliable` and
    /// `rank` have to be *synthesised*, and nothing told the backend what
    /// combinations exist. Guess wrong and the driver drops the batch on a lane
    /// it does not have — silently until #52's first commit, and counted as
    /// `rx_unroutable_total` since.
    ///
    /// The driver is the authority here: these are the lanes it resolved from
    /// its own config and will actually serve, not the lanes a config file
    /// mentioned. Returning an error refuses startup, which is the right
    /// response to a medium that cannot serve what it is being asked for.
    async fn configure_lanes(&self, lanes: &[LaneKey]) -> Result<(), DeviceError> {
        let _ = lanes;
        Ok(())
    }
}

/// A device whose data plane is the kernel's: a network interface that Zenoh
/// reaches over an ordinary TCP link bound to it (#118, #130).
///
/// Nothing here moves a byte — that is the point. The driver serves such a
/// device on the management plane exactly as it serves a [`Medium`], and the
/// lanes, the scheduler and the framing never see it: `Netdev: Device`, not
/// `Netdev: Medium`. What a netdev knows about its interface — statistics,
/// the operational state, an MTU to configure — arrives with #130; this
/// release names the interface and nothing else, so that a host can carry
/// one beside a modem and the roster shows one producer.
pub trait Netdev: Device {
    /// The interface name, as the kernel spells it: `wwan0`, `ppp0`.
    fn interface(&self) -> &str;

    /// The interface's counters, as the kernel keeps them (#130): sync and
    /// cached, like [`Device::report`]. A counter the kernel does not keep
    /// is absent, never zero.
    fn statistics(&self) -> NetdevStats {
        NetdevStats::default()
    }

    /// The presence epoch (zenkey RFC 04 §5, v1.39): moves when the
    /// interface is re-enumerated (its `ifindex` changed) or a counter is
    /// observed to decrease — what a USB modem re-enumerating looks like —
    /// and the management plane cycles `device/{device}/alive` when it does,
    /// which is the one reset the registry sanctions for the counters under
    /// this device. `0` until it moves.
    fn epoch(&self) -> u64 {
        0
    }
}

/// A network interface's counters (#130), with RFC 8343's names where Linux
/// keeps exactly that counter and nothing else.
///
/// `in_pkts` and `out_pkts` are **not** RFC 8343's: the RFC splits packets by
/// unicast, multicast and broadcast, Linux's `rx_packets` includes multicast,
/// and Linux keeps no broadcast counter. They are here because an operator
/// asks for them; the registry says what they are.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct NetdevStats {
    /// `rx_bytes` — RFC 8343 `in-octets`.
    pub in_octets: Option<u64>,
    /// `tx_bytes` — RFC 8343 `out-octets`.
    pub out_octets: Option<u64>,
    /// `rx_errors` — RFC 8343 `in-errors`.
    pub in_errors: Option<u64>,
    /// `tx_errors` — RFC 8343 `out-errors`.
    pub out_errors: Option<u64>,
    /// `rx_dropped` — RFC 8343 `in-discards`.
    pub in_discards: Option<u64>,
    /// `tx_dropped` — RFC 8343 `out-discards`.
    pub out_discards: Option<u64>,
    /// `multicast` — RFC 8343 `in-multicast-pkts`.
    pub in_multicast_pkts: Option<u64>,
    /// `rx_packets` — not RFC 8343: unicast and multicast together.
    pub in_pkts: Option<u64>,
    /// `tx_packets` — not RFC 8343.
    pub out_pkts: Option<u64>,
    /// Bytes queued in the interface's queue discipline now, not yet sent
    /// (#136). Not a sysfs counter: read over netlink, and only from the
    /// kernel's own interface. The queue an operator watches form when a
    /// bearer is slower than what is offered to it.
    pub qdisc_backlog_bytes: Option<u64>,
    /// Packets queued in the queue discipline now (#136).
    pub qdisc_backlog_pkts: Option<u64>,
}

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

    fn lane(rank: u8, reliable: bool) -> LaneKey {
        LaneKey {
            endpoint: EndpointId::new("peer-b"),
            reliable,
            rank,
        }
    }

    #[test]
    fn the_operational_states_spell_themselves_as_rfc_2863_does() {
        assert_eq!(OperState::Up.as_str(), "up");
        assert_eq!(OperState::Down.as_str(), "down");
        assert_eq!(OperState::NotPresent.as_str(), "notPresent");
        assert_eq!(OperState::Unknown.as_str(), "unknown");
        assert_eq!(AdminState::Down.to_string(), "down");
    }

    #[test]
    fn a_device_that_says_nothing_is_unknown_and_not_a_reason_to_restart() {
        let s = OperStatus::default();
        assert_eq!(s.status, OperState::Unknown);
        assert_eq!(s.admin, AdminState::Up);
        assert!(s.recoverable, "unknown is not a reason to restart");
        assert!(s.reason.is_none());
        assert!(!s.is_up());
        assert!(!OperStatus::down("dead", false).recoverable);
        assert!(OperStatus::down("no coverage", true).recoverable);
        assert!(!OperStatus::not_present("port unplugged").recoverable);
        assert!(OperStatus::up().is_up());
    }

    #[test]
    fn an_identity_says_only_what_the_device_knows() {
        assert!(Identity::unknown().is_empty());
        let id = Identity::unknown()
            .model_name("IRIDIUM 9603")
            .imei("300234060000000");
        assert!(!id.is_empty());
        assert_eq!(id.model_name.as_deref(), Some("IRIDIUM 9603"));
        assert_eq!(id.mfg_name, None, "unasked is absent, not empty");
    }

    #[test]
    fn the_vocabulary_keeps_the_report_copy_and_eq_at_fixed_point() {
        // RSRQ and SNR move in half-dB steps; milli-units hold them exactly,
        // which is what lets `Report` stay `Copy + Eq` without an `f64`.
        let r = Report::new()
            .rssi(-97_500)
            .rsrq(-10_500)
            .snr(12_000)
            .rx_rate(1_000_000)
            .latency(45_000)
            .registration(Registration::Home)
            .access_technology(AccessTechnology::Lte);
        assert_eq!(r, r, "Eq");
        let copy = r;
        assert_eq!(copy.rssi, Some(-97_500));
        assert_eq!(r.rsrp, None, "unmeasured is absent");
        assert_eq!(Registration::Home.as_str(), "home");
        assert_eq!(AccessTechnology::Nr5g.as_str(), "5gnr");
    }

    #[test]
    fn a_lane_renders_as_endpoint_reliability_and_rank() {
        assert_eq!(lane(0, true).to_string(), "peer-b/rel#0");
        assert_eq!(lane(5, false).to_string(), "peer-b/be#5");
    }

    #[test]
    fn lanes_differing_only_in_reliability_are_distinct() {
        assert_ne!(lane(0, true), lane(0, false));
    }

    #[test]
    fn capabilities_may_be_asymmetric() {
        // The SBD profile: 340 up, 270 down. Nothing here collapses them.
        let caps = Capabilities {
            tx_max_sdu: 340,
            rx_max_sdu: 270,
            duplex: Duplex::Full,
            reliable: true,
        };
        assert_ne!(caps.tx_max_sdu, caps.rx_max_sdu);
    }

    #[test]
    fn an_oversized_sdu_names_the_batch_size_that_would_fit() {
        // The +2 is Zenoh's length prefix, which lives inside the batch buffer:
        // a batch_size of N puts N-2 bytes on the medium.
        let e = DeviceError::SduTooLarge { got: 300, max: 218 };
        assert_eq!(
            e.to_string(),
            "sdu of 300 bytes exceeds the medium's tx_max_sdu of 218: \
             lower zenoh's batch_size to at most 220 (architecture I4, §4.5)"
        );
    }
}