modem_device/lib.rs
1//! The seam between the driver and a medium.
2//!
3//! This crate deliberately does not depend on `zenoh`, and CI holds that with a
4//! dependency-graph guard. The driver moves opaque batches and the medium moves
5//! opaque SDUs; the moment either could parse a key expression, the second
6//! policy plane the architecture forbids would exist
7//! (`docs/architecture.md` I1, §4.8).
8//!
9//! Everything here describes a medium in terms a modem vendor would recognise —
10//! how big an SDU may be, whether it can transmit and receive at once, whether
11//! delivery is ordered and loss-free. Nothing here describes Zenoh.
12//!
13//! Two traits since #117, split along the planes of
14//! `docs/design/device-planes.md`: [`Device`] is what the management plane
15//! serves — a report, events, a lifecycle, and later a configuration plane —
16//! and [`Medium`]`: Device` is the SDU data plane on top of it. A device whose
17//! data plane is the kernel's is a [`Netdev`]`: Device` — named, served on the
18//! management plane, and never seen by the lanes.
19
20use std::fmt;
21
22pub mod action;
23pub mod config;
24pub mod conformance;
25pub use action::Actions;
26pub use config::Configure;
27
28/// Zenoh's own framing on the data path: a two-byte little-endian length
29/// before every batch, which the driver strips before the medium and re-adds
30/// after (`docs/architecture.md` §4.1). Stated here because a batch of N
31/// bytes puts N - 2 on the medium, and every document that names a
32/// `max_batch_size` has to add it back — the contract's `Capabilities` does.
33pub const LENGTH_PREFIX: usize = 2;
34
35/// One service data unit: exactly what the medium carries in one transmission.
36///
37/// The driver has already stripped Zenoh's two-byte length prefix by the time an
38/// SDU reaches a backend, and re-adds it on the way back
39/// (`docs/architecture.md` §4.1). Contents are never inspected.
40pub type Sdu = Vec<u8>;
41
42/// A remote endpoint reachable over the medium.
43///
44/// Opaque to the driver and to Zenoh alike. It is a name from configuration —
45/// `"peer-b"`, `"auv-03"`, an IMEI — and per invariant I5 it is an *addressing*
46/// identifier, never a proof of identity.
47#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
48pub struct EndpointId(String);
49
50impl EndpointId {
51 /// Wrap a configured endpoint name.
52 pub fn new(name: impl Into<String>) -> Self {
53 Self(name.into())
54 }
55
56 /// The configured name, for logging and for keying medium-side tables.
57 pub fn as_str(&self) -> &str {
58 &self.0
59 }
60}
61
62impl fmt::Display for EndpointId {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 f.write_str(&self.0)
65 }
66}
67
68/// The driver's view of one QoS lane.
69///
70/// Under decision D1 a lane is a socket, and its properties come from the
71/// locator metadata Zenoh was configured with (`?rel=1;prio=0-2`) — resolved
72/// once, at startup, into this. A backend schedules lanes; it is never told what
73/// a Zenoh priority is, which is what keeps [`Sdu`] traffic and Zenoh semantics
74/// on opposite sides of this crate boundary.
75#[derive(Clone, Debug, PartialEq, Eq, Hash)]
76pub struct LaneKey {
77 /// Which remote this lane reaches.
78 pub endpoint: EndpointId,
79 /// Whether this lane promises ordered, loss-free delivery.
80 ///
81 /// Per invariant I2 this is a claim about the *medium*, not a request. A
82 /// backend that cannot honour it must not be configured behind a lane that
83 /// asserts it: Zenoh will not notice the lie, because `verify_sn` accepts a
84 /// forward sequence gap silently — the failure mode is lost data, not a
85 /// fault.
86 pub reliable: bool,
87 /// Scheduling rank; lower is more urgent.
88 ///
89 /// Derived at configuration time from the lane's declared priority range.
90 /// Rank 0 sorts first. The numbering happens to mirror Zenoh's, where
91 /// `Control` is 0, but nothing here depends on that.
92 pub rank: u8,
93}
94
95impl fmt::Display for LaneKey {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 write!(
98 f,
99 "{}/{}#{}",
100 self.endpoint,
101 if self.reliable { "rel" } else { "be" },
102 self.rank
103 )
104 }
105}
106
107/// Whether the medium can transmit and receive simultaneously.
108///
109/// Only the two variants that change behaviour exist. The withdrawn ICD series
110/// carried five, three of which had no consequence anywhere in the
111/// specification; new variants are added here when something acts on them.
112#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
113#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
114#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
115// Deliberately *not* `#[non_exhaustive]` (#97): a new duplex mode changes what
116// every scheduler and simulator must do, so it should break their builds, and
117// the contract's own `Duplex` maps this one variant for variant.
118pub enum Duplex {
119 /// Transmit and receive are independent.
120 #[default]
121 Full,
122 /// Transmitting blocks receiving and vice versa, as on a shared RF channel.
123 Half,
124}
125
126/// What a medium can do, as the medium itself would describe it.
127///
128/// Transmit and receive limits are separate because real media are asymmetric:
129/// Iridium SBD carries 340 bytes up and 270 down. Collapsing them to their
130/// minimum — as the withdrawn design did — silently wasted 21% of every paid
131/// uplink message (`docs/architecture.md` §4.9).
132#[derive(Clone, Copy, Debug, PartialEq, Eq)]
133pub struct Capabilities {
134 /// Largest SDU the medium will transmit, in bytes.
135 ///
136 /// `u16` because Zenoh's own `BatchSize` is `u16`, so a larger value could
137 /// never be filled.
138 pub tx_max_sdu: u16,
139 /// Largest SDU the medium will deliver, in bytes.
140 ///
141 /// **A promise this backend makes, and the driver checks it** (#75). An
142 /// arrival larger than this counts `rx_oversize_total` and is logged as a
143 /// contract violation; it is still delivered, because the batch is Zenoh's
144 /// to judge and discarding it here would be the driver deciding a question
145 /// I1 gives to Zenoh.
146 ///
147 /// It is **not** what stops a peer sending too much, and the distinction
148 /// matters on an asymmetric bearer. `batch_size` is node-global and Zenoh
149 /// negotiates the minimum of the two ends, so a pair configured
150 /// inconsistently produces a *small* effective batch — 21% of a paid
151 /// uplink slot wasted on SBD — never an oversized arrival. What an
152 /// operator does with this number is size the *far* node's `batch_size`,
153 /// which is why `Driver::start` logs it as `peer_max_batch_size` (#82).
154 pub rx_max_sdu: u16,
155 /// Whether transmit and receive contend.
156 pub duplex: Duplex,
157 /// Whether the medium delivers in order and without loss.
158 ///
159 /// Per invariant I2 this must be the truth about the hardware, not an
160 /// aspiration. A lane may only assert [`LaneKey::reliable`] over a medium
161 /// that reports `true` here.
162 pub reliable: bool,
163}
164
165/// Counters a medium exposes for telemetry.
166///
167/// Deliberately minimal: these are the quantities the driver can assert on in a
168/// test. Radio-specific figures such as RSSI belong on the management plane
169/// (`docs/architecture.md` §4.6), not in the data-path interface.
170#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
171pub struct Metrics {
172 /// SDUs handed to the medium and accepted.
173 pub tx_sdus: u64,
174 /// Bytes across those SDUs.
175 pub tx_bytes: u64,
176 /// SDUs delivered by the medium.
177 pub rx_sdus: u64,
178 /// Bytes across those SDUs.
179 pub rx_bytes: u64,
180 /// SDUs the medium accepted and then lost, where it can tell.
181 ///
182 /// A medium that cannot distinguish loss from delivery leaves this at zero;
183 /// per the architecture's telemetry rule, absence means unknown and must not
184 /// be read as none.
185 pub dropped: u64,
186}
187
188/// What a device says about itself, as far as it knows.
189///
190/// `Capabilities` is what the medium *can* carry and is read once; `Metrics` is
191/// what the driver counted and is what a test asserts on. This is the third
192/// thing, and the one that fell off the edge: what the hardware knows about its
193/// own condition. `modem-device` named the gap years before it had a shape —
194/// "radio-specific figures such as RSSI belong on the management plane" — and
195/// then never built the other side of it (#49).
196///
197/// **Every field is `Option`, and that is load-bearing twice over.** A device
198/// that cannot answer says `None` rather than zero, because a zeroed counter is
199/// a claim and absence is not. And five of this crate's eight implementors are
200/// decorators wrapping another `Medium`; a decorator that forgets to forward
201/// this method inherits the default, whose every field is `None` — the same
202/// answer as "I do not know", rather than a confident wrong number belonging to
203/// the medium underneath.
204///
205/// `#[non_exhaustive]` because #49 lists eleven quantities and hardware will
206/// suggest twenty more. As fields on one struct behind one defaulted method,
207/// adding `signal.rssi_dbm` later touches the backend that fills it and the
208/// publisher that reads it — as methods, each would be an eight-implementor
209/// event for ever.
210#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
211#[non_exhaustive]
212pub struct Report {
213 /// How long ago this snapshot was taken.
214 ///
215 /// [`Device::report`] is sync, so a backend cannot do I/O in it and
216 /// must answer from a cache. A cache with no age is a lie the moment the
217 /// modem stops answering, which is exactly when an operator is reading it —
218 /// so the age rides along, and a report older than a consumer's tolerance is
219 /// published as absent rather than as current.
220 pub age_ms: Option<u64>,
221
222 /// Cumulative channel occupancy, in milliseconds.
223 ///
224 /// What the medium has actually spent on the air. On a service billed in
225 /// airtime this is the bill; `lease-tuning-in-a-cell.md` is the measurement
226 /// that made the distinction between this and a message count matter.
227 pub time_on_air_ms: Option<u64>,
228
229 /// Transmissions made only because an earlier attempt was lost.
230 ///
231 /// The medium's own ARQ, which `rf-arq-requirement.md` makes a hardware
232 /// selection requirement. Counted by every simulator in the tree today and
233 /// reachable through none of them.
234 pub retransmits: Option<u64>,
235
236 /// Slot bytes paid for and not used.
237 ///
238 /// A per-message service charges for the whole slot; M2 measured 9.4%
239 /// utilisation at the defaults. This is the same figure from the medium's
240 /// side, for a deployment rather than for a measurement.
241 pub bytes_wasted: Option<u64>,
242
243 /// Frames the medium received and could not accept: FIFO overrun,
244 /// collision, CRC or header failure.
245 ///
246 /// **Distinct from [`Metrics::dropped`]**, which is accepted-then-lost on
247 /// *transmit*. #49 describes these as conflated; they are not — no shipped
248 /// medium puts receive-side errors into `dropped` — but they are counted
249 /// (`sim.rs`'s `lost_attempts`, `cell.rs`'s `collisions` and `overruns`) and
250 /// have had no way out of the crate at all.
251 pub rx_errors: Option<u64>,
252
253 /// Whether the medium may transmit now, and how long until it may.
254 pub duty_cycle: Option<DutyCycle>,
255
256 /// Received signal strength, on the device's own 0–5 scale.
257 ///
258 /// **Bars, not dBm, and the distinction is the point.** An Iridium ISU
259 /// answers `AT+CSQF` with an integer 0–5 and has no dBm to give; an
260 /// SX1262 reads a dBm out of a packet-status register and has no bars.
261 /// A field spelled `rssi_dbm` would force one of them to invent a number,
262 /// which is the failure `Report`'s all-`Option` shape exists to
263 /// avoid — a device says what it knows and stays quiet about the rest. A
264 /// dBm field arrives with the backend that measures one (#49, #76).
265 pub signal_bars: Option<u8>,
266
267 // --- The IP-bearer vocabulary (#123). Names carry no unit suffix: the
268 // registry's `unit` is where a unit lives, and a name-and-field pair is
269 // two places to drift. Fixed-point, because this type is `Copy + Eq`:
270 // milli-units cover RSRQ's and SNR's half-dB steps exactly.
271 /// Received signal strength, milli-dBm (ModemManager `Modem.Signal`,
272 /// an SX1262's packet status).
273 pub rssi: Option<i32>,
274 /// Reference signal received power, milli-dBm (LTE, NR).
275 pub rsrp: Option<i32>,
276 /// Reference signal received quality, milli-dB.
277 pub rsrq: Option<i32>,
278 /// Signal-to-noise ratio, milli-dB.
279 pub snr: Option<i32>,
280 /// Error rate, milli-percent.
281 pub error_rate: Option<i32>,
282 /// Current receive data rate, bit/s (DLEP, RFC 8175 §13 — session level;
283 /// per-destination metrics are not device-level and are not here).
284 pub rx_rate: Option<u64>,
285 /// Current transmit data rate, bit/s.
286 pub tx_rate: Option<u64>,
287 /// Maximum receive data rate, bit/s.
288 pub rx_max_rate: Option<u64>,
289 /// Maximum transmit data rate, bit/s.
290 pub tx_max_rate: Option<u64>,
291 /// Latency, microseconds.
292 pub latency: Option<u64>,
293 /// Resources available on the link, milli-percent.
294 pub resources: Option<i32>,
295 /// Relative receive link quality, milli-percent.
296 pub rx_quality: Option<i32>,
297 /// Relative transmit link quality, milli-percent.
298 pub tx_quality: Option<i32>,
299 /// Network registration, for a bearer that registers with one.
300 pub registration: Option<Registration>,
301 /// The access technology the bearer is on.
302 pub access_technology: Option<AccessTechnology>,
303}
304
305impl Report {
306 /// An empty report — the same thing [`Device::report`]'s default
307 /// returns, and the starting point for a backend that fills some of it.
308 ///
309 /// The setters below take and return `self` so a backend names only what it
310 /// knows: `Report::new().retransmits(n).rx_errors(m)`. That shape is
311 /// what makes `#[non_exhaustive]` free rather than annoying — this type is
312 /// implemented from *outside* this crate, so a struct literal would make
313 /// every new field a breaking change, which is exactly the churn #49's
314 /// eleven-and-counting quantities would cause.
315 #[must_use]
316 pub fn new() -> Self {
317 Self::default()
318 }
319
320 /// How old this snapshot is. See [`Report::age_ms`].
321 #[must_use]
322 pub fn age_ms(mut self, ms: u64) -> Self {
323 self.age_ms = Some(ms);
324 self
325 }
326
327 /// Cumulative channel occupancy.
328 #[must_use]
329 pub fn time_on_air_ms(mut self, ms: u64) -> Self {
330 self.time_on_air_ms = Some(ms);
331 self
332 }
333
334 /// Transmissions made only because an earlier attempt was lost.
335 #[must_use]
336 pub fn retransmits(mut self, n: u64) -> Self {
337 self.retransmits = Some(n);
338 self
339 }
340
341 /// Slot bytes paid for and not used.
342 #[must_use]
343 pub fn bytes_wasted(mut self, n: u64) -> Self {
344 self.bytes_wasted = Some(n);
345 self
346 }
347
348 /// Frames received and not accepted.
349 #[must_use]
350 pub fn rx_errors(mut self, n: u64) -> Self {
351 self.rx_errors = Some(n);
352 self
353 }
354
355 /// Whether the medium may transmit now.
356 #[must_use]
357 pub fn duty_cycle(mut self, duty: DutyCycle) -> Self {
358 self.duty_cycle = Some(duty);
359 self
360 }
361
362 /// Signal strength on the device's own 0–5 scale.
363 #[must_use]
364 pub fn signal_bars(mut self, bars: u8) -> Self {
365 self.signal_bars = Some(bars);
366 self
367 }
368
369 /// Received signal strength, milli-dBm.
370 #[must_use]
371 pub fn rssi(mut self, milli_dbm: i32) -> Self {
372 self.rssi = Some(milli_dbm);
373 self
374 }
375
376 /// Reference signal received power, milli-dBm.
377 #[must_use]
378 pub fn rsrp(mut self, milli_dbm: i32) -> Self {
379 self.rsrp = Some(milli_dbm);
380 self
381 }
382
383 /// Reference signal received quality, milli-dB.
384 #[must_use]
385 pub fn rsrq(mut self, milli_db: i32) -> Self {
386 self.rsrq = Some(milli_db);
387 self
388 }
389
390 /// Signal-to-noise ratio, milli-dB.
391 #[must_use]
392 pub fn snr(mut self, milli_db: i32) -> Self {
393 self.snr = Some(milli_db);
394 self
395 }
396
397 /// Error rate, milli-percent.
398 #[must_use]
399 pub fn error_rate(mut self, milli_percent: i32) -> Self {
400 self.error_rate = Some(milli_percent);
401 self
402 }
403
404 /// Current receive data rate, bit/s.
405 #[must_use]
406 pub fn rx_rate(mut self, bps: u64) -> Self {
407 self.rx_rate = Some(bps);
408 self
409 }
410
411 /// Current transmit data rate, bit/s.
412 #[must_use]
413 pub fn tx_rate(mut self, bps: u64) -> Self {
414 self.tx_rate = Some(bps);
415 self
416 }
417
418 /// Maximum receive data rate, bit/s.
419 #[must_use]
420 pub fn rx_max_rate(mut self, bps: u64) -> Self {
421 self.rx_max_rate = Some(bps);
422 self
423 }
424
425 /// Maximum transmit data rate, bit/s.
426 #[must_use]
427 pub fn tx_max_rate(mut self, bps: u64) -> Self {
428 self.tx_max_rate = Some(bps);
429 self
430 }
431
432 /// Latency, microseconds.
433 #[must_use]
434 pub fn latency(mut self, us: u64) -> Self {
435 self.latency = Some(us);
436 self
437 }
438
439 /// Resources available on the link, milli-percent.
440 #[must_use]
441 pub fn resources(mut self, milli_percent: i32) -> Self {
442 self.resources = Some(milli_percent);
443 self
444 }
445
446 /// Relative receive link quality, milli-percent.
447 #[must_use]
448 pub fn rx_quality(mut self, milli_percent: i32) -> Self {
449 self.rx_quality = Some(milli_percent);
450 self
451 }
452
453 /// Relative transmit link quality, milli-percent.
454 #[must_use]
455 pub fn tx_quality(mut self, milli_percent: i32) -> Self {
456 self.tx_quality = Some(milli_percent);
457 self
458 }
459
460 /// Network registration.
461 #[must_use]
462 pub fn registration(mut self, r: Registration) -> Self {
463 self.registration = Some(r);
464 self
465 }
466
467 /// The access technology the bearer is on.
468 #[must_use]
469 pub fn access_technology(mut self, t: AccessTechnology) -> Self {
470 self.access_technology = Some(t);
471 self
472 }
473}
474
475/// Where a bearer stands with its network (ModemManager's 3GPP registration
476/// states; #123). A device that registers with nothing — a point-to-point
477/// radio — reports none.
478#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
479#[non_exhaustive]
480pub enum Registration {
481 /// Not registered, not searching.
482 Idle,
483 /// Registered on the home network.
484 Home,
485 /// Searching for a network.
486 Searching,
487 /// Registration denied.
488 Denied,
489 /// Registered, roaming.
490 Roaming,
491 /// The device cannot say.
492 Unknown,
493}
494
495impl Registration {
496 /// The wire spelling.
497 #[must_use]
498 pub const fn as_str(self) -> &'static str {
499 match self {
500 Self::Idle => "idle",
501 Self::Home => "home",
502 Self::Searching => "searching",
503 Self::Denied => "denied",
504 Self::Roaming => "roaming",
505 Self::Unknown => "unknown",
506 }
507 }
508}
509
510impl fmt::Display for Registration {
511 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512 f.write_str(self.as_str())
513 }
514}
515
516/// The access technology a bearer is on (#123). Closed and
517/// `#[non_exhaustive]`: a value is added when a device produces it, and a
518/// reader that sees one it does not know treats it as text.
519#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
520#[non_exhaustive]
521pub enum AccessTechnology {
522 Gsm,
523 Gprs,
524 Edge,
525 Umts,
526 Hspa,
527 Lte,
528 Nr5g,
529 /// Iridium's own air interface — an SBD terminal.
530 Iridium,
531}
532
533impl AccessTechnology {
534 /// The wire spelling: ModemManager's, lowercase.
535 #[must_use]
536 pub const fn as_str(self) -> &'static str {
537 match self {
538 Self::Gsm => "gsm",
539 Self::Gprs => "gprs",
540 Self::Edge => "edge",
541 Self::Umts => "umts",
542 Self::Hspa => "hspa",
543 Self::Lte => "lte",
544 Self::Nr5g => "5gnr",
545 Self::Iridium => "iridium",
546 }
547 }
548}
549
550impl fmt::Display for AccessTechnology {
551 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
552 f.write_str(self.as_str())
553 }
554}
555
556/// Why a medium is not transmitting, when the answer is "not yet".
557///
558/// The case #49 calls sharpest, and the reason it is in v1 rather than deferred
559/// with the rest: a compliant EU868 backend must **block** in `send` for up to
560/// ~99 s, and an operator watching `queue_depth` climb cannot tell
561/// "duty-cycle limited" from "radio dead". `SimMedium::slide_to_contact` already
562/// blocks for exactly this reason and `ContactWindow::wait_at` already computes
563/// the number, so this is a producer that exists rather than a keyspace row
564/// waiting for hardware.
565#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
566#[non_exhaustive]
567pub struct DutyCycle {
568 /// Whether the medium would take an SDU right now.
569 pub available: bool,
570 /// Milliseconds until it would, when it would not.
571 ///
572 /// Zero while [`available`](Self::available) is false means the medium is
573 /// blocked and does not know for how long, which is a different answer from
574 /// "blocked for 0 ms" and a real state for a device that can say it is busy
575 /// without saying when it will not be.
576 pub next_available_in_ms: u64,
577}
578
579impl DutyCycle {
580 /// The medium would take an SDU now.
581 #[must_use]
582 pub fn ready() -> Self {
583 Self {
584 available: true,
585 next_available_in_ms: 0,
586 }
587 }
588
589 /// The medium would not, and this is how long until it would.
590 ///
591 /// Two named constructors rather than one taking `(bool, u64)`, because the
592 /// two states are what a caller is choosing between and a boolean argument
593 /// at a call site says nothing about which way round it goes.
594 #[must_use]
595 pub fn wait_ms(ms: u64) -> Self {
596 Self {
597 available: false,
598 next_available_in_ms: ms,
599 }
600 }
601}
602
603/// Something the medium wants to say when nobody is calling [`Medium::send`].
604///
605/// The gap #51 names: every `DeviceError` is the return value of a data-path
606/// call, so a radio that loses registration, overheats, or drops off the bus is
607/// silent until the next transmission — which on a store-and-forward link may
608/// be an hour away, and on a dead one is never.
609///
610/// A plain struct rather than a channel, and that is the whole reason this
611/// works. `modem-device` has three dependencies — `async-trait`, `thiserror`,
612/// optional `serde` — and **no tokio**. Putting a `watch::Receiver` or a
613/// `broadcast::Receiver` on the trait would drag a runtime into a crate whose
614/// entire job is to be the seam, to obtain a channel type. An `async fn`
615/// mirroring [`Medium::recv`] needs nothing, is dyn-compatible through the
616/// `async-trait` already here, and has a default whose meaning is exactly
617/// "this medium never says anything".
618#[derive(Clone, Debug, PartialEq, Eq)]
619#[non_exhaustive]
620pub struct DeviceEvent {
621 /// The lane it concerns, if it concerns one.
622 ///
623 /// `None` for a device-wide condition — registration lost, over
624 /// temperature, duty-cycle budget exhausted — which is most of them.
625 pub lane: Option<LaneKey>,
626 /// Whether this is the medium becoming unhappy or becoming happy again.
627 ///
628 /// Edge-triggered by contract. A backend that repeated `Raised` while a
629 /// condition persisted would produce a stream no `rate` declaration could
630 /// honestly cover, and the consumer's job is to publish these, not to
631 /// deduplicate somebody else's.
632 pub edge: Edge,
633 /// The device's own words.
634 ///
635 /// Carried verbatim to the management plane, which is the point: until #51
636 /// a `DeviceError::Device(String)` reached a `warn!` and was discarded, so
637 /// `+CME ERROR 3` — the one thing that says what is actually wrong — never
638 /// left the process.
639 pub detail: String,
640}
641
642impl DeviceEvent {
643 /// A condition beginning.
644 #[must_use]
645 pub fn raised(detail: impl Into<String>) -> Self {
646 Self {
647 lane: None,
648 edge: Edge::Raised,
649 detail: detail.into(),
650 }
651 }
652
653 /// A condition ending.
654 #[must_use]
655 pub fn cleared(detail: impl Into<String>) -> Self {
656 Self {
657 lane: None,
658 edge: Edge::Cleared,
659 detail: detail.into(),
660 }
661 }
662
663 /// Attribute this event to one lane.
664 #[must_use]
665 pub fn on_lane(mut self, lane: LaneKey) -> Self {
666 self.lane = Some(lane);
667 self
668 }
669}
670
671/// Which way a condition just went.
672#[derive(Clone, Copy, Debug, PartialEq, Eq)]
673#[non_exhaustive]
674pub enum Edge {
675 /// It started.
676 Raised,
677 /// It stopped.
678 Cleared,
679}
680
681/// Why a medium refused or failed an SDU.
682///
683/// `#[non_exhaustive]`: both consumers on the data path already match with a
684/// catch-all (`sched.rs`'s retry arm, `lanes.rs`'s receive loop), so this costs
685/// nothing today and leaves room for the variants a real device will need. The
686/// alternative is discovering later that adding one is a breaking change to a
687/// crate whose whole job is to be implemented from outside.
688#[derive(Debug, thiserror::Error)]
689#[non_exhaustive]
690pub enum DeviceError {
691 /// The SDU is larger than the medium can carry.
692 ///
693 /// Invariant I4: the driver never splits a batch to make it fit. An SDU that
694 /// does not fit is a configuration error — Zenoh's `batch_size` was set
695 /// above what this medium can carry — and it is reported, loudly, as one.
696 #[error(
697 "sdu of {got} bytes exceeds the medium's tx_max_sdu of {max}: \
698 lower zenoh's batch_size to at most {} (architecture I4, §4.5)", *max as usize + 2
699 )]
700 SduTooLarge { got: usize, max: u16 },
701
702 /// No such lane is configured on this medium.
703 #[error("unknown lane {0} (architecture §4.1)")]
704 UnknownLane(LaneKey),
705
706 /// The medium is up but cannot transmit right now, and says so rather than
707 /// waiting.
708 ///
709 /// For hardware whose API refuses instead of blocking — a half-duplex
710 /// medium mid-reception, on a device that reports rather than queues.
711 ///
712 /// **A contact window is still not an instance of this.** A satellite
713 /// terminal out of coverage *blocks*, because that is what a
714 /// store-and-forward service does. See
715 /// `docs/measurements/contact-windows.md`.
716 ///
717 /// What returning it costs, exactly: on a **reliable** lane the scheduler
718 /// holds the batch and offers it again with a backoff, for as long as the
719 /// medium keeps refusing (#40) — so this trades a stall for a delay, never
720 /// for lost data, and the stall reaches Zenoh as ordinary backpressure. On
721 /// a **best-effort** lane the batch is dropped and counted, which is what
722 /// best-effort means. Either way the refusal appears on
723 /// `DriverMetrics::tx_failed`.
724 ///
725 /// Earlier versions of this note warned that the scheduler dropped the
726 /// batch on both lane classes. It did, silently, and that was #40.
727 #[error("medium cannot transmit at present")]
728 TxUnavailable,
729
730 /// The medium is gone: closed, unplugged, or failed.
731 #[error("medium is closed")]
732 Closed,
733
734 /// Anything hardware-specific, in the backend's own words.
735 ///
736 /// Handled exactly as [`DeviceError::TxUnavailable`]: held and retried on
737 /// a reliable lane, dropped and counted on a best-effort one. Return it
738 /// for a failure the medium expects to survive — `+CME ERROR`, an SPI
739 /// timeout, an MO status of "no network". A device that is *gone* should
740 /// say [`DeviceError::Closed`] instead, which stops the driver rather
741 /// than retrying into it.
742 ///
743 /// The string reaches the management plane verbatim. `sched::transmit`
744 /// raises a [`DeviceEvent`] carrying it, the driver's event stream carries
745 /// that, and it is published as `events/modem/device_fault/<ulid>` with the
746 /// text in `detail` (#51). Write it for an operator, not for a log grep:
747 /// it is the only place a device speaks in its own words.
748 #[error("medium error: {0}")]
749 Device(String),
750}
751
752/// RFC 2863's operational status — the states something here produces.
753///
754/// `dormant`, `testing` and `lowerLayerDown` are not declared, deliberately: a
755/// state is added when a device produces it. Linux's operstate documentation
756/// defines dormant as "L1 up, but waiting for an external event", and a
757/// coverage gap is L1 down — so a terminal out of coverage is [`Down`] with
758/// [`OperStatus::recoverable`] set, never dormant (#121).
759///
760/// [`Down`]: OperState::Down
761#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
762#[non_exhaustive]
763pub enum OperState {
764 /// Passing traffic.
765 Up,
766 /// Not passing traffic; [`OperStatus::recoverable`] says whether it
767 /// expects to again without help.
768 Down,
769 /// The device node is gone: a serial port unplugged, an interface
770 /// removed. Distinct from `Down` because no amount of waiting fixes it.
771 NotPresent,
772 /// The device has not said, and nothing else can tell. The default.
773 Unknown,
774}
775
776impl OperState {
777 /// The wire spelling: RFC 2863's own, so `notPresent` keeps its case.
778 #[must_use]
779 pub const fn as_str(self) -> &'static str {
780 match self {
781 Self::Up => "up",
782 Self::Down => "down",
783 Self::NotPresent => "notPresent",
784 Self::Unknown => "unknown",
785 }
786 }
787}
788
789impl fmt::Display for OperState {
790 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
791 f.write_str(self.as_str())
792 }
793}
794
795/// RFC 2863's administrative status: what was asked of the device.
796///
797/// Exists so that radio silence is expressible and distinguishable from a
798/// failure — an operator who ordered EMCON reads `admin: down, status: down`
799/// and knows nothing broke. Ordering it is a hot configuration group (#126).
800#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
801#[non_exhaustive]
802pub enum AdminState {
803 /// Asked to carry traffic.
804 #[default]
805 Up,
806 /// Asked to be silent.
807 Down,
808}
809
810impl AdminState {
811 /// The wire spelling.
812 #[must_use]
813 pub const fn as_str(self) -> &'static str {
814 match self {
815 Self::Up => "up",
816 Self::Down => "down",
817 }
818 }
819}
820
821impl fmt::Display for AdminState {
822 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
823 f.write_str(self.as_str())
824 }
825}
826
827/// What a device says about whether it is working (#121).
828///
829/// Sync and cached, like [`Report`]: the management plane polls it, and a
830/// device that needs I/O to answer keeps a snapshot. Every field is a fact
831/// the device has; a device that has none returns [`OperStatus::unknown`],
832/// which is the default and is honest. It cannot be derived from
833/// [`DeviceEvent`], whose detail is free text.
834#[derive(Clone, Debug, PartialEq, Eq)]
835#[non_exhaustive]
836pub struct OperStatus {
837 /// The operational status.
838 pub status: OperState,
839 /// The administrative status.
840 pub admin: AdminState,
841 /// Why, in the device's words, when it is not up.
842 pub reason: Option<String>,
843 /// Whether the device expects to come back on its own. `false` is the
844 /// one value that means something — a dead medium — and is what a
845 /// supervisor reads before deciding to restart (#96). A coverage gap is
846 /// `true`; so are `up` and `unknown`, because neither is a reason to
847 /// restart.
848 pub recoverable: bool,
849 /// When the status last changed, on the device's clock.
850 pub since: Option<std::time::SystemTime>,
851}
852
853impl Default for OperStatus {
854 fn default() -> Self {
855 Self::unknown()
856 }
857}
858
859impl OperStatus {
860 fn with(status: OperState, reason: Option<String>, recoverable: bool) -> Self {
861 Self {
862 status,
863 admin: AdminState::Up,
864 reason,
865 recoverable,
866 since: None,
867 }
868 }
869
870 /// The device has not said. The default.
871 #[must_use]
872 pub fn unknown() -> Self {
873 Self::with(OperState::Unknown, None, true)
874 }
875
876 /// Passing traffic.
877 #[must_use]
878 pub fn up() -> Self {
879 Self::with(OperState::Up, None, true)
880 }
881
882 /// Not passing traffic, with the reason and whether it expects to again.
883 #[must_use]
884 pub fn down(reason: impl Into<String>, recoverable: bool) -> Self {
885 Self::with(OperState::Down, Some(reason.into()), recoverable)
886 }
887
888 /// The device node is gone.
889 #[must_use]
890 pub fn not_present(reason: impl Into<String>) -> Self {
891 Self::with(OperState::NotPresent, Some(reason.into()), false)
892 }
893
894 /// When this status began, on the device's clock.
895 #[must_use]
896 pub fn since(mut self, at: std::time::SystemTime) -> Self {
897 self.since = Some(at);
898 self
899 }
900
901 /// With the administrative status.
902 #[must_use]
903 pub fn admin(mut self, admin: AdminState) -> Self {
904 self.admin = admin;
905 self
906 }
907
908 /// Whether the device is passing traffic.
909 #[must_use]
910 pub fn is_up(&self) -> bool {
911 self.status == OperState::Up
912 }
913}
914
915/// What a device is, with RFC 8348's field names (#122).
916///
917/// Every field optional and the type `#[non_exhaustive]`: a device says what
918/// it knows, and a field arrives when a device produces it. **Subscriber
919/// identifiers never appear here** — an IMSI, an ICCID, an MSISDN identifies
920/// a person's subscription, not equipment (invariant I5). The equipment
921/// identifier does, because the gateway keys its endpoints by it; it is an
922/// addressing identifier, never a proof of identity.
923#[derive(Clone, Debug, Default, PartialEq, Eq)]
924#[non_exhaustive]
925pub struct Identity {
926 /// Who made it.
927 pub mfg_name: Option<String>,
928 /// What it is, in the maker's words.
929 pub model_name: Option<String>,
930 /// The maker's serial number.
931 pub serial_num: Option<String>,
932 /// Hardware revision.
933 pub hardware_rev: Option<String>,
934 /// Firmware revision.
935 pub firmware_rev: Option<String>,
936 /// Software revision, where it is distinct from the firmware's.
937 pub software_rev: Option<String>,
938 /// The bearer's equipment identifier — an IMEI.
939 pub imei: Option<String>,
940}
941
942impl Identity {
943 /// A device that knows nothing about itself.
944 #[must_use]
945 pub fn unknown() -> Self {
946 Self::default()
947 }
948
949 /// Whether the device said anything at all.
950 #[must_use]
951 pub fn is_empty(&self) -> bool {
952 *self == Self::default()
953 }
954
955 fn set(mut self, field: fn(&mut Self) -> &mut Option<String>, v: impl Into<String>) -> Self {
956 *field(&mut self) = Some(v.into());
957 self
958 }
959
960 /// With the maker's name.
961 #[must_use]
962 pub fn mfg_name(self, v: impl Into<String>) -> Self {
963 self.set(|i| &mut i.mfg_name, v)
964 }
965
966 /// With the model name.
967 #[must_use]
968 pub fn model_name(self, v: impl Into<String>) -> Self {
969 self.set(|i| &mut i.model_name, v)
970 }
971
972 /// With the serial number.
973 #[must_use]
974 pub fn serial_num(self, v: impl Into<String>) -> Self {
975 self.set(|i| &mut i.serial_num, v)
976 }
977
978 /// With the hardware revision.
979 #[must_use]
980 pub fn hardware_rev(self, v: impl Into<String>) -> Self {
981 self.set(|i| &mut i.hardware_rev, v)
982 }
983
984 /// With the firmware revision.
985 #[must_use]
986 pub fn firmware_rev(self, v: impl Into<String>) -> Self {
987 self.set(|i| &mut i.firmware_rev, v)
988 }
989
990 /// With the software revision.
991 #[must_use]
992 pub fn software_rev(self, v: impl Into<String>) -> Self {
993 self.set(|i| &mut i.software_rev, v)
994 }
995
996 /// With the equipment identifier.
997 #[must_use]
998 pub fn imei(self, v: impl Into<String>) -> Self {
999 self.set(|i| &mut i.imei, v)
1000 }
1001}
1002
1003/// A device: anything the driver serves on the management plane.
1004///
1005/// The core and introspection planes of `docs/design/device-planes.md`, and
1006/// nothing about how bytes move — that is [`Medium`] for an SDU device, and
1007/// a netdev's is the kernel's. Every method is defaulted, because a device
1008/// that says nothing about itself is a legitimate device and every simulator
1009/// was one until #49; the split from the old `Backend` (#117) changed no
1010/// behaviour, only which trait a method belongs to.
1011#[async_trait::async_trait]
1012pub trait Device: Send + Sync {
1013 /// What this device says about itself.
1014 ///
1015 /// Defaulted to "nothing", because a medium that knows nothing about its
1016 /// own condition is a legitimate medium and every simulator was one until
1017 /// #49. Sync rather than `async` **on purpose**: the driver calls this from
1018 /// `mgmt/telemetry.rs`'s five-second publish loop, and an `async` signature
1019 /// would invite a backend to put an AT-command round trip there. A device
1020 /// that needs I/O to answer keeps atomics and a cached snapshot, and says
1021 /// how old the snapshot is through [`Report::age_ms`].
1022 ///
1023 /// **Decorators must forward this.** Seven of this crate's implementors wrap
1024 /// another `Medium`, and one that inherits the default answers `None` to
1025 /// everything — which reads as "unknown" rather than as a wrong number, but
1026 /// is still a lie about the medium underneath. The conformance kit's
1027 /// [`conformance::medium_decorator_forwards`] is what catches it, and it
1028 /// covers the whole trait rather than this method alone — which is new: the
1029 /// check this comment named for three issues asserted `report` and
1030 /// nothing else, and `close`, `configure_lanes` and `next_event` had gone
1031 /// unforwarded behind the claim (#50, #51, #52).
1032 fn report(&self) -> Report {
1033 Report::default()
1034 }
1035
1036 /// Whether this device is working, as RFC 2863 has it (#121).
1037 ///
1038 /// Sync and cached, for [`report`](Device::report)'s reason. Defaulted to
1039 /// [`OperStatus::unknown`]: a device that cannot tell says so, and the
1040 /// plane publishes that rather than a guess. A medium that has *failed*
1041 /// need not report it here — the driver knows, and overlays `down` with
1042 /// `recoverable: false` on whatever the device says. What a device does
1043 /// know that the driver cannot is the recoverable kind of down: a
1044 /// coverage gap, a closed contact window, a carrier that dropped.
1045 ///
1046 /// **Decorators must forward this**, like everything else here.
1047 fn oper(&self) -> OperStatus {
1048 OperStatus::default()
1049 }
1050
1051 /// What this device is (#122): RFC 8348's fields and the bearer's
1052 /// equipment identifier, as much of it as the device knows.
1053 ///
1054 /// Sync and cached, for [`report`](Device::report)'s reason: a modem
1055 /// reads its model, firmware and IMEI once, at open, and answers from
1056 /// that. Defaulted to [`Identity::unknown`], which is a legitimate
1057 /// answer — the management plane publishes it as a document with only
1058 /// the device's name, and a reader knows the device was asked. The plane
1059 /// polls it and raises `identity_change` when it differs: a terminal
1060 /// swapped, or its firmware updated, under a running driver.
1061 ///
1062 /// **Never a subscriber identifier** (I5). **Decorators must forward
1063 /// this**, like everything else here.
1064 fn identity(&self) -> Identity {
1065 Identity::default()
1066 }
1067
1068 /// Wait for the next thing the medium wants to say.
1069 ///
1070 /// Mirrors [`recv`](Medium::recv) deliberately: a driver drains this in
1071 /// its own task, so a backend may block here for as long as it likes and a
1072 /// medium with nothing to report simply never resolves. The default is
1073 /// exactly that, which is why every medium in this workspace needs no
1074 /// implementation.
1075 ///
1076 /// **Edge-triggered.** One event when a condition starts and one when it
1077 /// stops, not a repeat while it persists — see [`Edge`]. A backend that
1078 /// repeated itself would produce a rate the `events` keyspace cannot
1079 /// honestly declare, and the driver deduplicating on its behalf would be
1080 /// guessing at which repeats meant something.
1081 async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
1082 std::future::pending().await
1083 }
1084
1085 /// Stop, cleanly.
1086 ///
1087 /// Called once, on the way down, after every lane task has been aborted and
1088 /// before the process exits. The default does nothing, because an
1089 /// in-process medium has nothing to release.
1090 ///
1091 /// **A real device does (#50).** Teardown used to be: `Driver::shutdown`
1092 /// aborts its tasks, the `Arc<dyn Medium>` is dropped, and anything a
1093 /// radio needed to be told happened in `Drop` with no `async` available. A
1094 /// radio left keyed, or a modem left in binary-write mode, is the
1095 /// observable consequence — and neither is visible while a simulator is the
1096 /// only implementor, because a simulator never needs telling.
1097 ///
1098 /// Errors are reported and not propagated: the process is going away, and
1099 /// there is nothing a caller could do differently. Say what failed.
1100 async fn close(&self) -> Result<(), DeviceError> {
1101 Ok(())
1102 }
1103
1104 /// This device's configuration plane, if it has one (#125).
1105 ///
1106 /// `None` is the honest default: a device with nothing to configure
1107 /// declares no resource, and the management plane serves none for it.
1108 fn configuration(&self) -> Option<&dyn Configure> {
1109 None
1110 }
1111
1112 /// The operator actions this device offers (#129): explicit, costed,
1113 /// never scheduled — an operator deciding, once, now. `None` for a
1114 /// device with none. There is no `reset` and there will not be one
1115 /// (architecture §4.11): recovery is a restart, of the device (the
1116 /// driver's own `reopen` action) or of the daemon (#96).
1117 fn actions(&self) -> Option<&dyn Actions> {
1118 None
1119 }
1120}
1121
1122/// A physical or simulated medium: the SDU data plane of a [`Device`].
1123///
1124/// Implementations own everything below the driver: framing on the air, vendor
1125/// APIs, contact scheduling, radio state. They own nothing above it — no
1126/// routing, no retransmission the hardware does not already provide, and no
1127/// knowledge of what the bytes mean. `Medium: Device`, so an `Arc<dyn Medium>`
1128/// upcasts to `Arc<dyn Device>` and the management plane serves it like any
1129/// other device.
1130#[async_trait::async_trait]
1131pub trait Medium: Device {
1132 /// What this medium can carry. Read once at startup to size lanes.
1133 fn capabilities(&self) -> Capabilities;
1134
1135 /// Transmit one SDU on one lane.
1136 ///
1137 /// Returns once the medium has taken ownership — which is *not* a delivery
1138 /// receipt. Implementations must apply backpressure by not returning, rather
1139 /// than by accepting into an unbounded queue: invariant I3 exists because a
1140 /// hidden backlog between Zenoh's congestion control and the radio defeats
1141 /// the whole design.
1142 async fn send(&self, lane: &LaneKey, sdu: &[u8]) -> Result<(), DeviceError>;
1143
1144 /// Wait for the next SDU the medium delivers.
1145 ///
1146 /// Returns the lane it arrived on, so the driver can route it back to the
1147 /// matching socket without inspecting the payload.
1148 async fn recv(&self) -> Result<(LaneKey, Sdu), DeviceError>;
1149
1150 /// A snapshot of this medium's counters.
1151 fn metrics(&self) -> Metrics;
1152
1153 /// Tell the medium which lanes this driver will serve.
1154 ///
1155 /// Called once, from `Driver::start`, before anything moves. The default
1156 /// does nothing, because a medium that was given its topology at
1157 /// construction has nothing to learn — which is every medium in this
1158 /// workspace, and was every medium there was when the trait was written.
1159 ///
1160 /// **A real backend needs this and had no way to get it (#52).** `recv`
1161 /// returns a `LaneKey`, and hardware receives bytes with no lane in them:
1162 /// the endpoint can be recovered from on-air framing, but `reliable` and
1163 /// `rank` have to be *synthesised*, and nothing told the backend what
1164 /// combinations exist. Guess wrong and the driver drops the batch on a lane
1165 /// it does not have — silently until #52's first commit, and counted as
1166 /// `rx_unroutable_total` since.
1167 ///
1168 /// The driver is the authority here: these are the lanes it resolved from
1169 /// its own config and will actually serve, not the lanes a config file
1170 /// mentioned. Returning an error refuses startup, which is the right
1171 /// response to a medium that cannot serve what it is being asked for.
1172 async fn configure_lanes(&self, lanes: &[LaneKey]) -> Result<(), DeviceError> {
1173 let _ = lanes;
1174 Ok(())
1175 }
1176}
1177
1178/// A device whose data plane is the kernel's: a network interface that Zenoh
1179/// reaches over an ordinary TCP link bound to it (#118, #130).
1180///
1181/// Nothing here moves a byte — that is the point. The driver serves such a
1182/// device on the management plane exactly as it serves a [`Medium`], and the
1183/// lanes, the scheduler and the framing never see it: `Netdev: Device`, not
1184/// `Netdev: Medium`. What a netdev knows about its interface — statistics,
1185/// the operational state, an MTU to configure — arrives with #130; this
1186/// release names the interface and nothing else, so that a host can carry
1187/// one beside a modem and the roster shows one producer.
1188pub trait Netdev: Device {
1189 /// The interface name, as the kernel spells it: `wwan0`, `ppp0`.
1190 fn interface(&self) -> &str;
1191
1192 /// The interface's counters, as the kernel keeps them (#130): sync and
1193 /// cached, like [`Device::report`]. A counter the kernel does not keep
1194 /// is absent, never zero.
1195 fn statistics(&self) -> NetdevStats {
1196 NetdevStats::default()
1197 }
1198
1199 /// The presence epoch (zenkey RFC 04 §5, v1.39): moves when the
1200 /// interface is re-enumerated (its `ifindex` changed) or a counter is
1201 /// observed to decrease — what a USB modem re-enumerating looks like —
1202 /// and the management plane cycles `device/{device}/alive` when it does,
1203 /// which is the one reset the registry sanctions for the counters under
1204 /// this device. `0` until it moves.
1205 fn epoch(&self) -> u64 {
1206 0
1207 }
1208}
1209
1210/// A network interface's counters (#130), with RFC 8343's names where Linux
1211/// keeps exactly that counter and nothing else.
1212///
1213/// `in_pkts` and `out_pkts` are **not** RFC 8343's: the RFC splits packets by
1214/// unicast, multicast and broadcast, Linux's `rx_packets` includes multicast,
1215/// and Linux keeps no broadcast counter. They are here because an operator
1216/// asks for them; the registry says what they are.
1217#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1218pub struct NetdevStats {
1219 /// `rx_bytes` — RFC 8343 `in-octets`.
1220 pub in_octets: Option<u64>,
1221 /// `tx_bytes` — RFC 8343 `out-octets`.
1222 pub out_octets: Option<u64>,
1223 /// `rx_errors` — RFC 8343 `in-errors`.
1224 pub in_errors: Option<u64>,
1225 /// `tx_errors` — RFC 8343 `out-errors`.
1226 pub out_errors: Option<u64>,
1227 /// `rx_dropped` — RFC 8343 `in-discards`.
1228 pub in_discards: Option<u64>,
1229 /// `tx_dropped` — RFC 8343 `out-discards`.
1230 pub out_discards: Option<u64>,
1231 /// `multicast` — RFC 8343 `in-multicast-pkts`.
1232 pub in_multicast_pkts: Option<u64>,
1233 /// `rx_packets` — not RFC 8343: unicast and multicast together.
1234 pub in_pkts: Option<u64>,
1235 /// `tx_packets` — not RFC 8343.
1236 pub out_pkts: Option<u64>,
1237 /// Bytes queued in the interface's queue discipline now, not yet sent
1238 /// (#136). Not a sysfs counter: read over netlink, and only from the
1239 /// kernel's own interface. The queue an operator watches form when a
1240 /// bearer is slower than what is offered to it.
1241 pub qdisc_backlog_bytes: Option<u64>,
1242 /// Packets queued in the queue discipline now (#136).
1243 pub qdisc_backlog_pkts: Option<u64>,
1244}
1245
1246#[cfg(test)]
1247mod tests {
1248 use super::*;
1249
1250 fn lane(rank: u8, reliable: bool) -> LaneKey {
1251 LaneKey {
1252 endpoint: EndpointId::new("peer-b"),
1253 reliable,
1254 rank,
1255 }
1256 }
1257
1258 #[test]
1259 fn the_operational_states_spell_themselves_as_rfc_2863_does() {
1260 assert_eq!(OperState::Up.as_str(), "up");
1261 assert_eq!(OperState::Down.as_str(), "down");
1262 assert_eq!(OperState::NotPresent.as_str(), "notPresent");
1263 assert_eq!(OperState::Unknown.as_str(), "unknown");
1264 assert_eq!(AdminState::Down.to_string(), "down");
1265 }
1266
1267 #[test]
1268 fn a_device_that_says_nothing_is_unknown_and_not_a_reason_to_restart() {
1269 let s = OperStatus::default();
1270 assert_eq!(s.status, OperState::Unknown);
1271 assert_eq!(s.admin, AdminState::Up);
1272 assert!(s.recoverable, "unknown is not a reason to restart");
1273 assert!(s.reason.is_none());
1274 assert!(!s.is_up());
1275 assert!(!OperStatus::down("dead", false).recoverable);
1276 assert!(OperStatus::down("no coverage", true).recoverable);
1277 assert!(!OperStatus::not_present("port unplugged").recoverable);
1278 assert!(OperStatus::up().is_up());
1279 }
1280
1281 #[test]
1282 fn an_identity_says_only_what_the_device_knows() {
1283 assert!(Identity::unknown().is_empty());
1284 let id = Identity::unknown()
1285 .model_name("IRIDIUM 9603")
1286 .imei("300234060000000");
1287 assert!(!id.is_empty());
1288 assert_eq!(id.model_name.as_deref(), Some("IRIDIUM 9603"));
1289 assert_eq!(id.mfg_name, None, "unasked is absent, not empty");
1290 }
1291
1292 #[test]
1293 fn the_vocabulary_keeps_the_report_copy_and_eq_at_fixed_point() {
1294 // RSRQ and SNR move in half-dB steps; milli-units hold them exactly,
1295 // which is what lets `Report` stay `Copy + Eq` without an `f64`.
1296 let r = Report::new()
1297 .rssi(-97_500)
1298 .rsrq(-10_500)
1299 .snr(12_000)
1300 .rx_rate(1_000_000)
1301 .latency(45_000)
1302 .registration(Registration::Home)
1303 .access_technology(AccessTechnology::Lte);
1304 assert_eq!(r, r, "Eq");
1305 let copy = r;
1306 assert_eq!(copy.rssi, Some(-97_500));
1307 assert_eq!(r.rsrp, None, "unmeasured is absent");
1308 assert_eq!(Registration::Home.as_str(), "home");
1309 assert_eq!(AccessTechnology::Nr5g.as_str(), "5gnr");
1310 }
1311
1312 #[test]
1313 fn a_lane_renders_as_endpoint_reliability_and_rank() {
1314 assert_eq!(lane(0, true).to_string(), "peer-b/rel#0");
1315 assert_eq!(lane(5, false).to_string(), "peer-b/be#5");
1316 }
1317
1318 #[test]
1319 fn lanes_differing_only_in_reliability_are_distinct() {
1320 assert_ne!(lane(0, true), lane(0, false));
1321 }
1322
1323 #[test]
1324 fn capabilities_may_be_asymmetric() {
1325 // The SBD profile: 340 up, 270 down. Nothing here collapses them.
1326 let caps = Capabilities {
1327 tx_max_sdu: 340,
1328 rx_max_sdu: 270,
1329 duplex: Duplex::Full,
1330 reliable: true,
1331 };
1332 assert_ne!(caps.tx_max_sdu, caps.rx_max_sdu);
1333 }
1334
1335 #[test]
1336 fn an_oversized_sdu_names_the_batch_size_that_would_fit() {
1337 // The +2 is Zenoh's length prefix, which lives inside the batch buffer:
1338 // a batch_size of N puts N-2 bytes on the medium.
1339 let e = DeviceError::SduTooLarge { got: 300, max: 218 };
1340 assert_eq!(
1341 e.to_string(),
1342 "sdu of 300 bytes exceeds the medium's tx_max_sdu of 218: \
1343 lower zenoh's batch_size to at most 220 (architecture I4, §4.5)"
1344 );
1345 }
1346}